text:
using nHydrate.Generator.Common;
using nHydrate.Generator.Common.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace nHydrate.ModelManagement
{
    public static class FileManagement
    {
        private const string FOLDER_OLD_ET = "_entities";
        private const string FOLDER_OLD_VW = "_views";
        private const string FOLDER_ET = "entities";
        private const string FOLDER_VW = "views";
        public const string ModelExtension = ".nhydrate.yaml";
        public const string OldModelExtension = ".nhydrate";

        public static DiskModel Load(string rootFolder, string modelName, out bool wasLoaded)
        {
            wasLoaded = false;
            if (modelName.EndsWith(".yaml")) return null;
            var modelFile = Path.Combine(rootFolder, modelName);
            var fi = new FileInfo(modelFile);
            var showError = (fi.Length > 10); //New file is small so show no error if creating new

            var folderName = modelName.Replace(".nhydrate", ".model");
            var modelFolder = GetModelFolder(rootFolder, folderName);

            //If the model folder does NOT exist
            if (!Directory.Exists(modelFolder))
            {
                if (showError)
                {
                    throw new Exception("The model folder was not found.");
                }
            }
            else wasLoaded = true;

            //Remove old ZIP file. It is no longer used
            try
            {
                var compressedFile = Path.Combine(rootFolder, modelName + ".zip");
                if (File.Exists(compressedFile))
                    File.Delete(compressedFile);
            }
            catch { }

            var results = new DiskModel();
            LoadEntities(modelFolder, results);
            LoadViews(modelFolder, results);

            //Load the global model properties
            var globalFile = Path.Combine(modelFolder, "model.xml");
            if (File.Exists(globalFile))
                results.ModelProperties = GetObject<ModelProperties>(globalFile);

            RemoveNullStrings(results.ModelProperties);

            #region Clean up
            //Ensure all arrays are not null
            results.Entities.ForEach(x => x.fieldset = x.fieldset.OrDefault());
            results.Entities.Where(x => x.fieldset == null).ToList().ForEach(x => x.fieldset = x.fieldset.OrDefault());
            results.Indexes.Where(x => x.index == null).ToList().ForEach(x => x.index = x.index.OrDefault());
            results.Indexes.SelectMany(x => x.index).Where(x => x.indexcolumnset == null).ToList().ForEach(x => x.indexcolumnset = x.indexcolumnset.OrDefault());
            results.Relations.Where(x => x.relation == null).ToList().ForEach(x => x.relation = x.relation.OrDefault());
            results.Relations.SelectMany(x => x.relation).Where(x => x.relationfieldset == null).ToList().ForEach(x => x.relationfieldset = x.relationfieldset.OrDefault());
            results.StaticData.Where(x => x.data == null).ToList().ForEach(x => x.data = x.data.OrDefault());
            results.Views.Where(x => x.fieldset == null).ToList().ForEach(x => x.fieldset = x.fieldset.OrDefault());
            #endregion

            return results;
        }

        private static void LoadEntities(string rootFolder, DiskModel results)
        {
            var folder = Path.Combine(rootFolder, FOLDER_OLD_ET);
            if (!Directory.Exists(folder))
            {
                folder = Path.Combine(rootFolder, FOLDER_ET);
                if (!Directory.Exists(folder)) return;
            }

            //Load Entities
            foreach (var f in Directory.GetFiles(folder, "*.configuration.xml"))
            {
                results.Entities.Add(GetObject<Entity.configuration>(f));
            }

            //Load Indexes
            foreach (var f in Directory.GetFiles(folder, "*.indexes.xml"))
            {
                results.Indexes.Add(GetObject<nHydrate.ModelManagement.Index.configuration>(f));
            }

            //Clean up indexes
            var indexIdList = new List<string>();
            foreach (var i1 in results.Indexes)
            {
                var newList = new List<Index.configurationIndex>();
                foreach (var i2 in i1.index)
                {
                    if (!indexIdList.Contains(i2.id))
                    {
                        indexIdList.Add(i2.id);
                        newList.Add(i2);
                    }
                }
                i1.index = newList.ToArray();
            }

            //Load Relations
            foreach (var f in Directory.GetFiles(folder, "*.relations.xml"))
            {
                results.Relations.Add(GetObject<Relation.configuration>(f));
            }

            //Load Static Data
            foreach (var f in Directory.GetFiles(folder, "*.staticdata.xml"))
            {
                results.StaticData.Add(GetObject<StaticData.configuration>(f));
            }
        }

        private static void LoadViews(string rootFolder, DiskModel results)
        {
            var folder = Path.Combine(rootFolder, FOLDER_OLD_VW);
            if (!Directory.Exists(folder))
            {
                folder = Path.Combine(rootFolder, FOLDER_VW);
                if (!Directory.Exists(folder)) return;
            }

            //Load Views
            if (Directory.Exists(folder))
            {
                foreach (var f in Directory.GetFiles(folder, "*.configuration.xml"))
                {
                    results.Views.Add(GetObject<nHydrate.ModelManagement.View.configuration>(f));
                }

                foreach (var f in Directory.GetFiles(folder, "*.sql"))
                {
                    var fi = new FileInfo(f);
                    var name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length).ToLower();
                    var item = results.Views.FirstOrDefault(x => x.name.ToLower() == name);
                    if (item != null)
                        item.sql = File.ReadAllText(f);
                }
            }
        }

        public static DiskModelYaml Load2(string rootFolder, string modelName, out bool wasLoaded)
        {
            wasLoaded = false;
            var modelFile = Path.Combine(rootFolder, modelName);
            var fi = new FileInfo(modelFile);
            var showError = (fi.Length > 10); //New file is small so show no error if creating new

            var modelFolder = GetModelFolder(rootFolder, modelName.Replace(".nhydrate", ".model"));
            if (modelName.EndsWith(".yaml"))
                modelFolder = rootFolder;

            //If this is a new visual modeler file then create the folder to hold all files
            if (modelFolder.EndsWith(".model") && !Directory.Exists(modelFolder))
            {
                Directory.CreateDirectory(modelFolder);
                System.Threading.Thread.Sleep(500);
            }

            //If the model file is empty and folder has 1 file
            if (fi.Length == 0 && Directory.EnumerateFileSystemEntries(modelFolder).Count() == 1)
            {
                //The model file is 0 bytes and there is no folder, so this is a new model
                wasLoaded = true;
            }
            else if (!Directory.Exists(modelFolder))
            {
                if (showError)
                {
                    throw new Exception("The model folder was not found.");
                }
            }
            else wasLoaded = true;

            //Remove old ZIP file. It is no longer used
            try
            {
                var compressedFile = Path.Combine(rootFolder, modelName + ".zip");
                if (File.Exists(compressedFile))
                    File.Delete(compressedFile);
            }
            catch { }

            //Opened the ".nhydrate" XML file
            if (modelName.EndsWith(OldModelExtension) && File.Exists(modelFile))
            {
                var ff = Directory.GetFiles(Path.Combine(modelFolder)).FirstOrDefault(x => x.EndsWith("model.nhydrate.yaml"));
                if (ff != null)
                {
                    modelFile = ff;
                    modelName = (new FileInfo(ff)).Name;
                }
            }

            var results = new DiskModelYaml();

            //Determine if model is old XML style and convert
            var oldModel = Load(rootFolder, modelName, out bool wasOldLoaded);
            if (wasOldLoaded && oldModel.ModelProperties.Id != Guid.Empty)
            {
                ConvertEntitiesOld2Yaml(rootFolder, oldModel, results);
                ConvertViewsOld2Yaml(rootFolder, oldModel, results);
                results.ModelProperties = oldModel.ModelProperties;
            }
            else
            {
                LoadEntitiesYaml(modelFolder, results);
                LoadViewsYaml(modelFolder, results);

                //Save the global model properties
                var globalFile = Path.Combine(modelFolder, modelName);
                if (File.Exists(globalFile))
                    results.ModelProperties = GetYamlObject<ModelProperties>(globalFile) ?? new ModelProperties { Id = Guid.NewGuid() };
            }

            return results;
        }

        private static void LoadEntitiesYaml(string rootFolder, DiskModelYaml results)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder))
            {
                folder = Path.Combine(rootFolder, FOLDER_OLD_ET);
                if (!Directory.Exists(folder)) return;
            }

            var fList = Directory.GetFiles(folder, "*.yaml");
            //Only use Yaml if there are actual files
            if (!fList.Any()) return;

            results.Entities.Clear();
            foreach (var f in fList)
            {
                //Try single object
                Exception lastException = null;
                try
                {
                    results.Entities.Add(GetYamlObject<EntityYaml>(f));
                }
                catch (Exception ex) { lastException = ex; }

                if (lastException != null)
                {
                    //If fails try multiple objects per file. If error then really throw
                    try
                    {
                        results.Entities.AddRange(GetYamlObject<EntityYaml[]>(f));
                    }
                    catch (Exception ex)
                    {
                        //This is a bogus error because the file does NOT contain multiple objects
                        //The first error was correct as the single object YAML was incorrect format
                        if (ex.Message.Contains("Line: 1, Col: 1, Idx: 0"))
                            throw lastException;
                        else
                            throw;
                    }
                }

            }

        }

        private static void LoadViewsYaml(string rootFolder, DiskModelYaml results)
        {
            var folder = Path.Combine(rootFolder, FOLDER_VW);
            if (!Directory.Exists(folder))
            {
                folder = Path.Combine(rootFolder, FOLDER_OLD_VW);
                if (!Directory.Exists(folder)) return;
            }

            var fList = Directory.GetFiles(folder, "*.yaml");
            //Only use Yaml if there are actual files
            if (!fList.Any()) return;

            results.Views.Clear();
            foreach (var f in fList)
                results.Views.Add(GetYamlObject<ViewYaml>(f));

            foreach (var f in Directory.GetFiles(folder, "*.sql"))
            {
                var fi = new FileInfo(f);
                var name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length).ToLower();
                var item = results.Views.FirstOrDefault(x => x.Name.ToLower() == name);
                if (item != null)
                    item.Sql = File.ReadAllText(f);
            }

            FixupModel(results);
        }

        private static void FixupModel(DiskModelYaml results)
        {
            //Fill in field IDs if need be
            results.Entities
                .Where(x => x.Id == Guid.Empty)
                .ToList()
                .ForEach(x => x.Id = Guid.NewGuid());

            //Validate model. Ensure all Guids match up, etc
            var allEntities = results.Entities.Select(x => x.Id).ToList();
            if (allEntities.Count != allEntities.Distinct().Count())
                throw new ModelException("Entities must have unique ID values.");

            foreach (var entity in results.Entities)
            {
                //Fill in field IDs if need be
                entity.Fields
                    .Where(x => x.Id == Guid.Empty)
                    .ToList()
                    .ForEach(x => x.Id = Guid.NewGuid());

                //Reset predefined sizes if necessary
                foreach (var field in entity.Fields)
                {
                    var size = nHydrate.Generator.Common.Models.ColumnBase.GetPredefinedSize(field.Datatype.Convert<System.Data.SqlDbType>());
                    field.Length = (size == -1) ? field.Length : size;
                }

                if (entity.Fields.Count != entity.Fields.Select(x => x.Id).Count())
                    throw new ModelException($"Entity: '{entity.Name}': All fields must have a unique ID.");

                #region Indexes
                if (entity.Indexes.Count(x => x.Clustered) > 1)
                    throw new ModelException($"Entity: '{entity.Name}': An entity can have only one clustered index.");

                foreach (var index in entity.Indexes)
                {
                    foreach (var field in index.Fields)
                    {
                        var targetField = entity.Fields.FirstOrDefault(x => x.Id == field.FieldId);
                        if (field.FieldId == Guid.Empty)
                            targetField = entity.Fields.FirstOrDefault(x => x.Name?.ToLower() == field.FieldName?.ToLower());

                        if (targetField == null)
                            throw new ModelException($"Entity: '{entity.Name}': The index must map to an existing field.");

                        field.FieldId = targetField.Id;
                        field.FieldName = targetField.Name;
                    }
                }
                #endregion

                #region Indexes (Ensure if on fields marked then on index exists)
                foreach (var field in entity.Fields.Where(x => x.IsIndexed))
                {
                    if (!entity.Indexes.Any(x => x.Fields.Any(z => z.FieldId == field.Id)))
                    {
                        entity.Indexes.Add(new IndexYaml
                        {
                            Clustered = false,
                            Id = Guid.NewGuid(),
                            IndexType = field.IsPrimaryKey ? IndexTypeConstants.PrimaryKey : IndexTypeConstants.IsIndexed,
                            IsUnique = false,
                            Fields = new List<IndexFieldYaml>(new[] { new IndexFieldYaml { FieldId = field.Id, FieldName = field.Name, } }),
                        });
                    }
                }
                #endregion

                #region Relations
                foreach (var relation in entity.Relations)
                {
                    var foreignEntity = results.Entities.FirstOrDefault(x => x.Id == relation.ForeignEntityId);
                    if (relation.ForeignEntityId == Guid.Empty)
                        foreignEntity = results.Entities.FirstOrDefault(x => x.Name?.ToLower() == relation.ForeignEntityName?.ToLower());

                    if (foreignEntity == null)
                        throw new ModelException($"Entity: '{entity.Name}': The relation must map to an existing entity.");

                    if (!relation.Fields.Any())
                    {
                        //If there are 0 fields and the foreign table has the same field name as primary table
                        //then add a relation based on that field as this is a short cut for Table1.FieldName->Table2.FieldName
                        //This is the format of most PK-FK anyway.
                        if (entity.Fields.Count(x => x.IsPrimaryKey) == 1)
                        {
                            var pk = entity.Fields.FirstOrDefault(x => x.IsPrimaryKey);
                            var fk = foreignEntity.Fields.FirstOrDefault(x => x.Name == pk.Name);
                            if (fk != null)
                            {
                                relation.Id = Guid.NewGuid();
                                relation.Fields.Add(new RelationFieldYaml
                                {
                                    ForeignFieldId = fk.Id,
                                    ForeignFieldName = fk.Name,
                                    PrimaryFieldId = pk.Id,
                                    PrimaryFieldName = pk.Name,
                                });
                            }
                        }

                        if (!relation.Fields.Any())
                            throw new ModelException($"Entity: '{entity.Name}': The relation must have at least one field.");
                    }

                    relation.ForeignEntityName = foreignEntity.Name;
                    relation.ForeignEntityId = foreignEntity.Id;
                    foreach (var field in relation.Fields)
                    {
                        var primaryField = entity.Fields.FirstOrDefault(x => x.Id == field.PrimaryFieldId);
                        if (field.PrimaryFieldId == Guid.Empty)
                            primaryField = entity.Fields.FirstOrDefault(x => x.Name?.ToLower() == field.PrimaryFieldName?.ToLower());

                        var foreignField = foreignEntity.Fields.FirstOrDefault(x => x.Id == field.ForeignFieldId);
                        if (field.ForeignFieldId == Guid.Empty)
                            foreignField = foreignEntity.Fields.FirstOrDefault(x => x.Name?.ToLower() == field.ForeignFieldName?.ToLower());

                        if (primaryField == null)
                            throw new ModelException($"Entity: '{entity.Name}': The relation primary field must map to an existing field.");

                        if (foreignField == null)
                            throw new ModelException($"Entity: '{entity.Name}': The relation foreign field must map to an existing field.");

                        field.PrimaryFieldId = primaryField.Id;
                        field.PrimaryFieldName = primaryField.Name;

                        field.ForeignFieldId = foreignField.Id;
                        field.ForeignFieldName = foreignField.Name;
                    }
                }
                #endregion
            }
        }

        private static T GetObject<T>(string fileName)
        {
            var reader = new System.Xml.Serialization.XmlSerializer(typeof(T));
            using (var file = new System.IO.StreamReader(fileName))
            {
                return (T)reader.Deserialize(file);
            }
        }

        private static T GetYamlObject<T>(string fileName)
        {
            try
            {
                return File.ReadAllText(fileName).FromYaml<T>();
            }
            catch (YamlDotNet.Core.YamlException ex)
            {
                throw new ModelFileLoadException($"Yaml load error '{fileName}': " + ex.Message);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static void Save2(string rootFolder, string modelName, DiskModelYaml model)
        {
            FixupModel(model);

            var modelFolder = GetModelFolder(rootFolder, modelName.Replace(".nhydrate", ".model"));
            if (modelName.EndsWith(ModelExtension))
                modelFolder = rootFolder;

            var generatedFileList = new List<string>();
            SaveViewsYaml(modelFolder, model, generatedFileList); //must come before entities
            SaveEntitiesYaml(modelFolder, model, generatedFileList);

            //Save the global model properties
            SaveYamlObject(model.ModelProperties, Path.Combine(modelFolder, "model" + ModelExtension), generatedFileList);

            //Do not remove diagram file
            generatedFileList.Add(Path.Combine(modelFolder, "diagram.xml"));
            generatedFileList.Add(Path.Combine(modelFolder, "nhydrate.generators"));

            RemoveOrphans(modelFolder, generatedFileList);

            var folder = Path.Combine(modelFolder, FOLDER_OLD_ET);
            if (Directory.Exists(folder)) Directory.Delete(folder, true);
            folder = Path.Combine(modelFolder, FOLDER_OLD_VW);
            if (Directory.Exists(folder)) Directory.Delete(folder, true);

        }

        private static void SaveEntitiesYaml(string rootFolder, DiskModelYaml model, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            //Save Entities
            foreach (var obj in model.Entities)
            {
                var f = Path.Combine(folder, $"{obj.Name}.yaml".ToLower());
                SaveYamlObject(obj, f, generatedFileList);
            }
        }

        private static void SaveViewsYaml(string rootFolder, DiskModelYaml model, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_VW);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            //Save Views
            foreach (var obj in model.Views)
            {
                var f = Path.Combine(folder, $"{obj.Name}.yaml".ToLower());
                SaveYamlObject(obj, f, generatedFileList);
            }
        }

        private static void ConvertEntitiesOld2Yaml(string rootFolder, DiskModel model, DiskModelYaml model2)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            foreach (var obj in model.Entities)
            {
                var newEntity = model2.Entities.AddItem(new EntityYaml
                {
                    AllowCreateAudit = obj.allowcreateaudit != 0,
                    AllowModifyAudit = obj.allowmodifyaudit != 0,
                    AllowTimestamp = obj.allowtimestamp != 0,
                    CodeFacade = obj.codefacade,
                    GeneratesDoubleDerived = obj.generatesdoublederived != 0,
                    Id = obj.id.ToGuid(),
                    Immutable = obj.immutable != 0,
                    TypedTable = obj.typedentity.ToEnum<TypedTableConstants>(),
                    IsAssociative = obj.isassociative != 0,
                    IsTenant = obj.isTenant != 0,
                    Name = obj.name,
                    Schema = obj.schema,
                    Summary = obj.summary,
                });

                #region Fields
                foreach (var ff in obj.fieldset.OrderBy(x => x.sortorder))
                {
                    newEntity.Fields.AddItem(new EntityFieldYaml
                    {
                        CodeFacade = ff.codefacade,
                        DataFormatString = ff.dataformatstring,
                        Datatype = ff.datatype.ToEnum<DataTypeConstants>(),
                        Default = ff.@default,
                        DefaultIsFunc = ff.defaultisfunc != 0,
                        Formula = ff.formula,
                        Id = ff.id.ToGuid(),
                        Identity = ff.identity.ToEnum<IdentityTypeConstants>(),
                        IsCalculated = ff.Iscalculated != 0,
                        IsIndexed = ff.isindexed != 0,
                        IsPrimaryKey = ff.isprimarykey != 0,
                        IsReadonly = ff.isreadonly != 0,
                        IsUnique = ff.isunique != 0,
                        Length = ff.length,
                        Name = ff.name,
                        Nullable = ff.nullable != 0,
                        Obsolete = ff.obsolete != 0,
                        Scale = ff.scale,
                        Summary = ff.summary,
                    });
                }
                #endregion

                #region Indexes
                foreach (var ii in model.Indexes.Where(x => x.id == obj.id))
                {
                    foreach (var ifield in ii.index)
                    {
                        var newIndex = newEntity.Indexes.AddItem(new IndexYaml
                        {
                            Clustered = ifield.clustered != 0,
                            Id = ifield.id.ToGuid(),
                            ImportedName = ifield.importedname,
                            IndexType = (IndexTypeConstants)ifield.indextype,
                            IsUnique = ifield.isunique != 0,
                            Summary = ifield.summary,
                        });

                        foreach (var i2 in ifield.indexcolumnset.OrderBy(x => x.sortorder))
                        {
                            newIndex.Fields.AddItem(new IndexFieldYaml
                            {
                                Ascending = i2.ascending != 0,
                                FieldId = i2.fieldid.ToGuid(),
                                FieldName = newEntity.Fields.FirstOrDefault(x => x.Id == i2.fieldid.ToGuid())?.Name,
                                //Id = i2.id.ToGuid(),
                            });
                        }
                    }
                }
                #endregion

                #region Static data
                foreach (var sd in model.StaticData.Where(x => x.id == obj.id))
                {
                    foreach (var dd in sd.data.OrderBy(x => x.orderkey))
                    {
                        newEntity.StaticData.AddItem(new StaticDataYaml
                        {
                            ColumnId = dd.columnkey.ToGuid(),
                            Value = dd.value,
                            SortOrder = dd.orderkey,
                        });
                    }
                }
                #endregion
            }

            #region Relations (After all entities are loaded)

            foreach (var obj in model.Entities)
            {
                var newEntity = model2.Entities.First(x => x.Id == new Guid(obj.id));
                foreach (var rr in model.Relations.Where(x => x.id == obj.id))
                {
                    foreach (var relation in rr.relation)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.id == rr.id);
                        var entity2 = model.Entities.FirstOrDefault(x => x.id == relation.childid);
                        var newRelation = newEntity.Relations.AddItem(new RelationYaml
                        {
                            Id = relation.id.ToGuid(),
                            ForeignEntityName = entity2.name,
                            ForeignEntityId = entity2.id.ToGuid(),
                        });
                        newRelation.IsEnforced = relation.isenforced != 0;
                        newRelation.DeleteAction = relation.deleteaction.ToEnum<DeleteActionConstants>();
                        newRelation.RoleName = relation.rolename;
                        newRelation.Summary = relation.summary;
                        foreach (var fsi in relation.relationfieldset)
                        {
                            var newRelationField = new RelationFieldYaml
                            {
                                //Id = fsi.id.ToGuid(),
                                PrimaryFieldId = fsi.sourcefieldid.ToGuid(),
                                PrimaryFieldName = entity.fieldset.FirstOrDefault(x => x.id == fsi.sourcefieldid)?.name,
                                ForeignFieldId = fsi.targetfieldid.ToGuid(),
                                ForeignFieldName = entity2.fieldset.FirstOrDefault(x => x.id == fsi.targetfieldid)?.name,
                            };
                            newRelation.Fields.AddItem(newRelationField);
                        }
                    }
                }
            }
            #endregion
        }

        private static void ConvertViewsOld2Yaml(string rootFolder, DiskModel model, DiskModelYaml model2)
        {
            var folder = Path.Combine(rootFolder, FOLDER_VW);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            //Views
            foreach (var obj in model.Views)
            {
                var newView = model2.Views.AddItem(new ViewYaml
                {
                    CodeFacade = obj.codefacade,
                    GeneratesDoubleDerived = obj.generatesdoublederived != 0,
                    Id = obj.id.ToGuid(),
                    Sql = obj.sql,
                    Name = obj.name,
                    Schema = obj.schema,
                    Summary = obj.summary,
                });

                //Fields
                foreach (var ff in obj.fieldset)
                {
                    newView.Fields.AddItem(new ViewFieldYaml
                    {
                        CodeFacade = ff.codefacade,
                        Datatype = ff.datatype.ToEnum<DataTypeConstants>(),
                        Default = ff.@default,
                        Id = ff.id.ToGuid(),
                        IsPrimaryKey = ff.isprimarykey != 0,
                        Length = ff.length,
                        Name = ff.name,
                        Nullable = ff.nullable != 0,
                        Scale = ff.scale,
                        Summary = ff.summary,
                    });
                }
            }
        }

        //private static void SaveObject<T>(T obj, string fileName, List<string> generatedFileList)
        //{
        //    var ns = new XmlSerializerNamespaces();
        //    ns.Add("", "");
        //    var writer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        //    using (var wfile = new System.IO.StreamWriter(fileName))
        //    {
        //        writer.Serialize(wfile, obj, ns);
        //    }
        //    generatedFileList.Add(fileName);
        //}

        private static void SaveYamlObject<T>(T obj, string fileName, List<string> generatedFileList)
        {
            var yaml = obj.ToYaml();
            File.WriteAllText(fileName, yaml);
            generatedFileList.Add(fileName);
        }

        #region Private Helpers

        private static string GetModelFolder(string rootFolder, string modelName)
        {
            return Path.Combine(rootFolder, "_" + modelName);
        }

        //private static void WriteFileIfNeedBe(string fileName, string contents, List<string> generatedFileList)
        //{
        //    if (fileName.ToLower().EndsWith(".xml"))
        //    {
        //        generatedFileList.Add(fileName);
        //        try
        //        {
        //            //Load formatted original XML
        //            var origXML = string.Empty;
        //            if (File.Exists(fileName))
        //            {
        //                var xmlText = File.ReadAllText(fileName);
        //                if (!string.IsNullOrEmpty(xmlText))
        //                {
        //                    var documentCheck = new XmlDocument();
        //                    documentCheck.LoadXml(xmlText);
        //                    origXML = documentCheck.ToIndentedString();
        //                }
        //            }

        //            //Load formatted new XML
        //            var newXML = string.Empty;
        //            {
        //                var documentCheck = new XmlDocument();
        //                documentCheck.LoadXml(contents);
        //                newXML = documentCheck.ToIndentedString();
        //            }

        //            if (origXML == newXML)
        //                return;
        //            else
        //                contents = newXML;
        //        }
        //        catch (Exception ex)
        //        {
        //            //If there is an error then process like a non-XML file
        //            //Do Nothing
        //        }
        //    }
        //    else
        //    {
        //        //Check if this is the same content and if so do nothing
        //        generatedFileList.Add(fileName);
        //        if (File.Exists(fileName))
        //        {
        //            var t = File.ReadAllText(fileName);
        //            if (t == contents)
        //                return;
        //        }
        //    }

        //    File.WriteAllText(fileName, contents);
        //}

        //private static void WriteReadMeFile(string folder, List<string> generatedFileList)
        //{
        //    var f = Path.Combine(folder, "ReadMe.nHydrate.txt");
        //    WriteFileIfNeedBe(f, "This is a managed folder of a nHydrate model. You may change '*.configuration.xml' and '*.sql' files in any text editor if desired but do not add or remove files from this folder. This is a distributed model and making changes can break the model load.", generatedFileList);
        //}

        private static void RemoveOrphans(string rootFolder, List<string> generatedFiles)
        {
            //Only get these specific folder in case there is version control or some other third-party application running
            //Only touch the files we know about
            var files = new List<string>();
            files.AddRange(Directory.GetFiles(rootFolder, "*.*", SearchOption.TopDirectoryOnly));
            files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "entities"), "*.*", SearchOption.TopDirectoryOnly));
            files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "views"), "*.*", SearchOption.TopDirectoryOnly));

            if (Directory.Exists(Path.Combine(rootFolder, "_Entities")))
                files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "_Entities"), "*.*", SearchOption.TopDirectoryOnly));
            if (Directory.Exists(Path.Combine(rootFolder, "_Views")))
                files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "_Views"), "*.*", SearchOption.TopDirectoryOnly));

            files.ToList().ForEach(x => x = x.ToLower());
            generatedFiles.ToList().ForEach(x => x = x.ToLower());

            foreach (var f in files)
            {
                var fi = new FileInfo(f);
                if (generatedFiles.Contains(f))
                {
                    //Skip
                }
                else
                {
                    File.Delete(f);
                }
            }
        }

        //private static string ToIndentedString(this XmlDocument doc)
        //{
        //    var stringWriter = new StringWriter(new StringBuilder());
        //    var xmlTextWriter = new XmlTextWriter(stringWriter)
        //    {
        //        Formatting = Formatting.Indented,
        //        IndentChar = '\t'
        //    };
        //    doc.Save(xmlTextWriter);
        //    var t = stringWriter.ToString();
        //    t = t.Replace(@" encoding=""utf-16""", string.Empty);
        //    return t;
        //}

        private static void RemoveNullStrings(object obj)
        {
            foreach (var propertyInfo in obj.GetType().GetProperties())
            {
                if (propertyInfo.PropertyType == typeof(string))
                {
                    var v = propertyInfo.GetValue(obj);
                    if (v == null)
                        propertyInfo.SetValue(obj, string.Empty);
                }
            }

        }
        #endregion

    }
}


