Пример #1
0
        private static RecordBatch ArrowBasedCountCharacters(RecordBatch records)
        {
            StringArray nameColumn = records.Column("name") as StringArray;

            int characterCount = 0;

            for (int i = 0; i < nameColumn.Length; ++i)
            {
                string current = nameColumn.GetString(i);
                characterCount += current.Length;
            }

            int   ageFieldIndex = records.Schema.GetFieldIndex("age");
            Field ageField      = records.Schema.GetFieldByIndex(ageFieldIndex);

            // Return 1 record, if we were given any. 0, otherwise.
            int returnLength = records.Length > 0 ? 1 : 0;

            return(new RecordBatch(
                       new Schema.Builder()
                       .Field(ageField)
                       .Field(f => f.Name("name_CharCount").DataType(Int32Type.Default))
                       .Build(),
                       new IArrowArray[]
            {
                records.Column(ageFieldIndex),
                new Int32Array.Builder().Append(characterCount).Build()
            },
                       returnLength));
        }
Пример #2
0
    static void CreateLoggerFromConfig(string appenderName)
    {
        if (string.IsNullOrEmpty(appenderName))
        {
            return;
        }

        string name = appenderName.Substring(7);

        string options = ConfigMgr.GetDefaultValue(appenderName, "");

        if (string.IsNullOrEmpty(options))
        {
            Console.WriteLine("Log.CreateLoggerFromConfig: Missing config option Logger.{0}", name);
            return;
        }
        var tokens = new StringArray(options, ',');

        LogFilter type = name.ToEnum <LogFilter>();

        if (loggers.ContainsKey(type))
        {
            Console.WriteLine("Error while configuring Logger {0}. Already defined", name);
            return;
        }

        LogLevel level = (LogLevel)uint.Parse(tokens[0]);

        if (level > LogLevel.Fatal)
        {
            Console.WriteLine("Log.CreateLoggerFromConfig: Wrong Log Level {0} for logger {1}", type, name);
            return;
        }

        if (level < lowestLogLevel)
        {
            lowestLogLevel = level;
        }

        Logger logger = new Logger(name, level);

        int i  = 0;
        var ss = new StringArray(tokens[1], ' ');

        while (i < ss.Length)
        {
            var      str      = ss[i++];
            Appender appender = GetAppenderByName(str);
            if (appender == null)
            {
                Console.WriteLine("Error while configuring Appender {0} in Logger {1}. Appender does not exist", str, name);
            }
            else
            {
                logger.addAppender(appender.getId(), appender);
            }
        }

        loggers[type] = logger;
    }
        Evaluate(
            IRegExCommandLineArgument realArg)
        {
            if (null != realArg.ShortName)
            {
                throw new Exception("The command line argument '{0}' does not support short names", realArg.GetType().ToString());
            }
            var reg     = new System.Text.RegularExpressions.Regex(realArg.LongName);
            var results = new Array <StringArray>();

            foreach (var arg in Arguments)
            {
                var matches = reg.Match(arg);
                if (!matches.Success)
                {
                    continue;
                }

                var thisResult = new StringArray();
                foreach (var group in matches.Groups)
                {
                    if (group.ToString() == arg)
                    {
                        continue;
                    }
                    thisResult.Add(group.ToString());
                }
                results.Add(thisResult);
            }
            return(results);
        }
Пример #4
0
        internal static GameTable <T> Read <T>(string fileName) where T : new()
        {
            GameTable <T> storage = new GameTable <T>();

            if (!File.Exists(CliDB.DataPath + fileName))
            {
                Log.outError(LogFilter.ServerLoading, "File {0} not found.", fileName);
                return(storage);
            }
            using (var reader = new StreamReader(CliDB.DataPath + fileName))
            {
                string headers = reader.ReadLine();
                if (headers.IsEmpty())
                {
                    Log.outError(LogFilter.ServerLoading, "GameTable file {0} is empty.", fileName);
                    return(storage);
                }

                var columnDefs = new StringArray(headers, '\t');

                List <T> data = new List <T>();
                data.Add(new T()); // row id 0, unused

                string line;
                while (!(line = reader.ReadLine()).IsEmpty())
                {
                    var values = new StringArray(line, '\t');
                    if (values.Length == 0)
                    {
                        break;
                    }

                    var obj    = new T();
                    var fields = obj.GetType().GetFields();
                    for (int fieldIndex = 0, valueIndex = 1; fieldIndex < fields.Length && valueIndex < values.Length; ++fieldIndex, ++valueIndex)
                    {
                        var field = fields[fieldIndex];
                        if (field.FieldType.IsArray)
                        {
                            Array array = (Array)field.GetValue(obj);
                            for (var i = 0; i < array.Length; ++i)
                            {
                                array.SetValue(float.Parse(values[valueIndex++]), i);
                            }
                        }
                        else
                        {
                            fields[fieldIndex].SetValue(obj, float.Parse(values[valueIndex]));
                        }
                    }

                    data.Add(obj);
                }

                storage.SetData(data);
            }

            CliDB.LoadedFileCount++;
            return(storage);
        }
Пример #5
0
    public void CheckIngredients(StringArray chosenPizza, List <StringVariable> playerPizza)
    {
        for (int i = 0; i < chosenPizza.values.Count; i++)
        {
            if (chosenPizza.values[i].value == playerPizza[i].value)
            {
                points += 1;
            }

            if (playerPizza.Contains(chosenPizza.values[i]))
            {
                ingredientsRight += 1;
            }

            if (playerPizza[i].value == chosenPizza.values[i].value)
            {
                ingredientsOrderRight += 1;
            }
        }

        if (ingredientsOrderRight == chosenPizza.values.Count)
        {
            allCorrectIngredientsOrder = true;
        }
        if (ingredientsRight == chosenPizza.values.Count)
        {
            allCorrectIngredients = true;
        }
        else
        {
            allCorrectIngredients = false;
        }
    }
Пример #6
0
 public GMCommandOutMessage(ClientAgentBase sender, ulong __characterId__, StringArray commonds)
     : base(sender, ServiceType.Rank, 6900, (int)MessageType.SS)
 {
     Request = new __RPC_Rank_GMCommand_ARG_StringArray_commonds__();
     mMessage.CharacterId = __characterId__;
     Request.Commonds     = commonds;
 }
Пример #7
0
 protected bool Equals(AllTypes <T> other)
 {
     return(Id == other.Id && NullableId == other.NullableId &&
            Byte == other.Byte &&
            Short == other.Short &&
            Int == other.Int &&
            Long == other.Long &&
            UShort == other.UShort &&
            UInt == other.UInt &&
            ULong == other.ULong &&
            Float.Equals(other.Float) &&
            Double.Equals(other.Double) &&
            Decimal == other.Decimal &&
            string.Equals(String, other.String) &&
            DateTime.Equals(other.DateTime) &&
            TimeSpan.Equals(other.TimeSpan) &&
            DateTimeOffset.Equals(other.DateTimeOffset) &&
            Guid.Equals(other.Guid) &&
            Char == other.Char &&
            NullableDateTime.Equals(other.NullableDateTime) &&
            NullableTimeSpan.Equals(other.NullableTimeSpan) &&
            StringList.EquivalentTo(other.StringList) &&
            StringArray.EquivalentTo(other.StringArray) &&
            StringMap.EquivalentTo(other.StringMap) &&
            IntStringMap.EquivalentTo(other.IntStringMap) &&
            Equals(SubType, other.SubType) &&
            Equals(GenericType, other.GenericType));
 }
