public static CoreDataSet CalculateAverage(IList<CoreDataSet> validData)
 {
     var average = CoreDataSet.GetNullObject();
     average.Count = validData.Sum(x => x.Count.Value);
     average.Value = validData.Sum(x => x.Count).Value / validData.Count;
     return average;
 }
Пример #2
1
        private void loadReportBilancio(IList<ReportBilancioDTO> bilancioDataSource, CondominioDTO condominioDTO, EsercizioDTO esercizioDTO)
        {
            var importoTotale = 0m;

            reportViewer1.LocalReport.ReportEmbeddedResource = _reportParameters.TipoDettaglio == TipoDettaglioReportBilancio.Movimenti ? "Gipasoft.Stabili.UI.Bilanci.Reports.BilancioConsuntivo_Movimenti.rdlc" : "Gipasoft.Stabili.UI.Bilanci.Reports.BilancioConsuntivo_SottoConti.rdlc";
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ReportBilancioDTO", _bilancioService.CloneReportBilancioDataSource(bilancioDataSource)));

            if (_bilancioDataSource != null)
            {
                _reportParameters.TotaleVersamenti = _reportParameters.TotaleVersamenti*-1;
                importoTotale = bilancioDataSource.Sum(item => item.ImportoSottoConto) + bilancioDataSource.Sum(item => item.ImportoMovimento);
                if (Login.Instance.CurrentLogin().InversioneSaldiCondomini)
                {
                    importoTotale = importoTotale * -1;
                    _reportParameters.TotaleVersamenti = _reportParameters.TotaleVersamenti*-1;
                }
                
                importoTotale += _reportParameters.TotaleVersamenti;
                importoTotale += _reportParameters.SaldoPrecedente;
            }

            getReportParameters(importoTotale, condominioDTO, esercizioDTO);

            reportViewer1.LocalReport.SetParameters(getReportParameters(importoTotale, condominioDTO, esercizioDTO));
            reportViewer1.RefreshReport();
        }
Пример #3
1
        private void loadReportBilancio(IList<ReportBilancioDTO> bilancioDataSource)
        {
            var importoTotale = 0m;

            reportViewer1.LocalReport.ReportEmbeddedResource = "Gipasoft.Stabili.UI.Bilanci.Reports.BilancioConsuntivoDettaglio.rdlc";
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("ReportBilancioDTO", getBilancioService().CloneReportBilancioDataSource(bilancioDataSource)));

            if (_bilancioDataSource != null)
            {
                _reportParameters.TotaleVersamenti = _reportParameters.TotaleVersamenti*-1;
                importoTotale = bilancioDataSource.Sum(item => item.ImportoSottoConto) + bilancioDataSource.Sum(item => item.ImportoMovimento);
                if (Security.Login.Instance.CurrentLogin().InversioneSaldiCondomini)
                {
                    importoTotale = importoTotale * -1;
                    _reportParameters.TotaleVersamenti = _reportParameters.TotaleVersamenti*-1;
                }
                
                importoTotale += _reportParameters.TotaleVersamenti;
                importoTotale += _reportParameters.SaldoPrecedente;
            }

            getReportParameters(importoTotale);

            // Add a handler for SubreportProcessing
            reportViewer1.LocalReport.SubreportProcessing += localReportSubreportProcessing;

            reportViewer1.LocalReport.SetParameters(getReportParameters(importoTotale));
            reportViewer1.RefreshReport();
        }
        public void Update(ICacheService cacheService, Account selectedAccount, WorkPeriod currentWorkPeriod)
        {
            var accountType = cacheService.GetAccountTypeById(selectedAccount.AccountTypeId);
            var transactions = Dao.Query(GetCurrentRange(accountType.DefaultFilterType, x => x.AccountId == selectedAccount.Id, currentWorkPeriod)).OrderBy(x => x.Date);
            Transactions = transactions.Select(x => new AccountDetailData(x, selectedAccount)).ToList();
            if (accountType.DefaultFilterType > 0)
            {
                var pastDebit = Dao.Sum(x => x.Debit, GetPastRange(accountType.DefaultFilterType, x => x.AccountId == selectedAccount.Id, currentWorkPeriod));
                var pastCredit = Dao.Sum(x => x.Credit, GetPastRange(accountType.DefaultFilterType, x => x.AccountId == selectedAccount.Id, currentWorkPeriod));
                var pastExchange = Dao.Sum(x => x.Exchange, GetPastRange(accountType.DefaultFilterType, x => x.AccountId == selectedAccount.Id, currentWorkPeriod));
                if (pastCredit > 0 || pastDebit > 0)
                {
                    Summaries.Add(new AccountSummaryData(Resources.Total, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));
                    var detailValue =
                        new AccountDetailData(
                        new AccountTransactionValue
                        {
                            Name = Resources.PastTransactions,
                            Credit = pastCredit,
                            Debit = pastDebit,
                            Exchange = pastExchange
                        }, selectedAccount) { IsBold = true };
                    Transactions.Insert(0, detailValue);
                }
            }

            Summaries.Add(new AccountSummaryData(Resources.GrandTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));

            for (var i = 0; i < Transactions.Count; i++)
            {
                Transactions[i].Balance = (Transactions[i].Debit - Transactions[i].Credit);
                if (i > 0) (Transactions[i].Balance) += (Transactions[i - 1].Balance);
            }
        }
