private bool TryGetRequestedRange( HttpRequestBase request, out Range range )
        {
            var rangeHeader = request.Headers[ "Range" ];
            if ( string.IsNullOrEmpty( rangeHeader ) )
            {
                range = null;
                return false;
            }

            if ( !rangeHeader.StartsWith( RangeByteHeaderStart ) )
            {
                range = null;
                return false;
            }

            var parts = rangeHeader.Substring( RangeByteHeaderStart.Length ).Split( '-' );

            if ( parts.Length != 2 )
            {
                range = null;
                return false;
            }

            range = new Range
            {
                Start = string.IsNullOrEmpty( parts[ 0 ] ) ? (long?) null : long.Parse( parts[ 0 ] ),
                End = string.IsNullOrEmpty( parts[ 1 ] ) ? (long?) null : long.Parse( parts[ 1 ] )
            };
            return true;
        }
Пример #2
0
 public void A_value_gap()
 {
     _range1 = new Range(1, 5);
     _range2 = new Range(10, 15);
     _expectedStart = 6;
     _expectedEnd = 9;
 }
        //---------------------------------------------------------------------

        public static string MapCodesToString(List<ushort> mapCodes)
        {
            if (mapCodes == null || mapCodes.Count == 0)
                return "";

            mapCodes.Sort();
            List<Range> ranges = new List<Range>();
            Range currentRange = new Range(mapCodes[0]);
            for (int i = 1; i < mapCodes.Count; i++) {
                ushort mapCode = mapCodes[i];
                if (currentRange.End + 1 == mapCode)
                    currentRange.End = mapCode;
                else {
                    ranges.Add(currentRange);
                    currentRange = new Range(mapCode);
                }
            }
            ranges.Add(currentRange);

            StringBuilder listAsText = new StringBuilder(ranges[0].ToString());
            for (int i = 1; i < ranges.Count; i++) {
                listAsText.AppendFormat(", {0}", ranges[i]);
            }
            return listAsText.ToString();
        }
Пример #4
0
        protected LogDetailsPageModel(BatNodeLog batLog)
        {
            EditLogCommand = new RelayCommand(() => _navigationService.EditLog(BatLog));

            BatLog = batLog;
            _batCalls = new List<BatCall>();

            FrequencyRange = new Range<uint>(0, 100);
            FrequencyRange.PropertyChanged += async (s, e) => await UpdateBins();

            IntensityRange = new Range<uint>(0, 1024);
            IntensityRange.PropertyChanged += async (s, e) => await UpdateBins();

            DurationRange = new Range<uint>(0, 100);
            DurationRange.PropertyChanged += async (s, e) => await UpdateBins();

            TimeRange = new Range<uint>(0, 100);
            TimeRange.PropertyChanged += async (s, e) => await UpdateBins();

			//BUG!
            Func<BatCall, bool> filter = c => IntensityRange.Contains(c.MaxPower) && FrequencyRange.Contains(c.MaxFrequency) && DurationRange.Contains(c.Duration / 1000) && TimeRange.Contains(c.StartTimeMs);
            FreqBins = new UintBinCollection(100, b => (uint)b.MaxFrequency, filter);
            IntensityBins = new UintBinCollection(200, b => (uint)b.MaxPower, filter);
            CallDurationBins = new UintBinCollection(100, b => b.Duration / 1000, filter);
            TimeBins = new TimeCallBinCollection(200, batLog.LogStart, filter);
        }
Пример #5
0
        public void IsOverlappingTest( float min1, float max1, float min2, float max2, bool expectedResult )
        {
            Range range1 = new Range( min1, max1 );
            Range range2 = new Range( min2, max2 );

            Assert.AreEqual( expectedResult, range1.IsOverlapping( range2 ) );
        }
Пример #6
0
        void MakePage(Document doc, Range range)
        {
            var table = doc.Tables.Add(range, (int)m_numberOfRows, 2);

            table.Rows.SetHeight(136.1F, WdRowHeightRule.wdRowHeightExactly);
            table.Columns.SetWidth(295.65F, WdRulerStyle.wdAdjustNone); // 297.65F

            table.LeftPadding = 0.75F;
            table.RightPadding = 0.75F;
            table.TopPadding = 5F;

            for (int row = 1; row <= m_numberOfRows; ++row)
                for (int col = 1; col <= 2; ++col)
                {
                    string code = m_tr.ReadLine();

                    if (code == null) return;

                    Console.WriteLine("Row:{0}, Col:{1}", row, col);
                    var cell = table.Cell(row, col);

                    cell.Range.Delete();
                    cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                    PopCell(cell.Range, "Horsell Jubilation Balloon Race", isBold:true, fontSize:12, first:true);
                    PopCell(cell.Range, "", fontSize:12);
                    PopCell(cell.Range, "Notice to the finder of this balloon:", isBold:true);
                    PopCell(cell.Range, "Please go to the website www.diamondballoons.info to register your details and the location of the balloon. By doing so you will be entered into a draw for a £25 Amazon Gift Voucher. Good luck and thank you!");
                    PopCell(cell.Range, code, false, 12, centre: true);
                    PopCell(cell.Range, "", fontSize: 12);

                    ++m_count;
                }
        }
 public void AllFloats_EndpointsExcluded()
 {
     Range<float> range = new Range<float>();
     range.MinIncluded = false;
     range.MaxIncluded = false;
     CheckFloatRange(range);
 }
        public void EqualsShouldFailIfObjectIsNotRange()
        {
            var a = new Range<int>(1, 3);
            const int b = 1;

            Assert.False(a.Equals(b));
        }
Пример #9
0
        public override void Draw(Graphics gr, Point position, Range range)
        {
            if (range.End.iChar > range.Start.iChar)
            {
                base.Draw(gr, position, range);

                int firstNonSpaceSymbolX = position.X;

                //find first non space symbol
                for (int i = range.Start.iChar; i < range.End.iChar; i++)
                    if (range.tb[range.Start.iLine][i].c != ' ')
                        break;
                    else
                        firstNonSpaceSymbolX += range.tb.CharWidth;

                //create marker
                range.tb.AddVisualMarker(new FoldedAreaMarker(range.Start.iLine, new Rectangle(firstNonSpaceSymbolX, position.Y, position.X + (range.End.iChar - range.Start.iChar) * range.tb.CharWidth - firstNonSpaceSymbolX, range.tb.CharHeight)));
            }
            else
            {
                //draw '...'
                using (Font f = new Font(range.tb.Font, FontStyle))
                    gr.DrawString("...", f, ForeBrush, range.tb.LeftIndent, position.Y - 2);
                //create marker
                range.tb.AddVisualMarker(new FoldedAreaMarker(range.Start.iLine, new Rectangle(range.tb.LeftIndent + 2, position.Y, 2 * range.tb.CharHeight, range.tb.CharHeight)));
            }
        }
Пример #10
0
 /// <summary>
 /// Creates a new <see cref="ConstraintsExpectation"/> instance.
 /// </summary>
 /// <param name="invocation">Invocation for this expectation</param>
 /// <param name="constraints">Constraints.</param>
 /// <param name="expectedRange">Number of method calls for this expectations</param>
 public ConstraintsExpectation(IInvocation invocation,AbstractConstraint[] constraints, Range expectedRange)
     : base(invocation, expectedRange)
 {
     Validate.IsNotNull(()=>constraints);
     this.constraints = constraints;
     ConstraintsMatchMethod();
 }
		public void AbstractExpectationPropertiesReturnTheValuesSetByDerivedClass()
		{
			Range r = new Range(0, 30);
			IExpectation test = GetExpectation(method, r, 5);
			Assert.Equal(r, test.Expected);
			Assert.Equal(5, test.ActualCallsCount);
		}
