text:
"""Handles low-level interfacing for files' tags. Wraps Mutagen to
automatically detect file types and provide a unified interface for a
useful subset of music files' tags.

Usage:

    >>> f = MediaFile('Lucy.mp3')
    >>> f.title
    u'Lucy in the Sky with Diamonds'
    >>> f.artist = 'The Beatles'
    >>> f.save()

A field will always return a reasonable value of the correct type, even
if no tag is present. If no value is available, the value will be false
(e.g., zero or the empty string).
"""
import mutagen
import mutagen.mp3
import mutagen.oggvorbis
import mutagen.mp4
import mutagen.flac
import mutagen.monkeysaudio
import datetime
import re
import base64
import imghdr
import os
import logging
import traceback
from beets.util.enumeration import enum

__all__ = ['UnreadableFileError', 'FileTypeError', 'MediaFile']

# Logger.
log = logging.getLogger('beets')

# Exceptions.

# Raised for any file MediaFile can't read.
class UnreadableFileError(IOError):
    pass

# Raised for files that don't seem to have a type MediaFile supports.
class FileTypeError(UnreadableFileError):
    pass

# Constants.

# Human-readable type names.
TYPES = {
    'mp3':  'MP3',
    'mp4':  'AAC',
    'ogg':  'OGG',
    'flac': 'FLAC',
    'ape':  'APE',
    'wv':   'WavPack',
    'mpc':  'Musepack',
}

# Utility.

def _safe_cast(out_type, val):
    """Tries to covert val to out_type but will never raise an
    exception. If the value can't be converted, then a sensible
    default value is returned. out_type should be bool, int, or
    unicode; otherwise, the value is just passed through.
    """
    if out_type == int:
        if val is None:
            return 0
        elif isinstance(val, int) or isinstance(val, float):
            # Just a number.
            return int(val)
        else:
            # Process any other type as a string.
            if not isinstance(val, basestring):
                val = unicode(val)
            # Get a number from the front of the string.
            val = re.match(r'[0-9]*', val.strip()).group(0)
            if not val:
                return 0
            else:
                return int(val)

    elif out_type == bool:
        if val is None:
            return False
        else:
            try:
                # Should work for strings, bools, ints:
                return bool(int(val))
            except ValueError:
                return False

    elif out_type == unicode:
        if val is None:
            return u''
        else:
            if isinstance(val, str):
                return val.decode('utf8', 'ignore')
            elif isinstance(val, unicode):
                return val
            else:
                return unicode(val)

    elif out_type == float:
        if val is None:
            return 0.0
        elif isinstance(val, int) or isinstance(val, float):
            return float(val)
        else:
            if not isinstance(val, basestring):
                val = unicode(val)
            val = re.match(r'[\+-]?[0-9\.]*', val.strip()).group(0)
            if not val:
                return 0.0
            else:
                return float(val)

    else:
        return val

# Flags for encoding field behavior.

# Determine style of packing, if any.
packing = enum('SLASHED', # pair delimited by /
               'TUPLE',   # a python tuple of 2 items
               'DATE',    # YYYY-MM-DD
               name='packing')

class StorageStyle(object):
    """Parameterizes the storage behavior of a single field for a
    certain tag format.
     - key: The Mutagen key used to access the field's data.
     - list_elem: Store item as a single object or as first element
       of a list.
     - as_type: Which type the value is stored as (unicode, int,
       bool, or str).
     - packing: If this value is packed in a multiple-value storage
       unit, which type of packing (in the packing enum). Otherwise,
       None. (Makes as_type irrelevant).
     - pack_pos: If the value is packed, in which position it is
       stored.
     - ID3 storage only: match against this 'desc' field as well
       as the key.
    """
    def __init__(self, key, list_elem = True, as_type = unicode,
                 packing = None, pack_pos = 0, id3_desc = None,
                 id3_frame_field = 'text'):
        self.key = key
        self.list_elem = list_elem
        self.as_type = as_type
        self.packing = packing
        self.pack_pos = pack_pos
        self.id3_desc = id3_desc
        self.id3_frame_field = id3_frame_field

# Dealing with packings.

class Packed(object):
    """Makes a packed list of values subscriptable. To access the packed
    output after making changes, use packed_thing.items.
    """
    def __init__(self, items, packstyle, none_val=0, out_type=int):
        """Create a Packed object for subscripting the packed values in
        items. The items are packed using packstyle, which is a value
        from the packing enum. none_val is returned from a request when
        no suitable value is found in the items. Vales are converted to
        out_type before they are returned.
        """
        self.items = items
        self.packstyle = packstyle
        self.none_val = none_val
        self.out_type = out_type

    def __getitem__(self, index):
        if not isinstance(index, int):
            raise TypeError('index must be an integer')

        if self.items is None:
            return self.none_val

        items = self.items
        if self.packstyle == packing.DATE:
            # Remove time information from dates. Usually delimited by
            # a "T" or a space.
            items = re.sub(r'[Tt ].*$', '', unicode(items))

        # transform from a string packing into a list we can index into
        if self.packstyle == packing.SLASHED:
            seq = unicode(items).split('/')
        elif self.packstyle == packing.DATE:
            seq = unicode(items).split('-')
        elif self.packstyle == packing.TUPLE:
            seq = items # tuple: items is already indexable

        try:
            out = seq[index]
        except:
            out = None

        if out is None or out == self.none_val or out == '':
            return _safe_cast(self.out_type, self.none_val)
        else:
            return _safe_cast(self.out_type, out)

    def __setitem__(self, index, value):
        if self.packstyle in (packing.SLASHED, packing.TUPLE):
            # SLASHED and TUPLE are always two-item packings
            length = 2
        else:
            # DATE can have up to three fields
            length = 3

        # make a list of the items we'll pack
        new_items = []
        for i in range(length):
            if i == index:
                next_item = value
            else:
                next_item = self[i]
            new_items.append(next_item)

        if self.packstyle == packing.DATE:
            # Truncate the items wherever we reach an invalid (none)
            # entry. This prevents dates like 2008-00-05.
            for i, item in enumerate(new_items):
                if item == self.none_val or item is None:
                    del(new_items[i:]) # truncate
                    break

        if self.packstyle == packing.SLASHED:
            self.items = '/'.join(map(unicode, new_items))
        elif self.packstyle == packing.DATE:
            field_lengths = [4, 2, 2] # YYYY-MM-DD
            elems = []
            for i, item in enumerate(new_items):
                elems.append( ('%0' + str(field_lengths[i]) + 'i') % item )
            self.items = '-'.join(elems)
        elif self.packstyle == packing.TUPLE:
            self.items = new_items

# The field itself.

class MediaField(object):
    """A descriptor providing access to a particular (abstract) metadata
    field. out_type is the type that users of MediaFile should see and
    can be unicode, int, or bool. id3, mp4, and flac are StorageStyle
    instances parameterizing the field's storage for each type.
    """
    def __init__(self, out_type = unicode, **kwargs):
        """Creates a new MediaField.
         - out_type: The field's semantic (exterior) type.
         - kwargs: A hash whose keys are 'mp3', 'mp4', and 'etc'
           and whose values are StorageStyle instances
           parameterizing the field's storage for each type.
        """
        self.out_type = out_type
        if not set(['mp3', 'mp4', 'etc']) == set(kwargs):
            raise TypeError('MediaField constructor must have keyword '
                            'arguments mp3, mp4, and etc')
        self.styles = kwargs

    def _fetchdata(self, obj, style):
        """Get the value associated with this descriptor's field stored
        with the given StorageStyle. Unwraps from a list if necessary.
        """
        # fetch the value, which may be a scalar or a list
        if obj.type == 'mp3':
            if style.id3_desc is not None: # also match on 'desc' field
                frames = obj.mgfile.tags.getall(style.key)
                entry = None
                for frame in frames:
                    if frame.desc.lower() == style.id3_desc.lower():
                        entry = getattr(frame, style.id3_frame_field)
                        break
                if entry is None: # no desc match
                    return None
            else:
                # Get the metadata frame object.
                try:
                    frame = obj.mgfile[style.key]
                except KeyError:
                    return None

                entry = getattr(frame, style.id3_frame_field)

        else:  # Not MP3.
            try:
                entry = obj.mgfile[style.key]
            except KeyError:
                return None

        # Possibly index the list.
        if style.list_elem:
            if entry:  # List must have at least one value.
                # Handle Mutagen bugs when reading values (#356).
                try:
                    return entry[0]
                except:
                    log.error('Mutagen exception when reading field: %s' %
                              traceback.format_exc)
                    return None
            else:
                return None
        else:
            return entry

    def _storedata(self, obj, val, style):
        """Store val for this descriptor's field in the tag dictionary
        according to the provided StorageStyle. Store it as a
        single-item list if necessary.
        """
        # Wrap as a list if necessary.
        if style.list_elem:
            out = [val]
        else:
            out = val

        if obj.type == 'mp3':
            # Try to match on "desc" field.
            if style.id3_desc is not None:
                frames = obj.mgfile.tags.getall(style.key)

                # try modifying in place
                found = False
                for frame in frames:
                    if frame.desc.lower() == style.id3_desc.lower():
                        setattr(frame, style.id3_frame_field, out)
                        found = True
                        break

                # need to make a new frame?
                if not found:
                    assert isinstance(style.id3_frame_field, str)  # Keyword.
                    frame = mutagen.id3.Frames[style.key](
                        encoding=3,
                        desc=style.id3_desc,
                        **{style.id3_frame_field: val}
                    )
                    obj.mgfile.tags.add(frame)

            # Try to match on "owner" field.
            elif style.key.startswith('UFID:'):
                owner = style.key.split(':', 1)[1]
                frames = obj.mgfile.tags.getall(style.key)

                for frame in frames:
                    # Replace existing frame data.
                    if frame.owner == owner:
                        setattr(frame, style.id3_frame_field, val)
                else:
                    # New frame.
                    assert isinstance(style.id3_frame_field, str)  # Keyword.
                    frame = mutagen.id3.UFID(owner=owner,
                        **{style.id3_frame_field: val})
                    obj.mgfile.tags.setall('UFID', [frame])

            # Just replace based on key.
            else:
                assert isinstance(style.id3_frame_field, str)  # Keyword.
                frame = mutagen.id3.Frames[style.key](encoding = 3,
                    **{style.id3_frame_field: val})
                obj.mgfile.tags.setall(style.key, [frame])

        else: # Not MP3.
            obj.mgfile[style.key] = out

    def _styles(self, obj):
        if obj.type in ('mp3', 'mp4'):
            styles = self.styles[obj.type]
        else:
            styles = self.styles['etc']  # Sane styles.

        # Make sure we always return a list of styles, even when given
        # a single style for convenience.
        if isinstance(styles, StorageStyle):
            return [styles]
        else:
            return styles

    def __get__(self, obj, owner):
        """Retrieve the value of this metadata field.
        """
        # Fetch the data using the various StorageStyles.
        styles = self._styles(obj)
        if styles is None:
            out = None
        else:
            for style in styles:
                # Use the first style that returns a reasonable value.
                out = self._fetchdata(obj, style)
                if out:
                    break

            if style.packing:
                out = Packed(out, style.packing)[style.pack_pos]

            # MPEG-4 freeform frames are (should be?) encoded as UTF-8.
            if obj.type == 'mp4' and style.key.startswith('----:') and \
                    isinstance(out, str):
                out = out.decode('utf8')

        return _safe_cast(self.out_type, out)

    def __set__(self, obj, val):
        """Set the value of this metadata field.
        """
        # Store using every StorageStyle available.
        styles = self._styles(obj)
        if styles is None:
            return

        for style in styles:

            if style.packing:
                p = Packed(self._fetchdata(obj, style), style.packing)
                p[style.pack_pos] = val
                out = p.items

            else: # unicode, integer, or boolean scalar
                out = val

                # deal with Nones according to abstract type if present
                if out is None:
                    if self.out_type == int:
                        out = 0
                    elif self.out_type == bool:
                        out = False
                    elif self.out_type == unicode:
                        out = u''
                    # We trust that packed values are handled above.

                # Convert to correct storage type (irrelevant for
                # packed values).
                if style.as_type == unicode:
                    if out is None:
                        out = u''
                    else:
                        if self.out_type == bool:
                            # store bools as 1,0 instead of True,False
                            out = unicode(int(out))
                        elif isinstance(out, str):
                            out = out.decode('utf8', 'ignore')
                        else:
                            out = unicode(out)
                elif style.as_type == int:
                    if out is None:
                        out = 0
                    else:
                        out = int(out)
                elif style.as_type in (bool, str):
                    out = style.as_type(out)

            # MPEG-4 "freeform" (----) frames must be encoded as UTF-8
            # byte strings.
            if obj.type == 'mp4' and style.key.startswith('----:') and \
                    isinstance(out, unicode):
                out = out.encode('utf8')

            # Store the data.
            self._storedata(obj, out, style)