Пример #5
1
        public void Update(Account selectedAccount, DateTime? start, DateTime? end)
        {
            Start = start;
            End = end;
            var transactions = Dao.Query(GetCurrentRange(start, end, x => x.AccountId == selectedAccount.Id)).OrderBy(x => x.Date);
            Transactions = transactions.Select(x => new AccountDetailData(x, selectedAccount)).ToList();
            if (start.HasValue)
            {
                var pastDebit = Dao.Sum(x => x.Debit, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                var pastCredit = Dao.Sum(x => x.Credit, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                var pastExchange = Dao.Sum(x => x.Exchange, GetPastRange(start, x => x.AccountId == selectedAccount.Id));
                if (pastCredit > 0 || pastDebit > 0)
                {
                    Summaries.Add(new AccountSummaryData(Resources.TransactionTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));
                    var detailValue =
                        new AccountDetailData(
                        new AccountTransactionValue
                        {
                            Date = start.GetValueOrDefault(),
                            Name = Resources.BalanceBroughtForward,
                            Credit = pastCredit,
                            Debit = pastDebit,
                            Exchange = pastExchange
                        }, selectedAccount) { IsBold = true };
                    Transactions.Insert(0, detailValue);
                }
            }
            if (end.HasValue && end != start)
            {
                var futureDebit = Dao.Sum(x => x.Debit, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                var futureCredit = Dao.Sum(x => x.Credit, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                var futureExchange = Dao.Sum(x => x.Exchange, GetFutureRange(end, x => x.AccountId == selectedAccount.Id));
                if (futureCredit > 0 || futureDebit > 0)
                {
                    Summaries.Add(new AccountSummaryData(Resources.DateRangeTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));
                    var detailValue =
                        new AccountDetailData(
                        new AccountTransactionValue
                        {
                            Date = end.GetValueOrDefault(),
                            Name = Resources.BalanceAfterDate,
                            Credit = futureCredit,
                            Debit = futureDebit,
                            Exchange = futureExchange
                        }, selectedAccount) { IsBold = true };
                    Transactions.Add(detailValue);
                }
            }

            Summaries.Add(new AccountSummaryData(Resources.GrandTotal, Transactions.Sum(x => x.Debit), Transactions.Sum(x => x.Credit)));

            for (var i = 0; i < Transactions.Count; i++)
            {
                Transactions[i].Balance = (Transactions[i].Debit - Transactions[i].Credit);
                if (i > 0) (Transactions[i].Balance) += (Transactions[i - 1].Balance);
            }
        }
        public static CoreDataSet CalculateAverage(IList<CoreDataSet> validData, Unit unit)
        {
            var average = CoreDataSet.GetNullObject();
            average.Count = validData.Sum(x => x.Count.Value);
            average.Denominator = validData.Sum(x => x.Denominator);
            average.Value = (average.Count.Value / average.Denominator) * unit.Value;

            average.ValueNoteId = ValueNoteIds.ValueAggregatedFromAllKnownGeographyValues;
            return average;
        }
        public double Calculate(IList<Coder> participants)
        {
            var n = participants.Count;
            var ratAvg = participants.Average(x => x.R);

            var sqrRatStdev = participants.Sum(x => Math.Pow(x.R - ratAvg, 2)) / (n - 1);
            var sqrVolAvg = participants.Sum(x => x.V * x.V) / n;

            return Math.Sqrt(sqrVolAvg + sqrRatStdev);
        }
Пример #8
1
        public OrderLine(Product product, int quantity, IList<Outcome> outcomes):this()
        {
            Product = product;
            Quantity = quantity;
            Price = product.Price;
            ProductName = product.Name;

            Outcomes = outcomes;
            outcomes.ForEach(x => x.OrderLine = this);

            Profit = Outcomes.Sum(outcome => outcome.Profit);
            SummWithDiscount = Outcomes.Sum(outcome => outcome.SummWithDiscount);

        }
Пример #9
1
    private static StatisticsForPeriod ForPeriod(IList<FocusSession> sessions, string periodName)
    {
        var result = new StatisticsForPeriod
        {
            PeriodName = periodName,
            FocusMinutes = sessions.Sum(x => x.WasInterrupted ? - x.Minutes : x.Minutes),
            TotalMinutes = sessions.Sum(x => x.Minutes),
            InterruptionCount = sessions.Count(x => x.WasInterrupted),
            InterruptionMinutes = sessions.Where(x => x.WasInterrupted).Sum(x => x.Minutes),
            SessionCount = sessions.Count
        };

        return result;
    }
Пример #10
1
        public static LineEquation ApproximateLine(IList<double> values)
        {
            double sumX = 0;
            for (int i = 0; i < values.Count; ++i)
            {
                sumX += i;
            }

            int n = values.Count;
            double ssXX = 0;
            double ssYY = 0;
            double ssXY = 0;
            double meanX = sumX / n;
            double meanY = values.Sum() / n;
            for (int i = 0; i < values.Count; ++i)
            {
                ssXX += (double)Math.Pow(i - meanX, 2);
                ssYY += (double)Math.Pow(values[i] - meanY, 2);
                ssXY += (i - meanX)*(values[i] - meanY);
            }

            double b = ssXY / ssXX;
            double a = meanY - b * meanX;

            return new LineEquation(a, b);
        }
        public static int CalculateUpdatedTeamMoney(IList<Transfer> transfers, int currentMoney)
        {
            //process transfers as a whole
            int totalMoneySpent = transfers.Sum(t => t.PlayerIn.NowCost);

            int totalMoneyIn = 0;
            foreach (var transfer in transfers)
            {
                if (transfer.PlayerOut.NowCost <= transfer.PlayerOut.OriginalCost)
                {
                    totalMoneyIn += transfer.PlayerOut.NowCost;
                }
                else
                {
                    var difference = transfer.PlayerOut.NowCost - transfer.PlayerOut.OriginalCost;

                    //you get 50% of the difference, rounded down to nearest 0.1 mllion
                    totalMoneyIn += transfer.PlayerOut.OriginalCost + (difference / 2);
                }
            }

            var newMoneyValue = currentMoney - totalMoneySpent + totalMoneyIn;

            return newMoneyValue;
        }
Пример #12
1
 public Spectrum(double startRt, double endRt, IList<double> xValues, IList<double> yValues)
     : base(xValues, yValues)
 {
     StartRT = startRt;
     EndRT = endRt;
     totalIntensity = yValues.Sum();
 }
      public async Task<IssuesCollectionStatistics> Calculate(IList<JiraIssue> issues)
      {
         if(issues == null || issues.Any() == false)
            return null;

         return await Task.Factory.StartNew(() =>
         {
            return new IssuesCollectionStatistics
            {
               IssuesCount = issues.Count(),
               ResolvedIssuesCount = issues.Where(i => i.Resolved.HasValue).Count(),
               UnresolvedIssuesCount = issues.Where(i => i.Resolved.HasValue == false).Count(),

               AverageResolutionTimeHours = issues
                                               .Where(i => i.Resolved.HasValue)
                                               .Select(i => (i.Resolved.Value - i.Created).TotalHours).Average(),
               MaxResolutionTimeHours = issues
                                               .Where(i => i.Resolved.HasValue)
                                               .Select(i => (i.Resolved.Value - i.Created).TotalHours).Max(),

               TotalStorypoints = issues.Sum(i => i.StoryPoints),
               AverageStorypointsPerTask = issues.Average(i => i.StoryPoints),

               AverageSubtasksCount = issues.Average(i => i.Subtasks),

               EpicsInvolved = issues.Select(i => i.EpicLink).Distinct().Count(),

               DistinctReporters = issues.Select(i => i.Reporter).Distinct().Count()
            };
         });
      }
Пример #14
1
 public NumericRange(IList<double> values)
 {
     double num3;
     double num4;
     double current;
     Func<double, double> selector = null;
     double num = 0.0;
     double num2 = 0.0;
     goto Label_016A;
     Label_00F1:
     using (IEnumerator<double> enumerator = values.GetEnumerator())
     {
         goto Label_011B;
     Label_00FB:
         if ((((uint) current) - ((uint) num)) > uint.MaxValue)
         {
             goto Label_0142;
         }
         num4 += current * current;
     Label_011B:
         if (!enumerator.MoveNext())
         {
             goto Label_0157;
         }
         current = enumerator.Current;
         num = Math.Max(num, current);
         num2 = Math.Min(num2, current);
     Label_0142:
         num3 += current;
         goto Label_00FB;
     }
     Label_0157:
     this._xdc8f3f8857bee4c6 = values.Count;
     this._x628ea9b89457a2a9 = num;
     this._xd12d1dba8a023d95 = num2;
     this._x0eb49ee242305597 = num3 / ((double) this._xdc8f3f8857bee4c6);
     this._xcce91100698a4514 = Math.Sqrt(num4 / ((double) this._xdc8f3f8857bee4c6));
     if (((((uint) num2) & 0) != 0) || ((((uint) num2) + ((uint) current)) >= 0))
     {
         if (selector == null)
         {
             selector = new Func<double, double>(this, (IntPtr) this.xf29670e286f5562f);
         }
         double num6 = values.Sum<double>(selector);
         this._x8db8a12c7e795fea = Math.Sqrt(num6 / ((double) this._xdc8f3f8857bee4c6));
         if ((((uint) current) + ((uint) num4)) > uint.MaxValue)
         {
             goto Label_00F1;
         }
         if ((((uint) num6) - ((uint) current)) <= uint.MaxValue)
         {
             return;
         }
     }
     Label_016A:
     num3 = 0.0;
     num4 = 0.0;
     goto Label_00F1;
 }
        private static void FindSumAndAverage(IList<int> numbers)
        {
            long numbersSum = 0;
            double numbersAverage = 0;

            numbersSum = numbers.Sum();
            numbersAverage = numbers.Average();
            Console.WriteLine("The sum of your sequence is: {0} and the avgerage is: {1}.", numbersSum, numbersAverage);
        }
 public static DailyBuildSummary Create(DateTime date, IList<BuildDetails> dailyBuilds)
 {
     return new DailyBuildSummary()
     {
         Date = date,
         FailedBuilds = dailyBuilds.Count(b => b.Status == BuildState.Broken),
         TotalBuilds = dailyBuilds.Count(),
         NumberChangedFiles = dailyBuilds.Sum(b => b.NumberChangedFiles)
     };
 }
Пример #17
0
 public override void Update()
 {
     base.Update();
     var enemies = Scene.GetEntities<Monster>();
     if (enemies.IsEmpty())
         return;
     var targetsDistance = enemies.Select(x => new { Target = x, Distance = Vector2.Distance(new Vector2(x.X, x.Y), new Vector2(Entity.X, Entity.Y))}).ToList();
     Targets = targetsDistance.OrderBy(x => x.Distance).Select(x => x.Target).Take(Tower.MaxTargets).ToList();
     if (Targets.Any())
     {
         Tower.Direction.X = Targets.Sum(target => target.X) / Targets.Count;
         Tower.Direction.Y = Targets.Sum(target => target.Y) / Targets.Count;
     }
     if (AtMax)
         Shoot();
 }
Пример #18
0
 public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data)
 {
     var total = data.Sum(d => d.Count);
     var payloadLength = context.PayloadLength;
     var text = Encoding.UTF8.GetString(data, total - payloadLength, payloadLength);
     return new WebSocketPackageInfo(text, ServiceProvider.StringParser);
 }
Пример #19
0
        protected void WriteFramesToStream(IList<Frame> frames, Stream stream)
        {
            //TODO: Issue #11 -- Implement BufferPool (or consider WCF BufferManager?)
            //TODO: Issue #12 -- Consider custom implementation of FrameWriter for sockets.
            var rawMessage = new Byte[frames.Count * Frame.PreambleSize + frames.Sum(frame => frame.Body.Count)];
            var offset = 0;

            foreach (var frame in frames)
            {
                unsafe
                {
                    fixed (Byte* numRef = this.preamble)
                        *((Int32*)numRef) = sizeof(Byte) + frame.Body.Count;

                    this.preamble[Frame.PreambleFlagsOffset] = (Byte)frame.Flags;
                }

                Buffer.BlockCopy(this.preamble, 0, rawMessage, offset, Frame.PreambleSize);
                offset += Frame.PreambleSize;

                Buffer.BlockCopy(frame.Body.Array, frame.Body.Offset, rawMessage, offset, frame.Body.Count);
                offset += frame.Body.Count;
            }

            stream.Write(rawMessage, 0, rawMessage.Length);
        }
 public AggregationOperationResult Do(IList<double> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     if (!input.Any())
         throw new InvalidOperationException("No elements to aggregate");
     return new AggregationOperationResult(AggregationType.Sum, input.Sum());
 }
        public ProgramFitnessFunction(Puzzle puzzle, IList<int> funcSlotCount)
        {
            Debug.Assert(puzzle != null && funcSlotCount != null && funcSlotCount.Count > 0);

            this.puzzle = puzzle;
            this.funcSlotCount = funcSlotCount;
            this.totalSlots = funcSlotCount.Sum();
        }
 public AggregationOperationResult Do(IList<UniversalValue> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     AggregationOperationResult result = new AggregationOperationResult();
     result.Add("sum", input.Sum());
     return result;
 }
Пример #23
0
        private static void PrintResult(IList<Item> getResult)
        {
            Console.WriteLine(getResult.Sum(x => x.Price));

            foreach (var item in getResult)
            {
                Console.WriteLine(item);
            }
        }
Пример #24
0
 public QuotaWrapper(TenantQuota quota, IList<TenantQuotaRow> quotaRows)
 {
     StorageSize = (ulong) Math.Max(0, quota.MaxTotalSize);
     MaxFileSize = (ulong) Math.Max(0, quota.MaxFileSize);
     UsedSize = (ulong) Math.Max(0, quotaRows.Sum(r => r.Counter));
     StorageUsage =
         quotaRows.Select(x => new QuotaUsage() {Path = x.Path.TrimStart('/').TrimEnd('/'), Size = x.Counter,}).
             ToList();
 }
Пример #25
0
        private static void AssertSortedDescending(IEnumerable<int> input, IList<int> output)
        {
            Assert.Equal(input.Sum(), output.Sum());

            for (var i = 0; i < output.Count - 1; i++)
            {
                Assert.True(output[i] >= output[i + 1]);
            }
        }
Пример #26
0
 public static string PorcentagemEquivalente(IList<Estatistica> estatisticas)
 {
     string retorno = "";
     int total = estatisticas.Sum(estatistica => estatistica.Votos);
     foreach (Estatistica estatistica in estatisticas)
     {
         retorno += Environment.NewLine + String.Format("{0}: {1:0.00}%", estatistica.Nome, ((double)estatistica.Votos * 100 / (double)total));
     }
     return retorno + Environment.NewLine;
 }
Пример #27
0
        public CarCalculatorSummary(IList<FuelEntryModel> fuelEntries)
        {
            HasData = fuelEntries != null && fuelEntries.Any();
            if (!HasData) return;

            MinAmountOf100Km = fuelEntries.Min(i => i.AmountOfFuelPer100Km);
            MaxAmountOf100Km = fuelEntries.Max(i => i.AmountOfFuelPer100Km);

            MinCost1Km = fuelEntries.Min(i => i.CostOf1Km);
            MaxCost1Km = fuelEntries.Max(i => i.CostOf1Km);

            SumDistance = fuelEntries.Sum(i => i.CurrentDistance);
            SumAmountOfFuel = fuelEntries.Sum(i => i.AmountOfFuel);
            SumTotalCost = fuelEntries.Sum(i => i.GasPrice * i.AmountOfFuel);

            var minDate = fuelEntries.Min(i => i.Date);
            var maxDate = fuelEntries.Max(i => i.Date);
            AverageFuel = (decimal)((maxDate - minDate).TotalDays/fuelEntries.Count);
        }
Пример #28
0
 public void Print(IList<Transaction> transactions)
 {
     _Console.WriteLine(StatementHeader);
     var balance = new Money(transactions.Sum(a => a.Money.Amount));
     foreach (var transaction in transactions.OrderByDescending(a => a.Date))
     {
          _Console.WriteLine(GetFormattedLine(transaction, balance));
          balance.Amount -= transaction.Money.Amount;
     }
 }
Пример #29
0
 /// <summary>
 /// 全てのチャンネルを独立して計算し、
 /// 全て同じ比率でミックスします。
 /// <para>厳密にはこれはFM音源にはなりません。</para>
 /// </summary>
 /// <param name="op">オペレーターのリスト</param>
 /// <param name="tag">フィードバックの保持など自由に使えるタグオブジェクト</param>
 /// <param name="state">合成状態の情報</param>
 /// <returns>状態</returns>
 public static double ParallelMixAlgorithm(IList<FMOperator> op, ref object tag, FMSynthesisState state)
 {
     var mix = 0.0;
     var max = op.Sum(p => p.ModulationIndex);
     foreach (var i in op)
     {
         mix += i.GetState(state);
     }
     return mix / max;
 }
Пример #30
0
 /// <summary>
 /// Create a new BinaryTokenStreamReader to read from the specified input buffers.
 /// </summary>
 /// <param name="buffs">The list of ArraySegments to use for the data.</param>
 public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs)
 {
     buffers = buffs;
     totalProcessedBytes = 0;
     currentSegmentIndex = 0;
     InitializeCurrentSegment(0);
     totalLength = buffs.Sum(b => b.Count);
     buffersCount = buffs.Count;
     Trace("Starting new stream reader");
 }
Пример #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelScene"/> class.
        /// </summary>
        /// <param name="logicalIndex">The logical index of the scene within its parent model.</param>
        /// <param name="name">The scene's name.</param>
        /// <param name="nodes">The scene's list of nodes.</param>
        public ModelScene(Int32 logicalIndex, String name, IList <ModelNode> nodes = null)
        {
            this.LogicalIndex   = logicalIndex;
            this.Name           = name;
            this.Nodes          = new ModelNodeCollection(nodes);
            this.TotalNodeCount = this.Nodes.Count + nodes?.Sum(x => x.TotalNodeCount) ?? 0;

            foreach (var node in Nodes)
            {
                node.SetParentModelScene(this);
            }
        }
Пример #32
0
        private static void ExecuteStrategy(IList <DefinitionDto> definitions, IList <ResultDto> results, IStrategy strategy, int repetition, out double relativeErrorAvg, out double maxError)
        {
            IList <double> errors = null;

            for (int repetitionIndex = 0; repetitionIndex < repetition; repetitionIndex++)
            {
                errors = definitions.Zip(results, (definition, result) =>
                {
                    var computedResult = strategy.Compute(definition);

                    return((double)(result.Price - computedResult.Item1.Price) / result.Price);
                }).ToList();
            }
            relativeErrorAvg = (errors?.Sum() ?? 0) / definitions.Count;
            maxError         = errors?.Max() ?? 0;
        }
Пример #33
0
        private CustomerData CreateCustomerData(Customer customer, IEnumerable <Bet> bets)
        {
            IList <Bet> betsByCustomer = bets?.Where(b => b.Customer?.Id == customer.Id).ToList();

            CustomerData customerData = new CustomerData
            {
                Id                = customer.Id,
                NumberOfBets      = betsByCustomer?.Count ?? 0,
                TotalAmountOnBets = betsByCustomer?.Sum(b => b.Stake) ?? 0
            };

            customerData.IsAtRisk =
                customerData.TotalAmountOnBets > Constant.RiskBetThreshold;

            return(customerData);
        }
Пример #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelNode"/> class.
        /// </summary>
        /// <param name="logicalIndex">The logical index of the node within its parent model.</param>
        /// <param name="name">The node's name.</param>
        /// <param name="mesh">The node's associated mesh.</param>
        /// <param name="children">The node's list of child nodes.</param>
        /// <param name="transform">The node's transform matrix.</param>
        public ModelNode(Int32 logicalIndex, String name, ModelMesh mesh, IList <ModelNode> children, Matrix transform)
        {
            this.LogicalIndex = logicalIndex;
            this.Name         = name;
            this.Mesh         = mesh;
            this.Mesh?.SetParentModelNode(this);
            this.Children       = new ModelNodeCollection(children);
            this.TotalNodeCount = this.Children.Count + (children?.Sum(x => x.TotalNodeCount) ?? 0);
            this.Transform.UpdateFromMatrix(transform);

            foreach (var child in Children)
            {
                child.SetParentModelNode(this);
            }

            this.HasGeometry = (Mesh?.Geometries.Count > 0) || this.Children.Any(x => x.HasGeometry);
        }
Пример #35
0
 private double SumOfNTTAllSites(int month)
 {
     return(_artSites.Sum(site => site.GetNTTMonthValue(month)));
 }
Пример #36
0
 /** <inheritDoc /> */
 public int Reduce(IList <IComputeJobResult <int> > results)
 {
     return(results.Sum(res => res.Data));
 }
Пример #37
0
        private void btn_OK_Click(object sender, EventArgs e)
        {
            if (this.ncc_Employee.EditValue == null)
            {
                MessageBox.Show("請選擇業務員", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(this.comboBoxEditCurrency.Text))
            {
                MessageBox.Show("請選擇幣別", "提示", MessageBoxButtons.OK);
                return;
            }
            if (this.date_Start.EditValue == null || this.date_End.EditValue == null)
            {
                MessageBox.Show("請選擇日期區間", "提示", MessageBoxButtons.OK);
                return;
            }

            Model.Employee employee  = this.ncc_Employee.EditValue as Model.Employee;
            DateTime       startDate = this.date_Start.DateTime;
            DateTime       endDate   = this.date_End.DateTime;
            string         currency  = this.comboBoxEditCurrency.Text;

            IList <Model.InvoiceXO> list = invoiceXOManager.AmountStatistics(employee.EmployeeId, startDate, endDate, currency);

            if (list == null || list.Count == 0)
            {
                MessageBox.Show("無數據", "提示", MessageBoxButtons.OK);
                return;
            }

            var group = list.GroupBy(l => l.InvoiceDate.Value.Year);

            try
            {
                Type objClassType = null;
                objClassType = Type.GetTypeFromProgID("Excel.Application");
                if (objClassType == null)
                {
                    MessageBox.Show("本機沒有安裝Excel", "提示!", MessageBoxButtons.OK);
                    return;
                }

                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Application.Workbooks.Add(true);

                int col = 1 + group.Count();


                Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.Worksheets[1];
                Microsoft.Office.Interop.Excel.Range     r     = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, col]);
                r.MergeCells            = true;//合并单元格
                sheet.Cells.ColumnWidth = 12;

                sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, 1]).HorizontalAlignment = -4108;
                sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[18, col]).BorderAround(1, XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic, null);
                sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[18, col]).Borders.Value = 1;

                sheet.Cells[1, 1] = "客戶訂單-金額統計";
                sheet.Cells[2, 1] = string.Format("業務員編號:{0}", employee.IDNo);
                sheet.Cells[2, 3] = string.Format("業務員名稱:{0}", employee.EmployeeName);
                sheet.Cells[3, 1] = string.Format("日期區間:{0} ~ {1}", startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"));
                sheet.Cells[3, 4] = string.Format("幣別:{0}", Model.ExchangeRate.GetCurrencyENName(currency));

                //左邊第一列
                sheet.Cells[6, 1]  = "一月";
                sheet.Cells[7, 1]  = "二月";
                sheet.Cells[8, 1]  = "三月";
                sheet.Cells[9, 1]  = "四月";
                sheet.Cells[10, 1] = "五月";
                sheet.Cells[11, 1] = "六月";
                sheet.Cells[12, 1] = "七月";
                sheet.Cells[13, 1] = "八月";
                sheet.Cells[14, 1] = "九月";
                sheet.Cells[15, 1] = "十月";
                sheet.Cells[16, 1] = "十一月";
                sheet.Cells[17, 1] = "十二月";
                sheet.Cells[18, 1] = "合計";

                for (int i = 0; i < group.Count(); i++)   //列
                {
                    //int year = i + startDate.Year;         //可能查詢年並沒有數據,從有數據最小年開始
                    int year = i + group.Min(g => g.Key);

                    sheet.Cells[5, 2 + i] = year;
                    var yearList = group.First(g => g.Key == year).ToList();

                    for (int j = 1; j <= 12; j++)       //行
                    {
                        var monthMoney = yearList.Where(l => l.InvoiceDate.Value.Month == j).Sum(d => d.InvoiceTotal);

                        sheet.Cells[5 + j, 2 + i] = monthMoney;
                    }

                    sheet.Cells[18, 2 + i] = yearList.Sum(l => l.InvoiceTotal);
                }

                sheet.Cells[18, 2 + group.Count()] = list.Sum(l => l.InvoiceTotal);


                excel.Visible     = true;//是否打开该Excel文件
                excel.WindowState = XlWindowState.xlMaximized;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Excel未生成完畢,請勿操作,并重新點擊按鈕生成數據!", "提示!", MessageBoxButtons.OK);
                return;
            }
        }
 public static float Average(this IList <float> col)
 => col.Sum() / col.Count;
 public static long Average(this IList <long> col)
 => col.Sum() / col.Count;