Пример #12
0
        public SentimentIndex()
            : base("Sentiment Index")
        {
            numberOfTrainingItems = Variable.New<int>();
            var rangeOfTrainingItems = new Range(numberOfTrainingItems);
            trainingInputs = Variable.Array<Vector>(rangeOfTrainingItems);
            trainingOutputs = Variable.Array<bool>(rangeOfTrainingItems);

            weights = Variable.Random(new VectorGaussian(Vector.Zero(numberOfFeatures), PositiveDefiniteMatrix.Identity(numberOfFeatures)));

            using (Variable.ForEach(rangeOfTrainingItems))
            {
                trainingOutputs[rangeOfTrainingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(weights, trainingInputs[rangeOfTrainingItems]), noise));
            }

            trainingEngine = new InferenceEngine();
            trainingEngine.ShowProgress = false;

            numberOfTestingItems = Variable.New<int>();
            var rangeOfTestingItems = new Range(numberOfTestingItems);
            testingInputs = Variable.Array<Vector>(rangeOfTestingItems);
            testingOutputs = Variable.Array<bool>(rangeOfTestingItems);

            weightsPosteriorDistribution = Variable.New<VectorGaussian>();
            var testWeights = Variable<Vector>.Random(weightsPosteriorDistribution);

            using (Variable.ForEach(rangeOfTestingItems))
            {
                testingOutputs[rangeOfTestingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(testWeights, testingInputs[rangeOfTestingItems]), noise));
            }

            testingEngine = new InferenceEngine();
            testingEngine.ShowProgress = false;
        }
Пример #13
0
        public void WriteCarInfo(List<CarBrand> carBrandList)
        {
            int index = 1;
            foreach (CarBrand carBrand in carBrandList)
            {
                foreach (CarFactory carFactory in carBrand.CarFactoryList)
                {
                    foreach (CarType carType in carFactory.CarTypeList)
                    {
                        ++index;
                        
                        mWorksheet.Cells[index, 1] = carBrand.Alpha.ToString();
                        mWorksheet.Cells[index, 2] = carBrand.Name;
                        mWorksheet.Cells[index, 3] = carBrand.OfficialSite;
                        mWorksheet.Cells[index, 4] = carBrand.Country.Name;
                        mWorksheet.Cells[index, 5] = carFactory.Name;
                        mWorksheet.Cells[index, 6] = carFactory.OfficialSite;
                        mWorksheet.Cells[index, 7] = carType.Name;
                        mWorksheet.Cells[index, 8] = carType.PriceMin;
                        mWorksheet.Cells[index, 9] = carType.PriceMax;

                        for (int i = 1; i <= ExcelConstants.SHEET_HEADERS.Length; ++i)
                        {
                            mRange = mWorksheet.Cells[index, i];
                            mRange.EntireColumn.AutoFit();
                        }
                    }
                }
            }

            saveExcelFile();
        }
Пример #14
0
 public string GetHtml(FastColoredTextBox tb)
 {
     this.tb = tb;
     Range sel = new Range(tb);
     sel.SelectAll();
     return GetHtml(sel);
 }
Пример #15
0
 /// <summary>
 /// Get range of text
 /// </summary>
 /// <param name="textbox"></param>
 /// <param name="fromPos">Absolute start position</param>
 /// <param name="toPos">Absolute finish position</param>
 /// <returns>Range</returns>
 public static Range GetRange(FastColoredTextBox textbox, int fromPos, int toPos)
 {
     var sel = new Range(textbox);
     sel.Start = TextSourceUtil.PositionToPlace(textbox.lines, fromPos);
     sel.End = TextSourceUtil.PositionToPlace(textbox.lines, toPos);
     return sel;
 }
Пример #16
0
        public void Overlaps_should_return_correct_value(int a1, int a2, int b1, int b2, bool expected)
        {
            var subject = new Range<int>(a1, a2);
            var comparand = new Range<int>(b1, b2);

            subject.Overlaps(comparand).Should().Be(expected);
        }
Пример #17
0
 public void ShouldSupportDecimal()
 {
     var range = new Range<decimal>(0.1m, 3.1m);
     var other = new Range<decimal>(2.1m, 4);
     Assert.AreEqual(new Range<decimal>(2.1m, 3.1m), range.Intersect(other));
     
 }
        public ComponentSetSelectionCarouselDialog(Scene.ObjectRegistrationHandler registrationHandler, Scene.ObjectUnregistrationHandler unregistrationHandler)
            : base(registrationHandler, unregistrationHandler)
        {
            _selectableComponentSets = new List<AvatarComponentSet>();

            Height = Dialog_Height;
            TopYWhenActive = Definitions.Back_Buffer_Height - Dialog_Height;
            CarouselCenter = new Vector2(Definitions.Back_Buffer_Center.X, Carousel_Center_Y);
            CarouselRadii = new Vector2(Carousel_Horizontal_Radius, Carousel_Vertical_Radius);
            _itemRenderDepths = new Range(Minimum_Item_Render_Depth, Maximum_Item_Render_Depth);
            _itemScales = new Range(Minimum_Item_Scale, Maximum_Item_Scale);

            AddIconButton("previous", new Vector2(Definitions.Back_Buffer_Center.X - 450, 175), Button.ButtonIcon.Previous, Color.DodgerBlue);
            AddIconButton("next", new Vector2(Definitions.Back_Buffer_Center.X + 450, 175), Button.ButtonIcon.Next, Color.DodgerBlue);

            AddButton("Back", new Vector2(Definitions.Left_Button_Column_X, 325), Button.ButtonIcon.Back, Color.Red, 0.7f);
            AddButton("Change", new Vector2(Definitions.Right_Button_Column_X, 325), Button.ButtonIcon.Options, Color.LawnGreen, 0.7f);

            ActionButtonPressHandler = HandleActionButtonPress;
            TopYWhenInactive = Definitions.Back_Buffer_Height;

            SetupButtonLinkagesAndDefaultValues();

            registrationHandler(this);
        }
Пример #19
0
			//

			public void UpdateToLibrary( bool updateDirection )
			{
				if( joint.jointID == IntPtr.Zero )
					return;

				if( updateDirection )
					Ode.dJointSetHingeAxis( joint.jointID, Direction.X, Direction.Y, Direction.Z );

				//limits

				Range range;
				if( LimitsEnabled )
				{
					if( joint.Body1.Static )
						range = new Range( LimitLow.InRadians(), LimitHigh.InRadians() );
					else
						range = new Range( -LimitHigh.InRadians(), -LimitLow.InRadians() );
				}
				else
					range = new Range( -Ode.dInfinity, Ode.dInfinity );

				// Both limits must be set twice because of a ODE bug in
				// the limit setting function.
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamLoStop, range.Minimum );
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamHiStop, range.Maximum );
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamLoStop, range.Minimum );
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamHiStop, range.Maximum );

				float h = LimitsRestitution * ( Defines.maxERP - Defines.minERP ) + Defines.minERP;
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamStopERP, h );

				float b = LimitsRestitution * ( Defines.maxERP - Defines.minERP ) + Defines.minERP;
				Ode.dJointSetHingeParam( joint.jointID, Ode.dJointParams.dParamBounce, b );
			}
