/// <summary>
        /// BuildTeachersTable
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="Teachers"></param>
        private static void BuildTeachersTable(ExcelWorksheet ws, IEnumerable<OfficeVisitsByTeacher> Teachers)
        {

            ws.Column(1).Width = 17.86;
            ws.Column(2).Width = 12.43;

            //Set Header titles
            ws.Cells[4, 1].Value = "Teachers";
            ws.Cells[4, 1].Style.Font.Bold = true;
            ws.Cells[5, 1].Value = "Teacher Name";
            ws.Cells[5, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin);
           // ws.Cells[5, 1].AutoFilter = true;
            ws.Cells[5, 2].Value = "Office Visits";
            ws.Cells[5, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin);
           // ws.Cells[5, 2].AutoFilter = true;

            //Get Data for Teachers       
            for (int i = 0; i < Teachers.Count(); i++)
            {
                ws.Cells[i + 6, 1].Value = Teachers.ElementAt(i).sent_by_contact_name;
                ws.Cells[i + 6, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin);
                ws.Cells[i + 6, 2].Value = Teachers.ElementAt(i).total_visits;
                ws.Cells[i + 6, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin);
            }

            //Set Header style
            using (ExcelRange rng = ws.Cells[4, 1, 5 + Teachers.Count(), 2])
            {
                rng.Style.Border.BorderAround(ExcelBorderStyle.Medium);            
            }

        }
        public static VectorRectangle GetUnion(IEnumerable<VectorRectangle> list)
        {
            if (list == null || list.Count() == 0)
            {
                throw new ArgumentException("list can't be null and must contain at least one element.");
            }

            VectorRectangle result = new VectorRectangle();
            result.Position = list.ElementAt(0).Position;
            result.Size = list.ElementAt(0).Size;

            VectorRectangle lowest = list.ElementAt(0);
            VectorRectangle rightest = list.ElementAt(0);

            foreach (VectorRectangle rect in list) {
                if (rect.Left < result.Left)
                    result.Position = new Vector2(rect.Left, result.Position.Y);

                if (rect.Right > rightest.Right)
                    rightest = rect;

                if (rect.Top < result.Top)
                    result.Position = new Vector2(result.Position.X, rect.Top);

                if (rect.Bottom > lowest.Bottom)
                    lowest = rect;
            }

            result.Size = new Vector2(result.Size.X, lowest.Bottom - result.Top);
            result.Size = new Vector2(rightest.Right - result.Left, result.Size.Y);

            return result;
        }
        public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters)
        {
            if (period - 1 < 0)
                return null;

            int numberOfPeriods = strategyParameters.PeriodCount;

            if (numberOfPeriods > dataEntries.Count())
                throw new ArgumentException("The number of periods can not be greater than the number of entries.");

            double value;

            if (dataEntries.Count() == 1 || period == 1)
                value = dataEntries.ElementAt(0).Value;
            else if (period < numberOfPeriods)
                value = dataEntries.ElementAt(period - 1).Value;
            else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1)
                value =
                    dataEntries.Take(period - 1).Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/
                    numberOfPeriods;
            else
                value = dataEntries.Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/
                        numberOfPeriods;

            return new ForecastEntry
                {
                    Period = period,
                    DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1),
                    ForecastValue = value,
                    ConfidenceIntervalLow = value,
                    ConfidenceIntervalHigh = value,
                    IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent
                };
        }
 public static double FindYieldN(double y, IEnumerable<Object> otherParams)
 {
     double P = (double) otherParams.ElementAt(0);
     double C = (double) otherParams.ElementAt(1);
     long N = (long) otherParams.ElementAt(2);
     return AnnuityWithCandyandN(C, y, N) - P;
 }
Exemple #5
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var firstArg = arguments.ElementAt(0);
     var args = firstArg.Value as IEnumerable<FunctionArgument>;
     if (args == null && firstArg.IsExcelRange)
     {
         args = new List<FunctionArgument>(){ firstArg };
     }
     var criteria = arguments.ElementAt(1).Value;
     ThrowExcelErrorValueExceptionIf(() => criteria == null || criteria.ToString().Length > 255, eErrorType.Value);
     var retVal = 0d;
     if (arguments.Count() > 2)
     {
         var secondArg = arguments.ElementAt(2);
         var lookupRange = secondArg.Value as IEnumerable<FunctionArgument>;
         if (lookupRange == null && secondArg.IsExcelRange)
         {
             lookupRange = new List<FunctionArgument>() {secondArg};
         }
         retVal = CalculateWithLookupRange(args, criteria.ToString(), lookupRange, context);
     }
     else
     {
         retVal = CalculateSingleRange(args, criteria.ToString(), context);
     }
     return CreateResult(retVal, DataType.Decimal);
 }
Exemple #6
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var args = arguments.ElementAt(0).Value as ExcelDataProvider.IRangeInfo; //IEnumerable<FunctionArgument>;
     var criteria = arguments.ElementAt(1).Value;
     ThrowExcelErrorValueExceptionIf(() => criteria == null || criteria.ToString().Length > 255, eErrorType.Value);
     var retVal = 0d;
     if (arguments.Count() > 2)
     {
         var sumRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;//IEnumerable<FunctionArgument>;
         retVal = CalculateWithSumRange(args, criteria.ToString(), sumRange, context);
     }
     else
     {
         if (args != null)
         {
             retVal = CalculateSingleRange(args, criteria.ToString(), context);   
         }
         else
         {
             retVal = CalculateSingleRange((arguments.ElementAt(0).Value as IEnumerable<FunctionArgument>),
                                           criteria.ToString(), context);
         }
     }
     return CreateResult(retVal, DataType.Decimal);
 }
        private static object[] GenerateArgs(IEnumerable <CommandParameterInfo> paramList, IEnumerable <string> argList)
        {
            var result = new object[paramList.Count()];

            for (var i = 0; i < paramList.Count(); i++)
            {
                var parameter = paramList.ElementAt(i);

                if (argList?.ElementAt(i) == null)
                {
                    if (!parameter.IsRequired)
                    {
                        result[i] = parameter.DefaultValue;
                    }
                    else
                    {
                        throw new InvalidOperationException($"Component Interaction handler is executed with too few args.");
                    }
                }
                else if (parameter.IsParameterArray)
                {
                    string[] paramArray = new string[argList.Count() - i];
                    argList.ToArray().CopyTo(paramArray, i);
                    result[i] = paramArray;
                }
                else
                {
                    result[i] = argList?.ElementAt(i);
                }
            }

            return(result);
        }
Exemple #8
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var args = arguments.ElementAt(0).Value as ExcelDataProvider.IRangeInfo;
     var criteria = arguments.ElementAt(1).ValueFirst != null ? ArgToString(arguments, 1) : null;
     var retVal = 0d;
     if (args == null)
     {
         var val = arguments.ElementAt(0).Value;
         if (criteria != null && Evaluate(val, criteria))
         {
             var lookupRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;
             retVal = arguments.Count() > 2
                 ? lookupRange.First().ValueDouble
                 : ConvertUtil.GetValueDouble(val, true);
         }
         else
         {
             throw new ExcelErrorValueException(eErrorType.Div0);
         }
     }
     else if (arguments.Count() > 2)
     {
         var lookupRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;
         retVal = CalculateWithLookupRange(args, criteria, lookupRange, context);
     }
     else
     {
         retVal = CalculateSingleRange(args, criteria, context);
     }
     return CreateResult(retVal, DataType.Decimal);
 }
Exemple #9
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 2);
     var row = ArgToInt(arguments, 0);
     var col = ArgToInt(arguments, 1);
     ThrowExcelErrorValueExceptionIf(() => row < 0 && col < 0, eErrorType.Value);
     var referenceType = ExcelReferenceType.AbsoluteRowAndColumn;
     var worksheetSpec = string.Empty;
     if (arguments.Count() > 2)
     {
         var arg3 = ArgToInt(arguments, 2);
         ThrowExcelErrorValueExceptionIf(() => arg3 < 1 || arg3 > 4, eErrorType.Value);
         referenceType = (ExcelReferenceType)ArgToInt(arguments, 2);
     }
     if (arguments.Count() > 3)
     {
         var fourthArg = arguments.ElementAt(3).Value;
         if (fourthArg is bool && !(bool)fourthArg)
         {
             throw new InvalidOperationException("Excelformulaparser does not support the R1C1 format!");
         }
     }
     if (arguments.Count() > 4)
     {
         var fifthArg = arguments.ElementAt(4).Value;
         if (fifthArg is string && !string.IsNullOrEmpty(fifthArg.ToString()))
         {
             worksheetSpec = fifthArg + "!";
         }
     }
     var translator = new IndexToAddressTranslator(context.ExcelDataProvider, referenceType);
     return CreateResult(worksheetSpec + translator.ToAddress(col, row), DataType.ExcelAddress);
 }
        public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters)
        {
            if (period - 1 < 0)
                return null;

            double alpha = strategyParameters.Alpha;
            double beta = strategyParameters.Beta;
            double value;

            if (dataEntries.Count() < 3 || period < 3)
                value = dataEntries.ElementAt(0).Value;
            else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1)
                value = GenerateForecast(3, period, alpha, beta, dataEntries, dataEntries.First().Value, 0);
            else
                value = GenerateForecast(3, dataEntries.Count() + 1, alpha, beta, dataEntries, dataEntries.First().Value,
                                         0);

            return new ForecastEntry
                {
                    Period = period,
                    DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1),
                    ForecastValue = value,
                    ConfidenceIntervalLow = value,
                    ConfidenceIntervalHigh = value,
                    IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent
                };
        }
        private static void ProcessNotesInTimeRow(List <NoteData> notes)
        {
            List <CustomNoteData> customNotes = notes.Cast <CustomNoteData>().ToList();

            ProcessFlipData(customNotes, false);

            _numberOfNotesInLines.Clear();
            for (int i = 0; i < customNotes.Count; i++)
            {
                CustomNoteData noteData = customNotes[i];
                dynamic        dynData  = noteData.customData;

                IEnumerable <float?> position = ((List <object>)Trees.at(dynData, POSITION))?.Select(n => n.ToNullableFloat());
                float lineIndex = position?.ElementAt(0) ?? noteData.lineIndex;
                float lineLayer = position?.ElementAt(1) ?? (float)noteData.noteLineLayer;
                if (_numberOfNotesInLines.TryGetValue(lineIndex, out float num))
                {
                    Dictionary <float, float> numberOfNotesInLines = _numberOfNotesInLines;
                    float num2 = Math.Max(numberOfNotesInLines[lineIndex], 0) + Math.Min(lineLayer, 1);
                    dynData.startNoteLineLayer      = num2;
                    numberOfNotesInLines[lineIndex] = num2;
                }
                else
                {
                    float startLineLayer = Math.Min(lineLayer, 0);
                    _numberOfNotesInLines[lineIndex] = startLineLayer;
                    dynData.startNoteLineLayer       = startLineLayer;
                }
            }
        }
        public static Result Execute(IEnumerable<string> args)
        {
            var input = args.ElementAt(1);
            var output = args.ElementAt(2);

            return Migrate(input, output);
        }
Exemple #13
0
        public static IEnumerable<Price> Convert(IEnumerable<Price> shareData, IEnumerable<SplitEvent> splits)
        {
            int cumaltiveUpdateIndex = 0;
            decimal cumaltiveAdj = splits.First().cumalitveAdjustment;

            foreach (var d in shareData.Skip(1))
            {
                if (splits.ElementAt(cumaltiveUpdateIndex).date <= d.date)
                {
                    cumaltiveUpdateIndex++;
                    cumaltiveAdj = splits.ElementAt(cumaltiveUpdateIndex).cumalitveAdjustment;
                }

                yield return new Price()
                {
                    date = d.date,
                    openPrice = d.openPrice * cumaltiveAdj,
                    highPrice = d.highPrice * cumaltiveAdj,
                    lowPrice = d.lowPrice * cumaltiveAdj,
                    closePrice = d.closePrice * cumaltiveAdj,
                    //volume = long.Parse(fields[5]),
                    //adjClose = decimal.Parse(fields[6])
                };
            }
        }