class CompositeDateField(object):
    """A MediaFile field for conveniently accessing the year, month, and
    day fields as a datetime.date object. Allows both getting and
    setting of the component fields.
    """
    def __init__(self, year_field, month_field, day_field):
        """Create a new date field from the indicated MediaFields for
        the component values.
        """
        self.year_field = year_field
        self.month_field = month_field
        self.day_field = day_field

    def __get__(self, obj, owner):
        """Return a datetime.date object whose components indicating the
        smallest valid date whose components are at least as large as
        the three component fields (that is, if year == 1999, month == 0,
        and day == 0, then date == datetime.date(1999, 1, 1)). If the
        components indicate an invalid date (e.g., if month == 47),
        datetime.date.min is returned.
        """
        try:
            return datetime.date(
                max(self.year_field.__get__(obj, owner), datetime.MINYEAR),
                max(self.month_field.__get__(obj, owner), 1),
                max(self.day_field.__get__(obj, owner), 1)
            )
        except ValueError:  # Out of range values.
            return datetime.date.min

    def __set__(self, obj, val):
        """Set the year, month, and day fields to match the components of
        the provided datetime.date object.
        """
        self.year_field.__set__(obj, val.year)
        self.month_field.__set__(obj, val.month)
        self.day_field.__set__(obj, val.day)

class ImageField(object):
    """A descriptor providing access to a file's embedded album art.
    Holds a bytestring reflecting the image data. The image should
    either be a JPEG or a PNG for cross-format compatibility. It's
    probably a bad idea to use anything but these two formats.
    """
    @classmethod
    def _mime(cls, data):
        """Return the MIME type (either image/png or image/jpeg) of the
        image data (a bytestring).
        """
        kind = imghdr.what(None, h=data)
        if kind == 'png':
            return 'image/png'
        else:
            # Currently just fall back to JPEG.
            return 'image/jpeg'

    @classmethod
    def _mp4kind(cls, data):
        """Return the MPEG-4 image type code of the data. If the image
        is not a PNG or JPEG, JPEG is assumed.
        """
        kind = imghdr.what(None, h=data)
        if kind == 'png':
            return mutagen.mp4.MP4Cover.FORMAT_PNG
        else:
            return mutagen.mp4.MP4Cover.FORMAT_JPEG

    def __get__(self, obj, owner):
        if obj.type == 'mp3':
            # Look for APIC frames.
            for frame in obj.mgfile.tags.values():
                if frame.FrameID == 'APIC':
                    picframe = frame
                    break
            else:
                # No APIC frame.
                return None

            return picframe.data

        elif obj.type == 'mp4':
            if 'covr' in obj.mgfile:
                covers = obj.mgfile['covr']
                if covers:
                    cover = covers[0]
                    # cover is an MP4Cover, which is a subclass of str.
                    return cover

            # No cover found.
            return None

        else:
            # Here we're assuming everything but MP3 and MPEG-4 uses
            # the Xiph/Vorbis Comments standard. This may not be valid.
            # http://wiki.xiph.org/VorbisComment#Cover_art

            if 'metadata_block_picture' not in obj.mgfile:
                # Try legacy COVERART tags.
                if 'coverart' in obj.mgfile and obj.mgfile['coverart']:
                    return base64.b64decode(obj.mgfile['coverart'][0])
                return None

            for data in obj.mgfile["metadata_block_picture"]:
                try:
                    pic = mutagen.flac.Picture(base64.b64decode(data))
                    break
                except TypeError:
                    pass
            else:
                return None

            return pic.data

    def __set__(self, obj, val):
        if val is not None:
            if not isinstance(val, str):
                raise ValueError('value must be a byte string or None')

        if obj.type == 'mp3':
            # Clear all APIC frames.
            obj.mgfile.tags.delall('APIC')
            if val is None:
                # If we're clearing the image, we're done.
                return

            picframe = mutagen.id3.APIC(
                encoding = 3,
                mime = self._mime(val),
                type = 3, # front cover
                desc = u'',
                data = val,
            )
            obj.mgfile['APIC'] = picframe

        elif obj.type == 'mp4':
            if val is None:
                if 'covr' in obj.mgfile:
                    del obj.mgfile['covr']
            else:
                cover = mutagen.mp4.MP4Cover(val, self._mp4kind(val))
                obj.mgfile['covr'] = [cover]

        else:
            # Again, assuming Vorbis Comments standard.

            # Strip all art, including legacy COVERART.
            if 'metadata_block_picture' in obj.mgfile:
                if 'metadata_block_picture' in obj.mgfile:
                    del obj.mgfile['metadata_block_picture']
                if 'coverart' in obj.mgfile:
                    del obj.mgfile['coverart']
                if 'coverartmime' in obj.mgfile:
                    del obj.mgfile['coverartmime']

            # Add new art if provided.
            if val is not None:
                pic = mutagen.flac.Picture()
                pic.data = val
                pic.mime = self._mime(val)
                obj.mgfile['metadata_block_picture'] = [
                    base64.b64encode(pic.write())
                ]

class FloatValueField(MediaField):
    """A field that stores a floating-point number as a string."""
    def __init__(self, places=2, suffix=None, **kwargs):
        """Make a field that stores ``places`` digits after the decimal
        point and appends ``suffix`` (if specified) when encoding as a
        string.
        """
        super(FloatValueField, self).__init__(unicode, **kwargs)

        fmt = ['%.', str(places), 'f']
        if suffix:
            fmt += [' ', suffix]
        self.fmt = ''.join(fmt)

    def __get__(self, obj, owner):
        valstr = super(FloatValueField, self).__get__(obj, owner)
        return _safe_cast(float, valstr)

    def __set__(self, obj, val):
        if not val:
            val = 0.0
        valstr = self.fmt % val
        super(FloatValueField, self).__set__(obj, valstr)

# The file (a collection of fields).