Пример #20
0
 public void Intersect_ShouldReturnIntersection_WhenExists()
 {
     var range = new Range<int>(0, 3);
     var other = new Range<int>(2, 4);
     Assert.AreEqual(new Range<int>(2, 3), range.Intersect(other));
     
 }
Пример #21
0
        /// <summary>
        /// Parses a range from the given query.
        /// </summary>
        /// <param name="query">Query.</param>
        /// <returns>Range.</returns>
        public Range<int> Parse(Query query)
        {
            Range<int> ret = null;

            Skip = -1;
            Take = -1;

            Visit(query);

            if (Skip > 0 || Take > 0)
            {
                ret = new Range<int>();

                if (Skip <= 0 && Take > 0)
                    ret.To = Take;
                else if (Skip > 0 && Take <= 0)
                    ret.From = Skip;
                else
                {
                    ret.From = Skip + 1;
                    ret.To = System.Math.Abs(Skip + Take);
                }
            }
            else
                ret = new Range<int>(-1, -1);

            return ret;
        }
Пример #22
0
 public override void SelectRange(Range range, bool select)
 {
     for (int r = range.Start.Row; r <= range.End.Row; r++)
     {
         SelectRow(r, select);
     }
 }
Пример #23
0
        private static double pppx = -1, pppy = -1; //points per pixel per axis

        #endregion Fields

        #region Methods

        public static void CellTopLeftPixels(Range rng)
        {
            if (!init)
            {
                PixelsPerPointX();
                PixelsPerPointY();
                GetFormulaBarAndHeadingsDim();
                init = true;
            }

            //get all the pieces together

            double appTop = Globals.ThisAddIn.Application.Top;
            double appLeft = Globals.ThisAddIn.Application.Left;
            long RibbonHeight = Globals.ThisAddIn.Application.CommandBars["Ribbon"].Height;

            //the upper-left corner position

            top = (long)((appTop + RibbonHeight + rng.Top + fbTop + hTop - 15) * pppy);
            left = (long)((appLeft + rng.Left + fbLeft + hLeft + rng.Width + 25) * pppx);

            //the lower-right corner position
            long topc = (long)((appTop + RibbonHeight + rng.Top + fbTop + hTop + rng.Height) * pppy);
            long leftc = (long)((appLeft + rng.Left + rng.Width + fbLeft + hTop) * pppx);
        }
        public StorePurchaseDialog(Scene.ObjectRegistrationHandler registrationHandler, Scene.ObjectUnregistrationHandler unregistrationHandler)
            : base(registrationHandler, unregistrationHandler)
        {
            Height = Purchase_Dialog_Height;
            TopYWhenActive = Definitions.Back_Buffer_Height - (Purchase_Dialog_Height + Bopscotch.Scenes.NonGame.StoreScene.Dialog_Margin);
            CarouselCenter = new Vector2(Definitions.Back_Buffer_Center.X, Carousel_Center_Y);
            CarouselRadii = new Vector2(Carousel_Horizontal_Radius, Carousel_Vertical_Radius);
            _itemRenderDepths = new Range(Minimum_Item_Render_Depth, Maximum_Item_Render_Depth);
            _itemScales = new Range(Minimum_Item_Scale, Maximum_Item_Scale);

            AddIconButton("previous", new Vector2(Definitions.Back_Buffer_Center.X - 450, 175), Button.ButtonIcon.Previous, Color.DodgerBlue);
            AddIconButton("next", new Vector2(Definitions.Back_Buffer_Center.X + 450, 175), Button.ButtonIcon.Next, Color.DodgerBlue);

            AddButton("Back", new Vector2(Definitions.Left_Button_Column_X, 400), Button.ButtonIcon.Back, Color.DodgerBlue, 0.7f);
            AddButton("Buy", new Vector2(Definitions.Right_Button_Column_X, 400), Button.ButtonIcon.Tick, Color.Orange, 0.7f);

            _nonSpinButtonCaptions.Add("Buy");

            ActionButtonPressHandler = HandleActionButtonPress;
            TopYWhenInactive = Definitions.Back_Buffer_Height;

            SetupButtonLinkagesAndDefaultValues();

            registrationHandler(this);

            _textTransitionTimer = new Timer("");
            GlobalTimerController.GlobalTimer.RegisterUpdateCallback(_textTransitionTimer.Tick);
            _textTransitionTimer.NextActionDuration = 1;
            _textTint = Color.White;

            _font = Game1.Instance.Content.Load<SpriteFont>("Fonts\\arial");
        }
Пример #25
0
        protected override IEnumerable<IEventInfo> GetEventInfos(TimeLineVisualizationState state, HierarchicalItem hierarchicalWrapper)
        {
            if (!(hierarchicalWrapper.SourceItem is CustomRecurrenceTask))
            {
                foreach (var info in base.GetEventInfos(state, hierarchicalWrapper))
                {
                    yield return info;
                }
            }

            var dateRange = hierarchicalWrapper.SourceItem as IDateRange;
            var roundedRange = state.Rounder.Round(dateRange);
            var taskRange = new Range<long>(roundedRange.Start.Ticks, roundedRange.End.Ticks);
            var task = hierarchicalWrapper.SourceItem as CustomRecurrenceTask;
            Range<long> range = null;

            if (task != null && task.RecurrenceRule != null)
            {
                for (int i = 0; i < task.RecurrenceRule.OcurrenceCount; i++)
                {
                    var recurrence = state.Rounder.Round(this.GetRecurrence(task, i));
                    range = new Range<long>(recurrence.Start.Ticks, recurrence.End.Ticks);

                    yield return new TimeLineRecurrenceEventInfo(range, hierarchicalWrapper.Index)
                    {
                        OriginalEvent = recurrence
                    };
                }
            }
        }
Пример #26
0
		private void Join(Range range1, Range range2)
		{
			Range result = Range.GetBounds(range1, range2);
			m_ranges.Remove(range1);
			m_ranges.Remove(range2);
			m_ranges.Add(result);
		}
Пример #27
0
 public UnitFormat(double unit, string name, Range potRange, bool factored, bool decimalExtend, double weight)
     : base(factored, decimalExtend, weight)
 {
     _unit = unit;
     _name = name;
     _potRange = potRange;
 }
Пример #28
0
		/// <summary>
		/// Creates a new iterator instance.
		/// </summary>
		/// <param name="sequence">An existing sequence instance.</param>
		/// <exception cref="System.ArgumentNullException">if sequence is null.</exception>
		public QuotesRangeSingleIterator(QuotesRangeSingleSequence sequence)
		{
			if (sequence == null)
    			throw new ArgumentNullException(nameof(sequence), "Sequence parameter can not be null.");

			this.Sequence = sequence;

            this.iterator = new QuotesSingleIterator(sequence.Storage, sequence.Symbol, sequence.StartTime, sequence.EndTime, sequence.Depth);
            var range = new Range<Quote>(sequence.LowerBound, sequence.UpperBound);

            var index = sequence.LowerBound;

            for (; (index < sequence.UpperBound) && this.iterator.Continue; ++index)
            {
                range[index] = this.iterator.Current;
                this.iterator.NextTick();
            }

            if (index == sequence.UpperBound)
            {
                this.Current = range;
                this.Continue = true;
            }
            else
            {
                this.Continue = false;
            }
		}