Пример #40
0
 public int Size()
 {
     return(_components.Sum(component => component.Size()));
 }
Пример #41
0
        internal static IEnumerable <TResult> WeightedFilter <T, TResult>(this IList <T> source, double start, double end, Func <T, long> weightSelector, Func <T, long, TResult> resultSelector)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (start < 0 || start > 1)
            {
                throw new ArgumentOutOfRangeException(nameof(start));
            }
            if (end < start || start + end > 1)
            {
                throw new ArgumentOutOfRangeException(nameof(end));
            }
            if (weightSelector == null)
            {
                throw new ArgumentNullException(nameof(weightSelector));
            }
            if (resultSelector == null)
            {
                throw new ArgumentNullException(nameof(resultSelector));
            }
            if (source.Count == 0 || start == end)
            {
                yield break;
            }
            double amount  = source.Sum(weightSelector);
            long   sum     = 0;
            double current = 0;

            foreach (T item in source)
            {
                if (current >= end)
                {
                    break;
                }
                long weight = weightSelector(item);
                sum += weight;
                double old = current;
                current = sum / amount;
                if (current <= start)
                {
                    continue;
                }
                if (old < start)
                {
                    if (current > end)
                    {
                        weight = (long)((end - start) * amount);
                    }
                    else
                    {
                        weight = (long)((current - start) * amount);
                    }
                }
                else if (current > end)
                {
                    weight = (long)((end - old) * amount);
                }
                yield return(resultSelector(item, weight));
            }
        }
