text:
' Fw Model base class
'
' Part of ASP.NET osa framework  www.osalabs.com/osafw/asp.net
' (c) 2009-2013 Oleg Savchuk www.osalabs.com

Imports System.IO

Public MustInherit Class FwModel : Implements IDisposable
    Public Const STATUS_ACTIVE = 0
    Public Const STATUS_INACTIVE = 10
    Public Const STATUS_DELETED = 127

    Protected fw As FW
    Protected db As DB
    Protected db_config As String = "" 'if empty(default) - fw.db used, otherwise - new db connection created based on this config name

    Public table_name As String = "" 'must be assigned in child class
    Public csv_export_fields As String = "" 'all or Utils.qw format
    Public csv_export_headers As String = "" 'comma-separated format

    Public field_id As String = "id" 'default primary key name
    Public field_iname As String = "iname"
    Public field_icode As String = "icode"

    'default field names. If you override it and make empty - automatic processing disabled
    Public field_status As String = "status"
    Public field_add_users_id As String = "add_users_id"
    Public field_upd_users_id As String = "upd_users_id"
    Public field_upd_time As String = "upd_time"
    Public field_prio As String = ""
    Public is_normalize_names As Boolean = False 'if true - Utils.name2fw() will be called for all fetched rows to normalize names (no spaces or special chars)

    Public is_log_changes As Boolean = True 'if true - event_log record added on add/update/delete
    Public is_log_fields_changed As Boolean = True 'if true - event_log.fields filled with changes

    'for linked models ex UsersCompanies that link 2 tables
    Public linked_model_main As FwModel
    Public linked_field_main_id As String 'ex users_id
    Public linked_model_link As FwModel
    Public linked_field_link_id As String 'ex companies_id

    Protected cache_prefix As String = "fwmodel.one." 'default cache prefix for caching items

    Protected Sub New(Optional fw As FW = Nothing)
        If fw IsNot Nothing Then
            Me.fw = fw
            Me.db = fw.db
        End If

        cache_prefix = cache_prefix & Me.GetType().Name & "*" 'setup cache prefix for this model only
    End Sub

    Public Overridable Sub init(fw As FW)
        Me.fw = fw
        If Me.db_config > "" Then
            Me.db = New DB(fw, fw.config("db")(Me.db_config), Me.db_config)
        Else
            Me.db = fw.db
        End If
    End Sub

    Public Overridable Function getDB() As DB
        Return db
    End Function

    Public Overridable Function one(id As Integer) As Hashtable
        Dim cache_key = Me.cache_prefix & id
        Dim item As Hashtable = fw.cache.getRequestValue(cache_key)
        If IsNothing(item) Then
            Dim where As Hashtable = New Hashtable
            where(Me.field_id) = id
            item = db.row(table_name, where)
            normalizeNames(item)
            fw.cache.setRequestValue(cache_key, item)
        End If
        Return item
    End Function

    Public Overridable Function multi(ids As ICollection) As ArrayList
        Dim arr(ids.Count - 1) As Object
        ids.CopyTo(arr, 0)
        Return db.array(table_name, New Hashtable From {{"id", db.opIN(arr)}})
    End Function

    'add renamed fields For template engine - spaces and special chars replaced With "_" and other normalizations
    Public Overloads Sub normalizeNames(row As Hashtable)
        If Not is_normalize_names OrElse row.Count = 0 Then Return
        For Each key In New ArrayList(row.Keys) 'static copy of row keys to avoid loop issues
            row(Utils.name2fw(key)) = row(key)
        Next
        If field_id > "" AndAlso row(field_id) IsNot Nothing AndAlso Not row.ContainsKey("id") Then row("id") = row(field_id)
    End Sub

    Public Overloads Sub normalizeNames(rows As ArrayList)
        If Not is_normalize_names Then Return
        For Each row As Hashtable In rows
            normalizeNames(row)
        Next
    End Sub

    Public Overridable Overloads Function iname(id As Integer) As String
        If field_iname = "" Then Return ""

        Dim row As Hashtable = one(id)
        Return row(field_iname)
    End Function
    Public Overridable Overloads Function iname(id As Object) As String
        Dim result = ""
        If Utils.f2int(id) > 0 Then
            result = iname(Utils.f2int(id))
        End If
        Return result
    End Function

    Protected Overridable Function getOrderBy() As String
        Dim result = field_iname
        If field_prio > "" Then result = db.q_ident(field_prio) & " desc, " & db.q_ident(field_iname)
        Return result
    End Function

    'return standard list of id,iname where status=0 order by iname
    Public Overridable Function list() As ArrayList
        Dim where As New Hashtable
        If field_status > "" Then where(field_status) = db.opNOT(STATUS_DELETED)
        Return db.array(table_name, where, getOrderBy())
    End Function

    'override if id/iname differs in table
    'def - in dynamic controller - field definition (also contains "i" and "ps", "lookup_params", ...) or you could use it to pass additional params
    Public Overridable Function listSelectOptions(Optional def As Hashtable = Nothing) As ArrayList
        Dim where As New Hashtable
        If field_status > "" Then where(field_status) = db.opNOT(STATUS_DELETED)

        Dim select_fields As New ArrayList From {
                New Hashtable From {{"field", field_id}, {"alias", "id"}},
                New Hashtable From {{"field", field_iname}, {"alias", "iname"}}
            }
        Return db.array(table_name, where, getOrderBy(), select_fields)
    End Function

    'similar to listSelectOptions but returns iname/iname
    Public Overridable Function listSelectOptionsName(Optional def As Hashtable = Nothing) As ArrayList
        Dim where As New Hashtable
        If field_status > "" Then where(field_status) = db.opNOT(STATUS_DELETED)

        Dim select_fields As New ArrayList From {
                New Hashtable From {{"field", field_iname}, {"alias", "id"}},
                New Hashtable From {{"field", field_iname}, {"alias", "iname"}}
            }
        Return db.array(table_name, where, getOrderBy(), select_fields)
    End Function

    'return count of all non-deleted
    Public Function getCount() As Integer
        Dim where As New Hashtable
        If field_status > "" Then where(field_status) = db.opNOT(STATUS_DELETED)
        Return db.value(table_name, where, "count(*)")
    End Function

    'just return first row by iname field (you may want to make it unique)
    Public Overridable Function oneByIname(iname As String) As Hashtable
        If field_iname = "" Then Return New Hashtable

        Dim where As Hashtable = New Hashtable
        where(field_iname) = iname
        Return db.row(table_name, where)
    End Function

    Public Overridable Function oneByIcode(icode As String) As Hashtable
        If field_icode = "" Then Return New Hashtable

        Dim where As Hashtable = New Hashtable
        where(field_icode) = icode
        Return db.row(table_name, where)
    End Function

    'check if item exists for a given field
    Public Overridable Function isExistsByField(uniq_key As Object, not_id As Integer, field As String) As Boolean
        Dim where As New Hashtable
        where(field) = uniq_key
        If field_id > "" Then where(field_id) = db.opNOT(not_id)
        Dim val As String = db.value(table_name, where, "1")
        If val = "1" Then
            Return True
        Else
            Return False
        End If
    End Function

    'check if item exists for a given iname
    Public Overridable Function isExists(uniq_key As Object, not_id As Integer) As Boolean
        Return isExistsByField(uniq_key, not_id, field_iname)
    End Function

    'add new record and return new record id
    Public Overridable Function add(item As Hashtable) As Integer
        'item("add_time") = Now() 'not necessary because add_time field in db should have default value now() or getdate()
        If field_add_users_id > "" AndAlso Not item.ContainsKey(field_add_users_id) AndAlso fw.SESSION("is_logged") Then item(field_add_users_id) = fw.SESSION("user_id")
        Dim id As Integer = db.insert(table_name, item)

        If is_log_changes Then
            If is_log_fields_changed Then
                fw.logEvent(table_name & "_add", id, 0, "", 0, item)
            Else
                fw.logEvent(table_name & "_add", id)
            End If
        End If

        Me.removeCache(id)

        Return id
    End Function

    'update exising record
    Public Overridable Function update(id As Integer, item As Hashtable) As Boolean
        Dim item_changes As New Hashtable
        If is_log_changes Then
            Dim item_old = Me.one(id)
            item_changes = fw.model(Of FwEvents).changes_only(item, item_old)
        End If

        If field_upd_time > "" Then item(field_upd_time) = Now()
        If field_upd_users_id > "" AndAlso Not item.ContainsKey(field_upd_users_id) AndAlso fw.SESSION("is_logged") Then item(field_upd_users_id) = fw.SESSION("user_id")

        Dim where As New Hashtable
        where(Me.field_id) = id
        db.update(table_name, item, where)

        Me.removeCache(id) 'cleanup cache, so next one read will read new value

        If is_log_changes AndAlso item_changes.Count > 0 Then
            If is_log_fields_changed Then
                fw.logEvent(table_name & "_upd", id, 0, "", 0, item_changes)
            Else
                fw.logEvent(table_name & "_upd", id)
            End If
        End If

        Return True
    End Function

    'mark record as deleted (status=127) OR actually delete from db (if is_perm or status field not defined for this model table)
    Public Overridable Sub delete(id As Integer, Optional is_perm As Boolean = False)
        Dim where As New Hashtable
        where(Me.field_id) = id

        If is_perm OrElse String.IsNullOrEmpty(field_status) Then
            'place here code that remove related data
            db.del(table_name, where)
            Me.removeCache(id)
        Else
            Dim vars As New Hashtable
            vars(field_status) = STATUS_DELETED
            If field_upd_time > "" Then vars(field_upd_time) = Now()
            If field_upd_users_id > "" AndAlso fw.SESSION("is_logged") Then vars(field_upd_users_id) = fw.SESSION("user_id")

            db.update(table_name, vars, where)
        End If
        If is_log_changes Then
            fw.logEvent(table_name & "_del", id)
        End If
    End Sub

    Public Overridable Sub removeCache(id As Integer)
        Dim cache_key = Me.cache_prefix & id
        fw.cache.requestRemove(cache_key)
    End Sub

    Public Overridable Sub removeCacheAll()
        fw.cache.requestRemoveWithPrefix(Me.cache_prefix)
    End Sub

    'upload utils
    Public Overridable Function uploadFile(id As Integer, ByRef filepath As String, Optional input_name As String = "file1", Optional is_skip_check As Boolean = False) As Boolean
        Return UploadUtils.uploadFile(fw, table_name, id, filepath, input_name, is_skip_check)
    End Function
    Public Overridable Function uploadFile(id As Integer, ByRef filepath As String, Optional file_index As Integer = 0, Optional is_skip_check As Boolean = False) As Boolean
        Return UploadUtils.uploadFile(fw, table_name, id, filepath, file_index, is_skip_check)
    End Function

    'return upload dir for the module name and id related to FW.config("site_root")/upload
    ' id splitted to 1000
    Public Overridable Function getUploadDir(ByVal id As Long) As String
        Return UploadUtils.getUploadDir(fw, table_name, id)
    End Function

    Public Overridable Function getUploadUrl(ByVal id As Long, ByVal ext As String, Optional size As String = "") As String
        Return UploadUtils.getUploadUrl(fw, table_name, id, ext, size)
    End Function

    'removes all type of image files uploaded with thumbnails
    Public Overridable Function removeUpload(ByVal id As Long, ByVal ext As String) As Boolean
        Dim dir As String = getUploadDir(id)

        If UploadUtils.isUploadImgExtAllowed(ext) Then
            'if this is image - remove possibly created thumbs
            File.Delete(dir & "/" & id & "_l" & ext)
            File.Delete(dir & "/" & id & "_m" & ext)
            File.Delete(dir & "/" & id & "_s" & ext)
        End If

        'delete main file
        File.Delete(dir & "/" & id & ext)
        Return True
    End Function

    Public Overridable Function getUploadImgPath(ByVal id As Long, ByVal size As String, Optional ext As String = "") As String
        Return UploadUtils.getUploadImgPath(fw, table_name, id, size, ext)
    End Function

    'methods from fw - just for a covenience, so no need to use "fw.", as they are used quite frequently
    Public Overloads Sub logger(ByVal ParamArray args() As Object)
        If args.Length = 0 Then Return
        fw._logger(LogLevel.DEBUG, args)
    End Sub
    Public Overloads Sub logger(level As LogLevel, ByVal ParamArray args() As Object)
        If args.Length = 0 Then Return
        fw._logger(level, args)
    End Sub

    Public Overridable Function getSelectOptions(sel_id As String) As String
        Return FormUtils.selectOptions(Me.listSelectOptions(), sel_id)
    End Function

    Public Overridable Function getAutocompleteList(q As String) As ArrayList
        Dim where As New Hashtable
        where(field_iname) = db.opLIKE("%" & q & "%")
        If field_status > "" Then where(field_status) = db.opNOT(STATUS_DELETED)
        Return db.col(table_name, where, field_iname)
    End Function

    'called from withing link model like UsersCompanies that links 2 tables By Main ID (like users_id)
    'id - main table id
    'def - in dynamic controller - field definition (also contains "i" and "ps", "lookup_params", ...) or you could use it to pass additional params
    Public Overridable Function getMultiListLinkedRows(id As Object, Optional def As Hashtable = Nothing) As ArrayList
        Dim linked_rows = db.array(table_name, New Hashtable From {{linked_field_main_id, id}})

        Dim lookup_rows As ArrayList = linked_model_link.list()
        If linked_rows IsNot Nothing AndAlso linked_rows.Count > 0 Then
            For Each row As Hashtable In lookup_rows
                'check if linked_rows contain main id
                row("is_checked") = False
                row("_link") = New Hashtable
                For Each lrow As Hashtable In linked_rows
                    If row(linked_model_link.field_id) = lrow(linked_field_link_id) Then
                        row("is_checked") = True
                        row("_link") = lrow
                        Exit For
                    End If
                Next
            Next

            'now sort so checked values will be at the top AND then by prio field (if any) - using LINQ
            Dim result As New ArrayList
            If field_prio > "" Then
                result.AddRange((From h In lookup_rows Order By h("_link")(field_prio), h("is_checked") Descending).ToList())
            Else
                result.AddRange((From h In lookup_rows Order By h("is_checked") Descending).ToList())
            End If
            lookup_rows = result
        End If
        Return lookup_rows
    End Function

    'called from withing link model like UsersCompanies that links 2 tables By Linked ID (like companies_id)
    'id - linked table id
    'def - in dynamic controller - field definition (also contains "i" and "ps", "lookup_params", ...) or you could use it to pass additional params
    Public Overridable Function getMultiListLinkedRowsByLinkedId(id As Object, Optional def As Hashtable = Nothing) As ArrayList
        Dim linked_rows = db.array(table_name, New Hashtable From {{linked_field_link_id, id}})

        Dim lookup_rows As ArrayList = linked_model_main.list()
        If linked_rows IsNot Nothing AndAlso linked_rows.Count > 0 Then
            For Each row As Hashtable In lookup_rows
                'check if linked_rows contain main id
                row("is_checked") = False
                row("_link") = New Hashtable
                For Each lrow As Hashtable In linked_rows
                    If row(linked_model_main.field_id) = lrow(linked_field_main_id) Then
                        row("is_checked") = True
                        row("_link") = lrow
                        Exit For
                    End If
                Next
            Next

            'now sort so checked values will be at the top AND then by prio field (if any) - using LINQ
            Dim result As New ArrayList
            If field_prio > "" Then
                result.AddRange((From h In lookup_rows Order By h("_link")(field_prio), h("is_checked") Descending).ToList())
            Else
                result.AddRange((From h In lookup_rows Order By h("is_checked") Descending).ToList())
            End If
            lookup_rows = result
        End If
        Return lookup_rows
    End Function

    Protected Sub setMultiListChecked(ByRef rows As ArrayList, ids As ArrayList, Optional def As Hashtable = Nothing)
        Dim is_checked_only = def IsNot Nothing AndAlso Utils.f2bool(def("lookup_checked_only"))

        If ids IsNot Nothing AndAlso ids.Count > 0 Then
            For Each row As Hashtable In rows
                row("is_checked") = ids.Contains(row(Me.field_id))
            Next
            'now sort so checked values will be at the top - using LINQ
            Dim result As New ArrayList
            If is_checked_only Then
                result.AddRange((From h In rows Where h("is_checked")).ToList())
            Else
                result.AddRange((From h In rows Order By h("is_checked") Descending).ToList())
            End If
            rows = result
        Else
            If is_checked_only Then
                'return no items if no checked
                rows = New ArrayList
            End If
        End If
    End Sub

    'sel_ids - selected ids in the list()
    'def - in dynamic controller - field definition (also contains "i" and "ps", "lookup_params", ...) or you could use it to pass additional params
    Public Overridable Function getMultiListAL(ids As ArrayList, Optional def As Hashtable = Nothing) As ArrayList
        Dim rows As ArrayList = Me.list()
        setMultiListChecked(rows, ids, def)
        Return rows
    End Function

    'overloaded version for string comma-separated ids
    'sel_ids - comma-separated ids
    'def - in dynamic controller - field definition (also contains "i" and "ps", "lookup_params", ...) or you could use it to pass additional params
    Public Overridable Function getMultiList(sel_ids As String, Optional def As Hashtable = Nothing) As ArrayList
        Dim ids As New ArrayList(Split(sel_ids, ","))
        Return Me.getMultiListAL(ids, def)
    End Function

    ''' <summary>
    '''     return array of ids of linked elements
    ''' </summary>
    ''' <param name="link_table_name">link table name that contains id_name and link_id_name fields</param>
    ''' <param name="id">main id</param>
    ''' <param name="id_name">field name for main id</param>
    ''' <param name="link_id_name">field name for linked id</param>
    ''' <returns></returns>
    Public Overridable Function getLinkedIds(link_table_name As String, id As Integer, id_name As String, link_id_name As String) As ArrayList
        Dim where As New Hashtable
        where(id_name) = id
        Dim rows As ArrayList = db.array(link_table_name, where)
        Dim result As New ArrayList
        For Each row As Hashtable In rows
            result.Add(row(link_id_name))
        Next

        Return result
    End Function

    'shortcut for getLinkedIds based on dynamic controller definition
    Public Overridable Function getLinkedIdsByDef(id As Integer, def As Hashtable) As ArrayList
        Return getLinkedIds(def("table_link"), id, def("table_link_id_name"), def("table_link_linked_id_name"))
    End Function

    ''' <summary>
    '''  update (and add/del) linked table
    ''' </summary>
    ''' <param name="link_table_name">link table name that contains id_name and link_id_name fields</param>
    ''' <param name="id">main id</param>
    ''' <param name="id_name">field name for main id</param>
    ''' <param name="link_id_name">field name for linked id</param>
    ''' <param name="linked_keys">hashtable with keys as link id (as passed from web)</param>
    Public Overridable Sub updateLinked(link_table_name As String, id As Integer, id_name As String, link_id_name As String, linked_keys As Hashtable)
        Dim fields As New Hashtable
        Dim where As New Hashtable
        Dim link_table_field_status = "status"

        'set all fields as under update
        fields(link_table_field_status) = 1
        where(id_name) = id
        db.update(link_table_name, fields, where)

        If linked_keys IsNot Nothing Then
            For Each link_id As String In linked_keys.Keys
                fields = New Hashtable
                fields(id_name) = id
                fields(link_id_name) = link_id
                fields(link_table_field_status) = 0

                where = New Hashtable
                where(id_name) = id
                where(link_id_name) = link_id
                db.update_or_insert(link_table_name, fields, where)
            Next
        End If

        'remove those who still not updated (so removed)
        where = New Hashtable
        where(id_name) = id
        where(link_table_field_status) = 1
        db.del(link_table_name, where)
    End Sub

    'override to add set more additional fields
    Public Overridable Sub updateLinkedRowsAdditional(linked_keys As Hashtable, link_id As String, fields As Hashtable)
        If field_prio > "" AndAlso linked_keys.Contains(field_prio & "_" & link_id) Then
            fields(field_prio) = Utils.f2int(linked_keys(field_prio & "_" & link_id)) 'get value from prio_ID
        End If
    End Sub
    'called from withing link model like UsersCompanies that links 2 tables
    Public Overridable Sub updateLinkedRows(main_id As Integer, linked_keys As Hashtable)
        Dim fields As New Hashtable
        Dim where As New Hashtable
        Dim link_table_field_status = Me.field_status

        'set all fields as under update
        fields(link_table_field_status) = 1
        where(linked_field_main_id) = main_id
        db.update(table_name, fields, where)

        If linked_keys IsNot Nothing Then
            For Each link_id As String In linked_keys.Keys
                If Utils.f2int(link_id) = 0 Then Continue For 'skip non-id, ex prio_ID

                fields = New Hashtable
                fields(linked_field_main_id) = main_id
                fields(linked_field_link_id) = link_id
                fields(link_table_field_status) = 0

                'additional fields here
                updateLinkedRowsAdditional(linked_keys, link_id, fields)

                where = New Hashtable
                where(linked_field_main_id) = main_id
                where(linked_field_link_id) = link_id
                db.update_or_insert(table_name, fields, where)
            Next
        End If

        'remove those who still not updated (so removed)
        where = New Hashtable
        where(linked_field_main_id) = main_id
        where(link_table_field_status) = 1
        db.del(table_name, where)
    End Sub

    'override to add set more additional fields
    Public Overridable Sub updateLinkedRowsByLinkedIdAdditional(linked_keys As Hashtable, main_id As String, fields As Hashtable)
        If field_prio > "" AndAlso linked_keys.ContainsKey(field_prio & "_" & main_id) Then
            fields(field_prio) = Utils.f2int(linked_keys(field_prio & "_" & main_id)) 'get value from prio_ID
        End If
    End Sub
    'called from withing link model like UsersCompanies that links 2 tables
    Public Overridable Sub updateLinkedRowsByLinkedId(linked_id As Integer, linked_keys As Hashtable)
        Dim fields As New Hashtable
        Dim where As New Hashtable
        Dim link_table_field_status = Me.field_status

        'set all fields as under update
        fields(link_table_field_status) = 1
        where(linked_field_link_id) = linked_id
        db.update(table_name, fields, where)

        If linked_keys IsNot Nothing Then
            For Each main_id As String In linked_keys.Keys
                If Utils.f2int(main_id) = 0 Then Continue For 'skip non-id, ex prio_ID

                fields = New Hashtable
                fields(linked_field_link_id) = linked_id
                fields(linked_field_main_id) = main_id
                fields(link_table_field_status) = 0

                'additional fields here
                updateLinkedRowsByLinkedIdAdditional(linked_keys, main_id, fields)

                where = New Hashtable
                where(linked_field_link_id) = linked_id
                where(linked_field_main_id) = main_id
                logger(fields)
                db.update_or_insert(table_name, fields, where)
            Next
        End If

        'remove those who still not updated (so removed)
        where = New Hashtable
        where(linked_field_link_id) = linked_id
        where(link_table_field_status) = 1
        db.del(table_name, where)
    End Sub

    Public Overridable Function findOrAddByIname(iname As String, ByRef Optional is_added As Boolean = False) As Integer
        iname = Trim(iname)
        If iname.Length = 0 Then Return 0
        Dim result As Integer
        Dim item As Hashtable = Me.oneByIname(iname)
        If item.ContainsKey(Me.field_id) Then
            'exists
            result = item(Me.field_id)
        Else
            'not exists - add new
            item = New Hashtable
            item(field_iname) = iname
            result = Me.add(item)
            is_added = True
        End If
        Return result
    End Function

    Public Overridable Function getCSVExport() As StringBuilder
        Dim where As New Hashtable
        If field_status > "" Then where(field_status) = STATUS_ACTIVE

        Dim aselect_fields As String() = Array.Empty(Of String)()
        If csv_export_fields > "" Then
            aselect_fields = Utils.qw(csv_export_fields)
        End If

        Dim rows = db.array(table_name, where, "", aselect_fields)
        Return Utils.getCSVExport(csv_export_headers, csv_export_fields, rows)

    End Function

    Public Sub Dispose() Implements IDisposable.Dispose
        DirectCast(fw, IDisposable).Dispose()
    End Sub
