public async Task<AdminCommand> CreateAsync(TextReader reader, CancellationToken cancellationToken) { var json = await reader.ReadJsonAsync(cancellationToken); if (string.IsNullOrWhiteSpace(json)) { return null; } var adminCommandDto = json.FromJson<AdminCommandDto>(); switch (adminCommandDto.Type) { case AdminCommandType.StartGame: var startGameAdminCommandDto = json.FromJson<StartGameAdminCommandDto>(); return new StartGameAdminCommand(startGameAdminCommandDto.Size, _physics, _stateTracker, _playerRepository); case AdminCommandType.StopGame: return new StopGameAdminCommand(); case AdminCommandType.GetSnapshot: return new GetSnapshotAdminCommand(); case AdminCommandType.StartPushingState: return new StartPushingStateAdminCommand(); case AdminCommandType.UpdateSettings: var updateSettingsAdminCommandDto = json.FromJson<UpdateSettingsAdminCommandDto>(); var settings = Mapper.Map<WorldSettings>(updateSettingsAdminCommandDto.Settings); return new UpdateSettingsAdminCommand(settings); default: throw new ArgumentOutOfRangeException(); } }
public override TokenStream TokenStream(string fieldName, TextReader reader) { // Split the title based on IdSeparators, then run it through the innerAnalyzer string title = reader.ReadToEnd(); string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries)); return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized)); }
public XElement ParseFragment(TextReader reader, string fragmentContext) { Reset(); treeBuilder.SetFragmentContext(fragmentContext); Tokenize(reader); return treeBuilder.getDocumentFragment(); }
protected static void MigrateUsingXslt(TextReader xslStream, TextReader xmlStream, string destinationFilePath) { var transform = new XslCompiledTransform(); using (xslStream) { using (xmlStream) { using (var destinationStream = new StreamWriter(destinationFilePath)) { var xslReader = XmlReader.Create(xslStream); transform.Load(xslReader); xslReader.Close(); xslStream.Close(); var reader = XmlReader.Create(xmlStream); var settings = new XmlWriterSettings { Indent = true }; var writer = XmlWriter.Create(destinationStream, settings); transform.Transform(reader, writer); var tempfiles = transform.TemporaryFiles; if (tempfiles != null) // tempfiles will be null when debugging is not enabled { tempfiles.Delete(); } writer.Close(); reader.Close(); destinationStream.Close(); } xmlStream.Close(); } } }
public JobDefinition ParseJIL(TextReader instr) { JobDefinition jobdef = new JobDefinition(); char[] delim = {':'}; string [] keyval = new string[2]; string jil; Regex rx = new Regex("[A-Za-z-_]+:.*"); // Looks like a JIL key/value pair while ( (jil = instr.ReadLine()) != null ) { if (rx.IsMatch(jil)) { keyval = jil.Split(delim, 2); jobdef.SetField(keyval[0], keyval[1]); } else { Console.Error.WriteLine("Warning: Malformed JIL encountered and ignored: {0}", jil); } } return jobdef; }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public JsonMessageDeserializer([NotNull] IMessageTypeResolver typeResolver, TextReader textReader) : base(textReader) { if (typeResolver == null) { throw new ArgumentNullException("typeResolver"); } this._typeResolver = typeResolver; }
public RecentComputerList Read( TextReader reader ) { RecentComputerList computers = new RecentComputerList(); while ( true ) { string line = reader.ReadLine(); if ( line == null ) break; string[] pair = line.Split( '\t' ); // Avoid processing an empty line if ( pair[0] == "" ) continue; string computer = pair[0]; string alias = pair.Length > 1 ? pair[1] : ""; bool adminMode = false; if ( pair.Length > 2 ) bool.TryParse( pair[2], out adminMode ); computers.Add( new ComputerName( computer, alias, adminMode ) ); } return computers; }
public bool Parse(TextReader reader) { List<EarleyItem> previousState, currentState; currentState = new List<EarleyItem>(); currentState.Add(new EarleyItem(_start, 0, currentState)); int i; while((i = reader.Read()) >= 0) { char c = (char)i; previousState = currentState; currentState = Parse(previousState, c); } // finish it off for (var s = 0; s < currentState.Count; s++) { var item = currentState[s]; AddNewItems(currentState, Predict(item, currentState).ToList()); AddNewItems(currentState, Complete(item).ToList()); } return currentState.Any(x => x.IsComplete && x.Production.Equals(_start)); }
public ConfigNode(string name, TextReader reader) { _name = name; _data = new Hashtable(); _childConfigNodes = new ArrayList(); ReadFrom(reader); }
public static RuntimeGraph ReadRuntimeGraph(TextReader textReader) { using (var jsonReader = new JsonTextReader(textReader)) { return ReadRuntimeGraph(JToken.Load(jsonReader)); } }
/// <summary> /// Provide as much information about the input stream as we can, size /// and position /// </summary> /// <param name="reader">reader we are analysing</param> public StreamInfoProvider(TextReader reader) { if (reader is StreamReader) { var stream = ((StreamReader)reader).BaseStream; mLength = stream.Length; // Uses the buffer position mPositionCalculator = () => stream.Position; } else if (reader is InternalStreamReader) { var reader2 = ((InternalStreamReader)reader); var stream = reader2.BaseStream; mLength = stream.Length; // Real Position mPositionCalculator = () => reader2.Position; } else if (reader is InternalStringReader) { var stream = (InternalStringReader)reader; mLength = stream.Length; mPositionCalculator = () => stream.Position; } }
public MarkdownReader(TextReader reader) { _reader = reader; _spec = new Specification(); _modes.Push(new HeaderMode(_spec)); }
public AbsTcpCommunication(TcpClient sock) { _sock = sock; _socketStream = _sock.GetStream (); _in = new StreamReader (_socketStream); _out = new StreamWriter (_socketStream); }
/// <summary>Read in rating data from a TextReader</summary> /// <param name="reader">the <see cref="TextReader"/> to read from</param> /// <param name="user_mapping">mapping object for user IDs</param> /// <param name="item_mapping">mapping object for item IDs</param> /// <returns>the rating data</returns> public static ITimedRatings Read(TextReader reader, IEntityMapping user_mapping = null, IEntityMapping item_mapping = null) { if (user_mapping == null) user_mapping = new IdentityMapping(); if (item_mapping == null) item_mapping = new IdentityMapping(); var ratings = new TimedRatings(); string[] separators = { "::" }; string line; while ((line = reader.ReadLine()) != null) { string[] tokens = line.Split(separators, StringSplitOptions.None); if (tokens.Length < 4) throw new FormatException(string.Format("Expected at least 4 columns: {0}", line)); int user_id = user_mapping.ToInternalID(tokens[0]); int item_id = item_mapping.ToInternalID(tokens[1]); float rating = float.Parse(tokens[2], CultureInfo.InvariantCulture); long seconds = uint.Parse(tokens[3]); var time = new DateTime(seconds * 10000000L).AddYears(1969); var offset = TimeZone.CurrentTimeZone.GetUtcOffset(time); time -= offset; ratings.Add(user_id, item_id, rating, time); } return ratings; }
/// <summary> /// Constructor /// </summary> /// <param name="data">detailed results of the comparison</param> /// <param name="identical">summary result if the /// comparison, value is 'true' if there were no /// differences found.</param> internal XmlDiffViewResults( MemoryStream data, bool identical) { this.reader = this.PopulateReader(ref data); this.identicalData = identical; }
/// <exception cref="T:System.NotImplementedException"></exception> public MessageParser(TextReader reader) { string line; while ((line = reader.ReadLine()) != nameof(FCP2Protocol.EndMessage)) { int pos; if (line == "End") throw new NotImplementedException("NoEnd"); if (line == "Data") { DataAvailable = true; break; } if ((pos = line.IndexOf('=')) == -1) { throw new NotImplementedException("EmptyValue:" + line); } var key = line.Substring(0, pos); var val = line.Substring(pos + 1); _parameters.Add(key, val); #if DEBUG _debugCount.Add(line.Substring(0, pos), 0); #endif } }
public static Knapsack GetKnapsack(TextReader reader) { Contract.Requires<ArgumentNullException>(reader != null, "reader"); var firstRow = reader.ReadLine(); var firtsRowParts = firstRow.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); int capacity = int.Parse(firtsRowParts[0]); int numberOfItems = int.Parse(firtsRowParts[1]); var items = new List<KnapsackItem>(numberOfItems); while (true) { string row = reader.ReadLine(); if (row == null) { break; } var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var parameters = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray(); items.Add(new KnapsackItem(parameters[0], parameters[1])); } return new Knapsack(items, capacity); }
protected object Deserialize(TextReader reader, Type aType) { XmlSerializer xmlSerializer = new XmlSerializer(aType); object local = xmlSerializer.Deserialize(reader); reader.Close(); return local; }
public OrchardConsoleLogger( TextReader input, TextWriter output) { _input = input; _output = output; }
public MainClass(TextReader @in, TextWriter @out) { _out = @out; _in = @in; this.movieRepository = new MovieRepository(); this.rentalFactory = new RentalFactory(movieRepository); }
public virtual void SetUp() { stdin = Console.In; stdout = Console.Out; displayOutput = new StringWriter(); Console.SetOut(displayOutput); }
/// <summary> /// Parse and filter the supplied modifications. The position of each modification in the list is used as the ChangeNumber. /// </summary> /// <param name="history"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public Modification[] Parse(TextReader history, DateTime from, DateTime to) { StringReader sr = new StringReader(string.Format(@"<ArrayOfModification xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">{0}</ArrayOfModification>" , history.ReadToEnd())); XmlSerializer serializer = new XmlSerializer(typeof(Modification[])); Modification[] mods; try { mods = (Modification[])serializer.Deserialize(sr); } catch (Exception ex) { throw new CruiseControlException("History Parsing Failed", ex); } ArrayList results = new ArrayList(); int change = 0; foreach (Modification mod in mods) { change++; mod.ChangeNumber = change; if ((mod.ModifiedTime >= from) & (mod.ModifiedTime <= to)) { results.Add(mod); } } return (Modification[])results.ToArray(typeof(Modification)); }
public static void Template(TextReader reader, object data, TextWriter writer, RenderContextBehaviour renderContextBehaviour = null) { var renderBehaviour = renderContextBehaviour ?? RenderContextBehaviour.GetDefaultRenderContextBehaviour(); Template(reader, data, writer, null, renderBehaviour); }
public DatabaseVersionSetup Load(TextReader reader) { var versionSetup = new DatabaseVersionSetup(); var shemas = new XmlSchemaSet(); Assembly assem = typeof(DatabaseVersionSetup).Assembly; using (Stream stream = assem.GetManifestResourceStream("DatabaseVersionControl.Core.Xsd.DVCSchema.xsd")) { if (stream != null){ shemas.Add("", XmlReader.Create(stream)); } else{ throw new Exception("Could not load embedded resource Xsd.DVCSchema.xsd"); } } XDocument element = XDocument.Load(reader); element.Validate(shemas, (sender, e) => { if (_exception != null) _exception(e); }, true); var profiles = element.XPathSelectElements("//profiles/profile"); versionSetup.DefaultProfile = element.Root.Attribute("defaultProfile").Value; LoadProfiles(versionSetup, profiles); var databases = element.XPathSelectElements("//repositories/repository"); LoadRepositories(versionSetup, databases); return versionSetup; }
public static XmlDocument IsWellFormed(TextReader reader) { Assert.IsNotNull(reader); XmlDocument doc = new XmlDocument(); doc.Load(reader); return doc; }
public static YamlNode LoadFromTextReader(TextReader reader) { var yaml = new YamlStream(); yaml.Load(reader); return yaml.Documents.First().RootNode; }
public List<string> ParseText(TextReader pReader) { result.Clear(); int count = 0; do { count = pReader.ReadBlock(buffer, 0, BUFFER_SIZE); for (int i = 0; i < count; ++i) { char c = buffer[i]; if (char.IsWhiteSpace(c)) { ParseWhitespace(); } else if (Contains(punctuation, c)) { ParsePunctuation(c); } else if (char.IsLetterOrDigit(c)) { ParseLetter(c); }else{ ParseLetter(c); } } } while(count == BUFFER_SIZE); return result; }
public static KeyValueConfig ReadVerBarConfig(TextReader reader) { var result = new KeyValueConfig(); string line; int lineNum = 0; while ((line = reader.ReadLine()) != null) { string[] tokens = line.Split(new char[] {'|'}); if (lineNum == 0) // keys { foreach (var token in tokens) { var tokens2 = token.Split(new char[] {'!'}); result.Data[tokens2[0]] = new List<string>(); } } else // values { //if (Data.Count != tokens.Length) // throw new Exception("VerBarConfig: Data.Count != tokens.Length"); if (result.Data.Count != tokens.Length) continue; for (int i = 0; i < result.Data.Count; i++) result.Data.ElementAt(i).Value.Add(tokens[i]); } lineNum++; } return result; }
public static void Answer(TextReader reader) { int n = Convert.ToInt32(reader.ReadLine()); int[] coordinates = reader.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToArray(); List<Line> lines = new List<Line>(); for (int index = 0; index < coordinates.Length - 1; index++) { int a = coordinates[index]; int b = coordinates[index + 1]; lines.Add(new Line {From = Math.Min(a,b), To = Math.Max(a,b)}); } for (int i = 0; i < lines.Count; i++) { for(int j = 0; j< lines.Count; j++) { if (intersect(lines[i], lines[j])) { Console.WriteLine("yes"); return; } } } Console.WriteLine("no"); }
public BinHexDecoder(TextReader input) { this.input = input; FindBinhexHeader(); EatNewline(); EatColon(); }
public FragmentXmlTextReader(System.IO.TextReader reader) : base(reader) { }
/// <summary> /// Deserializes the content of <paramref name="textReader"/> the data structure <typeparamref name="T"/>. /// </summary> /// <param name="textReader">The TextReader</param> /// <returns>An instance of <typeparamref name="T"/></returns> public static T Deserialize(IO.TextReader textReader) => (T)XmlSerializer.Deserialize(textReader);
/// <summary> /// Return a query that will return docs like the passed Reader. /// </summary> /// <returns> a query that will return docs like the passed Reader. </returns> public Query Like(Reader r, string fieldName) { return(CreateQuery(RetrieveTerms(r, fieldName))); }
private void ReadCSV_StagingDirection(System.IO.TextReader reader) { string line; float totalBeatCount = 0; float repeatPosition = 0; List <StagingDirection> sequence = new List <StagingDirection>(); while ((line = reader.ReadLine()) != null) { string[] lineCells = line.Split(','); switch (lineCells[0]) { case "regionParameters": totalBeatCount = float.Parse(lineCells[2]); repeatPosition = float.Parse(lineCells[3]); break; case "AllBandMemberDefaultAnimation": { foreach (GameObject member in GameObject.FindGameObjectsWithTag("BandMember")) { StagingDirection_SetBandMemberDefaultAnimation defaultAnimationSet = new StagingDirection_SetBandMemberDefaultAnimation(); defaultAnimationSet.triggerBeatTiming = float.Parse(lineCells[1]); defaultAnimationSet.m_memberName = member.name; defaultAnimationSet.m_animationFromIndex = int.Parse(lineCells[2]); defaultAnimationSet.m_animationToIndex = int.Parse(lineCells[3]); sequence.Add(defaultAnimationSet); } } break; case "SetAllBandMemberAction": { foreach (GameObject member in GameObject.FindGameObjectsWithTag("BandMember")) { StagingDirection_SetBandMemberAction actionSet = new StagingDirection_SetBandMemberAction(); actionSet.triggerBeatTiming = float.Parse(lineCells[1]); actionSet.m_memberName = member.name; actionSet.m_actionName = lineCells[2]; sequence.Add(actionSet); } } break; case "stagingDirectionSequenceRegion-End": { for (float repeatOffest = 0; repeatOffest < totalBeatCount;) { foreach (StagingDirection stagingDirection in sequence) { if (stagingDirection.triggerBeatTiming + repeatOffest > totalBeatCount) { break; } StagingDirection cloned = stagingDirection.GetClone() as StagingDirection; cloned.triggerBeatTiming += m_stagingDirectoionRegionOffset + repeatOffest; songInfo.stagingDirectionSequence.Add(cloned); } repeatOffest += repeatPosition; } m_stagingDirectoionRegionOffset += totalBeatCount; } return; // ↑已经有 return 所以这个 break 不会被执行 //break; default: { StagingDirection stagingDirection = StagingDirectionFactory.CreateStagingDirectionFromEnum( (StagingDirectionEnum)System.Enum.Parse(typeof(StagingDirectionEnum), lineCells[0]) ); if (stagingDirection != null) { stagingDirection.ReadCustomParameterFromString(lineCells); stagingDirection.triggerBeatTiming = float.Parse(lineCells[1]); sequence.Add(stagingDirection); } } break; } ; } Debug.LogError("StagingDirectionSequenceRegion.ReadCSV: ParseError - missing stagingDirectionSequenceRegion-End"); }
private int ReadCSV_OnBeatAction(System.IO.TextReader reader, int line_number) { string line; SequenceRegion region = new SequenceRegion(); List <OnBeatActionInfo> sequence = new List <OnBeatActionInfo>(); while ((line = reader.ReadLine()) != null) { line_number++; string[] lineCells = line.Split(','); switch (lineCells[0]) { case "regionParameters": region.name = lineCells[1]; region.totalBeatCount = float.Parse(lineCells[2]); region.repeatPosition = float.Parse(lineCells[3]); break; case "scoringUnitSequenceRegion-End": { region.triggerBeatTiming = m_onBeatActionInfoRegionOffset; songInfo.onBeatActionRegionSequence.Add(region); for (float repeatOffest = 0; repeatOffest < region.totalBeatCount; repeatOffest += region.repeatPosition) { foreach (OnBeatActionInfo onBeatActionInfo in sequence) { if (onBeatActionInfo.triggerBeatTiming + repeatOffest > region.totalBeatCount) { break; } OnBeatActionInfo cloned = onBeatActionInfo.GetClone() as OnBeatActionInfo; cloned.triggerBeatTiming += m_onBeatActionInfoRegionOffset + repeatOffest; songInfo.onBeatActionSequence.Add(cloned); } } m_onBeatActionInfoRegionOffset += region.totalBeatCount; return(line_number); } // ↑已经有 return 所以这个 break 不会被执行 //break; case "SingleShot": { OnBeatActionInfo onBeatActionInfo = new OnBeatActionInfo(); if (lineCells[2] != "") { onBeatActionInfo.playerActionType = (PlayerActionEnum)System.Enum.Parse(typeof(PlayerActionEnum), lineCells[2]); } else { onBeatActionInfo.playerActionType = PlayerActionEnum.HeadBanging; } onBeatActionInfo.triggerBeatTiming = float.Parse(lineCells[1]); // 记录下定义的行号用于调试 onBeatActionInfo.line_number = line_number; sequence.Add(onBeatActionInfo); } break; } ; } Debug.LogError("ScoringUnitSequenceRegion.ReadCSV: ParseError - missing ScoringUnitSequenceRegion-End"); return(line_number); }
public override ParsedDocument Parse(bool storeAst, string fileName, System.IO.TextReader content, Projects.Project project = null) { currentDocument = openDocuments.FirstOrDefault(d => d != null && d.FileName == fileName); // We need document and project to be loaded to correctly initialize Razor Host. this.project = project as DotNetProject; if (this.project == null || (currentDocument == null && !TryAddDocument(fileName))) { return(new RazorCSharpParsedDocument(fileName, new RazorCSharpPageInfo())); } this.aspProject = project as AspMvcProject; EnsureParserInitializedFor(fileName); var errors = new List <Error> (); using (var source = new SeekableTextReader(content)) { var textChange = CreateTextChange(source); var parseResult = editorParser.CheckForStructureChanges(textChange); if (parseResult == PartialParseResult.Rejected) { parseComplete.WaitOne(); if (!capturedArgs.GeneratorResults.Success) { GetRazorErrors(errors); } } } CreateHtmlDocument(); GetHtmlErrors(errors); CreateCSharpParsedDocument(); ClearLastChange(); RazorHostKind kind = RazorHostKind.WebPage; if (editorParser.Host is WebCodeRazorHost) { kind = RazorHostKind.WebCode; } else if (editorParser.Host is MonoDevelop.RazorGenerator.RazorHost) { kind = RazorHostKind.Template; } var pageInfo = new RazorCSharpPageInfo() { HtmlRoot = htmlParsedDocument, GeneratorResults = capturedArgs.GeneratorResults, Spans = editorParser.CurrentParseTree.Flatten(), CSharpParsedFile = parsedCodeFile, CSharpCode = csharpCode, Errors = errors, FoldingRegions = GetFoldingRegions(), Comments = comments, Compilation = CreateCompilation(), HostKind = kind, }; return(new RazorCSharpParsedDocument(fileName, pageInfo)); }
public ConsoleInput(System.IO.TextReader stream, char separator = ' ') { this._separator = separator; this._stream = stream; inputStream = new Queue(); }
public void GetObjectProperties() { // Путь к базовому файлу // Путь к файлу списка протофайлов // Пусть к файлам прототипа // Путь к файлу списка графики // Путь к файлам графики // Временная строка №1 string TempString = " "; // Временная строка №2 string TempString1 = " "; string baseFile = GamePath + @"\MASTER.DAT\text\english\game\pro_item.msg"; string listFile = GamePath + @"\MASTER.DAT\proto\items\items.lst"; string pathToProto = GamePath + @"\MASTER.DAT\proto\items\"; string pathToArt = string.Format(@"{0}\MASTER.DAT\art\items\", GamePath); string artListFile = GamePath + @"\MASTER.DAT\art\items\items.lst"; // Получение файла прототипа объекта System.IO.TextReader fListFile = System.IO.File.OpenText(listFile); for (int i = 1; i <= ObjectId; i++) { TempString = fListFile.ReadLine(); } fListFile.Close(); // Путь к файлу прототипа объекта ObjectProto = pathToProto + TempString; //Загоняем весь прото-файл в байтовый массив FileStream fProtoFile = new FileStream(ObjectProto, FileMode.Open); _buffer = new byte[Convert.ToInt32(fProtoFile.Length)]; fProtoFile.Read(_buffer, 0, Convert.ToInt16(fProtoFile.Length)); fProtoFile.Close(); System.IO.TextReader fArtListFile = System.IO.File.OpenText(artListFile); for (int i = 0; i <= (_buffer[10] * 256 + _buffer[11]); i++) { TempString = fArtListFile.ReadLine(); } fListFile.Close(); // Путь к файлу с графикой объекта ObjectFrame = TempString.Replace(".FRM", ""); // Открытие базового файла объектов System.IO.TextReader fBaseFile = System.IO.File.OpenText(baseFile); if (!(fBaseFile.Peek() == -1)) { do { TempString = fBaseFile.ReadLine(); }while (!(TempString.Substring(1, ObjectId.ToString().Length + 2) == (ObjectId * 100).ToString()) && !((fBaseFile.Peek() == -1))); if (!(TempString.Substring(1, ObjectId.ToString().Length) == ObjectId.ToString())) { TempString = " "; } } else { TempString = " "; } if ((TempString.Substring(1, ObjectId.ToString().Length) == ObjectId.ToString()) && !(TempString == " ")) { char[] aStrSplit = { '{', '}' }; // Получение наименования объекта ObjectName = TempString.Split(aStrSplit)[5]; if (!(fBaseFile.Peek() == -1)) { TempString1 = fBaseFile.ReadLine(); if (TempString1.Substring(1, TempString.Split(aStrSplit)[1].Length) == (ObjectId.ToString() + "01")) { // Получение описания объекта ObjectDesc = TempString1.Split(aStrSplit)[5]; } else { ObjectDesc = " "; } fBaseFile.Close(); } else { ObjectDesc = " "; } } else { ObjectDesc = " "; ObjectName = " "; } FrameIdType = _buffer[8]; FrameIdOffset = _buffer[9]; FrameId = _buffer[10] * 256 + _buffer[11]; LightDistance = (_buffer[12] << 24) + (_buffer[13] << 16) + (_buffer[14] << 8) + _buffer[15]; LightIntensity = (_buffer[16] << 24) + (_buffer[17] << 16) + (_buffer[18] << 8) + _buffer[19]; AttackMode1 = (_buffer[27] & 15); AttackMode2 = (_buffer[27] & 240) >> 4; int offset = 0x1C; ScriptId = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x20; ItemSubtype = (ItemSubtype)(_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x24; MaterialType = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x28; Volume = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x2C; Weight = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x30; BasePrice = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; offset = 0x34; InvenId = _buffer[offset]; offset = 0x36; InvenFrame = (_buffer[offset] << 8) + _buffer[offset + 1]; offset = 0x38; SoundId = (_buffer[offset] << 24) + (_buffer[offset + 1] << 16) + (_buffer[offset + 2] << 8) + _buffer[offset + 3]; }
/// <summary> /// Convenience method which calls <code>fill(buffer, reader, buffer.buffer.length)</code>. </summary> public virtual bool Fill(CharacterBuffer buffer, Reader reader) { return(Fill(buffer, reader, buffer.buffer.Length)); }
public NamespaceIgnorantXmlTextReader(System.IO.TextReader reader) : base(reader) { }
/** * Creates a new scanner * There is also a System.IO.Stream version of this constructor. * * @param in the System.IO.TextReader to read input from. */ public Lexer(TextReader @in) { this.zzReader = @in; }
/// <summary> /// Creates a new scanner /// </summary> /// <param name="in"> the java.io.Reader to read input from. </param> internal ClassicTokenizerImpl(Reader @in) { this.zzReader = @in; }
private void btnSelectKMLFile_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { /* Get kml filename */ string kml_file = openFileDialog1.FileName; if (kml_file.Contains(".kml")) { Form1.Globals.kml_filename = kml_file; rtbKMLRead.AppendText("KML File : " + kml_file + "\n"); rtbKMLRead.AppendText("\n"); /* Open KML File */ System.IO.TextReader stream = System.IO.File.OpenText(kml_file); SharpKml.Engine.KmlFile file = KmlFile.Load(stream); Kml _kml = file.Root as Kml; SharpKml.Dom.Placemark[] tempPlaceMarks = new SharpKml.Dom.Placemark[1000]; SharpKml.Dom.Placemark tmp_placemark = new SharpKml.Dom.Placemark(); CoordinateCollection coordinates = new CoordinateCollection(); Form1.Globals.kml_point_count = 0; //rtbKMLRead.AppendText("Waypoint Count : " + Convert.ToString(Globals.waypoint_count) + "\n"); int numOfPlaceMarks = 0; if (_kml != null) { foreach (var placemark in _kml.Flatten().OfType <SharpKml.Dom.Placemark>()) { string placename = placemark.Name; rtbKMLRead.AppendText("Placemark Name : " + placename + "\n"); tmp_placemark.Name = placename; numOfPlaceMarks++; } rtbKMLRead.AppendText("Number of Placemarks : " + Convert.ToString(numOfPlaceMarks) + "\n"); int num_linestring = 0; SharpKml.Base.Vector vector; double lat; double lon; double alt; foreach (var linestring in _kml.Flatten().OfType <LineString>()) { coordinates = linestring.Coordinates; int num = coordinates.Count; rtbKMLRead.AppendText("Num Coordinates : " + Convert.ToString(num) + "\n"); for (int i = 0; i < num; i++) { vector = coordinates.ElementAt(i); lat = vector.Latitude; lon = vector.Longitude; alt = (double)vector.Altitude; rtbKMLRead.AppendText("Lat/Lon : " + Convert.ToString(lat)); rtbKMLRead.AppendText(", " + Convert.ToString(lon) + "Altitude : " + Convert.ToString(alt) + "\n"); _kml_points[_kml_point_count, 0] = lat; _kml_points[_kml_point_count, 1] = lon; _kml_points[_kml_point_count, 2] = alt; _kml_point_count++; //dgvWaypoints.Rows.Add(Globals.waypoint_count, Convert.ToString(lat), Convert.ToString(lon), Convert.ToString(30)); } num_linestring++; } rtbKMLRead.AppendText("Number of Linestrings : " + Convert.ToString(num_linestring) + "\n"); BuildKMLPath(); } } else { MessageBox.Show("Wrong file type!", "GPS Grid:", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } }
/// <summary> /// Fills the <seealso cref="CharacterBuffer"/> with characters read from the given /// reader <seealso cref="Reader"/>. This method tries to read <code>numChars</code> /// characters into the <seealso cref="CharacterBuffer"/>, each call to fill will start /// filling the buffer from offset <code>0</code> up to <code>numChars</code>. /// In case code points can span across 2 java characters, this method may /// only fill <code>numChars - 1</code> characters in order not to split in /// the middle of a surrogate pair, even if there are remaining characters in /// the <seealso cref="Reader"/>. /// <para> /// Depending on the <seealso cref="LuceneVersion"/> passed to /// <seealso cref="CharacterUtils#getInstance(Version)"/> this method implements /// supplementary character awareness when filling the given buffer. For all /// <seealso cref="LuceneVersion"/> > 3.0 <seealso cref="#fill(CharacterBuffer, Reader, int)"/> guarantees /// that the given <seealso cref="CharacterBuffer"/> will never contain a high surrogate /// character as the last element in the buffer unless it is the last available /// character in the reader. In other words, high and low surrogate pairs will /// always be preserved across buffer boarders. /// </para> /// <para> /// A return value of <code>false</code> means that this method call exhausted /// the reader, but there may be some bytes which have been read, which can be /// verified by checking whether <code>buffer.getLength() > 0</code>. /// </para> /// </summary> /// <param name="buffer"> /// the buffer to fill. </param> /// <param name="reader"> /// the reader to read characters from. </param> /// <param name="numChars"> /// the number of chars to read </param> /// <returns> <code>false</code> if and only if reader.read returned -1 while trying to fill the buffer </returns> /// <exception cref="IOException"> /// if the reader throws an <seealso cref="IOException"/>. </exception> public abstract bool Fill(CharacterBuffer buffer, Reader reader, int numChars);
public unsafe ikaSprite(System.IO.TextReader sourceStream) { DataNode document = DataNode.ReadDocument(sourceStream); DataNode rootNode = document.GetChild("ika-sprite"); string version = rootNode.GetChild("version").GetString(); DataNode infoNode = rootNode.GetChild("information"); title = infoNode.GetChild("title").GetString(); DataNode metaNode = infoNode.GetChild("meta"); foreach (DataNode n in metaNode.Children) { DataNode node = (DataNode)n.Children[0]; Metadata.Add(node.Name, node.GetString()); } DataNode framesNode = rootNode.GetChild("frames"); int frameCount = Convert.ToInt32(framesNode.GetChild("count").GetString()); DataNode dimNode = framesNode.GetChild("dimensions"); Size size = new Size( Convert.ToInt32(dimNode.GetChild("width").GetString()), Convert.ToInt32(dimNode.GetChild("height").GetString()) ); DataNode hsNode = framesNode.GetChild("hotspot"); HotSpot = new Rectangle( Convert.ToInt32(hsNode.GetChild("x").GetString()), Convert.ToInt32(hsNode.GetChild("y").GetString()), Convert.ToInt32(hsNode.GetChild("width").GetString()), Convert.ToInt32(hsNode.GetChild("height").GetString()) ); DataNode animNode = rootNode.GetChild("scripts"); foreach (DataNode child in animNode.GetChildren("script")) { string name = child.GetChild("label").GetString(); string script = child.GetString(); Scripts.Add(name, script); } // Read pixel data DataNode dataNode = framesNode.GetChild("data"); string dataFormat = dataNode.GetChild("format").GetString(); if (dataFormat != "zlib") { throw new Exception(string.Format("Invalid data format \"{0}\". Only \"zlib\" compression is supported.", dataFormat)); } string data64 = dataNode.GetString(); byte[] cdata = Convert.FromBase64String(data64); // shorthand int width = size.Width; int height = size.Height; byte[] pixels = new byte[width * height * frameCount * 4]; using (MemoryStream compressed = new MemoryStream(cdata)) using (InflaterInputStream iis = new InflaterInputStream(compressed)) { /** * This is silly. * InflaterInputStream doesn't actually read until it's got what you asked for. * It seems to just stop when it feels like a good idea, then returns the number * of bytes read. * * What the hell. */ int byteCount = 0; while (byteCount < pixels.Length) { byteCount += iis.Read(pixels, byteCount, pixels.Length - byteCount); } } frames = new ImageArray(width, height); fixed(byte *p = &pixels[0]) { byte *ptr = p; for (int i = 0; i < frameCount; i++) { Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bd = bmp.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb ); byte *dest = (byte *)bd.Scan0; byte *src = ptr; for (int k = 0; k < width * height; k++) { // swap red and blue dest[0] = src[2]; dest[1] = src[1]; dest[2] = src[0]; dest[3] = src[3]; dest += 4; src += 4; } bmp.UnlockBits(bd); frames.Add(bmp); ptr += width * height * 4; } } }
/// <summary> Return a query that will return docs like the passed Reader. /// /// </summary> /// <returns> a query that will return docs like the passed Reader. /// </returns> public Query Like(System.IO.TextReader r) { return(CreateQuery(RetrieveTerms(r))); }
/// <summary> /// Reads a TextReader into the answer collection without first clearing existing answers. /// </summary> /// <param name="input">A TextReader containing a HotDocs answer file.</param> public void OverlayXml(System.IO.TextReader input) { // create an XmlTextReader XmlReaderSettings settings = new XmlReaderSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; settings.IgnoreWhitespace = false; settings.IgnoreProcessingInstructions = true; settings.IgnoreComments = true; settings.ValidationType = ValidationType.None; //settings.ProhibitDtd = false; // obsolete in .NET 4.0, replaced with: settings.DtdProcessing = DtdProcessing.Ignore; // .NET 4.0 only try { using (XmlReader reader = XmlReader.Create(input, settings)) { // then read the XML and create the answers... reader.MoveToContent(); if (reader.Name == "AnswerSet") { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "title") { _title = reader.Value; } else if (reader.Name == "version") { _version = XmlConvert.ToSingle(reader.Value); } } } } else { throw new XmlException("Expected an AnswerSet element."); } int[] repeatStack = RepeatIndices.Empty; // read answers: while (reader.Read()) { reader.MoveToContent(); if (reader.Name == "Answer" && reader.HasAttributes) { string answerName = null; bool? answerSave = null; bool? userExtendible = null; while (reader.MoveToNextAttribute()) { if (reader.Name == "name") { answerName = TextValue.XMLUnescape(reader.Value).Trim(); } else if (reader.Name == "save") { switch (reader.Value) { case "true": answerSave = true; break; case "false": answerSave = false; break; // else no change } } else if (reader.Name == "userExtendible") { userExtendible = XmlConvert.ToBoolean(reader.Value); } } if (String.IsNullOrEmpty(answerName)) { throw new XmlException("Answer name is missing."); } Answer ans = null; reader.Read(); reader.MoveToContent(); ReadValue(reader, ref ans, answerName, repeatStack); if (answerSave.HasValue && !answerSave.Value) { ans.Save = false; } if (userExtendible.HasValue) { ans.UserExtendible = userExtendible.Value; } } } } } catch { // Just eat any exceptions that are thrown for now. } }
public static request Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <request>(xmlFile)); }
/// <summary> Create a tokenized and indexed field that is not stored. Term vectors will /// not be stored. The Reader is read only when the Document is added to the index, /// i.e. you may not close the Reader until <see cref="IndexWriter.AddDocument(Document)" /> /// has been called. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="reader">The reader with the content /// </param> /// <throws> NullPointerException if name or reader is <c>null</c> </throws> public Field(System.String name, System.IO.TextReader reader) : this(name, reader, TermVector.NO) { }
/// <summary> /// Reads text from the input stream, and splits it into tokens, using whitespace and a list /// of separator characters as token delimiters. /// </summary> /// <remarks>This tokenizer does not return line number and column information.</remarks> /// <param name="inputReader">Input text reader containing textual data.</param> /// <returns>List of non-whitespace, or separator tokens.</returns> public IEnumerable <IToken> EnumerateTokens(System.IO.TextReader inputReader) { if (inputReader == null) { yield break; } // Initialize parser state. ParserState currentState = ParserState.Init; int tokenStart = -1; int position = 0; StringBuilder tokenBuilder = new StringBuilder(1024); // Read each character one by one. for (int c = inputReader.Read(); c >= 0; c = inputReader.Read()) { char currentChar = (char)c; switch (currentState) { case ParserState.Init: { if (char.IsWhiteSpace(currentChar) || currentChar == '\n' || currentChar == '\r') { currentState = ParserState.WhiteSpace; } else { currentState = ParserState.NonWhiteSpace; if (IsSeparator(currentChar)) { if (EmitSeparatorsAsTokens) { yield return(new Token(new string( currentChar, 1 ), TOKEN_TYPE_SEPARATOR, position, 1)); } tokenStart = position + 1; } else { tokenBuilder.Append(currentChar); tokenStart = position; } } } break; case ParserState.WhiteSpace: { if (!(char.IsWhiteSpace(currentChar) || currentChar == '\n' || currentChar == '\r')) { currentState = ParserState.NonWhiteSpace; tokenBuilder.Clear(); tokenBuilder.EnsureCapacity(1024); if (IsSeparator(currentChar)) { if (tokenBuilder.Length > 0) { yield return(new Token(tokenBuilder.ToString(), TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart)); } if (EmitSeparatorsAsTokens) { yield return(new Token(new String(currentChar, 1), TOKEN_TYPE_SEPARATOR, position, 1)); } tokenBuilder.Clear(); tokenBuilder.EnsureCapacity(1024); tokenStart = position + 1; } else { tokenStart = position; tokenBuilder.Append(currentChar); } } } break; case ParserState.NonWhiteSpace: { if ((char.IsWhiteSpace(currentChar) || currentChar == '\n' || currentChar == '\r')) { if (tokenBuilder.Length > 0) { yield return(new Token(tokenBuilder.ToString(), TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart)); } currentState = ParserState.WhiteSpace; tokenBuilder.Clear(); tokenBuilder.EnsureCapacity(1024); tokenStart = -1; } else { if (IsSeparator(currentChar)) { if (tokenBuilder.Length > 0) { yield return(new Token(tokenBuilder.ToString(), TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart)); } if (EmitSeparatorsAsTokens) { yield return(new Token(new String(currentChar, 1), TOKEN_TYPE_SEPARATOR, position, 1)); } tokenBuilder.Clear(); tokenBuilder.EnsureCapacity(1024); tokenStart = position + 1; } else { tokenBuilder.Append(currentChar); } } } break; } ++position; } if (tokenStart >= 0 && tokenBuilder.Length > 0) { yield return(new Token(tokenBuilder.ToString(), TOKEN_TYPE_NONWHITESPACE, tokenStart, position - tokenStart)); } }
public NamespaceTolerantXmlTextReader(FrameworkSystemIO.TextReader reader) : base(reader) { }
/// <summary> /// Reads a TextReader into the answer collection. /// </summary> /// <param name="input">A TextReader containing a HotDocs answer file, clearing existing answers.</param> public void ReadXml(System.IO.TextReader input) { Clear(); OverlayXml(input); }
internal System.IO.TextReader input; // source of chars /// <summary> /// Constructs from a <see cref="System.IO.TextReader"/>. /// </summary> public FastCharStream(System.IO.TextReader r) { input = r; }
public static xdoc Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <xdoc>(xmlFile)); }
internal static VerifyRequired Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <VerifyRequired>(xmlFile)); }
public override TokenStreamComponents CreateComponents(string fieldName, Reader reader) { Tokenizer tokenizer = new EdgeNGramTokenizer(TEST_VERSION_CURRENT, reader, min, max); return(new TokenStreamComponents(tokenizer, tokenizer)); }
internal static Transformation Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <Transformation>(xmlFile)); }
protected internal override TokenStreamComponents CreateComponents(string fieldName, Reader reader) { #pragma warning disable 612, 618 Tokenizer tokenizer = new Lucene43EdgeNGramTokenizer(Version.LUCENE_43, reader, Lucene43EdgeNGramTokenizer.Side.BACK, 2, 4); #pragma warning restore 612, 618 return(new TokenStreamComponents(tokenizer, tokenizer)); }
internal static Validation Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <Validation>(xmlFile)); }
internal static Deanonymize Load(System.IO.TextReader xmlFile) { return(XTypedServices.Load <Deanonymize>(xmlFile)); }