Пример #42
0
 public int NumberOfItemsInSubscription()
 {
     return(_items.Sum(i => i.Qty));
 }
Пример #43
0
 /// <summary>
 /// Returns whether the specified sequences tends towards infinity.
 /// </summary>
 /// <param name="sequence">The sequence of integers.</param>
 /// <returns>
 /// <see langword="true"/> if the sequence tends towards positive or negative infinity.
 /// </returns>
 private static bool TendsToInfinity(IList <int> sequence)
 => Math.Abs(sequence.Sum(Math.Sign)) == sequence.Count((p) => p is not 0);
Пример #44
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            BLL.wx_shop_cart            cartBll  = new BLL.wx_shop_cart();
            string                      _action  = MyCommFun.QueryString("myact");
            string                      openid   = MyCommFun.RequestOpenid(); //得到微信用户的openid
            Dictionary <string, string> jsonDict = new Dictionary <string, string>();

            if (_action == "addCart")
            {
                #region 添加购物车
                try
                {
                    int     wid        = MyCommFun.RequestInt("wid");
                    int     productId  = MyCommFun.RequestInt("productid");
                    string  skuId      = MyCommFun.QueryString("mid");
                    string  skuInfo    = MyCommFun.QueryString("attr");
                    int     productNum = MyCommFun.RequestInt("bc");
                    decimal totalPrice = (decimal)MyCommFun.RequestFloat("totprice", 0);

                    Model.wx_shop_cart cart = new Model.wx_shop_cart();

                    IList <Model.wx_shop_cart> cartList = cartBll.GetModelList("productId=" + productId + " and openid='" + openid + "' and skuId='" + skuId + "'");
                    int  getCartCount = cartBll.GetRecordCount("wid=" + wid + " and openid='" + openid + "'");
                    bool isAdd        = true;
                    if (cartList != null && cartList.Count > 0)
                    {
                        isAdd = false;
                        cart  = cartList[0];
                    }
                    if (isAdd)
                    {
                        cart.createDate = DateTime.Now;
                        cart.openid     = openid;
                        cart.productId  = productId;
                        cart.productNum = productNum;
                        cart.skuId      = skuId;
                        cart.skuInfo    = skuInfo;
                        cart.totPrice   = totalPrice * productNum;
                        cart.wid        = wid;
                        int ret = cartBll.Add(cart);
                        if (ret > 0)
                        {
                            jsonDict.Add("errCode", "false");
                            jsonDict.Add("recontent", "添加购物车成功!");
                            jsonDict.Add("cartcount", (getCartCount + 1).ToString());
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                            jsonDict.Add("recontent", "添加购物车失败!");
                            jsonDict.Add("cartcount", getCartCount.ToString());
                        }
                    }
                    else
                    {
                        cart.openid = openid;

                        cart.productNum += productNum;
                        cart.skuId       = skuId;
                        cart.skuInfo     = skuInfo;
                        cart.totPrice   += totalPrice * productNum;
                        cart.wid         = wid;
                        bool ret = cartBll.Update(cart);
                        if (ret)
                        {
                            jsonDict.Add("errCode", "false");
                            jsonDict.Add("recontent", "更新购物车成功!");
                            jsonDict.Add("cartcount", getCartCount.ToString());
                        }
                        else
                        {
                            jsonDict.Add("errCode", "true");
                            jsonDict.Add("recontent", "更新购物车失败!");
                            jsonDict.Add("cartcount", getCartCount.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    jsonDict.Add("errCode", "true");
                    jsonDict.Add("recontent", "添加购物车失败!");
                }
                finally
                {
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }
                #endregion
            }
            else if (_action == "pcount")
            {
                #region 购物车商品数量
                jsonDict = new Dictionary <string, string>();
                int wid   = MyCommFun.RequestInt("wid");
                int count = cartBll.GetRecordCount("wid=" + wid + " and openid='" + openid + "'");
                jsonDict.Add("data", count.ToString());
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "remove")
            {
                #region 移除购物车商品
                jsonDict = new Dictionary <string, string>();
                int cartId = MyCommFun.RequestInt("id");
                cartBll.Delete(cartId);
                jsonDict.Add("errCode", "false");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "modifyNum")
            {
                #region 修改购物车商品数量
                jsonDict = new Dictionary <string, string>();
                int cartId = MyCommFun.RequestInt("ic");
                int newNum = MyCommFun.RequestInt("bc");
                cartBll.UpdateNum(cartId, newNum);
                jsonDict.Add("errCode", "false");
                jsonDict.Add("recontent", "更新成功!");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                #endregion
            }
            else if (_action == "getCity")
            {
                #region  择省份,改变城市列表
                int privice = MyCommFun.RequestInt("pvid");
                BLL.pre_common_district           areaBll = new BLL.pre_common_district();
                IList <Model.pre_common_district> disList = areaBll.GetModelList("upid=" + privice + " and level=2");
                Model.pre_common_district         dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion
            }
            else if (_action == "getArea")
            {
                #region  择城市,改变区域列表
                int ctid = MyCommFun.RequestInt("ctid");
                BLL.pre_common_district           areaBll = new BLL.pre_common_district();
                IList <Model.pre_common_district> disList = areaBll.GetModelList("upid=" + ctid + " and level=3");
                Model.pre_common_district         dis;
                StringBuilder jsonStr = new StringBuilder("{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                for (int i = 0; i < disList.Count; i++)
                {
                    dis = new Model.pre_common_district();
                    if (i != disList.Count - 1)
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                    }
                    else
                    {
                        jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                    }
                }
                jsonStr.Append("]}");
                context.Response.Write(jsonStr);
                #endregion
            }
            else if (_action == "order_save")
            {
                #region 保存订单信息
                //获得传参信息
                int wid = MyCommFun.RequestInt("wid");

                int payment_id = MyCommFun.RequestInt("pc");    //支付方式:1货到付款;3微支付
                int express_id = MyCommFun.RequestInt("mtype"); //物流方式
                // string orderStrList = MyCommFun.QueryString("orderStrList");

                //检查物流方式
                if (express_id == 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,请选择配送方式!\"}");
                    return;
                }

                BLL.wx_shop_user_addr           uAddrBll  = new BLL.wx_shop_user_addr();
                IList <Model.wx_shop_user_addr> uaddrList = uAddrBll.GetOpenidAddrName(openid, wid);
                if (uaddrList == null || uaddrList.Count <= 0 || uaddrList[0].id <= 0)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"收货地址不存在,无法结算!\"}");
                    return;
                }


                //检查购物车商品
                IList <Model.cartProduct> cartList = cartBll.GetCartList(openid, wid);
                if (cartList == null)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"对不起,购物车为空,无法结算!\"}");
                    return;
                }
                //统计购物车
                decimal payable_amount = cartList.Sum(c => c.totPrice);
                //物流费用
                BLL.express   expressBll = new BLL.express();
                Model.express expModel   = expressBll.GetModel(express_id);
                //支付方式
                BLL.payment   pbll     = new BLL.payment();
                Model.payment payModel = pbll.GetModelBypTypeId(payment_id);
                //保存订单=======================================================================
                Model.orders model = new Model.orders();
                model.order_no = "b" + Utils.GetOrderNumber(); //订单号B开头为商品订单

                model.wid             = wid;
                model.openid          = openid;
                model.modelName       = "微商城";
                model.modelCode       = "shop";
                model.modelActionName = "";
                model.modelActionId   = 0;
                model.user_id         = 0;
                model.user_name       = "";
                model.payment_id      = payment_id;
                model.express_id      = express_id;
                model.accept_name     = uaddrList[0].contractPerson;
                model.post_code       = "";
                model.telphone        = uaddrList[0].tel;
                model.mobile          = uaddrList[0].tel;
                model.area            = uaddrList[0].province;
                model.city            = uaddrList[0].city;
                model.district        = uaddrList[0].area;
                model.address         = uaddrList[0].province + " " + uaddrList[0].city + " " + uaddrList[0].area + " " + uaddrList[0].addrDetail;
                model.message         = "";
                model.payable_amount  = payable_amount; //应付商品总金额
                model.real_amount     = payable_amount; //实际商品总金额,
                model.status          = 1;
                model.express_status  = 1;
                model.express_fee     = expModel.express_fee; //物流费用

                if (payment_id == 1)
                {                             //货到付款,需要确认订单
                    model.payment_status = 0; //标记未付款
                }
                else
                {                             //先款后货
                    model.payment_status = 1; //标记未付款
                }
                bool quicklyFH = false;
                //如果是先款后货的话
                if (payment_id == 3)
                {
                    if (payModel.poundage_type == 1) //百分比
                    {
                        model.payment_fee = model.real_amount * payModel.poundage_amount / 100;
                    }
                    else //固定金额
                    {
                        model.payment_fee = payModel.poundage_amount;
                    }
                    BLL.wx_payment_wxpay   wxBll = new BLL.wx_payment_wxpay();
                    Model.wx_payment_wxpay wxpay = wxBll.GetModelByWid(wid);
                    quicklyFH = wxpay.quicklyFH;
                }
                if (quicklyFH)
                {
                    model.express_status = 0;
                }
                //订单总金额=实付商品金额+运费+支付手续费
                model.order_amount = model.real_amount + model.express_fee + model.payment_fee;
                //购物积分,可为负数
                model.point    = 0;
                model.add_time = DateTime.Now;
                //商品详细列表
                List <Model.order_goods> gls = new List <Model.order_goods>();
                foreach (Model.cartProduct item in cartList)
                {
                    gls.Add(new Model.order_goods {
                        goods_id = item.productId, goods_title = item.productName, goods_price = item.totPrice, real_price = item.totPrice, quantity = item.productNum, point = 0
                    });
                }
                model.order_goods = gls;
                int result = new BLL.orders().Add(model);
                if (result < 1)
                {
                    context.Response.Write("{\"errCode\":3, \"msg\":\"订单保存过程中发生错误,请重新提交!\"}");
                    return;
                }

                //清空购物车
                cartBll.RemoveCartInfo(wid, openid);
                //提交成功,返回URL  order_no
                context.Response.Write("{\"errCode\":true, \"payType\":\"" + payment_id + "\", \"order_no\":\"" + model.order_no + "\",\"orderid\":\"" + result + "\",\"wid\":\"" + wid + "\",\"openid\":\"" + openid + "\",\"payable_amount\":\"" + payable_amount + "\", \"msg\":\"恭喜您,订单已成功提交!\"}");
                return;

                #endregion
            }
            else if (_action == "order_canel")
            {
                #region  //取消订单
                int        orderid = MyCommFun.RequestInt("order_id");
                BLL.orders oBll    = new BLL.orders();
                oBll.UpdateField(orderid, "status=4");
                context.Response.Write("{\"errCode\":true, \"msg\":\"订单已取消!\"}");
                #endregion
            }
            else if (_action == "fukuan")
            {
                #region  //在线支付
                int          orderid = MyCommFun.RequestInt("order_id");
                BLL.orders   oBll    = new BLL.orders();
                Model.orders order   = oBll.GetModel(orderid);
                oBll.UpdateField(orderid, "express_status=1,payment_status=2 , status=2");
                context.Response.Write("{\"errCode\":true, \"msg\":\"付款成功!\"}");
                #endregion
            }
            else if (_action == "shouhuo")
            {
                #region  //确认收货
                int          orderid = MyCommFun.RequestInt("order_id");
                BLL.orders   oBll    = new BLL.orders();
                Model.orders order   = oBll.GetModel(orderid);

                //if (order.payment_id == 1)
                //{
                //货到付款
                //    oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                // }
                // else
                //{
                //在线支付
                oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=6");
                // }

                context.Response.Write("{\"errCode\":true, \"msg\":\"交易完成!\"}");
                #endregion
            }
            else if (_action == "so")
            {
                #region  //产品搜索,主要字段名称,分类,简介

                int    wid         = MyCommFun.RequestInt("wid");
                string pagesizeStr = MyCommFun.RequestParam("pagesize");
                string orderby     = " id desc";
                int    currPage    = MyCommFun.RequestInt("currPage");; //当前页面
                int    recordCount = 0;                                 //总记录数
                int    totPage     = 1;                                 //总页数
                int    pageSize    = MyCommFun.Str2Int(pagesizeStr);    //每页的记录数
                if (pageSize <= 0)
                {
                    pageSize = 10;
                }
                if (MyCommFun.RequestInt("page") > 0)
                {
                    currPage = 1;
                }

                string key = MyCommFun.RequestParam("key");

                DataSet productlist = new DataSet();


                DAL.wx_shop_product artDal = new DAL.wx_shop_product();
                productlist = artDal.SoGetList(wid, key, pageSize, currPage, "upselling=1", orderby, out recordCount);
                if (productlist != null && productlist.Tables.Count > 0 && productlist.Tables[0].Rows.Count > 0)
                {
                    DataRow dr;
                    for (int i = 0; i < productlist.Tables[0].Rows.Count; i++)
                    {
                        dr            = productlist.Tables[0].Rows[i];
                        dr["p_count"] = recordCount;
                        if (dr["link_url"] != null && dr["link_url"].ToString().Trim().Length > 0)
                        {
                            dr["link_url"] = MyCommFun.urlAddOpenid(dr["link_url"].ToString().Trim(), openid);
                        }
                        else
                        {
                            dr["link_url"] = MyCommFun.urlAddOpenid("detail.aspx?wid=" + wid + "&pid=" + dr["id"].ToString(), openid);
                        }
                        productlist.AcceptChanges();
                    }

                    context.Response.Write(MyCommFun.GetJsonByDataset(productlist));
                }



                #endregion
            }
        }