End Class


text:
package org.apache.commons.vfs2.provider.temp.test;

import java.io.File;

import org.apache.commons.AbstractVfsTestCase;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.provider.temp.TemporaryFileProvider;
import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
import org.apache.commons.vfs2.test.ProviderTestSuite;

import junit.framework.Test;

/**
 * Test cases for the tmp: file provider.
 */
public class TemporaryProviderTestCase extends AbstractProviderTestConfig {
    /**
     * Creates the test suite for the tmp file system.
     */
    public static Test suite() throws Exception {
        return new ProviderTestSuite(new TemporaryProviderTestCase());
    }

    /**
     * Prepares the file system manager.
     */
    @Override
    public void prepare(final DefaultFileSystemManager manager) throws Exception {
        final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
        manager.addProvider("tmp", new TemporaryFileProvider(baseDir));
    }

    /**
     * Returns the base folder for tests.
     */
    @Override
    public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
        return manager.resolveFile("tmp:/");
    }
}

redpajama_set_name: RedPajamaGithub


text:
function toggleLicenseAccept(){
    var theForm     = document.forms[0];

    if( theForm.setup_license_accept.checked ){
        theForm.setup_license_accept.checked = "";
    }
    else {
        theForm.setup_license_accept.checked = "yes";
    }

    toggleNextButton();
}