Пример #29
0
        public override object CalculateResult()
        {
            var digitRepresentations = new Range(0, 9, true)
                .Select(n => PrimeGenerator.Instance.GetPrimeAtIndex(n))
                .ToArray();

            return new Range(1, int.MaxValue)
                .Select(numDigits =>
                {
                    long num = MathUtilities.Pow(10L, numDigits - 1);
                    long maximum = num * 10;

                    return new Range((int)Math.Pow(num, 1.0 / 3.0), int.MaxValue)
                        .Select(n => (long)n)
                        .Select(n => n * n * n)
                        .SkipWhile(n => n < num)
                        .TakeWhile(n => n < maximum)
                        .GroupBy(n => MathUtilities.ToDigits(n)
                            .Select(d => digitRepresentations[d])
                            .Product())
                        .Where(g => g.Count() == 5)
                        .SelectMany(x => x)
                        .Select(x => (long?)x)
                        .DefaultIfEmpty()
                        .Min();
                })
                .WhereNotNull()
                .First();
        }
Пример #30
0
        /*
         * Returns the cell Border of a cell
         */
        public static CellBorder getBorder(Range cell)
        {
            sally.BorderLine top, right, bottom, left;
            CellBorder ret = null;
            int weight, style;
            Microsoft.Office.Interop.Excel.Border aux;
            try
            {
                Microsoft.Office.Interop.Excel.Borders borders= cell.Borders;
                aux = borders[XlBordersIndex.xlEdgeTop];
                lineStyle(aux,out weight, out style);
                top = sally.BorderLine.CreateBuilder().SetBorderColor((int)aux.Color).SetFormatStyle(0).SetExcelBorderStyle(style).SetExcelBorderWeight(weight).Build();

                aux = borders[XlBordersIndex.xlEdgeRight];
                lineStyle(aux, out weight, out style);
                right = sally.BorderLine.CreateBuilder().SetBorderColor((int)aux.Color).SetFormatStyle(0).SetExcelBorderStyle(style).SetExcelBorderWeight(weight).Build();

                aux = borders[XlBordersIndex.xlEdgeLeft];
                lineStyle(aux, out weight, out style);
                left = sally.BorderLine.CreateBuilder().SetBorderColor((int)aux.Color).SetFormatStyle(0).SetExcelBorderStyle(style).SetExcelBorderWeight(weight).Build();

                aux = borders[XlBordersIndex.xlEdgeBottom];
                lineStyle(aux, out weight, out style);
                bottom = sally.BorderLine.CreateBuilder().SetBorderColor((int)aux.Color).SetFormatStyle(0).SetExcelBorderStyle(style).SetExcelBorderWeight(weight).Build();

                ret = CellBorder.CreateBuilder().SetBottom(bottom).SetLeft(left).SetRight(right).SetTop(top).Build();
            }
            catch (Exception ex) { }
            return ret;
        }
Пример #31
0
 public static Range SetVerticalAlignmentToTop(this Range range)
 {
     return(range.SetVerticalAlignment(TextAlignmentType.Top));
 }
Пример #32
0
        public static string teGetMarkets(string mrkt, string columnsToUse, [ExcelArgument(AllowReference = true)] object firstCell)
        {
            helperClass.log.Info("=======================");
            helperClass.log.Info("Starting TEMarkets udf");
            string key = Properties.Settings.Default.userApiKey;

            // Convert column names to JArray names
            fullNames = new Dictionary <string, string>();
            if (mrkt == "bonds")
            {
                for (int i = 0; i < helperClass.bondsNames.Length; i++)
                {
                    fullNames.Add(helperClass.bondsNames[i], helperClass.bondsNamesFull[i]);
                }
            }
            else
            {
                for (int i = 0; i < helperClass.marketsNames.Length; i++)
                {
                    fullNames.Add(helperClass.marketsNames[i], helperClass.marketsNamesFull[i]);
                }
            }

            string answer  = "Updated at " + DateTime.Now.TimeOfDay.ToString("hh\\:mm\\:ss");
            string columns = columnsToUse;

            try
            {
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;
            }
            catch (Exception)
            {
                MyRibbon.app   = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;
            }

            ExcelReference caller       = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
            Range          caller_range = helperClass.ReferenceToRange(caller);
            Range          formulaCell  = caller_range; //Last cell used in userform
            Range          dataStartCell;

            string newFormula;

            if (firstCell is ExcelMissing)
            {
                dataStartCell = formulaCell;
                newFormula    = string.Format($"=TEMarkets( \"{mrkt}\", \"{columns}\")");
            }
            else
            {
                try
                {
                    dataStartCell = helperClass.ReferenceToRange((ExcelReference)firstCell);
                    newFormula    = string.Format($"=TEMarkets( \"{mrkt}\", \"{columns}\", {dataStartCell.Address[false, false]})");
                }
                catch (Exception)
                {
                    refError = true;
                    helperClass.getNewDict();
                    return("#REF!");

                    throw;
                }
            }
            Range          pass             = null;
            formulaColumns frmlaColumnsPair = new formulaColumns(newFormula, columns, pass, formulaCell);

            MyRibbon.myNewDict = new Dictionary <string, formulaColumns>();

            try
            {
                XlCall.Excel(XlCall.xlfVolatile, false);
            }
            catch (Exception e)
            {
                helperClass.log.Error(e.Message);
                helperClass.log.Trace(e.StackTrace);
                throw;
            }

            if (formulaCell.Address == dataStartCell.Address)
            {
                answer = columns.Split(',')[0];
            }

            if (helperClass.runFormula == "RunAutomatically = 1")
            {
                helperClass.log.Info("TEMarkets udf -> RunAutomatically = 1");

                if (MyRibbon.refresh != true)
                {
                    helperClass.setGlobalDict(formulaCell.Address[false, false], frmlaColumnsPair);
                }

                url = host + "markets/" + mrkt + "?client=" + key + "&excel=" + helperClass.Determine_OfficeVersion();
                var jsnData = new requestData(url);
                var jsData  = jsnData.getJSON();

                if (jsData.Count == 0)
                {
                    MessageBox.Show("No data provided for selected parameters");
                }
                else
                {
                    List <string> columnsFull = new List <string>();

                    foreach (var item in columns.Split(','))
                    {
                        if (fullNames.ContainsKey(item))
                        {
                            columnsFull.Add(fullNames[item]);
                        }
                    }
                    columns = String.Join(",", columnsFull);
                    try
                    {
                        helperClass.elseFunction(columns, jsData, key, dataStartCell, newFormula, formulaCell);
                    }
                    catch (Exception ex)
                    {
                        helperClass.log.Info(ex.Message);
                        helperClass.log.Trace(ex.StackTrace);
                        throw;
                    }
                }
            }
            else
            {
                helperClass.log.Info("TEMarkets udf -> RunAutomatically != 1");
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;
                if (MyRibbon.myMainDict.ContainsKey(MyRibbon.sheet.Index.ToString()))
                {
                    MyRibbon.myFormulasDict = MyRibbon.myMainDict[MyRibbon.sheet.Index.ToString()];
                }
                else
                {
                    MyRibbon.myFormulasDict = new Dictionary <string, formulaColumns>();
                }
                foreach (var item in MyRibbon.myFormulasDict.Keys)
                {
                    if (MyRibbon.myFormulasDict[item]._formula == newFormula && item == MyRibbon.myFormulasDict[item]._caller.Address[false, false])
                    {
                        return(answer);
                    }
                }
                Dictionary <string, formulaColumns> myNewDict = helperClass.getNewDict();

                url = host + "markets/" + mrkt + "?client=" + key + "&excel=" + helperClass.Determine_OfficeVersion();
                var jsnData = new requestData(url);
                var jsData  = jsnData.getJSON();
                if (jsData.Count == 0)
                {
                    MessageBox.Show("No data provided for selected parameters");
                }
                else
                {
                    List <string> columnsFull = new List <string>();

                    foreach (var item in columns.Split(','))
                    {
                        if (fullNames.ContainsKey(item))
                        {
                            columnsFull.Add(fullNames[item]);
                        }
                    }
                    columns = String.Join(",", columnsFull);
                    try
                    {
                        helperClass.elseFunction(columns, jsData, key, dataStartCell, newFormula, formulaCell);
                    }
                    catch (Exception ex)
                    {
                        helperClass.log.Info(ex.Message);
                        helperClass.log.Trace(ex.StackTrace);
                        throw;
                    }
                }
                helperClass.RemoveOldKey(myNewDict);
            }
            helperClass.runFormula = "RunAutomatically = 0";
            helperClass.origin     = true;
            helperClass.log.Info("Printing current cell value and finishing Markets process");
            MyRibbon.refresh = false;
            return(answer);
        }