text:
<?php

class PatientTreatment extends \Eloquent {
	protected $table = 'patient_treatments';
	protected $primaryKey = array('treatment_id','patient_process_timetable_id');
	public $timestamps = false;
	protected $fillable = array(
		'treatment_id','patient_process_timetable_id'
		);

}

redpajama_set_name: RedPajamaGithub


text:
package benchmark;

import model.lookup.AbstractBuilderAlgorithm;
import model.lookup.Circuit;

import java.util.ArrayList;
import java.util.List;

public class PopulationFactory {
	private AbstractBuilderAlgorithm lookup;

	public PopulationFactory(AbstractBuilderAlgorithm lookup) {
		this.lookup = lookup;
	}

	public List<Circuit> manufacture(int populationSize) {
		ArrayList<Circuit> population = new ArrayList<>();
		for(int i = 0; i < populationSize; i++) {
			population.add(lookup.run());
		}
		return population;
	}
}


text:
package edu.reins.mongocloud.monitor.daemon;

import edu.reins.mongocloud.Context;
import edu.reins.mongocloud.Daemon;
import edu.reins.mongocloud.EventBus;
import edu.reins.mongocloud.cluster.*;
import edu.reins.mongocloud.instance.Instance;
import edu.reins.mongocloud.instance.InstanceReport;
import edu.reins.mongocloud.monitor.Monitor;
import edu.reins.mongocloud.support.annotation.Nothrow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Daemon
@Slf4j
public class RsAutoscaler {
    private static final int CPU_UTILIZATION_HIGH = 70;
    private static final int CPU_UTILIZATION_LOW = 30;
    private static final int MINIMUM_RS_SIZE = 3;