function toggleNextButton(){
    var theForm     = document.forms[0];
    var nextButton  = document.getElementById( "button_next" );

    if( theForm.setup_license_accept.checked ){
        nextButton.disabled = '';
        nextButton.focus();
    }
    else {
        nextButton.disabled = "disabled";
    }
}


text:
_spaceship_ uses [Faraday](https://github.com/lostisland/faraday) to interact with multiple Apple API endpoints:

## Overview

Spaceship wraps various APIs using the following pattern:

A simple `client` and various data models, usually subclassed from a `Base` model (e.g. Spaceship::TestFlight::Base)
The `client` is responsible for making HTTP requests for a given API or domain. It should be very simple and have no logic.
It is only responsible for creating the request and parsing the response. The best practice is for each method to have a single request and return the data from the response.

The data models generally map to a REST resource or some logical grouping of data. Each data model has an instance of `client` which it can use to put or get data. It should encapsulate all interactions with the API, so other _fastlane_ tools interface with the data models, and not the `client` directly.

## Technical

_spaceship_ is split into 3 layers:

- `client.rb` which is the client superclass that contains all shared code between App Store Connect the Developer Portal
- `tunes_client.rb` and `portal_client.rb` which are the implementations for both App Store Connect and Developer Portal. Those classes include the actual HTTP requests that are being sent:
```ruby
def app_version_data(app_id, version_platform: nil, version_id: nil)
  r = request(:get, "ra/apps/#{app_id}/platforms/#{version_platform}/versions/#{version_id}")
  parse_response(r, 'data')
end
```
- _spaceship_ classes, e.g. `app_version.rb` which contain the API the user works with. These classes usually have some logic on how to handle responses.

Don't use any custom HTML parsing in _spaceship_, instead try to only use JSON and XML APIs.


text:
class Rpm < Formula
  desc "Standard unix software packaging tool"
  homepage "https://rpm.org/"
  url "http://ftp.rpm.org/releases/rpm-4.15.x/rpm-4.15.1.tar.bz2"
  sha256 "ddef45f9601cd12042edfc9b6e37efcca32814e1e0f4bb8682d08144a3e2d230"
  revision 1
  version_scheme 1

  livecheck do
    url "https://github.com/rpm-software-management/rpm.git"
    regex(/rpm[._-]v?(\d+(?:\.\d+)+)-release/i)
  end

  bottle do
    sha256 "e5d398daca37da278add441d2cb0825c019fed8bcfb33bd4abb01dad3dce42e0" => :catalina
    sha256 "0b5556d33614062b0b9d39cc8d3f4046d562cbaa9b03498cf4b11c57debb38fe" => :mojave
    sha256 "a59870c437fe72ce7438726f79a44111d8352dbe50b7f6cf9d147210034a764b" => :high_sierra
  end

  depends_on "berkeley-db"
  depends_on "gettext"
  depends_on "libarchive"
  depends_on "libmagic"
  depends_on "libomp"
  depends_on "lua"
  depends_on "openssl@1.1"
  depends_on "pkg-config"
  depends_on "popt"
  depends_on "xz"
  depends_on "zstd"

  def install
    ENV.prepend_path "PKG_CONFIG_PATH", Formula["lua"].opt_libexec/"lib/pkgconfig"
    ENV.append "CPPFLAGS", "-I#{Formula["lua"].opt_include}/lua"
    ENV.append "LDFLAGS", "-lomp"

    # only rpm should go into HOMEBREW_CELLAR, not rpms built
    inreplace ["macros.in", "platform.in"], "@prefix@", HOMEBREW_PREFIX

    # ensure that pkg-config binary is found for dep generators
    inreplace "scripts/pkgconfigdeps.sh",
              "/usr/bin/pkg-config", Formula["pkg-config"].opt_bin/"pkg-config"

    system "./configure", "--disable-dependency-tracking",
                          "--disable-silent-rules",
                          "--prefix=#{prefix}",
                          "--localstatedir=#{var}",
                          "--sharedstatedir=#{var}/lib",
                          "--sysconfdir=#{etc}",
                          "--with-path-magic=#{HOMEBREW_PREFIX}/share/misc/magic",
                          "--enable-nls",
                          "--disable-plugins",
                          "--with-external-db",
                          "--with-crypto=openssl",
                          "--without-apidocs",
                          "--with-vendor=homebrew",
                          # Don't allow superenv shims to be saved into lib/rpm/macros
                          "__MAKE=/usr/bin/make",
                          "__SED=/usr/bin/sed",
                          "__GIT=/usr/bin/git",
                          "__LD=/usr/bin/ld"
    system "make", "install"
  end

  def post_install
    (var/"lib/rpm").mkpath

    # Attempt to fix expected location of GPG to a sane default.
    inreplace lib/"rpm/macros", "/usr/bin/gpg2", HOMEBREW_PREFIX/"bin/gpg"
  end

  def test_spec
    <<~EOS
      Summary:   Test package
      Name:      test
      Version:   1.0
      Release:   1
      License:   Public Domain
      Group:     Development/Tools
      BuildArch: noarch

      %description
      Trivial test package

      %prep
      %build
      %install
      mkdir -p $RPM_BUILD_ROOT/tmp
      touch $RPM_BUILD_ROOT/tmp/test

      %files
      /tmp/test

      %changelog

    EOS
  end

  def rpmdir(macro)
    Pathname.new(`#{bin}/rpm --eval #{macro}`.chomp)
  end

  test do
    (testpath/"rpmbuild").mkpath

    (testpath/".rpmmacros").write <<~EOS
      %_topdir		#{testpath}/rpmbuild
      %_tmppath		%\{_topdir}/tmp
    EOS

    system "#{bin}/rpm", "-vv", "-qa", "--dbpath=#{testpath}/var/lib/rpm"
    assert_predicate testpath/"var/lib/rpm/Packages", :exist?,
                     "Failed to create 'Packages' file!"
    rpmdir("%_builddir").mkpath
    specfile = rpmdir("%_specdir")+"test.spec"
    specfile.write(test_spec)
    system "#{bin}/rpmbuild", "-ba", specfile
    assert_predicate rpmdir("%_srcrpmdir")/"test-1.0-1.src.rpm", :exist?
    assert_predicate rpmdir("%_rpmdir")/"noarch/test-1.0-1.noarch.rpm", :exist?
    system "#{bin}/rpm", "-qpi", "--dbpath=#{testpath}/var/lib/rpm",
                         rpmdir("%_rpmdir")/"noarch/test-1.0-1.noarch.rpm"
  end
end


text:
namespace EditorCommon
{
    public static class EditorConst
    {
        public static string[] TextureExts = { ".tga", ".png", ".jpg", ".tif", ".psd", ".exr" };
        public static string[] MaterialExts = { ".mat" };
        public static string[] ModelExts = { ".fbx", ".asset", ".obj" };
        public static string[] AnimationExts = { ".anim" };
        public static string[] MetaExts = { ".meta" };
        public static string[] ShaderExts = { ".shader" };
        public static string[] ScriptExts = { ".cs" };
        public static string[] PrefabExts = { ".prefab" };

        public static string PlatformAndroid = "Android";
        public static string PlatformIos = "iPhone";
        public static string PlatformStandalones = "Standalones";

        public static string EDITOR_ANICLIP_NAME = "__preview__Take 001";
        public static string[] EDITOR_CONTROL_NAMES = {"AnimatorStateMachine",
            "AnimatorStateTransition", "AnimatorState", "AnimatorTransition", "BlendTree" };
    }
}


text:
package com.baidu.ub.common.dbmanage.datasource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.baidu.ub.common.commons.ThreadContext;

public class MultiDataSource extends AbstractRoutingDataSource {

    private static final Logger log = Logger.getLogger(MultiDataSource.class);

    static {
        ThreadContext.putContext("Bootstrap", Boolean.TRUE);
    }

    private MultiDataSourceKeyContext multiDataSourceKeyContext;

    @Override
    protected Object determineCurrentLookupKey() {
        String key = "";
        try {
            key = multiDataSourceKeyContext.getKey();
        } catch (Throwable e) {
            logTrace(e);
        }
        return key;
    }

    private void logTrace(Throwable e) {

        StackTraceElement[] stackTraces = e.getStackTrace();
        if (Boolean.TRUE.equals(ThreadContext.getContext("Bootstrap"))) {
            for (int i = 4; i < stackTraces.length; i++) {// 过滤掉启动的时候,初始化的时候的一次连接没有key,如果有bean去连库数目大于1的库,就需要打印log
                String infos = stackTraces[i].getClassName();
                if (infos.contains("com.baidu.dsp")) {
                    log.error("get data source key fail,will use default data source", e);
                    break;
                }
            }
        } else {// 不是启动的时候报的找不到key,直接打印log和堆栈
            log.error("get data source key fail,will use default data source", e);
            return;
        }
        return;
    }

    public MultiDataSourceKeyContext getMultiDataSourceKeyContext() {
        return multiDataSourceKeyContext;
    }

    public void setMultiDataSourceKeyContext(MultiDataSourceKeyContext multiDataSourceKeyContext) {
        this.multiDataSourceKeyContext = multiDataSourceKeyContext;
    }

}


text:
using Freelancer.Model;
using Freelancer.Model.Models.EmployeeType;
using System.Collections.Generic;
using System.Data.Entity;

namespace Freelancer.Data
{
    public class FreelancerSeedData : CreateDatabaseIfNotExists<FreelancerEntities>
    {
        protected override void Seed(FreelancerEntities context)
        {
            //GetCategories().ForEach(c => context.Categories.Add(c));
            //GetGadgets().ForEach(g => context.Gadgets.Add(g));
            GetEmployeeType().ForEach(g => context.EmployeeTypes.Add(g));
            context.Commit();
        }
        private static List<EmployeeType> GetEmployeeType()
        {
            return new List<EmployeeType>
            {
                new EmployeeType {
                    Name = "Private"
                },
                new EmployeeType {
                    Name = "Company"
                },

            };
        }
        private static List<Category> GetCategories()
        {
            return new List<Category>
            {
                new Category {
                    Name = "Tablets"
                },
                new Category {
                    Name = "Laptops"
                },
                new Category {
                    Name = "Mobiles"
                }
            };
        }

        private static List<Gadget> GetGadgets()
        {
            return new List<Gadget>
            {
                new Gadget {
                    Name = "ProntoTec 7",
                    Description = "Android 4.4 KitKat Tablet PC, Cortex A8 1.2 GHz Dual Core Processor,512MB / 4GB,Dual Camera,G-Sensor (Black)",
                    CategoryID = 1,
                    Price = 46.99m,
                    Image = "prontotec.jpg"
                },
                new Gadget {
                    Name = "Samsung Galaxy",
                    Description = "Android 4.4 Kit Kat OS, 1.2 GHz quad-core processor",
                    CategoryID = 1,
                    Price = 120.95m,
                    Image= "samsung-galaxy.jpg"
                },
                new Gadget {
                    Name = "NeuTab® N7 Pro 7",
                    Description = "NeuTab N7 Pro tablet features the amazing powerful, Quad Core processor performs approximately Double multitasking running speed, and is more reliable than ever",
                    CategoryID = 1,
                    Price = 59.99m,
                    Image= "neutab.jpg"
                },
                new Gadget {
                    Name = "Dragon Touch® Y88X 7",
                    Description = "Dragon Touch Y88X tablet featuring the incredible powerful Allwinner Quad Core A33, up to four times faster CPU, ensures faster multitasking speed than ever. With the super-portable size, you get a robust power in a device that can be taken everywhere",
                    CategoryID = 1,
                    Price = 54.99m,
                    Image= "dragon-touch.jpg"
                },
                new Gadget {
                    Name = "Alldaymall A88X 7",
                    Description = "This Alldaymall tablet featuring the incredible powerful Allwinner Quad Core A33, up to four times faster CPU, ensures faster multitasking speed than ever. With the super-portable size, you get a robust power in a device that can be taken everywhere",
                    CategoryID = 1,
                    Price = 47.99m,
                    Image= "Alldaymall.jpg"
                },
                new Gadget {
                    Name = "ASUS MeMO",
                    Description = "Pad 7 ME170CX-A1-BK 7-Inch 16GB Tablet. Dual-Core Intel Atom Z2520 1.2GHz CPU",
                    CategoryID = 1,
                    Price = 94.99m,
                    Image= "asus-memo.jpg"
                },
                new Gadget {
                    Name = "ASUS 15.6-Inch",
                    Description = "Latest Generation Intel Dual Core Celeron 2.16 GHz Processor (turbo to 2.41 GHz)",
                    CategoryID = 2,
                    Price = 249.5m,
                    Image = "asus-latest.jpg"
                },
                new Gadget {
                    Name = "HP Pavilion 15-r030wm",
                    Description = "This Certified Refurbished product is manufacturer refurbished, shows limited or no wear, and includes all original accessories plus a 90-day warranty",
                    CategoryID = 2,
                    Price = 299.95m,
                    Image = "hp-pavilion.jpg"
                },
                new Gadget {
                    Name = "Dell Inspiron 15.6-Inch",
                    Description = "Intel Celeron N2830 Processor, 15.6-Inch Screen, Intel HD Graphics",
                    CategoryID = 2,
                    Price = 308.00m,
                    Image = "dell-inspiron.jpg"
                },
                new Gadget {
                    Name = "Acer Aspire E Notebook",
                    Description = "15.6 HD Active Matrix TFT Color LED (1366 x 768) 16:9 CineCrystal Display",
                    CategoryID = 2,
                    Price = 299.95m,
                    Image = "acer-aspire.jpg"
                },
                new Gadget {
                    Name = "HP Stream 13",
                    Description = "Intel Celeron N2840 Processor. 2 GB DDR3L SDRAM, 32 GB Solid-State Drive and 1TB OneDrive Cloud Storage for one year",
                    CategoryID = 2,
                    Price = 202.99m,
                    Image = "hp-stream.jpg"
                },
                new Gadget {
                    Name = "Nokia Lumia 521",
                    Description = "T-Mobile Cell Phone 4G - White. 5MP Camera - Snap creative photos with built-in digital lenses",
                    CategoryID = 3,
                    Price = 63.99m,
                    Image = "nokia-lumia.jpg"
                },
                new Gadget {
                    Name = "HTC Desire 816",
                    Description = "13 MP Rear Facing BSI Camera / 5 MP Front Facing",
                    CategoryID = 3,
                    Price = 177.99m,
                    Image = "htc-desire.jpg"
                },
                new Gadget {
                    Name = "Sanyo Innuendo",
                    Description = "Uniquely designed 3G-enabled messaging phone with side-flipping QWERTY keyboard and external glow-thru OLED dial pad that 'disappears' when not in use",
                    CategoryID = 3,
                    Price = 54.99m,
                    Image = "sanyo-innuendo.jpg"
                },
                new Gadget {
                    Name = "Ulefone N9000",
                    Description = "Unlocked world GSM phone. 3G-850/2100, 2G -850/900/1800/1900",
                    CategoryID = 3,
                    Price = 133.99m,
                    Image = "ulefone.jpg"
                }

            };
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<test-data>
    <test-code>
        <description><![CDATA[
bad, 012
     ]]></description>
        <expected-problems>1</expected-problems>
        <![CDATA[
public class Foo {
  int x = 012;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
OK, hex value
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
  int x = 0xCAFE;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
OK, long value
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
  long x = 0L;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
OK, double value
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
  double d = 0.1;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
OK, double value
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
  float f = 0f;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
bad, 012L
     ]]></description>
        <expected-problems>1</expected-problems>
        <![CDATA[
public class Foo {
  long x = 012L;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
OK, 06 if strict is not set
     ]]></description>
        <expected-problems>0</expected-problems>
        <![CDATA[
public class Foo {
  int x = 06;
}
     ]]>
    </test-code>
    <test-code>
        <description><![CDATA[
BAD, 06 if strict is set
     ]]></description>
        <expected-problems>1</expected-problems>
        <rule-property name="strict">true</rule-property>
        <![CDATA[
public class Foo {
  int x = 06;
}
     ]]>
    </test-code>
</test-data>


text:
using Avalonia;
using Avalonia.Controls.Utils;
using Avalonia.Media;

namespace Avalonia.Controls
{
    /// <summary>
    /// A control which decorates a child with a border and background.
    /// </summary>
    public partial class Border : Decorator
    {
        /// <summary>
        /// Defines the <see cref="Background"/> property.
        /// </summary>
        public static readonly StyledProperty<IBrush> BackgroundProperty =
            AvaloniaProperty.Register<Border, IBrush>(nameof(Background));

        /// <summary>
        /// Defines the <see cref="BorderBrush"/> property.
        /// </summary>
        public static readonly StyledProperty<IBrush> BorderBrushProperty =
            AvaloniaProperty.Register<Border, IBrush>(nameof(BorderBrush));

        /// <summary>
        /// Defines the <see cref="BorderThickness"/> property.
        /// </summary>
        public static readonly StyledProperty<Thickness> BorderThicknessProperty =
            AvaloniaProperty.Register<Border, Thickness>(nameof(BorderThickness));

        /// <summary>
        /// Defines the <see cref="CornerRadius"/> property.
        /// </summary>
        public static readonly StyledProperty<CornerRadius> CornerRadiusProperty =
            AvaloniaProperty.Register<Border, CornerRadius>(nameof(CornerRadius));

        private readonly BorderRenderHelper _borderRenderHelper = new BorderRenderHelper();

        /// <summary>
        /// Initializes static members of the <see cref="Border"/> class.
        /// </summary>
        static Border()
        {
            AffectsRender(BackgroundProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty);
            AffectsMeasure(BorderThicknessProperty);
        }

        /// <summary>
        /// Gets or sets a brush with which to paint the background.
        /// </summary>
        public IBrush Background
        {
            get { return GetValue(BackgroundProperty); }
            set { SetValue(BackgroundProperty, value); }
        }

        /// <summary>
        /// Gets or sets a brush with which to paint the border.
        /// </summary>
        public IBrush BorderBrush
        {
            get { return GetValue(BorderBrushProperty); }
            set { SetValue(BorderBrushProperty, value); }
        }

        /// <summary>
        /// Gets or sets the thickness of the border.
        /// </summary>
        public Thickness BorderThickness
        {
            get { return GetValue(BorderThicknessProperty); }
            set { SetValue(BorderThicknessProperty, value); }
        }

        /// <summary>
        /// Gets or sets the radius of the border rounded corners.
        /// </summary>
        public CornerRadius CornerRadius
        {
            get { return GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }

        /// <summary>
        /// Renders the control.
        /// </summary>
        /// <param name="context">The drawing context.</param>
        public override void Render(DrawingContext context)
        {
            _borderRenderHelper.Render(context, Bounds.Size, BorderThickness, CornerRadius, Background, BorderBrush);
        }

        /// <summary>
        /// Measures the control.
        /// </summary>
        /// <param name="availableSize">The available size.</param>
        /// <returns>The desired size of the control.</returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            return MeasureOverrideImpl(availableSize, Child, Padding, BorderThickness);
        }

        /// <summary>
        /// Arranges the control's child.
        /// </summary>
        /// <param name="finalSize">The size allocated to the control.</param>
        /// <returns>The space taken.</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            if (Child != null)
            {
                var padding = Padding + BorderThickness;
                Child.Arrange(new Rect(finalSize).Deflate(padding));
            }

            _borderRenderHelper.Update(finalSize, BorderThickness, CornerRadius);

            return finalSize;
        }

        internal static Size MeasureOverrideImpl(
            Size availableSize,
            IControl child,
            Thickness padding,
            Thickness borderThickness)
        {
            padding += borderThickness;

            if (child != null)
            {
                child.Measure(availableSize.Deflate(padding));
                return child.DesiredSize.Inflate(padding);
            }

            return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top);
        }
    }
}


text:
package de.mprengemann.intellij.plugin.androidicons.controllers.multi;

import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.images.RefactoringTask;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageInformation;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;

import java.io.File;
import java.util.List;
import java.util.Map;

public interface IMultiImporterController extends IController<MultiImporterObserver> {

    String getTargetRoot();

    void setTargetRoot(File path);

    void addImage(File source, Resolution target);

    RefactoringTask getTask(Project project);

    void addZipImage(File file, Resolution resolution);

    Map<Resolution, List<ImageInformation>> getZipImages();

    void resetZipInformation();

    RefactoringTask getZipTask(Project project, File tempDir);

    void setExportName(String exportName);

    String getExportName();

    File getMostRecentImage();

    void setMostRecentImage(Resolution resolution);

    boolean containsNinePatch();

    Format getFormat();

    void setFormat(Format format);
}


text:
var assert = require('assert')
  , async = require('async')
  , utils = require('../lib/utils')

describe('parseFormat', function() {

  it('should parse string from soxi and return a format', function() {
    var soxiInfos = "Input File     : 'powerpad.wav'\n"
                  + "Channels       : 2\n"
                  + "Sample Rate    : 44100\n"
                  + "Precision      : 16-bit\n"
                  + "Duration       : 00:00:08.41 = 370944 samples = 630.857 CDDA sectors\n"
                  + "File Size      : 1.48M\n"
                  + "Bit Rate       : 1.41M\n"
                  + "Sample Encoding: 16-bit Signed Integer PCM\n"
      , format = utils.parseFormat(soxiInfos)
    assert.deepEqual(Object.keys(format).sort(), ['bitDepth', 'numberOfChannels', 'sampleRate'].sort())
    assert.equal(format.numberOfChannels, 2)
    assert.equal(format.sampleRate, 44100)
    assert.equal(format.bitDepth, 16)
  })

})

describe('getFileFormat', function() {

  it('should get the format of an audio file that exists', function(done) {
    utils.getFileFormat(__dirname + '/sounds/powerpad.wav', function(err, format) {
      assert.ok(!err)
      assert.deepEqual(Object.keys(format).sort(), ['bitDepth', 'numberOfChannels', 'sampleRate'].sort())
      assert.equal(format.numberOfChannels, 2)
      assert.equal(format.sampleRate, 44100)
      assert.equal(format.bitDepth, 16)
      done()
    })
  })

  it('should return an error if the file doesn\'t exist', function(done) {
    async.series([
      function(next) {
        utils.getFileFormat(__dirname + '/sounds/wotwotwot.wav', function(err, format) {
          assert.ok(err)
          assert.ok(!format)
          next()
        })
      },
      function(next) {
        utils.getFileFormat('wotwotwot', function(err, format) {
          assert.ok(err)
          assert.ok(!format)
          done()
        })
      }
    ])
  })

  it('should return an error if the file isn\'t a soundfile', function(done) {
    utils.getFileFormat(__filename, function(err, format) {
      assert.ok(err)
      assert.ok(!format)
      done()
    })
  })

})


text:
<!doctype html>

  <title>Chromium Buildbot Monitor Options</title>

Options for Chromium Buildbot Monitor

    Use desktop notifications:
    <input id="notifications" type="checkbox">

    Username for try job monitoring:
    <input id="try-job-username" type="text">


text:
<!DOCTYPE html>

		<title>Unicorn Admin</title>
		<meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="stylesheet" href="css/bootstrap.min.css" />
		<link rel="stylesheet" href="css/bootstrap-responsive.min.css" />
        <link rel="stylesheet" href="css/colorpicker.css" />
        <link rel="stylesheet" href="css/datepicker.css" />
		<link rel="stylesheet" href="css/uniform.css" />
		<link rel="stylesheet" href="css/select2.css" />
		<link rel="stylesheet" href="css/unicorn.main.css" />
		<link rel="stylesheet" href="css/unicorn.grey.css" class="skin-color" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Unicorn Admin

			<input type="text" placeholder="Search here..." /><button type="submit" class="tip-right" title="Search"></button>

 Profile

 Messages 5

new message

inbox

outbox

trash

 Settings

 Logout

			 Common Elements

 Dashboard

					 Form elements 3

Common elements

Validation

Wizard

 Buttons & icons

 Interface elements

 Tables

 Grid Layout

					 Sample pages 4

Invoice

Support chat

Calendar

Gallery

					 Charts & graphs

					 Widgets

			Style:

Common Form Elements

					5

				 Home
				Form elements
				Common elements

Text inputs

								<form action="#" method="get" class="form-horizontal" />

										Normal text input

											<input type="text" />

										Password input

											<input type="password" />

										Input with description

											<input type="text" />
											This is a description

										Input with placeholder

											<input type="text" placeholder="This is a placeholder..." />

										Normal textarea

											<textarea></textarea>

										<button type="submit" class="btn btn-primary">Save</button>

								</form>

Rest of elements...

								<form action="#" method="get" class="form-horizontal" />

										Select input

											<select>
												<option />First option
												<option />Second option
												<option />Third option
												<option />Fourth option
												<option />Fifth option
												<option />Sixth option
												<option />Seventh option
												<option />Eighth option
											</select>

										Multiple Select input

											<select multiple="">
												<option />First option
												<option selected="" />Second option
												<option />Third option
												<option />Fourth option
												<option />Fifth option
												<option />Sixth option
												<option />Seventh option
												<option />Eighth option
											</select>

                                        Color picker (hex)

                                            <input type="text" data-color="#000000" value="#000000" class="colorpicker input-small" />

                                        Color picker (rgba)

                                            <input type="text" data-color="rgba(244,202,56,0.5)" value="rgba(244,202,56,0.5)" data-color-format="rgba" class="colorpicker" />

                                        Date picker

                                            <input type="text" data-date="12-02-2012" data-date-format="dd-mm-yyyy" value="12-02-2012" class="datepicker" />

										Radio inputs

											<input type="radio" name="radios" /> First One
											<input type="radio" name="radios" /> Second One
											<input type="radio" name="radios" /> Third One

										Checkboxes

											<input type="checkbox" name="radios" /> First One
											<input type="checkbox" name="radios" /> Second One
											<input type="checkbox" name="radios" /> Third One

										File upload input

											<input type="file" />

								</form>

						2012 © Unicorn Admin. Brought to you by diablo9983


text:
package protos

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

type BuildResult_StatusCode int32

const (
	BuildResult_UNDEFINED BuildResult_StatusCode = 0
	BuildResult_SUCCESS   BuildResult_StatusCode = 1
	BuildResult_FAILURE   BuildResult_StatusCode = 2
)

var BuildResult_StatusCode_name = map[int32]string{
	0: "UNDEFINED",
	1: "SUCCESS",
	2: "FAILURE",
}
var BuildResult_StatusCode_value = map[string]int32{
	"UNDEFINED": 0,
	"SUCCESS":   1,
	"FAILURE":   2,
}

func (x BuildResult_StatusCode) String() string {
	return proto.EnumName(BuildResult_StatusCode_name, int32(x))
}

// Secret is a temporary object to establish security with the Devops.
// A better solution using certificate will be introduced later
type Secret struct {
	EnrollId     string `protobuf:"bytes,1,opt,name=enrollId" json:"enrollId,omitempty"`
	EnrollSecret string `protobuf:"bytes,2,opt,name=enrollSecret" json:"enrollSecret,omitempty"`
}

func (m *Secret) Reset()         { *m = Secret{} }
func (m *Secret) String() string { return proto.CompactTextString(m) }
func (*Secret) ProtoMessage()    {}

type SigmaInput struct {
	Secret   *Secret `protobuf:"bytes,1,opt,name=secret" json:"secret,omitempty"`
	AppTCert []byte  `protobuf:"bytes,2,opt,name=appTCert,proto3" json:"appTCert,omitempty"`
	Data     []byte  `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
}

func (m *SigmaInput) Reset()         { *m = SigmaInput{} }
func (m *SigmaInput) String() string { return proto.CompactTextString(m) }
func (*SigmaInput) ProtoMessage()    {}

func (m *SigmaInput) GetSecret() *Secret {
	if m != nil {
		return m.Secret
	}
	return nil
}

type ExecuteWithBinding struct {
	ChaincodeInvocationSpec *ChaincodeInvocationSpec `protobuf:"bytes,1,opt,name=chaincodeInvocationSpec" json:"chaincodeInvocationSpec,omitempty"`
	Binding                 []byte                   `protobuf:"bytes,2,opt,name=binding,proto3" json:"binding,omitempty"`
}

func (m *ExecuteWithBinding) Reset()         { *m = ExecuteWithBinding{} }
func (m *ExecuteWithBinding) String() string { return proto.CompactTextString(m) }
func (*ExecuteWithBinding) ProtoMessage()    {}

func (m *ExecuteWithBinding) GetChaincodeInvocationSpec() *ChaincodeInvocationSpec {
	if m != nil {
		return m.ChaincodeInvocationSpec
	}
	return nil
}

type SigmaOutput struct {
	Tcert        []byte `protobuf:"bytes,1,opt,name=tcert,proto3" json:"tcert,omitempty"`
	Sigma        []byte `protobuf:"bytes,2,opt,name=sigma,proto3" json:"sigma,omitempty"`
	Asn1Encoding []byte `protobuf:"bytes,3,opt,name=asn1Encoding,proto3" json:"asn1Encoding,omitempty"`
}

func (m *SigmaOutput) Reset()         { *m = SigmaOutput{} }
func (m *SigmaOutput) String() string { return proto.CompactTextString(m) }
func (*SigmaOutput) ProtoMessage()    {}

type BuildResult struct {
	Status         BuildResult_StatusCode   `protobuf:"varint,1,opt,name=status,enum=protos.BuildResult_StatusCode" json:"status,omitempty"`
	Msg            string                   `protobuf:"bytes,2,opt,name=msg" json:"msg,omitempty"`
	DeploymentSpec *ChaincodeDeploymentSpec `protobuf:"bytes,3,opt,name=deploymentSpec" json:"deploymentSpec,omitempty"`
}

func (m *BuildResult) Reset()         { *m = BuildResult{} }
func (m *BuildResult) String() string { return proto.CompactTextString(m) }
func (*BuildResult) ProtoMessage()    {}

func (m *BuildResult) GetDeploymentSpec() *ChaincodeDeploymentSpec {
	if m != nil {
		return m.DeploymentSpec
	}
	return nil
}

type TransactionRequest struct {
	TransactionUuid string `protobuf:"bytes,1,opt,name=transactionUuid" json:"transactionUuid,omitempty"`
}

func (m *TransactionRequest) Reset()         { *m = TransactionRequest{} }
func (m *TransactionRequest) String() string { return proto.CompactTextString(m) }
func (*TransactionRequest) ProtoMessage()    {}

func init() {
	proto.RegisterEnum("protos.BuildResult_StatusCode", BuildResult_StatusCode_name, BuildResult_StatusCode_value)
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// Client API for Devops service

type DevopsClient interface {
	// Log in - passed Secret object and returns Response object, where
	// msg is the security context to be used in subsequent invocations
	Login(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error)
	// Build the chaincode package.
	Build(ctx context.Context, in *ChaincodeSpec, opts ...grpc.CallOption) (*ChaincodeDeploymentSpec, error)
	// Deploy the chaincode package to the chain.
	Deploy(ctx context.Context, in *ChaincodeSpec, opts ...grpc.CallOption) (*ChaincodeDeploymentSpec, error)
	// Invoke chaincode.
	Invoke(ctx context.Context, in *ChaincodeInvocationSpec, opts ...grpc.CallOption) (*Response, error)
	// Invoke chaincode.
	Query(ctx context.Context, in *ChaincodeInvocationSpec, opts ...grpc.CallOption) (*Response, error)
	// Request a TransactionResult.  The Response.Msg will contain the TransactionResult if successfully found the transaction in the chain.
	GetTransactionResult(ctx context.Context, in *TransactionRequest, opts ...grpc.CallOption) (*Response, error)
	// Retrieve a TCert.
	EXP_GetApplicationTCert(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error)
	// Prepare for performing a TX, which will return a binding that can later be used to sign and then execute a transaction.
	EXP_PrepareForTx(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error)
	// Prepare for performing a TX, which will return a binding that can later be used to sign and then execute a transaction.
	EXP_ProduceSigma(ctx context.Context, in *SigmaInput, opts ...grpc.CallOption) (*Response, error)
	// Execute a transaction with a specific binding
	EXP_ExecuteWithBinding(ctx context.Context, in *ExecuteWithBinding, opts ...grpc.CallOption) (*Response, error)
}

type devopsClient struct {
	cc *grpc.ClientConn
}

func NewDevopsClient(cc *grpc.ClientConn) DevopsClient {
	return &devopsClient{cc}
}

func (c *devopsClient) Login(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/Login", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) Build(ctx context.Context, in *ChaincodeSpec, opts ...grpc.CallOption) (*ChaincodeDeploymentSpec, error) {
	out := new(ChaincodeDeploymentSpec)
	err := grpc.Invoke(ctx, "/protos.Devops/Build", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) Deploy(ctx context.Context, in *ChaincodeSpec, opts ...grpc.CallOption) (*ChaincodeDeploymentSpec, error) {
	out := new(ChaincodeDeploymentSpec)
	err := grpc.Invoke(ctx, "/protos.Devops/Deploy", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) Invoke(ctx context.Context, in *ChaincodeInvocationSpec, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/Invoke", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) Query(ctx context.Context, in *ChaincodeInvocationSpec, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/Query", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) GetTransactionResult(ctx context.Context, in *TransactionRequest, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/GetTransactionResult", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) EXP_GetApplicationTCert(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/EXP_GetApplicationTCert", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) EXP_PrepareForTx(ctx context.Context, in *Secret, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/EXP_PrepareForTx", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) EXP_ProduceSigma(ctx context.Context, in *SigmaInput, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/EXP_ProduceSigma", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *devopsClient) EXP_ExecuteWithBinding(ctx context.Context, in *ExecuteWithBinding, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/protos.Devops/EXP_ExecuteWithBinding", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for Devops service

type DevopsServer interface {
	// Log in - passed Secret object and returns Response object, where
	// msg is the security context to be used in subsequent invocations
	Login(context.Context, *Secret) (*Response, error)
	// Build the chaincode package.
	Build(context.Context, *ChaincodeSpec) (*ChaincodeDeploymentSpec, error)
	// Deploy the chaincode package to the chain.
	Deploy(context.Context, *ChaincodeSpec) (*ChaincodeDeploymentSpec, error)
	// Invoke chaincode.
	Invoke(context.Context, *ChaincodeInvocationSpec) (*Response, error)
	// Invoke chaincode.
	Query(context.Context, *ChaincodeInvocationSpec) (*Response, error)
	// Request a TransactionResult.  The Response.Msg will contain the TransactionResult if successfully found the transaction in the chain.
	GetTransactionResult(context.Context, *TransactionRequest) (*Response, error)
	// Retrieve a TCert.
	EXP_GetApplicationTCert(context.Context, *Secret) (*Response, error)
	// Prepare for performing a TX, which will return a binding that can later be used to sign and then execute a transaction.
	EXP_PrepareForTx(context.Context, *Secret) (*Response, error)
	// Prepare for performing a TX, which will return a binding that can later be used to sign and then execute a transaction.
	EXP_ProduceSigma(context.Context, *SigmaInput) (*Response, error)
	// Execute a transaction with a specific binding
	EXP_ExecuteWithBinding(context.Context, *ExecuteWithBinding) (*Response, error)
}

func RegisterDevopsServer(s *grpc.Server, srv DevopsServer) {
	s.RegisterService(&_Devops_serviceDesc, srv)
}

func _Devops_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(Secret)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).Login(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_Build_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(ChaincodeSpec)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).Build(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_Deploy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(ChaincodeSpec)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).Deploy(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_Invoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(ChaincodeInvocationSpec)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).Invoke(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(ChaincodeInvocationSpec)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).Query(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_GetTransactionResult_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(TransactionRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).GetTransactionResult(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_EXP_GetApplicationTCert_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(Secret)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).EXP_GetApplicationTCert(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_EXP_PrepareForTx_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(Secret)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).EXP_PrepareForTx(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_EXP_ProduceSigma_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(SigmaInput)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).EXP_ProduceSigma(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Devops_EXP_ExecuteWithBinding_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(ExecuteWithBinding)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(DevopsServer).EXP_ExecuteWithBinding(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

var _Devops_serviceDesc = grpc.ServiceDesc{
	ServiceName: "protos.Devops",
	HandlerType: (*DevopsServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Login",
			Handler:    _Devops_Login_Handler,
		},
		{
			MethodName: "Build",
			Handler:    _Devops_Build_Handler,
		},
		{
			MethodName: "Deploy",
			Handler:    _Devops_Deploy_Handler,
		},
		{
			MethodName: "Invoke",
			Handler:    _Devops_Invoke_Handler,
		},
		{
			MethodName: "Query",
			Handler:    _Devops_Query_Handler,
		},
		{
			MethodName: "GetTransactionResult",
			Handler:    _Devops_GetTransactionResult_Handler,
		},
		{
			MethodName: "EXP_GetApplicationTCert",
			Handler:    _Devops_EXP_GetApplicationTCert_Handler,
		},
		{
			MethodName: "EXP_PrepareForTx",
			Handler:    _Devops_EXP_PrepareForTx_Handler,
		},
		{
			MethodName: "EXP_ProduceSigma",
			Handler:    _Devops_EXP_ProduceSigma_Handler,
		},
		{
			MethodName: "EXP_ExecuteWithBinding",
			Handler:    _Devops_EXP_ExecuteWithBinding_Handler,
		},
	},
	Streams: []grpc.StreamDesc{},
}


text:
using namespace Eigen;
using namespace std;

int main(int, char**)
{
  cout.precision(3);
  Matrix4i m = Matrix4i::Random();
m.row(1).setZero();
cout << m << endl;

  return 0;
}


text:
using Google.Apis.Auth.OAuth2.Requests;
using System;
using Xunit;

namespace Google.Apis.Auth.Tests.OAuth2.Requests
{
    /// <summary>
    /// Tests for <seealso cref="Google.Apis.Auth.OAuth2.Requests.AuthorizationCodeRequestUrl"/>.
    /// It tests that the constructor sets the default values and the building URI method.
    /// </summary>
    public class AuthorizationCodeRequestUrlTests
    {
        private readonly Uri AuthorizationCodeUrl = new Uri("http://www.authorization-server.com");

        [Fact]
        public void TestConstructor()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl);
            Assert.Equal(AuthorizationCodeUrl, request.AuthorizationServerUrl);
            Assert.Null(request.ClientId);
            Assert.Null(request.RedirectUri);
            Assert.Equal("code", request.ResponseType);
            Assert.Null(request.Scope);
            Assert.Null(request.State);
        }

        [Fact]
        public void TestBuild_DefaultValues()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl);
            var uri = request.Build();
            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code"), uri);
        }

        [Fact]
        public void TestBuild()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl)
            {
                ClientId = "100",
                RedirectUri = "200",
                Scope = "SCOPE",
                State = "state",
            };
            var uri = request.Build();
            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code&client_id=100&redirect_uri=200&scope=SCOPE&state=state"), uri);
        }

        [Fact]
        public void TestBuild_EscapeValues()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl)
            {
                ClientId = "pa$$word",
                RedirectUri = "???",
                Scope = "SC@PE",
                State = "!",
            };
            var uri = request.Build();
            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code&client_id=pa%24%24word&redirect_uri=%3F%3F%3F&scope=SC%40PE&state=%21"), uri);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Igor.Annotations;

namespace Igor.Models
{
    [UsedImplicitly]
    public class AppSettingsDto
    {
        public IDictionary<string,string> Settings { get; set; }
    }
}


text:
<?php

namespace nglasl\mediawesome;

use SilverStripe\Forms\DateField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\ORM\DataObject;

/**
 *	This is essentially the versioned join between `MediaPage` and `MediaAttribute`, since each page will have different content for an attribute.
 *	@author Nathan Glasl <nathan@symbiote.com.au>
 */

class MediaPageAttribute extends DataObject {

	private static $table_name = 'MediaPageAttribute';

	private static $db = array(
		'Content' => 'HTMLText'
	);

	private static $has_one = array(
		'MediaPage' => MediaPage::class,
		'MediaAttribute' => MediaAttribute::class
	);

	private static $summary_fields = array(
		'Title',
		'Content'
	);

	public function canDelete($member = null) {

		return false;
	}

	public function getTitle() {

		return $this->MediaAttribute()->Title;
	}

	public function getCMSFields() {

		$fields = parent::getCMSFields();
		$fields->removeByName('MediaPageID');
		$fields->removeByName('MediaAttributeID');

		// Determine the field type.

		if(strrpos($this->getTitle(), 'Date')) {

			// The user expects this to be a date attribute.

			$fields->replaceField('Content', DateField::create(
				'Content'
			));
		}
		else {

			// This is most commonly a simple attribute, so a HTML field only complicates things for the user.

			$fields->replaceField('Content', TextareaField::create(
				'Content'
			));
		}

		// Allow extension customisation.

		$this->extend('updateMediaPageAttributeCMSFields', $fields);
		return $fields;
	}

}


text:
* Anzahl Punkte: 12
* Kalkulierte Zeit: 30 Minuten

## Einleitung

Sie haben die Aufgabe, eine bestehende Node.js-Anwendung, die in JavaScript geschrieben ist, auf TypeScript umzustellen. Die Anwendung implementiert eine einfache RESTful Web API **mit dem [Restify](http://restify.com/) Framework**, die die Verwaltung von Kunden ermöglicht.

Die Node.js-Anwendung, die umzustellen ist, finden Sie im Ordner [start](start).

Konzentrieren Sie sich bei der Aufgabe auf die **Projektkonfiguration** und das **Übersetzen von JavaScript in TypeScript**. Sie brauchen in dieser Übung **keine neuen Programmfunktionen hinzuzufügen**!

## Anforderungen

Beachten Sie beim Lösen der Aufgabe folgende Anforderungen.

### Pflichtaufgaben (6 Punkte)

Pflichtaufgaben, die alle korrekt gelöst werden müssen, um Punkte für das Beispiel zu erhalten:

* Alle für das Projekt notwendigen Node-Packages und *TypeScript Type Definition*-Packages müssen lokal installert sein. Außer Node.js und NPM dürfen keine global installierten Softwarekomponenten vorausgesetzt werden.
* Bei der Installation der Node-Packages ist unbedingt darauf zu achten, dass korrekt zwischen *dependencies* und *devDependencies* unterschieden wird.
* Das Projekt muss in der Kommandozeile mit dem Kommando `npm run build` gebaut werden können.
* [*server.js*](start/server.js) und [*customers.js*](start/customers.js) werden in TypeScript übersetzt, kompilieren ohne Fehler und können ausgeführt werden.
* Alle `require` Statemens wurden in `import` Statements umgebaut.
* Das Projekt muss in der Kommandozeile mit dem Kommando `npm start` gestartet werden können.
* Der TypeScript-Compiler muss in der TypeScript-Konfigurationsdatei so konfiguriert werden, dass als *ECMAScript target version* `ES2015` verwendet wird.

### Optionale Aufgaben

Optionale Aufgaben, um die volle Punktzahl für das Beispiel zu erhalten:

* 2 Punkte: Sie haben ein Interface `ICustomer` angelegt und verwendet, das einen Kunden repräsentiert. Das Interface wird in beiden TypeScript-Dateien verwendet.
* 1 Punkt: Der TypeScript-Compiler muss in der Kommandozeile mit dem Kommando `npm run watch` im [*watch mode*](https://www.typescriptlang.org/docs/handbook/compiler-options.html) gestartet werden können.
* 2 Punkte: Dateistruktur
  * Alle Konfigurationsdateien müssen sich im Wurzelverzeichnis des Projekts befinden.
  * Alle TypeScript-Quellcodedateien müssen sich im Verzeichnis *src* befinden.
  * Die beim Kompilieren mit `npm run build` entstehenden JavaScript-Dateien müssen im Verzeichnis *dist* landen.
* 1 Punkt: Das Projekt muss in der Kommandozeile mit dem Kommando `npm run clean` "aufgeräumt" werden können. "Aufräumen" heißt, dass alle beim Kompilieren des Programms entstandenen JavaScript-Dateien gelöscht werden (z.B. *dist* Ordner wird gelöscht).


text:
DROP TRIGGER cascade_change_qu_id_stock;
CREATE TRIGGER cascade_change_qu_id_stock AFTER UPDATE ON products
BEGIN
	UPDATE recipes_pos
	SET qu_id = (SELECT qu_id_stock FROM products WHERE id = NEW.id)
	WHERE product_id IN (SELECT id FROM products WHERE id = NEW.id)
		AND only_check_single_unit_in_stock = 0;
END;

UPDATE recipes_pos
SET qu_id = (SELECT qu_id_stock FROM products WHERE id = recipes_pos.product_id)
WHERE only_check_single_unit_in_stock = 0;

DROP VIEW recipes_fulfillment;
CREATE VIEW recipes_fulfillment
AS
SELECT
	r.id AS recipe_id,
	rp.id AS recipe_pos_id,
	rp.product_id AS product_id,
	rp.amount AS recipe_amount,
	IFNULL(sc.amount, 0) AS stock_amount,
	CASE WHEN IFNULL(sc.amount, 0) >= CASE WHEN rp.only_check_single_unit_in_stock = 1 THEN 1 ELSE IFNULL(rp.amount, 0) END THEN 1 ELSE 0 END AS need_fulfilled,
	CASE WHEN IFNULL(sc.amount, 0) - CASE WHEN rp.only_check_single_unit_in_stock = 1 THEN 1 ELSE IFNULL(rp.amount, 0) END < 0 THEN ABS(IFNULL(sc.amount, 0) - CASE WHEN rp.only_check_single_unit_in_stock = 1 THEN 1 ELSE IFNULL(rp.amount, 0) END) ELSE 0 END AS missing_amount,
	IFNULL(sl.amount, 0) * p.qu_factor_purchase_to_stock AS amount_on_shopping_list,
	CASE WHEN IFNULL(sc.amount, 0) + (IFNULL(sl.amount, 0) * p.qu_factor_purchase_to_stock) >= CASE WHEN rp.only_check_single_unit_in_stock = 1 THEN 1 ELSE IFNULL(rp.amount, 0) END THEN 1 ELSE 0 END AS need_fulfilled_with_shopping_list,
	rp.qu_id
FROM recipes r
JOIN recipes_pos rp
	ON r.id = rp.recipe_id
JOIN products p
	ON rp.product_id = p.id
LEFT JOIN (
	SELECT product_id, SUM(amount + amount_autoadded) AS amount
	FROM shopping_list
	GROUP BY product_id) sl
	ON rp.product_id = sl.product_id
LEFT JOIN stock_current sc
	ON rp.product_id = sc.product_id
WHERE rp.not_check_stock_fulfillment = 0

UNION

-- Just add all recipe positions which should not be checked against stock with fulfilled need

SELECT
	r.id AS recipe_id,
	rp.id AS recipe_pos_id,
	rp.product_id AS product_id,
	rp.amount AS recipe_amount,
	IFNULL(sc.amount, 0) AS stock_amount,
	1 AS need_fulfilled,
	0 AS missing_amount,
	IFNULL(sl.amount, 0) * p.qu_factor_purchase_to_stock AS amount_on_shopping_list,
	1 AS need_fulfilled_with_shopping_list,
	rp.qu_id
FROM recipes r
JOIN recipes_pos rp
	ON r.id = rp.recipe_id
JOIN products p
	ON rp.product_id = p.id
LEFT JOIN (
	SELECT product_id, SUM(amount + amount_autoadded) AS amount
	FROM shopping_list
	GROUP BY product_id) sl
	ON rp.product_id = sl.product_id
LEFT JOIN stock_current sc
	ON rp.product_id = sc.product_id
WHERE rp.not_check_stock_fulfillment = 1;


text:
using namespace ProjectExplorer;

QtcGtest::Internal::CustomRunConfiguration::CustomRunConfiguration(LocalApplicationRunConfiguration *source) :
  LocalApplicationRunConfiguration (source->target (), source)
{
  Q_ASSERT (source != NULL);
  executable_ = source->executable ();
  runMode_ = source->runMode ();
  workingDirectory_ = source->workingDirectory ();
  commandLineArguments_ = source->commandLineArguments ();
  EnvironmentAspect *aspect = source->extraAspect<EnvironmentAspect>();
  if (aspect != NULL) {
    environment_ = aspect->environment ();
  }
}

QWidget *QtcGtest::Internal::CustomRunConfiguration::createConfigurationWidget()
{
  return NULL;
}

QString QtcGtest::Internal::CustomRunConfiguration::executable() const
{
  return executable_;
}

ApplicationLauncher::Mode QtcGtest::Internal::CustomRunConfiguration::runMode() const
{
  return runMode_;
}

QString QtcGtest::Internal::CustomRunConfiguration::workingDirectory() const
{
  return workingDirectory_;
}

QString QtcGtest::Internal::CustomRunConfiguration::commandLineArguments() const
{
  return commandLineArguments_;
}
void QtcGtest::Internal::CustomRunConfiguration::addToBaseEnvironment(Utils::Environment &env) const
{
  env = environment_;
}

void QtcGtest::Internal::CustomRunConfiguration::setArguments(const QString &arguments)
{
  commandLineArguments_ = arguments;
}


text:
package com.blazeloader.event.handlers.client;

import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockModelShapes;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.RayTraceResult;

import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import com.blazeloader.api.block.ApiBlock;
import com.blazeloader.api.client.render.BlockRenderRegistry;
import com.blazeloader.api.entity.IMousePickHandler;
import com.blazeloader.event.handlers.EventHandler;
import com.blazeloader.event.mixin.Mix;

/**
 * Event handler for events that are not passed to mods, but rather to BL itself
 */
public class InternalEventHandlerClient {
	public static void eventDispatchKeypresses(Minecraft sender) {
		if (EventHandler.inventoryEventHandlers.size() > 0) {
			if (sender == null) return;
			if (sender.player != null && !sender.player.isSpectator()) {
				if (sender.currentScreen == null || sender.currentScreen.allowUserInput) {
					for (int i = 0; i < sender.gameSettings.keyBindsHotbar.length; i++) {
			            if (sender.gameSettings.keyBindsHotbar[i].isPressed()) {
		                    if (EventHandler.inventoryEventHandlers.all().onSlotSelectionChanged(sender.player, sender.player.inventory.getCurrentItem(), i)) {
		                    	KeyBinding.onTick(sender.gameSettings.keyBindsHotbar[i].getKeyCode());
		                    }
		                    break;
		                }
		            }
		        }
			}
		}
	}

    public static void eventGetTexture(BlockModelShapes sender, CallbackInfoReturnable<TextureAtlasSprite> info, IBlockState state) {
    	Block block = state.getBlock();
        IBakedModel model = sender.getModelForState(state);
        ModelManager manager = sender.getModelManager();
        if (model == null || model == manager.getMissingModel()) {
        	String texture = BlockRenderRegistry.lookupTexture(block);
        	if (texture != null) info.setReturnValue(manager.getTextureMap().getAtlasSprite(texture));
        }
    }

    public static void eventMiddleClickMouse(Minecraft sender, CallbackInfo info) {
    	IMousePickHandler handler = null;
    	boolean creative = sender.player.capabilities.isCreativeMode;

    	if (sender.objectMouseOver != null) {
    		if (sender.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
	    		Entity entity = sender.objectMouseOver.entityHit;
	    		if (entity instanceof IMousePickHandler) {
	    			handler = (IMousePickHandler)entity;
	    		}
    		} else if (creative && sender.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) {
    			TileEntity tileentity = sender.world.getTileEntity(sender.objectMouseOver.getBlockPos());
    			if (tileentity != null && tileentity instanceof IMousePickHandler) {
    				handler = (IMousePickHandler)tileentity;
    			}
    		}
    	}

    	if (handler != null) {
	    	ItemStack stack = handler.onPlayerMiddleClick(sender.player);
	    	if (stack != null && !stack.isEmpty()) {
				InventoryPlayer inventory = sender.player.inventory;

				int i = inventory.getSlotFor(stack);

				if (creative) {
					inventory.setPickedItemStack(stack);
	                sender.playerController.sendSlotPacket(sender.player.getHeldItem(EnumHand.MAIN_HAND), 36 + inventory.currentItem);
	            } else if (i > -1) {
                    if (InventoryPlayer.isHotbar(i)) {
                        inventory.currentItem = i;
                    } else {
                        sender.playerController.pickItem(i);
                    }
                }
				info.cancel();
			}
    	}
    }

    public static void eventRenderByItem(CallbackInfo info, ItemStack itemStack) {
    	Mix.intercept(BlockRenderRegistry.tryRenderTileEntity(itemStack), info);
    }

    public static void eventRenderItem(CallbackInfo info, ItemStack stack, IBakedModel model) {
    	Block block = ApiBlock.getBlockByItem(stack.getItem());
        if (BlockRenderRegistry.isTileEntityRendered(block)) {
        	GlStateManager.pushMatrix();
            GlStateManager.scale(0.5F, 0.5F, 0.5F);
            GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
            GlStateManager.translate(-0.5F, -0.5F, -0.5F);
            GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
            GlStateManager.enableRescaleNormal();
            Mix.intercept(BlockRenderRegistry.doRenderTileEntity(block, stack), info);
            GlStateManager.popMatrix();
        }
    }
}


text:
package com.github.zulhilmizainuddin.httprequest;

import java.util.HashMap;
import java.util.Map;

final class StreamConverterFactory {
    private static final Map<String, Class<? extends StreamConverter>> encodingTypeMap = new HashMap<>();

    static {
        encodingTypeMap.put("", StringStreamConverter.class);
        encodingTypeMap.put("gzip", GzipStreamConverter.class);
        encodingTypeMap.put("deflate", DeflateStreamConverter.class);
    }

    public static StreamConverter getConverter(String encodingType) {
        if (encodingType == null)
            encodingType = "";

        StreamConverter streamConverter = null;

        try {
            streamConverter = encodingTypeMap.get(encodingType.toLowerCase()).newInstance();
        }
        catch (InstantiationException ex) {}
        catch (IllegalAccessException ex) {}

        return streamConverter;
    }
}


text:
package org.apache.myfaces.view.facelets.tag.jstl.core;

import java.io.Serializable;
import java.util.Map;

import javax.el.ELContext;
import javax.el.ValueExpression;

/**
 * @author Jacob Hookom
 * @version $Id: MappedValueExpression.java 1187701 2011-10-22 12:21:54Z bommel $
 */
public final class MappedValueExpression extends ValueExpression
{
    private final static class Entry implements Map.Entry, Serializable
    {
        private final Map src;
        private final Object key;

        public Entry(Map src, Object key)
        {
            this.src = src;
            this.key = key;
        }

        public Object getKey()
        {
            return key;
        }

        public Object getValue()
        {
            return src.get(key);
        }

        public Object setValue(Object value)
        {
            return src.put(key, value);
        }

    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final Object key;

    private final ValueExpression orig;

    /**
     *
     */
    public MappedValueExpression(ValueExpression orig, Map.Entry entry)
    {
        this.orig = orig;
        this.key = entry.getKey();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
     */
    public Object getValue(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(true);
            return new Entry((Map) base, key);

        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#setValue(javax.el.ELContext, java.lang.Object)
     */
    public void setValue(ELContext context, Object value)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            context.getELResolver().setValue(context, base, key, value);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
     */
    public boolean isReadOnly(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            return context.getELResolver().isReadOnly(context, base, key);
        }
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getType(javax.el.ELContext)
     */
    public Class getType(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            return context.getELResolver().getType(context, base, key);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getExpectedType()
     */
    public Class getExpectedType()
    {
        return Object.class;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#getExpressionString()
     */
    public String getExpressionString()
    {
        return this.orig.getExpressionString();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#equals(java.lang.Object)
     */
    public boolean equals(Object obj)
    {
        return this.orig.equals(obj);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#hashCode()
     */
    public int hashCode()
    {
        // TODO Auto-generated method stub
        return 0;
    }

    /*
     * (non-Javadoc)eturn new Map.Entry<K, V>
     *
     * @see javax.el.Expression#isLiteralText()
     */
    public boolean isLiteralText()
    {
        // TODO Auto-generated method stub
        return false;
    }

}


text:
package org.gradle.api.internal.artifacts.repositories.resolver;

import org.gradle.api.internal.artifacts.metadata.IvyArtifactName;
import org.gradle.internal.resource.ResourceException;

public interface VersionPatternVisitor {
    /**
     *
Adds those versions available for the given pattern.

     *
     * If no versions are listed with the given pattern, then no versions are added.
     *
     * @throws ResourceException If information for versions cannot be loaded.
     */
    void visit(ResourcePattern pattern, IvyArtifactName artifact) throws ResourceException;
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	player = mongoose.model('player'),
	_ = require('lodash');

/**
 * Create an player
 */
exports.create = function(req, res) {
	var player = new player(req.body.user);

	player.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(player);
		}
	});
};

/**
 * Show the current player
 */
exports.read = function(req, res) {
	res.json(req.player);
};

/**
 * List of players
 */
exports.list = function(req, res) {
	player.find().sort('-created').exec(function(err, players) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(players);
		}
	});
};

/**
 * game middleware
 */
exports.playrByID = function(req, res, next, id) {
	player.findById(id).exec(function(err, player) {
		if (err) return next(err);
		if (!player) return next(new Error('Failed to load player ' + id));
		req.player = player;
		next();
	});
};