Пример #33
0
        public static string teGetCalendar(string cntry, string indctr, string startDate, string endDate, string columnsToUse, [ExcelArgument(AllowReference = true)] object firstCell)
        {
            helperClass.log.Info("=======================");
            helperClass.log.Info("Starting TECalendar udf");
            string key     = Properties.Settings.Default.userApiKey;
            string answer  = "Updated at " + DateTime.Now.TimeOfDay.ToString("hh\\:mm\\:ss");
            string columns = columnsToUse;

            helperClass.fromCalendar = true;
            try
            {
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;
            }
            catch (Exception)
            {
                MyRibbon.app   = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;
            }

            ExcelReference caller       = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
            Range          caller_range = helperClass.ReferenceToRange(caller);
            Range          formulaCell  = caller_range; //Last cell used in userform
            Range          dataStartCell;

            string newFormula;

            if (firstCell is ExcelMissing)
            {
                dataStartCell = formulaCell;
                newFormula    = string.Format($"=TECalendar( \"{cntry}\", \"{indctr}\", \"{startDate}\", \"{endDate}\", \"{columns}\")");
            }
            else
            {
                try
                {
                    dataStartCell = helperClass.ReferenceToRange((ExcelReference)firstCell);
                    newFormula    = string.Format($"=TECalendar( \"{cntry}\", \"{indctr}\", \"{startDate}\", \"{endDate}\", \"{columns}\", {dataStartCell.Address[false, false]})");
                }
                catch (Exception)
                {
                    refError = true;
                    helperClass.getNewDict();
                    return("#REF!");

                    throw;
                }
            }
            Range          pass             = null;
            formulaColumns frmlaColumnsPair = new formulaColumns(newFormula, columns, pass, formulaCell);

            MyRibbon.myNewDict = new Dictionary <string, formulaColumns>();

            try
            {
                XlCall.Excel(XlCall.xlfVolatile, false);
            }
            catch (Exception e)
            {
                helperClass.log.Error(e.Message);
                helperClass.log.Trace(e.StackTrace);
                throw;
            }

            if (formulaCell.Address == dataStartCell.Address)
            {
                answer = columns.Split(',')[0];
            }

            if (helperClass.runFormula == "RunAutomatically = 1")
            {
                helperClass.log.Info("TECalendar udf -> RunAutomatically = 1");

                if (MyRibbon.refresh != true)
                {
                    helperClass.setGlobalDict(formulaCell.Address[false, false], frmlaColumnsPair);
                }

                JArray jsData = helperClass.SOmeName(cntry, indctr, key, "Cal", startDate, endDate);

                if (jsData.Count == 0)
                {
                    MessageBox.Show("No data provided for selected parameters");
                }
                else
                {
                    try
                    {
                        helperClass.elseFunction(columns, jsData, key, dataStartCell, newFormula, formulaCell);
                    }
                    catch (Exception ex)
                    {
                        helperClass.log.Info(ex.Message);
                        helperClass.log.Trace(ex.StackTrace);
                        throw;
                    }
                }
            }
            else
            {
                helperClass.log.Info("TECalendar udf -> RunAutomatically != 1");
                MyRibbon.sheet = MyRibbon.app.ActiveSheet;

                if (MyRibbon.myMainDict.ContainsKey(MyRibbon.sheet.Index.ToString()))
                {
                    MyRibbon.myFormulasDict = MyRibbon.myMainDict[MyRibbon.sheet.Index.ToString()];
                }
                else
                {
                    MyRibbon.myFormulasDict = new Dictionary <string, formulaColumns>();
                }

                foreach (var item in MyRibbon.myFormulasDict.Keys)
                {
                    if (MyRibbon.myFormulasDict[item]._formula == newFormula && item == MyRibbon.myFormulasDict[item]._caller.Address[false, false])
                    {
                        return(answer);
                    }
                }

                Dictionary <string, formulaColumns> myNewDict = helperClass.getNewDict();
                JArray jsData = helperClass.SOmeName(cntry, indctr, key, "Cal", startDate, endDate);

                if (jsData.Count == 0)
                {
                    MessageBox.Show("No data provided for selected parameters");
                }
                else
                {
                    try
                    {
                        helperClass.elseFunction(columns, jsData, key, dataStartCell, newFormula, formulaCell);
                    }
                    catch (Exception ex)
                    {
                        helperClass.log.Info(ex.Message);
                        helperClass.log.Trace(ex.StackTrace);
                        throw;
                    }
                }
                helperClass.RemoveOldKey(myNewDict);
            }
            helperClass.runFormula = "RunAutomatically = 0";
            helperClass.origin     = true;
            MyRibbon.refresh       = false;
            helperClass.log.Info("Printing current cell value and finishing Calendar process");
            return(answer);
        }
Пример #34
0
 //public RetrieveAndWriteTSData(string[] names, Dictionary<string, Dictionary<string, string>> dict, string key, Range dataStartCell, string nFrmla, Range formulaCell)
 public RetrieveAndWriteTSData(string[] names, Dictionary <DateTime, Dictionary <string, string> > dict, string key, Range dataStartCell, string nFrmla, Range formulaCell)
 {
     this.names         = names;
     this.dict          = dict;
     this.key           = key;
     this.dataStartCell = dataStartCell;
     this.newFormula    = nFrmla;
     this.formulaCell   = formulaCell;
 }
Пример #35
0
 public static Range SetFontUnderlineToNone(this Range range)
 {
     return(range.SetFontUnderline(FontUnderlineType.None));
 }
Пример #36
0
 public static Range SetBorder(this Range range, BorderType borderType)
 {
     range.SetOutlineBorder(borderType, CellBorderType.Thin, Color.Silver);
     return(range);
 }
Пример #37
0
        public bool Equals([AllowNull] Step other)
        {
            if (other == null)
            {
                return(false);
            }

            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return((Color == other.Color && Color != null && other.Color != null && Color.Equals(other.Color)) &&
                   (Line == other.Line && Line != null && other.Line != null && Line.Equals(other.Line)) &&
                   (Thickness == other.Thickness && Thickness != null && other.Thickness != null && Thickness.Equals(other.Thickness)) &&
                   (Equals(Range, other.Range) || Range != null && other.Range != null && Range.SequenceEqual(other.Range)) &&
                   (Name == other.Name && Name != null && other.Name != null && Name.Equals(other.Name)) &&
                   (TemplateItemName == other.TemplateItemName && TemplateItemName != null && other.TemplateItemName != null && TemplateItemName.Equals(other.TemplateItemName)));
        }