class MediaFile(object):
    """Represents a multimedia file on disk and provides access to its
    metadata.
    """
    def __init__(self, path):
        """Constructs a new MediaFile reflecting the file at path. May
        throw UnreadableFileError.
        """
        self.path = path

        unreadable_exc = (
            mutagen.mp3.HeaderNotFoundError,
            mutagen.flac.FLACNoHeaderError,
            mutagen.monkeysaudio.MonkeysAudioHeaderError,
            mutagen.mp4.MP4StreamInfoError,
            mutagen.oggvorbis.OggVorbisHeaderError,
        )
        try:
            self.mgfile = mutagen.File(path)
        except unreadable_exc:
            log.warn('header parsing failed')
            raise UnreadableFileError('Mutagen could not read file')
        except IOError:
            raise UnreadableFileError('could not read file')
        except Exception as exc:
            # Hide bugs in Mutagen.
            log.debug(traceback.format_exc())
            log.error('uncaught Mutagen exception: {0}'.format(exc))
            raise UnreadableFileError('Mutagen raised an exception')

        if self.mgfile is None: # Mutagen couldn't guess the type
            raise FileTypeError('file type unsupported by Mutagen')
        elif type(self.mgfile).__name__ == 'M4A' or \
             type(self.mgfile).__name__ == 'MP4':
            self.type = 'mp4'
        elif type(self.mgfile).__name__ == 'ID3' or \
             type(self.mgfile).__name__ == 'MP3':
            self.type = 'mp3'
        elif type(self.mgfile).__name__ == 'FLAC':
            self.type = 'flac'
        elif type(self.mgfile).__name__ == 'OggVorbis':
            self.type = 'ogg'
        elif type(self.mgfile).__name__ == 'MonkeysAudio':
            self.type = 'ape'
        elif type(self.mgfile).__name__ == 'WavPack':
            self.type = 'wv'
        elif type(self.mgfile).__name__ == 'Musepack':
            self.type = 'mpc'
        else:
            raise FileTypeError('file type %s unsupported by MediaFile' %
                                type(self.mgfile).__name__)

        # add a set of tags if it's missing
        if self.mgfile.tags is None:
            self.mgfile.add_tags()

    def save(self):
        self.mgfile.save()

    # Field definitions.

    title = MediaField(
        mp3 = StorageStyle('TIT2'),
        mp4 = StorageStyle("\xa9nam"),
        etc = StorageStyle('TITLE'),
    )
    artist = MediaField(
        mp3 = StorageStyle('TPE1'),
        mp4 = StorageStyle("\xa9ART"),
        etc = StorageStyle('ARTIST'),
    )
    album = MediaField(
        mp3 = StorageStyle('TALB'),
        mp4 = StorageStyle("\xa9alb"),
        etc = StorageStyle('ALBUM'),
    )
    genre = MediaField(
        mp3 = StorageStyle('TCON'),
        mp4 = StorageStyle("\xa9gen"),
        etc = StorageStyle('GENRE'),
    )
    composer = MediaField(
        mp3 = StorageStyle('TCOM'),
        mp4 = StorageStyle("\xa9wrt"),
        etc = StorageStyle('COMPOSER'),
    )
    grouping = MediaField(
        mp3 = StorageStyle('TIT1'),
        mp4 = StorageStyle("\xa9grp"),
        etc = StorageStyle('GROUPING'),
    )
    year = MediaField(out_type=int,
        mp3 = StorageStyle('TDRC', packing=packing.DATE, pack_pos=0),
        mp4 = StorageStyle("\xa9day", packing=packing.DATE, pack_pos=0),
        etc = [StorageStyle('DATE', packing=packing.DATE, pack_pos=0),
               StorageStyle('YEAR')]
    )
    month = MediaField(out_type=int,
        mp3 = StorageStyle('TDRC', packing=packing.DATE, pack_pos=1),
        mp4 = StorageStyle("\xa9day", packing=packing.DATE, pack_pos=1),
        etc = StorageStyle('DATE', packing=packing.DATE, pack_pos=1),
    )
    day = MediaField(out_type=int,
        mp3 = StorageStyle('TDRC', packing=packing.DATE, pack_pos=2),
        mp4 = StorageStyle("\xa9day", packing=packing.DATE, pack_pos=2),
        etc = StorageStyle('DATE', packing=packing.DATE, pack_pos=2),
    )
    date = CompositeDateField(year, month, day)
    track = MediaField(out_type=int,
        mp3 = StorageStyle('TRCK', packing=packing.SLASHED, pack_pos=0),
        mp4 = StorageStyle('trkn', packing=packing.TUPLE, pack_pos=0),
        etc = [StorageStyle('TRACK'),
               StorageStyle('TRACKNUMBER')]
    )
    tracktotal = MediaField(out_type=int,
        mp3 = StorageStyle('TRCK', packing=packing.SLASHED, pack_pos=1),
        mp4 = StorageStyle('trkn', packing=packing.TUPLE, pack_pos=1),
        etc = [StorageStyle('TRACKTOTAL'),
               StorageStyle('TRACKC'),
               StorageStyle('TOTALTRACKS')]
    )
    disc = MediaField(out_type=int,
        mp3 = StorageStyle('TPOS', packing=packing.SLASHED, pack_pos=0),
        mp4 = StorageStyle('disk', packing=packing.TUPLE, pack_pos=0),
        etc = [StorageStyle('DISC'),
               StorageStyle('DISCNUMBER')]
    )
    disctotal = MediaField(out_type=int,
        mp3 = StorageStyle('TPOS', packing=packing.SLASHED, pack_pos=1),
        mp4 = StorageStyle('disk', packing=packing.TUPLE, pack_pos=1),
        etc = [StorageStyle('DISCTOTAL'),
               StorageStyle('DISCC'),
               StorageStyle('TOTALDISCS')]
    )
    lyrics = MediaField(
        mp3 = StorageStyle('USLT', list_elem=False, id3_desc=u''),
        mp4 = StorageStyle("\xa9lyr"),
        etc = StorageStyle('LYRICS')
    )
    comments = MediaField(
        mp3 = StorageStyle('COMM', id3_desc=u''),
        mp4 = StorageStyle("\xa9cmt"),
        etc = [StorageStyle('DESCRIPTION'),
               StorageStyle('COMMENT')]
    )
    bpm = MediaField(out_type=int,
        mp3 = StorageStyle('TBPM'),
        mp4 = StorageStyle('tmpo', as_type=int),
        etc = StorageStyle('BPM'),
    )
    comp = MediaField(out_type=bool,
        mp3 = StorageStyle('TCMP'),
        mp4 = StorageStyle('cpil', list_elem=False, as_type=bool),
        etc = StorageStyle('COMPILATION'),
    )
    albumartist = MediaField(
        mp3 = StorageStyle('TPE2'),
        mp4 = StorageStyle('aART'),
        etc = [StorageStyle('ALBUM ARTIST'),
               StorageStyle('ALBUMARTIST')]
    )
    albumtype = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'MusicBrainz Album Type'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Album Type'),
        etc = StorageStyle('MUSICBRAINZ_ALBUMTYPE'),
    )
    label = MediaField(
        mp3 = StorageStyle('TPUB'),
        mp4 = [StorageStyle('----:com.apple.iTunes:Label'),
               StorageStyle('----:com.apple.iTunes:publisher')],
        etc = [StorageStyle('LABEL'),
               StorageStyle('PUBLISHER')]  # Traktor
    )
    artist_sort = MediaField(
        mp3 = StorageStyle('TSOP'),
        mp4 = StorageStyle("soar"),
        etc = StorageStyle('ARTISTSORT'),
    )
    albumartist_sort = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'ALBUMARTISTSORT'),
        mp4 = StorageStyle("soaa"),
        etc = StorageStyle('ALBUMARTISTSORT'),
    )
    asin = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'ASIN'),
        mp4 = StorageStyle("----:com.apple.iTunes:ASIN"),
        etc = StorageStyle('ASIN'),
    )
    catalognum = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'CATALOGNUMBER'),
        mp4 = StorageStyle("----:com.apple.iTunes:CATALOGNUMBER"),
        etc = StorageStyle('CATALOGNUMBER'),
    )
    disctitle = MediaField(
        mp3 = StorageStyle('TSST'),
        mp4 = StorageStyle("----:com.apple.iTunes:DISCSUBTITLE"),
        etc = StorageStyle('DISCSUBTITLE'),
    )
    encoder = MediaField(
        mp3 = StorageStyle('TENC'),
        mp4 = StorageStyle("\xa9too"),
        etc = [StorageStyle('ENCODEDBY'),
               StorageStyle('ENCODER')]
    )
    script = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'Script'),
        mp4 = StorageStyle("----:com.apple.iTunes:SCRIPT"),
        etc = StorageStyle('SCRIPT'),
    )
    language = MediaField(
        mp3 = StorageStyle('TLAN'),
        mp4 = StorageStyle("----:com.apple.iTunes:LANGUAGE"),
        etc = StorageStyle('LANGUAGE'),
    )
    country = MediaField(
        mp3 = StorageStyle('TXXX',
                           id3_desc=u'MusicBrainz Album Release Country'),
        mp4 = StorageStyle("----:com.apple.iTunes:MusicBrainz Album "
                           "Release Country"),
        etc = StorageStyle('RELEASECOUNTRY'),
    )
    albumstatus = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'MusicBrainz Album Status'),
        mp4 = StorageStyle("----:com.apple.iTunes:MusicBrainz Album Status"),
        etc = StorageStyle('MUSICBRAINZ_ALBUMSTATUS'),
    )
    media = MediaField(
        mp3 = StorageStyle('TMED'),
        mp4 = StorageStyle("----:com.apple.iTunes:MEDIA"),
        etc = StorageStyle('MEDIA'),
    )
    albumdisambig = MediaField(
        # This tag mapping was invented for beets (not used by Picard, etc).
        mp3 = StorageStyle('TXXX', id3_desc=u'MusicBrainz Album Comment'),
        mp4 = StorageStyle("----:com.apple.iTunes:MusicBrainz Album Comment"),
        etc = StorageStyle('MUSICBRAINZ_ALBUMCOMMENT'),
    )

    # Nonstandard metadata.
    artist_credit = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'Artist Credit'),
        mp4 = StorageStyle("----:com.apple.iTunes:Artist Credit"),
        etc = StorageStyle('ARTIST_CREDIT'),
    )
    albumartist_credit = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'Album Artist Credit'),
        mp4 = StorageStyle("----:com.apple.iTunes:Album Artist Credit"),
        etc = StorageStyle('ALBUMARTIST_CREDIT'),
    )

    # Album art.
    art = ImageField()

    # MusicBrainz IDs.
    mb_trackid = MediaField(
        mp3 = StorageStyle('UFID:http://musicbrainz.org',
                            list_elem = False,
                            id3_frame_field = 'data'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Track Id',
                           as_type=str),
        etc = StorageStyle('MUSICBRAINZ_TRACKID')
    )
    mb_albumid = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'MusicBrainz Album Id'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Album Id',
                           as_type=str),
        etc = StorageStyle('MUSICBRAINZ_ALBUMID')
    )
    mb_artistid = MediaField(
        mp3 = StorageStyle('TXXX', id3_desc=u'MusicBrainz Artist Id'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Artist Id',
                           as_type=str),
        etc = StorageStyle('MUSICBRAINZ_ARTISTID')
    )
    mb_albumartistid = MediaField(
        mp3 = StorageStyle('TXXX',
                            id3_desc=u'MusicBrainz Album Artist Id'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Album Artist Id',
                           as_type=str),
        etc = StorageStyle('MUSICBRAINZ_ALBUMARTISTID')
    )
    mb_releasegroupid = MediaField(
        mp3 = StorageStyle('TXXX',
                            id3_desc=u'MusicBrainz Release Group Id'),
        mp4 = StorageStyle('----:com.apple.iTunes:MusicBrainz Release Group Id',
                           as_type=str),
        etc = StorageStyle('MUSICBRAINZ_RELEASEGROUPID')
    )

    # Acoustid fields.
    acoustid_fingerprint = MediaField(
        mp3 = StorageStyle('TXXX',
                            id3_desc=u'Acoustid Fingerprint'),
        mp4 = StorageStyle('----:com.apple.iTunes:Acoustid Fingerprint',
                           as_type=str),
        etc = StorageStyle('ACOUSTID_FINGERPRINT')
    )
    acoustid_id = MediaField(
        mp3 = StorageStyle('TXXX',
                            id3_desc=u'Acoustid Id'),
        mp4 = StorageStyle('----:com.apple.iTunes:Acoustid Id',
                           as_type=str),
        etc = StorageStyle('ACOUSTID_ID')
    )

    # ReplayGain fields.
    rg_track_gain = FloatValueField(2, 'dB',
        mp3 = StorageStyle('TXXX', id3_desc=u'REPLAYGAIN_TRACK_GAIN'),
        mp4 = None,
        etc = StorageStyle(u'REPLAYGAIN_TRACK_GAIN')
    )
    rg_album_gain = FloatValueField(2, 'dB',
        mp3 = StorageStyle('TXXX', id3_desc=u'REPLAYGAIN_ALBUM_GAIN'),
        mp4 = None,
        etc = StorageStyle(u'REPLAYGAIN_ALBUM_GAIN')
    )
    rg_track_peak = FloatValueField(6, None,
        mp3 = StorageStyle('TXXX', id3_desc=u'REPLAYGAIN_TRACK_PEAK'),
        mp4 = None,
        etc = StorageStyle(u'REPLAYGAIN_TRACK_PEAK')
    )
    rg_album_peak = FloatValueField(6, None,
        mp3 = StorageStyle('TXXX', id3_desc=u'REPLAYGAIN_ALBUM_PEAK'),
        mp4 = None,
        etc = StorageStyle(u'REPLAYGAIN_ALBUM_PEAK')
    )

    @property
    def length(self):
        """The duration of the audio in seconds (a float)."""
        return self.mgfile.info.length

    @property
    def samplerate(self):
        """The audio's sample rate (an int)."""
        if hasattr(self.mgfile.info, 'sample_rate'):
            return self.mgfile.info.sample_rate
        return 0

    @property
    def bitdepth(self):
        """The number of bits per sample in the audio encoding (an int).
        Only available for certain file formats (zero where
        unavailable).
        """
        if hasattr(self.mgfile.info, 'bits_per_sample'):
            return self.mgfile.info.bits_per_sample
        return 0

    @property
    def channels(self):
        """The number of channels in the audio (an int)."""
        if isinstance(self.mgfile.info, mutagen.mp3.MPEGInfo):
            return {
                mutagen.mp3.STEREO: 2,
                mutagen.mp3.JOINTSTEREO: 2,
                mutagen.mp3.DUALCHANNEL: 2,
                mutagen.mp3.MONO: 1,
            }[self.mgfile.info.mode]
        if hasattr(self.mgfile.info, 'channels'):
            return self.mgfile.info.channels
        return 0

    @property
    def bitrate(self):
        """The number of bits per seconds used in the audio coding (an
        int). If this is provided explicitly by the compressed file
        format, this is a precise reflection of the encoding. Otherwise,
        it is estimated from the on-disk file size. In this case, some
        imprecision is possible because the file header is incorporated
        in the file size.
        """
        if hasattr(self.mgfile.info, 'bitrate') and self.mgfile.info.bitrate:
            # Many formats provide it explicitly.
            return self.mgfile.info.bitrate
        else:
            # Otherwise, we calculate bitrate from the file size. (This
            # is the case for all of the lossless formats.)
            if not self.length:
                # Avoid division by zero if length is not available.
                return 0
            size = os.path.getsize(self.path)
            return int(size * 8 / self.length)

    @property
    def format(self):
        """A string describing the file format/codec."""
        return TYPES[self.type]


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/*
 * Problem: There were no SSA edges added for cloned finally blocks. A finally block is cloned if there is an EH, switch or throw within it. This implied bad codegen as described in the customer scenario below. The call to Console.WriteLine changes code movement around the call and so the issue appears to go away but the Console.WriteLine is not really related.
 *
 * Solution: Add an OPONERROR edge around the summary OPSIDEEFFECT tuples to show that they are conditional.
 *
 * Customer Scenario: We seem to be hitting this strange bug (see repro code). If there is a try/catch statement in the finally block, the Test() method returns false, even if this should be impossible. Uncommenting the Console.WriteLine in the try block suddenly makes the test pass. Note that there is only one place where shouldFail becomes true. We tried this on an x86 machine, and the test always returns what we expected (true), we also get the correct result on VS2008, so the bug seems to be only on x64 builds.
 *
 * */