Exemple #14
0
        /// <summary>
        /// Checks wheter an outport is required for a Statement with the given 
        /// index. An outport is not required if there are no defined variables 
        /// or if any of the defined variables have been declared again later on
        /// in the same code block.
        /// </summary>
        /// <param name="statementVariables">A list of lists, each of which 
        /// contains variables defined by a Statement at the index. This list 
        /// can be obtained from calling GetStatementVariables method.</param>
        /// <param name="index">The index of the Statement for which this call 
        /// is made.</param>
        /// <returns>Returns true if an output port is required, or false 
        /// otherwise.</returns>
        /// 
        public static bool DoesStatementRequireOutputPort(
            IEnumerable<IEnumerable<string>> statementVariables, int index)
        {
            if (statementVariables == null)
                throw new ArgumentNullException("statementVariables");

            int statementCount = statementVariables.Count();
            if (statementCount <= 0)
                return false;

            if (index < 0 || (index >= statementCount))
                throw new IndexOutOfRangeException("index");

            var currentVariables = statementVariables.ElementAt(index);
            for (int stmt = index + 1; stmt < statementCount; stmt++)
            {
                var variables = statementVariables.ElementAt(stmt);
                foreach (var cv in currentVariables)
                {
                    if (variables.Contains(cv))
                        return false;
                }
            }

            return true;
        }
 public static double FindYieldMm(double y, IEnumerable<Object> otherParams)
 {
     double P = (double) otherParams.ElementAt(0);
     double C = (double) otherParams.ElementAt(1);
     long M = (long) otherParams.ElementAt(2);
     long littleM = (long) otherParams.ElementAt(3);
     return AnnuityWithCandyandMm(C, y, M, littleM) - P;
 }
Exemple #16
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 1);
     if (arguments.Count() == 1 && arguments.ElementAt(0).Value != null)
     {
         return CreateResult((arguments.ElementAt(0).Value is string), DataType.Boolean);
     }
     return CreateResult(false, DataType.Boolean);
 }
Exemple #17
0
 public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
 {
     ValidateArguments(arguments, 3);
     var condition = ArgToBool(arguments, 0);
     var firstStatement = arguments.ElementAt(1).Value;
     var secondStatement = arguments.ElementAt(2).Value;
     var factory = new CompileResultFactory();
     return condition ? factory.Create(firstStatement) : factory.Create(secondStatement);
 }
 public MatchViewModel(IEnumerable<Club> clubs, Ranking ranking)
 {
     this._clubs = clubs;
     this._home = clubs.ElementAt(0);
     this._away = clubs.ElementAt(1);
     this._ranking = ranking;
     this._hgoals =
     this._agoals = 0;
 }
 internal static IEnumerable<QueryFrame> YieldQueryFrames(this Controller controller, IEnumerable<string> queryItems)
 {
     for (int i = 0; i < queryItems.Count(); i += 4)
     {
         yield return new QueryFrame(
             key: queryItems.ElementAt(i + 2),
             value: queryItems.ElementAt(i + 3),
             op: queryItems.ElementAt(i + 1));
     }
 }
 private static void SetReturnedDateToBlank(IEnumerable<BorrowerItemRowViewModel> borrowerItemViewModels)
 {
     for (var i = 0; i < borrowerItemViewModels.Count(); i++)
     {
         if (borrowerItemViewModels.ElementAt(i).DateReturned.Equals("0001-01-01"))
         {
             borrowerItemViewModels.ElementAt(i).DateReturned = "";
         }
     }
 }
 private void AssertFilePathRegexInformation(
     IEnumerable<PathLevelWithRegex> itemsToAssert, int expectedRegexCount, string[] expectedPattern, int[] expectedLevels)
 {
     Assert.AreEqual(expectedRegexCount, itemsToAssert.Count());
     for (int i = 0; i < itemsToAssert.Count(); i++)
     {
         Assert.AreEqual(expectedPattern.ElementAt(i), itemsToAssert.ElementAt(i).Pattern, "the pattern is not expected");
         Assert.AreEqual(expectedLevels.ElementAt(i), itemsToAssert.ElementAt(i).Level, "the level is not expected");
     }
 }
Exemple #22
0
        private int PercentageChange(string servername, IEnumerable<DataRow> results)
        {
            if (results.Count<DataRow>() > 1)
            {
                decimal r = ((decimal)results.ElementAt(0).Field<Int32>("Measurement") / (decimal)results.ElementAt(1).Field<Int32>("Measurement"));
                return (int)(r * 100) - 100;
            }

            return 0;
        }
Exemple #23
0
 public CsvCellResult(IEnumerable<MeasurePoint> pointList)
 {
     Longtitute = pointList.ElementAt(0).Result.StrongestCell.Cell.Cell.Longtitute;
     Lattitute = pointList.ElementAt(0).Result.StrongestCell.Cell.Cell.Lattitute;
     StrongestCellName = pointList.ElementAt(0).Result.StrongestCell.CellName;
     StrongestCellRsrp = pointList.Select(x => x.Result.StrongestCell.ReceivedRsrp).SumOfPowerLevel(x => x);
     StrongestCellDistanceInMeter = pointList.Select(x => x.Result.StrongestCell.DistanceInMeter).Average();
     TotalInterferencePower = pointList.Select(x => x.Result.TotalInterferencePower).SumOfPowerLevel(x => x);
     NominalSinr = StrongestCellRsrp - TotalInterferencePower;
 }
Exemple #24
0
 public SubSet(GameManager manager, IEnumerable<string> arguments)
 {
     if (arguments.Count() < 3)
         throw new Exception("Usage: subset max_white max_black deck_type [deck_arguments]");
     _maxWhite = int.Parse(arguments.ElementAt(0));
     _maxBlack = int.Parse(arguments.ElementAt(1));
     _deck = (IDeckType) GameManager.DeckTypes[arguments.ElementAt(2)]
         .GetConstructor(new Type[] { typeof(GameManager), typeof(IEnumerable<string>) })
         .Invoke(new object[] { manager, arguments.Skip(3) });
 }
 static Person QueryDisambiguator(IEnumerable<Person> kandidati, string pitanje = "")
 {
     DisambiguatorForm dis = new DisambiguatorForm();
     foreach( Person p in kandidati ){
         dis.listBox.Items.Add(p.ToString());
     }
     if (dis.ShowDialog() == DialogResult.OK)
         return kandidati.ElementAt(dis.chosen);
     else
         return kandidati.ElementAt(0);
 }
 public LookupArguments(IEnumerable<FunctionArgument> arguments, ArgumentParsers argumentParsers)
 {
     _argumentParsers = argumentParsers;
     SearchedValue = arguments.ElementAt(0).Value;
     RangeAddress = arguments.ElementAt(1).Value.ToString();
     LookupIndex = (int)_argumentParsers.GetParser(DataType.Integer).Parse(arguments.ElementAt(2).Value);
     if (arguments.Count() > 3)
     {
         RangeLookup = (bool)_argumentParsers.GetParser(DataType.Boolean).Parse(arguments.ElementAt(3).Value);
     }
 }
        private static IEnumerable<double> CalculateDerivative(IEnumerable<int> functionYTable)
        {
            var deriviatives = new List<double>(functionYTable.Count() - 1);
            for (int x0 = 0; x0 < functionYTable.Count() - 1; x0++)
            {
                int y0 = functionYTable.ElementAt(x0);
                int y = functionYTable.ElementAt(x0 + 1);
                double deriative = y - y0; // (y - y0) / deltaX, but deltaX = 0;
                deriviatives.Add(deriative);
            }

            return deriviatives;
        }
Exemple #28
0
        /// <summary>
        /// Calculates the real area.
        /// </summary>
        /// <param name="vertices">The vertices.</param>
        /// <returns></returns>
        private static double CalculateRealArea(IEnumerable<Vector2> vertices)
        {
            double area = 0;
            int count = vertices.Count();

            for(int index = 0; index < count; ++index)
            {
                int nextIndex = (index + 1) % count;
                area += vertices.ElementAt(index).X * vertices.ElementAt(nextIndex).Y;
                area -= vertices.ElementAt(index).Y * vertices.ElementAt(nextIndex).X;
            }

            return area/2;
        }
 /// <summary>
 /// Write the changes passed on the command-line (used for writing with UAC elevation)
 /// </summary>
 private void WriteChangesFromCommandLine(IEnumerable<string> args)
 {
     for (int i = 0; i < args.Count(); i++)
     {
         if (args.ElementAt(i).ToLower() == "/system") {
             reg.SystemPath = ParseCommandLinePath(args.ElementAt(i + 1));
             i++;
         }
         if (args.ElementAt(i).ToLower() == "/user") {
             reg.UserPath = ParseCommandLinePath(args.ElementAt(i + 1));
             i++;
         }
     }
 }
Exemple #30
0
        /// <summary>
        /// Calculates Money Flow Index (MFI) indicator
        /// </summary>
        /// <param name="highs">Signal representing price highs</param>
        /// <param name="lows">Signal representing price lows</param>
        /// <param name="closes">Signal representing closing prices</param>
        /// <param name="periods">Number of periods</param>
        /// <param name="volume">Signal representing daily volumes</param>
        /// <returns>Object containing operation results</returns>
        public static MFIResult MFI(IEnumerable<double> highs, IEnumerable<double> lows, IEnumerable<double> closes, IEnumerable<int> volume, int periods)
        {
            double lastTypicalPrice = (highs.ElementAt(0) + lows.ElementAt(0) + closes.ElementAt(0)) / 3;

            var moneyFlowList = new List<MFIMoneyFlow>();

            for (int i = 1; i < highs.Count(); i++)
            {
                double typicalPrice = (highs.ElementAt(i) + lows.ElementAt(i) + closes.ElementAt(i)) / 3;
                bool up = typicalPrice > lastTypicalPrice;
                lastTypicalPrice = typicalPrice;

                double rawMoneyFlow = typicalPrice * volume.ElementAt(i);

                var moneyFlow = new MFIMoneyFlow();
                
                if (up)
                {
                    moneyFlow.PositiveMoneyFlow = rawMoneyFlow;
                }
                else
                {
                    moneyFlow.NegativeMoneyFlow = rawMoneyFlow;
                }

                moneyFlowList.Add(moneyFlow);
            }

            var moneyFlowIndexList = new List<double>();

            for (int i = 0; i < moneyFlowList.Count - periods + 1; i++)
            {
                var range = moneyFlowList.GetRange(i, periods);

                double positiveMoneyFlow = range.Sum(x => x.PositiveMoneyFlow);
                double negativeMoneyFlow = range.Sum(x => x.NegativeMoneyFlow);
                double moneyFlowRatio = positiveMoneyFlow / negativeMoneyFlow;
                double moneyFlowIndex = 100 - 100 / (1 + moneyFlowRatio);

                moneyFlowIndexList.Add(moneyFlowIndex);
           }

            var result = new MFIResult()
            {
                Values = moneyFlowIndexList,
                StartIndexOffset = periods
            };

            return result;
        }
