///<summary> /// /// Creates lexer, that corresponds to source file text (NOT generated!) /// ///</summary> /// public ILexerFactory CreateLexer(ProjectFileType languageType, IBuffer buffer) { if (languageType != L4N) return null; return new XmlLexerFactory(L4NLanguageService.L4N); }
public Sprite( ITexture2D texture, IEffect effect ) { if ( effect == null ) { if ( baseSpriteEffect == null ) baseSpriteEffect = new SpriteEffect (); effect = baseSpriteEffect; } if ( projectionMatrix == null ) projectionMatrix = new OrthographicOffCenterProjection ( 0, 800, 600, 0, 0.001f, 1000.0f ); Effect = effect; if ( vertexDeclaration == null ) { vertexDeclaration = Core.GraphicsDevice.CreateVertexDeclaration ( Utilities.CreateVertexElementArray<SpriteVertex> () ); } indexReference++; vertexBuffer = Core.GraphicsDevice.CreateBuffer ( BufferType.VertexBuffer, typeof ( SpriteVertex ), 4 ); textureArgument = new SamplerState ( texture, Graphics.TextureFilter.Nearest, TextureAddressing.Clamp, 0 ); Reset ( texture ); innerWorld = new World2(); }
public InlineImageBody( IBuffer value ) : base(null) { this.value = value; }
public PdfStream( IBuffer body ) : this(new PdfDictionary(), body) { }
public ILexerFactory GetMixedLexerFactory(IBuffer buffer, IPsiSourceFile sourceFile, PsiManager manager) { var LanguageService = RaconteurLanguage.Instance.LanguageService(); return LanguageService == null ? null : LanguageService.GetPrimaryLexerFactory(); }
public ILexerFactory CreateLexer(ProjectFileType languageType, IBuffer buffer) { //Logger.LogMessage("MappingFileProjectFileLanguageService.CreateLexer for language type {0}", languageType.Name); if (languageType == MAPPING_FILE) { return new XmlLexerFactory(MappingFileLanguageService.MAPPING_FILE); } return null; }
public void Init(IBuffer buffer) { m_rawData = buffer; m_buffer = m_rawData.Buffer; bufferLength = m_buffer.Length; m_ioIndex = 0; }
public PhysicalPartition(PartitionDescriptor descriptor, IBuffer buffer, uint sectorSize) { _partitionNumber = descriptor.PartitionNumber; _parentBuffer = buffer; _contentBuffer = new SubBuffer(_parentBuffer, descriptor.PartitionStartingLocation * (long)sectorSize, descriptor.PartitionLength * (long)sectorSize); _descriptor = descriptor; }
public PsiLexerGenerated(IBuffer buffer, int startOffset, int endOffset) : this(buffer) { yy_buffer_index = startOffset; yy_buffer_start = startOffset; yy_buffer_end = startOffset; yy_eof_pos = endOffset + 1; }
public void SendAsync(IBuffer buffer) { if (IsConnected && buffer.Size > 0) { Socket.SendAsync(buffer); } }
/// <summary> /// Sets a value of all cells in a buffer /// </summary> /// <param name="source">image source</param> /// <param name="value">value to set</param> public void SetValue(IBuffer<float> source, float value) { if (source == null) throw new ArgumentNullException("source"); for (int i = 0, length = source.HostBuffer.Length; i < length; i++) source.HostBuffer[i] = value; }
private void HandleDataReceived(INetSocket clientSocket, IBuffer buffer) { if (buffer.Size > 0) { ReceiveData(); } OnMessage(this, buffer); }
public InputAssembler( IBuffer vertexBuffer, IVertexDeclaration vertexDeclaration, PrimitiveType primitiveType = PrimitiveType.TriangleList, IBuffer indexBuffer = null ) : this() { PrimitiveType = primitiveType; VertexBuffer = vertexBuffer; VertexDeclaration = vertexDeclaration; IndexBuffer = indexBuffer; }
/// <summary> /// Reads the given stream up to the end, returning the data as a byte /// array, using the given buffer for transferring data. Note that the /// current contents of the buffer is ignored, so the buffer needn't /// be cleared beforehand. /// </summary> /// <param name="input">The stream to read from</param> /// <param name="buffer">The buffer to use to transfer data</param> /// <exception cref="ArgumentNullException">input is null</exception> /// <exception cref="ArgumentNullException">buffer is null</exception> /// <exception cref="IOException">An error occurs while reading from the stream</exception> /// <returns>The data read from the stream</returns> public static byte[] ReadFully(Stream input, IBuffer buffer) { if (buffer==null) { throw new ArgumentNullException("buffer"); } return ReadFully(input, buffer.Bytes); }
protected Document (IBuffer buffer,ILineSplitter splitter) { this.buffer = buffer; this.splitter = splitter; splitter.LineChanged += SplitterLineSegmentTreeLineChanged; splitter.LineRemoved += HandleSplitterLineSegmentTreeLineRemoved; foldSegmentTree.InstallListener (this); }
protected Document (IBuffer buffer,ILineSplitter splitter) { this.buffer = buffer; this.splitter = splitter; splitter.LineChanged += SplitterLineSegmentTreeLineChanged; splitter.LineRemoved += HandleSplitterLineSegmentTreeLineRemoved; foldSegmentTree.tree.NodeRemoved += HandleFoldSegmentTreetreeNodeRemoved; }
/// <summary> /// Copies all the data from one stream into another, using the given /// buffer for transferring data. Note that the current contents of /// the buffer is ignored, so the buffer needn't be cleared beforehand. /// </summary> /// <param name="input">The stream to read from</param> /// <param name="output">The stream to write to</param> /// <param name="buffer">The buffer to use to transfer data</param> /// <exception cref="ArgumentNullException">input is null</exception> /// <exception cref="ArgumentNullException">output is null</exception> /// <exception cref="ArgumentNullException">buffer is null</exception> /// <exception cref="IOException">An error occurs while reading or writing</exception> public static void Copy(Stream input, Stream output, IBuffer buffer) { if (buffer==null) { throw new ArgumentNullException("buffer"); } Copy(input, output, buffer.Bytes); }
public static void Set(this IBinding<BufferRange> binding, IBuffer buffer) { binding.Set(new BufferRange { Buffer = buffer, Offset = 0, Size = buffer.SizeInBytes }); }
public PsiLexerGenerated(IBuffer buffer) : this() { if (null == buffer) { throw new System.ApplicationException("Error: Bad lexer buffer."); } yy_buffer = buffer; yy_eof_pos = yy_buffer.Length; }
internal void ReleaseBufferToPool(IBuffer buffer) { for (int i = 0; i < pool.Length; i++) { if (Interlocked.CompareExchange(ref pool[i], buffer, null) == null) { break; // found a null; swapped it in } } }
/// <summary> /// Initializes a new instance of the SubBuffer class. /// </summary> /// <param name="parent">The parent buffer.</param> /// <param name="first">The first byte in <paramref name="parent"/> represented by this sub-buffer.</param> /// <param name="length">The number of bytes of <paramref name="parent"/> represented by this sub-buffer.</param> public SubBuffer(IBuffer parent, long first, long length) { _parent = parent; _first = first; _length = length; if (_first + _length > _parent.Capacity) { throw new ArgumentException("Substream extends beyond end of parent stream"); } }
public void Reset(bool clear) { if (clear) { count = 0; points = null; } indices = null; partition = null; colors = null; }
protected Document (IBuffer buffer,ILineSplitter splitter) { this.buffer = buffer; this.splitter = splitter; splitter.LineChanged += SplitterLineSegmentTreeLineChanged; splitter.LineRemoved += HandleSplitterLineSegmentTreeLineRemoved; foldSegmentTree.InstallListener (this); foldSegmentTree.tree.NodeRemoved += delegate(object sender, RedBlackTree<FoldSegment>.RedBlackTreeNodeEventArgs e) { if (e.Node.IsFolded) foldedSegments.Remove (e.Node); }; }
/// <summary> /// Initializes a new <see cref="BufferMapping"/>. /// </summary> /// <param name="buffer">The <see cref="IBuffer"/> to map.</param> /// <param name="access">The <see cref="BufferAccess"/>.</param> /// <param name="mapImmediately"><c>true</c> if the <paramref name="buffer"/> shall be mapped directly, otherwise <c>false</c>.</param> public BufferMapping(IBuffer buffer, BufferAccess access, bool mapImmediately = true) : this() { Contract.Requires<ArgumentNullException>(buffer != null); this.access = access; this.buffer = buffer; if (mapImmediately) { this.Map(); } }
public PdfStream( PdfDictionary header, IBuffer body ) { this.header = (PdfDictionary)Include(header); this.body = body; body.Clean(); body.OnChange += delegate( object sender, EventArgs args ) {Update();}; }
private void BeginVertexDeclaration( IBuffer buffer, IVertexDeclaration decl ) { GL.BindBuffer ( BufferTarget.ArrayBuffer, ( int ) buffer.Handle ); int i = 0, offset = 0; foreach ( VertexElement element in decl ) { int size = ElementSizeToRealSize ( element.Size ); GL.EnableVertexAttribArray ( i ); GL.VertexAttribPointer ( i, size / 4, ElementSizeToRealType ( element.Size ), false, buffer.RecordTypeSize, offset ); ++i; offset += size; } }
public override void Intro( params object [] args ) { Core.Window.Title = "Cube"; contentManager = new ResourceTable ( FileSystemManager.GetFileSystem ( "ManifestFileSystem" ) ); cubeEffect = contentManager.Load<IEffect> ( "Resources/Cube/CubeShader.xml", "i_pos", "i_col" ); cubeVertices = Core.GraphicsDevice.CreateBuffer<CubeVertex>( BufferType.VertexBuffer, new CubeVertex [] { new CubeVertex () { Position = new Vector3 ( -1, -1, -1 ), Diffuse = Color.Red }, new CubeVertex () { Position = new Vector3 ( +1, -1, -1 ), Diffuse = Color.Blue }, new CubeVertex () { Position = new Vector3 ( -1, -1, +1 ), Diffuse = Color.Green }, new CubeVertex () { Position = new Vector3 ( +1, -1, +1 ), Diffuse = Color.White }, new CubeVertex () { Position = new Vector3 ( -1, +1, -1 ), Diffuse = Color.Magenta }, new CubeVertex () { Position = new Vector3 ( -1, +1, +1 ), Diffuse = Color.Cyan }, new CubeVertex () { Position = new Vector3 ( +1, +1, -1 ), Diffuse = Color.Yellow }, new CubeVertex () { Position = new Vector3 ( +1, +1, +1 ), Diffuse = Color.White }, } ); cubeIndices = Core.GraphicsDevice.CreateBuffer<CubeIndex> ( BufferType.IndexBuffer, new CubeIndex [] { // TOP new CubeIndex () { I0 = 0, I1 = 1, I2 = 2 }, new CubeIndex () { I0 = 1, I1 = 3, I2 = 2 }, // LEFT new CubeIndex () { I0 = 0, I1 = 2, I2 = 4 }, new CubeIndex () { I0 = 2, I1 = 5, I2 = 4 }, // FRONT new CubeIndex () { I0 = 2, I1 = 3, I2 = 5 }, new CubeIndex () { I0 = 3, I1 = 7, I2 = 5 }, // RIGHT new CubeIndex () { I0 = 3, I1 = 1, I2 = 7 }, new CubeIndex () { I0 = 1, I1 = 6, I2 = 7 }, // BACK new CubeIndex () { I0 = 1, I1 = 0, I2 = 6 }, new CubeIndex () { I0 = 6, I1 = 0, I2 = 4 }, // BOTTOM new CubeIndex () { I0 = 5, I1 = 6, I2 = 4 }, new CubeIndex () { I0 = 5, I1 = 7, I2 = 6 }, } ); vertexDeclarataion = Core.GraphicsDevice.CreateVertexDeclaration ( Utilities.CreateVertexElementArray<CubeVertex> () ); proj = new PerspectiveFieldOfViewProjection (); lookAt = new LookAt ( new Vector3 ( 5, 5, 5 ), new Vector3 ( 0, 0, 0 ), new Vector3 ( 0, 1, 0 ) ); world = World3.Identity; base.Intro ( args ); }
public BoundingBox SetPoints(IBuffer<float> buffer) { BoundingBox bounds = new BoundingBox(); if (points != null && points.Count < buffer.Count) { count = points.Count / points.Size; } else { count = buffer.Count / buffer.Size; } this.points = buffer; return bounds; }
public EarthlitNightScene(IEye eye) { this.eye = eye; device = eye.Device; swapChain = device.PrimarySwapChain; stars = new Stars(device, StarCount); var meshFactory = new MeshFactory(device, Handedness.Right, Winding.Clockwise); var earthMesh = meshFactory.CreateSphere(false, 1.0f, 36); earthVertexBuffer = earthMesh.Vertices.Buffer; earthIndexBuffer = earthMesh.Indices.Buffer; var formatInfo = eye.Adapters[0].GetSupportedFormats(FormatSupport.RenderTarget | FormatSupport.Texture2D | FormatSupport.TextureCube) .First(x => x.ColorBits == 24 && x.AlphaBits == 8 && x.ColorFormatType == FormatElementType.UNORM); starsProxyTexture = device.Create.Texture2D(new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Usage = Usage.Default, Width = SkyboxSize, Height = SkyboxSize, ArraySize = 1, MipLevels = 1, FormatID = formatInfo.ID }); skyboxTexture = device.Create.Texture2D(new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Usage = Usage.Default, Width = SkyboxSize, Height = SkyboxSize, ArraySize = 6, MipLevels = TextureHelper.MipLevels(SkyboxSize, SkyboxSize, 1), FormatID = formatInfo.ID, MiscFlags = MiscFlags.TextureCube | MiscFlags.GenerateMips }); var textureLoader = new TextureLoader(device); earthTexture = textureLoader.Load("../Textures/BasicTest.png"); }
public void SetBuffer(uint index, IBuffer buffer) { if (transformFeedbackBuffers[index] == buffer) return; context.Bindings.TransformFeedback.Set(this); GL.BindBufferBase((int)BufferTarget.TransformFeedback, index, buffer.SafeGetHandle()); transformFeedbackBuffers[index] = buffer; if (buffer != null) { if (index >= enabledBufferRange) enabledBufferRange = index + 1; } else { if (index == enabledBufferRange - 1) while (enabledBufferRange > 0 && transformFeedbackBuffers[enabledBufferRange - 1] == null) enabledBufferRange--; } }
/// <summary> /// This method skips m_Modifications entry in prefab document and stores modifications in dictionaries /// /// After this method is executed, lexer current token is null or indent of next entry (after m_Modifications) /// </summary> private void GetModifications(IBuffer buffer, YamlLexer lexer, int parentIndentSize, Dictionary <FileID, string> names, Dictionary <FileID, int?> rootIndexes) { FileID curTarget = null; string curPropertyPath = null; string curValue = null; // Each property modifications is flow node: // - target: .. // propertyPath: .. // value: // Minus token means that new modification description is started // There are several entries in description. We are interested only // in target, propertyPath and value while (UnitySceneDataUtil.FindNextIndent(lexer)) { var currentSize = lexer.TokenEnd - lexer.TokenStart; lexer.Advance(); var tokenType = lexer.TokenType; if (tokenType == YamlTokenType.MINUS) { currentSize++; AddData(); lexer.Advance(); } if (currentSize <= parentIndentSize) { break; } UnitySceneDataUtil.SkipWhitespace(lexer); tokenType = lexer.TokenType; if (tokenType == YamlTokenType.NS_PLAIN_ONE_LINE_IN) { var text = buffer.GetText(new TextRange(lexer.TokenStart, lexer.TokenEnd)); if (text.Equals(UnityYamlConstants.TargetProperty)) { lexer.Advance(); UnitySceneDataUtil.SkipWhitespace(lexer); lexer.Advance(); // skip column // [TODO] handle prefab in prefab curTarget = UnitySceneDataUtil.GetFileId(buffer, lexer).WithGuid(null); } else if (text.Equals(UnityYamlConstants.PropertyPathProperty)) { lexer.Advance(); UnitySceneDataUtil.SkipWhitespace(lexer); lexer.Advance(); curPropertyPath = UnitySceneDataUtil.GetPrimitiveValue(buffer, lexer); } else if (text.Equals(UnityYamlConstants.ValueProperty)) { lexer.Advance(); UnitySceneDataUtil.SkipWhitespace(lexer); lexer.Advance(); curValue = UnitySceneDataUtil.GetPrimitiveValue(buffer, lexer); } } } AddData(); void AddData() { if (curTarget != null) { if (curPropertyPath != null && curPropertyPath.Equals(UnityYamlConstants.NameProperty)) { names[curTarget] = curValue; } else if (curPropertyPath != null && curPropertyPath.Equals(UnityYamlConstants.RootOrderProperty)) { rootIndexes[curTarget] = int.TryParse(curValue, out var r) ? (int?)r : null; } curTarget = null; curPropertyPath = null; curValue = null; } } }
private async Task ReadLoop() { try { bool ContinueReading = true; int NrRead; while (ContinueReading && this.client != null) { #if WINDOWS_UWP IBuffer DataRead = await this.client.InputStream.ReadAsync(this.buffer, BufferSize, InputStreamOptions.Partial); byte[] Data; if (DataRead.Length == 0) { NrRead = 0; Data = null; } else { CryptographicBuffer.CopyToByteArray(DataRead, out Data); if (Data == null) { NrRead = 0; } else { NrRead = Data.Length; } } #else NrRead = await this.stream.ReadAsync(this.buffer, 0, BufferSize); #endif if (NrRead <= 0) { ContinueReading = false; } else { int i; byte b; if (this.HasSniffers) { #if WINDOWS_UWP this.ReceiveBinary(Data); #else if (NrRead != BufferSize) { byte[] Data = new byte[NrRead]; Array.Copy(this.buffer, 0, Data, 0, NrRead); this.ReceiveBinary(Data); } #endif } for (i = 0; i < NrRead; i++) { #if WINDOWS_UWP b = Data[i]; #else b = this.buffer[i]; #endif switch (this.inputState) { case 0: this.inputPacket = new MemoryStream(); this.inputPacket.WriteByte(b); this.inputPacketType = (MqttControlPacketType)(b >> 4); this.inputPacketQoS = (MqttQualityOfService)((b >> 1) & 3); this.inputRemainingLength = 0; this.inputOffset = 0; this.inputState++; break; case 1: this.inputRemainingLength |= ((b & 127) << this.inputOffset); this.inputOffset += 7; this.inputPacket.WriteByte(b); if ((b & 128) == 0) { switch (this.inputPacketType) { case MqttControlPacketType.CONNECT: case MqttControlPacketType.CONNACK: case MqttControlPacketType.PINGREQ: case MqttControlPacketType.PINGRESP: case MqttControlPacketType.DISCONNECT: case MqttControlPacketType.PUBLISH: default: if (this.inputRemainingLength == 0) { this.inputState = 0; if (!this.ProcessInputPacket()) { ContinueReading = false; } } else { this.inputState += 3; } break; case MqttControlPacketType.PUBACK: case MqttControlPacketType.PUBREC: case MqttControlPacketType.PUBREL: case MqttControlPacketType.PUBCOMP: case MqttControlPacketType.SUBSCRIBE: case MqttControlPacketType.SUBACK: case MqttControlPacketType.UNSUBSCRIBE: case MqttControlPacketType.UNSUBACK: this.inputState++; break; } } break; case 2: this.inputPacket.WriteByte(b); this.inputState++; this.inputRemainingLength--; break; case 3: this.inputPacket.WriteByte(b); this.inputRemainingLength--; if (this.inputRemainingLength == 0) { this.inputState = 0; if (!this.ProcessInputPacket()) { ContinueReading = false; } } else { this.inputState++; } break; case 4: this.inputPacket.WriteByte(b); this.inputRemainingLength--; if (this.inputRemainingLength == 0) { this.inputState = 0; if (!this.ProcessInputPacket()) { ContinueReading = false; } } break; } } } } } catch (Exception ex) { this.ConnectionError(ex); return; } }
public override LeafElementBase Create(IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset) { return(new PascalLeafToken(buffer.GetText(new TextRange(startOffset.Offset, endOffset.Offset)), this)); }
public override int Id => 0x12; //18 public override void Handle(EzClient client, EzPacket packet) { Score score = new Score(); score.AccountId = client.Account.Id; score.GameId = client.Game.Id; score.SongId = client.Room.Info.SelectedSong; score.Created = DateTime.Now; score.Difficulty = client.Room.Info.Difficulty; score.FadeEffect = client.Room.Info.FadeEffect; score.NoteEffect = client.Room.Info.NoteEffect; score.Slot = client.Player.Slot; score.Team = client.Player.Team; byte unknown0 = packet.Data.ReadByte(); score.StageClear = packet.Data.ReadByte() == 0; short unknown1 = packet.Data.ReadInt16(Endianness.Big); score.MaxCombo = packet.Data.ReadInt16(Endianness.Big); score.Kool = packet.Data.ReadInt16(Endianness.Big); score.Cool = packet.Data.ReadInt16(Endianness.Big); score.Good = packet.Data.ReadInt16(Endianness.Big); score.Miss = packet.Data.ReadInt16(Endianness.Big); score.Fail = packet.Data.ReadInt16(Endianness.Big); short unknown2 = packet.Data.ReadInt16(Endianness.Big); score.RawScore = packet.Data.ReadInt32(Endianness.Big); score.TotalNotes = packet.Data.ReadInt16(Endianness.Big); score.Rank = (ScoreRankType)packet.Data.ReadByte(); byte unknown3 = packet.Data.ReadByte(); score.ComboType = Score.GetComboType(score); _logger.Debug("StageClear: {0}", score.StageClear); _logger.Debug("MaxCombo: {0}", score.MaxCombo); _logger.Debug("Kool: {0}", score.Kool); _logger.Debug("Cool: {0}", score.Cool); _logger.Debug("Good: {0}", score.Good); _logger.Debug("Miss: {0}", score.Miss); _logger.Debug("Fail: {0}", score.Fail); _logger.Debug("RawScore: {0}", score.RawScore); _logger.Debug("TotalScore: {0}", score.TotalScore); _logger.Debug("Rank: {0}", score.Rank); _logger.Debug("Total Notes: {0}", score.TotalNotes); _logger.Debug("Unknown0: {0}", unknown0); _logger.Debug("Unknown1: {0}", unknown1); _logger.Debug("Unknown2: {0}", unknown2); _logger.Debug("Unknown3: {0}", unknown3); client.Player.Playing = false; client.Score = score; /* * //Play check * IBuffer player4 = EzServer.Buffer.Provide(); * player4.WriteByte(0); * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(100); * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(6); //MAX COMBO * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(7); //SCORE * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); //? * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); //? * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); //? * * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); * player4.WriteByte(0); //? * Send(client, 0x19, player4); */ if (!Database.InsertScore(score)) { _logger.Error("Could't save score for: {0}", client.Character.Name); } if (!client.Room.Finished()) { // Last player finish will be responsible for going back to room. // TODO let the server check periodically incase the last person disconnectes. return; } List <EzClient> clients = client.Room.GetClients(); IBuffer scorePacket = ScorePacket.Create(clients); Send(client.Room, 0x1B, scorePacket); //27 Task.Delay(TimeSpan.FromSeconds(10)).ContinueWith(t => { // Display Room after 10 seconds IBuffer buffer = EzServer.Buffer.Provide(); buffer.WriteByte(0); Send(client.Room, 0x1C, buffer); //28 }); }
public CheckedReader(IBuffer buffer, ulong byteCapacity) : base(buffer) { _byteCapacity = byteCapacity; }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(System.Runtime.InteropServices.WindowsRuntime.AsyncInfo.Run <IBuffer, uint>((token, progress) => { return Task.Run(() => { System.Diagnostics.Debug.WriteLine("ReadAsync for: " + count.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); // If first Read call if ((ReadDataIndex == 0) && (internalStream.Size > count)) { // First dummy read of the header inputStream = internalStream.GetInputStreamAt(wavHeaderLength); uint currentDataLength = (uint)(internalStream.Size - wavHeaderLength); if (currentDataLength > 0) { data.length = currentDataLength; var WAVHeaderBuffer = CreateWAVHeaderBuffer(data.length); if (WAVHeaderBuffer != null) { int headerLen = WAVHeaderBuffer.Length; if (count >= headerLen) { byte[] updatedBuffer = new byte[count]; WAVHeaderBuffer.CopyTo(updatedBuffer.AsBuffer()); if (count > headerLen) { //fill buffer inputStream.ReadAsync(updatedBuffer.AsBuffer((int)headerLen, (int)(count - headerLen)), (uint)(count - headerLen), options).AsTask().Wait(); } buffer = updatedBuffer.AsBuffer(); ReadDataIndex += buffer.Length; System.Diagnostics.Debug.WriteLine("ReadAsync return : " + buffer.Length.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); progress.Report((uint)buffer.Length); return updatedBuffer.AsBuffer(); } } } } else { inputStream.ReadAsync(buffer, count, options).AsTask().Wait(); ReadDataIndex += buffer.Length; System.Diagnostics.Debug.WriteLine("ReadAsync return : " + buffer.Length.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); progress.Report((uint)buffer.Length); return buffer; } return null; }); })); }
public FastComputer(int id, IBus bus, Register register, IBuffer buffer) : base(id, bus, register, buffer, 100) { }
private void SendAuctionNotifyClose(NecClient client) { IBuffer res = BufferProvider.Provide(); router.Send(client.map, (ushort)AreaPacketId.recv_auction_notify_close, res, ServerType.Area, client); }
// If we add any more references, add them here, or SWEA's usage count won't pick them up!! public static bool CanContainReference([NotNull] IBuffer buffer) { return(UnityEventTargetReferenceFactory.CanContainReference(buffer) || MonoScriptReferenceFactory.CanContainReference(buffer)); }
private async Task SendDataToProxy(string data) { byte[] buffer = Encoding.ASCII.GetBytes(data); IBuffer ibuffer = buffer.AsBuffer(); await standardInput.WriteAsync(ibuffer); }
private string getRandomBytes(uint size) { IBuffer buffer = CryptographicBuffer.GenerateRandom(size); return(CryptographicBuffer.EncodeToHexString(buffer)); }
/// <summary> /// 获取请求返回结果 /// </summary> /// <param name="requestItem"></param> /// <returns></returns> public async Task <HttpResult> GetResultAsync(HttpItem requestItem) { HttpResult result = new HttpResult(); try { ProtocolFilter.AllowAutoRedirect = requestItem.AllowAutoRedirect; //10586没有这个属性? //ProtocolFilter.AllowUI = requestItem.AllowUI; ProtocolFilter.AutomaticDecompression = requestItem.AutomaticDecompression; ProtocolFilter.MaxConnectionsPerServer = requestItem.MaxConnectionsPerServer; ProtocolFilter.UseProxy = requestItem.UseProxy; ProtocolFilter.CookieUsageBehavior = requestItem.UseCookies ? HttpCookieUsageBehavior.Default : HttpCookieUsageBehavior.NoCookies; ProtocolFilter.CacheControl.WriteBehavior = requestItem.IsWriteCache ? HttpCacheWriteBehavior.Default : HttpCacheWriteBehavior.NoCache; //请求结果 HttpResponseMessage responseMessage = null; //请求的异常 Exception requestException = null; //获取请求体 using (HttpRequestMessage requestMessage = await GetRequestMessage(requestItem)) { AutoResetEvent waitEvent = new AutoResetEvent(false); //进行请求并获取结果 var requestTask = Task.Run(async() => { try { responseMessage = await Client.SendRequestAsync(requestMessage); } catch (Exception ex) { requestException = ex; } finally { waitEvent.Set(); } }); waitEvent.WaitOne(requestItem.TimeOut); } if (requestException != null) { throw requestException; } if (responseMessage == null) { result.Html = "请求超时"; result.StatusCode = HttpStatusCode.RequestTimeout; } else { result.OriginResponse = responseMessage; //设置状态 result.StatusCode = responseMessage.StatusCode; //设置重定向地址 result.Location = responseMessage?.Headers?.Location; //设置请求地址 result.RequestUri = responseMessage?.RequestMessage?.RequestUri; //读取内容buffer IBuffer buffer = await responseMessage.Content.ReadAsBufferAsync(); #region 根据返回类型处理请求的返回值 switch (requestItem.ResultType) { case ResultType.STRING: //返回字符串 result.Html = requestItem.Encoding.GetString(WindowsRuntimeBufferExtensions.ToArray(buffer), 0, (int)buffer.Length); break; case ResultType.DATA: //返回数据 result.Data = buffer; break; default: break; } #endregion 根据返回类型处理请求的返回值 } } catch (Exception ex) { Debug.WriteLine(ex); if (requestItem.ThrowException) { throw; } else { result.Html = ex.Message; } } return(result); }
public void AddPrefabModification(IBuffer buffer) { var anchor = UnitySceneDataUtil.GetAnchorFromBuffer(buffer); if (anchor == null) { return; } var lexer = new YamlLexer(buffer, false, false); lexer.Start(); TokenNodeType currentToken; var transformParentId = FileID.Null; while ((currentToken = lexer.TokenType) != null) { if (currentToken == YamlTokenType.INDENT) { var indentSize = lexer.TokenEnd - lexer.TokenStart; lexer.Advance(); currentToken = lexer.TokenType; if (currentToken == YamlTokenType.NS_PLAIN_ONE_LINE_IN) { var text = buffer.GetText(new TextRange(lexer.TokenStart, lexer.TokenEnd)); if (text.Equals(UnityYamlConstants.TransformParentProperty)) { lexer.Advance(); UnitySceneDataUtil.SkipWhitespace(lexer); currentToken = lexer.TokenType; if (currentToken == YamlTokenType.COLON) { lexer.Advance(); var result = UnitySceneDataUtil.GetFileId(buffer, lexer); if (result != null) { transformParentId = result; } } } else if (text.Equals(UnityYamlConstants.ModificationsProperty)) { var names = new Dictionary <FileID, string>(); var rootIndexes = new Dictionary <FileID, int?>(); GetModifications(buffer, lexer, indentSize, names, rootIndexes); var id = new FileID(null, anchor); Elements[id] = new ModificationHierarchyElement(id, null, null, false, transformParentId, rootIndexes, names); return; } } } else { lexer.Advance(); } } }
public YamlBinaryLexer(IBuffer buffer) { Buffer = buffer; }
protected virtual ILexer GetDefaultLexer(IBuffer buffer) => new YamlLexer(buffer, true, false);
public static bool CanContainReference(IBuffer bodyBuffer) { return(ourScriptReferenceStringSearcher.Find(bodyBuffer) >= 0); }
public void Setup() { this.destination = Configuration.Default.MemoryManager.Allocate <TPixel>(this.Count); this.source = Configuration.Default.MemoryManager.Allocate <Vector4>(this.Count); }
/// <summary> /// Read bytes until buffer filled or throw IOException. /// </summary> /// <param name="buffer">The buffer to read</param> /// <returns>The data read from the stream</returns> public static byte[] ReadAll(IBuffer buffer) { return(ReadFully(buffer, 0, (int)buffer.Capacity)); }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } using (NtfsFileSystem fs = new NtfsFileSystem(volInfo.Open())) { MasterFileTable mft = fs.GetMasterFileTable(); if (_recoverFile.IsPresent) { MasterFileTableEntry entry = mft[long.Parse(_recoverFile.Value)]; IBuffer content = GetContent(entry); if (content == null) { Console.WriteLine("Sorry, unable to recover content"); Environment.Exit(1); } string outFile = _recoverFile.Value + "__recovered.bin"; if (File.Exists(outFile)) { Console.WriteLine("Sorry, the file already exists: " + outFile); Environment.Exit(1); } using (FileStream outFileStream = new FileStream(outFile, FileMode.CreateNew, FileAccess.Write)) { Pump(content, outFileStream); } Console.WriteLine("Possible file contents saved as: " + outFile); Console.WriteLine(); Console.WriteLine("Caution! It is rare for the file contents of deleted files to be intact - most"); Console.WriteLine("likely the contents recovered are corrupt as the space has been reused."); } else { foreach (var entry in mft.GetEntries(EntryStates.NotInUse)) { // Skip entries with no attributes, they've probably never been used. We're certainly // not going to manage to recover any useful data from them. if (entry.Attributes.Count == 0) { continue; } // Skip directories - any useful files inside will be found separately if ((entry.Flags & MasterFileTableEntryFlags.IsDirectory) != 0) { continue; } long size = GetSize(entry); string path = GetPath(mft, entry); if (!_showMeta.IsPresent && path.StartsWith(@"<root>\$Extend")) { continue; } if (!_showZeroSize.IsPresent && size == 0) { continue; } Console.WriteLine("Index: {0,-4} Size: {1,-8} Path: {2}", entry.Index, Utilities.ApproximateDiskSize(size), path); } } } }
public override LeafElementBase Create(IBuffer buffer, TreeOffset startOffset, TreeOffset endOffset) { return(new CgBuiltInTypeTokenNode(this, buffer.GetText(new TextRange(startOffset.Offset, endOffset.Offset)))); }
public int Receive(byte[] buffer, int offset, int count) { IBuffer result = this.socket.InputStream.ReadAsync(buffer.AsBuffer(offset, count), (uint)count, InputStreamOptions.Partial).AsTask().Result; return((int)result.Length); }
public static byte[] ReadBuffer(IBuffer buffer) { byte[] bytes = new byte[buffer.Length]; DataReader.FromBuffer(buffer).ReadBytes(bytes); return(bytes); }
public void SetNonce(IBuffer nonce) { Nonce = CryptographicBuffer.EncodeToBase64String(nonce); }
protected override IBuffer ToBuffer() { IBuffer res = BufferProvider.Provide(); res.WriteInt32(0); //sub_496540 res.WriteInt64(0); res.WriteInt32(0); for (int i = 0; i < 0x5; i++) { res.WriteInt32(0); } //4929F0 res.WriteInt64(0); //sub4929A0 res.WriteInt16(0); for (int i = 0; i < 0x2; i++) { res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } for (int k = 0; k < 0x5; k++) { res.WriteInt16(0); //sub492940 res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } //4929F0 res.WriteInt64(0); //sub4929A0 res.WriteInt16(0); for (int i = 0; i < 0x2; i++) { res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } for (int k = 0; k < 0x5; k++) { res.WriteInt16(0); //sub492940 res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } //4929F0 res.WriteInt64(0); //sub4929A0 res.WriteInt16(0); for (int i = 0; i < 0x2; i++) { res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } for (int k = 0; k < 0x5; k++) { res.WriteInt16(0); //sub492940 res.WriteInt32(0); res.WriteInt32(0); for (int j = 0; j < 0x2; j++) { res.WriteInt16(0); } } //end sub_496540 return(res); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { var inputStream = this.GetInputStreamAt(0); return(inputStream.ReadAsync(buffer, count, options)); }
public Windows.Foundation.IAsyncOperationWithProgress <uint, uint> WriteAsync(IBuffer buffer) { return(System.Runtime.InteropServices.WindowsRuntime.AsyncInfo.Run <uint, uint>((token, progress) => { return Task.Run(() => { // If it's the first WriteAsync in the stream // the buffer should contains the WAV Header if ((internalStream.Size == 0) && (wavHeaderLength == 0)) { WriteDataIndex = 0; // Check header byte[] array = buffer.ToArray(); wavHeaderLength = ParseAndGetWAVHeaderLength(array); internalStream.WriteAsync(buffer).AsTask().Wait(); WriteDataIndex += buffer.Length; progress.Report((uint)(buffer.Length)); return (uint)(buffer.Length); } else { if (internalStream.Position != internalStream.Size) { System.Diagnostics.Debug.WriteLine("Warning WriteAsync: " + internalStream.Position.ToString() + "/" + internalStream.Size.ToString()); } ulong index = internalStream.Size; uint byteToWrite = buffer.Length; // System.Diagnostics.Debug.WriteLine("WriteAsync: " + buffer.Length.ToString() + " at position: " + internalStream.Position); internalStream.WriteAsync(buffer.ToArray(0, (int)byteToWrite).AsBuffer()).AsTask().Wait(); WriteDataIndex += buffer.Length; var byteArray = buffer.ToArray(); if (byteArray.Length >= 2) { var amplitude = Decode(byteArray).Select(Math.Abs).Average(x => x); if (AudioLevel != null) { this.AudioLevel(this, amplitude); } // Currently the level is too low if (thresholdDurationInBytes > 0) { if (audioStream == null) { if (internalStream.Size > thresholdDurationInBytes) { var readStream = internalStream.GetInputStreamAt(internalStream.Size - thresholdDurationInBytes); byte[] readBuffer = new byte[thresholdDurationInBytes]; readStream.ReadAsync(readBuffer.AsBuffer(), (uint)thresholdDurationInBytes, InputStreamOptions.None).AsTask().Wait(); var level = Decode(readBuffer).Select(Math.Abs).Average(x => x); if (level > thresholdLevel) { System.Diagnostics.Debug.WriteLine("Audio Level sufficient to start recording"); thresholdStart = WriteDataIndex - thresholdDurationInBytes; audioStream = SpeechToTextAudioStream.Create(nChannels, nSamplesPerSec, nAvgBytesPerSec, nBlockAlign, wBitsPerSample, thresholdStart); var headerBuffer = CreateWAVHeaderBuffer(0); if ((audioStream != null) && (headerBuffer != null)) { audioStream.WriteAsync(headerBuffer.AsBuffer()).AsTask().Wait(); audioStream.WriteAsync(readBuffer.AsBuffer()).AsTask().Wait(); } } } } else { audioStream.WriteAsync(buffer.ToArray(0, (int)byteToWrite).AsBuffer()).AsTask().Wait(); var readStream = internalStream.GetInputStreamAt(internalStream.Size - thresholdDurationInBytes); byte[] readBuffer = new byte[thresholdDurationInBytes]; readStream.ReadAsync(readBuffer.AsBuffer(), (uint)thresholdDurationInBytes, InputStreamOptions.None).AsTask().Wait(); var level = Decode(readBuffer).Select(Math.Abs).Average(x => x); if (level < thresholdLevel) { System.Diagnostics.Debug.WriteLine("Audio Level lower enough to stop recording"); thresholdEnd = WriteDataIndex; audioStream.Seek(0); var headerBuffer = CreateWAVHeaderBuffer((uint)(thresholdEnd - thresholdStart)); if (headerBuffer != null) { audioStream.WriteAsync(headerBuffer.AsBuffer()).AsTask().Wait(); } if (audioQueue != null) { audioStream.endIndex = thresholdEnd; audioQueue.Enqueue(audioStream); } if (BufferReady != null) { this.BufferReady(this); if (audioStream != null) { audioStream = null; } thresholdStart = 0; thresholdEnd = 0; } } } } } if (maxSize > 0) { // check maxSize if ((internalStream.Size > maxSize) && (audioStream == null)) { lock (maxSizeLock) { byte[] headerBuffer = null; if (wavHeaderLength > 0) { // WAV header present headerBuffer = new byte[wavHeaderLength]; inputStream = internalStream.GetInputStreamAt(0); inputStream.ReadAsync(headerBuffer.AsBuffer(), (uint)wavHeaderLength, InputStreamOptions.None).AsTask().Wait(); } seekOffset += (internalStream.Size - wavHeaderLength); internalStream.Dispose(); inputStream.Dispose(); internalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); if (headerBuffer != null) { internalStream.WriteAsync(headerBuffer.AsBuffer()).AsTask().Wait(); } inputStream = internalStream.GetInputStreamAt(0); } } } if (internalStream.Position == internalStream.Size) { WriteDataIndex += buffer.Length; } progress.Report((uint)buffer.Length); return (uint)buffer.Length; } }); })); }
public Windows.Foundation.IAsyncOperationWithProgress <uint, uint> WriteAsync(IBuffer buffer) { var outputStream = this.GetOutputStreamAt(0); return(outputStream.WriteAsync(buffer)); }
public IAsyncOperationWithProgress <IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options) { if (buffer == null) { // Mapped to E_POINTER. throw new ArgumentNullException(nameof(buffer)); } if (count < 0 || Int32.MaxValue < count) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count)); ex.SetErrorCode(__HResults.E_INVALIDARG); throw ex; } if (buffer.Capacity < count) { ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity); ex.SetErrorCode(__HResults.E_INVALIDARG); throw ex; } if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead)) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue); ex.SetErrorCode(__HResults.E_INVALIDARG); throw ex; } // Commented due to a reported CCRewrite bug. Should uncomment when fixed: //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null); //Contract.EndContractBlock(); Stream str = EnsureNotDisposed(); IAsyncOperationWithProgress <IBuffer, UInt32> readAsyncOperation; switch (_readOptimization) { case StreamReadOperationOptimization.MemoryStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count); break; case StreamReadOperationOptimization.AbstractStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options); break; // Use this pattern to add more optimisation options if necessary: //case StreamReadOperationOptimization.XxxxStream: // readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options); // break; default: Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option."); readAsyncOperation = null; break; } return(readAsyncOperation); }
private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { // GetDataReader() throws an exception when either: // (1) The underlying TCP connection is closed prematurely (e.g., FIN/RST received without sending/receiving a WebSocket Close frame). // (2) The server sends invalid data (e.g., corrupt HTTP headers or a message exceeding the MaxMessageSize). // // In both cases, the appropriate thing to do is to close the socket, as we have reached an unexpected state in // the WebSocket protocol. try { using (DataReader reader = args.GetDataReader()) { uint dataAvailable; while ((dataAvailable = reader.UnconsumedBufferLength) > 0) { ArraySegment <byte> buffer; try { buffer = _receiveAsyncBufferTcs.Task.GetAwaiter().GetResult(); } catch (OperationCanceledException) // Caused by Abort call on WebSocket { return; } _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); WebSocketMessageType messageType; if (args.MessageType == SocketMessageType.Binary) { messageType = WebSocketMessageType.Binary; } else { messageType = WebSocketMessageType.Text; } bool endOfMessage = false; uint readCount = Math.Min(dataAvailable, (uint)buffer.Count); if (readCount > 0) { IBuffer dataBuffer = reader.ReadBuffer(readCount); // Safe to cast readCount to int as the maximum value that readCount can be is buffer.Count. dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int)readCount); } if (dataAvailable == readCount) { endOfMessage = !IsPartialMessageEvent(args); } WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int)readCount, messageType, endOfMessage); _webSocketReceiveResultTcs.TrySetResult(recvResult); } } } catch (Exception exc) { // WinRT WebSockets always throw exceptions of type System.Exception. However, we can determine whether // or not we're dealing with a known error by using WinRT's WebSocketError.GetStatus method. WebErrorStatus status = RTWebSocketError.GetStatus(exc.HResult); WebSocketError actualError = WebSocketError.Faulted; switch (status) { case WebErrorStatus.ConnectionAborted: case WebErrorStatus.ConnectionReset: case WebErrorStatus.Disconnected: actualError = WebSocketError.ConnectionClosedPrematurely; break; } // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket. WebSocketException customException = new WebSocketException(actualError, exc); AbortInternal(customException); } }
private async void ButtonGo_Click(object sender, RoutedEventArgs e) { //Sytem de Sauvegarde var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Bitmap", new List <string>() { ".bmp" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "VacationPictures"; if (fileEncrypted.file != null && !string.IsNullOrWhiteSpace(messageToHide.Text) && !string.IsNullOrWhiteSpace(ParameterMessageToFindStart.Text) && !string.IsNullOrWhiteSpace(ParameterMessageSkippingBytes.Text)) { LoadingIndicator.IsActive = true; fileEncrypted.NBytesOffset = Int32.Parse(ParameterMessageSkippingBytes.Text); if (ParameterMessageToFindStart.Text.Length != 0) { fileEncrypted.StartAtPosition = Int32.Parse(ParameterMessageToFindStart.Text); } else { fileEncrypted.StartAtPosition = 0; } if (MessageToHideBool) { fileEncrypted.MessageToHide = messageToHide.Text; } else { IBuffer bufferToHide = await FileIO.ReadBufferAsync(fileToHide); byte[] fileToHideBytes = bufferToHide.ToArray(); fileEncrypted.MessageByte = fileToHideBytes; } fileEncrypted.MessageToAscii(MessageToHideBool); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { await FileIO.WriteBytesAsync(file, fileEncrypted.FinalsFiles); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { this.test.Text = "File " + file.Name + " was saved."; } else { this.test.Text = "File " + file.Name + " couldn't be saved."; } } else { this.test.Text = "Operation cancelled."; } } LoadingIndicator.IsActive = false; }