Пример #45
0
 public decimal GetTotal()
 {
     return(_orderLineItems.Sum(oli => oli.GetTotal()));
 }
 public static int Average(this IList <int> col)
 => col.Sum() / col.Count;
 public static uint Average(this IList <uint> col)
 => col.Sum() / (uint)col.Count;
Пример #48
0
        private decimal CountSiteQuantity(string productId, DateTime dateEnd)
        {
            //  2018年7月3日22:17:36 改:只查询2018.1.1 之后的订单
            DateTime startDate = new DateTime(2018, 1, 1);
            IList <Model.PronoteHeader> phList = pronoteHeaderManager.SelectByProductId(startDate, dateEnd.AddSeconds(-1), productId);
            //if (phList == null || phList.Count == 0)
            //    return 0;
            string pronoteHeaderIds = "";
            string invoiceXOIds     = "";
            string allInvoiceXOIds  = "";

            #region 验片:合计前单位转入 - 合计生产数量(包含合计合格数量,合计不良品)
            double yanpianTransferIn = 0;
            double yanpianProcedures = 0;
            double yanpianBuliang    = 0;
            double yanpianXianchang  = 0;

            if (phList != null && phList.Count > 0)
            {
                foreach (var ph in phList)
                {
                    pronoteHeaderIds += "'" + ph.PronoteHeaderID + "',";
                    invoiceXOIds     += "'" + ph.InvoiceXOId + "',";
                }
                pronoteHeaderIds = pronoteHeaderIds.TrimEnd(',');
                allInvoiceXOIds  = invoiceXOIds = invoiceXOIds.TrimEnd(',');

                //计算所有转入 验片 部门的数量
                Model.ProduceInDepotDetail pidYanpianIn = produceInDepotDetailManager.SelectByNextWorkhouse(productId, dateEnd.AddSeconds(-1), workHouseYanpian, pronoteHeaderIds);
                yanpianTransferIn = Convert.ToDouble(pidYanpianIn.ProduceTransferQuantity);

                //计算 验片 部门的生产数量
                Model.ProduceInDepotDetail pidYanpianOut = produceInDepotDetailManager.SelectByThisWorkhouse(productId, dateEnd.AddSeconds(-1), workHouseYanpian, pronoteHeaderIds);
                yanpianProcedures = Convert.ToDouble(pidYanpianOut.ProceduresSum);
                yanpianBuliang    = Convert.ToDouble(pidYanpianOut.ProceduresSum - pidYanpianOut.CheckOutSum);

                yanpianXianchang = yanpianTransferIn - yanpianProcedures;
                yanpianXianchang = yanpianXianchang < 0 ? 0 : yanpianXianchang;
            }
            #endregion

            #region 组装现场:合计前单位转入+ 合计领料单领出 - 合计出库数量(合计转生产到其他部门,成品入库数量换算后扣减数量)- 生产退料(从组装现场退的)

            double zuzhuangTransferIn  = 0;
            double zuzhuangTransferOut = 0;
            double exitQty             = 0;
            double deductionQty        = 0;
            //领到 组装现场 部门的数量
            double materialQty = 0;

            //materialQty = produceMaterialdetailsManager.SelectMaterialQty(productId, startDate, dateEnd.AddSeconds(-1), workHouseZuzhuang);
            //2018年7月9日23:07:51 领料单所包含的未结案订单号码拉出来,用于查询母件入库扣减
            System.Data.DataTable dt = produceMaterialdetailsManager.SelectMaterialQty(productId, startDate, dateEnd.AddSeconds(-1), workHouseZuzhuang, invoiceXOIds);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    materialQty += Convert.ToDouble(dr["Materialprocessum"].ToString());

                    if (!invoiceXOIds.Contains(dr["InvoiceId"].ToString()))
                    {
                        allInvoiceXOIds = "'" + dr["InvoiceId"].ToString() + "'," + allInvoiceXOIds;
                    }
                }
                allInvoiceXOIds = allInvoiceXOIds.TrimEnd(',');
            }


            #region 查询商品对应的所有母件 入库 扣减
            //if (!string.IsNullOrEmpty(xoIDs))
            //if (!string.IsNullOrEmpty(invoiceXOIds))
            if (!string.IsNullOrEmpty(allInvoiceXOIds))
            {
                Dictionary <string, double> parentProductDic = new Dictionary <string, double>();

                GetParentProductInfo("'" + productId + "'", parentProductDic);

                string proIds = "";
                foreach (var str in parentProductDic.Keys)
                {
                    proIds += "'" + str + "',";
                }
                proIds = proIds.TrimEnd(',');

                if (!string.IsNullOrEmpty(proIds))
                {
                    //IList<Model.ProduceInDepotDetail> pids = produceInDepotDetailManager.SelectIndepotQty(proIds, dateEnd.AddSeconds(-1), workHouseChengpinZuzhuang, xoIDs); //对应转到组装现场的生产入库单的客户订单,如果订单不在范围内,母件入库不扣减
                    //IList<Model.ProduceInDepotDetail> pids = produceInDepotDetailManager.SelectIndepotQty(proIds, dateEnd.AddSeconds(-1), workHouseChengpinZuzhuang, invoiceXOIds);

                    //2018年7月9日23:21:00  加上领料单对应的订单
                    IList <Model.ProduceInDepotDetail> pids = produceInDepotDetailManager.SelectIndepotQty(proIds, dateEnd.AddSeconds(-1), workHouseChengpinZuzhuang, allInvoiceXOIds);

                    foreach (var pid in pids)
                    {
                        deductionQty += Convert.ToDouble(pid.ProduceQuantity) * parentProductDic[pid.ProductId];
                    }


                    //2018年8月1日22:51:32  对应的母件领到组装现场的数量
                    List <Model.ProduceMaterialdetails> pmds = produceMaterialdetailsManager.SelectMaterialsByProductIds(proIds, startDate, dateEnd.AddSeconds(-1), workHouseZuzhuang, allInvoiceXOIds).ToList();
                    foreach (var pmd in pmds)
                    {
                        //如果母件有领料,对应抵消入库扣减
                        if (pids.Any(P => P.ProductId == pmd.ProductId))
                        {
                            deductionQty -= pmd.Materialprocessum.HasValue ? pmd.Materialprocessum.Value * parentProductDic[pmd.ProductId] : 0;
                        }
                        else
                        {
                            Dictionary <string, double> fatherDic = new Dictionary <string, double>();
                            GetParentProductInfo("'" + pmd.ProductId + "'", fatherDic);
                            if (pids.Any(P => fatherDic.Keys.Contains(P.ProductId)))
                            {
                                deductionQty -= pmd.Materialprocessum.HasValue ? pmd.Materialprocessum.Value * parentProductDic[pmd.ProductId] * fatherDic[pids.First(P => fatherDic.Keys.Contains(P.ProductId)).ProductId] : 0;
                            }
                        }
                    }

                    deductionQty = deductionQty < 0 ? 0 : deductionQty;

                    //2018年8月16日11:26:19  对应的母件退料,组装现场数量扣减
                    List <Model.ProduceMaterialExitDetail> pmeds = produceMaterialExitDetailManager.SelectSumQtyFromZuzhuangByPros(proIds, startDate, dateEnd.AddSeconds(-1), workHouseZuzhuang, allInvoiceXOIds).ToList();
                    foreach (var pmed in pmeds)
                    {
                        exitQty += pmed.ProduceQuantity.Value * parentProductDic[pmed.ProductId];
                    }
                }
            }

            #endregion


            //计算 从组装现场退回的 生产退料
            exitQty += produceMaterialExitDetailManager.SelectSumQtyFromZuzhuang(productId, startDate, dateEnd.AddSeconds(-1), workHouseZuzhuang, allInvoiceXOIds);


            #region 计算所有转入 组装现场 部门的数量
            if (phList != null && phList.Count > 0)
            {
                IList <Model.ProduceInDepotDetail> pidZuzhuangIn = produceInDepotDetailManager.SelectTransZuZhuangXianChang(productId, dateEnd.AddSeconds(-1), workHouseZuzhuang, pronoteHeaderIds);
                zuzhuangTransferIn = pidZuzhuangIn.Sum(P => P.ProduceTransferQuantity).Value;

                //计算 组装现场 部门转入其他部门的数量
                Model.ProduceInDepotDetail pidZuzhuangOut = produceInDepotDetailManager.SelectByThisWorkhouse(productId, dateEnd.AddSeconds(-1), workHouseZuzhuang, pronoteHeaderIds);
                zuzhuangTransferOut = Convert.ToDouble(pidZuzhuangOut.ProduceTransferQuantity);
            }
            #endregion

            //double zuzhuangXianchang = zuzhuangTransferIn + materialQty - zuzhuangTransferOut - deductionQty;
            double zuzhuangXianchang = zuzhuangTransferIn + materialQty - zuzhuangTransferOut - deductionQty - exitQty;
            zuzhuangXianchang = zuzhuangXianchang < 0 ? 0 : zuzhuangXianchang;

            #endregion

            return((decimal)zuzhuangXianchang + (decimal)yanpianXianchang);
        }
 public static ulong Average(this IList <ulong> col)
 => col.Sum() / (ulong)col.Count;