Exemple #31
0
        /// <summary>
        /// Get variance
        /// </summary>
        public static double Variance(IEnumerable<double> data)
        {
            int len = data.Count();

            // Get average
            double avg = data.Average();

            double sum = 0;

            for (int i = 0; i < len; i++)
                sum += (data.ElementAt(i) - avg) * (data.ElementAt(i) - avg);

            return sum / (len - 1);
        }
        public LookupArguments(IEnumerable<FunctionArgument> arguments, ArgumentParsers argumentParsers, ParsingContext context)
        {
            _argumentParsers = argumentParsers;
            SearchedValue = arguments.ElementAt(0).Value;
            var arg1 = arguments.ElementAt(1).Value;
            var dataArray = arg1 as IEnumerable<FunctionArgument>;
            if (dataArray != null)
            {
                DataArray = dataArray;
                ArgumentDataType = LookupArgumentDataType.DataArray;
            }
            else
            {
                //if (arg1 is ExcelDataProvider.INameInfo) arg1 = ((ExcelDataProvider.INameInfo) arg1).Value;
                var rangeInfo = arg1 as ExcelDataProvider.IRangeInfo;
                if (rangeInfo != null)
                {
                    RangeAddress = string.IsNullOrEmpty(rangeInfo.Address.WorkSheet) ? rangeInfo.Address.Address : "'" + rangeInfo.Address.WorkSheet + "'!" + rangeInfo.Address.Address;
                    RangeInfo = rangeInfo;
                    ArgumentDataType = LookupArgumentDataType.ExcelRange;
                }
                else
                {
                    RangeAddress = arg1.ToString();
                    ArgumentDataType = LookupArgumentDataType.ExcelRange;
                }
            }
            var indexVal = arguments.ElementAt(2);

            if (indexVal.DataType == DataType.ExcelAddress)
            {
                var address = new ExcelAddress(indexVal.Value.ToString());
                var indexObj = context.ExcelDataProvider.GetRangeValue(address.WorkSheet, address._fromRow, address._fromCol);
                LookupIndex = (int) _argumentParsers.GetParser(DataType.Integer).Parse(indexObj);
            }
            else
            {
                LookupIndex = (int)_argumentParsers.GetParser(DataType.Integer).Parse(arguments.ElementAt(2).Value);
            }

            if (arguments.Count() > 3)
            {
                RangeLookup = (bool)_argumentParsers.GetParser(DataType.Boolean).Parse(arguments.ElementAt(3).Value);
            }
            else
            {
                RangeLookup = true;
            }
        }
Exemple #33
0
        protected override object GetItemAtRow(int row)
        {
            if (row < 0)
            {
                return(null);
            }
            var list = store as IList;

            if (list != null)
            {
                return(list[row]);
            }
            return(store?.ElementAt(row));
        }
        public static System.Collections.ArrayList Modes(this System.Collections.ArrayList x)
        {
            IEnumerable <KeyValuePair <object, uint> > frequencies = x.Frequencies();

            System.Collections.ArrayList modes = new System.Collections.ArrayList();

            uint occurences = ((KeyValuePair <object, uint>)frequencies?.ElementAt(0)).Value;

            foreach (KeyValuePair <object, uint> kvp in frequencies)
            {
                if (occurences == kvp.Value)
                {
                    modes.Add(kvp.Key);
                }
            }

            return(modes);
        }
Exemple #35
0
        public Message NextOrdered(bool ascending, ref int lastOffset)
        {
            if (lastOffset >= (Messages.Count - 1))
            {
                lastOffset = 0;
            }
            else
            {
                System.Threading.Interlocked.Increment(ref lastOffset);
            }

            if (ascending)
            {
                return(orderedAsc?.ElementAt(lastOffset));
            }
            else
            {
                return(orderedDesc?.ElementAt(lastOffset));
            }
        }
        public bool HotPlug(SynchronizationContext uiContext)
        {
            if (running)
            {
                DS4Devices.findControllers();
                IEnumerable <DS4Device> devices = DS4Devices.getDS4Controllers();
                //foreach (DS4Device device in devices)
                for (int i = 0, devlen = devices.Count(); i < devlen; i++)
                {
                    DS4Device device = devices.ElementAt(i);

                    if (device.isDisconnectingStatus())
                    {
                        continue;
                    }

                    if (((Func <bool>) delegate
                    {
                        for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength; Index++)
                        {
                            if (DS4Controllers[Index] != null &&
                                DS4Controllers[Index].getMacAddress() == device.getMacAddress())
                            {
                                return(true);
                            }
                        }

                        return(false);
                    })())
                    {
                        continue;
                    }

                    for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength; Index++)
                    {
                        if (DS4Controllers[Index] == null)
                        {
                            LogDebug(Properties.Resources.FoundController + device.getMacAddress() + " (" + device.getConnectionType() + ")");
                            Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
                            task.Start();
                            DS4Controllers[Index] = device;
                            device.setUiContext(uiContext);
                            device.Removal      += this.On_DS4Removal;
                            device.Removal      += DS4Devices.On_Removal;
                            device.SyncChange   += this.On_SyncChange;
                            device.SyncChange   += DS4Devices.UpdateSerial;
                            device.SerialChange += this.On_SerialChange;
                            if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
                            {
                                ProfilePath[Index] = getLinkedProfile(device.getMacAddress());
                            }
                            else
                            {
                                ProfilePath[Index] = OlderProfilePath[Index];
                            }

                            LoadProfile(Index, false, this, false, false);
                            touchPad[Index]      = new Mouse(Index, device);
                            device.LightBarColor = getMainColor(Index);
                            device.Report       += this.On_Report;
                            if (!getDInputOnly(Index) && device.isSynced())
                            {
                                int xinputIndex = x360Bus.FirstController + Index;
                                LogDebug("Plugging in X360 Controller #" + xinputIndex);
                                bool xinputResult = x360Bus.Plugin(Index);
                                if (xinputResult)
                                {
                                    LogDebug("X360 Controller # " + xinputIndex + " connected");
                                    useDInputOnly[Index] = false;
                                }
                                else
                                {
                                    LogDebug("X360 Controller # " + xinputIndex + " failed. Using DInput only mode");
                                    useDInputOnly[Index] = true;
                                }
                            }

                            TouchPadOn(Index, device);
                            CheckProfileOptions(Index, device);
                            device.StartUpdate();

                            //string filename = Path.GetFileName(ProfilePath[Index]);
                            if (File.Exists(appdatapath + "\\Profiles\\" + ProfilePath[Index] + ".xml"))
                            {
                                string prolog = Properties.Resources.UsingProfile.Replace("*number*", (Index + 1).ToString()).Replace("*Profile name*", ProfilePath[Index]);
                                LogDebug(prolog);
                                Log.LogToTray(prolog);
                            }
                            else
                            {
                                string prolog = Properties.Resources.NotUsingProfile.Replace("*number*", (Index + 1).ToString());
                                LogDebug(prolog);
                                Log.LogToTray(prolog);
                            }

                            break;
                        }
                    }
                }
            }

            return(true);
        }
