text:
namespace Anycmd.Ac.ViewModels
{
    using AppSystemViewModels;
    using ButtonViewModels;
    using Engine;
    using Engine.Ac;
    using Engine.Ac.Dsd;
    using Engine.Ac.Groups;
    using Engine.Ac.Privileges;
    using Engine.Ac.Roles;
    using Engine.Ac.Ssd;
    using Engine.Rdb;
    using EntityTypeViewModels;
    using Exceptions;
    using FunctionViewModels;
    using GroupViewModels;
    using PrivilegeViewModels;
    using RdbViewModels;
    using RoleViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using UIViewViewModels;
    using Util;
    using ViewModel;

    public static class AcDomainExtension
    {
        private static EntityTypeState GetEntityType(this IAcDomain acDomain, Coder code)
        {
            EntityTypeState entityTypeState;
            if (!acDomain.EntityTypeSet.TryGetEntityType(code, out entityTypeState))
            {
                throw new InvalidEntityTypeCodeException(code);
            }
            return entityTypeState;
        }

        #region GetPlistAppSystems
        public static IQueryable<AppSystemTr> GetPlistAppSystems(this IAcDomain acDomain, GetPlistResult requestData)
        {
            EntityTypeState appSystemEntityType = acDomain.GetEntityType(new Coder("Ac", "AppSystem"));
            foreach (var filter in requestData.Filters)
            {
                PropertyState property;
                if (!appSystemEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的AppSystem实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = acDomain.AppSystemSet.Select(a => AppSystemTr.Create(acDomain, a)).AsQueryable();
            foreach (var filter in requestData.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistButtons
        public static IQueryable<ButtonTr> GetPlistButtons(this IAcDomain acDomain, GetPlistResult requestData)
        {
            EntityTypeState buttonEntityType = acDomain.GetEntityType(new Coder("Ac", "Button"));
            foreach (var filter in requestData.Filters)
            {
                PropertyState property;
                if (!buttonEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的Button实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = acDomain.ButtonSet.Select(ButtonTr.Create).AsQueryable();
            foreach (var filter in requestData.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistUIViewButtons
        public static IQueryable<UiViewAssignButtonTr> GetPlistUiViewButtons(this IAcDomain acDomain, GetPlistUiViewButtons requestData)
        {
            if (!requestData.UiViewId.HasValue)
            {
                throw new ValidationException("uiViewID是必须的");
            }
            UiViewState view;
            if (!acDomain.UiViewSet.TryGetUiView(requestData.UiViewId.Value, out view))
            {
                throw new ValidationException("意外的页面标识" + requestData.UiViewId);
            }
            var viewButtons = acDomain.UiViewSet.GetUiViewButtons(view);
            var buttons = acDomain.ButtonSet;
            var data = new List<UiViewAssignButtonTr>();
            foreach (var button in buttons)
            {
                var viewButton = viewButtons.FirstOrDefault(a => a.ButtonId == button.Id && a.UiViewId == view.Id);
                if (requestData.IsAssigned.HasValue)
                {
                    if (requestData.IsAssigned.Value)
                    {
                        if (viewButton == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (viewButton != null)
                        {
                            continue;
                        }
                    }
                }
                DateTime? createOn = null;
                int isEnabled;
                string functionCode = null;
                Guid? functionId = null;
                string functionName = null;
                Guid id;
                bool isAssigned;
                int functionIsEnabled = 0;
                if (viewButton != null)
                {
                    createOn = viewButton.CreateOn;
                    isEnabled = viewButton.IsEnabled;
                    id = viewButton.Id;
                    isAssigned = true;
                    FunctionState function;
                    if (viewButton.FunctionId.HasValue && acDomain.FunctionSet.TryGetFunction(viewButton.FunctionId.Value, out function))
                    {
                        functionCode = function.Code;
                        functionId = function.Id;
                        functionName = function.Description;
                        functionIsEnabled = function.IsEnabled;
                    }
                }
                else
                {
                    id = Guid.NewGuid();
                    isAssigned = false;
                    isEnabled = 0;
                }
                data.Add(new UiViewAssignButtonTr
                {
                    CreateOn = createOn,
                    Id = id,
                    IsAssigned = isAssigned,
                    FunctionIsEnabled = functionIsEnabled,
                    Icon = button.Icon,
                    IsEnabled = isEnabled,
                    Name = button.Name,
                    ButtonId = button.Id,
                    ButtonIsEnabled = button.IsEnabled,
                    Code = button.Code,
                    FunctionCode = functionCode,
                    FunctionId = functionId,
                    FunctionName = functionName,
                    UiViewId = view.Id,
                    SortCode = button.SortCode
                });
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = data.AsQueryable();
            if (!string.IsNullOrEmpty(requestData.key))
            {
                queryable = queryable.Where(a => a.Name.Contains(requestData.key) || a.Code.Contains(requestData.key));
            }
            requestData.Total = queryable.Count();
            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistDatabases
        public static IQueryable<IRDatabase> GetPlistDatabases(this IAcDomain acDomain, GetPlistResult requestModel)
        {
            EntityTypeState entityType = acDomain.GetEntityType(new Coder("Ac", "RDatabase"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!entityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的RDatabase实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.Rdbs.Select(a => a.Database).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistTables
        public static IQueryable<DbTable> GetPlistTables(this IAcDomain acDomain, GetPlistTables requestModel)
        {
            if (!requestModel.DatabaseId.HasValue)
            {
                throw new ValidationException("databaseId为空");
            }
            RdbDescriptor db;
            if (!acDomain.Rdbs.TryDb(requestModel.DatabaseId.Value, out db))
            {
                throw new ValidationException("意外的数据库Id");
            }
            var properties = new HashSet<string>()
            {
                "Id",
                "DatabaseId",
                "CatalogName",
                "SchemaName",
                "Name",
                "Description"
            };
            foreach (var filter in requestModel.Filters)
            {
                if (!properties.Contains(filter.field))
                {
                    throw new ValidationException("意外的DbTable实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = db.DbTables.Values.Select(a => a).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistViews
        public static IQueryable<DbView> GetPlistViews(this IAcDomain acDomain, GetPlistViews requestModel)
        {
            if (!requestModel.DatabaseId.HasValue)
            {
                throw new ValidationException("databaseId为空");
            }
            RdbDescriptor db;
            if (!acDomain.Rdbs.TryDb(requestModel.DatabaseId.Value, out db))
            {
                throw new ValidationException("意外的数据库Id");
            }
            var properties = new HashSet<string>()
            {
                "Id",
                "DatabaseId",
                "CatalogName",
                "SchemaName",
                "Name",
                "Description"
            };
            foreach (var filter in requestModel.Filters)
            {
                if (!properties.Contains(filter.field))
                {
                    throw new ValidationException("意外的DbView实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = db.DbViews.Values.Select(a => a).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistTableColumns
        public static IQueryable<DbTableColumn> GetPlistTableColumns(this IAcDomain acDomain, GetPlistTableColumns requestModel)
        {
            if (!requestModel.DatabaseId.HasValue)
            {
                throw new ValidationException("databaseId为空");
            }
            RdbDescriptor db;
            if (!acDomain.Rdbs.TryDb(requestModel.DatabaseId.Value, out db))
            {
                throw new ValidationException("意外的数据库Id");
            }
            DbTable dbTable;
            if (!db.TryGetDbTable(requestModel.TableId, out dbTable))
            {
                throw new ValidationException("意外的数据库表名" + requestModel.TableName);
            }
            var properties = new HashSet<string>()
            {
                "DatabaseId",
                "Id",
                "CatalogName",
                "DateTimePrecision",
                "DefaultValue",
                "Description",
                "IsIdentity",
                "IsNullable",
                "IsPrimaryKey",
                "IsStoreGenerated",
                "MaxLength",
                "Name",
                "Ordinal",
                "Precision",
                "Scale",
                "SchemaName",
                "TableName",
                "TypeName"
            };
            foreach (var filter in requestModel.Filters)
            {
                if (!properties.Contains(filter.field))
                {
                    throw new ValidationException("意外的DbTableColumn实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            IReadOnlyDictionary<string, DbTableColumn> dbTableColumns;
            if (!acDomain.Rdbs.DbTableColumns.TryGetDbTableColumns(db, dbTable, out dbTableColumns))
            {
                throw new AnycmdException("意外的数据库表列");
            }
            var queryable = dbTableColumns.Values.Select(a => a).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistViewColumns
        public static IQueryable<DbViewColumn> GetPlistViewColumns(this IAcDomain acDomain, GetPlistViewColumns requestModel)
        {
            if (!requestModel.DatabaseId.HasValue)
            {
                throw new ValidationException("databaseId为空");
            }
            RdbDescriptor db;
            if (!acDomain.Rdbs.TryDb(requestModel.DatabaseId.Value, out db))
            {
                throw new ValidationException("意外的数据库Id");
            }
            DbView dbView;
            if (!db.TryGetDbView(requestModel.ViewId, out dbView))
            {
                throw new ValidationException("意外的数据库表名" + requestModel.ViewName);
            }
            var properties = new HashSet<string>()
            {
                "DatabaseId",
                "Id",
                "CatalogName",
                "DateTimePrecision",
                "DefaultValue",
                "Description",
                "IsIdentity",
                "IsNullable",
                "IsPrimaryKey",
                "IsStoreGenerated",
                "MaxLength",
                "Name",
                "Ordinal",
                "Precision",
                "Scale",
                "SchemaName",
                "TableName",
                "TypeName"
            };
            foreach (var filter in requestModel.Filters)
            {
                if (!properties.Contains(filter.field))
                {
                    throw new ValidationException("意外的DbViewColumn实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            IReadOnlyDictionary<string, DbViewColumn> dbViewColumns;
            if (!acDomain.Rdbs.DbViewColumns.TryGetDbViewColumns(db, dbView, out dbViewColumns))
            {
                throw new AnycmdException("意外的数据库视图列");
            }
            var queryable = dbViewColumns.Values.Select(a => a).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistEntityTypes
        public static IQueryable<EntityTypeTr> GetPlistEntityTypes(this IAcDomain acDomain, GetPlistResult requestData)
        {
            EntityTypeState entityTypeEntityType = acDomain.GetEntityType(new Coder("Ac", "EntityType"));
            foreach (var filter in requestData.Filters)
            {
                PropertyState property;
                if (!acDomain.EntityTypeSet.TryGetProperty(entityTypeEntityType, filter.field, out property))
                {
                    throw new ValidationException("意外的EntityType实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = acDomain.EntityTypeSet.Select(EntityTypeTr.Create).AsQueryable();
            foreach (var filter in requestData.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistFunctions
        public static IQueryable<FunctionTr> GetPlistFunctions(this IAcDomain acDomain, GetPlistResult requestData)
        {
            EntityTypeState entityType = acDomain.GetEntityType(new Coder("Ac", "Function"));
            foreach (var filter in requestData.Filters)
            {
                PropertyState property;
                if (!acDomain.EntityTypeSet.TryGetProperty(entityType, filter.field, out property))
                {
                    throw new ValidationException("意外的Function实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = acDomain.FunctionSet.Select(FunctionTr.Create).AsQueryable();
            foreach (var filter in requestData.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistPrivilegeByRoleId
        public static IQueryable<RoleAssignFunctionTr> GetPlistPrivilegeByRoleId(this IAcDomain acDomain, GetPlistFunctionByRoleId requestData)
        {
            AppSystemState appSystem;
            if (!acDomain.AppSystemSet.TryGetAppSystem(requestData.AppSystemId, out appSystem))
            {
                throw new ValidationException("意外的应用系统标识" + requestData.AppSystemId);
            }
            RoleState role;
            if (!acDomain.RoleSet.TryGetRole(requestData.RoleId, out role))
            {
                throw new ValidationException("意外的角色标识" + requestData.RoleId);
            }
            if (requestData.ResourceTypeId.HasValue)
            {
                CatalogState resource;
                if (!acDomain.CatalogSet.TryGetCatalog(requestData.ResourceTypeId.Value, out resource))
                {
                    throw new ValidationException("意外的资源标识" + requestData.ResourceTypeId);
                }
            }
            var roleFunctions = acDomain.PrivilegeSet.Where(a => a.SubjectType == AcElementType.Role && a.ObjectType == AcElementType.Function).ToList();
            var functions = acDomain.FunctionSet.Where(a => a.AppSystem.Id == requestData.AppSystemId && a.IsManaged);
            if (requestData.ResourceTypeId.HasValue)
            {
                functions = functions.Where(a => a.ResourceTypeId == requestData.ResourceTypeId.Value);
            }
            var data = new List<RoleAssignFunctionTr>();
            foreach (var function in functions)
            {
                var roleFunction = roleFunctions.FirstOrDefault(a => a.SubjectInstanceId == role.Id && a.ObjectInstanceId == function.Id);
                if (requestData.IsAssigned.HasValue)
                {
                    if (requestData.IsAssigned.Value)
                    {
                        if (roleFunction == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (roleFunction != null)
                        {
                            continue;
                        }
                    }
                }
                string createBy = null;
                DateTime? createOn = null;
                Guid? createUserId = null;
                Guid id;
                bool isAssigned;
                string orientation = null;
                string privilegeConstraint = null;
                if (roleFunction != null)
                {
                    createBy = roleFunction.CreateBy;
                    createOn = roleFunction.CreateOn;
                    createUserId = roleFunction.CreateUserId;
                    id = roleFunction.Id;
                    isAssigned = true;
                    orientation = roleFunction.AcContentType;
                    privilegeConstraint = roleFunction.AcContent;
                }
                else
                {
                    id = Guid.NewGuid();
                    isAssigned = false;
                }
                data.Add(new RoleAssignFunctionTr
                {
                    AppSystemCode = appSystem.Code,
                    AppSystemId = appSystem.Id,
                    CreateBy = createBy,
                    CreateOn = createOn,
                    CreateUserId = createUserId,
                    Description = function.Description,
                    FunctionCode = function.Code,
                    FunctionId = function.Id,
                    Id = id,
                    IsAssigned = isAssigned,
                    AcContentType = orientation,
                    AcContent = privilegeConstraint,
                    ResourceCode = function.Resource.Code,
                    ResourceTypeId = function.ResourceTypeId,
                    ResourceName = function.Resource.Name,
                    RoleId = requestData.RoleId,
                    SortCode = function.SortCode
                });
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = data.AsQueryable();
            if (!string.IsNullOrEmpty(requestData.Key))
            {
                queryable = queryable.Where(a => a.Description.Contains(requestData.Key) || a.FunctionCode.Contains(requestData.Key));
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistGroups
        public static IQueryable<IGroup> GetPlistGroups(this IAcDomain acDomain, GetPlistResult requestModel)
        {
            EntityTypeState groupEntityType = acDomain.GetEntityType(new Coder("Ac", "Group"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!groupEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的Group实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.GroupSet.AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistRoleGroups
        public static IQueryable<Dictionary<string, object>> GetPlistRoleGroups(this IAcDomain acDomain, GetPlistRoleGroups requestData)
        {
            RoleState role;
            if (!acDomain.RoleSet.TryGetRole(requestData.RoleId, out role))
            {
                throw new ValidationException("意外的角色标识" + requestData.RoleId);
            }
            var data = new List<Dictionary<string, object>>();
            foreach (var group in acDomain.GroupSet)
            {
                var roleGroup = acDomain.PrivilegeSet.FirstOrDefault(a =>
                    a.SubjectType == AcElementType.Role && a.ObjectType == AcElementType.Group
                    && a.SubjectInstanceId == role.Id && a.ObjectInstanceId == group.Id);
                if (requestData.IsAssigned.HasValue)
                {
                    if (requestData.IsAssigned.Value)
                    {
                        if (roleGroup == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (roleGroup != null)
                        {
                            continue;
                        }
                    }
                }
                string createBy = null;
                DateTime? createOn = null;
                Guid? createUserId = null;
                Guid id;
                bool isAssigned;
                if (roleGroup != null)
                {
                    createBy = roleGroup.CreateBy;
                    createOn = roleGroup.CreateOn;
                    createUserId = roleGroup.CreateUserId;
                    id = roleGroup.Id;
                    isAssigned = true;
                }
                else
                {
                    id = Guid.NewGuid();
                    isAssigned = false;
                }
                data.Add(new Dictionary<string, object>
                {
                    {"CategoryCode", group.CategoryCode??string.Empty},
                    {"CreateBy", createBy},
                    {"CreateOn", createOn},
                    {"CreateUserId", createUserId},
                    {"GroupId", group.Id},
                    {"Id", id},
                    {"IsAssigned", isAssigned},
                    {"IsEnabled", group.IsEnabled},
                    {"Name", group.Name??string.Empty},
                    {"RoleId", role.Id},
                    {"SortCode", group.SortCode}
                });
            }
            var pageIndex = requestData.PageIndex;
            var pageSize = requestData.PageSize;
            var queryable = data.AsQueryable();
            if (!string.IsNullOrEmpty(requestData.Key))
            {
                queryable = queryable.Where(a => a["Name"].ToString().Contains(requestData.Key) || a["CategoryCode"].ToString().Contains(requestData.Key));
            }
            requestData.Total = queryable.Count();
            if (requestData.Total > 0)
            {
                var firstRecord = queryable.First();
                if (!firstRecord.Keys.Contains(requestData.SortField))
                {
                    throw new ValidationException("意外的字段" + requestData.SortField);
                }
                var sortOrder = (requestData.SortOrder ?? "asc").ToLower();
                switch (sortOrder)
                {
                    case "asc":
                        queryable = queryable.OrderBy(a => a[requestData.SortField]);
                        break;
                    case "desc":
                        queryable = queryable.OrderByDescending(a => a[requestData.SortField]);
                        break;
                    default:
                        throw new InvalidOperationException();
                }
            }

            return queryable.Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistUiViews
        public static IQueryable<UiViewTr> GetPlistUiViews(this IAcDomain acDomain, GetPlistResult requestData)
        {
            EntityTypeState viewEntityType = acDomain.GetEntityType(new Coder("Ac", "UIView"));
            foreach (var filter in requestData.Filters)
            {
                PropertyState property;
                if (!viewEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的UIView实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = acDomain.UiViewSet.Select(UiViewTr.Create).AsQueryable();
            foreach (var filter in requestData.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistProperties
        public static IQueryable<PropertyTr> GetPlistProperties(this IAcDomain acDomain, GetPlistProperties requestModel)
        {
            if (!requestModel.EntityTypeId.HasValue)
            {
                throw new ValidationException("entityTypeID是必须的");
            }
            EntityTypeState entityType = acDomain.GetEntityType(new Coder("Ac", "Property"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!acDomain.EntityTypeSet.TryGetProperty(entityType, filter.field, out property))
                {
                    throw new ValidationException("意外的Property实体类型属性" + filter.field);
                }
            }
            if (!acDomain.EntityTypeSet.TryGetEntityType(requestModel.EntityTypeId.Value, out entityType))
            {
                throw new AnycmdException("意外的实体类型标识" + requestModel.EntityTypeId.Value);
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.EntityTypeSet.GetProperties(entityType).Select(a => PropertyTr.Create(a.Value)).AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            if (!string.IsNullOrEmpty(requestModel.Key))
            {
                queryable = queryable.Where(a => a.Code.ToLower().Contains(requestModel.Key) || a.Name.ToLower().Contains(requestModel.Key));
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistRoles
        public static IQueryable<IRole> GetPlistRoles(this IAcDomain acDomain, GetPlistResult requestModel)
        {
            EntityTypeState roleEntityType = acDomain.GetEntityType(new Coder("Ac", "Role"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!roleEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的Role实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.RoleSet.AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistSsdSets
        public static IQueryable<ISsdSet> GetPlistSsdSets(this IAcDomain acDomain, GetPlistResult requestModel)
        {
            EntityTypeState roleEntityType = acDomain.GetEntityType(new Coder("Ac", "SsdSet"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!roleEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的SsdSet实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.SsdSetSet.AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistDsdSets
        public static IQueryable<IDsdSet> GetPlistDsdSets(this IAcDomain acDomain, GetPlistResult requestModel)
        {
            EntityTypeState roleEntityType = acDomain.GetEntityType(new Coder("Ac", "DsdSet"));
            foreach (var filter in requestModel.Filters)
            {
                PropertyState property;
                if (!roleEntityType.TryGetProperty(filter.field, out property))
                {
                    throw new ValidationException("意外的DsdSet实体类型属性" + filter.field);
                }
            }
            int pageIndex = requestModel.PageIndex;
            int pageSize = requestModel.PageSize;
            var queryable = acDomain.DsdSetSet.AsQueryable();
            foreach (var filter in requestModel.Filters)
            {
                queryable = queryable.Where(filter.ToPredicate(), filter.value);
            }
            requestModel.Total = queryable.Count();

            return queryable.OrderBy(requestModel.SortField + " " + requestModel.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistGroupRoles
        public static IQueryable<GroupAssignRoleTr> GetPlistGroupRoles(this IAcDomain acDomain, GetPlistGroupRoles requestData)
        {
            GroupState group;
            if (!acDomain.GroupSet.TryGetGroup(requestData.GroupId, out group))
            {
                throw new ValidationException("意外的工作组标识" + requestData.GroupId);
            }
            var data = new List<GroupAssignRoleTr>();
            foreach (var role in acDomain.RoleSet)
            {
                var roleGroup = acDomain.PrivilegeSet.FirstOrDefault(a =>
                    a.SubjectType == AcElementType.Role && a.ObjectType == AcElementType.Group
                    && a.SubjectInstanceId == role.Id && a.ObjectInstanceId == group.Id);
                if (requestData.IsAssigned.HasValue)
                {
                    if (requestData.IsAssigned.Value)
                    {
                        if (roleGroup == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (roleGroup != null)
                        {
                            continue;
                        }
                    }
                }
                string createBy = null;
                DateTime? createOn = null;
                Guid? createUserId = null;
                Guid id;
                bool isAssigned;
                if (roleGroup != null)
                {
                    createBy = roleGroup.CreateBy;
                    createOn = roleGroup.CreateOn;
                    createUserId = roleGroup.CreateUserId;
                    id = roleGroup.Id;
                    isAssigned = true;
                }
                else
                {
                    id = Guid.NewGuid();
                    isAssigned = false;
                }
                data.Add(new GroupAssignRoleTr
                {
                    CategoryCode = role.CategoryCode,
                    CreateBy = createBy,
                    CreateOn = createOn,
                    CreateUserId = createUserId,
                    GroupId = group.Id,
                    Id = id,
                    IsAssigned = isAssigned,
                    IsEnabled = role.IsEnabled,
                    Name = role.Name,
                    RoleId = role.Id,
                    SortCode = role.SortCode,
                    Icon = role.Icon
                });
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = data.AsQueryable();
            if (!string.IsNullOrEmpty(requestData.Key))
            {
                queryable = queryable.Where(a => a.Name.Contains(requestData.Key) || a.CategoryCode.Contains(requestData.Key));
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion

        #region GetPlistMenuRoles
        public static IQueryable<MenuAssignRoleTr> GetPlistMenuRoles(this IAcDomain acDomain, GetPlistMenuRoles requestData)
        {
            if (!requestData.MenuId.HasValue)
            {
                throw new ValidationException("menuID为空");
            }
            MenuState menu;
            if (!acDomain.MenuSet.TryGetMenu(requestData.MenuId.Value, out menu))
            {
                throw new ValidationException("意外的菜单标识" + requestData.MenuId);
            }
            var roleMenus = acDomain.PrivilegeSet.Where(a => a.SubjectType == AcElementType.Role && a.ObjectType == AcElementType.Menu).ToList();
            var roles = acDomain.RoleSet;
            var data = new List<MenuAssignRoleTr>();
            foreach (var role in roles)
            {
                var roleMenu = roleMenus.FirstOrDefault(a => a.SubjectInstanceId == role.Id && a.ObjectInstanceId == menu.Id);
                if (requestData.IsAssigned.HasValue)
                {
                    if (requestData.IsAssigned.Value)
                    {
                        if (roleMenu == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (roleMenu != null)
                        {
                            continue;
                        }
                    }
                }
                string createBy = null;
                DateTime? createOn = null;
                Guid? createUserId = null;
                Guid id;
                bool isAssigned;
                string orientation = null;
                string privilegeConstraint = null;
                if (roleMenu != null)
                {
                    createBy = roleMenu.CreateBy;
                    createOn = roleMenu.CreateOn;
                    createUserId = roleMenu.CreateUserId;
                    id = roleMenu.Id;
                    isAssigned = true;
                    orientation = roleMenu.AcContentType;
                    privilegeConstraint = roleMenu.AcContent;
                }
                else
                {
                    id = Guid.NewGuid();
                    isAssigned = false;
                }
                data.Add(new MenuAssignRoleTr
                {
                    CreateBy = createBy,
                    CreateOn = createOn,
                    CreateUserId = createUserId,
                    Id = id,
                    IsAssigned = isAssigned,
                    AcContentType = orientation,
                    AcContent = privilegeConstraint,
                    RoleId = role.Id,
                    CategoryCode = role.CategoryCode,
                    Icon = role.Icon,
                    IsEnabled = role.IsEnabled,
                    MenuId = requestData.MenuId.Value,
                    Name = role.Name,
                    SortCode = role.SortCode
                });
            }
            int pageIndex = requestData.PageIndex;
            int pageSize = requestData.PageSize;
            var queryable = data.AsQueryable();
            if (!string.IsNullOrEmpty(requestData.Key))
            {
                queryable = queryable.Where(a => a.Name.Contains(requestData.Key) || a.CategoryCode.Contains(requestData.Key));
            }
            requestData.Total = queryable.Count();

            return queryable.OrderBy(requestData.SortField + " " + requestData.SortOrder).Skip(pageIndex * pageSize).Take(pageSize);
        }
        #endregion
    }
}


text:
<?php

final class PhabricatorFileChunk extends PhabricatorFileDAO
  implements
    PhabricatorPolicyInterface,
    PhabricatorDestructibleInterface {

  protected $chunkHandle;
  protected $byteStart;
  protected $byteEnd;
  protected $dataFilePHID;

  private $dataFile = self::ATTACHABLE;

  protected function getConfiguration() {
    return array(
      self::CONFIG_TIMESTAMPS => false,
      self::CONFIG_COLUMN_SCHEMA => array(
        'chunkHandle' => 'bytes12',
        'byteStart' => 'uint64',
        'byteEnd' => 'uint64',
        'dataFilePHID' => 'phid?',
      ),
      self::CONFIG_KEY_SCHEMA => array(
        'key_file' => array(
          'columns' => array('chunkHandle', 'byteStart', 'byteEnd'),
        ),
        'key_data' => array(
          'columns' => array('dataFilePHID'),
        ),
      ),
    ) + parent::getConfiguration();
  }

  public static function newChunkHandle() {
    $seed = Filesystem::readRandomBytes(64);
    return PhabricatorHash::digestForIndex($seed);
  }

  public static function initializeNewChunk($handle, $start, $end) {
    return id(new PhabricatorFileChunk())
      ->setChunkHandle($handle)
      ->setByteStart($start)
      ->setByteEnd($end);
  }

  public function attachDataFile(PhabricatorFile $file = null) {
    $this->dataFile = $file;
    return $this;
  }

  public function getDataFile() {
    return $this->assertAttached($this->dataFile);
  }

/* -(  PhabricatorPolicyInterface  )----------------------------------------- */

  public function getCapabilities() {
    return array(
      PhabricatorPolicyCapability::CAN_VIEW,
    );
  }

  public function getPolicy($capability) {
    // These objects are low-level and only accessed through the storage
    // engine, so policies are mostly just in place to let us use the common
    // query infrastructure.
    return PhabricatorPolicies::getMostOpenPolicy();
  }

  public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
    return false;
  }

/* -(  PhabricatorDestructibleInterface  )----------------------------------- */

  public function destroyObjectPermanently(
    PhabricatorDestructionEngine $engine) {

    $data_phid = $this->getDataFilePHID();
    if ($data_phid) {
      $data_file = id(new PhabricatorFileQuery())
        ->setViewer($engine->getViewer())
        ->withPHIDs(array($data_phid))
        ->executeOne();
      if ($data_file) {
        $engine->destroyObject($data_file);
      }
    }

    $this->delete();
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.ruesga.rview.gerrit.filter;

/**
 * @link "https://gerrit-review.googlesource.com/Documentation/user-search-groups.html#_search_operators"
 */
public class GroupQuery extends SimpleQuery {

    public GroupQuery any(String q) {
        add(sanitizeValue(q));
        return this;
    }

    public GroupQuery description(String description) {
        add("description:" + sanitizeValue(description));
        return this;
    }

    public GroupQuery name(String name) {
        add("name:" + sanitizeValue(name));
        return this;
    }

    public GroupQuery inname(String inname) {
        add("inname:" + sanitizeValue(inname));
        return this;
    }

    public GroupQuery owner(String owner) {
        add("owner:" + sanitizeValue(owner));
        return this;
    }

    public GroupQuery uuid(String uuid) {
        add("uuid:" + sanitizeValue(uuid));
        return this;
    }

    public GroupQuery member(String member) {
        add("member:" + sanitizeValue(member));
        return this;
    }

    public GroupQuery subgroup(String subgroup) {
        add("subgroup:" + sanitizeValue(subgroup));
        return this;
    }

    public GroupQuery visibletoall(boolean status) {
        if (status) {
            add("is:visibletoall");
        } else {
            remove("is:visibletoall");
        }
        return this;
    }

    public GroupQuery visible(boolean status) {
        if (status) {
            add("is:visible");
        } else {
            remove("is:visible");
        }
        return this;
    }
}


text:
package com.siyeh.ig.junit;

import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.testFrameworks.AssertHint;
import org.jetbrains.annotations.NotNull;

public class AssertEqualsCalledOnArrayInspection extends BaseInspection {

  @NotNull
  @Override
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("assertequals.called.on.arrays.problem.descriptor");
  }

  @Override
  protected InspectionGadgetsFix buildFix(Object... infos) {
    return new ReplaceAssertEqualsFix("assertArrayEquals");
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new AssertEqualsOnArrayVisitor();
  }

  private static class AssertEqualsOnArrayVisitor extends BaseInspectionVisitor {

    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression expression) {
      super.visitMethodCallExpression(expression);
      final AssertHint assertHint = AssertHint.createAssertEqualsHint(expression, false);
      if (assertHint == null) {
        return;
      }
      final PsiType type1 = assertHint.getFirstArgument().getType();
      final PsiType type2 = assertHint.getSecondArgument().getType();
      if (!(type1 instanceof PsiArrayType) || !(type2 instanceof PsiArrayType)) {
        return;
      }
      registerMethodCallError(expression);
    }
  }
}


text:
<?php

namespace Frontend\Modules\Location\Engine;

use Frontend\Core\Engine\Model as FrontendModel;

/**
 * In this file we store all generic functions that we will be using in the location module
 *
 * @author Matthias Mullie <forkcms@mullie.eu>
 * @author Jelmer Snoeck <jelmer@siphoc.com>
 */
class Model
{
    /**
     * This will build the url to google maps for a large map
     *
     * @param array $settings
     * @param array $markers
     *
     * @return string
     */
    public static function buildUrl(array $settings, array $markers = array())
    {
        $url = 'http://maps.google.be/?';

        // add the center point
        $url .= 'll=' . $settings['center']['lat'] . ',' . $settings['center']['lng'];

        // add the zoom level
        $url .= '&z=' . $settings['zoom_level'];

        // set the map type
        switch (mb_strtolower($settings['map_type'])) {
            case 'roadmap':
                $url .= '&t=m';
                break;
            case 'hybrid':
                $url .= '&t=h';
                break;
            case 'terrain':
                $url .= '&t=p';
                break;
            default:
                $url .= '&t=k';
                break;
        }

        $pointers = array();
        // add the markers to the url
        foreach ($markers as $marker) {
            $pointers[] = urlencode($marker['title']) . '@' . $marker['lat'] . ',' . $marker['lng'];
        }

        if (!empty($pointers)) {
            $url .= '&q=' . implode('|', $pointers);
        }

        return $url;
    }

    /**
     * Get an item
     *
     * @param int $id The id of the item to fetch.
     *
     * @return array
     */
    public static function get($id)
    {
        return (array) FrontendModel::getContainer()->get('database')->getRecord(
            'SELECT *
             FROM location
             WHERE id = ? AND language = ?',
            array((int) $id, FRONTEND_LANGUAGE)
        );
    }

    /**
     * Get all items
     *
     * @return array
     */
    public static function getAll()
    {
        return (array) FrontendModel::getContainer()->get('database')->getRecords(
            'SELECT * FROM location WHERE language = ? AND show_overview = ?',
            array(FRONTEND_LANGUAGE, 'Y')
        );
    }

    /**
     * Retrieve a map setting
     *
     * @param int    $mapId
     * @param string $name
     *
     * @return mixed
     */
    public static function getMapSetting($mapId, $name)
    {
        $serializedData = (string) FrontendModel::getContainer()->get('database')->getVar(
            'SELECT s.value
             FROM location_settings AS s
             WHERE s.map_id = ? AND s.name = ?',
            array((int) $mapId, (string) $name)
        );

        if ($serializedData != null) {
            return unserialize($serializedData);
        }

        return false;
    }

    /**
     * Fetch all the settings for a specific map
     *
     * @param int $mapId
     *
     * @return array
     */
    public static function getMapSettings($mapId)
    {
        $mapSettings = (array) FrontendModel::getContainer()->get('database')->getPairs(
            'SELECT s.name, s.value
             FROM location_settings AS s
             WHERE s.map_id = ?',
            array((int) $mapId)
        );

        foreach ($mapSettings as $key => $value) {
            $mapSettings[$key] = unserialize($value);
        }

        return $mapSettings;
    }
}


text:
"""
Django settings for app project.

Generated by 'django-admin startproject' using Django 1.10.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1yh7p13pn9&u8d5cc%-&ym*=i%r@=qhdpckil@92a88r-)y=at'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CAPTCHA_TEST_MODE = True
ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'authentication',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'app.middleware.CorsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ocbl_rest',
        'USER': 'root',
        'PASSWORD': 'justdoit',
        'HOST': '127.0.0.1',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
RESOURCE_ROOT='/opt/www/tiger/'
#RESOURCE_ROOT='e:/opt/var/www/ocbl/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '[ %(levelname)s ] %(asctime)s - %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'debug.logfile': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(RESOURCE_ROOT,'logs/debug.log'),
            'formatter': 'verbose',
        },
        'requests.logfile': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(RESOURCE_ROOT,'logs/requests.log'),
            'formatter': 'simple',
        },
    },
    'loggers': {
        'authentication': {
            'handlers': ['debug.logfile', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'app': {
            'handlers': ['debug.logfile', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'tools': {
            'handlers': ['debug.logfile', 'console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['requests.logfile'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT=  os.path.join(RESOURCE_ROOT,'static')

#variables for developement
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
    STATIC_PATH,
)

TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_PATH,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                "django.contrib.auth.context_processors.auth",
            ]
        },
    },
]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(RESOURCE_ROOT,'media')

# setting for testing seeding
FIXTURE_PATH = os.path.join(BASE_DIR,'fixture')
FIXTURE_DIRS = (
    FIXTURE_PATH,
)

LOCALE_PATH = os.path.join(BASE_DIR,'locale')
LOCALE_PATHS = [
    LOCALE_PATH,
]

AUTH_USER_MODEL = 'authentication.Account'
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        #'rest_framework.authentication.SessionAuthentication',
        'app.security.JWTAuthentication',
    )
}

JWT_SECRET = 'JNIOI&(56!'
JWT_SIGN_ALGORITHM = 'HS256'
JWT_EXPIRE_IN_MINUTE=60
JWT_HEADER='Bearer'


text:
#include <math.h>

#include "Audio.h"
#include "AudioInput.h"
#include "AudioOutput.h"
#include "Global.h"
#include "PacketDataStream.h"

class CodecInit : public DeferInit {
	public:
		void initialize();
		void destroy();
};

#define DOUBLE_RAND (rand()/static_cast<double>(RAND_MAX))

LoopUser LoopUser::lpLoopy;
CodecInit ciInit;

void CodecInit::initialize() {
	CELTCodec *codec = NULL;

	codec = new CELTCodec070(QLatin1String("0.7.0"));
	if (codec->isValid()) {
		codec->report();
		g.qmCodecs.insert(codec->bitstreamVersion(), codec);
	} else {
		delete codec;
		codec = new CELTCodec070(QLatin1String("0.0.0"));
		if (codec->isValid()) {
			codec->report();
			g.qmCodecs.insert(codec->bitstreamVersion(), codec);
		} else {
			delete codec;
		}
	}

	codec = new CELTCodec080(QLatin1String("0.8.0"));
	if (codec->isValid()) {
		codec->report();
		g.qmCodecs.insert(codec->bitstreamVersion(), codec);
	} else {
		delete codec;
		codec = new CELTCodec080(QLatin1String("1.0.0"));
		if (codec->isValid()) {
			codec->report();
			g.qmCodecs.insert(codec->bitstreamVersion(), codec);
		} else {
			delete codec;
		}
	}
}

void CodecInit::destroy() {
	foreach(CELTCodec *codec, g.qmCodecs)
		delete codec;
	g.qmCodecs.clear();
}

#define RESOLVE(var) { * reinterpret_cast<void **>(&var) = static_cast<void *>(qlCELT.resolve(#var)); bValid = bValid && (var != NULL); }

#ifdef Q_OS_WIN
extern "C" {
	void __cpuid(int a[4], int b);
};
#endif

CELTCodec::CELTCodec(const QString &version) {
	bValid = false;
	cmMode = NULL;
	qsVersion = version;
	qlCELT.setLoadHints(QLibrary::ResolveAllSymbolsHint);

	QStringList alternatives;
#if defined(Q_OS_MAC)
	alternatives << QString::fromLatin1("libcelt0.%1.dylib").arg(version);
	alternatives << QString::fromLatin1("celt0.%1.dylib").arg(version);
	alternatives << QString::fromLatin1("libcelt.%1.dylib").arg(version);
	alternatives << QString::fromLatin1("celt.%1.dylib").arg(version);
#elif defined(Q_OS_UNIX)
	alternatives << QString::fromLatin1("libcelt0.so.%1").arg(version);
	alternatives << QString::fromLatin1("libcelt.so.%1").arg(version);
	alternatives << QString::fromLatin1("celt.so.%1").arg(version);
#else
	int cpuinfo[4];
	__cpuid(cpuinfo, 1);
	if (cpuinfo[3] & 0x02000000) {
		if (cpuinfo[3] & 0x04000000) {
			if (cpuinfo[2] & 0x00000001) {
				alternatives << QString::fromLatin1("celt0.%1.sse3.dll").arg(version);
			}
			alternatives << QString::fromLatin1("celt0.%1.sse2.dll").arg(version);
		}
		alternatives << QString::fromLatin1("celt0.%1.sse.dll").arg(version);
	}

	alternatives << QString::fromLatin1("celt0.%1.dll").arg(version);
#endif
	foreach(const QString &lib, alternatives) {
		qlCELT.setFileName(QApplication::instance()->applicationDirPath() + QLatin1String("/") + lib);
		if (qlCELT.load()) {
			bValid = true;
			break;
		}

#ifdef Q_OS_MAC
		qlCELT.setFileName(QApplication::instance()->applicationDirPath() + QLatin1String("/../Codecs/") + lib);
		if (qlCELT.load()) {
			bValid = true;
			break;
		}
#endif

#ifdef PLUGIN_PATH
		qlCELT.setFileName(QLatin1String(MUMTEXT(PLUGIN_PATH) "/") + lib);
		if (qlCELT.load()) {
			bValid = true;
			break;
		}
#endif

		qlCELT.setFileName(lib);
		if (qlCELT.load()) {
			bValid = true;
			break;
		}
	}

	RESOLVE(celt_mode_destroy);
	RESOLVE(celt_mode_info);

	RESOLVE(celt_encoder_destroy);
	RESOLVE(celt_encoder_ctl);

	RESOLVE(celt_decoder_destroy);
	RESOLVE(celt_decoder_ctl);
}

CELTCodec::~CELTCodec() {
	if (cmMode)
		celt_mode_destroy(const_cast<CELTMode *>(cmMode));
}

bool CELTCodec::isValid() const {
	return bValid;
}

int CELTCodec::bitstreamVersion() const {
	int v = INT_MIN;

	if (cmMode)
		celt_mode_info(cmMode, CELT_GET_BITSTREAM_VERSION, reinterpret_cast<celt_int32 *>(&v));
	return v;
}

QString CELTCodec::version() const {
	return qsVersion;
}

void CELTCodec::report() const {
	qWarning("CELT bitstream %08x from %s", bitstreamVersion(), qPrintable(qlCELT.fileName()));
}

CELTCodec070::CELTCodec070(const QString &version) : CELTCodec(version) {
	RESOLVE(celt_mode_create);
	RESOLVE(celt_encoder_create);
	RESOLVE(celt_decoder_create);
	RESOLVE(celt_encode_float);
	RESOLVE(celt_encode);
	RESOLVE(celt_decode_float);
	RESOLVE(celt_decode);
	RESOLVE(celt_strerror);

	if (bValid) {
		cmMode = celt_mode_create(SAMPLE_RATE, SAMPLE_RATE / 100, NULL);
	}
}

CELTEncoder *CELTCodec070::encoderCreate() {
	return celt_encoder_create(cmMode, 1, NULL);
}

CELTDecoder *CELTCodec070::decoderCreate() {
	return celt_decoder_create(cmMode, 1, NULL);
}

int CELTCodec070::encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) {
	return celt_encode(st, pcm, NULL, compressed, nbCompressedBytes);
}

int CELTCodec070::decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) {
	return celt_decode_float(st, data, len, pcm);
}

CELTCodec080::CELTCodec080(const QString &version) : CELTCodec(version) {
	RESOLVE(celt_mode_create);
	RESOLVE(celt_encoder_create);
	RESOLVE(celt_decoder_create);
	RESOLVE(celt_encode_float);
	RESOLVE(celt_encode);
	RESOLVE(celt_decode_float);
	RESOLVE(celt_decode);
	RESOLVE(celt_strerror);

	if (bValid) {
		cmMode = celt_mode_create(SAMPLE_RATE, SAMPLE_RATE / 100, NULL);
	}
}

CELTEncoder *CELTCodec080::encoderCreate() {
	return celt_encoder_create(cmMode, 1, NULL);
}

CELTDecoder *CELTCodec080::decoderCreate() {
	return celt_decoder_create(cmMode, 1, NULL);
}

int CELTCodec080::encode(CELTEncoder *st, const celt_int16 *pcm, unsigned char *compressed, int nbCompressedBytes) {
	return celt_encode(st, pcm, SAMPLE_RATE / 100, compressed, nbCompressedBytes);
}

int CELTCodec080::decode_float(CELTDecoder *st, const unsigned char *data, int len, float *pcm) {
	return celt_decode_float(st, data, len, pcm, SAMPLE_RATE / 100);
}

LoopUser::LoopUser() {
	qsName = QLatin1String("Loopy");
	uiSession = 0;
	iId = 0;
	bMute = bDeaf = bSuppress = false;
	bLocalMute = bSelfDeaf = false;
	tsState = Settings::Passive;
	cChannel = NULL;
	qtTicker.start();
}

void LoopUser::addFrame(const QByteArray &packet) {
	if (DOUBLE_RAND < g.s.dPacketLoss) {
		qWarning("Drop");
		return;
	}

	{
		QMutexLocker l(&qmLock);
		bool restart = (qtLastFetch.elapsed() > 100);

		double time = qtTicker.elapsed();

		double r;
		if (restart)
			r = 0.0;
		else
			r = DOUBLE_RAND * g.s.dMaxPacketDelay;

		qmPackets.insert(static_cast<float>(time + r), packet);
	}

	// Restart check
	if (qtLastFetch.elapsed() > 100) {
		AudioOutputPtr ao = g.ao;
		if (ao) {
			MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((packet.at(0) >> 5) & 0x7);
			ao->addFrameToBuffer(this, QByteArray(), 0, msgType);
		}
	}

}

void LoopUser::fetchFrames() {
	QMutexLocker l(&qmLock);

	AudioOutputPtr ao(g.ao);
	if (!ao || qmPackets.isEmpty()) {
		return;
	}

	double cmp = qtTicker.elapsed();

	QMultiMap<float, QByteArray>::iterator i = qmPackets.begin();

	while (i != qmPackets.end()) {
		if (i.key() > cmp)
			break;

		int iSeq;
		const QByteArray &data = i.value();
		PacketDataStream pds(data.constData(), data.size());

		unsigned int msgFlags = static_cast<unsigned int>(pds.next());

		pds >> iSeq;

		QByteArray qba;
		qba.reserve(pds.left() + 1);
		qba.append(static_cast<char>(msgFlags));
		qba.append(pds.dataBlock(pds.left()));

		MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((msgFlags >> 5) & 0x7);

		ao->addFrameToBuffer(this, qba, iSeq, msgType);
		i = qmPackets.erase(i);
	}

	qtLastFetch.restart();
}

RecordUser::RecordUser() : LoopUser() {
	qsName = QLatin1String("Recorder");
}

RecordUser::~RecordUser() {
	AudioOutputPtr ao = g.ao;
	if (ao)
		ao->removeBuffer(this);
}

void RecordUser::addFrame(const QByteArray &packet) {
	AudioOutputPtr ao(g.ao);
	if (!ao)
		return;

	int iSeq;
	PacketDataStream pds(packet.constData(), packet.size());

	unsigned int msgFlags = static_cast<unsigned int>(pds.next());

	pds >> iSeq;

	QByteArray qba;
	qba.reserve(pds.left() + 1);
	qba.append(static_cast<char>(msgFlags));
	qba.append(pds.dataBlock(pds.left()));

	MessageHandler::UDPMessageType msgType = static_cast<MessageHandler::UDPMessageType>((msgFlags >> 5) & 0x7);

	ao->addFrameToBuffer(this, qba, iSeq, msgType);
}

void Audio::startOutput(const QString &output) {
	g.ao = AudioOutputRegistrar::newFromChoice(output);
	if (g.ao)
		g.ao->start(QThread::HighPriority);
}

void Audio::stopOutput() {
	AudioOutputPtr ao = g.ao;

	g.ao.reset();

	while (ao.get() && ! ao.unique()) {
#if QT_VERSION >= 0x040500
		QThread::yieldCurrentThread();
#endif
	}

	ao.reset();
}

void Audio::startInput(const QString &input) {
	g.ai = AudioInputRegistrar::newFromChoice(input);
	if (g.ai)
		g.ai->start(QThread::HighestPriority);
}

void Audio::stopInput() {
	AudioInputPtr ai = g.ai;

	g.ai.reset();

	while (ai.get() && ! ai.unique()) {
#if QT_VERSION >= 0x040500
		QThread::yieldCurrentThread();
#endif
	}

	ai.reset();
}

void Audio::start(const QString &input, const QString &output) {
	startInput(input);
	startOutput(output);
}

void Audio::stop() {
	AudioInputPtr ai = g.ai;
	AudioOutputPtr ao = g.ao;

	g.ao.reset();
	g.ai.reset();

	while ((ai.get() && ! ai.unique()) || (ao.get() && ! ao.unique())) {
#if QT_VERSION >= 0x040500
		QThread::yieldCurrentThread();
#endif
	}

	ai.reset();
	ao.reset();
}


text:
#include <Box.h>
#include <Button.h>
#include <CheckBox.h>
#include <FilePanel.h>
#include <Path.h>
#include <RadioButton.h>
#include <string.h>
#include <TabView.h>
#include <TextControl.h>
#include <Window.h>

extern "C" {
#include "attach.h"
#include "drive.h"
#include "resources.h"
#include "ui.h"
#include "ui_device.h"
#include "vsync.h"
}

static char *resource_p00_name[] = {
    "FSDevice%dConvertP00",
    "FSDevice%dSaveP00",
    "FSDevice%dHideCBMFiles"
};

static char *p00_text[] = {
    "Read P00 files",
    "Write P00 files",
    "Hide non-P00 files"
};

class DeviceView : public BView {
    public:
        DeviceView(BRect r, int device_num);
        void UpdateP00(int device_num);
        BTextControl *dirtextcontrol;
        BCheckBox *checkboxp00[3];
};

DeviceView::DeviceView(BRect r, int device_num) : BView(r, "device_view", B_FOLLOW_NONE, B_WILL_DRAW)
{
    const char *instruction_text = "Remember that these settings only work if\n"
                                   "  - True Drive Emulation is disabled\n"
                                   "  - Virtual Devices are enabled\n"
                                   "  - no diskimage is attached";
    BButton *button;
    BTextView *instruction;
    BMessage *msg;
    BBox *box;
    const char *disk_image, *dir;
    int i;

    BView::SetViewColor(220, 220, 220, 0);

    disk_image = file_system_get_disk_name(device_num);
    resources_get_string_sprintf("FSDevice%dDir", &dir, device_num);
    r.InsetBy(10, 10);
    box = new BBox(r);
    AddChild(box);

    /* the directory related controls */
    msg = new BMessage(MESSAGE_DEVICE_DIRECTORY);
    msg->AddInt32("device", device_num);
    dirtextcontrol = new BTextControl(BRect(10, 10, box->Bounds().right - 10, 20), "dir text", "Directory", dir,msg);
    dirtextcontrol->SetDivider(60);
    box->AddChild(dirtextcontrol);

    msg = new BMessage(MESSAGE_DEVICE_BROWSE);
    msg->AddInt32("device", device_num);
    button = new BButton(BRect(70,30,130,40), "browsedir", "Browse", msg);
    box->AddChild(button);

    for (i = 0; i < 3; i++) {
        msg = new BMessage(MESSAGE_DEVICE_P00);
        msg->AddInt32("type", i);
        msg->AddInt32("device", device_num);

        checkboxp00[i] = new BCheckBox(BRect(150,30 + i * 20, 260, 40 + i * 20), p00_text[i], p00_text[i], msg);
        box->AddChild(checkboxp00[i]);
    }
    UpdateP00(device_num);

    /* some explanations */
    r=box->Bounds();
    r.InsetBy(5, 5);
    r.top += 100;
    instruction = new BTextView(r, "instructions", BRect(20, 5, r.Width() - 20, r.Height() - 5), B_FOLLOW_NONE, B_WILL_DRAW);
    box->AddChild(instruction);
    instruction->MakeEditable(false);
    instruction->MakeSelectable(false);
    instruction->SetViewColor(180, 180, 180, 0);
    instruction->SetText(instruction_text);
}

void DeviceView::UpdateP00(int device_num)
{
    int res_value;
    int i;

    for (i = 0; i < 3; i++) {
        resources_get_int_sprintf(resource_p00_name[i], &res_value, device_num);
        checkboxp00[i]->SetValue(res_value);
    }
}

class DeviceWindow : public BWindow {
    public:
        DeviceWindow();
        ~DeviceWindow();
        virtual void MessageReceived(BMessage *msg);
    private:
        DeviceView *dv[4]; /* pointers to the Devices 8-11 */
        BTextControl *printertextcontrol;
};

static DeviceWindow *devicewindow = NULL;

DeviceWindow::DeviceWindow()
    : BWindow(BRect(50, 50, 400, 270),"Device settings", B_TITLED_WINDOW_LOOK, B_MODAL_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_NOT_RESIZABLE)
{
    BRect frame, r;
    BView *printerview;
    BTabView *tabview;
    BTab *tab;
    BBox *box;
    BCheckBox *checkbox;
    int device_num;
    int printer4;
    const char *printerfile;
    char str[20];

    frame = Bounds();
    tabview = new BTabView(frame, "tab_view");
    tabview->SetViewColor(220, 220, 220, 0);

    frame = tabview->Bounds();
    frame.InsetBy(5, 5);
    frame.OffsetTo(3, 3);
    frame.bottom -= tabview->TabHeight();

    /* the printer 4 device */
    r = frame;
    tab = new BTab();
    tabview->AddTab(printerview = new BView(r, "printerview", B_FOLLOW_NONE, B_WILL_DRAW), tab);
    tab->SetLabel("Printer 4");
    printerview->SetViewColor(220,220,220,0);

    resources_get_int("Printer4", &printer4);
    resources_get_string("PrinterTextDevice1", &printerfile);
    r.InsetBy(10, 10);
    box = new BBox(r);
    printerview->AddChild(box);

    checkbox = new BCheckBox(BRect(20, 20, 200, 30), "printer4", "Printer 4 enabled", new BMessage(MESSAGE_DEVICE_PRINTER4));
    checkbox->SetValue(printer4);
    box->AddChild(checkbox);

    printertextcontrol = new BTextControl(BRect(10, 50, 240, 60), "printerfile", "Output to file", printerfile, new BMessage(MESSAGE_DEVICE_PRINTERFILE));
    printertextcontrol->SetDivider(80);
    box->AddChild(printertextcontrol);

    /* the disk devices 8-11 */
    for (device_num = 8; device_num < 12; device_num++) {
        tab = new BTab();
        tabview->AddTab(dv[device_num - 8] = new DeviceView(frame,device_num), tab);
        sprintf(str, "Drive %d", device_num);
        tab->SetLabel(str);
    }

    AddChild(tabview);
    tabview->SetTabWidth(B_WIDTH_FROM_WIDEST);
    Show();
}

DeviceWindow::~DeviceWindow()
{
    devicewindow = NULL;
}

void DeviceWindow::MessageReceived(BMessage *msg) {
    int32 device_num;
    int32 resource_index;
    char str[256];
    const char *s;
    int res_val;
    BFilePanel *filepanel;
    BMessage *newmsg;

    msg->FindInt32("device", &device_num);

    switch (msg->what) {
        case MESSAGE_DEVICE_PRINTER4:
            resources_toggle("Printer4", NULL);
            break;
        case MESSAGE_DEVICE_PRINTERFILE:
            resources_set_string("PrinterTextDevice1", printertextcontrol->Text());
            break;
        case MESSAGE_DEVICE_P00:
            msg->FindInt32("type", &resource_index);
            resources_get_int_sprintf(resource_p00_name[resource_index], &res_val, device_num);
            resources_set_int_sprintf(resource_p00_name[resource_index], !res_val, device_num);
            /* the p00-resources have side effects on each other */
            dv[device_num - 8]->UpdateP00(device_num);
            break;
        case MESSAGE_DEVICE_BROWSE:
            resources_get_string_sprintf("FSDevice%dDir", &s, device_num);
            filepanel = new BFilePanel(B_OPEN_PANEL, new BMessenger(this), NULL, B_DIRECTORY_NODE, false, NULL, NULL, true);
            sprintf(str,"Choose directory for device %d", device_num);
            filepanel->Window()->SetTitle(str);
            filepanel->SetPanelDirectory(s);
            /* we have to remember the device number */
            newmsg = new BMessage(MESSAGE_DEVICE_BROWSE_END);
            newmsg->AddInt32("device", device_num);
            filepanel->SetMessage(newmsg);
            delete newmsg;
            filepanel->Show();
            break;
        case MESSAGE_DEVICE_BROWSE_END:
            {
                entry_ref ref;
                BPath *path;

                msg->FindRef("refs", 0, &ref);
                path = new BPath(&ref);

                resources_set_string_sprintf("FSDevice%dDir", path->Path(), device_num);
                dv[device_num - 8]->dirtextcontrol->SetText(path->Path());
                break;
            }
        case MESSAGE_DEVICE_DIRECTORY:
            resources_set_string_sprintf("FSDevice%dDir", dv[device_num - 8]->dirtextcontrol->Text(), device_num);
            break;
        default:
            BWindow::MessageReceived(msg);
    }
}

void ui_device() {
    thread_id devicethread;
    status_t exit_value;

    if (devicewindow != NULL) {
        return;
    }

    devicewindow = new DeviceWindow;

    vsync_suspend_speed_eval();

    /* wait until window closed */
    devicethread = devicewindow->Thread();
    wait_for_thread(devicethread, &exit_value);
}