using System;

class ApplicationException : Exception { }

public class TestClass
{
    public static int Main(string[] args)
    {
        //this should return true;
        return Test() ? 100 : 101;
    }

    public static bool Test()
    {
        Console.WriteLine("Begin Test....");
        bool shouldFail = false;

        try
        {
            throw new ApplicationException();
        }
        catch (ApplicationException) //This is the expected behavior.
        {
            Console.WriteLine("correct exception occured.");
        }
        catch (Exception e)
        {
            Console.WriteLine("ApplicationException  was expected, but instead got:" + e);
            shouldFail = true;
        }

        finally
        {
            Console.WriteLine("In finally");

            try
            {
                //Console.WriteLine("In finally - try block");
            }
            catch (Exception e)
            {
                Console.WriteLine("test threw an Exception in finally: " + e);
                shouldFail = true;
            }
        }

        Console.WriteLine("should fail...{0}", shouldFail);
        if (shouldFail)
        {
            Console.WriteLine("should fail...{0}", shouldFail);
            return false;
        }

        Console.WriteLine("End Test. (PASSED)");
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
void Box::save () {
    string addr="Boxes/" + int2str(fileDescriptor) + ".txt";
    ofstream file(addr.c_str(), std::ofstream::out);
    for (int i = 0; i < votes.size(); i++)
    {
    	file<<votes[i].CANDIDATE_CODE<<endl;
    	file<<votes[i].CANDIDATE_VOTES<<endl;
    }
    file.close();
}

void Box::vote(int candidateCode, string voter)
{
	if(candidateCodes[candidateCode]==0)
	{
		candidateCodes[candidateCode]=votes.size();
		votes.push_back(pii(candidateCode, 1));
	}
	else
		votes[candidateCodes[candidateCode]].CANDIDATE_VOTES++;
	voters.push_back(voter);
	save();
}

int Box::getVote (int candidateCode)
{
	return votes[candidateCodes[candidateCode]].CANDIDATE_VOTES;
}

vector<pii> Box::getVotes ()
{
	return votes;
}

vector<string> Box::getVoters()
{
	return voters;
}

string int2str(int n)
{
	stringstream s;
	s<<n;
	return s.str();
}


text:
#ifndef SRC_TRACE_PROCESSOR_TRACE_PROCESSOR_STORAGE_IMPL_H_
#define SRC_TRACE_PROCESSOR_TRACE_PROCESSOR_STORAGE_IMPL_H_

#include <memory>

#include "perfetto/trace_processor/basic_types.h"
#include "perfetto/trace_processor/status.h"
#include "perfetto/trace_processor/trace_processor_storage.h"
#include "src/trace_processor/types/trace_processor_context.h"

namespace perfetto {
namespace trace_processor {

class TraceProcessorStorageImpl : public TraceProcessorStorage {
 public:
  explicit TraceProcessorStorageImpl(const Config&);
  ~TraceProcessorStorageImpl() override;

  util::Status Parse(std::unique_ptr<uint8_t[]>, size_t) override;
  void NotifyEndOfFile() override;

  TraceProcessorContext* context() { return &context_; }

 protected:
  TraceProcessorContext context_;
  bool unrecoverable_parse_error_ = false;
};

}  // namespace trace_processor
}  // namespace perfetto

#endif  // SRC_TRACE_PROCESSOR_TRACE_PROCESSOR_STORAGE_IMPL_H_


text:
require 'rubygems'
require 'bundler/setup'

require 'qenumerable'

require 'coveralls'
Coveralls.wear!

RSpec.configure do |config|
  # some (optional) config here
end


text:
//## begin module.cp preserve=yes
/*
 *   VGA13.H - VGA Mode 13h Functions
 */

//## end module.cp
#ifndef _VGA13_H_
#define _VGA13_H_
//## begin module.epilog preserve=yes

#if defined( __cplusplus )
extern "C" {
#endif

void get_pixels_13( unsigned char *pixels, int npixels,
                    int x, int y );
void put_pixels_13( unsigned char *pixels, int npixels,
                    int x, int y );

#if defined( __cplusplus )
}
#endif

//## end module.epilog
#endif


text:
#pragma once
#include <aws/elastictranscoder/ElasticTranscoder_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ElasticTranscoder
{
namespace Model
{

  /**
   *
Details about the timing of a job.

See Also:
   AWS
   * API Reference

   */
  class AWS_ELASTICTRANSCODER_API Timing
  {
  public:
    Timing();
    Timing(Aws::Utils::Json::JsonView jsonValue);
    Timing& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The time the job was submitted to Elastic Transcoder, in epoch
     * milliseconds.

     */
    inline long long GetSubmitTimeMillis() const{ return m_submitTimeMillis; }

    /**
     *
The time the job was submitted to Elastic Transcoder, in epoch
     * milliseconds.

     */
    inline void SetSubmitTimeMillis(long long value) { m_submitTimeMillisHasBeenSet = true; m_submitTimeMillis = value; }

    /**
     *
The time the job was submitted to Elastic Transcoder, in epoch
     * milliseconds.

     */
    inline Timing& WithSubmitTimeMillis(long long value) { SetSubmitTimeMillis(value); return *this;}

    /**
     *
The time the job began transcoding, in epoch milliseconds.

     */
    inline long long GetStartTimeMillis() const{ return m_startTimeMillis; }

    /**
     *
The time the job began transcoding, in epoch milliseconds.

     */
    inline void SetStartTimeMillis(long long value) { m_startTimeMillisHasBeenSet = true; m_startTimeMillis = value; }

    /**
     *
The time the job began transcoding, in epoch milliseconds.

     */
    inline Timing& WithStartTimeMillis(long long value) { SetStartTimeMillis(value); return *this;}

    /**
     *
The time the job finished transcoding, in epoch milliseconds.

     */
    inline long long GetFinishTimeMillis() const{ return m_finishTimeMillis; }

    /**
     *
The time the job finished transcoding, in epoch milliseconds.

     */
    inline void SetFinishTimeMillis(long long value) { m_finishTimeMillisHasBeenSet = true; m_finishTimeMillis = value; }

    /**
     *
The time the job finished transcoding, in epoch milliseconds.

     */
    inline Timing& WithFinishTimeMillis(long long value) { SetFinishTimeMillis(value); return *this;}

  private:

    long long m_submitTimeMillis;
    bool m_submitTimeMillisHasBeenSet;

    long long m_startTimeMillis;
    bool m_startTimeMillisHasBeenSet;

    long long m_finishTimeMillis;
    bool m_finishTimeMillisHasBeenSet;
  };

} // namespace Model
} // namespace ElasticTranscoder
} // namespace Aws


text:
/**
  *File: calFn.cpp

  *Description:

   this file implements the class calFn

  *Version: 1.2

  *Dependencies:

  *Authors: Premalatha, Vidyadhar Mudkavi, CTFD, NAL.

  *Date:
  */

// system includes
// standard templates
// local includes
#include "calFn.h"
#include "calRataDie.h"
#include "calGregorian.h"

// const declarations
const char* calFn_id =
   "@(#) calFn. implementation. ver. 1.2. Premalatha, Vidyadhar Mudkavi, CTFD, NAL.";
// function prototypes
// forward declarations

// begin class implementation
   ////////////////////////////////////////
   //
   //    implement constructors here
   //
   //

/**
  *Purpose: provides default constructor
  */
calFn::calFn()
{
// empty
}

/**
  *Purpose: provides copy constructor
  */
calFn::calFn(const calFn& fn)
{
// empty
}

   ////////////////////////////////////////
   //
   //    implement assignment operators
   //
   //

calFn& calFn::operator=(const calFn& fn)
{
   return *this;
}

   ////////////////////////////////////////
   //
   //    implement the destructor
   //
   //

calFn::~calFn()
{
// empty
}