Exemple #37
0
            private void AnalyzeNodeForXsltSettings(SyntaxNodeAnalysisContext context)
            {
                SyntaxNode    node  = context.Node;
                SemanticModel model = context.SemanticModel;

                SyntaxNode lhs = _syntaxNodeHelper.GetAssignmentLeftNode(node);
                SyntaxNode rhs = _syntaxNodeHelper.GetAssignmentRightNode(node);

                if (lhs == null || rhs == null)
                {
                    return;
                }

                ISymbol lhsSymbol = SyntaxNodeHelper.GetSymbol(lhs, model);

                if (lhsSymbol == null)
                {
                    return;
                }

                IMethodSymbol   rhsMethodSymbol   = _syntaxNodeHelper.GetCalleeMethodSymbol(rhs, model);
                IPropertySymbol rhsPropertySymbol = SyntaxNodeHelper.GetCalleePropertySymbol(rhs, model);

                if (SecurityDiagnosticHelpers.IsXsltSettingsCtor(rhsMethodSymbol, _xmlTypes))
                {
                    XsltSettingsEnvironment env = new XsltSettingsEnvironment();
                    _xsltSettingsEnvironments[lhsSymbol] = env;

                    env.XsltSettingsSymbol           = lhsSymbol;
                    env.XsltSettingsDefinitionSymbol = rhsMethodSymbol;
                    env.XsltSettingsDefinition       = node;
                    env.EnclosingConstructSymbol     = _syntaxNodeHelper.GetEnclosingConstructSymbol(node, model);
                    //default both properties are disbled
                    env.IsDocumentFunctionDisabled = true;
                    env.IsScriptDisabled           = true;

                    // XsltSettings Constructor (Boolean, Boolean)
                    if (rhsMethodSymbol.Parameters.Any())
                    {
                        IEnumerable <SyntaxNode> argumentExpressionNodes = _syntaxNodeHelper.GetObjectCreationArgumentExpressionNodes(rhs);
                        env.IsDocumentFunctionDisabled = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(argumentExpressionNodes.ElementAt(0), model);
                        env.IsScriptDisabled           = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(argumentExpressionNodes.ElementAt(1), model);
                    }

                    foreach (SyntaxNode arg in _syntaxNodeHelper.GetObjectInitializerExpressionNodes(rhs))
                    {
                        SyntaxNode argLhs = _syntaxNodeHelper.GetAssignmentLeftNode(arg);
                        SyntaxNode argRhs = _syntaxNodeHelper.GetAssignmentRightNode(arg);

                        ISymbol argLhsSymbol = SyntaxNodeHelper.GetSymbol(argLhs, model);

                        // anything other than a constant false is treated as true
                        if (SecurityDiagnosticHelpers.IsXsltSettingsEnableDocumentFunctionProperty(argLhsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            env.IsDocumentFunctionDisabled = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(argRhs, model);
                        }
                        else if (SecurityDiagnosticHelpers.IsXsltSettingsEnableScriptProperty(argLhsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            env.IsScriptDisabled = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(argRhs, model);
                        }
                    }
                }
                else if (SecurityDiagnosticHelpers.IsXsltSettingsDefaultProperty(rhsPropertySymbol, _xmlTypes))
                {
                    XsltSettingsEnvironment env = new XsltSettingsEnvironment();
                    _xsltSettingsEnvironments[lhsSymbol] = env;

                    env.XsltSettingsSymbol           = lhsSymbol;
                    env.XsltSettingsDefinitionSymbol = rhsPropertySymbol;
                    env.XsltSettingsDefinition       = node;
                    env.EnclosingConstructSymbol     = _syntaxNodeHelper.GetEnclosingConstructSymbol(node, model);
                    env.IsDocumentFunctionDisabled   = true;
                    env.IsScriptDisabled             = true;
                }
                else if (SecurityDiagnosticHelpers.IsXsltSettingsTrustedXsltProperty(rhsPropertySymbol, _xmlTypes))
                {
                    XsltSettingsEnvironment env = new XsltSettingsEnvironment();
                    _xsltSettingsEnvironments[lhsSymbol] = env;

                    env.XsltSettingsSymbol           = lhsSymbol;
                    env.XsltSettingsDefinitionSymbol = rhsPropertySymbol;
                    env.XsltSettingsDefinition       = node;
                    env.EnclosingConstructSymbol     = _syntaxNodeHelper.GetEnclosingConstructSymbol(node, model);
                }
                else
                {
                    bool isXlstSettingsEnableDocumentFunctionProperty = SecurityDiagnosticHelpers.IsXsltSettingsEnableDocumentFunctionProperty(lhsSymbol as IPropertySymbol, _xmlTypes);
                    bool isXlstSettingsEnableScriptProperty           = SecurityDiagnosticHelpers.IsXsltSettingsEnableScriptProperty(lhsSymbol as IPropertySymbol, _xmlTypes);


                    if (isXlstSettingsEnableDocumentFunctionProperty ||
                        isXlstSettingsEnableScriptProperty)
                    {
                        SyntaxNode lhsExpressionNode = _syntaxNodeHelper.GetMemberAccessExpressionNode(lhs);
                        if (lhsExpressionNode == null)
                        {
                            return;
                        }

                        ISymbol lhsExpressionSymbol = SyntaxNodeHelper.GetSymbol(lhsExpressionNode, model);
                        if (lhsExpressionSymbol == null)
                        {
                            return;
                        }

                        if (!_xsltSettingsEnvironments.TryGetValue(lhsExpressionSymbol, out XsltSettingsEnvironment env))
                        {
                            env = new XsltSettingsEnvironment
                            {
                                XsltSettingsSymbol = lhsExpressionSymbol
                            };
                            _xsltSettingsEnvironments[lhsExpressionSymbol] = env;
                        }

                        if (isXlstSettingsEnableDocumentFunctionProperty)
                        {
                            env.IsDocumentFunctionDisabled = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(rhs, model);
                        }
                        else if (isXlstSettingsEnableScriptProperty)
                        {
                            env.IsScriptDisabled = SyntaxNodeHelper.NodeHasConstantValueBoolFalse(rhs, model);
                        }
                    }
                }
            }
        /// <summary>
        /// Gets the string to insert values into the SQL table.
        /// </summary>
        ///
        /// <remarks>
        /// <example>
        /// <code>
        /// INSERT INTO BCPTest VALUES
        /// (
        /// 'string',
        /// 'string',
        /// NULL,
        /// NULL
        /// ),
        /// (
        /// 'string',
        /// 'string',
        /// NULL,
        /// NULL
        /// )
        /// </code>
        /// </example>
        /// </remarks>
        ///
        /// <param name="columns">List of SQL types.</param>
        /// <param name="rows">Values.</param>
        /// <returns>SQL insert into table string.</returns>
        static private string GetInsertIntoString(List <IBCPSerialization> columns, IEnumerable <object> rows)
        {
            StringBuilder insertIntoString = new StringBuilder();

            if (rows.Count() == 0)
            {
                return(string.Empty);
            }

            insertIntoString.AppendLine("INSERT INTO BCPTest VALUES");

            for (int i = 0; i < rows.Count(); i++)
            {
                int modulo = i % columns.Count();
                if (modulo == 0 && i > 0)
                {
                    insertIntoString.AppendLine("),");
                }
                if (modulo > 0)
                {
                    insertIntoString.AppendLine(",");
                }
                if (modulo == 0)
                {
                    insertIntoString.Append("(");
                }

                IBCPSerialization column = columns[modulo];
                object            row    = rows.ElementAt(i);

                // FIXME Is there a better way than casting every type?
                // Don't forget to add new SQL types here and to modify the unit tests accordingly
                if (column is SQLBinary)
                {
                    SQLBinary sql   = (SQLBinary)column;
                    byte[]    value = (byte[])row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat(
                            "CAST('{0}' AS binary({1}))",
                            Encoding.Default.GetString(value), sql.Length);
                    }
                }
                else if (column is SQLChar)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLInt)
                {
                    int?value = (int?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("{0}", value.Value);
                    }
                }
                else if (column is SQLNChar)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLNVarChar)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLVarBinary)
                {
                    SQLVarBinary sql   = (SQLVarBinary)column;
                    byte[]       value = (byte[])row;

                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        if (sql.Length == SQLVarBinary.MAX)
                        {
                            insertIntoString.AppendFormat(
                                "CAST('{0}' AS varbinary(max))",
                                Encoding.Default.GetString(value));
                        }
                        else
                        {
                            insertIntoString.AppendFormat(
                                "CAST('{0}' AS varbinary({1}))",
                                Encoding.Default.GetString(value), sql.Length);
                        }
                    }
                }
                else if (column is SQLVarChar)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLNText)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLText)
                {
                    string value = (string)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value);
                    }
                }
                else if (column is SQLXml)
                {
                    XmlDocument value = (XmlDocument)row;
                    if (value == null)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.DocumentElement.OuterXml);
                    }
                }
                else if (column is SQLReal)
                {
                    float?value = (float?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("{0}", value.Value);
                    }
                }
                else if (column is SQLFloat)
                {
                    if (row is float)
                    {
                        // Don't treat null case here
                        float?value = (float?)row;
                        insertIntoString.AppendFormat("{0}", value.Value);
                    }
                    else
                    {
                        // If we don't know, let's cast it to double
                        // if value is null then double? will work, not float?
                        // More explanations inside SQLFloat
                        double?value = (double?)row;
                        if (!value.HasValue)
                        {
                            insertIntoString.Append("NULL");
                        }
                        else
                        {
                            insertIntoString.AppendFormat("{0}", value.Value);
                        }
                    }
                }
                else if (column is SQLUniqueIdentifier)
                {
                    Guid?value = (Guid?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.Value);
                    }
                }
                else if (column is SQLBigInt)
                {
                    long?value = (long?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("{0}", value.Value);
                    }
                }
                else if (column is SQLDateTime)
                {
                    DateTime?value = (DateTime?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.Value);
                    }
                }
                else if (column is SQLDateTime2)
                {
                    DateTime?value = (DateTime?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.Value);
                    }
                }
                else if (column is SQLDate)
                {
                    DateTime?value = (DateTime?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.Value);
                    }
                }
                else if (column is SQLTime)
                {
                    DateTime?value = (DateTime?)row;
                    if (!value.HasValue)
                    {
                        insertIntoString.Append("NULL");
                    }
                    else
                    {
                        insertIntoString.AppendFormat("'{0}'", value.Value);
                    }
                }
                else
                {
                    System.Diagnostics.Trace.Assert(false);
                }
            }

            insertIntoString.Append(")");

            return(insertIntoString.ToString());
        }
        public bool Start(object tempui, bool showlog = true)
        {
            if (x360Bus.Open() && x360Bus.Start())
            {
                if (showlog)
                {
                    LogDebug(Properties.Resources.Starting);
                }

                LogDebug("Connection to Scp Virtual Bus established");

                DS4Devices.isExclusiveMode = getUseExclusiveMode();
                if (showlog)
                {
                    LogDebug(Properties.Resources.SearchingController);
                    LogDebug(DS4Devices.isExclusiveMode ? Properties.Resources.UsingExclusive : Properties.Resources.UsingShared);
                }

                try
                {
                    DS4Devices.findControllers();
                    IEnumerable <DS4Device> devices = DS4Devices.getDS4Controllers();
                    //int ind = 0;
                    DS4LightBar.defaultLight = false;
                    //foreach (DS4Device device in devices)

                    for (int i = 0, devCount = devices.Count(); i < devCount; i++)
                    {
                        DS4Device device = devices.ElementAt(i);
                        if (showlog)
                        {
                            LogDebug(Properties.Resources.FoundController + device.getMacAddress() + " (" + device.getConnectionType() + ")");
                        }

                        Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
                        task.Start();

                        DS4Controllers[i] = device;
                        device.setUiContext(tempui as SynchronizationContext);
                        device.Removal      += this.On_DS4Removal;
                        device.Removal      += DS4Devices.On_Removal;
                        device.SyncChange   += this.On_SyncChange;
                        device.SyncChange   += DS4Devices.UpdateSerial;
                        device.SerialChange += this.On_SerialChange;
                        if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
                        {
                            ProfilePath[i] = getLinkedProfile(device.getMacAddress());
                        }
                        else
                        {
                            ProfilePath[i] = OlderProfilePath[i];
                        }
                        LoadProfile(i, false, this, false, false);
                        touchPad[i]          = new Mouse(i, device);
                        device.LightBarColor = getMainColor(i);

                        if (!getDInputOnly(i) && device.isSynced())
                        {
                            int xinputIndex = x360Bus.FirstController + i;
                            LogDebug("Plugging in X360 Controller #" + xinputIndex);
                            bool xinputResult = x360Bus.Plugin(i);
                            if (xinputResult)
                            {
                                LogDebug("X360 Controller # " + xinputIndex + " connected");
                                useDInputOnly[i] = false;
                            }
                            else
                            {
                                LogDebug("X360 Controller # " + xinputIndex + " failed. Using DInput only mode");
                                useDInputOnly[i] = true;
                            }
                        }

                        device.Report += this.On_Report;
                        TouchPadOn(i, device);
                        CheckProfileOptions(i, device, true);
                        device.StartUpdate();
                        //string filename = ProfilePath[ind];
                        //ind++;
                        if (showlog)
                        {
                            if (File.Exists(appdatapath + "\\Profiles\\" + ProfilePath[i] + ".xml"))
                            {
                                string prolog = Properties.Resources.UsingProfile.Replace("*number*", (i + 1).ToString()).Replace("*Profile name*", ProfilePath[i]);
                                LogDebug(prolog);
                                Log.LogToTray(prolog);
                            }
                            else
                            {
                                string prolog = Properties.Resources.NotUsingProfile.Replace("*number*", (i + 1).ToString());
                                LogDebug(prolog);
                                Log.LogToTray(prolog);
                            }
                        }

                        if (i >= 4) // out of Xinput devices!
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    LogDebug(e.Message);
                    Log.LogToTray(e.Message);
                }

                running = true;
            }
            else
            {
                string logMessage = "Could not connect to Scp Virtual Bus Driver. Please check the status of the System device in Device Manager";
                LogDebug(logMessage);
                Log.LogToTray(logMessage);
            }

            runHotPlug = true;
            return(true);
        }
Exemple #40
0
        /// <summary>
        /// If the argument is a boolean value its value will be returned.
        /// If the argument is an integer value, true will be returned if its
        /// value is not 0, otherwise false.
        /// </summary>
        /// <param name="arguments"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        protected bool ArgToBool(IEnumerable <FunctionArgument> arguments, int index)
        {
            var obj = arguments.ElementAt(index).Value ?? string.Empty;

            return((bool)_argumentParsers.GetParser(DataType.Boolean).Parse(obj));
        }
Exemple #41
0
 /// <summary>
 /// Returns the value of the argument att the position of the 0-based
 /// <paramref name="index"/> as a <see cref="System.Double"/>.
 /// </summary>
 /// <param name="arguments"></param>
 /// <param name="index"></param>
 /// <returns>Value of the argument as an integer.</returns>
 /// <exception cref="ExcelErrorValueException"></exception>
 protected double ArgToDecimal(IEnumerable <FunctionArgument> arguments, int index)
 {
     return(ArgToDecimal(arguments.ElementAt(index).Value));
 }
Exemple #42
0
        private static void AssertExportableCombinedFailureMechanismSectionResult(CombinedFailureMechanismSectionAssemblyResult expectedSection,
                                                                                  ExportableCombinedFailureMechanismSection actualSection,
                                                                                  ExportableCombinedSectionAssembly actualSectionResult,
                                                                                  bool hasAssemblyGroupResults)
        {
            Assert.AreSame(actualSection, actualSectionResult.Section);
            Assert.AreEqual(expectedSection.TotalResult, actualSectionResult.CombinedSectionAssemblyResult.AssemblyGroup);
            Assert.AreEqual(ExportableAssemblyMethodFactory.Create(expectedSection.CombinedSectionResultAssemblyMethod), actualSectionResult.CombinedSectionAssemblyResult.AssemblyGroupAssemblyMethod);

            IEnumerable <ExportableFailureMechanismCombinedSectionAssemblyResult> failureMechanismCombinedSectionResults = actualSectionResult.FailureMechanismResults;

            if (!hasAssemblyGroupResults)
            {
                CollectionAssert.IsEmpty(failureMechanismCombinedSectionResults);
                return;
            }

            Assert.AreEqual(17, failureMechanismCombinedSectionResults.Count());
            Assert.IsTrue(failureMechanismCombinedSectionResults.All(result => result.SectionAssemblyResult.AssemblyMethod == ExportableAssemblyMethodFactory.Create(
                                                                         expectedSection.FailureMechanismResultsAssemblyMethod)));

            AssertSubSection(expectedSection.Piping, "STPH", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(0));
            AssertSubSection(expectedSection.GrassCoverErosionInwards, "GEKB", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(1));
            AssertSubSection(expectedSection.MacroStabilityInwards, "STBI", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(2));
            AssertSubSection(expectedSection.Microstability, "STMI", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(3));
            AssertSubSection(expectedSection.StabilityStoneCover, "ZST", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(4));
            AssertSubSection(expectedSection.WaveImpactAsphaltCover, "AGK", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(5));
            AssertSubSection(expectedSection.WaterPressureAsphaltCover, "AWO", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(6));
            AssertSubSection(expectedSection.GrassCoverErosionOutwards, "GEBU", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(7));
            AssertSubSection(expectedSection.GrassCoverSlipOffOutwards, "GABU", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(8));
            AssertSubSection(expectedSection.GrassCoverSlipOffInwards, "GABI", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(9));
            AssertSubSection(expectedSection.HeightStructures, "HTKW", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(10));
            AssertSubSection(expectedSection.ClosingStructures, "BSKW", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(11));
            AssertSubSection(expectedSection.PipingStructure, "PKW", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(12));
            AssertSubSection(expectedSection.StabilityPointStructures, "STKWp", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(13));
            AssertSubSection(expectedSection.DuneErosion, "DA", ExportableFailureMechanismType.Generic,
                             failureMechanismCombinedSectionResults.ElementAt(14));
            AssertSubSection(expectedSection.SpecificFailureMechanisms[0], "Nieuw1", ExportableFailureMechanismType.Specific,
                             failureMechanismCombinedSectionResults.ElementAt(15));
            AssertSubSection(expectedSection.SpecificFailureMechanisms[1], "Nieuw2", ExportableFailureMechanismType.Specific,
                             failureMechanismCombinedSectionResults.ElementAt(16));
        }
Exemple #43
0
        private void button1_Click(object sender, EventArgs e)
        {
            XElement xe = XElement.Load(@"D:\减速器设计系统\中间轴2计算参数.xml");

            IEnumerable <XElement> elements = from 轴承配置 in xe.Elements("受力计算参数")
                                              select 轴承配置;

            Shaft.Faz = double.Parse(elements.ElementAt(0).Element("faz").Value);
            Shaft.Fa1 = double.Parse(elements.ElementAt(0).Element("fa1").Value);
            Shaft.r1  = double.Parse(elements.ElementAt(0).Element("r1").Value);
            Shaft.Fbz = double.Parse(elements.ElementAt(0).Element("fbz").Value);
            Shaft.Fa2 = double.Parse(elements.ElementAt(0).Element("fa2").Value);
            Shaft.r2  = double.Parse(elements.ElementAt(0).Element("r2").Value);
            Shaft.Fay = double.Parse(elements.ElementAt(0).Element("fay").Value);
            Shaft.Fby = double.Parse(elements.ElementAt(0).Element("fby").Value);
            Shaft.L2  = double.Parse(elements.ElementAt(0).Element("L2").Value);
            Shaft.L3  = double.Parse(elements.ElementAt(0).Element("L3").Value);
            Shaft.L4  = double.Parse(elements.ElementAt(0).Element("L4").Value);
            //C-C 水平面 垂直面 合成弯矩
            txtMczL.Text = Shaft.ShaftMczL3().ToString();
            txtMczR.Text = Shaft.ShaftMczR3().ToString();

            txtMcy.Text = Shaft.ShaftMcy3().ToString();

            txtMcL.Text = Shaft.SyntheticMoment(double.Parse(txtMczL.Text), double.Parse(txtMcy.Text)).ToString();
            txtMcR.Text = Shaft.SyntheticMoment(double.Parse(txtMczR.Text), double.Parse(txtMcy.Text)).ToString();

            //D-D水平面 垂直面 合成弯矩
            txtMdzR.Text = Shaft.ShaftMdzR3().ToString();
            txtMdzL.Text = Shaft.ShaftMdzL3().ToString();

            txtMdy.Text = Shaft.ShaftMdy3().ToString();

            txtMdL.Text = Shaft.SyntheticMoment(double.Parse(txtMdzL.Text), double.Parse(txtMdy.Text)).ToString();
            txtMdR.Text = Shaft.SyntheticMoment(double.Parse(txtMdzR.Text), double.Parse(txtMdy.Text)).ToString();
        }
Exemple #44
0
        /// <summary>
        ///   Parses the specified method element.
        /// </summary>
        /// <param name = "functionElement">The function element.</param>
        /// <returns></returns>
        public FunctionEntity Parse(TypedEntity typedEntity, XElement functionElement)
        {
            FunctionEntity functionEntity = new FunctionEntity();

            // Extract name
            String name = functionElement.TrimAll();

            functionEntity.Name = name;

            this.Logger.WriteLine("  Function '" + name + "'");

            // Extract abstract
            XElement abstractElement = (from el in functionElement.ElementsAfterSelf("p")
                                        where (String)el.Attribute("class") == "abstract"
                                        select el).FirstOrDefault();

            functionEntity.Summary.Add(abstractElement.TrimAll());

            // Extract declaration
            XElement declarationElement = (from el in functionElement.ElementsAfterSelf("pre")
                                           where (String)el.Attribute("class") == "declaration"
                                           select el).FirstOrDefault();

            String signature = declarationElement.TrimAll();

            if (signature.StartsWith("#define"))
            {
                this.Logger.WriteLine("SKIPPING define statement: " + name);
                return(null);
            }
            if (signature.StartsWith("typedef"))
            {
                this.Logger.WriteLine("SKIPPING define statement: " + name);
                return(null);
            }
            if (!signature.Contains("("))                // e.g. NS_DURING
            {
                this.Logger.WriteLine("SKIPPING non-function statement: " + name);
                return(null);
            }

            // Trim down signature
            while (signature.IndexOf("  ") != -1)
            {
                signature = signature.Replace("  ", " ");
            }
            functionEntity.Signature = signature;
            //Console.WriteLine("signature='" + signature + "'");

            // Parse signature
            int pos = signature.IndexOf(name);

            if (pos == -1)
            {
                this.Logger.WriteLine("MISMATCH between name and declaration: " + name);
                return(null);
            }
            String returnType   = signature.Substring(0, pos).Trim();
            int    paramsIndex  = pos + name.Length;
            int    paramsLength = signature.IndexOf(')') + 1 - paramsIndex;          // Stop before getting to function body
            String parameters   = signature.Substring(paramsIndex, paramsLength).Trim();

            parameters = parameters.Trim(';', '(', ')').Trim();
            if (parameters != "void")
            {
                foreach (string parameter in parameters.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    String parameterType = "NOTYPE";
                    String parameterName = "NONAME";

                    //Console.WriteLine("parameter='" + parameter + "'");
                    Match r = PARAMETER_REGEX.Match(parameter);
                    if (r.Success)
                    {
                        parameterType = r.Groups [2].Value.Trim();
                        parameterName = r.Groups [3].Value.Trim();
                    }
                    else if (parameter.Trim() == "...")
                    {
                        parameterType = "params Object[]";
                        parameterName = "values";
                    }
                    else
                    {
                        this.Logger.WriteLine("FAILED to parse parameter: " + parameter);
                        return(null);
                    }
                    parameterType = parameterType.Trim();

                    MethodParameterEntity parameterEntity = new MethodParameterEntity();
                    bool isOut, isByRef, isBlock;
                    parameterEntity.Type    = this.TypeManager.ConvertType(parameterType, out isOut, out isByRef, out isBlock, this.Logger);
                    parameterEntity.IsOut   = isOut;
                    parameterEntity.IsByRef = isByRef;
                    parameterEntity.IsBlock = isBlock;
                    parameterEntity.Name    = TypeManager.ConvertName(parameterName);
                    functionEntity.Parameters.Add(parameterEntity);
                }
            }

            // Extract return type
            functionEntity.ReturnType = this.TypeManager.ConvertType(returnType, this.Logger);

            // Extract parameter documentation
            if (functionEntity.Parameters.Count > 0)
            {
                XElement termList = (from el in functionElement.Elements("div").Elements("dl")
                                     where (String)el.Parent.Attribute("class") == "api parameters" &&
                                     (String)el.Attribute("class") == "termdef"
                                     select el).FirstOrDefault();
                if (termList != null)
                {
                    IEnumerable <XElement> dtList = from el in termList.Elements("dt") select el;
                    IEnumerable <XElement> ddList = from el in termList.Elements("dd") select el;

                    if (dtList.Count() == ddList.Count())
                    {
                        // Iterate over definitions
                        for (int i = 0; i < dtList.Count(); i++)
                        {
                            String term = dtList.ElementAt(i).TrimAll();
                            IEnumerable <String> summaries = ddList.ElementAt(i).Elements("p").Select(p => p.Value.TrimAll());

                            // Find the parameter
                            MethodParameterEntity parameterEntity = functionEntity.Parameters.Find(p => String.Equals(p.Name, term));
                            if (parameterEntity != null)
                            {
                                foreach (string sum in summaries)
                                {
                                    parameterEntity.Summary.Add(sum);
                                }
                            }
                        }
                    }
                }
            }

            // Fix the name only after looking for the documentation
            for (int i = 0; i < functionEntity.Parameters.Count; i++)
            {
                functionEntity.Parameters [i].Name = this.TypeManager.ConvertName(functionEntity.Parameters [i].Name);
            }

            // Get the summary for return type
            if (!String.Equals(functionEntity.ReturnType, "void", StringComparison.OrdinalIgnoreCase))
            {
                XElement returnValueElement = (from el in functionElement.ElementsAfterSelf("div")
                                               where (String)el.Attribute("class") == "return_value"
                                               select el).FirstOrDefault();
                if (returnValueElement != null)
                {
                    IEnumerable <String> documentations = returnValueElement.Elements("p").Select(p => p.Value.TrimAll());
                    functionEntity.ReturnsDocumentation = String.Join(String.Empty, documentations.ToArray());
                }
            }

            //// Extract discussion
            //XElement discussionElement = (from el in functionElement.ElementsAfterSelf("div")
            //                              where (String) el.Attribute("class") == "api discussion"
            //                              select el).FirstOrDefault();
            //if (discussionElement != null)
            //{
            //    foreach (XElement paragraph in discussionElement.Elements("p"))
            //    {
            //        functionEntity.Summary.Add(paragraph.TrimAll());
            //    }
            //}

            // Get the availability
            XElement availabilityElement = (from el in functionElement.ElementsAfterSelf("div")
                                            where (String)el.Attribute("class") == "api availability"
                                            select el).FirstOrDefault();
            String minAvailability = availabilityElement.Elements("ul").Elements("li").FirstOrDefault().TrimAll();

            functionEntity.MinAvailability = CommentHelper.ExtractAvailability(minAvailability);

            return(functionEntity);
        }
Exemple #45
0
        public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var  number = ArgToDecimal(arguments, 0);
            var  refer  = arguments.ElementAt(1);
            bool asc    = false;

            if (arguments.Count() > 2)
            {
                asc = base.ArgToBool(arguments, 2);
            }
            var l = new List <double>();

            foreach (var c in refer.ValueAsRangeInfo)
            {
                var v = Utils.ConvertUtil.GetValueDouble(c.Value, false, true);
                if (!double.IsNaN(v))
                {
                    l.Add(v);
                }
            }
            l.Sort();
            double ix;

            if (asc)
            {
                ix = l.IndexOf(number) + 1;
                if (_isAvg)
                {
                    int st = Convert.ToInt32(ix);
                    while (l.Count > st && l[st] == number)
                    {
                        st++;
                    }
                    if (st > ix)
                    {
                        ix = ix + ((st - ix) / 2D);
                    }
                }
            }
            else
            {
                ix = l.LastIndexOf(number);
                if (_isAvg)
                {
                    int st = Convert.ToInt32(ix) - 1;
                    while (0 <= st && l[st] == number)
                    {
                        st--;
                    }
                    if (st + 1 < ix)
                    {
                        ix = ix - ((ix - st - 1) / 2D);
                    }
                }
                ix = l.Count - ix;
            }
            if (ix <= 0 || ix > l.Count)
            {
                return(new CompileResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError));
            }
            else
            {
                return(CreateResult(ix, DataType.Decimal));
            }
        }
        public static XElement GetChannel(XElement measuremententry, int channelnum)
        {
            IEnumerable <XElement> channels = measuremententry.Elements("{http://www.unisens.org/unisens2.0}channel");

            return(channels.ElementAt(channelnum));
        }