Пример #8
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Id;
         hashCode = (hashCode * 397) ^ NullableId.GetHashCode();
         hashCode = (hashCode * 397) ^ Byte.GetHashCode();
         hashCode = (hashCode * 397) ^ Short.GetHashCode();
         hashCode = (hashCode * 397) ^ Int;
         hashCode = (hashCode * 397) ^ Long.GetHashCode();
         hashCode = (hashCode * 397) ^ UShort.GetHashCode();
         hashCode = (hashCode * 397) ^ (int)UInt;
         hashCode = (hashCode * 397) ^ ULong.GetHashCode();
         hashCode = (hashCode * 397) ^ Float.GetHashCode();
         hashCode = (hashCode * 397) ^ Double.GetHashCode();
         hashCode = (hashCode * 397) ^ Decimal.GetHashCode();
         hashCode = (hashCode * 397) ^ (String != null ? String.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ DateTime.GetHashCode();
         hashCode = (hashCode * 397) ^ TimeSpan.GetHashCode();
         hashCode = (hashCode * 397) ^ DateTimeOffset.GetHashCode();
         hashCode = (hashCode * 397) ^ Guid.GetHashCode();
         hashCode = (hashCode * 397) ^ Char.GetHashCode();
         hashCode = (hashCode * 397) ^ NullableDateTime.GetHashCode();
         hashCode = (hashCode * 397) ^ NullableTimeSpan.GetHashCode();
         hashCode = (hashCode * 397) ^ (StringList != null ? StringList.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (StringArray != null ? StringArray.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (StringMap != null ? StringMap.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (IntStringMap != null ? IntStringMap.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (SubType != null ? SubType.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (GenericType != null ? GenericType.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #9
0
    public static StringArray Parse(SqlString s)
    {
        if (s.IsNull)
        {
            return(Null);
        }

        StringArray u = new StringArray();

        string[] strings = ((string)s).Split(',');

        for (int i = 0; i < strings.Length; i++)
        {
            strings[i] = strings[i].Trim();
        }

        u.arr = new List <string>(strings.Length);

        foreach (string str in strings)
        {
            if (str != "")
            {
                u.arr.Add(str);
            }
        }

        return(u);
    }
Пример #10
0
        public bool GetNext(out StringArray keys, out MValueArray values)
        {
            if (size == 0)
            {
                keys   = default;
                values = default;
                return(false);
            }

            var mValue = Marshal.PtrToStructure <MValue>(data);

            data += MValue.Size;
            size--;
            if (mValue.type != MValue.Type.DICT)
            {
                keys   = default;
                values = default;
                return(false);
            }

            var stringArray   = StringArray.Nil;
            var valueArrayRef = MValueArray.Nil;

            AltNative.MValueGet.MValue_GetDict(ref mValue, ref stringArray, ref valueArrayRef);
            keys   = stringArray;
            values = valueArrayRef;
            return(true);
        }
Пример #11
0
        public void GetArray()
        {
            var string1      = new StringArray("test");
            var string1Array = string1.GetArray(2, 2);

            Assert.Equal(new[] { 's', 't' }, string1Array);
        }
Пример #12
0
        public async Task RemoveFromHuntList(string targetName)
        {
            //Roles with access
            List <string> roles = new List <string>();

            roles.Add(Setup.ApeChieftainRole);

            if (await Tools.RolesCheck(Context, roles, true, roles[0]))
            {
                //Loaded data
                List <string> entries = new List <string>();
                //Load
                StringArray.Load(Setup.HuntListPath, ref entries);
                //Modify
                for (int i = entries.Count - 1; i > -1; i--)
                {
                    if (entries[i] == targetName)
                    {
                        entries.RemoveAt(i);
                        break;
                    }
                }
                //Save
                StringArray.Save(Setup.HuntListPath, entries);

                await ModifyHuntList(Context, entries);
            }
            await Context.Message.DeleteAsync();
        }
Пример #13
0
        private static Action <string> CreateStringArray(int length, out Func <IArrowArray> build)
        {
            var valueOffsets = new ArrowBuffer.Builder <int>();
            var valueBuffer  = new ArrowBuffer.Builder <byte>();
            var offset       = 0;

            build = () =>
            {
                valueOffsets.Append(offset);
                var result = new StringArray(
                    new ArrayData(
                        StringType.Default,
                        valueOffsets.Length - 1,
                        0,
                        0,
                        new[] { ArrowBuffer.Empty, valueOffsets.Build(), valueBuffer.Build() }));

                valueOffsets = null;
                valueBuffer  = null;
                offset       = 0;
                return(result);
            };

            return(str =>
            {
                var bytes = Encoding.UTF8.GetBytes(str);
                valueOffsets.Append(offset);
                // TODO: Anyway to use the span-based GetBytes to write directly to
                // the value buffer?
                valueBuffer.Append(bytes);
                offset += bytes.Length;
            });
        }
Пример #14
0
        //发放每日奖励
        public void SendReward()
        {
            var item = new ItemBaseData();

            item.ItemId = -1;
            var args = new StringArray();

            foreach (var server in ServerAllianceManager.Servers.Values)
            {
                foreach (var data in server.mDBData.Values)
                {
                    var alliance = ServerAllianceManager.GetAllianceById(data.Occupant);
                    if (alliance == null)
                    {
                        continue;
                    }
                    var serverAlliance = alliance.Dad;
                    foreach (var id in alliance.mDBData.Members)
                    {
                        var member = serverAlliance.GetCharacterData(id);
                        if (member == null)
                        {
                            continue;
                        }
                        var tbGA = Table.GetGuildAccess(member.Ladder);
                        if (tbGA == null)
                        {
                            Logger.Error("In SendReward().tbGA == null");
                            continue;
                        }
                        SendMailToCharacter(id, tbGA.MailId, item, args);
                    }
                }
            }
        }
Пример #15
0
        public Channel(ObjectGuid guid, string name, Team team = 0)
        {
            _announceEnabled  = true;
            _ownershipEnabled = true;
            _channelFlags     = ChannelFlags.Custom;
            _channelTeam      = team;
            _channelGuid      = guid;
            _channelName      = name;

            // If storing custom channels in the db is enabled either load or save the channel
            if (WorldConfig.GetBoolValue(WorldCfg.PreserveCustomChannels))
            {
                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHANNEL);
                stmt.AddValue(0, _channelName);
                stmt.AddValue(1, (uint)_channelTeam);
                SQLResult result = DB.Characters.Query(stmt);

                if (!result.IsEmpty())                           //load
                {
                    _channelName      = result.Read <string>(0); // re-get channel name. MySQL table collation is case insensitive
                    _announceEnabled  = result.Read <bool>(1);
                    _ownershipEnabled = result.Read <bool>(2);
                    _channelPassword  = result.Read <string>(3);
                    string bannedList = result.Read <string>(4);

                    if (string.IsNullOrEmpty(bannedList))
                    {
                        var tokens = new StringArray(bannedList, ' ');
                        for (var i = 0; i < tokens.Length; ++i)
                        {
                            ObjectGuid bannedGuid = new();
                            if (ulong.TryParse(tokens[i].Substring(0, 16), out ulong highguid) && ulong.TryParse(tokens[i][16..], out ulong lowguid))
Пример #16
0
        public LinearAssignmentProblem()
            : base(new LAPEvaluator(), new RandomPermutationCreator())
        {
            Parameters.Add(new ValueParameter <DoubleMatrix>("Costs", CostsDescription, new DoubleMatrix(3, 3)));
            Parameters.Add(new OptionalValueParameter <ItemSet <Permutation> >("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
            Parameters.Add(new OptionalValueParameter <Permutation>("BestKnownSolution", "The best known solution which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
            Parameters.Add(new OptionalValueParameter <StringArray>("RowNames", RowNamesDescription));
            Parameters.Add(new OptionalValueParameter <StringArray>("ColumnNames", ColumnNamesDescription));

            ((ValueParameter <DoubleMatrix>)CostsParameter).ReactOnValueToStringChangedAndValueItemImageChanged              = false;
            ((OptionalValueParameter <StringArray>)RowNamesParameter).ReactOnValueToStringChangedAndValueItemImageChanged    = false;
            ((OptionalValueParameter <StringArray>)ColumnNamesParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;

            RowNames    = new StringArray(new string[] { "Eric", "Robert", "Allison" });
            ColumnNames = new StringArray(new string[] { "MRI", "Blood test", "Angiogram" });
            Costs[0, 0] = 4; Costs[0, 1] = 5; Costs[0, 2] = 3;
            Costs[1, 0] = 6; Costs[1, 1] = 6; Costs[1, 2] = 4;
            Costs[2, 0] = 5; Costs[2, 1] = 5; Costs[2, 2] = 1;

            bestLAPSolutionAnalyzer = new BestLAPSolutionAnalyzer();
            SolutionCreator.PermutationParameter.ActualName = "Assignment";
            InitializeOperators();
            Parameterize();
            AttachEventHandlers();
        }
            public void Visit(StructType type)
            {
                // TODO: Make data from type fields.

                // The following can be improved with a Builder class for StructArray.
                StringArray.Builder resultStringBuilder = new StringArray.Builder();
                Int32Array.Builder  resultInt32Builder  = new Int32Array.Builder();
                ArrowBuffer         nullBitmapBuffer    = new ArrowBuffer.BitmapBuilder().Append(true).Append(true).Append(false).Build();

                for (int i = 0; i < 3; i++)
                {
                    resultStringBuilder.Append("joe").AppendNull().AppendNull().Append("mark");
                    resultInt32Builder.Append(1).Append(2).AppendNull().Append(4);
                    StringArray  stringArray = new StringArray.Builder().Append("joe").AppendNull().AppendNull().Append("mark").Build();
                    Int32Array   intArray    = new Int32Array.Builder().Append(1).Append(2).AppendNull().Append(4).Build();
                    List <Array> arrays      = new List <Array>
                    {
                        stringArray,
                        intArray
                    };

                    TestTargetArrayList.Add(new StructArray(type, 3, arrays, nullBitmapBuffer, 1));
                }

                StringArray resultStringArray = resultStringBuilder.Build();
                Int32Array  resultInt32Array  = resultInt32Builder.Build();

                ExpectedArray = new StructArray(type, 3, new List <Array> {
                    resultStringArray, resultInt32Array
                }, nullBitmapBuffer, 1);
            }
Пример #18
0
        public void LoadPetActionBar(string data)
        {
            InitPetActionBar();

            var tokens = new StringArray(data, ' ');

            if (tokens.Length != (SharedConst.ActionBarIndexEnd - SharedConst.ActionBarIndexStart) * 2)
            {
                return;                                             // non critical, will reset to default
            }
            byte index = 0;

            for (byte i = 0; i < tokens.Length && index < SharedConst.ActionBarIndexEnd; ++i, ++index)
            {
                ActiveStates type = tokens[i++].ToEnum <ActiveStates>();
                uint.TryParse(tokens[i], out uint action);

                PetActionBar[index].SetActionAndType(action, type);

                // check correctness
                if (PetActionBar[index].IsActionBarForSpell())
                {
                    SpellInfo spelInfo = Global.SpellMgr.GetSpellInfo(PetActionBar[index].GetAction(), _unit.GetMap().GetDifficultyID());
                    if (spelInfo == null)
                    {
                        SetActionBar(index, 0, ActiveStates.Passive);
                    }
                    else if (!spelInfo.IsAutocastable())
                    {
                        SetActionBar(index, PetActionBar[index].GetAction(), ActiveStates.Passive);
                    }
                }
            }
        }
Пример #19
0
    public static IEnumerable GetTableFromStringArray(StringArray strings)
    {
        string csv = strings.ToString();

        string[] arr = csv.Split(',');
        return(arr);
    }
Пример #20
0
        private static RecordBatch CountCharacters(
            RecordBatch records,
            string groupFieldName,
            string stringFieldName)
        {
            int         stringFieldIndex = records.Schema.GetFieldIndex(stringFieldName);
            StringArray stringValues     = records.Column(stringFieldIndex) as StringArray;

            int characterCount = 0;

            for (int i = 0; i < stringValues.Length; ++i)
            {
                string current = stringValues.GetString(i);
                characterCount += current.Length;
            }

            int   groupFieldIndex = records.Schema.GetFieldIndex(groupFieldName);
            Field groupField      = records.Schema.GetFieldByIndex(groupFieldIndex);

            // Return 1 record, if we were given any. 0, otherwise.
            int returnLength = records.Length > 0 ? 1 : 0;

            return(new RecordBatch(
                       new Schema.Builder()
                       .Field(groupField)
                       .Field(f => f.Name(stringFieldName + "_CharCount").DataType(Int32Type.Default))
                       .Build(),
                       new IArrowArray[]
            {
                records.Column(groupFieldIndex),
                new Int32Array.Builder().Append(characterCount).Build()
            },
                       returnLength));
        }
Пример #21
0
            /// <summary>
            /// 生成类定义字符串
            /// </summary>
            /// <returns>类定义字符串</returns>
            public override string ToString()
            {
                typeDefinition = new TemplateGenerator.CSharpTypeDefinition(Type, true, true);
                (coder = new Coder(Parameter, Type, Auto.Language)).SkinEnd(coder.GetNode(Auto.GetFileName(Type)));
                codeBuilder = new StringArray();
                if (!Auto.IsDotNet2)
                {
                    codeBuilder.Append(@"
#if DOTNET2
#else");
                }
                codeBuilder.Append(@"
", typeDefinition.Start, @"
        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name=""isOut"">是否输出代码</param>
        protected override void create(bool _isOut_)
        {
            if (outStart(AutoCSer.CodeGenerator.CodeLanguage.", Auto.Language.ToString(), @", _isOut_))
            {
                ");
                switch (Auto.Language)
                {
                case CodeLanguage.JavaScript:
                case CodeLanguage.TypeScript:
                    return(javaScript());

                default: return(cSharp());
                }
            }
Пример #22
0
        public void Constructor()
        {
            var source = new CloneableType[4, 2]
            {
                { "a", "b" }, { "c", "d" }, { "e", "f" }, { "g", "h" }
            };
            StringArray array = new StringArray(source, true);

            Assert.AreEqual(8, array.Length);
            Assert.AreEqual(2, array.Rank);
            Assert.AreEqual(4, array.GetLength(0));
            Assert.AreEqual(2, array.GetLength(1));

            // check equality by multidimensional index
            for (int i = 0; i < array.Length; i++)
            {
                int[] indices = array.GetIndices(i);
                var   value   = source.GetValue(indices);
                Assert.AreEqual(value, array[i]);
                Assert.AreSame(value, array[i]);
            }

            // check equality by enumeration sequence
            int index = 0;

            foreach (CloneableType value in source)
            {
                Assert.AreEqual(value, array[index]);
                Assert.AreSame(value, array[index]);
                index++;
            }
        }
        protected override void OnContentChanged()
        {
            base.OnContentChanged();
            if (Content == null)
            {
                parametersView.Content       = null;
                covarianceMatrixView.Content = null;
            }
            else
            {
                // format numbers to make them easier to read
                var w = new StringArray(Content.W.Select(x => $"{x:e4}").ToArray());
                w.ElementNames         = Content.ParameterNames;
                parametersView.Content = w;

                // format all numbers in matrix
                var cStr = new string[Content.C.GetLength(0), Content.C.GetLength(1)];
                for (int i = 0; i < Content.C.GetLength(0); i++)
                {
                    for (int j = 0; j < Content.C.GetLength(0); j++)
                    {
                        cStr[i, j] = $"{Content.C[i, j]:e4}";
                    }
                }
                var c = new StringMatrix(cStr);
                c.RowNames    = Content.ParameterNames;
                c.ColumnNames = Content.ParameterNames;
                covarianceMatrixView.Content = c;
            }
        }
Пример #24
0
            public void Visit(StructType type)
            {
                StringArray.Builder stringBuilder = new StringArray.Builder();
                for (int i = 0; i < Length; i++)
                {
                    stringBuilder.Append(i.ToString());
                }
                StringArray stringArray = stringBuilder.Build();

                Int32Array.Builder intBuilder = new Int32Array.Builder();
                for (int i = 0; i < Length; i++)
                {
                    intBuilder.Append(i);
                }
                Int32Array intArray = intBuilder.Build();

                List <Array> arrays = new List <Array>();

                arrays.Add(stringArray);
                arrays.Add(intArray);

                ArrowBuffer.BitmapBuilder nullBitmap = new ArrowBuffer.BitmapBuilder();
                for (int i = 0; i < Length; i++)
                {
                    nullBitmap.Append(true);
                }

                Array = new StructArray(type, Length, arrays, nullBitmap.Build());
            }
        private static List <Citation> ReadFromDisk(PDFDocument pdf_document)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            List <Citation> citations = new List <Citation>();

            List <LibraryDB.LibraryItem> library_items = pdf_document.Library.LibraryDB.GetLibraryItems(pdf_document.Fingerprint, PDFDocumentFileLocations.CITATIONS);

            if (0 < library_items.Count)
            {
                LibraryDB.LibraryItem library_item = library_items[0];

                string      lines_all = Encoding.UTF8.GetString(library_item.data);
                StringArray lines     = StringTools.splitAtNewline(lines_all);
                foreach (string line in lines)
                {
                    string[] chunks = line.Split(',');

                    Citation citation = new Citation();
                    citation.fingerprint_outbound = chunks[0];
                    citation.fingerprint_inbound  = chunks[1];
                    citation.type = (Citation.Type)Convert.ToInt32(chunks[2]);

                    citations.Add(citation);
                }
            }

            return(citations);
        }
Пример #26
0
        public string this[string e]
        {
            [Script(DefineAsStatic = true)]
            get
            {
                string z = null;

                string k = StringArray.Split(this.search, "?")[1];

                if (k != null)
                {
                    StringArray u = StringArray.Split(k, "&");


                    foreach (string x in u.ToArray())
                    {
                        StringArray n = StringArray.Split(x, "=");

                        if (n.length > 1)
                        {
                            if (Native.window.unescape(n[0]) == e)
                            {
                                z = Native.window.unescape(n[1]);

                                break;
                            }
                        }
                    }
                }
                return(z);
            }
        }
Пример #27
0
 public bool Equals(HodgepodgeDto o) => o != null &&
 True == o.True &&
 False == o.False &&
 Int8 == o.Int8 &&
 Int16 == o.Int16 &&
 Int32 == o.Int32 &&
 Equals(String, o.String) &&
 Guid.Equals(o.Guid) &&
 IntList.SequenceEqual(o.IntList) &&
 StringArray.SequenceEqual(o.StringArray) &&
 IntPowersArray.SequenceEqual(o.IntPowersArray) &&
 IntStringMap.Count == o.IntStringMap.Count &&
 IntStringMap.All(kvp => o.IntStringMap[kvp.Key] == kvp.Value) &&
 IntStringStringArrayMapArrayMap.Count == o.IntStringStringArrayMapArrayMap.Count &&
 IntStringStringArrayMapArrayMap.All(kvp => {
     var aDicts = kvp.Value;
     var bDicts = o.IntStringStringArrayMapArrayMap[kvp.Key];
     return(aDicts.Length == bDicts.Length &&
            aDicts.Zip(bDicts, Tuple.Create).All(
                (dicts) => {
         var aDict = dicts.Item1;
         var bDict = dicts.Item2;
         return aDict.Count == bDict.Count &&
         aDict.All(innerKvp => bDict[innerKvp.Key].SequenceEqual(innerKvp.Value));
     }));
 }) &&
 Type == o.Type &&
 DateTime == o.DateTime &&
 // ReSharper disable once CompareOfFloatsByEqualityOperator
 Float == o.Float &&
 // ReSharper disable once CompareOfFloatsByEqualityOperator
 Double == o.Double;
Пример #28
0
 public MValueObjectReader(StringArray stringArray, MValueArray mValueArray)
 {
     this.stringArray  = stringArray;
     this.mValueArray  = mValueArray;
     mValueArrayBuffer = mValueArray.Reader();
     stringArrayOffset = this.stringArray.data;
     size = this.stringArray.size;
 }
Пример #29
0
 static Coder()
 {
     codes = new StringArray[EnumAttribute <CodeLanguage> .GetMaxValue(-1) + 1];
     for (int index = codes.Length; index != 0; codes[--index] = new StringArray())
     {
         ;
     }
 }
        public void StringArrayTest2()
        {
            var obj = new StringArray {Array = new[] {"aaa", "bbb"}};

            _sampleValueSetter.AssignSampleValues(obj, 1);
            Assert.That(obj.Array[0], Is.EqualTo("2"));
            Assert.That(obj.Array[1], Is.EqualTo("3"));
        }
Пример #31
0
 void Start()
 {
     //CheckIngredients(testPizza, testPizza2);
     points                = 0;
     ingredientsRight      = 0;
     ingredientsOrderRight = 0;
     chosenPizza           = allPizzas[Random.Range(0, allPizzas.Count)];
     startGame             = true;
 }
Пример #32
0
    //public static string FormatToProgram(ISymbolicExpressionTree tree, StringValue HeaderValue, StringValue FooterValue = null) {
    //  return FormatToProgram(tree, HeaderValue == null ? null : HeaderValue.Value, FooterValue == null ? null : FooterValue.Value);
    //}

    public static string ConvertToPythonValues(StringArray array, IEnumerable<int> indices) {
      StringBuilder strBuilder = new StringBuilder("[");
      foreach (int row in indices) {
        strBuilder.Append("[");
        strBuilder.Append(array[row]);
        strBuilder.Append("],");
      }
      strBuilder.Append("]");
      return strBuilder.ToString();
    }
Пример #33
0
 GetPackageHash(
     StringArray sourceCode,
     StringArray definitions,
     Array<BamAssemblyDescription> bamAssemblies)
 {
     int hashCode = 0;
     foreach (var source in sourceCode)
     {
         hashCode ^= source.GetHashCode();
     }
     foreach (var define in definitions)
     {
         hashCode ^= define.GetHashCode();
     }
     foreach (var assembly in bamAssemblies)
     {
         var assemblyPath = System.IO.Path.Combine(Graph.Instance.ProcessState.ExecutableDirectory, assembly.Name) + ".dll";
         var lastModifiedDate = System.IO.File.GetLastWriteTime(assemblyPath);
         hashCode ^= lastModifiedDate.GetHashCode();
     }
     var hash = hashCode.ToString();
     return hash;
 }
Пример #34
0
        public void initWithDefaults()
        {
            string param_WithDefault =
            "dd";
            WithDefault = param_WithDefault;
            long param_WithIntDef =
            120;
            WithIntDef = param_WithIntDef;
            WithSeqDefSequenceType param_WithSeqDef =

                new WithSeqDefSequenceType();
                {

                    param_WithSeqDef.Name =
                        "Name"
                    ;

                    param_WithSeqDef.Email =
                        "Email"
                    ;

                }
            ;
            WithSeqDef = param_WithSeqDef;
            TestOCT param_WithOctDef =
            new TestOCT (CoderUtils.defStringToOctetString("'01101100'B"));
            WithOctDef = param_WithOctDef;
            byte[] param_WithOctDef2 =
            CoderUtils.defStringToOctetString("'FFEEAA'H").Value;
            WithOctDef2 = param_WithOctDef2;
            System.Collections.Generic.ICollection<string> param_WithSeqOf =

                new System.Collections.Generic.List<string>();

                {

                    param_WithSeqOf.Add(
                        "aa"
                    );

                    param_WithSeqOf.Add(
                        "dd"
                    );

                }
            ;
            WithSeqOf = param_WithSeqOf;
            System.Collections.Generic.ICollection<TestPRN> param_WithSeqOf2 =

                new System.Collections.Generic.List<TestPRN>();

                {

                    param_WithSeqOf2.Add(
                        new TestPRN ("cc")
                    );

                    param_WithSeqOf2.Add(
                        new TestPRN ("ee")
                    );

                }
            ;
            WithSeqOf2 = param_WithSeqOf2;
            StringArray param_WithSeqOf3 =

                new StringArray();

                    param_WithSeqOf3.initValue();

                {

                    param_WithSeqOf3.Add(
                        "fff"
                    );

                    param_WithSeqOf3.Add(
                        "ggg"
                    );

                }
            ;
            WithSeqOf3 = param_WithSeqOf3;
        }
Пример #35
0
        ///<inheritdoc/>
        public void InitTable(ITable subtable)
        {
            Table = subtable;
            commands = new StringArray();
            ids = new NumberArray();
            toCancel = new NumberArray();

            Table.PutValue("Names", commands);
            Table.PutValue("Ids", ids);
            Table.PutValue("Cancel", toCancel);
        }
Пример #36
0
 static CommandLineProcessor()
 {
     Arguments = new StringArray(System.Environment.GetCommandLineArgs());
 }
Пример #37
0
        Evaluate(
            IRegExCommandLineArgument realArg)
        {
            if (null != realArg.ShortName)
            {
                throw new Exception("The command line argument '{0}' does not support short names", realArg.GetType().ToString());
            }
            var reg = new System.Text.RegularExpressions.Regex(realArg.LongName);
            var results = new Array<StringArray>();
            foreach (var arg in Arguments)
            {
                var matches = reg.Match(arg);
                if (!matches.Success)
                {
                    continue;
                }

                var thisResult = new StringArray();
                foreach (var group in matches.Groups)
                {
                    if (group.ToString() == arg)
                    {
                        continue;
                    }
                    thisResult.Add(group.ToString());
                }
                results.Add(thisResult);
            }
            return results;
        }
Пример #38
0
 public Tuple<IEnumerable<bool>, IEnumerable<double>, double, string> EvaluateProgram(string program, StringArray input, StringArray output, IEnumerable<int> indices, double timeout = 1) {
   return EvaluateProgram(program, PythonHelper.ConvertToPythonValues(input, indices), PythonHelper.ConvertToPythonValues(output, indices), indices, timeout);
 }
 public void getAllISOCode(StringArray s)
 {
     sa = s;
     Thread t = new Thread(new ThreadStart(thread_getAllISOCode));
     t.Start();
 }
Пример #40
0
        /// <summary>
        /// Based on the dependents lists in the XML file, resolve all dependents by reading more
        /// package definition files.
        /// </summary>
        /// <param name="current">Current.</param>
        /// <param name="authenticated">Authenticated.</param>
        /// <param name="candidatePackageDefinitions">Candidate package definitions.</param>
        public static void ResolveDependencies(
            PackageDefinition current,
            Array<PackageDefinition> authenticated,
            Array<PackageDefinition> candidatePackageDefinitions)
        {
            var matchingPackages = authenticated.Where(item => item.Name == current.Name);
            if (null != current.Version)
            {
                matchingPackages = matchingPackages.Where(item => item.Version == current.Version);
            }
            if (matchingPackages.FirstOrDefault() != null)
            {
                return;
            }

            if (!current.SupportedPlatforms.Includes(OSUtilities.CurrentOS))
            {
                throw new Exception("Package {0} is not supported on {1}", current.FullName, OSUtilities.CurrentOS.ToString());
            }

            authenticated.Add(current);
            foreach (var dependent in current.Dependents)
            {
                var depName = dependent.Item1;
                var depVersion = dependent.Item2;
                var candidates = candidatePackageDefinitions.Where(item => item.Name == depName);
                if (depVersion != null)
                {
                    candidates = candidates.Where(item => item.Version == depVersion);
                }
                var candidateCount = candidates.Count();
                if (0 == candidateCount)
                {
                    var message = new System.Text.StringBuilder();
                    message.AppendFormat("Unable to find a candidate package with name '{0}'", depName);
                    if (null != depVersion)
                    {
                        message.AppendFormat(" and version {0}", depVersion);
                    }
                    message.AppendLine();
                    var packageRepos = new StringArray();
                    Graph.Instance.PackageRepositories.ToList().ForEach(item => packageRepos.AddUnique(item));
                    message.AppendLine("Searched in the package repositories:");
                    message.AppendLine(packageRepos.ToString("\n"));
                    throw new Exception(message.ToString());
                }
                if (candidateCount > 1)
                {
                    var message = new System.Text.StringBuilder();
                    message.AppendFormat("There are {0} identical candidate packages with name '{1}'", candidateCount, depName);
                    if (null != depVersion)
                    {
                        message.AppendFormat(" and version {0}", depVersion);
                    }
                    message.AppendLine(" from the following package definition files:");
                    foreach (var candidate in candidates)
                    {
                        message.AppendFormat(candidate.XMLFilename);
                        message.AppendLine();
                    }
                    var packageRepos = new StringArray();
                    Graph.Instance.PackageRepositories.ToList().ForEach(item => packageRepos.AddUnique(item));
                    message.AppendLine("Found in the package repositories:");
                    message.AppendLine(packageRepos.ToString("\n"));
                    throw new Exception(message.ToString());
                }

                ResolveDependencies(candidates.First(), authenticated, candidatePackageDefinitions);
            }
        }
Пример #41
0
        CompilePackageAssembly(
            bool enforceBamAssemblyVersions = true,
            bool enableClean = true)
        {
            // validate build root
            if (null == Graph.Instance.BuildRoot)
            {
                throw new Exception("Build root has not been specified");
            }

            var gatherSourceProfile = new TimeProfile(ETimingProfiles.GatherSource);
            gatherSourceProfile.StartProfile();

            IdentifyAllPackages(enforceBamAssemblyVersions: enforceBamAssemblyVersions);

            var cleanFirst = CommandLineProcessor.Evaluate(new Options.CleanFirst());
            if (enableClean && cleanFirst && System.IO.Directory.Exists(Graph.Instance.BuildRoot))
            {
                Log.Info("Deleting build root '{0}'", Graph.Instance.BuildRoot);
                try
                {
                    System.IO.Directory.Delete(Graph.Instance.BuildRoot, true);
                }
                catch (System.IO.IOException ex)
                {
                    Log.Info("Failed to delete build root, because {0}. Continuing", ex.Message);
                }
            }

            if (!System.IO.Directory.Exists(Graph.Instance.BuildRoot))
            {
                System.IO.Directory.CreateDirectory(Graph.Instance.BuildRoot);
            }

            BuildModeUtilities.ValidateBuildModePackage();

            var definitions = new StringArray();

            // gather source files
            var sourceCode = new StringArray();
            int packageIndex = 0;
            foreach (var package in Graph.Instance.Packages)
            {
                Log.DebugMessage("{0}: '{1}' @ '{2}'", packageIndex, package.Version, (package.PackageRepositories.Count > 0) ? package.PackageRepositories[0] : "Not in a repository");

                // to compile with debug information, you must compile the files
                // to compile without, we need to file contents to hash the source
                if (Graph.Instance.CompileWithDebugSymbols)
                {
                    var scripts = package.GetScriptFiles();
                    sourceCode.AddRange(scripts);
                    Log.DebugMessage(scripts.ToString("\n\t"));
                }
                else
                {
                    foreach (var scriptFile in package.GetScriptFiles())
                    {
                        using (var reader = new System.IO.StreamReader(scriptFile))
                        {
                            sourceCode.Add(reader.ReadToEnd());
                        }
                        Log.DebugMessage("\t'{0}'", scriptFile);
                    }
                }

                foreach (var define in package.Definitions)
                {
                    if (!definitions.Contains(define))
                    {
                        definitions.Add(define);
                    }
                }

                ++packageIndex;
            }

            // add/remove other definitions
            definitions.Add(VersionDefineForCompiler);
            definitions.Add(HostPlatformDefineForCompiler);
            definitions.Sort();

            gatherSourceProfile.StopProfile();

            var assemblyCompileProfile = new TimeProfile(ETimingProfiles.AssemblyCompilation);
            assemblyCompileProfile.StartProfile();

            // assembly is written to the build root
            var cachedAssemblyPathname = System.IO.Path.Combine(Graph.Instance.BuildRoot, "CachedPackageAssembly");
            cachedAssemblyPathname = System.IO.Path.Combine(cachedAssemblyPathname, Graph.Instance.MasterPackage.Name) + ".dll";
            var hashPathName = System.IO.Path.ChangeExtension(cachedAssemblyPathname, "hash");
            string thisHashCode = null;

            var cacheAssembly = !CommandLineProcessor.Evaluate(new Options.DisableCacheAssembly());

            string compileReason = null;
            if (Graph.Instance.CompileWithDebugSymbols)
            {
                compileReason = "debug symbols were enabled";
            }
            else
            {
                // can an existing assembly be reused?
                thisHashCode = GetPackageHash(sourceCode, definitions, Graph.Instance.MasterPackage.BamAssemblies);
                if (cacheAssembly)
                {
                    if (System.IO.File.Exists(hashPathName))
                    {
                        using (var reader = new System.IO.StreamReader(hashPathName))
                        {
                            var diskHashCode = reader.ReadLine();
                            if (diskHashCode.Equals(thisHashCode))
                            {
                                Log.DebugMessage("Cached assembly used '{0}', with hash {1}", cachedAssemblyPathname, diskHashCode);
                                Log.Detail("Re-using existing package assembly");
                                Graph.Instance.ScriptAssemblyPathname = cachedAssemblyPathname;

                                assemblyCompileProfile.StopProfile();

                                return true;
                            }
                            else
                            {
                                compileReason = "package source has changed since the last compile";
                            }
                        }
                    }
                    else
                    {
                        compileReason = "no previously compiled package assembly exists";
                    }
                }
                else
                {
                    compileReason = "user has disabled package assembly caching";
                }
            }

            // use the compiler in the current runtime version to build the assembly of packages
            var clrVersion = System.Environment.Version;
            var compilerVersion = System.String.Format("v{0}.{1}", clrVersion.Major, clrVersion.Minor);

            Log.Detail("Compiling package assembly (C# compiler {0}{1}), because {2}.",
                compilerVersion,
                Graph.Instance.ProcessState.TargetFrameworkVersion != null ? (", targetting " + Graph.Instance.ProcessState.TargetFrameworkVersion) : string.Empty,
                compileReason);

            var providerOptions = new System.Collections.Generic.Dictionary<string, string>();
            providerOptions.Add("CompilerVersion", compilerVersion);

            if (Graph.Instance.ProcessState.RunningMono)
            {
                Log.DebugMessage("Compiling assembly for Mono");
            }

            using (var provider = new Microsoft.CSharp.CSharpCodeProvider(providerOptions))
            {
                var compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
                compilerParameters.TreatWarningsAsErrors = true;
                compilerParameters.WarningLevel = 4;
                compilerParameters.GenerateExecutable = false;
                compilerParameters.GenerateInMemory = false;

                if (Graph.Instance.CompileWithDebugSymbols)
                {
                    compilerParameters.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Graph.Instance.MasterPackage.Name) + ".dll";
                }
                else
                {
                    compilerParameters.OutputAssembly = cachedAssemblyPathname;
                }

                var compilerOptions = "/checked+ /unsafe-";
                if (Graph.Instance.CompileWithDebugSymbols)
                {
                    compilerParameters.IncludeDebugInformation = true;
                    compilerOptions += " /optimize-";
                }
                else
                {
                    compilerOptions += " /optimize+";
                }
                compilerOptions += " /platform:anycpu";

                // define strings
                compilerOptions += " /define:" + definitions.ToString(';');

                compilerParameters.CompilerOptions = compilerOptions;

                if (provider.Supports(System.CodeDom.Compiler.GeneratorSupport.Resources))
                {
                    // Bam assembly
                    // TODO: Q: why is it only for the master package? Why not all of them, which may have additional dependencies?
                    foreach (var assembly in Graph.Instance.MasterPackage.BamAssemblies)
                    {
                        var assemblyFileName = System.String.Format("{0}.dll", assembly.Name);
                        var assemblyPathName = System.IO.Path.Combine(Graph.Instance.ProcessState.ExecutableDirectory, assemblyFileName);
                        compilerParameters.ReferencedAssemblies.Add(assemblyPathName);
                    }

                    // DotNet assembly
                    foreach (var desc in Graph.Instance.MasterPackage.DotNetAssemblies)
                    {
                        var assemblyFileName = System.String.Format("{0}.dll", desc.Name);
                        compilerParameters.ReferencedAssemblies.Add(assemblyFileName);
                    }

                    if (Graph.Instance.ProcessState.RunningMono)
                    {
                        compilerParameters.ReferencedAssemblies.Add("Mono.Posix.dll");
                    }
                }
                else
                {
                    throw new Exception("C# compiler does not support Resources");
                }

                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(compilerParameters.OutputAssembly));

                var results = Graph.Instance.CompileWithDebugSymbols ?
                    provider.CompileAssemblyFromFile(compilerParameters, sourceCode.ToArray()) :
                    provider.CompileAssemblyFromSource(compilerParameters, sourceCode.ToArray());

                if (results.Errors.HasErrors || results.Errors.HasWarnings)
                {
                    Log.ErrorMessage("Failed to compile package '{0}'. There are {1} errors.", Graph.Instance.MasterPackage.FullName, results.Errors.Count);
                    foreach (System.CodeDom.Compiler.CompilerError error in results.Errors)
                    {
                        Log.ErrorMessage("\t{0}({1}): {2} {3}", error.FileName, error.Line, error.ErrorNumber, error.ErrorText);
                    }
                    return false;
                }

                if (!Graph.Instance.CompileWithDebugSymbols)
                {
                    if (cacheAssembly)
                    {
                        using (var writer = new System.IO.StreamWriter(hashPathName))
                        {
                            writer.WriteLine(thisHashCode);
                        }
                    }
                    else
                    {
                        // will not throw if the file doesn't exist
                        System.IO.File.Delete(hashPathName);
                    }
                }

                Log.DebugMessage("Written assembly to '{0}'", compilerParameters.OutputAssembly);
                Graph.Instance.ScriptAssemblyPathname = compilerParameters.OutputAssembly;
            }

            assemblyCompileProfile.StopProfile();

            return true;
        }
Пример #42
0
        /// <summary>
        /// Get the array of files to compile from all packages.
        /// </summary>
        /// <returns>The script files.</returns>
        /// <param name="allBuilders">If set to <c>true</c> all builders.</param>
        public StringArray GetScriptFiles(
            bool allBuilders = false)
        {
            var bamDir = this.GetBamDirectory();
            var scriptDir = System.IO.Path.Combine(bamDir, PackageUtilities.ScriptsSubFolder);
            var scripts = new StringArray(System.IO.Directory.GetFiles(scriptDir, "*.cs", System.IO.SearchOption.AllDirectories));

            var builderNames = new StringArray();
            if (allBuilders)
            {
                foreach (var package in Graph.Instance.Packages)
                {
                    if (!BuildModeUtilities.IsBuildModePackage(package.Name))
                    {
                        continue;
                    }
                    builderNames.Add(package.Name);
                }
            }
            else
            {
                builderNames.AddUnique(System.String.Format("{0}Builder", Graph.Instance.Mode));
            }
            foreach (var builderName in builderNames)
            {
                var builderScriptDir = System.IO.Path.Combine(bamDir, builderName);
                if (System.IO.Directory.Exists(builderScriptDir))
                {
                    scripts.AddRange(System.IO.Directory.GetFiles(builderScriptDir, "*.cs", System.IO.SearchOption.AllDirectories));
                }
            }
            return scripts;
        }
Пример #43
0
        /// <summary>
        /// Write the latest version of the XML definition file.
        /// Always refer to the schema location as a relative path to the bam executable.
        /// Always reference the default namespace in the first element.
        /// Don't use a namespace prefix on child elements, as the default namespace covers them.
        /// </summary>
        public void Write()
        {
            if (System.IO.File.Exists(this.XMLFilename))
            {
                var attributes = System.IO.File.GetAttributes(this.XMLFilename);
                if (0 != (attributes & System.IO.FileAttributes.ReadOnly))
                {
                    throw new Exception("File '{0}' cannot be written to as it is read only", this.XMLFilename);
                }
            }

            this.Dependents.Sort();

            var document = new System.Xml.XmlDocument();
            var namespaceURI = "http://www.buildamation.com";
            var packageDefinition = document.CreateElement("PackageDefinition", namespaceURI);
            {
                var xmlns = "http://www.w3.org/2001/XMLSchema-instance";
                var schemaAttribute = document.CreateAttribute("xsi", "schemaLocation", xmlns);
                var mostRecentSchemaRelativePath = "./Schema/BamPackageDefinitionV1.xsd";
                schemaAttribute.Value = System.String.Format("{0} {1}", namespaceURI, mostRecentSchemaRelativePath);
                packageDefinition.Attributes.Append(schemaAttribute);
                packageDefinition.SetAttribute("name", this.Name);
                if (null != this.Version)
                {
                    packageDefinition.SetAttribute("version", this.Version);
                }
            }
            document.AppendChild(packageDefinition);

            // package description
            if (!string.IsNullOrEmpty(this.Description))
            {
                var descriptionElement = document.CreateElement("Description", namespaceURI);
                descriptionElement.InnerText = this.Description;
                packageDefinition.AppendChild(descriptionElement);
            }

            // package repositories
            var packageRepos = new StringArray(this.PackageRepositories);
            // TODO: could these be marked as transient?
            // don't write out the repo that this package resides in
            packageRepos.Remove(this.GetPackageRepository());
            // nor an associated repo for tests
            var associatedRepo = this.GetAssociatedPackageDirectoryForTests();
            if (null != associatedRepo)
            {
                packageRepos.Remove(associatedRepo);
            }
            if (packageRepos.Count > 0)
            {
                var packageRootsElement = document.CreateElement("PackageRepositories", namespaceURI);
                var bamDir = this.GetBamDirectory() + System.IO.Path.DirectorySeparatorChar; // slash added to make it look like a directory
                foreach (string repo in packageRepos)
                {
                    var relativePackageRepo = RelativePathUtilities.GetPath(repo, bamDir);
                    if (OSUtilities.IsWindowsHosting)
                    {
                        // standardize on non-Windows directory separators
                        relativePackageRepo = relativePackageRepo.Replace(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);
                    }

                    var rootElement = document.CreateElement("Repo", namespaceURI);
                    rootElement.SetAttribute("dir", relativePackageRepo);
                    packageRootsElement.AppendChild(rootElement);
                }

                packageDefinition.AppendChild(packageRootsElement);
            }

            if (this.Dependents.Count > 0)
            {
                var dependentsEl = document.CreateElement("Dependents", namespaceURI);
                foreach (var package in this.Dependents)
                {
                    var packageName = package.Item1;
                    var packageVersion = package.Item2;
                    var packageIsDefault = package.Item3;
                    System.Xml.XmlElement packageElement = null;

                    {
                        var node = dependentsEl.FirstChild;
                        while (node != null)
                        {
                            var attributes = node.Attributes;
                            var nameAttribute = attributes["Name"];
                            if ((null != nameAttribute) && (nameAttribute.Value == packageName))
                            {
                                packageElement = node as System.Xml.XmlElement;
                                break;
                            }

                            node = node.NextSibling;
                        }
                    }

                    if (null == packageElement)
                    {
                        packageElement = document.CreateElement("Package", namespaceURI);
                        packageElement.SetAttribute("name", packageName);
                        if (null != packageVersion)
                        {
                            packageElement.SetAttribute("version", packageVersion);
                        }
                        if (packageIsDefault.HasValue)
                        {
                            packageElement.SetAttribute("default", packageIsDefault.Value.ToString().ToLower());
                        }
                        dependentsEl.AppendChild(packageElement);
                    }
                }
                packageDefinition.AppendChild(dependentsEl);
            }

            if (this.BamAssemblies.Count > 0)
            {
                var requiredAssemblies = document.CreateElement("BamAssemblies", namespaceURI);
                foreach (var assembly in this.BamAssemblies)
                {
                    var assemblyElement = document.CreateElement("BamAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", assembly.Name);
                    if (assembly.MajorVersion.HasValue)
                    {
                        assemblyElement.SetAttribute("major", assembly.MajorVersion.ToString());
                        if (assembly.MinorVersion.HasValue)
                        {
                            assemblyElement.SetAttribute("minor", assembly.MinorVersion.ToString());
                            if (assembly.PatchVersion.HasValue)
                            {
                                // honour any existing BamAssembly with a specific patch version
                                assemblyElement.SetAttribute("patch", assembly.PatchVersion.ToString());
                            }
                        }
                    }
                    requiredAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredAssemblies);
            }

            if (this.DotNetAssemblies.Count > 0)
            {
                var requiredDotNetAssemblies = document.CreateElement("DotNetAssemblies", namespaceURI);
                foreach (var desc in this.DotNetAssemblies)
                {
                    var assemblyElement = document.CreateElement("DotNetAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", desc.Name);
                    if (null != desc.RequiredTargetFramework)
                    {
                        assemblyElement.SetAttribute("requiredTargetFramework", desc.RequiredTargetFramework);
                    }
                    requiredDotNetAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredDotNetAssemblies);
            }

            // supported platforms
            {
                var supportedPlatformsElement = document.CreateElement("SupportedPlatforms", namespaceURI);

                if (EPlatform.Windows == (this.SupportedPlatforms & EPlatform.Windows))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Windows");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.Linux == (this.SupportedPlatforms & EPlatform.Linux))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Linux");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.OSX == (this.SupportedPlatforms & EPlatform.OSX))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "OSX");
                    supportedPlatformsElement.AppendChild(platformElement);
                }

                packageDefinition.AppendChild(supportedPlatformsElement);
            }

            // definitions
            this.Definitions.Remove(this.GetPackageDefinitionName());
            if (this.Definitions.Count > 0)
            {
                var definitionsElement = document.CreateElement("Definitions", namespaceURI);

                foreach (string define in this.Definitions)
                {
                    var defineElement = document.CreateElement("Definition", namespaceURI);
                    defineElement.SetAttribute("name", define);
                    definitionsElement.AppendChild(defineElement);
                }

                packageDefinition.AppendChild(definitionsElement);
            }

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.CloseOutput = true;
            xmlWriterSettings.OmitXmlDeclaration = false;
            xmlWriterSettings.NewLineOnAttributes = false;
            xmlWriterSettings.NewLineChars = "\n";
            xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;
            xmlWriterSettings.Encoding = new System.Text.UTF8Encoding(false);

            using (var xmlWriter = System.Xml.XmlWriter.Create(this.XMLFilename, xmlWriterSettings))
            {
                document.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(xmlWriterSettings.NewLineChars);
            }

            if (this.validate)
            {
                this.Validate();
            }
        }
Пример #44
0
 public LAPAssignment(DoubleMatrix costs, StringArray rowNames, StringArray columnNames, Permutation assignment)
   : this(costs, assignment) {
   this.rowNames = rowNames;
   this.columnNames = columnNames;
 }
Пример #45
0
 private LAPAssignment(LAPAssignment original, Cloner cloner)
   : base(original, cloner) {
   costs = cloner.Clone(original.costs);
   assignment = cloner.Clone(original.assignment);
   rowNames = cloner.Clone(original.rowNames);
   columnNames = cloner.Clone(original.columnNames);
   quality = cloner.Clone(original.quality);
 }
Пример #46
0
 public LAPAssignment(DoubleMatrix costs, StringArray rowNames, StringArray columnNames, Permutation assignment, DoubleValue quality)
   : this(costs, rowNames, columnNames, assignment) {
   this.quality = quality;
 }