Пример #50
0
        private void WriteProjectAnalysisResults(IList <ProjectAnalysisResult> results)
        {
            if (Options.LogAnalyzerExecutionTime)
            {
                WriteExecutionTime();
            }

            int totalCount = results.Sum(f => f.Diagnostics.Length + f.CompilerDiagnostics.Length);

            if (totalCount > 0)
            {
                WriteLine(Verbosity.Normal);

                Dictionary <DiagnosticDescriptor, int> diagnosticsByDescriptor = results
                                                                                 .SelectMany(f => f.Diagnostics.Concat(f.CompilerDiagnostics))
                                                                                 .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id)
                                                                                 .ToDictionary(f => f.Key, f => f.Count());

                int maxCountLength = Math.Max(totalCount.ToString().Length, diagnosticsByDescriptor.Max(f => f.Value.ToString().Length));
                int maxIdLength    = diagnosticsByDescriptor.Max(f => f.Key.Id.Length);

                foreach (KeyValuePair <DiagnosticDescriptor, int> kvp in diagnosticsByDescriptor.OrderBy(f => f.Key.Id))
                {
                    WriteLine($"{kvp.Value.ToString().PadLeft(maxCountLength)} {kvp.Key.Id.PadRight(maxIdLength)} {kvp.Key.Title}", Verbosity.Normal);
                }
            }

            WriteLine(Verbosity.Minimal);
            WriteLine($"{totalCount} {((totalCount == 1) ? "diagnostic" : "diagnostics")} found", ConsoleColors.Green, Verbosity.Minimal);

            void WriteExecutionTime()
            {
                var telemetryInfos = new Dictionary <DiagnosticAnalyzer, AnalyzerTelemetryInfo>();

                foreach (ProjectAnalysisResult result in results)
                {
                    foreach (KeyValuePair <DiagnosticAnalyzer, AnalyzerTelemetryInfo> kvp in result.Telemetry)
                    {
                        DiagnosticAnalyzer analyzer = kvp.Key;

                        if (!telemetryInfos.TryGetValue(analyzer, out AnalyzerTelemetryInfo telemetryInfo))
                        {
                            telemetryInfo = new AnalyzerTelemetryInfo();
                        }

                        telemetryInfo.Add(kvp.Value);

                        telemetryInfos[analyzer] = telemetryInfo;
                    }
                }

                using (IEnumerator <KeyValuePair <DiagnosticAnalyzer, AnalyzerTelemetryInfo> > en = telemetryInfos
                                                                                                    .Where(f => f.Value.ExecutionTime >= MinimalExecutionTime)
                                                                                                    .OrderByDescending(f => f.Value.ExecutionTime)
                                                                                                    .GetEnumerator())
                {
                    if (en.MoveNext())
                    {
                        WriteLine(Verbosity.Minimal);

                        do
                        {
                            WriteLine($"{en.Current.Value.ExecutionTime:mm\\:ss\\.fff} '{en.Current.Key.GetType().FullName}'", Verbosity.Minimal);
                        }while (en.MoveNext());
                    }
                }
            }
        }
 public static double Average(this IList <double> col)
 => col.Sum() / col.Count;