Пример #38
0
 public static Range SetVerticalAlignmentToBottom(this Range range)
 {
     return(range.SetVerticalAlignment(TextAlignmentType.Bottom));
 }
Пример #39
0
 public static Range SetHorizontalAlignmentToRight(this Range range)
 {
     return(range.SetHorizontalAlignment(TextAlignmentType.Right));
 }
Пример #40
0
 public static Range SetVerticalAlignmentToCenter(this Range range)
 {
     return(range.SetVerticalAlignment(TextAlignmentType.Center));
 }
Пример #41
0
 public static Range SetFormat(this Range range, DisplayFormat value)
 {
     return(range.SetFormat((int)value));
 }
Пример #42
0
 public static Range SetRowHeight(this Range range, double height)
 {
     range.RowHeight = height;
     return(range);
 }
Пример #43
0
 /// <summary>
 /// Queries the signal buffer for the collection of measurements
 /// between the dates specified by the given time range.
 /// </summary>
 /// <param name="key">The key which identifies the signal to be queried.</param>
 /// <param name="timeRange">The time range to be queried.</param>
 /// <returns>The collection of measurements for the signal that fall between the dates in the given time range.</returns>
 public IEnumerable <IMeasurement> QuerySignalBuffer(MeasurementKey key, Range <DateTime> timeRange)
 {
     return(QuerySignalBuffer(key, timeRange.Start, timeRange.End));
 }
Пример #44
0
 public static Range SetColumnWidth(this Range range, double width)
 {
     range.ColumnWidth = width;
     return(range);
 }
Пример #45
0
        private int CreateFullyConnectedRoomGrid(
            Random rng)
        {
            int lateralRoomCount = m_worldTemplate.DungeonLateralRoomCount;
            int floorCount       = m_worldTemplate.DungeonFloorCount;
            int totalRoomCount   = lateralRoomCount * lateralRoomCount * floorCount;

            m_roomGrid   = new RoomLayout[lateralRoomCount, lateralRoomCount, floorCount];
            m_minRoomKey = new RoomKey(m_gameId, -lateralRoomCount / 2, -lateralRoomCount / 2, 0);

            // Fully connect the rooms on each floor, but leave each floor unconnected initially
            for (RoomIndexIterator iterator = new RoomIndexIterator(m_roomGrid, RoomIndexIterator.eIterationType.allRooms);
                 iterator.Valid;
                 iterator.Next())
            {
                RoomIndex roomIndex = iterator.Current;

                RoomKey roomKey =
                    new RoomKey(
                        m_gameId,
                        roomIndex.X - lateralRoomCount / 2,
                        roomIndex.Y - lateralRoomCount / 2,
                        roomIndex.Z);
                RoomLayout room = new RoomLayout(roomKey);

                if (roomIndex.X > 0)
                {
                    room.RoomFlagPortalOnSide(MathConstants.eSignedDirection.negative_x, true);
                }

                if (roomIndex.X < lateralRoomCount - 1)
                {
                    room.RoomFlagPortalOnSide(MathConstants.eSignedDirection.positive_x, true);
                }

                if (roomIndex.Y > 0)
                {
                    room.RoomFlagPortalOnSide(MathConstants.eSignedDirection.negative_y, true);
                }

                if (roomIndex.Y < lateralRoomCount - 1)
                {
                    room.RoomFlagPortalOnSide(MathConstants.eSignedDirection.positive_y, true);
                }

                m_roomGrid[roomIndex.X, roomIndex.Y, roomIndex.Z] = room;
            }

            // Randomly add stairs connecting each floor
            for (int z_index = 0; z_index < floorCount - 1; z_index++)
            {
                Range <int>       stairsRange       = m_worldTemplate.StairsPerFloor;
                IList <RoomIndex> randomRoomIndices = GetRoomIndexListForFloor(z_index);
                int desiredStairsCount = RNGUtilities.RandomInt(rng, stairsRange.Min, stairsRange.Max);
                int currentStairsCount = 0;

                RNGUtilities.DeterministicKnuthShuffle(rng, randomRoomIndices);

                foreach (RoomIndex roomIndex in randomRoomIndices)
                {
                    Room room      = m_roomGrid[roomIndex.X, roomIndex.Y, roomIndex.Z];
                    Room roomAbove = m_roomGrid[roomIndex.X, roomIndex.Y, roomIndex.Z + 1];

                    // Only consider rooms of the configuration X+X-Y+Y- to add stairs to
                    // because we only have rooms with stairs for the templates
                    // X+X-Y+Y-Z+ and X+X-Y+Y-Z-
                    // We do this so that we can get away with 18 room templates rather than 64
                    if (room.RoomHasAllPossibleDoors && !room.RoomHasStairs)
                    {
                        room.RoomFlagPortalOnSide(MathConstants.eSignedDirection.positive_z, true);
                        roomAbove.RoomFlagPortalOnSide(MathConstants.eSignedDirection.negative_z, true);
                        ++currentStairsCount;
                    }

                    if (currentStairsCount >= desiredStairsCount)
                    {
                        break;
                    }
                }
            }

            return(totalRoomCount);
        }
Пример #46
0
 public static Range SetForegroundColorToTransparent(this Range range)
 {
     return(range.SetForegroundColor(Color.Transparent));
 }
Пример #47
0
 public Expression(T value, Range range)
 {
     GenericValue = value;
     Range        = range;
 }
Пример #48
0
 /// <summary>
 /// Queries the signal buffer for the collection of measurements
 /// between the dates specified by the given time range.
 /// </summary>
 /// <param name="signalID">The ID of the signal to be queried.</param>
 /// <param name="timeRange">The time range to be queried.</param>
 /// <returns>The collection of measurements for the signal that fall between the dates in the given time range.</returns>
 public IEnumerable <IMeasurement> QuerySignalBuffer(Guid signalID, Range <DateTime> timeRange)
 {
     return(QuerySignalBuffer(signalID, timeRange.Start, timeRange.End));
 }
Пример #49
0
        FillIDColumn
        (
            ListObject oTable
        )
        {
            Debug.Assert(oTable != null);
            AssertValid();

            // Read the range that contains visible data.  If the table is
            // filtered, the range may contain multiple areas.

            Range      oVisibleRange;
            ListColumn oIDColumn;

            if (
                !ExcelTableUtil.TryGetVisibleTableRange(oTable, out oVisibleRange)
                ||
                ExcelTableUtil.VisibleTableRangeIsEmpty(oTable)
                ||
                !ExcelTableUtil.TryGetOrAddTableColumn(oTable,
                                                       CommonTableColumnNames.ID, ExcelTableUtil.AutoColumnWidth,
                                                       null, out oIDColumn)
                )
            {
                return;
            }

            Int32 iIDColumnIndex = oIDColumn.Index;

            Range oDataBodyRange = oTable.DataBodyRange;

            Debug.Assert(oDataBodyRange != null);
            Debug.Assert(oTable.Parent is Worksheet);

            Worksheet oWorksheet = (Worksheet)oTable.Parent;

            foreach (Range oArea in oVisibleRange.Areas)
            {
                // Get the rows within the ID column that should be filled in.

                Int32 iAreaStartRowOneBased  = oArea.Row;
                Int32 iRowsInArea            = oArea.Rows.Count;
                Int32 iTableStartRowOneBased = oTable.Range.Row;

                Range oIDRange = oWorksheet.get_Range(

                    (Range)oDataBodyRange.Cells[
                        iAreaStartRowOneBased - iTableStartRowOneBased,
                        iIDColumnIndex],

                    (Range)oDataBodyRange.Cells[
                        iAreaStartRowOneBased - iTableStartRowOneBased
                        + iRowsInArea - 1,
                        iIDColumnIndex]
                    );

                // Use the Excel row numbers as the unique IDs.  Create a
                // one-column array, then fill it in with the row numbers.

                Int32 iRows = oIDRange.Rows.Count;

                Object [,] aoValues = ExcelUtil.GetSingleColumn2DArray(iRows);

                for (Int32 i = 1; i <= iRows; i++)
                {
                    aoValues[i, 1] = iAreaStartRowOneBased + i - 1;
                }

                oIDRange.Value2 = aoValues;

            #if false
                // Note: Don't use the following clever code to fill in the row
                // numbers.  On large worksheets, the calculations take forever.

                oIDRange.Value2 = "=ROW()";
                oIDRange.Value2 = oIDRange.Value2;
            #endif
            }
        }