Exemple #47
0
        /// <summary>
        /// This method is considered as main execute method which defines the
        /// step by step algorithm. Derived class flows the defined flow by this
        /// method.
        /// </summary>
        /// <param name="referenceSequenceList">Reference sequence.</param>
        /// <param name="originalQuerySequences">List of input sequences.</param>
        /// <returns>A list of sequence alignment.</returns>
        private IEnumerable <IPairwiseSequenceAlignment> Alignment(IEnumerable <ISequence> referenceSequenceList, IEnumerable <ISequence> originalQuerySequences)
        {
            ConsensusResolver = new SimpleConsensusResolver(referenceSequenceList.ElementAt(0).Alphabet);

            IEnumerable <ISequence> querySequenceList =
                ForwardOnly ? originalQuerySequences
                    : (ReverseOnly
                        ? ReverseComplementSequenceList(originalQuerySequences)
                        : AddReverseComplementsToSequenceList(originalQuerySequences));

            IList <IPairwiseSequenceAlignment> results = new List <IPairwiseSequenceAlignment>();

            var deltas = new List <DeltaAlignment>();

            foreach (ISequence refSequence in referenceSequenceList)
            {
                this.nucmerAlgo = new NUCmer(refSequence);

                if (GapOpenCost != DefaultGapOpenCost)
                {
                    this.nucmerAlgo.GapOpenCost = GapOpenCost;
                }
                if (GapExtensionCost != DefaultGapExtensionCost)
                {
                    this.nucmerAlgo.GapExtensionCost = GapExtensionCost;
                }
                if (LengthOfMUM != DefaultLengthOfMUM)
                {
                    this.nucmerAlgo.LengthOfMUM = LengthOfMUM;
                }

                // Set the ClusterBuilder properties to defaults
                if (FixedSeparation != ClusterBuilder.DefaultFixedSeparation)
                {
                    this.nucmerAlgo.FixedSeparation = FixedSeparation;
                }
                if (MaximumSeparation != ClusterBuilder.DefaultMaximumSeparation)
                {
                    this.nucmerAlgo.MaximumSeparation = MaximumSeparation;
                }
                if (MinimumScore != ClusterBuilder.DefaultMinimumScore)
                {
                    this.nucmerAlgo.MinimumScore = MinimumScore;
                }
                if (SeparationFactor != ClusterBuilder.DefaultSeparationFactor)
                {
                    this.nucmerAlgo.SeparationFactor = SeparationFactor;
                }
                if (BreakLength != ModifiedSmithWaterman.DefaultBreakLength)
                {
                    this.nucmerAlgo.BreakLength = BreakLength;
                }

                this.nucmerAlgo.ConsensusResolver = ConsensusResolver;
                if (SimilarityMatrix != null)
                {
                    this.nucmerAlgo.SimilarityMatrix = SimilarityMatrix;
                }

                foreach (ISequence querySequence in querySequenceList)
                {
                    IEnumerable <DeltaAlignment> deltaAlignment = this.nucmerAlgo.GetDeltaAlignments(querySequence, !MaxMatch, querySequence.IsMarkedAsReverseComplement());
                    deltas.AddRange(deltaAlignment);
                }
            }

            if (deltas.Count > 0)
            {
                ISequence concatReference = referenceSequenceList.ElementAt(0);
                //// concat all the sequences into one sequence
                if (referenceSequenceList.Count() > 1)
                {
                    concatReference = ConcatSequence(referenceSequenceList);
                }

                foreach (ISequence querySequence in querySequenceList)
                {
                    List <DeltaAlignment>      qDelta            = deltas.Where(d => d.QuerySequence.Equals(querySequence)).ToList();
                    IPairwiseSequenceAlignment sequenceAlignment = new PairwiseSequenceAlignment(concatReference, querySequence);

                    // Convert delta alignments to sequence alignments
                    IList <PairwiseAlignedSequence> alignments = ConvertDeltaToAlignment(qDelta);

                    if (alignments.Count > 0)
                    {
                        foreach (PairwiseAlignedSequence align in alignments)
                        {
                            // Calculate the score of alignment
                            align.Score = CalculateScore(
                                align.FirstSequence,
                                align.SecondSequence);

                            // Make Consensus
                            align.Consensus = MakeConsensus(
                                align.FirstSequence,
                                align.SecondSequence);

                            sequenceAlignment.PairwiseAlignedSequences.Add(align);
                        }
                    }

                    results.Add(sequenceAlignment);
                }
            }

            return(results);
        }
 protected override object GetItemAt(NSIndexPath indexPath)
 {
     return(ItemsSource?.ElementAt(indexPath.Row));
 }