Пример #52
0
        public async Task <IActionResult> Upload(IList <IFormFile> files)
        {
            try
            {
                if (files.Any(f => !Path.GetExtension(f.FileName).Equals(".pdf")))
                {
                    return(Redirect("~/Home"));
                }

                if (files.Any(f => f.Length > 31457280))
                {
                    return(Redirect("~/Home"));
                }

                FileDownloadModel fdm = new FileDownloadModel();
                fdm.Files = new List <FileModel>();
                long size           = files.Sum(f => f.Length);
                long totalReadBytes = 0;

                string firstFolderId = Guid.NewGuid().ToString();
                string directoryPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}";
                var    filePath      = Path.GetTempFileName();
                filePath = filePath.Replace(".tmp", ".pdf");

                foreach (var formFile in files)
                {
                    var type = Path.GetExtension(formFile.FileName);

                    if (formFile.Length > 0)
                    {
                        byte[] buffer = new byte[16 * 1024];

                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            using (Stream input = formFile.OpenReadStream())
                            {
                                int readBytes;

                                while ((readBytes = input.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    await stream.WriteAsync(buffer, 0, readBytes);
                                }
                            }

                            await formFile.CopyToAsync(stream);
                        }

                        directoryPath = string.Concat(directoryPath, "/" + formFile.FileName);
                        Directory.CreateDirectory(directoryPath);

                        using (var rasterizer = new GhostscriptRasterizer())
                        {
                            rasterizer.Open(filePath);

                            for (int i = 1; i <= rasterizer.PageCount; i++)
                            {
                                var page     = rasterizer.GetPage(120, 120, i);
                                var savePath = $"{directoryPath}/{formFile.FileName}_{i}.jpg";
                                page.Save(savePath);
                            }

                            rasterizer.Close();
                        }

                        string zipPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}/{formFile.FileName}.zip";
                        ZipFile.CreateFromDirectory(directoryPath, zipPath);

                        FileModel fileModel = new FileModel
                        {
                            FileName = formFile.FileName,
                            FilePath = zipPath
                        };

                        fdm.Files.Add(fileModel);
                    }

                    directoryPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}";
                }

                fdm.DownloadAllId = firstFolderId;

                if (files.Count > 1)
                {
                    string allZipPath = $"{this.HostingEnvironment.WebRootPath}/download/{firstFolderId}/pdftojpg.zip";
                    var    allToZip   = Directory.GetFiles(directoryPath);

                    using (ZipArchive newFile = ZipFile.Open(allZipPath, ZipArchiveMode.Create))
                    {
                        foreach (string file in allToZip)
                        {
                            newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
                        }
                    }
                }

                return(View(fdm));
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return(Redirect("~/Home"));
            }
        }
Пример #53
0
 private int GetMessageSize(IList <ITransportPacketInfo> packetInfos)
 {
     return(PacketSizeCalculatorUtil.Calculate(this.settings.PacketSizeLimits, packetInfos.Sum(x => x.Length)));
 }
 public static uint Average <T>(this IList <T> col, Func <T, uint> summer)
 => col.Sum(summer) / (uint)col.Count;