Пример #50
0
 public ValidRange(Range range)
 {
     Range = range;
 }
Пример #51
0
 public CustomList2 this[Range range] => this;
Пример #52
0
        TryGetLocation
        (
            ExcelTableReader.ExcelTableRow oRow,
            String sXColumnName,
            String sYColumnName,
            VertexLocationConverter oVertexLocationConverter,
            out PointF oLocation
        )
        {
            Debug.Assert(oRow != null);
            Debug.Assert(!String.IsNullOrEmpty(sXColumnName));
            Debug.Assert(!String.IsNullOrEmpty(sYColumnName));
            Debug.Assert(oVertexLocationConverter != null);
            AssertValid();

            oLocation = PointF.Empty;

            String sX, sY;

            Boolean bHasX = oRow.TryGetNonEmptyStringFromCell(
                sXColumnName, out sX);

            Boolean bHasY = oRow.TryGetNonEmptyStringFromCell(
                sYColumnName, out sY);

            if (bHasX != bHasY)
            {
                // X or Y alone won't do.

                goto Error;
            }

            if (!bHasX && !bHasY)
            {
                return(false);
            }

            Single fX, fY;

            if (!Single.TryParse(sX, out fX) || !Single.TryParse(sY, out fY))
            {
                goto Error;
            }

            // Transform the location from workbook coordinates to graph
            // coordinates.

            oLocation = oVertexLocationConverter.WorkbookToGraph(fX, fY);

            return(true);

Error:

            Range oInvalidCell = oRow.GetRangeForCell(sXColumnName);

            OnWorkbookFormatError(String.Format(

                                      "There is a problem with the location at {0}.  If you enter a"
                                      + " location, it must include both X and Y numbers.  Any"
                                      + " numbers are acceptable, although {1} is used for any"
                                      + " number less than {1} and and {2} is used for any number"
                                      + " greater than {2}."
                                      ,
                                      ExcelUtil.GetRangeAddress(oInvalidCell),

                                      VertexLocationConverter.MinimumXYWorkbook.ToString(
                                          ExcelTemplateForm.Int32Format),

                                      VertexLocationConverter.MaximumXYWorkbook.ToString(
                                          ExcelTemplateForm.Int32Format)
                                      ),

                                  oInvalidCell
                                  );

            // Make the compiler happy.

            return(false);
        }
Пример #53
0
        /// <summary>
        /// Returns a System.IO.Packaging.Package stream for the given range.
        /// </summary>
        /// <param name="range">Range in word document</param>
        /// <returns></returns>
        public static Stream GetPackageStreamFromRange(this Range range)
        {
            XDocument  doc = XDocument.Parse(range.WordOpenXML);
            XNamespace pkg =
                "http://schemas.microsoft.com/office/2006/xmlPackage";
            XNamespace rel =
                "http://schemas.openxmlformats.org/package/2006/relationships";
            Package      InmemoryPackage = null;
            MemoryStream memStream       = new MemoryStream();

            using (InmemoryPackage = Package.Open(memStream, FileMode.Create))
            {
                // add all parts (but not relationships)
                foreach (var xmlPart in doc.Root
                         .Elements()
                         .Where(p =>
                                (string)p.Attribute(pkg + "contentType") !=
                                "application/vnd.openxmlformats-package.relationships+xml"))
                {
                    string name        = (string)xmlPart.Attribute(pkg + "name");
                    string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType.EndsWith("xml"))
                    {
                        Uri         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = InmemoryPackage.CreatePart(u, contentType,
                                                                      CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (XmlWriter xmlWriter = XmlWriter.Create(str))
                                xmlPart.Element(pkg + "xmlData")
                                .Elements()
                                .First()
                                .WriteTo(xmlWriter);
                    }
                    else
                    {
                        Uri         u    = new Uri(name, UriKind.Relative);
                        PackagePart part = InmemoryPackage.CreatePart(u, contentType,
                                                                      CompressionOption.SuperFast);
                        using (Stream str = part.GetStream(FileMode.Create))
                            using (BinaryWriter binaryWriter = new BinaryWriter(str))
                            {
                                string base64StringInChunks =
                                    (string)xmlPart.Element(pkg + "binaryData");
                                char[] base64CharArray = base64StringInChunks
                                                         .Where(c => c != '\r' && c != '\n').ToArray();
                                byte[] byteArray =
                                    System.Convert.FromBase64CharArray(base64CharArray,
                                                                       0, base64CharArray.Length);
                                binaryWriter.Write(byteArray);
                            }
                    }
                }
                foreach (var xmlPart in doc.Root.Elements())
                {
                    string name        = (string)xmlPart.Attribute(pkg + "name");
                    string contentType = (string)xmlPart.Attribute(pkg + "contentType");
                    if (contentType ==
                        "application/vnd.openxmlformats-package.relationships+xml")
                    {
                        // add the package level relationships
                        if (name == "/_rels/.rels")
                        {
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                string id         = (string)xmlRel.Attribute("Id");
                                string type       = (string)xmlRel.Attribute("Type");
                                string target     = (string)xmlRel.Attribute("Target");
                                string targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    InmemoryPackage.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    InmemoryPackage.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                        else
                        // add part level relationships
                        {
                            string directory    = name.Substring(0, name.IndexOf("/_rels"));
                            string relsFilename = name.Substring(name.LastIndexOf('/'));
                            string filename     =
                                relsFilename.Substring(0, relsFilename.IndexOf(".rels"));
                            PackagePart fromPart = InmemoryPackage.GetPart(
                                new Uri(directory + filename, UriKind.Relative));
                            foreach (XElement xmlRel in
                                     xmlPart.Descendants(rel + "Relationship"))
                            {
                                string id         = (string)xmlRel.Attribute("Id");
                                string type       = (string)xmlRel.Attribute("Type");
                                string target     = (string)xmlRel.Attribute("Target");
                                string targetMode =
                                    (string)xmlRel.Attribute("TargetMode");
                                if (targetMode == "External")
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Absolute),
                                        TargetMode.External, type, id);
                                }
                                else
                                {
                                    fromPart.CreateRelationship(
                                        new Uri(target, UriKind.Relative),
                                        TargetMode.Internal, type, id);
                                }
                            }
                        }
                    }
                }
                InmemoryPackage.Flush();
            }
            return(memStream);
        }