Exemple #49
0
            private void AnalyzeNodeForXslCompiledTransformLoad(SyntaxNodeAnalysisContext context)
            {
                SyntaxNode    node         = context.Node;
                SemanticModel model        = context.SemanticModel;
                IMethodSymbol methodSymbol = _syntaxNodeHelper.GetCalleeMethodSymbol(node, model);

                if (SecurityDiagnosticHelpers.IsXslCompiledTransformLoad(methodSymbol, _xmlTypes))
                {
                    bool isSecureResolver;
                    bool isSecureSettings;
                    bool isSetInBlock;

                    int xmlResolverIndex  = SecurityDiagnosticHelpers.GetXmlResolverParameterIndex(methodSymbol, _xmlTypes);
                    int xsltSettingsIndex = SecurityDiagnosticHelpers.GetXsltSettingsParameterIndex(methodSymbol, _xmlTypes);

                    // Overloads with no XmlResolver and XstlSettings specified are secure since they all have folowing behavior:
                    //  1. An XmlUrlResolver with no user credentials is used to process any xsl:import or xsl:include elements.
                    //  2. The document() function is disabled.
                    //  3. Embedded scripts are not supported.
                    if (xmlResolverIndex >= 0 &&
                        xsltSettingsIndex >= 0)
                    {
                        IEnumerable <SyntaxNode> argumentExpressionNodes = _syntaxNodeHelper.GetInvocationArgumentExpressionNodes(node);
                        SyntaxNode resolverNode = argumentExpressionNodes.ElementAt(xmlResolverIndex);

                        isSecureResolver = SyntaxNodeHelper.NodeHasConstantValueNull(resolverNode, model) ||
                                           SecurityDiagnosticHelpers.IsXmlSecureResolverType(model.GetTypeInfo(resolverNode).Type, _xmlTypes);


                        SyntaxNode settingsNode   = argumentExpressionNodes.ElementAt(xsltSettingsIndex);
                        ISymbol    settingsSymbol = SyntaxNodeHelper.GetSymbol(settingsNode, model);

                        // 1. pass null or XsltSettings.Default as XsltSetting : secure
                        if (settingsSymbol == null || SecurityDiagnosticHelpers.IsXsltSettingsDefaultProperty(settingsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            isSetInBlock     = true;
                            isSecureSettings = true;
                        }
                        // 2. XsltSettings.TrustedXslt : insecure
                        else if (SecurityDiagnosticHelpers.IsXsltSettingsTrustedXsltProperty(settingsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            isSetInBlock     = true;
                            isSecureSettings = false;
                        }
                        // 3. check xsltSettingsEnvironments, if IsScriptDisabled && IsDocumentFunctionDisabled then secure, else insecure
                        else if (_xsltSettingsEnvironments.TryGetValue(settingsSymbol, out XsltSettingsEnvironment env))
                        {
                            isSetInBlock     = false;
                            isSecureSettings = env.IsDocumentFunctionDisabled && env.IsScriptDisabled;
                        }
                        //4. symbol for settings is not found => passed in without any change => assume insecure
                        else
                        {
                            isSetInBlock     = true;
                            isSecureSettings = false;
                        }

                        if (!isSecureSettings && !isSecureResolver)
                        {
                            LocalizableResourceString message = SecurityDiagnosticHelpers.GetLocalizableResourceString(
                                isSetInBlock ? nameof(MicrosoftNetFrameworkAnalyzersResources.XslCompiledTransformLoadInsecureConstructedMessage) :
                                nameof(MicrosoftNetFrameworkAnalyzersResources.XslCompiledTransformLoadInsecureInputMessage),
                                SecurityDiagnosticHelpers.GetNonEmptyParentName(node, model, context.CancellationToken)
                                );

                            context.ReportDiagnostic(
                                Diagnostic.Create(
                                    RuleDoNotUseInsecureXSLTScriptExecution,
                                    node.GetLocation(),
                                    message
                                    )
                                );
                        }
                    }
                }
            }
Exemple #50
0
 public static T ElementAt <T>(IEnumerable <T> sourceCollection, int index)
 {
     return(sourceCollection.ElementAt(index));
 }
Exemple #51
0
        private void btSaveData_Click(object sender, EventArgs e)
        {
            XElement xe = XElement.Load(@"D:\减速器设计系统\中间轴2计算参数.xml");

            IEnumerable <XElement> elements = from 水平面左侧 in xe.Elements("强度计算").Elements("D剖面弯矩")
                                              select 水平面左侧;

            elements.ElementAt(0).Element("水平面左侧").Value = txtMdzL.Text;
            elements.ElementAt(0).Element("水平面右侧").Value = txtMdzR.Text;
            elements.ElementAt(0).Element("垂直面").Value   = txtMdy.Text;
            elements.ElementAt(0).Element("左侧合成").Value  = txtMdL.Text;
            elements.ElementAt(0).Element("右侧合成").Value  = txtMdR.Text;
            elements = from 水平面左侧 in xe.Elements("强度计算").Elements("C剖面弯矩")
                       select 水平面左侧;

            elements.ElementAt(0).Element("水平面左侧").Value = txtMczL.Text;
            elements.ElementAt(0).Element("水平面右侧").Value = txtMczR.Text;
            elements.ElementAt(0).Element("垂直面").Value   = txtMcy.Text;
            elements.ElementAt(0).Element("左侧合成").Value  = txtMcL.Text;
            elements.ElementAt(0).Element("右侧合成").Value  = txtMcR.Text;

            elements = from CD处扭矩 in xe.Elements("强度计算")
                       select CD处扭矩;

            elements.ElementAt(0).Element("CD处扭矩").Value     = txtT.Text;
            elements.ElementAt(0).Element("折合系数").Value      = cmbBoxAlpha.Text;
            elements.ElementAt(0).Element("C剖面左侧弯曲应力").Value = txtBendScl.Text;
            elements.ElementAt(0).Element("C剖面右侧弯曲应力").Value = txtBendScr.Text;
            elements.ElementAt(0).Element("D剖面左侧弯曲应力").Value = txtBendSdl.Text;
            elements.ElementAt(0).Element("D剖面右侧弯曲应力").Value = txtBendSdr.Text;
            xe.Save(@"D:\减速器设计系统\中间轴2计算参数.xml");
        }
Exemple #52
0
        public static void Verify(this IEnumerable <Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
        {
            int expectedCount = expectedResults.Count();
            int actualCount   = actualResults.Count();

            if (expectedCount != actualCount)
            {
                string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults) : "    NONE.";

                Assert.True(false,
                            string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
            }

            for (int i = 0; i < expectedResults.Length; i++)
            {
                var actual   = actualResults.ElementAt(i);
                var expected = expectedResults[i];

                if (expected.Line == -1 && expected.Column == -1)
                {
                    if (actual.Location != Location.None)
                    {
                        Assert.True(false,
                                    string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
                                                  FormatDiagnostics(analyzer, actual)));
                    }
                }
                else
                {
                    VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First());
                    var additionalLocations = actual.AdditionalLocations.ToArray();

                    if (additionalLocations.Length != expected.Locations.Length - 1)
                    {
                        Assert.True(false,
                                    string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n    {2}\r\n",
                                                  expected.Locations.Length - 1, additionalLocations.Length,
                                                  FormatDiagnostics(analyzer, actual)));
                    }

                    for (int j = 0; j < additionalLocations.Length; ++j)
                    {
                        VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
                    }
                }

                if (actual.Id != expected.Id)
                {
                    Assert.True(false,
                                string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                              expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
                }

                if (actual.Severity != expected.Severity)
                {
                    Assert.True(false,
                                string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                              expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)));
                }

                if (actual.GetMessage() != expected.Message)
                {
                    Assert.True(false,
                                string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                              expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)));
                }
            }
        }