   ////////////////////////////////////////////
   //
   //   implement other member functions here
   //
   //

/**
  * Fixed date of the k-day before fixed date (rd)
  * k-day of 0 means sunday, 1 means monday and so on.
  * Inputs are fixed date and weekday.
  */
int calFn::KDayBefore(const calRataDie& rd, int k)
{
   return KDayOnOrBefore(rd-1, k);
}

/**
  * Fixed date of the k-day after fixed date (rd)
  * k-day of 0 means sunday, 1 means monday and so on.
  * Inputs are fixed date and weekday.
  */
int calFn::KDayAfter(const calRataDie& rd, int k)
{
   return KDayOnOrBefore(rd()+7, k);
}

/**
  * Fixed date of the k-day on or before fixed date (rd)
  * k-day of 0 means sunday, 1 means monday and so on.
  * Inputs are fixed date and weekday.
  */
int calFn::KDayOnOrBefore(const calRataDie& rd, int k)
{
   return rd()-DayOfWeekFromFixed(rd-k);
}

/**
  * Residue class of the day of the week of date.
  * Inputs are fixed date. returns day of the week.
  */
int calFn::DayOfWeekFromFixed(const calRataDie& date)
{
   long int lindex = calFn::Mod(date(), 7);
   int index = static_cast<int>( calFn::Mod(date(), 7) );
   return index;
}

/**
  * Returns fixed date of the n-th k-day after Gregorian date.
  * Inputs are integer, weekday and gregorain-date
  * k-day of 0 means sunday, 1 means monday and so on.
  */
int calFn::NthKDay(int n, int k, const calGregorian& g_date)
{
   if (n > 0)
   {
      return ( 7*n + KDayBefore(g_date.Fixed(), k) ); // return n-th k-day on or after date.
   }
   else
   {
      return ( 7*n + KDayAfter(g_date.Fixed(), k) ); // return n-th k-day on or before date.
   }
}

// follow this pattern for function comments

/**
  *Purpose:
  *Returns:
  *Params:
  *Throws:
  */

// here is an example
#if 0 // here is an example
/**
  *Purpose:
      this function add the matrix passed as arg.

  *Returns:
      matrixNode* ... pointer to a matrix node

  *Params:
      ptr_mn -- a const pointer to matrix node
      gmn    -- general matrix node

  *Throws:
      aMatrix::exception object
  */
matrixNode* aMatrix::Add(const matrixNode* ptr_mn, ...)
#endif // end of example


text:
package net.modelbased.proasense.storage.writer;

import eu.proasense.internal.SimpleEvent;
import net.modelbased.proasense.storage.EventProperties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;

import java.util.Properties;

public class SimpleEventKafkaGenerator<T> implements Runnable {
    private Class<T> eventType;
    private String bootstrapServers;
    private String groupId;
    private String topic;
    private String collectionId;
    private int messages_per_second;
    private int max_messages;
    private RandomEventGenerator eventGenerator;

    public SimpleEventKafkaGenerator(Class<T> eventType, String bootstrapServers, String groupId, String topic, String collectionId, int messages_per_second, int max_messages) {
        this.eventType = eventType;
        this.bootstrapServers = bootstrapServers;
        this.groupId = groupId;
        this.topic = topic;
        this.collectionId = collectionId;
        this.messages_per_second = messages_per_second;
        this.max_messages = max_messages;
        this.eventGenerator = new RandomEventGenerator();
    }

    public void run() {
        KafkaProducer<String, byte[]> producer = createProducer(bootstrapServers);

        int cnt = 0;
        try {
            while (cnt < this.max_messages) {
                Thread.sleep(1000);

                String eventTypeName = eventType.getName();

                for (int i = 0; i < this.messages_per_second; i++) {
                    // Generate simple event with random values
                    if (eventTypeName.matches(EventProperties.SIMPLEEVENT_CLASS_NAME)) {
                        T event = (T) eventGenerator.generateSimpleEvent(this.collectionId);

                        // Serialize message
                        TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
                        byte[] bytes = serializer.serialize((SimpleEvent) event);

                        // Publish message
                        ProducerRecord<String, byte[]> message = new ProducerRecord<String, byte[]>(this.topic, bytes);
                        producer.send(message);

//                        if ((cnt + i) % 1000 == 0)
//                            System.out.println("SimpleEvent(" + (cnt + i) + "): " + message.toString());
                    }
                }
                cnt = cnt + this.messages_per_second;
            }
        } catch (InterruptedException e) {
            System.out.println(e.getClass().getName() + ": " + e.getMessage());
        } catch (TException e) {
            System.out.println(e.getClass().getName() + ": " + e.getMessage());
        } finally {
            producer.close();
        }
    }

    private static KafkaProducer<String, byte[]> createProducer(String bootstrapServers) {
        // Specify producer properties
        Properties props = new Properties();
        props.put("bootstrap.servers", bootstrapServers);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");

        // Define the producer object
        KafkaProducer<String, byte[]> producer = new KafkaProducer<String, byte[]>(props);

        return producer;
    }

}


text:
package adf.agent.office;

import adf.agent.info.AgentInfo;
import adf.control.Control;
import adf.control.ControlAmbulance;
import adf.util.datastorage.DataStorage;
import comlib.manager.MessageManager;
import rescuecore2.messages.Command;
import rescuecore2.standard.entities.Building;
import rescuecore2.standard.entities.StandardEntityURN;
import rescuecore2.worldmodel.ChangeSet;

import java.util.Collection;
import java.util.EnumSet;

public class OfficeAmbulance extends Office<Building>
{
	public OfficeAmbulance(ControlAmbulance control, boolean isPrecompute)
	{
		super(control, isPrecompute, DATASTORAGE_FILE_NAME_AMBULANCE);
	}

	@Override
	protected EnumSet<StandardEntityURN> getRequestedEntityURNsEnum()
	{
		return EnumSet.of(StandardEntityURN.AMBULANCE_CENTRE);
	}

	@Override
	protected void postConnect()
	{
		super.postConnect();
	}
}


text:
package io.github.jackmiras.nucleolus.views;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;

import io.github.jackmiras.nucleolus.factories.PresenterFactory;
import io.github.jackmiras.nucleolus.factories.ReflectionPresenterFactory;
import io.github.jackmiras.nucleolus.helpers.NucleolusPresenterHelper;
import io.github.jackmiras.nucleolus.presenters.Presenter;

public abstract class NucleolusAppCompatActivity<PresenterType extends Presenter> extends AppCompatActivity {
    private static final String PRESENTER_STATE_KEY = "presenter_state";
    private NucleolusPresenterHelper<PresenterType> helper = new NucleolusPresenterHelper(this.getPresenterFactory());

    public NucleolusAppCompatActivity() {
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            this.helper.setPresenterState(savedInstanceState.getBundle(PRESENTER_STATE_KEY));
        }
        this.helper.takeView(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (helper.getPresenter().getView() == null)
            helper.takeView(this);
    }

    protected void onDestroy() {
        super.onDestroy();
        if (this.isFinishing()) {
            this.destroyPresenter();
        }

    }

    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle(PRESENTER_STATE_KEY, this.helper.savePresenter());
    }

    protected void onPause() {
        super.onPause();
        this.helper.dropView(this.isFinishing());
    }

    /**
     * The factory class used to create the presenter. Defaults to {@link ReflectionPresenterFactory} to create the presenter
     * using a no arg constructor.
     * <p/>
     * Subclasses can override this to provide presenters in other ways, like via their dependency injector.
     *
     * @return The {@link PresenterFactory} that can build a {@link Presenter}, or null.
     */
    public PresenterFactory<PresenterType> getPresenterFactory() {
        return ReflectionPresenterFactory.fromViewClass(this.getClass());
    }

    /**
     * Returns a current attached presenter.
     * This method is guaranteed to return a non-null value between
     * onResume/onPause and onAttachedToWindow/onDetachedFromWindow calls
     * if the presenter factory returns a non-null value.
     *
     * @return a currently attached presenter or null.
     */
    public PresenterType getPresenter() {
        return this.helper.getPresenter();
    }

    /**
     * Destroys a presenter that is currently attached to the View.
     */
    public void destroyPresenter() {
        this.helper.destroyPresenter();
    }
}


text:
Names are hard. Scuba Steve will find your files with the same base name and allow
you to cycle through them.

There are two commands: 'scuba-steve:toggle', scuba-steve:start-dive'.
Dive will refresh the path cache, and toggle will cycle through similar files (foo.hpp, foo.cpp, etc).

Activate the package with scuba-steve:start-dive. This will build the path cache for cycling between files. scuba-steve:toggle will switch between the files once the path cache is generated.