    @Autowired
    private Monitor monitor;

    @Autowired
    private Context context;

    @Autowired
    private EventBus eventBus;

    @Value("${instance.data.definition.disk}")
    private int capacity;

    @Nothrow
    @Scheduled(fixedDelay = 60 * 1000)
    public void exec() {
        monitor.getClusters().stream()
                .map(id -> context.getClusters().get(id))
                .filter(c -> c instanceof ReplicaCluster)
                .forEach(this::tryScaling);
    }

    @Nothrow
    private void tryScaling(final Cluster cluster) {
        final ClusterReport report = cluster.getReport();

        if (isResourceDeficient(cluster)) {
            scaleOut(cluster);
        } else if (isResourceSuperfluous(cluster)) {
            scaleIn(cluster);
        }
    }

    @Nothrow
    private boolean isResourceDeficient(final Cluster cluster) {
        return cluster.getInstances().stream()
                .map(Instance::getReport)
                .mapToInt(InstanceReport::getCpuPercent)
                .allMatch(percent -> percent > CPU_UTILIZATION_HIGH);
    }

    @Nothrow
    private boolean isResourceSuperfluous(final Cluster cluster) {
        final List<Instance> instances = cluster.getInstances();

        if (instances.size() > MINIMUM_RS_SIZE) {
            return instances.stream()
                    .map(Instance::getReport)
                    .mapToInt(InstanceReport::getCpuPercent)
                    .allMatch(percent -> percent < CPU_UTILIZATION_LOW);
        }

        return false;
    }