Exemple #53
0
        private static void AssertCombinedFailureMechanismSectionAssemblyResults(IEnumerable <CombinedFailureMechanismSectionAssemblyResult> assemblyResults,
                                                                                 IEnumerable <ExportableCombinedSectionAssembly> exportableCombinedSectionAssemblies,
                                                                                 ReferenceLine referenceLine, bool hasAssemblyGroupResults)
        {
            int expectedNrOfSections = assemblyResults.Count();

            Assert.AreEqual(expectedNrOfSections, exportableCombinedSectionAssemblies.Count());

            for (var i = 0; i < expectedNrOfSections; i++)
            {
                CombinedFailureMechanismSectionAssemblyResult combinedFailureMechanismSectionAssemblyResult = assemblyResults.ElementAt(i);
                ExportableCombinedSectionAssembly             exportableCombinedSectionAssembly             = exportableCombinedSectionAssemblies.ElementAt(i);

                AssertExportableCombinedFailureMechanismSection(combinedFailureMechanismSectionAssemblyResult, exportableCombinedSectionAssembly.Section, referenceLine);
                AssertExportableCombinedFailureMechanismSectionResult(
                    combinedFailureMechanismSectionAssemblyResult, exportableCombinedSectionAssembly.Section, exportableCombinedSectionAssembly,
                    hasAssemblyGroupResults);
            }
        }
        private void ProcessFrame()
        {
            while (_captureContinue)
            {
                while (_processQueueLength != 2)
                {
                    Thread.Sleep(SleepInterval);
                }

                if ((Helper2D.FilterInstances.Mode == Mode.Cpu && useGpuMenuItem.Checked) ||
                    (Helper2D.FilterInstances.Mode == Mode.Gpu && useGpuMenuItem.Checked == false))
                {
                    Helper2D.FilterInstances = new FilterInstances(useGpuMenuItem.Checked ? Mode.Gpu : Mode.Cpu);
                }

                double distance;

                if (_cameras[0].FaceRegions == null ||
                    _cameras[1].FaceRegions == null)
                {
                    _resetCorrelation = true;
                }

                if (_resetCorrelation == false)
                {
                    #region Find correlation with previous face regions

                    // iterate through all cameras and track faces
                    foreach (Camera camera in _cameras)
                    {
                        var newRawFaceRegions = new List <FaceRegion2D>();

                        // iterate through every face found previously, rotate image and find faces
                        foreach (FaceRegion2D faceRegion in camera.FaceRegions)
                        {
                            Image <Bgr, byte> image = camera.Image.Rotate(faceRegion.EyeAngle,
                                                                          new PointF(faceRegion.Face.Location.X + faceRegion.Face.Width / 2, faceRegion.Face.Location.Y + faceRegion.Face.Height / 2),
                                                                          INTER.CV_INTER_CUBIC, _rotateBackground, true);

                            if (_debugRotation)
                            {
                                camera.Image = image;
                            }

                            // find faces in rotated image
                            newRawFaceRegions.AddRange(Helper2D.GetFaceRegion2Ds(image, FaceWidth, FaceHeight, true, false));
                        }

                        // find best corespondence between old faces and new faces
                        IEnumerable <Tuple <int, int> > corespondences = Helper.FindCorespondence
                                                                             (camera.FaceRegions.Select(item => item.Face.Location).ToArray(),
                                                                             newRawFaceRegions.Select(item => item.Face.Location).ToArray(),
                                                                             out distance);

                        if (corespondences == null ||
                            corespondences.Any() == false)
                        {
                            // face regions lost .. RESET both cameras
                            _resetCorrelation = true;
                            break;
                        }

                        var newFaceRegions = new FaceRegion2D[corespondences.Count()];

                        for (int i = 0; i < corespondences.Count(); i++)
                        {
                            FaceRegion2D faceRegion = newRawFaceRegions.ElementAt(corespondences.ElementAt(i).Item2);

                            faceRegion.SetHistory(camera.FaceRegions.ElementAt(corespondences.ElementAt(i).Item1));

                            newFaceRegions[i] = faceRegion;
                        }

                        camera.FaceRegions = newFaceRegions;
                    }

                    #endregion
                }

                if (_resetCorrelation)
                {
                    #region Reset Found Faces

                    foreach (Camera camera in _cameras)
                    {
                        camera.FaceRegions = Helper2D.GetFaceRegion2Ds(camera.Image, FaceWidth, FaceHeight, true, false);
                    }

                    #endregion
                }

                if (_cameras[0].FaceRegions.Length > 0 &&
                    _cameras[1].FaceRegions.Length > 0)
                {
                    #region Find correlation in stereo images and add history

                    IEnumerable <Point>[] points = _cameras.Select(camera => camera.FaceRegions.
                                                                   Select(region => region.Face.Location)).ToArray();

                    List <Tuple <int, int> > correlations = Helper.FindCorespondence(points.ElementAt(0), points.ElementAt(1), out distance).ToList();


                    // images have incorect correlations and history
                    if (_resetCorrelation == false &&
                        correlations.Any(item => _cameras[0].FaceRegions.ElementAt(item.Item1).Id != _cameras[1].FaceRegions.ElementAt(item.Item2).Id))
                    {
                        _resetCorrelation = true;
                    }

                    if (_resetCorrelation)
                    {
                        // assign faces color and Id
                        foreach (var correlation in correlations)
                        {
                            var color = new Bgr(_random.NextDouble() * 255, _random.NextDouble() * 255, _random.NextDouble() * 255);

                            FaceRegion2D leftFaceRegion  = _cameras[0].FaceRegions.ElementAt(correlation.Item1);
                            FaceRegion2D rightFaceRegion = _cameras[1].FaceRegions.ElementAt(correlation.Item2);

                            rightFaceRegion.Id = leftFaceRegion.Id;

                            leftFaceRegion.BoundingBoxColor  = color;
                            rightFaceRegion.BoundingBoxColor = color;
                        }
                    }

                    #endregion

                    #region Recognize Faces

                    _cameras.ForEach(camera =>
                    {
                        if (camera.FaceRegions != null)
                        {
                            camera.FaceRegions.ToList().ForEach(faceRegion =>
                            {
                                Helper.DrawFaceRegionCircle(camera.Image, faceRegion, faceRegion.BoundingBoxColor);

                                string label = HelperFaces.Recognize(faceRegion.FaceImage);

                                camera.Image.Draw(string.Format("{0}", label),
                                                  ref _font, faceRegion.Face.Location, new Bgr(0, 0, 255));
                            });
                        }
                    });

                    #endregion

                    EventHandler <FaceRegionsEventArgs> facesAvailableHandler = FacesAvailable;
                    if (facesAvailableHandler != null)
                    {
                        facesAvailableHandler(this, new FaceRegionsEventArgs(_cameras[0].FaceRegions, _cameras[1].FaceRegions, null));
                    }

                    _faces = _cameras.SelectMany(camera => camera.FaceRegions).Select(item => item.FaceImage).ToArray();
                }

                _resetCorrelation = false;

                PostProcess();

                lock (this)
                {
                    _processQueueLength = 0;
                }
            }
        }
Exemple #55
0
        /// <summary>
        /// 执行事务操作,返回最后一个语句受影响的行数,每个语句之间没有互相使用的数据
        /// </summary>
        /// <param name="xNames"></param>
        /// <param name="paras"></param>
        /// <param name="replacements"></param>
        /// <returns></returns>
        public int ExecuteTransaction(IEnumerable <string> xNames, IEnumerable <object> paras, IEnumerable <object> replacements = null)
        {
            List <string>         sqls          = new List <string>();
            List <SqlParameter[]> sqlParameters = new List <SqlParameter[]>();

            for (var i = 0; i < xNames.Count(); i++)
            {
                XElement xElement = mappings[mappingName + "." + xNames.ElementAt(i)];
                string   sql      = xmlStatement.GetXElementSql(xElement, paras.ElementAt(i), replacements?.ElementAt(i));
                sqls.Add(sql);
                sqlParameters.Add(xmlStatement.GetSqlParameters(paras.ElementAt(i)));
            }
            return(base.ExecuteTransaction(sqls, sqlParameters));
        }