![](https://github.com/heftyfunseeker/scuba-steve/blob/master/ezgif.com-optimize.gif?raw=true "Example")

Example keymap:

```
'atom-workspace:not([mini])':
	'alt-o': 'scuba-steve:toggle'
```


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

    ob_start(); //for whitespace test
    require('../../../config.php');
    $extraws = ob_get_clean();

    require_once($CFG->libdir.'/adminlib.php');
    require_once($CFG->dirroot . '/' . $CFG->admin . '/tool/health/locallib.php');

    admin_externalpage_setup('toolhealth');

    define('SEVERITY_NOTICE',      'notice');
    define('SEVERITY_ANNOYANCE',   'annoyance');
    define('SEVERITY_SIGNIFICANT', 'significant');
    define('SEVERITY_CRITICAL',    'critical');

    $solution = optional_param('solution', 0, PARAM_PLUGIN);

    require_login();
    require_capability('moodle/site:config', context_system::instance());

    $site = get_site();

    echo $OUTPUT->header();

    if(strpos($solution, 'problem_') === 0 && class_exists($solution)) {
        health_print_solution($solution);
    }
    else {
        health_find_problems();
    }

    echo $OUTPUT->footer();

function health_find_problems() {
    global $OUTPUT;

    echo $OUTPUT->heading(get_string('pluginname', 'tool_health'));

    $issues   = array(
        SEVERITY_CRITICAL    => array(),
        SEVERITY_SIGNIFICANT => array(),
        SEVERITY_ANNOYANCE   => array(),
        SEVERITY_NOTICE      => array(),
    );
    $problems = 0;

    for($i = 1; $i < 1000000; ++$i) {
        $classname = sprintf('problem_%06d', $i);
        if(!class_exists($classname)) {
            continue;
        }
        $problem = new $classname;

        if($problem->exists()) {
            $severity = $problem->severity();
            $issues[$severity][$classname] = array(
                'severity'    => $severity,
                'description' => $problem->description(),
                'title'       => $problem->title()
            );
            ++$problems;
        }
        unset($problem);
    }

    if($problems == 0) {
        echo '
';
        echo get_string('healthnoproblemsfound', 'tool_health');
        echo '
';
    }
    else {
        echo $OUTPUT->heading(get_string('healthproblemsdetected', 'tool_health'));
        $severities = array(SEVERITY_CRITICAL, SEVERITY_SIGNIFICANT, SEVERITY_ANNOYANCE, SEVERITY_NOTICE);
        foreach($severities as $severity) {
            if(!empty($issues[$severity])) {
                echo '
';
                foreach($issues[$severity] as $classname => $data) {
                    echo '
'.$data['title'].'
';
                    echo '
'.$data['description'];
                    echo '<form action="index.php#solution" method="get">';
                    echo '<input type="hidden" name="solution" value="'.$classname.'" /><input type="submit" value="'.get_string('viewsolution').'" />';
                    echo '</form>
';
                }
                echo '
';
            }
        }
    }
}

function health_print_solution($classname) {
    global $OUTPUT;
    $problem = new $classname;
    $data = array(
        'title'       => $problem->title(),
        'severity'    => $problem->severity(),
        'description' => $problem->description(),
        'solution'    => $problem->solution()
    );

    echo $OUTPUT->heading(get_string('pluginname', 'tool_health'));
    echo $OUTPUT->heading(get_string('healthproblemsolution', 'tool_health'));
    echo '
';
    echo '
'.$data['title'].'
';
    echo '
'.$data['description'].'
';
    echo '
'.get_string('healthsolution', 'tool_health').'
';
    echo '
'.$data['solution'].'

';
    echo '<form id="healthformreturn" action="index.php#'.$classname.'" method="get">';
    echo '<input type="submit" value="'.get_string('healthreturntomain', 'tool_health').'" />';
    echo '</form>';
}

class problem_base {
    function exists() {
        return false;
    }
    function title() {
        return '???';
    }
    function severity() {
        return SEVERITY_NOTICE;
    }
    function description() {
        return '';
    }
    function solution() {
        return '';
    }
}

class problem_000002 extends problem_base {
    function title() {
        return 'Extra characters at the end of config.php or other library function';
    }
    function exists() {
        global $extraws;

        if($extraws === '') {
            return false;
        }
        return true;
    }
    function severity() {
        return SEVERITY_SIGNIFICANT;
    }
    function description() {
        return 'Your Moodle configuration file config.php or another library file, contains some characters after the closing PHP tag (?>). This causes Moodle to exhibit several kinds of problems (such as broken downloaded files) and must be fixed.';
    }
    function solution() {
        global $CFG;
        return 'You need to edit '.$CFG->dirroot.'/config.php and remove all characters (including spaces and returns) after the ending ?> tag. These two characters should be the very last in that file. The extra trailing whitespace may be also present in other PHP files that are included from lib/setup.php.';
    }
}

class problem_000003 extends problem_base {
    function title() {
        return '$CFG->dataroot does not exist or does not have write permissions';
    }
    function exists() {
        global $CFG;
        if(!is_dir($CFG->dataroot) || !is_writable($CFG->dataroot)) {
            return true;
        }
        return false;
    }
    function severity() {
        return SEVERITY_SIGNIFICANT;
    }
    function description() {
        global $CFG;
        return 'Your config.php says that your "data root" directory is '.$CFG->dataroot.'. However, this directory either does not exist or cannot be written to by Moodle. This means that a variety of problems will be present, such as users not being able to log in and not being able to upload any files. It is imperative that you address this problem for Moodle to work correctly.';
    }
    function solution() {
        global $CFG;
        return 'First of all, make sure that the directory '.$CFG->dataroot.' exists. If the directory does exist, then you must make sure that Moodle is able to write to it. Contact your web server administrator and request that he gives write permissions for that directory to the user that the web server process is running as.';
    }
}

class problem_000004 extends problem_base {
    function title() {
        return 'cron.php is not set up to run automatically';
    }
    function exists() {
        global $DB;
        $lastcron = $DB->get_field_sql('SELECT max(lastcron) FROM {modules}');
        return (time() - $lastcron > 3600 * 24);
    }
    function severity() {
        return SEVERITY_SIGNIFICANT;
    }
    function description() {
        return 'The cron.php mainenance script has not been run in the past 24 hours. This probably means that your server is not configured to automatically run this script in regular time intervals. If this is the case, then Moodle will mostly work as it should but some operations (notably sending email to users) will not be carried out at all.';
    }
    function solution() {
        global $CFG;
        return 'For detailed instructions on how to enable cron, see wwwroot.'/doc/?file=install.html#cron">this section of the installation manual.';
    }
}

class problem_000005 extends problem_base {
    function title() {
        return 'PHP: session.auto_start is enabled';
    }
    function exists() {
        return ini_get_bool('session.auto_start');
    }
    function severity() {
        return SEVERITY_CRITICAL;
    }
    function description() {
        return 'Your PHP configuration includes an enabled setting, session.auto_start, that must be disabled in order for Moodle to work correctly. Notable symptoms arising from this misconfiguration include fatal errors and/or blank pages when trying to log in.';
    }
    function solution() {
        global $CFG;
        return '
There are two ways you can solve this problem:

If you have access to your main php.ini file, then find the line that looks like this:
session.auto_start = 1
 and change it to
session.auto_start = 0
 and then restart your web server. Be warned that this, as any other PHP setting change, might affect other web applications running on the server.

Finally, you may be able to change this setting just for your site by creating or editing the file '.$CFG->dirroot.'/.htaccess to contain this line:
php_value session.auto_start "0"

';
    }
}

class problem_000007 extends problem_base {
    function title() {
        return 'PHP: file_uploads is disabled';
    }
    function exists() {
        return !ini_get_bool('file_uploads');
    }
    function severity() {
        return SEVERITY_SIGNIFICANT;
    }
    function description() {
        return 'Your PHP configuration includes a disabled setting, file_uploads, that must be enabled to let Moodle offer its full functionality. Until this setting is enabled, it will not be possible to upload any files into Moodle. This includes, for example, course content and user pictures.';
    }
    function solution() {
        global $CFG;
        return '
There are two ways you can solve this problem:

If you have access to your main php.ini file, then find the line that looks like this:
file_uploads = Off
 and change it to
file_uploads = On
 and then restart your web server. Be warned that this, as any other PHP setting change, might affect other web applications running on the server.

Finally, you may be able to change this setting just for your site by creating or editing the file '.$CFG->dirroot.'/.htaccess to contain this line:
php_value file_uploads "On"

';
    }
}

class problem_000008 extends problem_base {
    function title() {
        return 'PHP: memory_limit cannot be controlled by Moodle';
    }
    function exists() {
        global $CFG;

        $oldmemlimit = @ini_get('memory_limit');
        if (empty($oldmemlimit)) {
            // PHP not compiled with memory limits, this means that it's
            // probably limited to 8M or in case of Windows not at all.
            // We can ignore it for now - there is not much to test anyway
            // TODO: add manual test that fills memory??
            return false;
        }
        $oldmemlimit = get_real_size($oldmemlimit);
        //now lets change the memory limit to something higher
        $newmemlimit = ($oldmemlimit + 1024*1024*5);
        raise_memory_limit($newmemlimit);
        $testmemlimit = get_real_size(@ini_get('memory_limit'));
        //verify the change had any effect at all
        if ($oldmemlimit == $testmemlimit) {
            //memory limit can not be changed - is it big enough then?
            if ($oldmemlimit < get_real_size('128M')) {
                return true;
            } else {
                return false;
            }
        }
        reduce_memory_limit($oldmemlimit);
        return false;
    }
    function severity() {
        return SEVERITY_NOTICE;
    }
    function description() {
        return 'The settings for PHP on your server do not allow a script to request more memory during its execution. '.
               'This means that there is a hard limit of '.@ini_get('memory_limit').' for each script. '.
               'It is possible that certain operations within Moodle will require more than this amount in order '.
               'to complete successfully, especially if there are lots of data to be processed.';
    }
    function solution() {
        return 'It is recommended that you contact your web server administrator to address this issue.';
    }
}

class problem_000009 extends problem_base {
    function title() {
        return 'SQL: using account without password';
    }
    function exists() {
        global $CFG;
        return empty($CFG->dbpass);
    }
    function severity() {
        return SEVERITY_CRITICAL;
    }
    function description() {
        global $CFG;
        return 'The user account your are connecting to the database server with is set up without a password. This is a very big security risk and is only somewhat lessened if your database is configured to not accept connections from any hosts other than the server Moodle is running on. Unless you use a strong password to connect to the database, you risk unauthorized access to and manipulation of your data.'.($CFG->dbuser != 'root'?'':' This is especially alarming because such access to the database would be as the superuser (root)!');
    }
    function solution() {
        global $CFG;
        return 'You should change the password of the user '.$CFG->dbuser.' both in your database and in your Moodle config.php immediately!'.($CFG->dbuser != 'root'?'':' It would also be a good idea to change the user account from root to something else, because this would lessen the impact in the event that your database is compromised anyway.');
    }
}
/* // not implemented in 2.0 yet
class problem_000010 extends problem_base {
    function title() {
        return 'Uploaded files: slasharguments disabled or not working';
    }
    function exists() {
        if (!$this->is_enabled()) {
            return true;
        }
        if ($this->status() < 1) {
            return true;
        }
        return false;
    }
    function severity() {
        if ($this->is_enabled() and $this->status() == 0) {
            return SEVERITY_SIGNIFICANT;
        } else {
            return SEVERITY_ANNOYANCE;
        }
    }
    function description() {
        global $CFG;
        $desc = 'Slasharguments are needed for relative linking in uploaded resources:
';
        if (!$this->is_enabled()) {
            $desc .= '
slasharguments are disabled in Moodle configuration
';
        } else {
            $desc .= '
slasharguments are enabled in Moodle configuration
';
        }
        if ($this->status() == -1) {
            $desc .= '
can not run automatic test, you can verify it wwwroot.'/file.php/testslasharguments" target="_blank">here manually
';
        } else if ($this->status() == 0) {
            $desc .= '
slashargument test failed, please check server configuration
';
        } else {
            $desc .= '
slashargument test passed
';
        }
        $desc .= '
';
        return $desc;
    }
    function solution() {
        global $CFG;
        $enabled = $this->is_enabled();
        $status = $this->status();
        $solution = '';
        if ($enabled and ($status == 0)) {
            $solution .= 'Slasharguments are enabled, but the test failed. Please disable slasharguments in Moodle configuration or fix the server configuration.
';
        } else if ((!$enabled) and ($status == 0)) {
            $solution .= 'Slasharguments are disabled and the test failed. You may try to fix the server configuration.
';
        } else if ($enabled and ($status == -1)) {
            $solution .= 'Slasharguments are enabled, wwwroot.'/file.php/testslasharguments">automatic testing not possible.
';
        } else if ((!$enabled) and ($status == -1)) {
            $solution .= 'Slasharguments are disabled, wwwroot.'/file.php/testslasharguments">automatic testing not possible.
';
        } else if ((!$enabled) and ($status > 0)) {
            $solution .= 'Slasharguments are disabled though the iternal test is OK. You should enable slasharguments in Moodle configuration.';
        } else if ($enabled and ($status > 0)) {
            $solution .= 'Congratulations - everything seems OK now :-D';
        }
        if ($status < 1) {
            $solution .= '
IIS:

try to add cgi.fix_pathinfo=1 to php.ini

do NOT enable AllowPathInfoForScriptMappings !!!

slasharguments may not work when using ISAPI and PHP 4.3.10 and older

';
            $solution .= '
Apache 1:

try to add cgi.fix_pathinfo=1 to php.ini

';
            $solution .= '
Apache 2:

you must add AcceptPathInfo on to php.ini or .htaccess

try to add cgi.fix_pathinfo=1 to php.ini

';
        }
        return $solution;
    }
    function is_enabled() {
        global $CFG;
        return !empty($CFG->slasharguments);
    }
    function status() {
        global $CFG;
        $handle = @fopen($CFG->wwwroot.'/file.php?file=/testslasharguments', "r");
        $contents = @trim(fread($handle, 10));
        @fclose($handle);
        if ($contents != 'test -1') {
            return -1;
        }
        $handle = @fopen($CFG->wwwroot.'/file.php/testslasharguments', "r");
        $contents = trim(@fread($handle, 10));
        @fclose($handle);
        switch ($contents) {
            case 'test 1': return 1;
            case 'test 2': return 2;
            default:  return 0;
        }
    }
}*/

class problem_000012 extends problem_base {
    function title() {
        return 'Random questions data consistency';
    }
    function exists() {
        global $DB;
        return $DB->record_exists_select('question', "qtype = 'random' AND parent <> id", array());
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        return '
For random questions, question.parent should equal question.id. ' .
        'There are some questions in your database for which this is not true. ' .
        'One way that this could have happened is for random questions restored from backup before ' .
        'MDL-5482 was fixed.
';
    }
    function solution() {
        global $CFG;
        return '
Upgrade to Moodle 1.9.1 or later, or manually execute the SQL
' .
        '
UPDATE ' . $CFG->prefix . 'question SET parent = id WHERE qtype = \'random\' and parent <> id;
';
    }
}

class problem_000013 extends problem_base {
    function title() {
        return 'Multi-answer questions data consistency';
    }
    function exists() {
        global $DB;
        $positionexpr = $DB->sql_position($DB->sql_concat("','", "q.id", "','"),
                $DB->sql_concat("','", "qma.sequence", "','"));
        return $DB->record_exists_sql("
                SELECT * FROM {question} q
                    JOIN {question_multianswer} qma ON $positionexpr > 0
                WHERE qma.question <> q.parent") ||
            $DB->record_exists_sql("
                SELECT * FROM {question} q
                    JOIN {question} parent_q ON parent_q.id = q.parent
                WHERE q.category <> parent_q.category");
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        return '
For each sub-question whose id is listed in ' .
        'question_multianswer.sequence, its question.parent field should equal ' .
        'question_multianswer.question; and each sub-question should be in the same ' .
        'category as its parent. There are questions in your database for ' .
        'which this is not the case. One way that this could have happened is ' .
        'for multi-answer questions restored from backup before ' .
        'MDL-14750 was fixed.
';
    }
    function solution() {
        return '
Upgrade to Moodle 1.9.1 or later, or manually execute the ' .
        'code in question_multianswer_fix_subquestion_parents_and_categories in ' .
        '/question/type/multianswer/db/upgrade.php' .
        'from the 1.9 stable branch.
';
    }
}

class problem_000014 extends problem_base {
    function title() {
        return 'Only multianswer and random questions should be the parent of another question';
    }
    function exists() {
        global $DB;
        return $DB->record_exists_sql("
                SELECT * FROM {question} q
                    JOIN {question} parent_q ON parent_q.id = q.parent
                WHERE parent_q.qtype NOT IN ('random', 'multianswer')");
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        return '
You have questions that violate this in your databse. ' .
        'You will need to investigate to determine how this happened.
';
    }
    function solution() {
        return '
It is impossible to give a solution without knowing more about ' .
        ' how the problem was caused. You may be able to get help from the ' .
        'Quiz forum.
';
    }
}

class problem_000015 extends problem_base {
    function title() {
        return 'Question categories should belong to a valid context';
    }
    function exists() {
        global $DB;
        return $DB->record_exists_sql("
            SELECT qc.*, (SELECT COUNT(1) FROM {question} q WHERE q.category = qc.id) AS numquestions
            FROM {question_categories} qc
                LEFT JOIN {context} con ON qc.contextid = con.id
            WHERE con.id IS NULL");
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        global $DB;
        $problemcategories = $DB->get_records_sql("
            SELECT qc.id, qc.name, qc.contextid, (SELECT COUNT(1) FROM {question} q WHERE q.category = qc.id) AS numquestions
            FROM {question_categories} qc
                LEFT JOIN {context} con ON qc.contextid = con.id
            WHERE con.id IS NULL
            ORDER BY numquestions DESC, qc.name");
        $table = '

Cat id	Category name	' .
        "Context id	Num Questions

\n";
        foreach ($problemcategories as $cat) {
            $table .= "
$cat->id	" . s($cat->name) . "	" .
            $cat->contextid ."	$cat->numquestions
\n";
        }
        $table .= '

';
        return '
All question categories are linked to a context id, and, ' .
        'the context they are linked to must exist. The following categories ' .
        'belong to a non-existant category:
' . $table . '
Any of these ' .
        'categories that contain no questions can just be deleted form the database. ' .
        'Other categories will require more thought.
';
    }
    function solution() {
        global $CFG;
        return '
You can delete the empty categories by executing the following SQL:

DELETE FROM ' . $CFG->prefix . 'question_categories
WHERE
    NOT EXISTS (SELECT * FROM ' . $CFG->prefix . 'question q WHERE q.category = ' . $CFG->prefix . 'question_categories.id)
AND NOT EXISTS (SELECT * FROM ' . $CFG->prefix . 'context con WHERE contextid = con.id)

Any remaining categories that contain questions will require more thought. ' .
        'People in the Quiz forum may be able to help.
';
    }
}

class problem_000016 extends problem_base {
    function title() {
        return 'Question categories should belong to the same context as their parent';
    }
    function exists() {
        global $DB;
        return $DB->record_exists_sql("
            SELECT parent_qc.id AS parent, child_qc.id AS child, child_qc.contextid
            FROM {question_categories} child_qc
                JOIN {question_categories} parent_qc ON child_qc.parent = parent_qc.id
            WHERE child_qc.contextid <> parent_qc.contextid");
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        global $DB;
        $problemcategories = $DB->get_records_sql("
            SELECT
                parent_qc.id AS parentid, parent_qc.name AS parentname, parent_qc.contextid AS parentcon,
                child_qc.id AS childid, child_qc.name AS childname, child_qc.contextid AS childcon
            FROM {question_categories} child_qc
                JOIN {question_categories} parent_qc ON child_qc.parent = parent_qc.id
            WHERE child_qc.contextid <> parent_qc.contextid");
        $table = '

Child category	Parent category

' .
        'Id	Name	Context id	' .
        'Id	Name	Context id	' .
        "

\n";
        foreach ($problemcategories as $cat) {
            $table .= "
$cat->childid	" . s($cat->childname) .
            "	$cat->childcon	$cat->parentid	" . s($cat->parentname) .
            "	$cat->parentcon
\n";
        }
        $table .= '

';
        return '
When one question category is the parent of another, then they ' .
        'should both belong to the same context. This is not true for the following categories:
' .
        $table;
    }
    function solution() {
        return '
An automated solution is difficult. It depends whether the ' .
        'parent or child category is in the wrong pace.' .
        'People in the Quiz forum may be able to help.
';
    }
}

class problem_000017 extends problem_base {
    function title() {
        return 'Question categories tree structure';
    }
    function find_problems() {
        global $DB;
        static $answer = null;

        if (is_null($answer)) {
            $categories = $DB->get_records('question_categories', array(), 'id');

            // Look for missing parents.
            $missingparent = tool_health_category_find_missing_parents($categories);

            // Look for loops.
            $loops = tool_health_category_find_loops($categories);

            $answer = array($missingparent, $loops);
        }

        return $answer;
    }
    function exists() {
        list($missingparent, $loops) = $this->find_problems();
        return !empty($missingparent) || !empty($loops);
    }
    function severity() {
        return SEVERITY_ANNOYANCE;
    }
    function description() {
        list($missingparent, $loops) = $this->find_problems();

        $description = '
The question categories should be arranged into tree ' .
                ' structures by the question_categories.parent field. Sometimes ' .
                ' this tree structure gets messed up.
';

        $description .= tool_health_category_list_missing_parents($missingparent);
        $description .= tool_health_category_list_loops($loops);

        return $description;
    }

    /**
     * Outputs resolutions to problems outlined in MDL-34684 with items having themselves as parent
     *
     * @link https://tracker.moodle.org/browse/MDL-34684
     * @return string Formatted html to be output to the browser with instructions and sql statements to run
     */
    public function solution() {
        global $CFG;
        list($missingparent, $loops) = $this->find_problems();

        $solution = '
Consider executing the following SQL queries. These fix ' .
                'the problem by moving some categories to the top level.
';

        if (!empty($missingparent)) {
            $solution .= "
UPDATE " . $CFG->prefix . "question_categories\n" .
                    "        SET parent = 0\n" .
                    "        WHERE id IN (" . implode(',', array_keys($missingparent)) . ");
\n";
        }

        if (!empty($loops)) {
            $solution .= "
UPDATE " . $CFG->prefix . "question_categories\n" .
                    "        SET parent = 0\n" .
                    "        WHERE id IN (" . implode(',', array_keys($loops)) . ");
\n";
        }

        return $solution;
    }
}

/**
 * Check course categories tree structure for problems.
 *
 * @copyright  2013 Marko Vidberg
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class problem_000018 extends problem_base {
    /**
     * Generate title for this problem.
     *
     * @return string Title of problem.
     */
    public function title() {
        return 'Course categories tree structure';
    }

    /**
     * Search for problems in the course categories.
     *
     * @uses $DB
     * @return array List of categories that contain missing parents or loops.
     */
    public function find_problems() {
        global $DB;
        static $answer = null;

        if (is_null($answer)) {
            $categories = $DB->get_records('course_categories', array(), 'id');

            // Look for missing parents.
            $missingparent = tool_health_category_find_missing_parents($categories);

            // Look for loops.
            $loops = tool_health_category_find_loops($categories);

            $answer = array($missingparent, $loops);
        }

        return $answer;
    }

    /**
     * Check if the problem exists.
     *
     * @return boolean True if either missing parents or loops found
     */
    public function exists() {
        list($missingparent, $loops) = $this->find_problems();
        return !empty($missingparent) || !empty($loops);
    }

    /**
     * Set problem severity.
     *
     * @return constant Problem severity.
     */
    public function severity() {
        return SEVERITY_SIGNIFICANT;
    }

    /**
     * Generate problem description.
     *
     * @return string HTML containing details of the problem.
     */
    public function description() {
        list($missingparent, $loops) = $this->find_problems();

        $description = '
The course categories should be arranged into tree ' .
                ' structures by the course_categories.parent field. Sometimes ' .
                ' this tree structure gets messed up.
';

        $description .= tool_health_category_list_missing_parents($missingparent);
        $description .= tool_health_category_list_loops($loops);

        return $description;
    }

    /**
     * Generate solution text.
     *
     * @uses $CFG
     * @return string HTML containing the suggested solution.
     */
    public function solution() {
        global $CFG;
        list($missingparent, $loops) = $this->find_problems();

        $solution = '
Consider executing the following SQL queries. These fix ' .
                'the problem by moving some categories to the top level.
';

        if (!empty($missingparent)) {
            $solution .= "
UPDATE " . $CFG->prefix . "course_categories\n" .
                    "        SET parent = 0, depth = 1, path = CONCAT('/', id)\n" .
                    "        WHERE id IN (" . implode(',', array_keys($missingparent)) . ");
\n";
        }

        if (!empty($loops)) {
            $solution .= "
UPDATE " . $CFG->prefix . "course_categories\n" .
                    "        SET parent = 0, depth = 1, path = CONCAT('/', id)\n" .
                    "        WHERE id IN (" . implode(',', array_keys($loops)) . ");
\n";
        }

        return $solution;
    }
}

class problem_00000x extends problem_base {
    function title() {
        return '';
    }
    function exists() {
        return false;
    }
    function severity() {
        return SEVERITY_SIGNIFICANT;
    }
    function description() {
        return '';
    }
    function solution() {
        global $CFG;
        return '';
    }
}

/*

TODO:

    session.save_path -- it doesn't really matter because we are already IN a session, right?
    detect unsupported characters in $CFG->wwwroot - see bug Bug #6091 - relative vs absolute path during backup/restore process

*/


text:
using System;
using UtahOpenSource.DataObjects;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace UtahOpenSource.DataStore.Abstractions
{
    public interface ISessionStore : IBaseStore<Session>
    {
        Task<IEnumerable<Session>> GetSpeakerSessionsAsync(string speakerId);
        Task<IEnumerable<Session>> GetNextSessions();
        Task<Session> GetAppIndexSession (string id);
    }
}


text:
			×
    		{{ message }}

    		×
    		{{ message }}

				×
    		{{ value }}

{{ results.messages[property].required }}

{{ results.messages[property].minlength }}

{{ results.messages[property].maxlength }}

{{ results.messages[property].pattern }}

{{ validations[property].required.message }}

{{ validations[property].minlength.message }}

{{ validations[property].maxlength.message }}

{{ validations[property].pattern.message }}


text:
package org.apache.camel.generator.openapi;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class PathSpringBootProjectSourceGeneratorTest {

    @Test
    public void shouldGenerateSourceCodeWithDefaults() throws IOException, URISyntaxException {
        Path path = new File("target/generated-sources").toPath();
        SpringBootProjectSourceCodeGenerator.generator().withPackageName("com.foo").generate(path);
        final String generatedContent = new String(Files.readAllBytes(Paths.get("target/generated-sources/com/foo/CamelRestController.java")), StandardCharsets.UTF_8);

        final URI file = PathSpringBootProjectSourceGeneratorTest.class.getResource("/SpringBootRestController.txt").toURI();
        final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8);

        assertThat(generatedContent).isEqualTo(expectedContent);
    }

}


text:
package org.apache.xbean.propertyeditor;

import java.beans.PropertyEditor;
import java.util.List;
import java.util.Collection;

/**
 * @version $Rev$ $Date$
 */
public class GenericCollectionConverter extends AbstractCollectionConverter {

    public GenericCollectionConverter(Class type, PropertyEditor editor) {
        super(type, editor);
    }

    protected Object createCollection(List list) {
        try {
            Collection collection = (Collection) getType().newInstance();
            collection.addAll(list);
            return collection;
        } catch (Exception e) {
            throw new PropertyEditorException(e);
        }
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ChangePositionsOnDeleteUserReferences extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('positions', function (Blueprint $table) {
            $table->dropForeign('positions_user_id_foreign');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('positions', function (Blueprint $table) {
            //
        });
    }
}


text:
#include "Thread.h"

#include "mbed_error.h"

namespace rtos {

Thread::Thread(void (*task)(void const *argument), void *argument,
        osPriority priority, uint32_t stack_size, unsigned char *stack_pointer) {
#ifdef CMSIS_OS_RTX
    _thread_def.pthread = task;
    _thread_def.tpriority = priority;
    _thread_def.stacksize = stack_size;
    if (stack_pointer != NULL) {
        _thread_def.stack_pointer = (uint32_t*)stack_pointer;
        _dynamic_stack = false;
    } else {
        _thread_def.stack_pointer = new uint32_t[stack_size/sizeof(uint32_t)];
        if (_thread_def.stack_pointer == NULL)
            error("Error allocating the stack memory\n");
        _dynamic_stack = true;
    }

    //Fill the stack with a magic word for maximum usage checking
    for (uint32_t i = 0; i < (stack_size / sizeof(uint32_t)); i++) {
        _thread_def.stack_pointer[i] = 0xE25A2EA5;
    }
#endif
    _tid = osThreadCreate(&_thread_def, argument);
}

osStatus Thread::terminate() {
    return osThreadTerminate(_tid);
}

osStatus Thread::set_priority(osPriority priority) {
    return osThreadSetPriority(_tid, priority);
}

osPriority Thread::get_priority() {
    return osThreadGetPriority(_tid);
}

int32_t Thread::signal_set(int32_t signals) {
    return osSignalSet(_tid, signals);
}

int32_t Thread::signal_clr(int32_t signals) {
    return osSignalClear(_tid, signals);
}

Thread::State Thread::get_state() {
#ifndef __MBED_CMSIS_RTOS_CA9
    return ((State)_thread_def.tcb.state);
#else
    uint8_t status;
    status = osThreadGetState(_tid);
    return ((State)status);
#endif
}

uint32_t Thread::stack_size() {
#ifndef __MBED_CMSIS_RTOS_CA9
    return _thread_def.tcb.priv_stack;
#else
    return 0;
#endif
}

uint32_t Thread::free_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
    uint32_t bottom = (uint32_t)_thread_def.tcb.stack;
    return _thread_def.tcb.tsk_stack - bottom;
#else
    return 0;
#endif
}

uint32_t Thread::used_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
    uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;
    return top - _thread_def.tcb.tsk_stack;
#else
    return 0;
#endif
}

uint32_t Thread::max_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
    uint32_t high_mark = 0;
    while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)
        high_mark++;
    return _thread_def.tcb.priv_stack - (high_mark * 4);
#else
    return 0;
#endif
}

osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {
    return osSignalWait(signals, millisec);
}

osStatus Thread::wait(uint32_t millisec) {
    return osDelay(millisec);
}

osStatus Thread::yield() {
    return osThreadYield();
}

osThreadId Thread::gettid() {
    return osThreadGetId();
}

Thread::~Thread() {
    terminate();
    if (_dynamic_stack) {
        delete[] (_thread_def.stack_pointer);
    }
}

}


text:
#ifndef SLAB_AUTOMOVE_H
#define SLAB_AUTOMOVE_H

/* default automove functions */
void *slab_automove_init(struct settings *settings);
void slab_automove_free(void *arg);
void slab_automove_run(void *arg, int *src, int *dst);

typedef void *(*slab_automove_init_func)(struct settings *settings);
typedef void (*slab_automove_free_func)(void *arg);
typedef void (*slab_automove_run_func)(void *arg, int *src, int *dst);

typedef struct {
    slab_automove_init_func init;
    slab_automove_free_func free;
    slab_automove_run_func run;
} slab_automove_reg_t;

#endif


text:
package org.apache.pig.scripting.jruby;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.util.Utils;
import org.apache.pig.parser.ParserException;
import org.apache.pig.backend.executionengine.ExecException;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;

/**
 * This class serves at the bridge between Ruby methods that
 * are registered with and extend PigUdf, and their execution in
 * Pig. An instance of the containing class is created, and their
 * method name will be called against that instance. If they have
 * a schema function associated, then when outputSchema is called,
 * that function will be given the input Schema and the output will
 * be given to Pig.
 */
public class JrubyEvalFunc extends EvalFunc<Object> {

    private String methodName;
    private long numRequiredArgs;
    private long numOptionalArgs;

    private String fileName;
    private String functionName;

    private boolean isInitialized = false;

    private String schemaPiece;
    private Object funcReceiver;
    private Object funcInfoEncapsulator;

    private static ScriptingContainer rubyEngine = JrubyScriptEngine.rubyEngine;
    private static Ruby ruby = rubyEngine.getProvider().getRuntime();

    // Instantiating this class without arguments is meaningless
    private JrubyEvalFunc() {}

    /**
     * The constructor for this class registers the filename of the Ruby script
     * and the name of the method we care about. The difference between function name
     * and method name is that the former is the name that was used to register the function,
     * whereas the method name is the actual method that must be invoked. The two are often
     * the same, but not always. functionName is the key to the list of EvalFuncs that
     * are registered.
     */
    public JrubyEvalFunc(String filename, String functionName) throws IOException {
        this.fileName = filename;
        this.functionName = functionName;
    }

    /**
     * This method initializes the objects necessary to evaluate the Ruby class on the pig side. Using
     * the object that was saved to the functionName key by Ruby, this class gets an instance of the
     * class that will receive method calls, as well as information on the arity.
     */
    private void initialize() {
        funcInfoEncapsulator = JrubyScriptEngine.RubyFunctions.getFunctions("evalfunc", fileName).get(functionName);

        funcReceiver = rubyEngine.callMethod(funcInfoEncapsulator, "get_receiver");
        methodName = rubyEngine.callMethod(funcInfoEncapsulator, "method_name", String.class);
        numRequiredArgs = rubyEngine.callMethod(funcInfoEncapsulator, "required_args", Long.class);
        numOptionalArgs = rubyEngine.callMethod(funcInfoEncapsulator, "optional_args", Long.class); //TODO support varargs?

        isInitialized = true;
    }

    /**
     * The exec method passes the tuple argument to the Ruby function, and converts the result back to Pig.
     */
    @Override
    public Object exec(Tuple tuple) throws IOException {
        if (!isInitialized)
            initialize();

        try {
            IRubyObject rubyResult = null;
            if (tuple == null || (numRequiredArgs == 0 && numOptionalArgs == 0)) {
                rubyResult = rubyEngine.callMethod(funcReceiver, methodName, IRubyObject.class);
            } else {
                Object[] args = PigJrubyLibrary.pigToRuby(ruby, tuple).toArray();
                if (args.length >= numRequiredArgs && (numOptionalArgs == -1 || args.length <= numRequiredArgs + numOptionalArgs)) {
                    rubyResult = rubyEngine.callMethod(funcReceiver, methodName, args, IRubyObject.class);
                } else {
                    String s = "Method " + methodName + " requires " + numRequiredArgs + " arguments and ";
                    s += ( numOptionalArgs == -1 ? "unlimitated " : numOptionalArgs ) +" optional arguments. ";
                    s += "Instead, " + args.length + " arguments given.";
                    throw new RuntimeException(s);
                }
            }
            return PigJrubyLibrary.rubyToPig(rubyResult);
        } catch (Exception e) {
            throw new IOException("Error executing function",  e);
        }
    }

    /**
     * This method uses the schema method of the function encapsulation object to get the Schema information for
     * the Ruby method.
     */
    @Override
    public Schema outputSchema(Schema input) {
        if (!isInitialized)
            initialize();
        RubySchema rs = PigJrubyLibrary.pigToRuby(ruby, input);
        return PigJrubyLibrary.rubyToPig(rubyEngine.callMethod(funcInfoEncapsulator, "schema", new Object[]{rs, funcReceiver}, RubySchema.class));
    }
}