Пример #54
0
        /// <summary>
        /// Creates a new set of monitored items for a set of variables.
        /// </summary>
        /// <remarks>
        /// This method only handles data change subscriptions. Event subscriptions are created by the SDK.
        /// </remarks>
        protected override ServiceResult CreateMonitoredItem(ServerSystemContext context, NodeHandle handle, uint subscriptionId, double publishingInterval, DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, ref long globalIdCounter, out MonitoringFilterResult filterResult, out IMonitoredItem monitoredItem)
        {
            filterResult = null;
            monitoredItem = null;

            // validate parameters.
            MonitoringParameters parameters = itemToCreate.RequestedParameters;

            // validate attribute.
            if (!Attributes.IsValid(handle.Node.NodeClass, itemToCreate.ItemToMonitor.AttributeId))
            {
                return StatusCodes.BadAttributeIdInvalid;
            }

            NodeState cachedNode = AddNodeToComponentCache(context, handle, handle.Node);

            // check if the node is already being monitored.
            MonitoredNode2 monitoredNode = null;

            if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out monitoredNode))
            {
                MonitoredNodes[handle.Node.NodeId] = monitoredNode = new MonitoredNode2(this, cachedNode);
            }

            handle.Node = monitoredNode.Node;
            handle.MonitoredNode = monitoredNode;

            // create a globally unique identifier.
            uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter);

            // determine the sampling interval.
            double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval;

            if (samplingInterval < 0)
            {
                samplingInterval = publishingInterval;
            }

            // ensure minimum sampling interval is not exceeded.
            if (itemToCreate.ItemToMonitor.AttributeId == Attributes.Value)
            {
                BaseVariableState variable = handle.Node as BaseVariableState;

                if (variable != null && samplingInterval < variable.MinimumSamplingInterval)
                {
                    samplingInterval = variable.MinimumSamplingInterval;
                }
            }

            // put a large upper limit on sampling.
            if (samplingInterval == Double.MaxValue)
            {
                samplingInterval = 365 * 24 * 3600 * 1000.0;
            }

            // put an upper limit on queue size.
            uint queueSize = itemToCreate.RequestedParameters.QueueSize;

            if (queueSize > MaxQueueSize)
            {
                queueSize = MaxQueueSize;
            }

            // validate the monitoring filter.
            Range euRange = null;
            MonitoringFilter filterToUse = null;

            ServiceResult error = ValidateMonitoringFilter(
                context,
                handle,
                itemToCreate.ItemToMonitor.AttributeId,
                samplingInterval,
                queueSize,
                parameters.Filter,
                out filterToUse,
                out euRange,
                out filterResult);

            if (ServiceResult.IsBad(error))
            {
                return error;
            }

            // create the item.
            MonitoredItem datachangeItem = new ComMonitoredItem(
                Server,
                this,
                handle,
                subscriptionId,
                monitoredItemId,
                context.OperationContext.Session,
                itemToCreate.ItemToMonitor,
                diagnosticsMasks,
                timestampsToReturn,
                itemToCreate.MonitoringMode,
                itemToCreate.RequestedParameters.ClientHandle,
                filterToUse,
                filterToUse,
                euRange,
                samplingInterval,
                queueSize,
                itemToCreate.RequestedParameters.DiscardOldest,
                0);

            // report the initial value.
            ReadInitialValue(context, handle, datachangeItem);

            // update monitored item list.
            monitoredItem = datachangeItem;

            // save the monitored item.
            MonitoredItems.Add(monitoredItemId, datachangeItem);
            monitoredNode.Add(datachangeItem);

            // report change.
            OnMonitoredItemCreated(context, handle, datachangeItem);

            return error;
        }
Пример #55
0
 public void AddMap(TextSegment segment, int length)
 {
     map [(int)segment] = new Range(GetStart(segment), (uint)length);
 }
Пример #56
0
 private void OnEnemiesWaveBordersChanged(Range waveBorder)
 {
     _horizontalMoveOffsetRange = Range.OffsetBetweenRanges(
         _gameSettings.HorizontalGameViewRange, waveBorder);
 }
Пример #57
0
        private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks, out Range range)
        {
            ulong rangeStart = ulong.MaxValue;
            ulong rangeEnd   = 0;

            for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
            {
                Block block = blocks[blkIndex];

                if (!block.Exit)
                {
                    if (rangeStart > block.Address)
                    {
                        rangeStart = block.Address;
                    }

                    if (rangeEnd < block.EndAddress)
                    {
                        rangeEnd = block.EndAddress;
                    }
                }

                context.CurrBlock = block;

                context.MarkLabel(context.GetLabel(block.Address));

                if (block.Exit)
                {
                    InstEmitFlowHelper.EmitTailContinue(context, Const(block.Address), block.TailCall);
                }
                else
                {
                    for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
                    {
                        OpCode opCode = block.OpCodes[opcIndex];

                        context.CurrOp = opCode;

                        bool isLastOp = opcIndex == block.OpCodes.Count - 1;

                        if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
                        {
                            EmitSynchronization(context);
                        }

                        Operand lblPredicateSkip = null;

                        if (opCode is OpCode32 op && op.Cond < Condition.Al)
                        {
                            lblPredicateSkip = Label();

                            InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
                        }

                        if (opCode.Instruction.Emitter != null)
                        {
                            opCode.Instruction.Emitter(context);
                        }
                        else
                        {
                            throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
                        }

                        if (lblPredicateSkip != null)
                        {
                            context.MarkLabel(lblPredicateSkip);
                        }
                    }
                }
            }

            range = new Range(rangeStart, rangeEnd);

            return(context.GetControlFlowGraph());
        }
Пример #58
0
 public void AddMap(TextSegment segment, Range range)
 {
     map [(int)segment] = range;
 }
Пример #59
0
        //按鈕Click事件
        protected void lbtOK_Click(object sender, EventArgs e)
        {
            string excel_filePath = "";

            if (FileUpload2.HasFile)
            {
                try
                {
                    excel_filePath = SaveFileAndReturnPath();    //先上傳EXCEL檔案給Server

                    if (this.xlApp == null)
                    {
                        this.xlApp = new Microsoft.Office.Interop.Excel.Application();
                    }
                    //打開Server上的Excel檔案
                    this.xlApp.Workbooks.Open(excel_filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    this.wb = xlApp.Workbooks[1];    //第一個Workbook
                    this.wb.Save();

                    //從第一個Worksheet讀資料
                    SaveOrInsertSheet(excel_filePath, (Worksheet)xlApp.Worksheets[1]);



                    ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "匯入完成", "alert('匯入完成');", true);
                }

                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    xlApp.Workbooks.Close();
                    xlApp.Quit();
                    try
                    {
                        //刪除 Windows工作管理員中的Excel.exe 處理緒.
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(this.xlApp);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(this.ws);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(this.aRange);
                    }
                    catch { }
                    this.xlApp  = null;
                    this.wb     = null;
                    this.ws     = null;
                    this.aRange = null;


                    //是否刪除Server上的Excel檔
                    bool isDeleteFileFromServer = true;
                    if (isDeleteFileFromServer)
                    {
                        System.IO.File.Delete(excel_filePath);
                    }


                    GC.Collect();
                }
            }
            else
            {
                ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "請選擇檔案", "alert('請選擇檔案');", true);
            }
        }
Пример #60
0
 public static IEnumerable <int> AsEnumerable(this Range range)
 {
     return(Range(range));
 }