Exemple #56
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            //unwrap the values
            IEnumerable <double> nvals = ((Value.List)args[0]).Item.Select(q => (double)((Value.Number)q).Item);

            var curve = (Curve)((Value.Container)args[1]).Item;

            sfm = (SpatialFieldManager)((Value.Container)args[2]).Item;

            if (!sfm.IsResultSchemaNameUnique(DYNAMO_TEMP_CURVES_SCHEMA, -1))
            {
                IList <int> arses = sfm.GetRegisteredResults();
                foreach (int i in arses)
                {
                    AnalysisResultSchema arsTest = sfm.GetResultSchema(i);
                    if (arsTest.Name == DYNAMO_TEMP_CURVES_SCHEMA)
                    {
                        schemaId = i;
                        break;
                    }
                }
            }
            else
            {
                var ars = new AnalysisResultSchema(DYNAMO_TEMP_CURVES_SCHEMA, "Temporary curves from Dynamo.");
                schemaId = sfm.RegisterResult(ars);
            }

            Transform trf = Transform.Identity;

            //http://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html#3

            var create = dynRevitSettings.Doc.Application.Application.Create;

            Transform t = curve.ComputeDerivatives(0, true);

            XYZ x = t.BasisX.Normalize();
            XYZ y = t.BasisX.IsAlmostEqualTo(XYZ.BasisZ) ?
                    t.BasisX.CrossProduct(XYZ.BasisY).Normalize() :
                    t.BasisX.CrossProduct(XYZ.BasisZ).Normalize();
            XYZ z = x.CrossProduct(y);

            Ellipse arc1 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, -Math.PI, 0);
            Ellipse arc2 = dynRevitSettings.Revit.Application.Create.NewEllipse(t.Origin, .1, .1, y, z, 0, Math.PI);

            var pathLoop = new CurveLoop();

            pathLoop.Append(curve);
            var profileLoop = new CurveLoop();

            profileLoop.Append(arc1);
            profileLoop.Append(arc2);

            double curveDomain = curve.get_EndParameter(1) - curve.get_EndParameter(0);

            int idx = -1;
            var s   = GeometryCreationUtilities.CreateSweptGeometry(pathLoop, 0, 0, new List <CurveLoop> {
                profileLoop
            });

            foreach (Face face in s.Faces)
            {
                //divide the V domain by the number of incoming
                BoundingBoxUV domain = face.GetBoundingBox();
                double        vSpan  = domain.Max.V - domain.Min.V;

                //analysis values
                idx = sfm.AddSpatialFieldPrimitive(face, trf);

                //a list to hold the analysis points
                IList <UV> uvPts = new List <UV>();

                //a list to hold the analysis values
                IList <ValueAtPoint> valList = new List <ValueAtPoint>();

                //int count = nvals.Count();

                //this is creating a lot of sample points, but if we used less
                //sampling points, AVF would draw the two surfaces as if there was a hard
                //edge between them. this provides a better blend.
                int count = 10;
                for (int i = 0; i < count; i++)
                {
                    //get a UV point on the face
                    //find its XYZ location and project to
                    //the underlying curve. find the value which corresponds
                    //to the location on the curve
                    var uv  = new UV(domain.Min.U, domain.Min.V + vSpan / count * (double)i);
                    var uv1 = new UV(domain.Max.U, domain.Min.V + vSpan / count * (double)i);
                    uvPts.Add(uv);
                    uvPts.Add(uv1);

                    XYZ facePt                    = face.Evaluate(uv);
                    IntersectionResult ir         = curve.Project(facePt);
                    double             curveParam = curve.ComputeNormalizedParameter(ir.Parameter);

                    if (curveParam < 0)
                    {
                        curveParam = 0;
                    }

                    if (curveParam > 1)
                    {
                        curveParam = 1;
                    }

                    var valueIndex = (int)Math.Floor(curveParam * (double)nvals.Count());
                    if (valueIndex >= nvals.Count())
                    {
                        valueIndex = nvals.Count() - 1;
                    }

                    //create list of values at this point - currently supporting only one
                    //var doubleList = new List<double> { nvals.ElementAt(i) };
                    var doubleList = new List <double> {
                        nvals.ElementAt(valueIndex)
                    };

                    //add value at point object containing the value list
                    valList.Add(new ValueAtPoint(doubleList));
                    valList.Add(new ValueAtPoint(doubleList));
                }

                var pnts = new FieldDomainPointsByUV(uvPts);
                var vals = new FieldValues(valList);

                sfm.UpdateSpatialFieldPrimitive(
                    idx, pnts, vals, schemaId);

                idxs.Add(idx);
            }

            return(Value.NewNumber(idx));
        }
        private List <BaseEntity> ExtractEnumeration(XElement constantElement, String name, String summary, String declaration)
        {
            declaration = declaration.Trim(';');

            // Default values
            String type   = "NOTYPE";
            String values = String.Empty;

            // Match the enumeration definition
            bool result = this.SplitEnumeration(declaration, ref name, ref type, ref values);

            if (!result)
            {
                return(null);
            }

            if (type == "NOTYPE")
            {
                type = RefineEnumBaseType(values);
            }

            // Create the enumeration
            EnumerationEntity enumerationEntity = new EnumerationEntity();

            enumerationEntity.Name      = name;
            enumerationEntity.BaseType  = type;
            enumerationEntity.Namespace = "MISSING";
            enumerationEntity.Summary.Add(summary);

            // Parse the values
            var pairs = values.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string immutablePair in pairs)
            {
                String key;
                String value = String.Empty;
                String pair  = immutablePair.Replace(",", "");

                // Handle value assignment
                if (pair.IndexOf('=') != -1)
                {
                    string[] parts = pair.Split(new [] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    key   = parts [0].Trim();
                    value = parts [1].Trim();
                }
                else
                {
                    key = pair.Trim();
                }

                // Add a new value
                EnumerationValueEntity enumerationValueEntity = new EnumerationValueEntity();
                enumerationValueEntity.Name = key;

                if (value.Length == 6 && value.StartsWith("'") && value.EndsWith("'"))
                {
                    String v = value.Trim('\'');
                    enumerationValueEntity.Value = "0x" + FourCharToInt(v).ToString("X8");
                }
                else
                {
                    enumerationValueEntity.Value = value;
                }

                // Convert number qualifiers from native to managed
                enumerationValueEntity.Value = ConvertNumericQualifier(enumerationValueEntity.Value);

                enumerationEntity.Values.Add(enumerationValueEntity);
            }

            // Get the definitions
            XElement termList = (from el in constantElement.ElementsAfterSelf("dl")
                                 where (String)el.Attribute("class") == "termdef"
                                 select el).FirstOrDefault();

            if (termList != null)
            {
                IEnumerable <XElement> dtList = termList.Elements("dt");
                IEnumerable <XElement> ddList = termList.Elements("dd");

                if (dtList.Count() == ddList.Count())
                {
                    // Iterate over definitions
                    for (int i = 0; i < dtList.Count(); i++)
                    {
                        String term = dtList.ElementAt(i).Value.TrimAll();
                        IEnumerable <String> summaries = ddList.ElementAt(i).Elements("p").Select(p => p.Value.TrimAll());

                        // Find the enumeration value
                        EnumerationValueEntity enumerationValueEntity = enumerationEntity.Values.Find(v => v.Name == term);
                        if (enumerationValueEntity != null)
                        {
                            foreach (string sum in summaries)
                            {
                                if (CommentHelper.IsAvailability(sum))
                                {
                                    enumerationValueEntity.MinAvailability = CommentHelper.ExtractAvailability(sum);
                                    break;
                                }
                                enumerationValueEntity.Summary.Add(sum);
                            }
                        }
                        else
                        {
                            this.Logger.WriteLine("Term with no match '" + term + "'");
                        }
                    }
                }
                else
                {
                    this.Logger.WriteLine("MISMATCH in terms");
                }
            }

            // Make sure availability is ok
            enumerationEntity.AdjustAvailability();

            return(new List <BaseEntity> {
                enumerationEntity
            });
        }
Exemple #58
0
        public async Task search(Category category, [Remainder] string Query)
        {
            IEnumerable <JToken> results = null;

            switch (category)
            {
            case Category.Action:
                results = FileManager.Actions.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Feat:
                results = FileManager.Feats.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Item:
                results = FileManager.Items.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Spell:
                results = FileManager.Spells.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Trait:
                results = FileManager.Traits.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Background:
                results = FileManager.Backgrounds.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;

            case Category.Condition:
                results = FileManager.Conditions.Where(x => ((string)x["name"]).ToLower().StartsWith(Query.ToLower()));
                break;
            }
            if (results.Count() == 0)
            {
                await ReplyAsync("Sorry, could not find any " + category.ToString() + " named \"" + Query + "\"");

                return;
            }
            else if (results.Count() > 1)
            {
                results = results.Take(Math.Min(5, results.Count()));

                IEnumerable <string> names = results.Select(x => (string)x["name"]);

                var sb = new StringBuilder("Multiple results were found:\n");

                for (int i = 0; i < results.Count(); i++)
                {
                    sb.AppendLine("`[" + i + "]` " + names.ElementAt(i));
                }
                var msg = await ReplyAsync(sb.ToString());

                var reply = await NextMessageAsync(true, true, TimeSpan.FromSeconds(10));

                if (reply == null)
                {
                    await msg.ModifyAsync(x => x.Content = "Timed out on selection.");

                    return;
                }
                if (int.TryParse(reply.Content, out int index))
                {
                    if (index >= results.Count())
                    {
                        await msg.ModifyAsync(x => x.Content = "Invalid choice, operation cancelled.");

                        return;
                    }
                    else
                    {
                        try
                        {
                            await reply.DeleteAsync();
                        }
                        catch
                        {
                        }
                        Embed embed = null;
                        switch (category)
                        {
                        case Category.Action:
                            embed = FileManager.EmbedAction(results.ElementAt(index)).Build();
                            break;

                        case Category.Feat:
                            embed = FileManager.EmbedFeat(results.ElementAt(index)).Build();
                            break;

                        case Category.Item:
                            switch ((string)results.ElementAt(index)["type"])
                            {
                            case "item":
                                embed = FileManager.EmbedItemSRD(results.ElementAt(index)).Build();
                                break;

                            case "weapon":
                                embed = FileManager.EmbedWeapon(results.ElementAt(index)).Build();
                                break;

                            case "armor":
                                embed = FileManager.EmbedArmor(results.ElementAt(index)).Build();
                                break;

                            case "shield":
                                embed = FileManager.EmbedShield(results.ElementAt(index)).Build();
                                break;
                            }
                            break;

                        case Category.Spell:
                            embed = FileManager.EmbedSpell(results.ElementAt(index)).Build();
                            break;

                        case Category.Trait:
                            embed = FileManager.EmbedTrait(results.ElementAt(index)).Build();
                            break;

                        case Category.Background:
                            embed = FileManager.EmbedAction(results.ElementAt(index)).Build();
                            break;

                        case Category.Condition:
                            embed = FileManager.EmbedCondition(results.ElementAt(index)).Build();
                            break;
                        }

                        await ReplyAsync("", embed);

                        return;
                    }
                }
            }
            else
            {
                Embed embed = null;
                switch (category)
                {
                case Category.Action:
                    embed = FileManager.EmbedAction(results.FirstOrDefault()).Build();
                    break;

                case Category.Feat:
                    embed = FileManager.EmbedFeat(results.FirstOrDefault()).Build();
                    break;

                case Category.Item:
                    switch ((string)results.FirstOrDefault()["type"])
                    {
                    case "item":
                        embed = FileManager.EmbedItemSRD(results.FirstOrDefault()).Build();
                        break;

                    case "weapon":
                        embed = FileManager.EmbedWeapon(results.FirstOrDefault()).Build();
                        break;

                    case "armor":
                        embed = FileManager.EmbedArmor(results.FirstOrDefault()).Build();
                        break;

                    case "shield":
                        embed = FileManager.EmbedShield(results.FirstOrDefault()).Build();
                        break;
                    }
                    break;

                case Category.Spell:
                    embed = FileManager.EmbedSpell(results.FirstOrDefault()).Build();
                    break;

                case Category.Trait:
                    embed = FileManager.EmbedAction(results.FirstOrDefault()).Build();
                    break;

                case Category.Background:
                    embed = FileManager.EmbedAction(results.FirstOrDefault()).Build();
                    break;

                case Category.Condition:
                    embed = FileManager.EmbedCondition(results.FirstOrDefault()).Build();
                    break;
                }

                await ReplyAsync("", embed);

                return;
            }
        }
Exemple #59
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="arguments"></param>
 /// <param name="index"></param>
 /// <returns></returns>
 protected IRangeInfo ArgToRangeInfo(IEnumerable <FunctionArgument> arguments, int index)
 {
     return(arguments.ElementAt(index).Value as IRangeInfo);
 }
        private List <BaseEntity> ExtractConstants(XElement constantElement, String name, String summary, String declaration)
        {
            List <BaseEntity> constants = new List <BaseEntity> ();

            // Extract types and names
            string[] declarations = declaration.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string part in declarations)
            {
                //this.Logger.WriteLine("Parsing constant '{0}'...", part.Trim());

                String stripped = part.Trim();
                stripped = stripped.Replace("extern", String.Empty);
                stripped = stripped.Replace("const", String.Empty);
                stripped = stripped.TrimAll();

                Match r = CONSTANT_REGEX.Match(stripped);
                if (r.Success)
                {
                    String type = r.Groups [1].Value.Trim(' ', '*', ' ');

                    bool isOut;
                    bool isByRef;
                    bool isBlock;
                    type = this.TypeManager.ConvertType(type, out isOut, out isByRef, out isBlock, this.Logger);

                    ConstantEntity constantEntity = new ConstantEntity();
                    constantEntity.Type = type;
                    constantEntity.Name = r.Groups [2].Value.Trim();
                    constants.Add(constantEntity);

                    //this.Logger.WriteLine("Constant found '{0}' of type '{1}'", constantEntity.Name, constantEntity.Type);
                }
                else
                {
                    this.Logger.WriteLine("FAILED to parse constant '{0}'", stripped);
                    return(null);
                }
            }

            // Get the definitions
            XElement termDefinitions = (from el in constantElement.ElementsAfterSelf("dl")
                                        where (String)el.Attribute("class") == "termdef"
                                        select el).FirstOrDefault();

            if (termDefinitions == null)
            {
                this.Logger.WriteLine("MISSING terms");
                return(null);
            }

            IEnumerable <XElement> termName       = termDefinitions.Elements("dt");
            IEnumerable <XElement> termDefinition = termDefinitions.Elements("dd");

            if (termName.Count() == termDefinition.Count())
            {
                // Iterate over definitions
                for (int i = 0; i < termName.Count(); i++)
                {
                    String term = termName.ElementAt(i).Value.TrimAll();
                    IEnumerable <String> summaries = termDefinition.ElementAt(i).Elements("p").Select(p => p.Value.TrimAll());

                    // Find the enumeration value
                    BaseEntity baseEntity = constants.Find(c => c.Name == term);
                    if (baseEntity != null)
                    {
                        foreach (string sum in summaries)
                        {
                            if (CommentHelper.IsAvailability(sum))
                            {
                                baseEntity.MinAvailability = CommentHelper.ExtractAvailability(sum);
                                break;
                            }
                            baseEntity.Summary.Add(sum);
                        }
                    }
                    else
                    {
                        this.Logger.WriteLine("Term with no match '" + term + "'");
                    }
                }
            }
            else
            {
                this.Logger.WriteLine("MISMATCH in terms");
                return(null);
            }

            return(constants);
        }