Пример #55
0
        /// <summary>
        /// Builds a dictionary containing Song ID keys and weight values.
        /// The weight values are determined by song popularity, song like, artist like, album like, and tag like.
        /// </summary>
        /// <param name="songsWithRanking">Songs grouped by community rank standing.</param>
        /// <returns></returns>
        /// <remarks>
        /// Based off of the song weights algorithm described here:
        /// http://stackoverflow.com/questions/3345788/algorithm-for-picking-thumbed-up-items/3345838#3345838
        ///
        /// The song weights algorithm is loosely based on the more general Multiplicative Weight Update Algorithm (MWUA), described here:
        /// https://jeremykun.com/2017/02/27/the-reasonable-effectiveness-of-the-multiplicative-weights-update-algorithm/
        /// </remarks>
        internal Dictionary <string, SongWeight> BuildSongWeightsTable(IList <Songs_RankStandings.Result> songsWithRanking)
        {
            // Generate a table containing all the songs. The table will be a dictionary of SongID keys and weight values.
            // Each song takes up N weight, where N starts out as 1, but can grow or shrink depending on whether that song/artist/album/tags is liked or disliked.
            var totalSongCount = songsWithRanking.Sum(s => s.SongIds.Count);
            var songWeights    = new Dictionary <string, SongWeight>(totalSongCount);

            foreach (var ranking in songsWithRanking)
            {
                var rankingMultipler = GetWeightMultiplier(ranking.Standing);
                var songIdsAndDates  = ranking.SongIds.Zip(ranking.SongUploadDates);
                foreach (var(songId, date) in songIdsAndDates)
                {
                    // Give it a weight based on its community rank.
                    // Multiply that weight by the song's age (newer songs are played more often.)
                    var ageMultiplier    = GetAgeMultiplier(date);
                    var rankAndAgeWeight = SongWeight.Default()
                                           .WithCommunityRankMultiplier(rankingMultipler)
                                           .WithAgeMultiplier(ageMultiplier);

                    songWeights[songId] = rankAndAgeWeight;
                }
            }

            // Now we've generated the table with all songs, each weighted according to their community ranking.
            // Next, adjust the weight based on whether we like this song or not.
            foreach (var likedSong in Songs)
            {
                if (songWeights.TryGetValue(likedSong.SongId, out var existingWeight))
                {
                    var songMultiplier = GetSongLikeDislikeMultiplier(likedSong);
                    songWeights[likedSong.SongId] = existingWeight.WithSongMultiplier(songMultiplier);
                }
            }

            // Next, adjust the weight based on whether we like this artist or not.
            var artistPrefs = Artists.GroupBy(a => a.Name);

            foreach (var artist in artistPrefs)
            {
                var artistMultiplier = GetArtistMultiplier(artist);
                if (artistMultiplier != 1.0)
                {
                    foreach (var pref in artist)
                    {
                        if (songWeights.TryGetValue(pref.SongId, out var existingWeight))
                        {
                            songWeights[pref.SongId] = existingWeight.WithArtistMultiplier(artistMultiplier);
                        }
                    }
                }
            }

            // Next, adjust the weight based on whether we like this album or not.
            var albumPrefs = Albums.GroupBy(a => a.Name);

            foreach (var album in albumPrefs)
            {
                var albumMultiplier = GetAlbumMultiplier(album);
                if (albumMultiplier != 1.0)
                {
                    foreach (var pref in album)
                    {
                        if (songWeights.TryGetValue(pref.SongId, out var existingWeight))
                        {
                            songWeights[pref.SongId] = existingWeight.WithAlbumMultiplier(albumMultiplier);
                        }
                    }
                }
            }

            // Adjust the weight based on whether we like the tags of the song or not.
            var tagLikeDislikeDifferences = CreateTagLikeDislikeDifferences(Tags);
            var songTags = Tags.GroupBy(t => t.SongId);
            var songsWithTagMultipliers = songTags.Select(tag => (SongId: tag.Key, TagsMultiplier: GetCumulativeTagMultiplier(tag, tagLikeDislikeDifferences)));

            foreach (var(SongId, TagsMultiplier) in songsWithTagMultipliers)
            {
                if (songWeights.TryGetValue(SongId, out var existingWeight))
                {
                    songWeights[SongId] = existingWeight.WithTagMultiplier(TagsMultiplier);
                }
            }

            return(songWeights);
        }
 public static ulong Average <T>(this IList <T> col, Func <T, ulong> summer)
 => col.Sum(summer) / (ulong)col.Count;
 public static float Average <T>(this IList <T> col, Func <T, float> summer)
 => col.Sum(summer) / col.Count;
 public static double Average <T>(this IList <T> col, Func <T, double> summer)
 => col.Sum(summer) / col.Count;
Пример #59
0
        private bool ScavengeChunks(bool alwaysKeepScavenged, IList <TFChunk.TFChunk> oldChunks, out long spaceSaved)
        {
            spaceSaved = 0;

            if (oldChunks.IsEmpty())
            {
                throw new ArgumentException("Provided list of chunks to scavenge and merge is empty.");
            }

            var sw = Stopwatch.StartNew();

            int  chunkStartNumber = oldChunks.First().ChunkHeader.ChunkStartNumber;
            long chunkStartPos    = oldChunks.First().ChunkHeader.ChunkStartPosition;
            int  chunkEndNumber   = oldChunks.Last().ChunkHeader.ChunkEndNumber;
            long chunkEndPos      = oldChunks.Last().ChunkHeader.ChunkEndPosition;

            var tmpChunkPath  = Path.Combine(_db.Config.Path, Guid.NewGuid() + ".scavenge.tmp");
            var oldChunksList = string.Join("\n", oldChunks);

            Log.Trace("SCAVENGING: started to scavenge & merge chunks: {0}\nResulting temp chunk file: {1}.",
                      oldChunksList, Path.GetFileName(tmpChunkPath));

            TFChunk.TFChunk newChunk;
            try
            {
                newChunk = TFChunk.TFChunk.CreateNew(tmpChunkPath, _db.Config.ChunkSize, chunkStartNumber, chunkEndNumber,
                                                     isScavenged: true, inMem: _db.Config.InMemDb);
            }
            catch (IOException exc)
            {
                Log.ErrorException(exc, "IOException during creating new chunk for scavenging purposes. Stopping scavenging process...");
                return(false);
            }

            try
            {
                var commits = new Dictionary <long, CommitInfo>();

                foreach (var oldChunk in oldChunks)
                {
                    TraverseChunk(oldChunk,
                                  prepare => { /* NOOP */ },
                                  commit =>
                    {
                        if (commit.TransactionPosition >= chunkStartPos)
                        {
                            commits.Add(commit.TransactionPosition, new CommitInfo(commit));
                        }
                    },
                                  system => { /* NOOP */ });
                }

                var positionMapping = new List <PosMap>();
                foreach (var oldChunk in oldChunks)
                {
                    TraverseChunk(oldChunk,
                                  prepare =>
                    {
                        if (ShouldKeepPrepare(prepare, commits, chunkStartPos, chunkEndPos))
                        {
                            positionMapping.Add(WriteRecord(newChunk, prepare));
                        }
                    },
                                  commit =>
                    {
                        if (ShouldKeepCommit(commit, commits))
                        {
                            positionMapping.Add(WriteRecord(newChunk, commit));
                        }
                    },
                                  // we always keep system log records for now
                                  system => positionMapping.Add(WriteRecord(newChunk, system)));
                }
                newChunk.CompleteScavenge(positionMapping);

                var oldSize = oldChunks.Sum(x => (long)x.PhysicalDataSize + x.ChunkFooter.MapSize + ChunkHeader.Size + ChunkFooter.Size);
                var newSize = (long)newChunk.PhysicalDataSize + PosMap.FullSize * positionMapping.Count + ChunkHeader.Size + ChunkFooter.Size;

                if (oldSize <= newSize && !alwaysKeepScavenged)
                {
                    Log.Trace("Scavenging of chunks:\n{0}\n"
                              + "completed in {1}.\n"
                              + "Old chunks' versions are kept as they are smaller.\n"
                              + "Old chunk total size: {2}, scavenged chunk size: {3}.\n"
                              + "Scavenged chunk removed.", oldChunksList, sw.Elapsed, oldSize, newSize);

                    newChunk.MarkForDeletion();
                    PublishChunksCompletedEvent(chunkStartNumber, chunkEndNumber, sw.Elapsed, false, spaceSaved);
                    return(false);
                }

                var chunk = _db.Manager.SwitchChunk(newChunk, verifyHash: false, removeChunksWithGreaterNumbers: false);
                if (chunk != null)
                {
                    Log.Trace("Scavenging of chunks:\n{0}\n"
                              + "completed in {1}.\n"
                              + "New chunk: {2} --> #{3}-{4} ({5}).\n"
                              + "Old chunks total size: {6}, scavenged chunk size: {7}.",
                              oldChunksList, sw.Elapsed, Path.GetFileName(tmpChunkPath),
                              chunkStartNumber, chunkEndNumber, Path.GetFileName(chunk.FileName), oldSize, newSize);
                    spaceSaved = oldSize - newSize;
                    PublishChunksCompletedEvent(chunkStartNumber, chunkEndNumber, sw.Elapsed, true, spaceSaved);
                    return(true);
                }
                else
                {
                    Log.Trace("Scavenging of chunks:\n{0}\n"
                              + "completed in {1}.\n"
                              + "But switching was prevented for new chunk: #{2}-{3} ({4}).\n"
                              + "Old chunks total size: {5}, scavenged chunk size: {6}.",
                              oldChunksList, sw.Elapsed,
                              chunkStartNumber, chunkEndNumber, Path.GetFileName(tmpChunkPath), oldSize, newSize);
                    PublishChunksCompletedEvent(chunkStartNumber, chunkEndNumber, sw.Elapsed, false, spaceSaved);
                    return(false);
                }
            }
            catch (FileBeingDeletedException exc)
            {
                Log.Info("Got FileBeingDeletedException exception during scavenging, that probably means some chunks were re-replicated.\n"
                         + "Scavenging of following chunks will be skipped:\n{0}\n"
                         + "Stopping scavenging and removing temp chunk '{1}'...\n"
                         + "Exception message: {2}.", oldChunksList, tmpChunkPath, exc.Message);
                Helper.EatException(() =>
                {
                    File.SetAttributes(tmpChunkPath, FileAttributes.Normal);
                    File.Delete(tmpChunkPath);
                });
                PublishChunksCompletedEvent(chunkStartNumber, chunkEndNumber, sw.Elapsed, false, spaceSaved);
                return(false);
            }
        }
Пример #60
0
 private static int CalculateError(IList <int> expenses, int target)
 {
     return(expenses.Sum() == target?expenses.Aggregate((x, y) => x *y) : 0);
 }