    @Nothrow
    private void scaleOut(final Cluster cluster) {
        LOG.info("scaleOut(rs: {}, from: {}, to: {})",
                cluster.getID(), cluster.getInstances().size(), cluster.getInstances().size() + 1);

        eventBus.post(new ClusterEvent(cluster.getID(), ClusterEventType.SCALE_OUT));
    }

    @Nothrow
    private void scaleIn(final Cluster cluster) {
        LOG.info("scaleIn(rs: {}, from: {}, to: {})",
                cluster.getID(), cluster.getInstances().size(), cluster.getInstances().size() - 1);

        eventBus.post(new ClusterEvent(cluster.getID(), ClusterEventType.SCALE_IN));
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<cell xmlns="http://docs.rackspacecloud.com/servers/api/v1.0" username="username3" rpc_host="None" type="child" name="cell3" rpc_port="None"/>


text:
import textwrap

######
# START IMPORTANT METHODS
######

 # Returns a list (see below) of all matching sequences in the given scaffold
 # with a given initial search length.
 # Returns: [search_length, (start_index, end_index), ...]
def find_matching_seqs(scaffold, sequence, initialSearchLength=5):
    searchLength = initialSearchLength - 1
    outputList = []
    workList = []
    while True:
        searchLength += 1
        outputList = workList
        workList = []
        for start in substrings(scaffold, sequence[:searchLength]):
            workList.append((start, start+searchLength))
        if len(workList)==0:
            outputList.insert(0, searchLength-1)
            return outputList

 # Returns a codon sequence for a given RNA sequence
def to_codon(seq):
    cDict = codon_dict()
    output = ""
    s = split_by_n(seq, 3)
    for codon in s:
        if cDict.get(codon) != None:
            if cDict[codon] == "Stop":
                break
            else:
                output += cDict[codon]
    return output

 # Transcribes DNA into RNA, returning an RNA seq
def transcribe_DNA(seq):
    rna = ''
    for c in seq:
        if c == 'T':
            rna += 'U'
        else:
            rna += c
    return rna

 # Transcribes RNA back into DNA
def RNA_to_DNA(seq):
    dna = ''
    for c in seq:
        if c == 'U':
            dna += 'T'
        else:
            dna += c
    return dna

######
# START UTILITY METHODS
######

 # generator for fasta files - returns (name, seq)
 # Call using 'with open(file) as f'
def read_fasta(fileHandle):
    title = None
    data = None
    for line in fileHandle:
        if line[0]==">":
            if title != None:
                yield (title,data)
            title = line[1:]
            data = ''
        else:
            data += line.strip()
    if title == None:
        yield None
    yield (title,data)

 # Takes a list of [(title, seq), ...] tuples and prints as a FASTA file
 # to the given filename
def write_fasta(listOfTuples, fileName):
    output = ""
    if fileName.find(".txt",0) == -1:
        fileName += ".txt"
    for data in listOfTuples:
        output += (">" + data[0])
        output += textwrap.fill(data[1], 70)
        output += "\n"
    with open(fileName, 'w') as outFile:
        outFile.write(output)

 # Generates list of locations of all substrings in seq
def substrings(seq, sub):
    start = 0
    while True:
        start = seq.find(sub, start)
        if start == -1:
            break
        else:
            yield start
            start += 1

 # Generates sequence split by n units
def split_by_n(seq, n):
    while seq:
        yield seq[:n]
        seq = seq[n:]

 # Returns a codon dict, used in to_codon
def codon_dict(): return file_to_dict("codons.txt")

 # Creates dicts from two-cell tables in txt files
def file_to_dict(file):
    mDict = {}
    with open(file) as f:
        lines = f.readlines()
        for l in lines:
            mList = l.split()
            mDict[mList[0]] = mList[1]
    return mDict

######
# START I/O METHODS
######

 # Returns a single tuple (head, name) for a given fasta file
 # In other words, gets the first fasta entry from a fasta file
def fasta_to_strings(fileName):
    with open(fileName, encoding="cp1252") as f:
        for name, seq in read_fasta(f):
            return (name, seq)

 # Called when search returns only a single result. Uses filename
 # and desired sequence length from user and outputs fasta file with
 # region upstream of found sequence
def single_result(length, start, searchName, scaffoldSeq, fileName, bp):
    print("Matching sequence of length " + str(length) +
          " found in scaffold at index " + str(start+1) + ".")
    x = start - int(bp)     # Makes sure the sequence doesn't wrap around the scaffold
    if x < 0:
        x = 0
    seq = scaffoldSeq[x:start]
    title = "Upstream of " + searchName + " from " + str(x) + " to " + str(start)
    title = title.replace("\n", "") + "\n"
    write_fasta([(title, seq)], fileName)
    print("File '" + fileName + "' saved.")

 # Called when sequenceSearch returns multiple results. Uses filename
 # and desired sequence length from user and outputs fasta file with
 # *all* seq upstream of found sequence
def multiple_result(length, startCodons, searchName, scaffoldSeq, fileName, bp):
    print("Multiple matching sequences found of length " + str(length))
    listOfTuples = []
    for i in range(1, len(startCodons)):
        start = startCodons[i][0]
        x = start - int(bp)     # Makes sure the sequence doesn't wrap around the scaffold
        if x < 0:
            x = 0
        title = "Upstream of " + searchName + " from " + str(x) + " to " + str(start)
        title = title.replace("\n", "") + "\n"
        seq = scaffoldSeq[x:start]
        listOfTuples.append((title, seq))
    write_fasta(listOfTuples, fileName)
    print("File '" + fileName + "' saved.")

 # Searches in the scaffold for a given sequence. If it finds a sequence, allows
 # the user to output a sequence upstream of the start position in the scaffold
 # as a file.
def sequence_search():

    print("Sequence search.")
    print()

        # Gets search and scaffold seq, adds .txt to names
    scaffoldFasta = input("Input scaffold's fasta filename: \n")
    searchFasta = input("Input search sequence's filename: \n")
    if scaffoldFasta.find(".txt",0) == -1: scaffoldFasta += ".txt"
    if searchFasta.find(".txt",0) == -1: searchFasta += ".txt"

        # Builds a tuple of (name, seq) out of each fasta w/ uppercase seq
    scaffold = fasta_to_strings(scaffoldFasta)
    search = fasta_to_strings(searchFasta)
    searchSeq = search[1].upper()
    scaffoldSeq = RNA_to_DNA(scaffold[1].upper())

        # Runs search
    startCodons = find_matching_seqs(scaffoldSeq, searchSeq)

        # Gets desired filename and length of upstream region to be returned
    fileName = input("What would you like to name the output fasta file? \n")
    bp = input("How many base pairs upstream would you like to find? \n")

        # Sets clear variables for search sequence's name and length
    searchName = search[0]
    length = startCodons[0]

        # If only one result found, output in fasta file
    if len(startCodons) == 2:
        start = startCodons[1][0]
        single_result(length, start, searchName, scaffoldSeq, fileName, bp)

        # If multiple results found, all are output in a single fasta file
    elif len(startCodons) > 2:
        multiple_result(length, startCodons, searchName, scaffoldSeq, fileName, bp)

        # In other cases, return no results
    else:
        print("No results found.")

    # Called in positionSearch to get correct list of positions from user.
    # If position is greater than given max integer or less than zero,
    # called recursively to get new list of integers.
def get_positions(max):
    inputPositions = input()
    positions = [int(x) for x in inputPositions.split(',')]
    for p in positions:
        if ((p < 0) or (p > max)):
            print("Position " + str(p) + " not in range of scaffold. Enter new position(s):")
            getPositions(max)
    return positions

 # Called in position_search. Uses filename
 # and desired sequence length from user and outputs fasta file with *all* seq X
 # bp upstream of found sequence
def position_result(positions, scaffoldName, scaffoldSeq, fileName, bp):
    listOfTuples = []
    for i in range(0, len(positions)):
        start = positions[i]
        x = start - int(bp)     # Makes sure the sequence doesn't wrap around the scaffold
        if x < 0:
            x = 0
        title = scaffoldName + " from bp " + str(x) + " to " + str(start)
        title = title.replace("\n", "") + "\n"
        seq = scaffoldSeq[x:start]
        listOfTuples.append((title, seq))
    write_fasta(listOfTuples, fileName)
    print("File '" + fileName + "' saved.")

    # Searches in the scaffold for given positions. Allows the user
    # to output a sequence upstream of the positions as a file.
def position_search():

    print("Position search.")
    print()

        # Gets scaffold seq and adds .txt to name
    scaffoldFasta = input("Input scaffold's fasta filename: \n")
    if scaffoldFasta.find(".txt",0) == -1: scaffoldFasta += ".txt"

        # Builds (name, seq) tuple of scaffold and changes seq to uppercase
    scaffold = fasta_to_strings(scaffoldFasta)
    scaffoldName = scaffold[0]
    scaffoldSeq = RNA_to_DNA(scaffold[1].upper())

        # Gets scaffold position to find the upstream region of
    print("Enter position(s) to find, separated by commas: ")
    positions = get_positions(len(scaffoldSeq))

        # Gets desired filename and length of upstream region to be returned
    fileName = input("What would you like to name the output fasta file? \n")
    bp = input("How many base pairs upstream would you like to find? \n")

        # Outputs all desired sequences in a single fasta file
    position_result(positions, scaffoldName, scaffoldSeq, fileName, bp)

def main():

        # Prints a nicely formatted introduction
    introText = '''Searches inside a scaffold DNA/RNA sequence for either positions
    in the scaffold or the start position of a given sequence in the
    scaffold. Outputs a region upstream of the found position(s) of a
    given length as a FASTA file.'''
    intro = textwrap.wrap(introText)
    for line in intro:
        print(line)

    print()
    print("Are you searching by position or with a sequence?")
    print("1: Position     2: Sequence")

    searchType = input("")
    if (searchType=="1") or (searchType=="Position") or (searchType=="position") or (searchType=="pos"):
        position_search()
    elif (searchType=="2") or (searchType=="Sequence") or (searchType=="sequence") or (searchType=="seq"):
        sequence_search()

main()


text:
CVE-2021-29615

### Impact
The implementation of
[`ParseAttrValue`](https://github.com/tensorflow/tensorflow/blob/c22d88d6ff33031aa113e48aa3fc9aa74ed79595/tensorflow/core/framework/attr_value_util.cc#L397-L453)
can be tricked into stack overflow due to recursion by giving in a specially
crafted input.

### Patches
We have patched the issue in GitHub commit
[e07e1c3d26492c06f078c7e5bf2d138043e199c1](https://github.com/tensorflow/tensorflow/commit/e07e1c3d26492c06f078c7e5bf2d138043e199c1).

The fix will be included in TensorFlow 2.5.0. We will also cherrypick this
commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow
2.1.4, as these are also affected and still in supported range.

### For more information
Please consult [our security
guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for
more information regarding the security model and how to contact us with issues
and questions.


text:
package com.yogee.zhebuy.interfaces.common;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yogee.zhebuy.common.config.Global;
import com.yogee.zhebuy.common.persistence.annotation.ApiVersion;
import com.yogee.zhebuy.common.utils.Hashids;
import com.yogee.zhebuy.common.utils.StringUtils;
import com.yogee.zhebuy.interfaces.util.HttpResultUtil;
import com.yogee.zhebuy.interfaces.util.HttpServletRequestUtils;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyCart;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyProItemMerchant;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyProSpecify;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyProUnit;
import com.yogee.zhebuy.modules.ebuy.service.EbuyCartService;
import com.yogee.zhebuy.modules.ebuy.service.EbuyProItemMerchantService;
import com.yogee.zhebuy.modules.ebuy.service.EbuyProSpecifyService;
import com.yogee.zhebuy.modules.ebuy.service.EbuyProUnitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("${apiPath}/{version}")
public class CartInterface {
    private static final Logger logger = LoggerFactory.getLogger(CartInterface.class);

    //用于对id进行加密
    private Hashids hashids = new Hashids(Global.getConfig("web.hashids.salt"));

    @Autowired
    EbuyProItemMerchantService ebuyProItemMerchantService;

    @Autowired
    EbuyCartService ebuyCartService;

    @Autowired
    EbuyProUnitService ebuyProUnitService;

    @Autowired
    EbuyProSpecifyService ebuyProSpecifyService;

    /**
     * 加入购物车
     * @param request
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "addItemToCart", method = RequestMethod.POST)
    @ResponseBody
    public synchronized String addItemToCart(HttpServletRequest request) {
        logger.info("app addItemToCart---------- Start--------");
        Map dataMap = Maps.newHashMap();
        Map jsonData = HttpServletRequestUtils.readJsonData(request);
        //非空校验
        String userId = (String) jsonData.get("userId");
        if (StringUtils.isEmpty(userId)) {
            logger.error("缺少userid!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }else {
            userId = hashids.decode(userId)[0]+"";
        }
        String sellerId = (String) jsonData.get("sellerId");
        if (StringUtils.isEmpty(sellerId)) {
            logger.error("缺少sellerId!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }else {
            sellerId = hashids.decode(sellerId)[0]+"";
        }
        String itemId = (String) jsonData.get("itemId");
        if (StringUtils.isEmpty(itemId)) {
            logger.error("缺少itemId!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }
        String itemSpecify = (String) jsonData.get("itemSpecify");
        if (StringUtils.isEmpty(itemSpecify)) {
            logger.error("缺少itemSpecify!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }
        String itemPrice = (String) jsonData.get("itemPrice");
        if (StringUtils.isEmpty(itemPrice)) {
            logger.error("缺少itemPrice!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }
        String buyCount = (String) jsonData.get("buyCount");
        if (StringUtils.isEmpty(buyCount)) {
            logger.error("缺少buyCount!");
            return HttpResultUtil.errorJson("加入购物车异常!");
        }

        EbuyCart cart = ebuyCartService.findByUserIdItemId(userId,itemId,itemSpecify,sellerId);
        //如果购买数量小于等于0 则从购物车删除该商品
        if (Integer.parseInt(buyCount) <= 0){
            ebuyCartService.delete(cart);
        }else {
//            //库存(废弃)
//            String item = ebuyProItemMerchantService.getItemCount(itemId,sellerId);
//            //库存和 购买数量对比
//            if (Integer.valueOf(item) < Integer.valueOf(buyCount)){
//                return HttpResultUtil.errorJson("仓库就剩这么多了!");
//            }
            //如果存在购物车,直接更新数量
            if (cart != null){
                cart.setBuyCount(buyCount);
                double total = new BigDecimal(itemPrice).multiply(new BigDecimal(buyCount)).doubleValue();
                cart.setTotalMoney(total+"");
                cart.setItemPrice(itemPrice);
                ebuyCartService.save(cart);
            }else {
                EbuyCart ebuyCart = new EbuyCart();
                ebuyCart.setBuyerId(Long.valueOf(userId));
                ebuyCart.setSellerId(Long.valueOf(sellerId));
                ebuyCart.setItemId(Long.valueOf(itemId));
                ebuyCart.setItemPrice(itemPrice);
                ebuyCart.setStatus("1");
                ebuyCart.setBuyCount(buyCount);
                ebuyCart.setItemSpecify(itemSpecify);
                double total = new BigDecimal(itemPrice).multiply(new BigDecimal(buyCount)).doubleValue();
                ebuyCart.setTotalMoney(total+"");
                ebuyCartService.save(ebuyCart);
            }
        }
        return HttpResultUtil.successJson(dataMap);
    }

    /**
     * 查看我的购物车
     * @param request
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "getMyCart", method = RequestMethod.POST)
    @ResponseBody
    public String getMyCart(HttpServletRequest request) {
        logger.info("app getMyCart---------- Start--------");
        Map dataMap = Maps.newHashMap();
        Map jsonData = HttpServletRequestUtils.readJsonData(request);
        //非空校验
        String userId = (String) jsonData.get("userId");
        if (StringUtils.isEmpty(userId)) {
            logger.error("缺少userId!");
            return HttpResultUtil.errorJson("购物车数据异常!");
        }else {
            userId = hashids.decode(userId)[0]+"";
        }
        List<EbuyCart> cartList = ebuyCartService.findListByUserId(userId);
        List cartLists = Lists.newArrayList();
        for (EbuyCart ebuyCart : cartList){
            Map itemMap = Maps.newHashMap();
            //获取商品规格
            EbuyProSpecify ebuyProSpecify =  ebuyProSpecifyService.get(ebuyCart.getItemSpecify());
            //获取商品信息
            EbuyProItemMerchant item = ebuyProItemMerchantService.getByItemidAndUserid(ebuyCart.getSellerId().toString(),ebuyCart.getItemId().toString(),ebuyCart.getItemSpecify());
            //如果商品被下架或已经删除则不取出来
            if (item == null){
                continue;
            }else {
                itemMap.put("cartId",ebuyCart.getId());
                itemMap.put("itemId",item.getItemId());
                String[] imgs = item.getItemImg().split("\\|");
                itemMap.put("itemImg",StringUtils.isEmpty(imgs[0]) ?  Global.getConfig("domain.url") + imgs[1] : Global.getConfig("domain.url") + imgs[0]);
                itemMap.put("itemName",item.getItemName());
                itemMap.put("itemPrice",ebuyCart.getItemPrice());
                itemMap.put("buyCount",ebuyCart.getBuyCount());
                itemMap.put("sellerId",hashids.encode(ebuyCart.getSellerId()));
                itemMap.put("itemSpecify",ebuyCart.getItemSpecify());
                itemMap.put("specCount",ebuyCart.getSpecCount());
                itemMap.put("specName",ebuyProSpecify.getSpecName());
                cartLists.add(itemMap);
            }
        }
        dataMap.put("cartList",cartLists);
        return HttpResultUtil.successJson(dataMap);
    }

    /**
     * 删除购物车商品
     * @param request
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "deleteItemToCart", method = RequestMethod.POST)
    @ResponseBody
    public String deleteItemToCart(HttpServletRequest request) {
        logger.info("app deleteItemToCart---------- Start--------");
        Map dataMap = Maps.newHashMap();
        Map jsonData = HttpServletRequestUtils.readJsonData(request);
        //非空校验
        String cartId = (String) jsonData.get("cartId");
        if (StringUtils.isEmpty(cartId)) {
            logger.error("缺少购物车id!");
            return HttpResultUtil.errorJson("缺少购物车id!");
        }
        EbuyCart ebuyCart = ebuyCartService.get(cartId);
        if (ebuyCart == null){
            return HttpResultUtil.errorJson("该商品不存在!");
        }
        ebuyCartService.delete(ebuyCart);
        return HttpResultUtil.successJson(dataMap);
    }

    /**
     * 清空购物车
     * @param request
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "clearCart", method = RequestMethod.POST)
    @ResponseBody
    public String clearCart(HttpServletRequest request) {
        logger.info("app clearCart---------- Start--------");
        Map dataMap = Maps.newHashMap();
        Map jsonData = HttpServletRequestUtils.readJsonData(request);
        //非空校验
        String userId = (String) jsonData.get("userId");
        if (StringUtils.isEmpty(userId)) {
            logger.error("缺少userid!");
            return HttpResultUtil.errorJson("缺少userid!");
        }else {
            userId = hashids.decode(userId)[0]+"";
        }
        ebuyCartService.deleteCartByUserId(userId);
        return HttpResultUtil.successJson(dataMap);
    }

}


text:
jest.mock('../../services/pageService');
jest.mock('../../utils');
import pageActions from '../pageActions';
import utils from "../../utils";
import PagesService from "../../services/pageService";

describe('Dnn Page Actions', () => {
    it('Redirects when parent page is deleted and the child page is the current page', done => {
        // Arrange
        const pageToDelete = {
            tabId: 1,
            hasChild: true
        };
        const defaultUrl = 'http://localhost';
        const redirectUrl = 'http://localhost/test';
        PagesService.deletePage.mockResolvedValue({});
        PagesService.getPageHierarchy.mockResolvedValue([1, 2]);
        utils.getCurrentPageId.mockReturnValue(2);
        utils.getDefaultPageUrl.mockReturnValue(redirectUrl);
        delete window.top.location;
        window.top.location = new URL(defaultUrl);
        Object.defineProperty(window.top.location, 'href', {
            set: (value) => {
                // Assert
                expect(value).toBe(redirectUrl)
                done();
            }
        });
        expect.assertions(1);

        // Act
        pageActions.deletePage(pageToDelete, null)(() => {});
    });
});


text:
//@Filename: file.tsx
// @jsx: preserve
// @noLib: true

//// declare module JSX {
////     interface Element { }
////     interface IntrinsicElements {
////     }
////     interface ElementAttributesProperty { props; }
//// }
//// interface OptionPropBag {
////     propx: number
////     propString: string
////     optional?: boolean
//// }
//// [|declare function [|{| "isWriteAccess": true, "isDefinition": true, "contextRangeIndex": 0 |}Opt|](attributes: OptionPropBag): JSX.Element;|]
//// let opt = [|<[|{| "contextRangeIndex": 2 |}Opt|] />|];
//// let opt1 = [|<[|{| "contextRangeIndex": 4 |}Opt|] propx={100} propString />|];
//// let opt2 = [|<[|{| "contextRangeIndex": 6 |}Opt|] propx={100} optional/>|];
//// let opt3 = [|<[|{| "contextRangeIndex": 8 |}Opt|] wrong />|];
//// let opt4 = [|<[|{| "contextRangeIndex": 10 |}Opt|] propx={100} propString="hi" />|];

verify.singleReferenceGroup(
    "function Opt(attributes: OptionPropBag): JSX.Element",
    "Opt"
);


text:
Instructional material for our 2017 web development camp

Days | Concepts
-----|-----
Day 1 | [HTML](https://github.com/Fun2LearnCode/website-development-plans/tree/master/day-1)
Day 2 | [CSS](https://github.com/Fun2LearnCode/website-development-plans/tree/master/day-2)
Day 3 | [Javascript](https://github.com/Fun2LearnCode/website-development-plans/tree/master/day-3)
Day 4 | [Basic Website](https://github.com/Fun2LearnCode/website-development-plans/tree/master/day-4)
Day 5 | [Customization and Deployment](https://github.com/Fun2LearnCode/website-development-plans/tree/master/day-5)


text:
<?php

namespace comyii\user\models;

use Yii;
use yii\base\Model;
use comyii\user\Module;

/**
 * Model for the login form
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class LoginForm extends Model
{
    /**
     * @var string the username
     */
    public $username;

    /**
     * @var string the write only password
     */
    public $password;

    /**
     * @var string the new password (required for password change)
     */
    public $password_new;

    /**
     * @var string the new password confirmation
     * (required during reset and password change)
     */
    public $password_confirm;

    /**
     * @var bool whether to remember the user
     */
    public $rememberMe = true;

    /**
     * @var Module the module instance
     */
    private $_module;

    /**
     * @var array the settings
     */
    private $_settings = [];

    /**
     * @inheritdoc
     */
    public function init()
    {
        Module::validateConfig($this->_module);
        $this->_settings = $this->_module->loginSettings;
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
            // username and password are both required
            [['username', 'password', 'password_new', 'password_confirm'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // check if valid password
            ['password', 'validatePassword'],
            // validate password confirmation
            ['password_confirm', 'compare', 'compareAttribute' => 'password_new'],
            // validate password confirmation
            ['password_new', 'compare', 'operator' => '!=', 'compareAttribute' => 'password'],
        ];
        if ($this->_settings['loginType'] === Module::LOGIN_EMAIL) {
            $rules += ['username', 'email'];
        }
        return $rules;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        $label = Yii::t('user', 'Username or Email');
        if ($this->_settings['loginType'] === Module::LOGIN_USERNAME) {
            $label = Yii::t('user', 'Username');
        } elseif ($this->_settings['loginType'] === Module::LOGIN_EMAIL) {
            $label = Yii::t('user', 'Email');
        }
        return [
            'username' => $label,
            'password' => Yii::t('user', 'Password'),
            'rememberMe' => Yii::t('user', 'Remember Me'),
            'password_new' => Yii::t('user', 'New Password'),
            'password_confirm' => Yii::t('user', 'Confirm Password')
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     */
    public function validatePassword($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        $user = $this->getUser();
        if ($user === null) {
            $this->addError('username', Yii::t('user', 'Could not validate the credentials'));
            return;
        }
        if ($user->status_sec == Module::STATUS_LOCKED) {
            return;
        }
        $outcome = $user ? $user->validatePassword($this->$attribute) : null;
        if ($outcome !== null && !$outcome) {
            $user->checkFailedLogin();
        }
        $attempts = $this->_module->passwordSettings['wrongAttempts'];
        if (!$user || !$outcome) {
            if (empty($attempts)) {
                $this->addError($attribute, Yii::t('user', 'The password is incorrect'));
            } else {
                $this->addError(
                    $attribute,
                    Yii::t('user', 'The password is incorrect. {n, plural, one{One try} other{# tries}} left.', [
                        'n' => ($attempts - (int)$user->password_fail_attempts)
                    ])
                );
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @param User $user the user model
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login($user)
    {
        if (!empty($user->status_sec)) {
            return (int)$user->status_sec;
        }
        if ($user->status_sec == Module::STATUS_EXPIRED || $user->status_sec == Module::STATUS_LOCKED) {
            return $user->status_sec;
        }
        if ($user->isPasswordExpired()) {
            $user->status_sec = Module::STATUS_EXPIRED;
            $user->save(false);
            return Module::STATUS_EXPIRED;
        }
        if ($user->isLocked()) {
            $user->status_sec = Module::STATUS_LOCKED;
            $user->save(false);
            return Module::STATUS_LOCKED;
        }
        return Yii::$app->user->login($user, $this->rememberMe ? $this->_settings['rememberMeDuration'] : 0);
    }

    /**
     * Finds user by [[username]], [[email]], or both
     *
     * @return User|null
     */
    public function getUser()
    {
        /**
         * @var User $class
         */
        $class = $this->_module->modelSettings[Module::MODEL_USER];
        $loginType = $this->_settings['loginType'];
        if ($loginType === Module::LOGIN_USERNAME) {
            $user = $class::findByUsername($this->username);
        } elseif ($loginType === Module::LOGIN_EMAIL) {
            $user = $class::findByEmail($this->username);
        } else {
            $user = $class::findByUserOrEmail($this->username);
        }
        return $user;
    }

    /**
     * User model scenarios
     *
     * @return array
     */
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[Module::SCN_LOGIN] = ['username', 'password', 'email', 'rememberMe'];
        $scenarios[Module::SCN_EXPIRY] = ['username', 'password', 'password_new', 'password_confirm'];
        return $scenarios;
    }
}


text:
var fpsCounter = {
	name: "fpsCounter",

	show_counter: false,
	show_stats: false,
	max_samples: 100,
	last_fps: 0,
	show_on_console: false,

	buffer: [],

	init: function()
	{
		LiteGUI.menubar.add("View/FPS Counter", {  instance: fpsCounter , property: "show_counter", type:"checkbox", callback: fpsCounter.onEnableFPS });
		LiteGUI.menubar.add("View/Render Stats", {  instance: fpsCounter , property: "show_stats", type:"checkbox", callback: fpsCounter.onEnableStats });
		LEvent.bind( LS.GlobalScene, "afterRender", fpsCounter.frameRendered.bind(this) );
	},

	onEnableFPS: function(v)
	{
		if(fpsCounter.show_counter)
		{
			if(!fpsCounter.canvas)
				fpsCounter.createGraph();
			fpsCounter.canvas.style.display = "block";
		}
		else
		{
			if(fpsCounter.canvas)
				fpsCounter.canvas.style.display = "none";
		}
	},

	onEnableStats: function(v)
	{
		if(fpsCounter.show_stats)
		{
			if(!fpsCounter.stats)
				fpsCounter.createStats();
			fpsCounter.stats.style.display = "block";
		}
		else
		{
			if(fpsCounter.stats)
				fpsCounter.stats.style.display = "none";
		}
	},

	createGraph: function()
	{
		var canvas = createCanvas(this.max_samples + 20,80);
		canvas.style.position = "absolute";
		canvas.style.left = "10px";
		canvas.style.bottom = "10px";
		this.canvas = canvas;
		var root = document.getElementById("visor");
		if(root)
			root.appendChild(canvas);
		this.updateGraph();
	},

	createStats: function()
	{

		var stats = document.createElement("div");
		this.stats = stats;
		var root = document.getElementById("visor");
		if(root)
			root.appendChild(stats);
		stats.className = "stats-info";
		stats.style.position = "absolute";
		stats.style.left = "150px";
		stats.style.bottom = "10px";
	},

	updateGraph: function()
	{
		if(!this.canvas) return;
		var ctx = this.canvas.getContext("2d");
		ctx.clearRect(0,0,this.canvas.width, this.canvas.height );
		ctx.fillStyle = "rgba(0,0,0,0.5)";
		ctx.fillRect(0,0,this.canvas.width, this.canvas.height );
		if(!this.buffer.length) return;

		ctx.lineWidth = 1;

		ctx.strokeStyle = "rgba(255,255,255,0.4)";
		ctx.beginPath();
		ctx.moveTo(10.5, 10.5 );
		ctx.lineTo(this.canvas.width - 20.5, 10.5 );
		ctx.moveTo(10.5, this.canvas.height - 10.5 );
		ctx.lineTo(this.canvas.width - 20.5, this.canvas.height - 10.5 );
		ctx.stroke();

		for(var i = 0; i < this.buffer.length; i++)
		{
			var v = this.buffer[i];
			ctx.strokeStyle = v > 50 ? "#8F8" : ( v > 30 ? "#AD5" : (v > 20 ? "orange" : "red") );
			ctx.beginPath();
			ctx.moveTo(i + 10.5, this.canvas.height - 10.5 );
			ctx.lineTo(i + 10.5, this.canvas.height - 10.5 - Math.round(v) );
			ctx.stroke();
		}

		ctx.fillStyle = "white";
		ctx.strokeStyle = "black";
		ctx.font = "18px Arial";
		ctx.lineWidth = 2;
		ctx.strokeText( this.last_fps , this.canvas.width * 0.5 - 10, this.canvas.height - 10 );
		ctx.fillText( this.last_fps , this.canvas.width * 0.5 - 10, this.canvas.height - 10 );
	},

	updateStats: function()
	{
		if(!this.stats) return;
		this.stats.innerHTML = "RIs: " + LS.Renderer._visible_instances.length + " Visible: " + LS.Renderer._rendered_instances + " DrawCalls: " + LS.Renderer._rendercalls + "";
	},

	last_time: 0,
	frames: 0,

	frameRendered: function()
	{
		if(!this.show_counter && !this.show_stats)
			return;

		var now = new Date().getTime();
		var elapsed = now - this.last_time;

		if(this.show_stats)
			this.updateStats();

		this.frames++;

		if(elapsed > 1000)
		{
			this.last_fps = this.frames;
			this.buffer.push( this.last_fps );
			this.frames = 0;
			if(this.show_on_console) trace("FPS: " + this.last_fps );
			if(this.buffer.length > 100)
				this.buffer.shift();
			this.last_time = now;
			if(this.show_counter)
				this.updateGraph();
		}
	},
};

CORE.registerModule( fpsCounter );


text:
import { Injectable } from '@angular/core';

/**
 * local存储服务
 */
@Injectable()
export class LocalStorageService {

    public localStorage: any;

    constructor() {
        if (!localStorage) {
            throw new Error('浏览器不支持本地存储!');
        }else{
            this.localStorage = window.localStorage;
        }
    }

    public set(key: string, value: string): void {
        this.localStorage[key] = value;
    }

    public get(key: string): string {
        return this.localStorage[key] || false;
    }

    public setObject(key: string, value: any): void {
        this.localStorage[key] = JSON.stringify(value);
    }

    public getObject(key: string): any {
        return JSON.parse(this.localStorage[key] || '{}');
    }

    public remove(key: string): any {
        this.localStorage.removeItem(key);
    }
}


text:
#include "jsvar.h"

JsVar *jswrap_string_constructor(JsVar *a);
JsVar *jswrap_string_fromCharCode(JsVarInt code);
JsVar *jswrap_string_charAt(JsVar *parent, JsVarInt idx);
JsVarInt jswrap_string_charCodeAt(JsVar *parent, JsVarInt idx);
JsVarInt jswrap_string_indexOf(JsVar *parent, JsVar *v);
JsVar *jswrap_string_substring(JsVar *parent, JsVarInt pStart, JsVar *vEnd);
JsVar *jswrap_string_substr(JsVar *parent, JsVarInt pStart, JsVar *vLen);
JsVar *jswrap_string_split(JsVar *parent, JsVar *split);


text:
package org.onosproject.codec.impl;

import org.onosproject.codec.CodecContext;
import org.onosproject.codec.JsonCodec;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.intent.ConnectivityIntent;
import org.onosproject.net.intent.PointToPointIntent;

import com.fasterxml.jackson.databind.node.ObjectNode;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Point to point intent codec.
 */
public final class PointToPointIntentCodec extends JsonCodec<PointToPointIntent> {

    @Override
    public ObjectNode encode(PointToPointIntent intent, CodecContext context) {
        checkNotNull(intent, "Point to point intent cannot be null");

        final JsonCodec<ConnectivityIntent> connectivityIntentCodec =
                context.codec(ConnectivityIntent.class);
        final ObjectNode result = connectivityIntentCodec.encode(intent, context);

        final JsonCodec<ConnectPoint> connectPointCodec =
                context.codec(ConnectPoint.class);
        final ObjectNode ingress =
                connectPointCodec.encode(intent.ingressPoint(), context);
        final ObjectNode egress =
                connectPointCodec.encode(intent.egressPoint(), context);

        result.set("ingressPoint", ingress);
        result.set("egressPoint", egress);

        return result;
    }
}


text:
package org.http4s
package headers

import cats.syntax.traverse._
import org.http4s.Header
import org.http4s.Method
import org.http4s.ParseResult
import org.http4s.internal.parsing.Rfc7230
import org.typelevel.ci.CIString
import org.typelevel.ci.CIStringSyntax

object `Access-Control-Allow-Methods` {

  private[http4s] val parser =
    Rfc7230
      .headerRep(Rfc7230.token.map(CIString(_)))
      .mapFilter { list =>
        val parsedMethodList = list.traverse { ciMethod =>
          Method.fromString(ciMethod.toString).toOption
        }
        parsedMethodList.map(list => apply(list.toSet))
      }

  def parse(s: String): ParseResult[`Access-Control-Allow-Methods`] =
    ParseResult.fromParser(parser, "Invalid Access-Control-Allow-Methods header")(s)

  implicit val headerInstance: Header[`Access-Control-Allow-Methods`, Header.Recurring] =
    Header.createRendered(
      ci"Access-Control-Allow-Methods",
      _.methods,
      parse,
    )

  implicit val headerSemigroupInstance: cats.Semigroup[`Access-Control-Allow-Methods`] =
    (a, b) => `Access-Control-Allow-Methods`(a.methods ++ b.methods)
}

/** The `Access-Control-Allow-Methods` header. */
final case class `Access-Control-Allow-Methods`(methods: Set[Method])


text:
#pragma once

#include <exception>
#include <typeindex>

#include <folly/io/IOBuf.h>

#include "mcrouter/lib/McReply.h"
#include "mcrouter/lib/MessageStorage.h"

namespace facebook { namespace memcache {

class McRequest;

class McAsciiParser {
 public:
  enum class State {
    // The parser is not initialized to parse any messages.
    UNINIT,
    // Have partial message, and need more data to complete it.
    PARTIAL,
    // There was an error on the protocol level.
    ERROR,
    // Complete message had been parsed and ready to be returned.
    COMPLETE,
  };

  McAsciiParser();

  McAsciiParser(const McAsciiParser&) = delete;
  McAsciiParser(McAsciiParser&&) = delete;
  McAsciiParser& operator=(const McAsciiParser&) = delete;
  McAsciiParser& operator=(McAsciiParser&&) = delete;

  /**
   * Consume given IOBuf.
   *
   * Should be called only in case hasReadBuffer() returned false.
   *
   * @param buffer  data to consume.
   * @return  new parser state.
   */
  State consume(folly::IOBuf& buffer);

  /**
   * Prepares parser for parsing reply for given request type and operation.
   */
  template<class Operation, class Request>
  void initializeReplyParser();

  /**
   * Obtain the message that was parsed.
   *
   * Should be called by user to obtain reply after consume() returns
   * State::COMPLETE.
   *
   * @tparam T  type of expected reply.
   */
  template<class T>
  T getReply();

  State getCurrentState() { return state_; }

  /**
   * Check if McAsciiParser already has its own buffer.
   * @return  true iff we already have our own buffer that we can read into.
   */
  bool hasReadBuffer();

  std::pair<void*, size_t> getReadBuffer();

  void readDataAvailable(size_t length);
 private:
  void appendCurrentCharTo(folly::IOBuf& from, folly::IOBuf& to);
  void handleError(folly::IOBuf& buffer);

  void initializeCommon();

  void initializeArithmReplyCommon();
  void initializeStorageReplyCommon();

  void consumeArithmReplyCommon(folly::IOBuf& buffer);
  void consumeStorageReplyCommon(folly::IOBuf& buffer);

  template<class Msg, class Op>
  void consumeMessage(folly::IOBuf& buffer);

  uint64_t currentUInt_{0};
  folly::IOBuf* currentIOBuf_{nullptr};
  size_t remainingIOBufLength_{0};
  MessageStorage<List<McReply>> currentMessage_;
  State state_{State::UNINIT};

  // Variables used by ragel.
  int savedCs_;
  int errorCs_;
  const char* p_{nullptr};
  const char* pe_{nullptr};
  const char* eof_{nullptr};
  // Used solely for proper error messages parsing.
  bool stripped_{false};
  // Used in parsing of metaget requests (in particular ip addresses).
  std::unique_ptr<folly::IOBuf> ipBuffer_;

  using ConsumerFunPtr = void (McAsciiParser::*)(folly::IOBuf&);
  ConsumerFunPtr consumer_{nullptr};
};

template<class T>
T McAsciiParser::getReply() {
  assert(state_ == State::COMPLETE);
  state_ = State::UNINIT;
  return std::move(currentMessage_.get<T>());
}

// Forward-declare initializers.
template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_get>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_gets>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_lease_get>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_set>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_add>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_replace>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_lease_set>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_cas>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_incr>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_decr>, McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_version>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_delete>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_metaget>,
                                          McRequest>();

template<>
void McAsciiParser::initializeReplyParser<McOperation<mc_op_flushall>,
                                          McRequest>();

template<class Operation, class Request>
void McAsciiParser::initializeReplyParser() {
  throw std::logic_error(
    folly::sformat("Unexpected call to McAsciiParser::initializeReplyParser "
                   "with template arguments [Operation = {}, Request = {}]",
                   typeid(Operation).name(), typeid(Request).name()));
}

}}  // facebook::memcache


text:
import { expectTypeOf } from 'expect-type';

import Mixin from '@ember/object/mixin';

const newMixin = Mixin.create({
  foo: 'bar',
});

expectTypeOf(newMixin).toMatchTypeOf<Mixin>();


text:
package net.bis5.mattermost.client4.api;

import static net.bis5.mattermost.client4.Assertions.assertNoError;
import static net.bis5.mattermost.client4.Assertions.assertSameFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collections;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import net.bis5.mattermost.client4.MattermostClient;
import net.bis5.mattermost.client4.MattermostClientTest;
import net.bis5.mattermost.client4.MattermostClientTestExtension;
import net.bis5.mattermost.client4.TestHelper;
import net.bis5.mattermost.client4.model.FileUploadResult;
import net.bis5.mattermost.model.FileInfo;
import net.bis5.mattermost.model.Post;

// Files
@ExtendWith(MattermostClientTestExtension.class)
class FilesApiTest implements MattermostClientTest {
  private TestHelper th;
  private MattermostClient client;

  @Override
  public void setHelper(TestHelper helper) {
    this.th = helper;
  }

  @BeforeEach
  void setup() {
    client = createClient();
    th.changeClient(client).initBasic();
  }

  @AfterEach
  void tearDown() {
    th.logout();
    client.close();
  }

  @Test
  void uploadNoFileThrowsException() {
    String channelId = th.basicChannel().getId();
    assertThrows(IllegalArgumentException.class, () -> client.uploadFile(channelId));
  }

  @Test
  void uplaodFile() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    String channelId = th.basicChannel().getId();

    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();

    assertEquals(1, uploadResult.getFileInfos().length);
    assertEquals(filePath.getFileName().toString(), uploadResult.getFileInfos()[0].getName());
  }

  @Test
  void uploadMultipleFile() throws URISyntaxException, IOException {
    Path file1 = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    Path file2 = th.getResourcePath(TestHelper.EMOJI_CONSTRUCTION);
    String channelId = th.basicChannel().getId();

    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, file1, file2)).readEntity();

    assertEquals(2, uploadResult.getFileInfos().length);
    boolean foundFile1 = false;
    boolean foundFile2 = false;
    for (FileInfo fileInfo : uploadResult.getFileInfos()) {
      foundFile1 = foundFile1 || fileInfo.getName().equals(file1.getFileName().toString());
      foundFile2 = foundFile2 || fileInfo.getName().equals(file2.getFileName().toString());
    }
    assertTrue(foundFile1);
    assertTrue(foundFile2);
  }

  @Test
  void getFile() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath("/LICENSE.txt");
    String channelId = th.basicChannel().getId();
    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
    FileInfo fileInfo = uploadResult.getFileInfos()[0];
    String fileId = fileInfo.getId();

    Path receivedFile = assertNoError(client.getFile(fileId)).readEntity();

    assertSameFile(filePath, receivedFile);
  }

  @Test
  void getFileThumbnail() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    String channelId = th.basicChannel().getId();
    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
    FileInfo fileInfo = uploadResult.getFileInfos()[0];
    String fileId = fileInfo.getId();

    Path thumbnail = assertNoError(client.getFileThumbnail(fileId)).readEntity();

    assertTrue(thumbnail.toFile().exists());
  }

  @Test
  void getFilePreview() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    String channelId = th.basicChannel().getId();
    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
    FileInfo fileInfo = uploadResult.getFileInfos()[0];
    String fileId = fileInfo.getId();

    Path preview = assertNoError(client.getFilePreview(fileId)).readEntity();

    assertTrue(preview.toFile().exists());
  }

  @Test
  void getPublicFileLink() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    String channelId = th.basicChannel().getId();
    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
    FileInfo fileInfo = uploadResult.getFileInfos()[0];
    String fileId = fileInfo.getId();

    Post post = new Post(channelId, "file attached post");
    post.setFileIds(Collections.singletonList(fileId));
    post = assertNoError(client.createPost(post)).readEntity();

    String publicLink = assertNoError(client.getPublicFileLink(fileId)).readEntity();

    Client jaxrsClient = ClientBuilder.newClient();
    WebTarget target = jaxrsClient.target(publicLink);
    Response response = target.request().get();
    InputStream downloadFile = response.readEntity(InputStream.class);
    Path tempFile = Files.createTempFile(null, null);
    Files.copy(downloadFile, tempFile, StandardCopyOption.REPLACE_EXISTING);

    assertSameFile(filePath, tempFile);
  }

  @Test
  void getFileMetadata() throws URISyntaxException, IOException {
    Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
    String channelId = th.basicChannel().getId();
    FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
    FileInfo fileInfo = uploadResult.getFileInfos()[0];
    String fileId = fileInfo.getId();

    FileInfo metadata = assertNoError(client.getFileMetadata(fileId)).readEntity();
    assertEquals(filePath.getFileName().toString(), metadata.getName());
  }

}


text:
{% extends "layout.html" %}

{% block page_title %}
  GOV.UK prototype kit
{% endblock %}

{% block content %}

        Search address

      <form action="select-address" method="post">

          Postcode or first line of address
          <input type="text" name="postcode" id="postcode" class="form-control" value="">

          <input type="submit" class="button" value="Continue">

      </form>

{% endblock %}


text:
As seen on [http://www.studioamanga.com](http://www.studioamanga.com)

![StdAMG logo](http://www.studioamanga.com/onelist/img/amgmini.png)

Based on [scarpenter/command_line_haml](https://github.com/scarpenter/command_line_haml)


text:
#include <linux/init.h>
#include <linux/of_irq.h>

#include "irqchip.h"

/*
 * This special of_device_id is the sentinel at the end of the
 * of_device_id[] array of all irqchips. It is automatically placed at
 * the end of the array by the linker, thanks to being part of a
 * special section.
 */
static const struct of_device_id
irqchip_of_match_end __used __section(__irqchip_of_end);

extern struct of_device_id __irqchip_begin[];

void __init irqchip_init(void)
{
	of_irq_init(__irqchip_begin);
}


text:
using namespace std;

string node = "soo";
int nodenum = -1;
vector<string> codestream;
vector<symbol> symboltable;

bool symbol_search(string name)
{
    for (int symbol_index = 0; symbol_index < symboltable.size(); symbol_index++)
    {
        if (name == symboltable[symbol_index].symbolname)
            return true;
    }
    return false;
}

void symbol_insert(string name, var_type type)
{
    symbol newsymbol;
    newsymbol.symbolname=name;
    newsymbol.type=type;
    symboltable.push_back(newsymbol);
}

var_type symbol_gettype(string name)
{
    symbol get;
    for (int symbol_index=0; symbol_index<symboltable.size(); symbol_index++) {
        if(name==symboltable[symbol_index].symbolname)
            get=symboltable[symbol_index];
    }
    return get.type;
}

symbol symbol_getsymbol(string name)
{
    symbol nullsymbol;
    for(int symbol_index=0;symbol_index<symboltable.size();symbol_index++)
    {
        if(name==symboltable[symbol_index].symbolname)
            return symboltable[symbol_index];
    }
    return nullsymbol;
}
void error(string strerror)
{
    cout << "Error:"<<strerror << endl;
}

char * string2char(string str)
{
    return const_cast<char *>(str.c_str());
}

//get address label
string getsign(string choice)
{
    if (choice == "now")
    {
        stringstream s;
        string str;
        s << nodenum;
        s >> str;
        string sign = node + str;
        return sign;
    }
    else if (choice == "next")
    {
        nodenum++;
        stringstream s;
        string str;
        s << nodenum;
        s >> str;
        string sign = node + str;
        return sign;
    }
    else
        return "";
}

//key word
string keyword[]=
{
    //define
    "var",
    "def",
    //type
    "int",
    "string",
    //exp
    "if",
    "while",
    //system function
    "print"

};


text:
<?php

namespace Symfony\Bundle\TwigBundle\Tests\DependencyInjection;

use Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension;
use Symfony\Bundle\TwigBundle\Tests\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

class TwigExtensionTest extends TestCase
{
    public function testLoadEmptyConfiguration()
    {
        $container = $this->createContainer();
        $container->registerExtension(new TwigExtension());
        $container->loadFromExtension('twig', array());
        $this->compileContainer($container);

        $this->assertEquals('Twig_Environment', $container->getParameter('twig.class'), '->load() loads the twig.xml file');
        $this->assertContains('form_div_layout.html.twig', $container->getParameter('twig.form.resources'), '->load() includes default template for form resources');

        // Twig options
        $options = $container->getParameter('twig.options');
        $this->assertEquals(__DIR__.'/twig', $options['cache'], '->load() sets default value for cache option');
        $this->assertEquals('UTF-8', $options['charset'], '->load() sets default value for charset option');
        $this->assertEquals(false, $options['debug'], '->load() sets default value for debug option');
    }

    /**
     * @dataProvider getFormats
     */
    public function testLoadFullConfiguration($format)
    {
        $container = $this->createContainer();
        $container->registerExtension(new TwigExtension());
        $this->loadFromFile($container, 'full', $format);
        $this->compileContainer($container);

        $this->assertEquals('Twig_Environment', $container->getParameter('twig.class'), '->load() loads the twig.xml file');

        // Form resources
        $resources = $container->getParameter('twig.form.resources');
        $this->assertContains('form_div_layout.html.twig', $resources, '->load() includes default template for form resources');
        $this->assertContains('MyBundle::form.html.twig', $resources, '->load() merges new templates into form resources');

        // Globals
        $calls = $container->getDefinition('twig')->getMethodCalls();
        $this->assertEquals('foo', $calls[0][1][0], '->load() registers services as Twig globals');
        $this->assertEquals(new Reference('bar'), $calls[0][1][1], '->load() registers services as Twig globals');
        $this->assertEquals('pi', $calls[1][1][0], '->load() registers variables as Twig globals');
        $this->assertEquals(3.14, $calls[1][1][1], '->load() registers variables as Twig globals');

        // Yaml and Php specific configs
        if (in_array($format, array('yml', 'php'))) {
            $this->assertEquals('bad', $calls[2][1][0], '->load() registers variables as Twig globals');
            $this->assertEquals(array('key' => 'foo'), $calls[2][1][1], '->load() registers variables as Twig globals');
        }

        // Twig options
        $options = $container->getParameter('twig.options');
        $this->assertTrue($options['auto_reload'], '->load() sets the auto_reload option');
        $this->assertTrue($options['autoescape'], '->load() sets the autoescape option');
        $this->assertEquals('stdClass', $options['base_template_class'], '->load() sets the base_template_class option');
        $this->assertEquals('/tmp', $options['cache'], '->load() sets the cache option');
        $this->assertEquals('ISO-8859-1', $options['charset'], '->load() sets the charset option');
        $this->assertTrue($options['debug'], '->load() sets the debug option');
        $this->assertTrue($options['strict_variables'], '->load() sets the strict_variables option');
    }

    public function testGlobalsWithDifferentTypesAndValues()
    {
        $globals = array(
            'array'   => array(),
            'false'   => false,
            'float'   => 2.0,
            'integer' => 3,
            'null'    => null,
            'object'  => new \stdClass(),
            'string'  => 'foo',
            'true'    => true,
        );

        $container = $this->createContainer();
        $container->registerExtension(new TwigExtension());
        $container->loadFromExtension('twig', array('globals' => $globals));
        $this->compileContainer($container);

        $calls = $container->getDefinition('twig')->getMethodCalls();

        foreach ($calls as $call) {
            list($name, $value) = each($globals);
            $this->assertEquals($name, $call[1][0]);
            $this->assertSame($value, $call[1][1]);
        }
    }

    public function getFormats()
    {
        return array(
            array('php'),
            array('yml'),
            array('xml'),
        );
    }

    private function createContainer()
    {
        $container = new ContainerBuilder(new ParameterBag(array(
            'kernel.cache_dir' => __DIR__,
            'kernel.charset'   => 'UTF-8',
            'kernel.debug'     => false,
        )));

        return $container;
    }

    private function compileContainer(ContainerBuilder $container)
    {
        $container->getCompilerPassConfig()->setOptimizationPasses(array());
        $container->getCompilerPassConfig()->setRemovingPasses(array());
        $container->compile();
    }

    private function loadFromFile(ContainerBuilder $container, $file, $format)
    {
        $locator = new FileLocator(__DIR__.'/Fixtures/'.$format);

        switch ($format) {
            case 'php':
                $loader = new PhpFileLoader($container, $locator);
                break;
            case 'xml':
                $loader = new XmlFileLoader($container, $locator);
                break;
            case 'yml':
                $loader = new YamlFileLoader($container, $locator);
                break;
            default:
                throw new \InvalidArgumentException('Unsupported format: '.$format);
        }

        $loader->load($file.'.'.$format);
    }
}