public VirtualDiskStream(string vhdPath) { this.vhdFile = new VhdFileFactory().Create(vhdPath); this.blockFactory = vhdFile.GetBlockFactory(); footerRange = this.blockFactory.GetFooterRange(); fileDataRange = IndexRange.FromLength(0, this.Length - footerRange.Length); }
/// <summary> /// 分割索引范围 /// </summary> /// <param name="index">索引</param> /// <param name="span">跨度</param> public IndexRange Split( int index, int span ) { if ( index == Index ) { Index = index + span; return null; } var result = new IndexRange( index + span,EndIndex ); EndIndex = index - 1; return result; }
private static int SolveWithMemoization( int[] treatValues, IndexRange indexRange, int age, Dictionary<IndexRange, int> memoizer) { if (indexRange.Start == indexRange.End) return age * treatValues[indexRange.Start]; int result; if (memoizer.TryGetValue(indexRange, out result)) return result; result = Math.Max( age * treatValues[indexRange.Start] + SolveWithMemoization(treatValues, IndexRange.Create(indexRange.Start + 1, indexRange.End), age + 1, memoizer), age * treatValues[indexRange.End] + SolveWithMemoization(treatValues, IndexRange.Create(indexRange.Start, indexRange.End - 1), age + 1, memoizer)); memoizer.Add(indexRange, result); return result; }
public void ContainsAllIndexes(int?start, int?end, int step, bool expected) { var range = new IndexRange(start, end, step); range.ContainsAllIndexes.Should().Be(expected); }
public void MessagePrintBlockRange(IndexRange range) { LogMessage("Range of the block is {0}, Length: {1}", range, range.Length); }
public void MessagePrintBlockRange(IndexRange range) { LogMessage(Resources.PSSyncOutputEventsPrintBlockRange, range, range.Length); }
public IPointSeries ToPointSeries(IList column, ResamplingMode resamplingMode, IndexRange pointRange, int viewportWidth, bool isCategoryAxis) { throw new NotSupportedException(); }
public IRange GetWindowedYRange(IndexRange xIndexRange, bool getPositiveRange) { throw new NotSupportedException(); }
private void OnNewPrice(PriceBar price) { // Ensure only one update processed at a time from multi-threaded timer lock (this) { // Update the last price, or append? var ds0 = (IOhlcDataSeries<DateTime, double>)_seriesViewModels[0].DataSeries; if (_lastPrice != null && _lastPrice.DateTime == price.DateTime) { ds0.Update(price.DateTime, price.Open, price.High, price.Low, price.Close); } else { ds0.Append(price.DateTime, price.Open, price.High, price.Low, price.Close); // If the latest appending point is inside the viewport (i.e. not off the edge of the screen) // then scroll the viewport 1 bar, to keep the latest bar at the same place if (XVisibleRange.Max > ds0.Count) { var existingRange = _xVisibleRange; var newRange = new IndexRange(existingRange.Min + 1, existingRange.Max + 1); XVisibleRange = newRange; } } _lastPrice = price; } }
/// <summary> /// Identify continuous blocks of variable metadata directives, mapped to the range of source code /// they're located in. /// </summary> /// <param name="source"></param> /// <param name="ignoreRegions"></param> /// <returns></returns> private Dictionary <IndexRange, List <IndexRange> > IdentifyMetadataBlocks(string source, List <IndexRange> ignoreRegions) { Dictionary <IndexRange, List <IndexRange> > metadataBlocks = new Dictionary <IndexRange, List <IndexRange> >(); using (StringReader reader = new StringReader(source)) { List <IndexRange> currentBlock = new List <IndexRange>(); IndexRange currentBlockRange = new IndexRange(0, 0); int lineIndex = 0; while (true) { string line = reader.ReadLine(); if (line == null) { break; } // Trim the current line, so ignored ranges are removed IndexRange lineRange = new IndexRange(lineIndex, line.Length); IndexRange trimmedLineRange = lineRange; foreach (IndexRange ignoreRange in ignoreRegions) { trimmedLineRange.Trim(ignoreRange); if (trimmedLineRange.Length == 0) { break; } } string trimmedLine = (trimmedLineRange.Length == 0) ? string.Empty : source.Substring(trimmedLineRange.Index, trimmedLineRange.Length); // Process the current line bool isLineEmpty = string.IsNullOrWhiteSpace(trimmedLine); if (!isLineEmpty) { Match match = RegexMetadataDirective.Match(trimmedLine); if (match != null && match.Length > 0) { // Extend the current metadata block to include the detected directive IndexRange metadataRange = new IndexRange(trimmedLineRange.Index + match.Index, match.Length); metadataRange = this.ExpandToLine(source, metadataRange); currentBlock.Add(metadataRange); currentBlockRange.Length = (metadataRange.Index + metadataRange.Length) - currentBlockRange.Index; } else { // Close the current metadata block if (currentBlock.Count > 0) { metadataBlocks.Add(currentBlockRange, new List <IndexRange>(currentBlock)); } // Start a new metadata block currentBlock.Clear(); currentBlockRange.Index = lineRange.Index + lineRange.Length + Environment.NewLine.Length; currentBlockRange.Length = 0; } } else { // If we have a current block, incorporate comment and empty lines into it until it ends if (currentBlock.Count > 0) { currentBlockRange.Length = (lineRange.Index + lineRange.Length) - currentBlockRange.Index; } // Otherwise, move the start of the current block forward until we actually find a metadata line else { currentBlockRange.Index = lineRange.Index + lineRange.Length + Environment.NewLine.Length; currentBlockRange.Length = 0; } } lineIndex += line.Length; lineIndex += Environment.NewLine.Length; } } return(metadataBlocks); }
public List <IndexRange> GetExceptRanges(string s) { var ranges = this.GetIndexRanges(s); return(IndexRange.GetExceptRanges(ranges, s)); }
private static object RunCSharpCodeWithRoslyn(LNode parent, LNodeList code, IMacroContext context, ParsingMode printMode = null) { // Note: when using compileTimeAndRuntime, the transforms here affect the version // sent to Roslyn, but not the runtime version placed in the output file. code = code.SmartSelectMany(stmt => { // Ensure #r gets an absolute path; I don't know what Roslyn does with a // relative path (maybe WithMetadataResolver would let me control this, // but it's easier not to) if ((stmt.Calls(S.CsiReference, 1) || stmt.Calls(S.CsiLoad, 1)) && stmt[0].Value is string fileName) { fileName = fileName.Trim().WithoutPrefix("\"").WithoutSuffix("\""); var inputFolder = context.ScopedProperties.TryGetValue((Symbol)"#inputFolder", "").ToString(); var fullPath = Path.Combine(inputFolder, fileName); return(LNode.List(stmt.WithArgChanged(0, stmt[0].WithValue("\"" + fullPath + "\"")))); } // For each (top-level) LexicalMacro method, call #macro_context.RegisterMacro(). LNode attribute = null; if ((attribute = stmt.Attrs.FirstOrDefault( attr => AppearsToCall(attr, "LeMP", nameof(LexicalMacroAttribute).WithoutSuffix("Attribute")) || AppearsToCall(attr, "LeMP", nameof(LexicalMacroAttribute)))) != null && EcsValidators.MethodDefinitionKind(stmt, out _, out var macroName, out _, out _) == S.Fn) { var setters = SeparateAttributeSetters(ref attribute); attribute = attribute.WithTarget((Symbol)nameof(LexicalMacroAttribute)); setters.Insert(0, attribute); var newAttribute = F.Call(S.New, setters); var registrationCommand = F.Call(F.Dot(__macro_context, nameof(IMacroContext.RegisterMacro)), F.Call(S.New, F.Call(nameof(MacroInfo), F.Null, newAttribute, macroName))); return(LNode.List(stmt, registrationCommand)); } return(LNode.List(stmt)); }); var outputLocationMapper = new LNodeRangeMapper(); var options = new LNodePrinterOptions { IndentString = " ", SaveRange = outputLocationMapper.SaveRange }; string codeText = EcsLanguageService.WithPlainCSharpPrinter.Print(code, context.Sink, printMode, options); _roslynSessionLog?.WriteLine(codeText); _roslynSessionLog?.Flush(); _roslynScriptState.GetVariable(__macro_context_sanitized).Value = context; try { // Allow users to write messages via MessageSink.Default using (MessageSink.SetDefault(new MessageSinkFromDelegate((sev, ctx, msg, args) => { _roslynSessionLog?.Write("{0} from user ({1}): ", sev, MessageSink.GetLocationString(ctx)); _roslynSessionLog?.WriteLine(msg, args); context.Sink.Write(sev, ctx, msg, args); }))) { _roslynScriptState = _roslynScriptState.ContinueWithAsync(codeText).Result; } return(_roslynScriptState.ReturnValue); } catch (CompilationErrorException e) when(e.Diagnostics.Length > 0 && e.Diagnostics[0].Location.IsInSource) { // Determine the best location in the source code at which to report the error. // Keep in mind that the error may have occurred in a synthetic location not // found in the original code, and we cannot report such a location. Microsoft.CodeAnalysis.Text.TextSpan range = e.Diagnostics[0].Location.SourceSpan; var errorLocation = new IndexRange(range.Start, range.Length); var mappedErrorLocation = outputLocationMapper.FindRelatedNodes(errorLocation, 10) .FirstOrDefault(p => !p.A.Range.Source.Text.IsEmpty); string locationCaveat = ""; if (mappedErrorLocation.A != null) { bool mappedIsEarly = mappedErrorLocation.B.EndIndex <= errorLocation.StartIndex; if (mappedIsEarly || mappedErrorLocation.B.StartIndex >= errorLocation.EndIndex) { locationCaveat = "; " + "The error occurred at a location ({0}) that doesn't seem to exist in the original code.".Localized( mappedIsEarly ? "after the location indicated".Localized() : "before the location indicated".Localized()); } } // Extract the line where the error occurred, for inclusion in the error message int column = e.Diagnostics[0].Location.GetLineSpan().StartLinePosition.Character; int lineStart = range.Start - column; int lineEnd = codeText.IndexOf('\n', lineStart); if (lineEnd < lineStart) { lineEnd = codeText.Length; } string line = codeText.Substring(lineStart, lineEnd - lineStart); string errorMsg = e.Message + " - in «{0}»{1}".Localized(line, locationCaveat); context.Sink.Error(mappedErrorLocation.A ?? parent, errorMsg); LogRoslynError(e, context.Sink, parent, compiling: true); } catch (Exception e) { while (e is AggregateException ae && ae.InnerExceptions.Count == 1) { e = ae.InnerExceptions[0]; } context.Sink.Error(parent, "An exception was thrown from your code:".Localized() + " " + e.ExceptionMessageAndType()); LogRoslynError(e, context.Sink, parent, compiling: false); } return(NoValue.Value); }
public IndexRange GetFooterRange() { return(IndexRange.FromLength(this.GetBlockSize() * this.BlockCount, VhdConstants.VHD_FOOTER_SIZE)); }
public IndexRange GetFooterRange() { return(IndexRange.FromLength(this.vhdFile.Footer.CurrentSize, VhdConstants.VHD_FOOTER_SIZE)); }
/// <summary> /// Parses all shader field declarations, aggregated with their metadata directives. /// </summary> /// <param name="source"></param> /// <param name="ignoreRegions"></param> /// <param name="removeSchedule"></param> /// <returns></returns> private void ParseFields(string source, List <IndexRange> ignoreRegions, List <IndexRange> removeSchedule) { // Read the source line by line and parse it along the way List <string> fieldMetadata = new List <string>(); using (StringReader reader = new StringReader(source)) { int lineIndex = 0; while (true) { string line = reader.ReadLine(); if (line == null) { break; } // Trim the current line, so ignored ranges are removed IndexRange lineRange = new IndexRange(lineIndex, line.Length); IndexRange trimmedLineRange = lineRange; foreach (IndexRange ignoreRange in ignoreRegions) { trimmedLineRange.Trim(ignoreRange); if (trimmedLineRange.Length == 0) { break; } } foreach (IndexRange ignoreRange in removeSchedule) { trimmedLineRange.Trim(ignoreRange); if (trimmedLineRange.Length == 0) { break; } } string trimmedLine = (trimmedLineRange.Length == 0) ? string.Empty : source.Substring(trimmedLineRange.Index, trimmedLineRange.Length); // Keep track of where we are in the source, and skip over lines that // fall within source regions that are flagged to be ignored. lineIndex += line.Length; lineIndex += Environment.NewLine.Length; // Cleanup remaining line to make it easier to parse trimmedLine = trimmedLine.Trim().TrimEnd(';'); if (string.IsNullOrEmpty(trimmedLine)) { continue; } // Scan for metadata directives and store them until we hit the next variable declaration Match metadataMatch = RegexMetadataDirective.Match(trimmedLine); if (metadataMatch != null && metadataMatch.Length > 0) { string metadataDirective = metadataMatch.Groups[1].Value; fieldMetadata.Add(metadataDirective); continue; } // Scan for field declarations and aggregate them with previously collected metadata directives ShaderFieldInfo field = this.ParseFieldDeclaration(trimmedLine, fieldMetadata); if (field != null) { this.fields.Add(field); fieldMetadata.Clear(); continue; } // Clear metadata directives when reading non-empty lines that don't match any of the above fieldMetadata.Clear(); } } }
public ChartViewModel() { this.SetDefaults(); if (IsInDesignMode) { // Code runs in Blend --> create design time data. _marketDataService = new MarketDataService(new DateTime(2015, 08, 11), 1, 5000); } else { // Code runs "for real" _marketDataService = new MarketDataService(new DateTime(2015, 08, 11), 1, 1000); } var ds0 = new OhlcDataSeries<DateTime, double>(); _seriesViewModels.Add(new ChartSeriesViewModel(ds0, new FastOhlcRenderableSeries() { Name = "Series1", XAxisId = "dateTimeXAxis", YAxisId = "Y1" })); // Append 500 historical bars to data series var prices = _marketDataService.GetHistoricalData(500); ds0.Append( prices.Select(x => x.DateTime), prices.Select(x => x.Open), prices.Select(x => x.High), prices.Select(x => x.Low), prices.Select(x => x.Close)); //Create price/volume distribution double minPrice = prices.Select(x => x.Low).Min(); double maxPrice = prices.Select(x => x.High).Max(); int numBins = 5; double interval = (maxPrice - minPrice) / numBins; var bins = new Tuple<double, double>[numBins]; double binLower = minPrice; for (int i = 0; i < numBins; i++) { bins[i] = new Tuple<double, double>(binLower, binLower + interval); binLower += interval; } var dsVolByPrice = new XyDataSeries<double, double>(); _seriesViewModels.Add(new ChartSeriesViewModel(dsVolByPrice, new FastColumnRenderableSeries() { Name = "PriceByVol", XAxisId = "verticalXAxis", YAxisId = "Y2" })); var dblVolume = new List<double>(); for (int i = 0; i < numBins; i++) dblVolume.Add(10 - i); dsVolByPrice.Append(bins.Select(x => x.Item1), dblVolume); _marketDataService.SubscribePriceUpdate(OnNewPrice); _xVisibleRange = new IndexRange(0, 1000); SelectedChartType = ChartType.FastOhlc; //this.DeleteCommand = new RelayCommand(DeleteCommandExecuted); }
public void MessagePrintBlockRange(IndexRange range) { LogMessage(Rsrc.PSSyncOutputEventsPrintBlockRange, range, range.Length); }
public bool TryReadFromFooter(IndexRange rangeToRead, byte[] buffer, int offset, out int readCount) { readCount = 0; var rangeToReadFromFooter = this.footerRange.Intersection(rangeToRead); if (rangeToReadFromFooter != null) { var footerData = GenerateFooter(); var copyStartIndex = rangeToReadFromFooter.StartIndex - footerRange.StartIndex; Buffer.BlockCopy(footerData, (int)copyStartIndex, buffer, offset, (int)rangeToReadFromFooter.Length); this.position += (int)rangeToReadFromFooter.Length; readCount = (int)rangeToReadFromFooter.Length; return true; } return false; }
public void DebugEmptyBlockDetected(IndexRange range) { LogDebug(Rsrc.PSSyncOutputEventsEmptyBlockDetected, range.ToString()); }
public IRange GetWindowedYRange(IndexRange xIndexRange) { throw new NotSupportedException(); }
private void InitHistory(string data) { List <Candle> list; Candles candles; using (var reader = new StringReader(data)) { list = new List <Candle>(); if (_candleSerializer == null) { _candleSerializer = new XmlSerializer(typeof(Candles)); } candles = (Candles) _candleSerializer.Deserialize(reader); reader.Close(); } //check if seccode matches if (candles.Seccode != Seccode) { return; } //check if timeframe matches if (candles.Candle.Count > 1 && candles.Period != _periodId.ToString()) { return; } list = candles.Candle; list = list.Where( item => item.TradeTime.Date >= DateTime.Today.AddDays(-_daysBack)).ToList(); if (list.Count == 0) { return; } _dispatcher.Invoke(() => { try { StockChartAnnotations.RemoveWhere( a => a is HorizontalLineAnnotation && ((HorizontalLineAnnotation)a).Name == "history"); } catch { } } ) ; OhlcDataSeries = new OhlcDataSeries <DateTime, double> { AcceptsUnsortedData = true }; OhlcDataSeries.Append(GetDateTime(list), GetValues(list)); XyDataSeries = new XyDataSeries <DateTime, int>(); XyDataSeries.Append(GetDateTime(list), GetVolumes(list)); //Add trendlines if (OhlcDataSeries.Count == 0) { return; } var dates = OhlcDataSeries.XValues.GroupBy(date => date.Date).Select(group => group.First().Date).ToList(); _lastCandle = list.Last(); if (_selectedTimeframe != "Day") { for (var i = 0; i < dates.Count; i++) { var date = dates[i]; if (i == dates.Count - 1) //for today (only open) { AddAnnotation("history", list.Where(item => Equals(item.TradeTime.Date, date)) .Select(item => item.Open) .First(), "Open"); } else //for other days { AddAnnotation("history", list.Where(item => Equals(item.TradeTime.Date, date)) .Select(item => item.Open) .First(), "Open"); AddAnnotation("history", list.Where(item => Equals(item.TradeTime.Date, date)) .Select(item => item.Close) .Last(), "Close"); AddAnnotation("history", list.Where(item => Equals(item.TradeTime.Date, date)).Select(item => item.High).Max(), "High"); AddAnnotation("history", list.Where(item => Equals(item.TradeTime.Date, date)).Select(item => item.Low).Min(), "Low"); } _dispatcher.Invoke(() => { //Vertical date annotations try { StockChartAnnotations.Add(new VerticalLineAnnotation { Name = "history", Stroke = new SolidColorBrush(Colors.DarkGray), X1 = OhlcDataSeries.FindIndex(OhlcDataSeries.XValues.First(x => x.Date == date)), IsEditable = false, Opacity = 0.5, AnnotationLabels = new ObservableCollection <AnnotationLabel> { new AnnotationLabel { LabelPlacement = LabelPlacement.Axis, Foreground = Brushes.White, Text = date.ToShortDateString() } } }); } catch { } }); } } try { SharedXRange = new IndexRange(0, OhlcDataSeries.Count + 3); YRange = new DoubleRange(OhlcDataSeries.LowValues.Min(), OhlcDataSeries.HighValues.Max()); } catch { } TXmlConnector.SendNewCandles -= ProcessCandles; }
public IPointSeries ToPointSeries(ResamplingMode resamplingMode, IndexRange pointRange, int viewportWidth, bool isCategoryAxis, bool? dataIsDisplayedAs2D, IRange visibleXRange, IPointResamplerFactory factory) { return pSeries; }
private static byte[] ReadBytes(Stream stream, IndexRange rangeToRead, BufferManager manager) { stream.Seek(rangeToRead.StartIndex, SeekOrigin.Begin); var bufferSize = (int)rangeToRead.Length; var buffer = manager.TakeBuffer(bufferSize); for (int bytesRead = stream.Read(buffer, 0, bufferSize); bytesRead < bufferSize; bytesRead += stream.Read(buffer, bytesRead, bufferSize - bytesRead)) { } return buffer; }
public void DebugEmptyBlockDetected(IndexRange range) { LogDebug("Empty block detected: {0}", range.ToString()); }
public void DebugEmptyBlockDetected(IndexRange range) { LogDebug(Resources.PSSyncOutputEventsEmptyBlockDetected, range.ToString()); }
public TextWord Create(string s, IndexRange ir) { return(this.Create(s.Substring(ir.Start, ir.Length))); }
public void IndexCount(int?start, int?end, int step, int expected) { var range = new IndexRange(start, end, step); range.IndexCount.Should().Be(expected); }