public static string getOneCell(string AirlineName) { if (sem_empty.WaitOne(300)) { for (int i = 0; i < 3; i++) { if (IsEmpty[i] == false) { string ObjectString = buffer[i]; Decoder decode_test = new Decoder(); OrderClass obj = new OrderClass(); if (ObjectString != null) { obj = decode_test.decryptString(ObjectString); //Console.WriteLine("string name passed is {0} actual name is {1}", AirlineName, obj.get_receiverId()); if (obj.get_receiverId() == AirlineName) { //Console.WriteLine("Readposition is {0}\n", i); mutex_lock.WaitOne(); buffer[i] = null; IsEmpty[i] = true; mutex_lock.ReleaseMutex(); sem_full.Release(); return ObjectString; } } } } sem_empty.Release(); } return null; }
public uint Decode(Decoder rangeDecoder) { uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; if (rangeDecoder.Code < newBound) { rangeDecoder.Range = newBound; Prob += (kBitModelTotal - Prob) >> kNumMoveBits; if (rangeDecoder.Range < Decoder.kTopValue) { rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); rangeDecoder.Range <<= 8; } return 0; } else { rangeDecoder.Range -= newBound; rangeDecoder.Code -= newBound; Prob -= (Prob) >> kNumMoveBits; if (rangeDecoder.Range < Decoder.kTopValue) { rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); rangeDecoder.Range <<= 8; } return 1; } }
public void EventHandler_ConfirmationStatus(string message) { Decoder decode_test = new Decoder(); OrderClass obj = new OrderClass(); obj = decode_test.decryptString(message); if (obj.get_senderId() == this.name) { Console.WriteLine("\n\n\n*************** ORDER STATUS ***************"); Console.WriteLine("Travel {0} placed an order of {1} ticktes to Airline {2}", obj.get_senderId(), obj.get_amount(), obj.get_receiverId()); Console.WriteLine("The price of each ticket is ${0}", obj.get_unitprice()); Console.WriteLine("The total amount charged is : ${0}", obj.get_totalamount()); Console.WriteLine("The order is charged to card number : {0}", obj.get_cardNo()); if (obj.get_confirmationstatus()) { Console.WriteLine("Congratulations !! the order has been processed. Have a safe Flight !"); } else { Console.WriteLine("No Tickets Available. Your order could not be processed at this time !"); } stopWatch.Stop(); timeSpan = stopWatch.Elapsed; Console.WriteLine("Total time taken for order confirmation: " + timeSpan.Milliseconds); Console.WriteLine("**************************************************"); Console.WriteLine("\n\n\n"); } }
public uint Decode(Decoder rangeDecoder) { uint m = 1; for (int bitIndex = _numBitLevels; bitIndex > 0; bitIndex--) m = (m << 1) + _models[m].Decode(rangeDecoder); return m - ((uint)1 << _numBitLevels); }
public void TestWithPointers() { var path = Path.Combine("..", "..", "TestData", "MaxMind-DB", "test-data", "maps-with-pointers.raw"); using (var database = new ArrayReader(path)) { var decoder = new Decoder(database, 0); var node = decoder.Decode(0).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(22).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value2")); node = decoder.Decode(37).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value1")); node = decoder.Decode(50).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); node = decoder.Decode(55).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(57).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); } }
public void TestWithPointers() { var path = Path.Combine(new[] { "..", "..", "TestData", "MaxMind-DB", "test-data", "maps-with-pointers.raw" }); var stream = new ThreadLocal<Stream>(() => new MemoryStream(File.ReadAllBytes(path))); using (stream) { var decoder = new Decoder(stream, 0); var node = decoder.Decode(0).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(22).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value2")); node = decoder.Decode(37).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value1")); node = decoder.Decode(50).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); node = decoder.Decode(55).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(57).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Decoder dcode = new Decoder(); string mErr = ""; // 檢查使用者權限但不存入登入紀錄 //Check_Power("3002", false); if (Request["fl_url"] != null) { lb_fl_url.Text = dcode.DeCode(Request["fl_url"].Trim()); if (lb_fl_url.Text == Album.Root) mErr = "根目錄不可刪除\\n"; else { lb_path.Text = Server.MapPath(lb_fl_url.Text); #region 取得目前目錄的名稱 lb_al_name.Text = lb_fl_url.Text.Replace(Album.Root,"").Replace("//",""); if (!Directory.Exists(lb_path.Text)) mErr = "找不到指定的路徑\\n"; #endregion } } else mErr = "參數傳送錯誤!\\n"; if (mErr != "") lt_show.Text = "<script language=\"javascript\">alert(\"" + mErr + "\");parent.close_all();parent.clean_win();</script>"; } }
/// <summary> /// Decodes an encoded frame. /// </summary> /// <param name="encodedFrame">The encoded frame.</param> /// <returns></returns> public override VideoBuffer Decode(byte[] encodedFrame) { if (Decoder == null) { Decoder = new Decoder(); } if (Padep.SequenceNumberingViolated) { Decoder.NeedsKeyFrame = true; return null; } // vp8 -> frame var width = 0; var height = 0; var frame = Decoder.Decode(encodedFrame, out width, out height); if (frame == null) { return null; } try { return new VideoBuffer(width, height, new VideoPlane(frame, width), VideoFormat.I420); } catch (Exception ex) { Log.Error("Could not convert decoded image to video buffer.", ex); return null; } }
public void ReturnsFalseIfTheInstructionIsNotValid() { var decoder = new Decoder(new Registry()); OpcodeAddressModePair pair; Assert.That(decoder.TryDecode(0xFF, out pair), Is.False, @"TryDecode returned true for an invalid instruction, which is not expected."); }
private static byte[] DecodeLzma(byte[] lzmaByteArray) { byte[] result = null; Decoder decoder = new Decoder(); using (MemoryStream memoryStream = new MemoryStream(lzmaByteArray)) { memoryStream.Seek(0L, SeekOrigin.Begin); using (MemoryStream memoryStream2 = new MemoryStream()) { byte[] array = new byte[5]; if (memoryStream.Read(array, 0, 5) != 5) { throw new Exception("input .lzma is too short"); } long num = 0L; for (int i = 0; i < 8; i++) { int num2 = memoryStream.ReadByte(); if (num2 < 0) { throw new Exception("Can't Read 1"); } num |= (long)((long)((ulong)((byte)num2)) << 8 * i); } decoder.SetDecoderProperties(array); long inSize = memoryStream.Length - memoryStream.Position; decoder.Code(memoryStream, memoryStream2, inSize, num, null); result = memoryStream2.ToArray(); } } return result; }
public byte DecodeNormal(Decoder rangeDecoder) { uint symbol = 1; do symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); return (byte)symbol; }
public Texture(Decoder scs) { m_vStorageObject = scs; m_vScImageTypes = new Dictionary<byte, Type>(); m_vScImageTypes.Add(0, typeof(ImageRgba8888)); m_vScImageTypes.Add(2, typeof(ImageRgba4444)); m_vScImageTypes.Add(4, typeof(ImageRgb565)); m_vTextureId = (short)m_vStorageObject.GetTextures().Count(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Decoder dcode = new Decoder(); string mErr = "", fl_name = "", fl_url = "", fpath = ""; // 檢查使用者權限,但不存登入紀錄 //Check_Power("3002", false); if (Request["fl_name"] == null || Request["fl_url"] == null) mErr = "參數傳送錯誤!\\n"; else { fl_name = Request["fl_name"].Trim().ToLower(); fl_url = dcode.DeCode(Request["fl_url"].Trim()); if (fl_name == "" || fl_url == "") mErr = "參數傳送錯誤!\\n"; } #region 取得相片資訊 if (mErr == "") { fpath = Server.MapPath(fl_url); if (fpath.Substring(fpath.Length - 1, 1) != "\\") fpath += "\\"; string[] mFiles = Directory.GetFiles(fpath, fl_name); if (mFiles.Length > 0) { FileInfo fi_obj = new FileInfo(mFiles[0].ToString()); lb_ac_name.Text = fl_name; lb_ac_size.Text = fi_obj.Length.ToString("N0"); lb_init_time.Text = fi_obj.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss"); lb_ac_type.Text = fi_obj.Extension.ToLower(); #region 讀取圖檔資料 using (System.Drawing.Image img_obj = System.Drawing.Image.FromFile(fpath + fl_name)) { lb_ac_wh.Text = img_obj.Width.ToString() + " × " + img_obj.Height.ToString(); } #endregion } else mErr = "找不到指定的相片!\\n"; mFiles = null; } #endregion if (mErr != "") lt_show.Text = "<script language=javascript>alert(\"" + mErr + "\");parent.close_all();parent.clean_win();</script>"; } }
private void btnOpen_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(openFileDialog.FileName)) { txtFileName.Text = openFileDialog.FileName; Decoder decoder = new Decoder(openFileDialog.FileName); gvData.DataSource = decoder.DecodeData; } }
protected void lb_ok_Click(object sender, EventArgs e) { string mErr = ""; string mg_pass, mg_pass1; // 載入公用函數 Common_Func cfc = new Common_Func(); mg_pass = tb_mg_pass.Text.Trim(); mg_pass1 = tb_mg_pass1.Text.Trim(); if (mg_pass == "") mErr = mErr + "「新登入密碼」沒有輸入!\\n"; else if (cfc.CheckSQL(mg_pass)) mErr = mErr + "「新登入密碼」請勿使用特殊符號!\\n"; else if (mg_pass.Length > 12 || mg_pass.Length < 4) mErr = mErr + "「新登入密碼」長度為4~12個字!\\n"; if (mg_pass != mg_pass1) mErr = mErr + "「新登入密碼」與「新密碼確認」不相同!\\n"; if (mErr == "") { using (SqlConnection Sql_conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["AppSysConnectionString"].ConnectionString)) { string SqlString = ""; Decoder decoder = new Decoder(); Sql_conn.Open(); // 建立 SQL 修改資料的語法 SqlString = "Update Manager Set mg_pass = @mg_pass"; SqlString = SqlString + " Where mg_sid = @mg_sid"; using (SqlCommand Sql_Command = new SqlCommand(SqlString, Sql_conn)) { Sql_Command.Parameters.AddWithValue("@mg_pass", decoder.EnCode(mg_pass)); Sql_Command.Parameters.AddWithValue("@mg_sid", lb_pg_mg_sid.Text); Sql_Command.ExecuteNonQuery(); } } } if (mErr == "") { mErr = "alert('密碼變更完成,新密碼該員於下次登入時生效!\\n');location.replace('10051.aspx" + lb_page.Text + "');"; } else mErr = "alert('" + mErr + "')"; lt_show.Text = "<script language=javascript>" + mErr + "</script>"; }
static void Main() { var readLine = Console.ReadLine(); if (readLine == null) return; var timesToRead = int.Parse(readLine); var decoder = new Decoder(); for (var i = 0; i < timesToRead; i++) { readLine = Console.ReadLine(); Console.WriteLine(decoder.DecodeMessage(readLine)); } }
public void Decode_CorrectlyDecodesInstructions(UInt64 raw, InstructionType expectedOp, Int32 expecteOperand) { // Arrange var decoder = new Decoder(); // Act var instruction = decoder.Decode(raw); // Assert instruction.Type.Should().Be(expectedOp); instruction.Operand.Should().Be(expecteOperand); }
/// <summary> /// Provides properties for storing and retrieving CME FIX market data incremental refresh fields. /// </summary> public MarketDataIncrementalRefresh(FieldInfo<byte> tagInfo, FieldInfo<byte> valueInfo, Trailer trailer, Decoder decoder) : base(tagInfo, valueInfo, trailer) { this.decoder = decoder; DataBlock = new RepeatingGroup[REPEATING_GROUP_ARRAY_LENGTH]; for (int i = 0; i < REPEATING_GROUP_ARRAY_LENGTH; i++) { DataBlock[i] = new RepeatingGroup(); } }
public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, Decoder rangeDecoder, int NumBitLevels) { uint m = 1; uint symbol = 0; for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) { uint bit = Models[startIndex + m].Decode(rangeDecoder); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; }
public uint ReverseDecode(Decoder rangeDecoder) { uint m = 1; uint symbol = 0; for (int bitIndex = 0; bitIndex < _numBitLevels; bitIndex++) { uint bit = _models[m].Decode(rangeDecoder); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; }
private void InitWithStandardHeader() { input = new MemoryStream(); patch = new MemoryStream(); output = new MemoryStream(); BinaryWriter patchWriter = new BinaryWriter(patch); patchWriter.Write(0x00C4C3D6); patchWriter.Write((byte)0x00); patch.Position = 0; decoder = new Decoder(input, patch, output); }
public MovieClip(MovieClip mv) { m_vStorageObject = mv.GetStorageObject(); m_vDataType = mv.GetMovieClipDataType(); m_vShapes = new List<ScObject>(); this.SetOffset(-Math.Abs(mv.GetOffset())); //Duplicate MovieClip using (FileStream input = new FileStream(m_vStorageObject.GetFileName(), FileMode.Open)) { input.Seek(Math.Abs(mv.GetOffset()) + 5, SeekOrigin.Begin); using (var br = new BinaryReader(input)) { this.ParseData(br); } } //Set new clip id short maxMovieClipId = this.GetId(); foreach(MovieClip clip in m_vStorageObject.GetMovieClips()) { if (clip.GetId() > maxMovieClipId) maxMovieClipId = clip.GetId(); } maxMovieClipId++; this.SetId(maxMovieClipId); //Get max shape id short maxShapeId = 20000;//avoid collision with other objects in MovieClips foreach(Shape shape in m_vStorageObject.GetShapes()) { if (shape.GetId() > maxShapeId) maxShapeId = shape.GetId(); } maxShapeId++; //Duplicate shapes associated to clip List<ScObject> newShapes = new List<ScObject>(); foreach(Shape s in m_vShapes) { Shape newShape = new Shape(s); newShape.SetId(maxShapeId); maxShapeId++; newShapes.Add(newShape); m_vStorageObject.AddShape(newShape);//Add to global shapelist m_vStorageObject.AddChange(newShape); } this.m_vShapes = newShapes; }
private static void Main(string[] args) { var ciphers = new Ciphertext[20]; var keys = new KeyContainer[53]; var result = @"C:\Users\Simon\Desktop\Krypto2\result.txt"; var file = new StreamWriter(result); //bedziemy wpisywac do file wynik var f = new FileReader(@"C:\Users\Simon\Desktop\Krypto2\zad1.txt"); var message = f.ReadFile(); //string //[]->rows []->kolumny var path = ""; for (var i = 0; i < 20; i++) { path = @"C:\Users\Simon\Desktop\Krypto2\k" + i + ".txt"; f = new FileReader(path); var c0 = f.ReadFile(); ciphers[i] = new Ciphertext(c0); } var keyGen = new KeyGenerator(); ////////////////////////////////////////////////////////////////////////////////////////////// for (var j = 0; j < 52; j++) //iteration through columns { keys[j] = new KeyContainer(); foreach (var key in keyGen) { var k = Converter.GetBytesFromBinaryString(key); var final = ""; var ks = 0; for (var i = 0; i < 20; i++) //lecimy po wszystkich kryptogramach { var cell = ciphers[i].GetByte(j); //musimy zmieniac var x = Converter.GetBytesFromBinaryString(cell); var res = Converter.XoR(k, x); final = final + Encoding.ASCII.GetString(res); } if (Converter.Check(final)) { Console.WriteLine("Key: " + key + " :" + final); keys[j].AddKey(key); } } } var decoder = new Decoder(message, keys); decoder.Decode(); Console.ReadKey(); }
public static uint ReverseDecode(BitDecoder[] models, uint startIndex, Decoder rangeDecoder, int numBitLevels) { uint m = 1; uint symbol = 0; for (var bitIndex = 0; bitIndex < numBitLevels; bitIndex++) { var bit = models[startIndex + m].Decode(rangeDecoder); m <<= 1; m += bit; symbol |= (bit << bitIndex); } return symbol; }
/** Picture: * @param b payload buffer * @param d decoder of the picture * * The b buffer should only point to the payload data section of * the picture (not the header). The only methods that would ever need * to be called are parse(), decode(), and getImage(). However, * one should check wether the error variable is set before and after * calling a method. One should not call them in any other order than that * just specified. Each can be called without arguments and should not be * called twice. */ public Picture(Buffer b, Decoder d) { num = b.GetInt(13); code = b.GetByte(4); buf = b; dec = d; par = new Parameters(code); coeffs = new SubBand[3][]; coeffs[0] = new SubBand[19]; coeffs[1] = new SubBand[19]; coeffs[2] = new SubBand[19]; motion_buffers = new Buffer[9]; status = Decoder.Status.NULL; }
static void testDecoder(Decoder decoder) { var jsonParser = new JsonParser() { CamelizeProperties = false }; dynamic config = jsonParser.Parse(System.IO.File.ReadAllText("config.txt")); Console.WriteLine("-----------------Decoder Test-----------------"); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0099],2012-10-02 21:14:45,STS,DC=0,PC=0,LV=0.0,BV=3.2,BU=3.6,I=5.3,T=23.9,DU=0.0,RU=0.0,STORAGE,OK,#E3", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0014],INVALID,#07", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0009],OK,#9A", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("450052,000,2012-10-02 21:19:19,STS,DC=0,PC=0,LV=0.0,BV=3.2,BU=3.6,I=2.7,T=23.7,DU=0.0,RU=0.0,XYZ=-0.06:-0.22:0.94,#8C", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("450052,001,2012-10-02 21:20:01,A69-9001,30444,#B3", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("450052,032,2012-10-02 21:40:42,A69-1303,48823,#C5", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("450052,039,2012-10-02 21:42:17,A69-9001,30,444,#CA", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0099],VR2C-69:450052,'VEMCO',MAP-113 [ 1105 1303 9001/9002 1420 1430 1601 1602 ],FW=0.0.25,HW=3,OK,#57", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0125],2012-10-02 21:47:06,STS,DC=108,PC=1199,LV=0.0,BV=3.2,BU=3.6,I=5.3,T=23.1,DU=0.0,RU=0.1,XYZ=-0.06:-0.22:0.94,STOPPED,OK,#89", null, null, null, null, config))); //printDecodedMessage(decoder.Decode(new UnparsedMessage("*450052.0#16[0053],232,SI=60,BL=U,BI=1,MA=U,FMT=SER SEQ UTC CS,OK,#8A", null, null, null, null, config))); }
private void button2_Click(object sender, EventArgs e) { Decoder decoder = new Decoder(); string s = richTextBox1.Text; try { Test o = (Test) decoder.Decode(s); richTextBox1.AppendText("\n" + "ok"); } catch (Exception exc) { richTextBox1.AppendText("\n" + exc.ToString()); } }
public void FindsTheProperOpCodeAndAddressingModeForTheInstruction( byte instruction, Opcode expectedOpcode, AddressingMode expectedAddressingMode) { var registry = new Registry { { instruction, expectedOpcode, null, expectedAddressingMode } }; var decoder = new Decoder(registry); OpcodeAddressModePair pair; var hasInstruction = decoder.TryDecode(instruction, out pair); Assert.That(hasInstruction, Is.True, @"Try Decode returned false for a valid instruction, which is not expected."); Assert.That(pair.Opcode, Is.EqualTo(expectedOpcode)); Assert.That(pair.Mode, Is.EqualTo(expectedAddressingMode)); }
private void button3_Click(object sender, EventArgs e) { Encoder encoder = new Encoder(); encoder.Indent = true; Test o = new Test(); string s = encoder.Encode(o); Decoder decoder = new Decoder(); Test o2 = (Test)decoder.Decode(s); string s2 = encoder.Encode(o2); if (s == s2) richTextBox1.AppendText("OK\n"); else richTextBox1.AppendText("FAIL\n"); }
// 建立子目錄 protected void bn_mkdir_ok_Click(object sender, EventArgs e) { Decoder dcode = new Decoder(); string smkdir = "", mErr = "", fpath = ""; smkdir = tb_al_name.Text.Trim(); if (smkdir == "") mErr = "請輸入子目錄的名稱!\\n"; else { fpath = Server.MapPath(lb_fl_url.Text); if (Directory.Exists(fpath)) { fpath = fpath + "\\" + smkdir + "\\"; if (Directory.Exists(fpath)) mErr = "這個子目錄名稱已經存在!\\n"; else { try { Directory.CreateDirectory(fpath); if (!Directory.Exists(fpath)) mErr = "目錄建立失敗!\\n"; else { #region 建立縮圖目錄 fpath = fpath + "_thumb\\"; Directory.CreateDirectory(fpath); #endregion } } catch (Exception ex) { mErr = ex.ToString() + "\\n"; } } } else mErr = "找不到現在的目錄!\\n"; } if (mErr == "") lt_show.Text = "<script language=\"javascript\">alert(\"目錄建立完成!\\n\");parent.tree_reload('" + Server.UrlEncode(dcode.EnCode(lb_fl_url.Text)) + "');parent.clean_win();</script>"; else lt_show.Text = "<script language=\"javascript\">alert(\"" + mErr + "\");parent.clean_win();</script>"; }
/// <summary> /// Prepares bare minimum information about beatmap /// </summary> /// <param name="file">beatmap path</param> /// <returns></returns> public Beatmap LoadBeatmap(string file) { IBeatmap lazerBeatmap; DifficultyAttributes difficultyAttributes; using (var raw = File.OpenRead(file)) using (var ms = new MemoryStream()) using (var sr = new LineBufferedReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = Decoder.GetDecoder <osu.Game.Beatmaps.Beatmap>(sr); lazerBeatmap = decoder.Decode(sr); lazerBeatmap.BeatmapInfo.Path = Path.GetFileName(file); lazerBeatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash(); var ruleset = Rulesets.GetOrDefault(lazerBeatmap.BeatmapInfo.RulesetID); lazerBeatmap.BeatmapInfo.Ruleset = ruleset.RulesetInfo; difficultyAttributes = ruleset?.CreateDifficultyCalculator(new DummyConversionBeatmap(lazerBeatmap)).Calculate(); lazerBeatmap.BeatmapInfo.StarDifficulty = Math.Round(difficultyAttributes?.StarRating ?? 0, 2); lazerBeatmap.BeatmapInfo.Length = CalculateLength(lazerBeatmap); } short circles, sliders, spinners; circles = sliders = spinners = 0; if (difficultyAttributes is OsuDifficultyAttributes osuAttributes) { circles = (short)osuAttributes.HitCircleCount; spinners = (short)osuAttributes.SpinnerCount; sliders = (short)osuAttributes.SliderCount; } return(new Beatmap { PlayMode = (PlayMode)lazerBeatmap.BeatmapInfo.RulesetID, ArtistRoman = lazerBeatmap.Metadata.Artist, ArtistUnicode = lazerBeatmap.Metadata.ArtistUnicode, TitleRoman = lazerBeatmap.Metadata.Title, TitleUnicode = lazerBeatmap.Metadata.TitleUnicode, DiffName = lazerBeatmap.BeatmapInfo.Version, Md5 = lazerBeatmap.BeatmapInfo.MD5Hash, MapId = lazerBeatmap.BeatmapInfo.OnlineBeatmapID ?? 0, ModPpStars = new PlayModeStars { { (PlayMode)lazerBeatmap.BeatmapInfo.RulesetID, new StarRating { { (int)Mods.Omod, lazerBeatmap.BeatmapInfo.StarDifficulty } } } }, MainBpm = Math.Round(lazerBeatmap.ControlPointInfo.BPMMode), MinBpm = Math.Round(lazerBeatmap.ControlPointInfo.BPMMinimum), MaxBpm = Math.Round(lazerBeatmap.ControlPointInfo.BPMMaximum), Creator = lazerBeatmap.Metadata.AuthorString, ApproachRate = lazerBeatmap.BeatmapInfo.BaseDifficulty.ApproachRate, CircleSize = lazerBeatmap.BeatmapInfo.BaseDifficulty.CircleSize, SliderVelocity = lazerBeatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier, OverallDifficulty = lazerBeatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty, Circles = circles, Dir = Path.GetFileName(Path.GetDirectoryName(file)), MapSetId = lazerBeatmap.BeatmapInfo.BeatmapSet.OnlineBeatmapSetID ?? 0, Mp3Name = lazerBeatmap.Metadata.AudioFile, PreviewTime = Convert.ToInt32(lazerBeatmap.BeatmapInfo.Metadata.PreviewTime), Sliders = sliders, Source = lazerBeatmap.Metadata.Source, Spinners = spinners, StackLeniency = lazerBeatmap.BeatmapInfo.StackLeniency, Tags = lazerBeatmap.Metadata.Tags, TotalTime = Convert.ToInt32(lazerBeatmap.BeatmapInfo.Length), OsuFileName = Path.GetFileName(file), AudioOffset = 0, DrainingTime = 0, ThreadId = 0, EditDate = DateTime.UtcNow, LastPlayed = DateTime.MinValue, LastSync = DateTime.MinValue }); }
public static void AddFreeVariables(Expression exp, Microsoft.Research.DataStructures.IMutableSet <Expression> set, Decoder decoder) { decoder.visitorForVariablesIn.Recurse(exp, set); }
/// <summary>If this request is a POST request, replaces the body of the request with data from the specified stream. /// This will clear and reinitialise all the POST parameter values and file uploads.</summary> /// <param name="body">Stream to read new POST request body from.</param> /// <param name="tempPath">The temporary directory to use for file uploads. Default is <see cref="Path.GetTempPath"/>.</param> /// <param name="storeFileUploadInFileAtSize">The maximum size (in bytes) at which file uploads are stored in memory. /// Any uploads that exceed this limit are written to temporary files on disk. Default is 16 MB.</param> internal void ParsePostBody(Stream body, string tempPath = null, long storeFileUploadInFileAtSize = 16 *1024 *1024) { _fileUploads.Clear(); _postFields.Clear(); if (Method != HttpMethod.Post) { return; } if (Headers.ContentType == HttpPostContentType.ApplicationXWwwFormUrlEncoded) { using (var reader = new StreamReader(body, Encoding.UTF8)) _postFields = HttpHelper.ParseQueryValueParameters(reader).ToNameValuesCollection(); return; } // An excessively long boundary is going to screw up the following algorithm. // (Actually a limit of up to bufferSize - 8 would work, but I think 1024 is more than enough.) if (body == null || Headers.ContentMultipartBoundary == null || Headers.ContentMultipartBoundary.Length > 1024) { return; } if (tempPath == null) { tempPath = Path.GetTempPath(); } // Instead of reallocating a new buffer multiple times, allocate at most two buffers and switch between them as necessary int bufferSize = 65536; byte[] buffer1 = new byte[bufferSize]; byte[] buffer2 = null; byte[] buffer = buffer1; Action <int, int> switchBuffer = (offset, count) => { if (buffer == buffer1) { if (buffer2 == null) { buffer2 = new byte[bufferSize]; } Buffer.BlockCopy(buffer, offset, buffer2, 0, count); buffer = buffer2; } else { Buffer.BlockCopy(buffer, offset, buffer1, 0, count); buffer = buffer1; } }; // Process POST request upload data int bytesRead = body.Read(buffer, 0, bufferSize); if (bytesRead == 0) // premature end of request body { return; } // We expect the input to begin with "--" followed by the boundary followed by "\r\n" byte[] expecting = ("--" + Headers.ContentMultipartBoundary + "\r\n").ToUtf8(); int bufferIndex = bytesRead; while (bufferIndex < expecting.Length) { bytesRead = body.Read(buffer, bufferIndex, buffer.Length - bufferIndex); if (bytesRead == 0) // premature end of request body { return; } bufferIndex += bytesRead; } if (!buffer.SubarrayEquals(0, expecting, 0, expecting.Length)) { return; } bytesRead = bufferIndex - expecting.Length; bufferIndex = expecting.Length; // Now comes the main reading loop bool processingHeaders = true; string currentHeaders = ""; string currentFieldName = null; Stream currentWritingStream = null; bool currentIsFileUpload = false; string currentFileUploadFilename = null; string currentFileUploadContentType = null; string currentFileUploadTempFilename = null; Decoder utf8Decoder = Encoding.UTF8.GetDecoder(); char[] chArr = new char[1]; byte[] lastBoundary = ("\r\n--" + Headers.ContentMultipartBoundary + "--\r\n").ToUtf8(); byte[] middleBoundary = ("\r\n--" + Headers.ContentMultipartBoundary + "\r\n").ToUtf8(); var inMemoryFileUploads = new SortedList <long, List <FileUpload> >(); long inMemoryFileUploadsTotal = 0; while (bufferIndex > 0 || bytesRead > 0) { int writeIndex = 0; if (bytesRead > 0) { if (processingHeaders) { bool newLineFound = false; while (!newLineFound && bytesRead > 0) { int numCh = utf8Decoder.GetChars(buffer, bufferIndex, 1, chArr, 0); bufferIndex++; bytesRead--; if (numCh != 0) { currentHeaders += chArr[0]; } newLineFound = currentHeaders.EndsWith("\r\n\r\n"); } if (newLineFound) { currentIsFileUpload = false; currentFileUploadContentType = null; currentFileUploadFilename = null; currentFileUploadTempFilename = null; currentFieldName = null; currentWritingStream = null; foreach (string header in currentHeaders.Split(new string[] { "\r\n" }, StringSplitOptions.None)) { Match m; if ((m = Regex.Match(header, @"^content-disposition\s*:\s*form-data\s*;(.*)$", RegexOptions.IgnoreCase)).Success) { string v = m.Groups[1].Value; while (v.Length > 0) { m = Regex.Match(v, @"^\s*(\w+)=""([^""]*)""\s*(?:;\s*|$)"); if (!m.Success) { m = Regex.Match(v, @"^\s*(\w+)=([^;]*)\s*(?:;\s*|$)"); } if (!m.Success) { break; } if (m.Groups[1].Value.ToLowerInvariant() == "name") { currentFieldName = m.Groups[2].Value; } else if (m.Groups[1].Value.ToLowerInvariant() == "filename") { currentFileUploadFilename = m.Groups[2].Value; } v = v.Substring(m.Length); } } else if ((m = Regex.Match(header, @"^content-type\s*:\s*(.*)$", RegexOptions.IgnoreCase)).Success) { currentFileUploadContentType = m.Groups[1].Value; } } if (currentFieldName != null) { currentWritingStream = new MemoryStream(); if (currentFileUploadFilename != null) { currentIsFileUpload = true; } } processingHeaders = false; continue; } } else if (bytesRead >= lastBoundary.Length) // processing content { bool boundaryFound = false; bool end = false; int boundaryIndex = buffer.IndexOfSubarray(lastBoundary, bufferIndex, bytesRead); if (boundaryIndex != -1) { boundaryFound = true; end = true; } int middleBoundaryIndex = buffer.IndexOfSubarray(middleBoundary, bufferIndex, bytesRead); if (middleBoundaryIndex != -1 && (!boundaryFound || middleBoundaryIndex < boundaryIndex)) { boundaryFound = true; boundaryIndex = middleBoundaryIndex; end = false; } int howMuchToWrite = boundaryFound // If we have encountered the boundary, write all the data up to it ? howMuchToWrite = boundaryIndex - bufferIndex // Write as much of the data to the output stream as possible, but leave enough so that we can still recognise the boundary : howMuchToWrite = bytesRead - lastBoundary.Length; // this is never negative because of the "if" we're in // Write the aforementioned amount of data to the output stream if (howMuchToWrite > 0 && currentWritingStream != null) { // If we're currently processing a file upload in memory, and it takes the total file uploads over the limit... if (currentIsFileUpload && currentWritingStream is MemoryStream && ((MemoryStream)currentWritingStream).Length + inMemoryFileUploadsTotal + howMuchToWrite > storeFileUploadInFileAtSize) { var memory = (MemoryStream)currentWritingStream; var inMemoryKeys = inMemoryFileUploads.Keys; if (inMemoryKeys.Count > 0 && memory.Length < inMemoryKeys[inMemoryKeys.Count - 1]) { // ... switch the largest one to a temporary file var lastKey = inMemoryKeys[inMemoryKeys.Count - 1]; var biggestUpload = inMemoryFileUploads[lastKey][0]; inMemoryFileUploads[lastKey].RemoveAt(0); Stream fileStream; biggestUpload.LocalFilename = HttpInternalObjects.RandomTempFilepath(tempPath, out fileStream); fileStream.Write(biggestUpload.Data, 0, biggestUpload.Data.Length); fileStream.Close(); fileStream.Dispose(); inMemoryFileUploadsTotal -= biggestUpload.Data.LongLength; biggestUpload.Data = null; if (inMemoryFileUploads[lastKey].Count == 0) { inMemoryFileUploads.Remove(lastKey); } } else { // ... switch this one to a temporary file currentFileUploadTempFilename = HttpInternalObjects.RandomTempFilepath(tempPath, out currentWritingStream); memory.WriteTo(currentWritingStream); memory.Close(); memory.Dispose(); } } currentWritingStream.Write(buffer, bufferIndex, howMuchToWrite); } // If we encountered the boundary, add this field to _postFields or this upload to _fileUploads or inMemoryFileUploads if (boundaryFound) { if (currentWritingStream != null) { currentWritingStream.Close(); if (!currentIsFileUpload) { // It's a normal field _postFields[currentFieldName].Add(Encoding.UTF8.GetString(((MemoryStream)currentWritingStream).ToArray())); } else { // It's a file upload var fileUpload = new FileUpload(currentFileUploadContentType, currentFileUploadFilename); if (currentFileUploadTempFilename != null) { // The file upload has already been written to disk fileUpload.LocalFilename = currentFileUploadTempFilename; } else { // The file upload is still in memory. Keep track of it in inMemoryFileUploads so that we can still write it to disk later if necessary var memory = (MemoryStream)currentWritingStream; fileUpload.Data = memory.ToArray(); inMemoryFileUploads.AddSafe(fileUpload.Data.LongLength, fileUpload); inMemoryFileUploadsTotal += fileUpload.Data.LongLength; } _fileUploads[currentFieldName] = fileUpload; } currentWritingStream.Dispose(); currentWritingStream = null; } // If that was the final boundary, we are done if (end) { break; } // Consume the boundary and go back to processing headers bytesRead -= boundaryIndex - bufferIndex + middleBoundary.Length; bufferIndex = boundaryIndex + middleBoundary.Length; processingHeaders = true; currentHeaders = ""; utf8Decoder.Reset(); continue; } else { // No boundary there. Received data has been written to the currentWritingStream above. // Now copy the remaining little bit (which may contain part of the bounary) into a new buffer switchBuffer(bufferIndex + howMuchToWrite, bytesRead - howMuchToWrite); bytesRead -= howMuchToWrite; writeIndex = bytesRead; } } else if (bufferIndex > 0) { // We are processing content, but there is not enough data in the buffer to ensure that it doesn't contain part of the boundary. // Therefore, just copy the data to a new buffer and continue receiving more switchBuffer(bufferIndex, bytesRead); writeIndex = bytesRead; } } bufferIndex = 0; // We need to read enough data to contain the boundary do { bytesRead = body.Read(buffer, writeIndex, bufferSize - writeIndex); if (bytesRead == 0) // premature end of content { if (currentWritingStream != null) { currentWritingStream.Close(); currentWritingStream.Dispose(); } return; } writeIndex += bytesRead; }while (writeIndex < lastBoundary.Length); bytesRead = writeIndex; } }
public Instr64Decoder(Decoder <OpenRISCDisassembler, Mnemonic, OpenRISCInstruction> dec32bit, Decoder <OpenRISCDisassembler, Mnemonic, OpenRISCInstruction> dec64bit) { this.dec32bit = dec32bit; this.dec64bit = dec64bit; }
protected MessageToMessageCodec() { this.encoder = new Encoder(this); this.decoder = new Decoder(this); }
public static T DecodeJsonObject <T>(object jsonObj) { Decoder decoder = GetDecoder(typeof(T)); return((T)decoder(typeof(T), jsonObj)); }
static OpenRISCDisassembler() { var invalid = Instr(Mnemonic.Invalid, InstrClass.Invalid); rootDecoder = Mask(26, 6, "OpenRISC", // 00 Instr(Mnemonic.l_j, TD, Pc26), Instr(Mnemonic.l_jal, TDC, Pc26), Instr64( Instr(Mnemonic.l_adrp, RD, Page(19)), Instr(Mnemonic.l_adrp, RD, Page(21))), Instr(Mnemonic.l_bnf, TD | InstrClass.Conditional, Pc26), Instr(Mnemonic.l_bf, TD | InstrClass.Conditional, Pc26), Instr(Mnemonic.l_nop, InstrClass.Linear | InstrClass.Padding), Mask(16, 1, " 0x06", Instr(Mnemonic.l_movhi, RD, Iu16), Instr(Mnemonic.l_macrc, RD)), invalid, Sparse(23, 3, " 0x08", invalid, (0b000, Instr(Mnemonic.l_sys, Iu16)), (0b010, Instr(Mnemonic.l_trap, Iu16)), (0b100, Instr(Mnemonic.l_msync)), (0b101, Instr(Mnemonic.l_psync)), (0b110, Instr(Mnemonic.l_csync))), Instr(Mnemonic.l_rfe, TD), Nyi("0x0A"), invalid, invalid, invalid, invalid, invalid, // 10 invalid, Instr(Mnemonic.l_jr, TD, RB), Instr(Mnemonic.l_jalr, TDC, RB), Instr(Mnemonic.l_maci, RA, Is16), invalid, invalid, invalid, invalid, invalid, invalid, Instr(Mnemonic.l_lf, RD, Mo(16, PrimitiveType.Real32)), Instr(Mnemonic.l_lwa, RD, Mo(16, PrimitiveType.Word32)), invalid, // 0x1C - custom invalid, // 0x1D - custom invalid, // 0x1E - custom invalid, // 0x1F - custom // 20 Instr64( invalid, Instr(Mnemonic.l_ld, RD, Mo(16, PrimitiveType.Word64))), Instr(Mnemonic.l_lwz, RD, Mo(16, PrimitiveType.Word32)), Instr(Mnemonic.l_lws, RD, Mo(16, PrimitiveType.Int32)), Instr(Mnemonic.l_lbz, RD, Mo(16, PrimitiveType.Byte)), Instr(Mnemonic.l_lbs, RD, Mo(16, PrimitiveType.SByte)), Instr(Mnemonic.l_lhz, RD, Mo(16, PrimitiveType.Word16)), Instr(Mnemonic.l_lhs, RD, Mo(16, PrimitiveType.Int16)), Instr(Mnemonic.l_addi, RD, RA, Is16), Instr(Mnemonic.l_addic, RD, RA, Is16), Instr(Mnemonic.l_andi, RD, RA, Iu16), Instr(Mnemonic.l_ori, RD, RA, Iu16), Instr(Mnemonic.l_xori, RD, RA, Iu16), Instr(Mnemonic.l_muli, RD, RA, Is16), Instr(Mnemonic.l_mfspr, RD, RA, Spr(Bf((0, 16)))), Mask(6, 2, " 0x2E", Instr(Mnemonic.l_slli, RD, RA, Iu6), Instr(Mnemonic.l_srli, RD, RA, Iu6), Instr(Mnemonic.l_srai, RD, RA, Iu6), Instr(Mnemonic.l_rori, RD, RA, Iu6)), Sparse(21, 5, " 0x2F", invalid, (0x0, Instr(Mnemonic.l_sfeqi, RA, Isu16)), (0x1, Instr(Mnemonic.l_sfnei, RA, Isu16)), (0x2, Instr(Mnemonic.l_sfgtui, RA, Isu16)), (0x3, Instr(Mnemonic.l_sfgeui, RA, Isu16)), (0x4, Instr(Mnemonic.l_sfltui, RA, Isu16)), (0x5, Instr(Mnemonic.l_sfleui, RA, Isu16)), (0xA, Instr(Mnemonic.l_sfgtsi, RA, Is16)), (0xB, Instr(Mnemonic.l_sfgesi, RA, Is16)), (0xC, Instr(Mnemonic.l_sfltsi, RA, Is16)), (0xD, Instr(Mnemonic.l_sflesi, RA, Is16))), // 30 Instr(Mnemonic.l_mtspr, RA, RB, Spr(Bf((21, 5), (0, 11)))), Nyi("0x31"), Nyi("0x32"), Nyi("0x33"), Instr64( invalid, Instr(Mnemonic.l_sd, Mo(16, Bf((21, 5), (0, 11)), PrimitiveType.Word32), RB)), Instr(Mnemonic.l_sw, Mo(16, Bf((21, 5), (0, 11)), PrimitiveType.Word32), RB), Instr(Mnemonic.l_sb, Mo(16, Bf((21, 5), (0, 11)), PrimitiveType.Byte), RB), Instr(Mnemonic.l_sh, Mo(16, Bf((21, 5), (0, 11)), PrimitiveType.Word16), RB), Mask(8, 2, " 0x38", Mask(0, 4, " 0x38-0", Instr(Mnemonic.l_add, RD, RA, RB), Instr(Mnemonic.l_addc, RD, RA, RB), Instr(Mnemonic.l_sub, RD, RA, RB), Instr(Mnemonic.l_and, RD, RA, RB), Instr(Mnemonic.l_or, RD, RA, RB), Instr(Mnemonic.l_xor, RD, RA, RB), invalid, invalid, Mask(6, 2, " 0x30-0-8", Instr(Mnemonic.l_sll, RD, RA, RB), Instr(Mnemonic.l_srl, RD, RA, RB), Instr(Mnemonic.l_sra, RD, RA, RB), Instr(Mnemonic.l_ror, RD, RA, RB)), invalid, invalid, invalid, Nyi(" 0x38-0-C"), Nyi(" 0x38-0-D"), Instr(Mnemonic.l_cmov, RD, RA, RB), Instr(Mnemonic.l_ff1, RD, RA)), Sparse(0, 4, " 0x38-1", invalid, (0xF, Instr(Mnemonic.l_fl1, RD, RA))), Nyi(" 0x38-2"), Sparse(0, 4, " 0x38-3", invalid, (0x6, Instr(Mnemonic.l_mul, RD, RA, RB)), (0x7, Instr(Mnemonic.l_muld, RA, RB)), (0x9, Instr(Mnemonic.l_div, RD, RA, RB)), (0xA, Instr(Mnemonic.l_divu, RD, RA, RB)), (0xB, Instr(Mnemonic.l_mulu, RD, RA, RB)), (0xC, Instr(Mnemonic.l_muldu, RA, RB)))), Sparse(21, 5, " 0x39", Nyi("0x39"), (0x0, Instr(Mnemonic.l_sfeq, RA, RB)), (0x1, Instr(Mnemonic.l_sfne, RA, RB)), (0x2, Instr(Mnemonic.l_sfgtu, RA, RB)), (0x3, Instr(Mnemonic.l_sfgeu, RA, RB)), (0x4, Instr(Mnemonic.l_sfltu, RA, RB)), (0x5, Instr(Mnemonic.l_sfleu, RA, RB)), (0xA, Instr(Mnemonic.l_sfgts, RA, RB)), (0xB, Instr(Mnemonic.l_sfges, RA, RB)), (0xC, Instr(Mnemonic.l_sflts, RA, RB)), (0xD, Instr(Mnemonic.l_sfles, RA, RB))), Nyi("0x3A"), Nyi("0x3B"), Nyi("0x3C"), Nyi("0x3D"), Nyi("0x3E"), Nyi("0x3F")); }
public static bool IsConstant(Expression exp, out object value, out Type type, Decoder decoder) { VisitorForValueOf visitor = decoder.visitorForValueOf; bool result = Decode(exp, visitor, decoder); value = visitor.Value; type = visitor.Type; return(result); }
/// <summary> /// Resets the filter. /// </summary> /// <remarks> /// Resets the filter. /// </remarks> public override void Reset() { Decoder.Reset(); base.Reset(); }
public static bool IsIsInst(Expression exp, out Type type, out Expression arg, Decoder decoder) { VisitorForIsInst visitor = decoder.visitorForIsInst; bool result = Decode(exp, visitor, decoder); type = visitor.Type; arg = visitor.Argument; return(result); }
public CharsetDecoder(Encoding enc) { this.enc = enc; this.decoder = enc.GetDecoder(); }
public static void Decrypt() { Decoder decoder = new Decoder(); string[] files = Directory.GetFiles(@"In\Encrypted - CSV", "*.csv"); string output = @"Out\Decrypted - CSV"; int filesAmount = 0; foreach (string file in files) { filesAmount++; } if (filesAmount == 0) { MessageBox.Show("No CSV files were found in the folder \"In\\Encrypted - CSV.\"" + Environment.NewLine + "Place encrypted files in the folder and try again.", "No Files Found", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } try { foreach (string str in files) { FileInfo fileInfo = new FileInfo(str); using (FileStream fileStream1 = new FileStream(str, FileMode.Open)) { using (FileStream fileStream2 = new FileStream(Path.Combine(output, Path.GetFileName(str)), FileMode.Create)) { byte[] numArray = new byte[5]; fileStream1.Read(numArray, 0, 5); byte[] buffer = new byte[4]; fileStream1.Read(buffer, 0, 4); int int32 = BitConverter.ToInt32(buffer, 0); decoder.SetDecoderProperties(numArray); decoder.Code((Stream)fileStream1, (Stream)fileStream2, fileStream1.Length, (long)int32, (ICodeProgress)null); fileStream2.Flush(); fileStream2.Close(); } fileStream1.Close(); } } var success = MessageBox.Show("Successfully Decrypted CSV Files!" + Environment.NewLine + "Select OK to open the folder, else select cancel!", "Success", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); if (success == DialogResult.OK) { Process.Start(output); } } catch (Exception e) { MessageBox.Show("An error occured, please try again or contact someone on the Ultrapowa Network." + Environment.NewLine + "Error: " + e, "Error - Key:1", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public ExpectList getFileData(string filename) { ExpectList ret = new ExpectList(); FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read); StreamReader str = new StreamReader(file, Encoding.Default); try { //用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0, //表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符. Decoder d = Encoding.Default.GetDecoder(); int lcnt = 0; string txtline; while ((txtline = str.ReadLine()) != null) { lcnt++; if (lcnt <= 1) { continue;//标题跳过 } if (txtline.Trim().Length == 0) { continue; } txtline = txtline.Replace(" ", ","); string[] items = txtline.Split(','); if (items.Length != 2) { throw new Exception(string.Format("{0}第{1}行数据异常!", filename, lcnt)); } ExpectData ed = new ExpectData(); ed.OpenCode = string.Join(",", items[1].ToCharArray()); string strOrg = items[0]; string[] strOrgs = strOrg.Split('-'); if (strOrgs.Length > 1) { string strDate = strOrgs[0]; string strId = strOrgs[1]; string DstrDate = string.Format("{0}-{1}-{2}", strDate.Substring(0, 4), strDate.Substring(4, 2), strDate.Substring(6)); DateTime etime = DateTime.Parse(DstrDate); ed.OpenTime = etime.AddMinutes(int.Parse(strId)).AddSeconds(6); ed.Expect = ed.OpenTime.ToString("yyyy-MM-dd HH-mm-SS").Replace("-", "").Replace("/", "").Replace(":", "").Replace(" ", "").Substring(0, 12); } else { ed.Expect = strOrg; string strDate = strOrg.Substring(0, 8); string strId = ed.Expect.Substring(8); string DstrDate = string.Format("{0}-{1}-{2} {3}:{4}:{5}", strDate.Substring(0, 4), strDate.Substring(4, 2), strDate.Substring(6), strId.Substring(0, 2), strId.Substring(2), "06"); DateTime etime = DateTime.Parse(DstrDate); ed.OpenTime = etime; } //ed.Expect = items[0].Replace("-", ""); //if (ed.OpenCode == "0,0,0,0,0") ret.Add(ed); } str.Close(); //file.Close(); } catch (IOException e) { str.Close(); //file.Close(); throw e; } return(ret); }
static MilStd1750Disassembler() { var invalid = Instr(Mnemonic.invalid, InstrClass.Invalid); var nyi = Nyi(""); rootDecoder = Mask(8, 8, "MIL-STD-1750", new Decoder <MilStd1750Disassembler, Mnemonic, Instruction>[256] { // 00 Instr(Mnemonic.lb, br12), Instr(Mnemonic.lb, br13), Instr(Mnemonic.lb, br14), Instr(Mnemonic.lb, br15), Instr(Mnemonic.dlb, br12), Instr(Mnemonic.dlb, br13), Instr(Mnemonic.dlb, br14), Instr(Mnemonic.dlb, br15), Instr(Mnemonic.stlb, br12), Instr(Mnemonic.stlb, br13), Instr(Mnemonic.stlb, br14), Instr(Mnemonic.stlb, br15), Instr(Mnemonic.dstb, br12), Instr(Mnemonic.dstb, br13), Instr(Mnemonic.dstb, br14), Instr(Mnemonic.dstb, br15), // 10 Instr(Mnemonic.ab, br12), Instr(Mnemonic.ab, br13), Instr(Mnemonic.ab, br14), Instr(Mnemonic.ab, br15), Instr(Mnemonic.sbb, br12), Instr(Mnemonic.sbb, br13), Instr(Mnemonic.sbb, br14), Instr(Mnemonic.sbb, br15), Instr(Mnemonic.mb, br12), Instr(Mnemonic.mb, br13), Instr(Mnemonic.mb, br14), Instr(Mnemonic.mb, br15), Instr(Mnemonic.db, br12), Instr(Mnemonic.db, br13), Instr(Mnemonic.db, br14), Instr(Mnemonic.db, br15), // 20 Instr(Mnemonic.fab, br12), Instr(Mnemonic.fab, br13), Instr(Mnemonic.fab, br14), Instr(Mnemonic.fab, br15), Instr(Mnemonic.fsb, br12), Instr(Mnemonic.fsb, br13), Instr(Mnemonic.fsb, br14), Instr(Mnemonic.fsb, br15), Instr(Mnemonic.fmb, br12), Instr(Mnemonic.fmb, br13), Instr(Mnemonic.fmb, br14), Instr(Mnemonic.fmb, br15), Instr(Mnemonic.fdb, br12), Instr(Mnemonic.fdb, br13), Instr(Mnemonic.fdb, br14), Instr(Mnemonic.fdb, br15), // 30 Instr(Mnemonic.orb, br12), Instr(Mnemonic.orb, br13), Instr(Mnemonic.orb, br14), Instr(Mnemonic.orb, br15), Instr(Mnemonic.andb, br12), Instr(Mnemonic.andb, br13), Instr(Mnemonic.andb, br14), Instr(Mnemonic.andb, br15), Instr(Mnemonic.cb, br12), Instr(Mnemonic.cb, br13), Instr(Mnemonic.cb, br14), Instr(Mnemonic.cb, br15), Instr(Mnemonic.fcb, br12), Instr(Mnemonic.fcb, br13), Instr(Mnemonic.fcb, br14), Instr(Mnemonic.fcb, br15), // 40 Mask(4, 4, " brx br12", // a Instr(Mnemonic.lbx, bx12), // a Instr(Mnemonic.dlbx, bx12), // a Instr(Mnemonic.stbx, bx12), // a Instr(Mnemonic.dstx, bx12), // a Instr(Mnemonic.abx, bx12), // a Instr(Mnemonic.sbbx, bx12), // a Instr(Mnemonic.mbx, bx12), // a Instr(Mnemonic.dbx, bx12), // a Instr(Mnemonic.fabx, bx12), // a Instr(Mnemonic.fsbx, bx12), // a Instr(Mnemonic.fmbx, bx12), // a Instr(Mnemonic.fdbx, bx12), // a Instr(Mnemonic.cbx, bx12), // a Instr(Mnemonic.fcbx, bx12), // a Instr(Mnemonic.andx, bx12), // a Instr(Mnemonic.orbx, bx12)), // a Mask(4, 4, " brx br13", // a Instr(Mnemonic.lbx, bx13), // a Instr(Mnemonic.dlbx, bx13), // a Instr(Mnemonic.stbx, bx13), // a Instr(Mnemonic.dstx, bx13), // a Instr(Mnemonic.abx, bx13), // a Instr(Mnemonic.sbbx, bx13), // a Instr(Mnemonic.mbx, bx13), // a Instr(Mnemonic.dbx, bx13), // a Instr(Mnemonic.fabx, bx13), // a Instr(Mnemonic.fsbx, bx13), // a Instr(Mnemonic.fmbx, bx13), // a Instr(Mnemonic.fdbx, bx13), // a Instr(Mnemonic.cbx, bx13), // a Instr(Mnemonic.fcbx, bx13), // a Instr(Mnemonic.andx, bx13), // a Instr(Mnemonic.orbx, bx13)), // a Mask(4, 4, " brx br14", // a Instr(Mnemonic.lbx, bx14), // a Instr(Mnemonic.dlbx, bx14), // a Instr(Mnemonic.stbx, bx14), // a Instr(Mnemonic.dstx, bx14), // a Instr(Mnemonic.abx, bx14), // a Instr(Mnemonic.sbbx, bx14), // a Instr(Mnemonic.mbx, bx14), // a Instr(Mnemonic.dbx, bx14), // a Instr(Mnemonic.fabx, bx14), // a Instr(Mnemonic.fsbx, bx14), // a Instr(Mnemonic.fmbx, bx14), // a Instr(Mnemonic.fdbx, bx14), // a Instr(Mnemonic.cbx, bx14), // a Instr(Mnemonic.fcbx, bx14), // a Instr(Mnemonic.andx, bx14), // a Instr(Mnemonic.orbx, bx14)), // a Mask(4, 4, " brx br15", // a Instr(Mnemonic.lbx, bx15), // a Instr(Mnemonic.dlbx, bx15), // a Instr(Mnemonic.stbx, bx15), // a Instr(Mnemonic.dstx, bx15), // a Instr(Mnemonic.abx, bx15), // a Instr(Mnemonic.sbbx, bx15), // a Instr(Mnemonic.mbx, bx15), // a Instr(Mnemonic.dbx, bx15), // a Instr(Mnemonic.fabx, bx15), // a Instr(Mnemonic.fsbx, bx15), // a Instr(Mnemonic.fmbx, bx15), // a Instr(Mnemonic.fdbx, bx15), // a Instr(Mnemonic.cbx, bx15), // a Instr(Mnemonic.fcbx, bx15), // a Instr(Mnemonic.andx, bx15), // a Instr(Mnemonic.orbx, bx15)), // a invalid, invalid, invalid, invalid, Instr(Mnemonic.xio, InstrClass.Linear | InstrClass.Privileged, Xio), // ab Instr(Mnemonic.vio, _("vio")), // ab Mask(0, 4, " imm", // ab invalid, Instr(Mnemonic.aim, Ra, IM), Instr(Mnemonic.sim, Ra, IM), Instr(Mnemonic.mim, Ra, IM), Instr(Mnemonic.msim, Ra, IM), Instr(Mnemonic.dim, Ra, IM), Instr(Mnemonic.dvim, Ra, IM), Instr(Mnemonic.andm, Ra, IM), Instr(Mnemonic.orim, Ra, IM), Instr(Mnemonic.xorm, Ra, IM), Instr(Mnemonic.cim, Ra, IM), Instr(Mnemonic.nim, Ra, IM), invalid, invalid, invalid, invalid), invalid, invalid, invalid, invalid, Instr(Mnemonic.bif, Imm8), // c // 50 Instr(Mnemonic.sb, N, Dx_w16), Instr(Mnemonic.sbr, N, Rb), Instr(Mnemonic.sbi, N, Ix_w16), Instr(Mnemonic.rb, N, Dx_w16), Instr(Mnemonic.rbr, N, Rb), Instr(Mnemonic.rbi, N, Ix_w16), Instr(Mnemonic.tb, _("tb")), Instr(Mnemonic.tbr, N, Rb), Instr(Mnemonic.tbi, _("tbi")), Instr(Mnemonic.tsb, _("tsb")), Instr(Mnemonic.svbr, _("svbr")), invalid, Instr(Mnemonic.rvbr, _("rvbr")), invalid, Instr(Mnemonic.tvbr, _("tvbr")), invalid, // 60 Instr(Mnemonic.sll, Rb, ISP_4), Instr(Mnemonic.srl, Rb, ISP_4), Instr(Mnemonic.sra, Rb, ISP_4), Instr(Mnemonic.slc, Rb, ISP_4), invalid, Instr(Mnemonic.dsll, Rb, ISP_4), Instr(Mnemonic.dsrl, Rb, ISP_4), Instr(Mnemonic.dsra, Rb, ISP_4), Instr(Mnemonic.dslc, Rb, ISP_4), invalid, Instr(Mnemonic.slr, Ra, Rb), Instr(Mnemonic.sar, Ra, Rb), Instr(Mnemonic.scr, Ra, Rb), Instr(Mnemonic.dslr, Ra, Rb), Instr(Mnemonic.dsar, Ra, Rb), Instr(Mnemonic.dscr, Ra, Rb), // 70 Instr(Mnemonic.jc, InstrClass.ConditionalTransfer, N, ICR), Instr(Mnemonic.jci, _("jci")), Instr(Mnemonic.js, InstrClass.Transfer | InstrClass.Call, Ra, Ax), Instr(Mnemonic.soj, InstrClass.ConditionalTransfer, Ra, Ax), Instr(Mnemonic.br, InstrClass.Transfer, ICR), Instr(Mnemonic.bez, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.blt, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.bex, InstrClass.ConditionalTransfer, Imm4), Instr(Mnemonic.ble, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.bgt, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.bnz, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.bge, InstrClass.ConditionalTransfer, ICR), Instr(Mnemonic.lsti, _("lsti")), // b Instr(Mnemonic.lst, _("lst")), // b Instr(Mnemonic.sjs, InstrClass.Transfer | InstrClass.Call, Ra, Ax), Instr(Mnemonic.urs, InstrClass.Transfer | InstrClass.Return, Ra), // 80 Instr(Mnemonic.l, Ra, Dx_w16), Instr(Mnemonic.lr, Ra, Rb), Instr(Mnemonic.lisp, Ra, ISP_0), Instr(Mnemonic.lisn, Ra, ISP_0), Instr(Mnemonic.li, _("li")), Instr(Mnemonic.lim, Ra, Imx_w16), Instr(Mnemonic.dl, Ra, Dx_w32), Instr(Mnemonic.dlr, Ra, Rb), Instr(Mnemonic.dli, _("dli")), Instr(Mnemonic.lm, N, Dx_w16), Instr(Mnemonic.efl, Ra, Dx_r48), Instr(Mnemonic.lub, Ra, Dx_w16), Instr(Mnemonic.llb, Ra, Dx_w16), Instr(Mnemonic.lubi, _("lubi")), Instr(Mnemonic.llbi, _("llbi")), Instr(Mnemonic.popm, Ra, Rb), // 90 Instr(Mnemonic.st, Ra, Dx_w16), Instr(Mnemonic.stc, N, Dx_w16), Instr(Mnemonic.stci, _("stci ")), Instr(Mnemonic.mov, Ra, Rb), Instr(Mnemonic.sti, _("sti ")), invalid, Instr(Mnemonic.dst, Ra, Dx_w32), Instr(Mnemonic.srm, _("srm ")), Instr(Mnemonic.dsti, Ra, Ix_w32), Instr(Mnemonic.stm, _("stm ")), Instr(Mnemonic.efst, Ra, Dx_r48), Instr(Mnemonic.stub, Ra, Dx_w16), Instr(Mnemonic.stlb, Ra, Dx_w16), Instr(Mnemonic.subi, _("subi")), Instr(Mnemonic.slbi, _("slbi")), Instr(Mnemonic.pshm, Ra, Rb), // A0 Instr(Mnemonic.a, Ra, Dx_w16), Instr(Mnemonic.ar, Ra, Rb), Instr(Mnemonic.aisp, Ra, ISP_0), Instr(Mnemonic.incm, ISP_4, Dx_w16), Instr(Mnemonic.abs, Ra, Rb), Instr(Mnemonic.dabs, Ra, Rb), Instr(Mnemonic.da, Ra, Dx_w32), Instr(Mnemonic.dar, Ra, Rb), Instr(Mnemonic.fa, Ra, Dx_w16), Instr(Mnemonic.far, Ra, Rb), Instr(Mnemonic.efa, Ra, Dx_r48), Instr(Mnemonic.efar, Ra, Rb), Instr(Mnemonic.fabs, Ra, Rb), invalid, invalid, invalid, // B0 Instr(Mnemonic.s, Ra, Dx_w16), Instr(Mnemonic.sr, Ra, Rb), Instr(Mnemonic.sisp, Ra, ISP_0), Instr(Mnemonic.decm, ISP_4, Dx_w16), Instr(Mnemonic.neg, Ra, Rb), Instr(Mnemonic.dneg, Ra, Rb), Instr(Mnemonic.ds, Ra, Dx_w32), Instr(Mnemonic.dsr, Ra, Rb), Instr(Mnemonic.fs, Ra, Dx_r32), Instr(Mnemonic.fsr, Ra, Rb), Instr(Mnemonic.efs, Ra, Dx_r48), Instr(Mnemonic.efsr, Ra, Rb), Instr(Mnemonic.fneg, Ra, Rb), invalid, invalid, invalid, // C0 Instr(Mnemonic.ms, Ra, Dx_w16), Instr(Mnemonic.msr, Ra, Rb), Instr(Mnemonic.misp, Rb, ISP_4), Instr(Mnemonic.misn, Rb, ISP_4), Instr(Mnemonic.m, Ra, Dx_w16), Instr(Mnemonic.mr, Ra, Rb), Instr(Mnemonic.dm, Ra, Dx_w32), Instr(Mnemonic.dmr, Ra, Rb), Instr(Mnemonic.fm, Ra, Dx_w16), Instr(Mnemonic.fmr, Ra, Rb), Instr(Mnemonic.efm, Ra, Dx_r48), Instr(Mnemonic.efmr, Ra, Rb), invalid, invalid, invalid, invalid, // D0 Instr(Mnemonic.dv, _("dv")), Instr(Mnemonic.dvr, _("dvr")), Instr(Mnemonic.disp, Ra, ISP_0), Instr(Mnemonic.disn, Ra, ISP_0), Instr(Mnemonic.d, Ra, Dx_w16), Instr(Mnemonic.dr, Ra, Rb), Instr(Mnemonic.dd, Ra, Dx_w32), Instr(Mnemonic.ddr, Ra, Rb), Instr(Mnemonic.fd, Ra, Dx_r32), Instr(Mnemonic.fdr, Ra, Rb), Instr(Mnemonic.efd, Ra, Dx_r48), Instr(Mnemonic.efdr, Ra, Rb), invalid, invalid, invalid, invalid, // E0 Instr(Mnemonic.or, Ra, Dx_w16), Instr(Mnemonic.orr, Ra, Rb), Instr(Mnemonic.and, Ra, Dx_w16), Instr(Mnemonic.andr, Ra, Rb), Instr(Mnemonic.xor, Ra, Dx_w16), Instr(Mnemonic.xorr, Ra, Rb), Instr(Mnemonic.n, Ra, Dx_w16), Instr(Mnemonic.nr, Ra, Rb), Instr(Mnemonic.fix, Ra, Rb), Instr(Mnemonic.flt, Ra, Rb), Instr(Mnemonic.efix, Ra, Rb), Instr(Mnemonic.eflt, Ra, Rb), Select((0, 4), Is0, " EC", Instr(Mnemonic.xbr, Ra), nyi), Instr(Mnemonic.xwr, Ra, Rb), invalid, invalid, // F0 Instr(Mnemonic.c, Ra, Dx_w16), Instr(Mnemonic.cr, Ra, Rb), Instr(Mnemonic.cisp, Ra, ISP_0), Instr(Mnemonic.cisn, Ra, ISP_0), Instr(Mnemonic.cbl, Ra, Dx_w16), invalid, Instr(Mnemonic.dc, Ra, Dx_w32), Instr(Mnemonic.dcr, Ra, Rb), Instr(Mnemonic.fc, Ra, Dx_r32), Instr(Mnemonic.fcr, Ra, Rb), Instr(Mnemonic.efc, Ra, Dx_r48), Instr(Mnemonic.efcr, Ra, Rb), invalid, invalid, invalid, Select((0, 8), Is0, " 0xFF", Instr(Mnemonic.nop, InstrClass.Linear | InstrClass.Padding), Select((0, 8), u => u == 0xFF, Instr(Mnemonic.bpt, InstrClass.Terminates), invalid)) });
public VisitorForDispatch(Decoder decoder) { Contract.Requires(decoder != null); this.decoder = decoder; }
protected static bool Decode <Visitor>(Expression exp, Visitor v, Decoder decoder) where Visitor : QueryVisitor { Contract.Requires(decoder != null); return(decoder.Context.ExpressionContext.Decode <Unit, bool, Visitor>(exp, v, Unit.Value)); }
// -------------------------------------------------------------------------------------------- // Use the Decoder.Convert() method to convert a file of encoded bytes to a file of characters. // -------------------------------------------------------------------------------------------- static void DecoderConvert(String inputFileName, String outputFileName, Encoding enc) { // Convert an input file of of encoded bytes to an output file characters. // StreamWriter could convert the input file for us, but we'll perform the conversion // ourselves. StreamWriter outputFile = new StreamWriter(outputFileName, false, Encoding.Unicode); // Read the input as a binary file so we can detect the Byte Order Mark. FileStream fs = new FileStream(inputFileName, FileMode.Open); BinaryReader inputFile = new BinaryReader(fs); // Get a Decoder. Decoder decoder = enc.GetDecoder(); // Guarantee the output buffer large enough to convert a few characters. int UseBufferSize = 64; if (UseBufferSize < enc.GetMaxCharCount(10)) { UseBufferSize = enc.GetMaxCharCount(10); } char[] chars = new char[UseBufferSize]; // Intentionally make the input byte buffer larger than the output character buffer so the // conversion loop executes more than one cycle. byte[] bytes = new byte[UseBufferSize * 4]; int bytesRead; do { // Read at most the number of bytes that will fit in the input buffer. The // return value is the actual number of bytes read, or zero if no bytes remain. bytesRead = inputFile.Read(bytes, 0, UseBufferSize * 4); bool completed = false; int byteIndex = 0; int bytesUsed; int charsUsed; while (!completed) { // If this is the last input data, flush the decoder's internal buffer and state. bool flush = (bytesRead == 0); decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, UseBufferSize, flush, out bytesUsed, out charsUsed, out completed); // The conversion produced the number of characters indicated by charsUsed. Write that number // of characters to the output file. outputFile.Write(chars, 0, charsUsed); // Increment byteIndex to the next block of bytes in the input buffer, if any, to convert. byteIndex += bytesUsed; } }while(bytesRead != 0); outputFile.Close(); fs.Close(); inputFile.Close(); }
private static void testHighLevelDecodeString(String expectedString, String b) { BitArray bits = EncoderTest.toBitArray(EncoderTest.stripSpace(b)); Assert.AreEqual(expectedString, Decoder.highLevelDecode(EncoderTest.toBooleanArray(bits)), "highLevelDecode() failed for input bits: " + b); }
public bool TryReadChars(char[] chars, int offset, int count, out int actual) { DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length)); if (_type == ValueHandleType.Unicode) { return(TryReadUnicodeChars(chars, offset, count, out actual)); } if (_type != ValueHandleType.UTF8) { actual = 0; return(false); } int charOffset = offset; int charCount = count; byte[] bytes = _bufferReader.Buffer; int byteOffset = _offset; int byteCount = _length; bool insufficientSpaceInCharsArray = false; var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); while (true) { while (charCount > 0 && byteCount > 0) { // fast path for codepoints U+0000 - U+007F byte b = bytes[byteOffset]; if (b >= 0x80) { break; } chars[charOffset] = (char)b; byteOffset++; byteCount--; charOffset++; charCount--; } if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray) { break; } int actualByteCount; int actualCharCount; try { // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount)) { actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset); actualByteCount = byteCount; } else { Decoder decoder = encoding.GetDecoder(); // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit actualByteCount = Math.Min(charCount, byteCount); // We use a decoder so we don't error if we fall across a character boundary actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset); // We might have gotten zero characters though if < 4 bytes were requested because // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8 // and represented as TWO chars (high+low surrogate) // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes) while (actualCharCount == 0) { // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte // if we don't bail out since the while loop will advance actualByteCount only after reading the byte. if (actualByteCount >= 3 && charCount < 2) { // If we reach here, it means that we're: // - trying to decode more than 3 bytes and, // - there is only one char left of charCount where we're stuffing decoded characters. // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once // and an ArgumentException will be thrown complaining that there's not enough space in the output char array. // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters insufficientSpaceInCharsArray = true; break; } else { DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length, string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length)); // Request a few more bytes to get at least one character actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset); actualByteCount++; } } // Now that we actually retrieved some characters, figure out how many bytes it actually was actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount); } } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception)); } // Advance byteOffset += actualByteCount; byteCount -= actualByteCount; charOffset += actualCharCount; charCount -= actualCharCount; } _offset = byteOffset; _length = byteCount; actual = (count - charCount); return(true); }
/// <inheritdoc/> public T Read(T reuse, Decoder decoder) { return((T)_reader(reuse, decoder)); }
protected DeviceDecapsulationUndoEntry(BinaryReader reader, int version) : base(reader, version) { index = reader.ReadInt32(); init = (T)Decoder.Decode <Device>(reader, version); }
private object ReadBoolean(object reuse, Decoder decoder) { return(decoder.ReadBoolean()); }
internal ExtendedCharacterDetectionDecoder(Decoder decoder, Action response) { this.decoder = decoder; this.response = response; }
private object ReadNull(object reuse, Decoder decoder) { decoder.ReadNull(); return(null); }
private static Instr64Decoder Instr64(Decoder dec32bit, Decoder dec64bit) { return(new Instr64Decoder(dec32bit, dec64bit)); }
private object ReadUnion(object reuse, Decoder d, ReadItem[] branchLookup) { return(branchLookup[d.ReadUnionIndex()](reuse, d)); }
static public int LzmaBenchmark(Int32 numIterations, UInt32 dictionarySize) { if (numIterations <= 0) { return(0); } if (dictionarySize < (1 << 18)) { System.Console.WriteLine("\nError: dictionary size for benchmark must be >= 19 (512 KB)"); return(1); } System.Console.Write("\n Compressing Decompressing\n\n"); Encoder encoder = new Encoder(); Decoder decoder = new Decoder(); CoderPropID[] propIDs = { CoderPropID.DictionarySize, }; object[] properties = { (Int32)(dictionarySize), }; UInt32 kBufferSize = dictionarySize + kAdditionalSize; UInt32 kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize; encoder.SetCoderProperties(propIDs, properties); System.IO.MemoryStream propStream = new System.IO.MemoryStream(); encoder.WriteCoderProperties(propStream); byte[] propArray = propStream.ToArray(); CBenchRandomGenerator rg = new CBenchRandomGenerator(); rg.Set(kBufferSize); rg.Generate(); CRC crc = new CRC(); crc.Init(); crc.Update(rg.Buffer, 0, rg.BufferSize); CProgressInfo progressInfo = new CProgressInfo(); progressInfo.ApprovedStart = dictionarySize; UInt64 totalBenchSize = 0; UInt64 totalEncodeTime = 0; UInt64 totalDecodeTime = 0; UInt64 totalCompressedSize = 0; MemoryStream inStream = new MemoryStream(rg.Buffer, 0, (int)rg.BufferSize); MemoryStream compressedStream = new MemoryStream((int)kCompressedBufferSize); CrcOutStream crcOutStream = new CrcOutStream(); for (Int32 i = 0; i < numIterations; i++) { progressInfo.Init(); inStream.Seek(0, SeekOrigin.Begin); compressedStream.Seek(0, SeekOrigin.Begin); encoder.Code(inStream, compressedStream, -1, -1, progressInfo); TimeSpan sp2 = DateTime.UtcNow - progressInfo.Time; UInt64 encodeTime = (UInt64)sp2.Ticks; long compressedSize = compressedStream.Position; if (progressInfo.InSize == 0) { throw (new Exception("Internal ERROR 1282")); } UInt64 decodeTime = 0; for (int j = 0; j < 2; j++) { compressedStream.Seek(0, SeekOrigin.Begin); crcOutStream.Init(); decoder.SetDecoderProperties(propArray); UInt64 outSize = kBufferSize; System.DateTime startTime = DateTime.UtcNow; decoder.Code(compressedStream, crcOutStream, 0, (Int64)outSize, null); TimeSpan sp = (DateTime.UtcNow - startTime); decodeTime = (ulong)sp.Ticks; if (crcOutStream.GetDigest() != crc.GetDigest()) { throw (new Exception("CRC Error")); } } UInt64 benchSize = kBufferSize - (UInt64)progressInfo.InSize; PrintResults(dictionarySize, encodeTime, benchSize, false, 0); System.Console.Write(" "); PrintResults(dictionarySize, decodeTime, kBufferSize, true, (ulong)compressedSize); System.Console.WriteLine(); totalBenchSize += benchSize; totalEncodeTime += encodeTime; totalDecodeTime += decodeTime; totalCompressedSize += (ulong)compressedSize; } System.Console.WriteLine("---------------------------------------------------"); PrintResults(dictionarySize, totalEncodeTime, totalBenchSize, false, 0); System.Console.Write(" "); PrintResults(dictionarySize, totalDecodeTime, kBufferSize * (UInt64)numIterations, true, totalCompressedSize); System.Console.WriteLine(" Average"); return(0); }
/// <summary> /// Get an <see cref="IObservable{T}"/> for lines streamed from an HTTP GET request. /// </summary> /// <param name="request"> /// The <see cref="HttpRequest"/> to execute. /// </param> /// <param name="operationDescription"> /// A short description of the operation (used in error messages if the request fails). /// </param> /// <param name="bufferSize"> /// The buffer size to use when streaming data. /// /// Default is 2048 bytes. /// </param> /// <returns> /// The <see cref="IObservable{T}"/>. /// </returns> protected IObservable <string> ObserveLines(HttpRequest request, string operationDescription, int bufferSize = DefaultStreamingBufferSize) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (String.IsNullOrWhiteSpace(operationDescription)) { throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'operationDescription'.", nameof(operationDescription)); } return(Observable.Create <string>(async(subscriber, cancellationToken) => { try { using (HttpResponseMessage responseMessage = await Http.GetStreamedAsync(request, cancellationToken).ConfigureAwait(false)) { if (!responseMessage.IsSuccessStatusCode) { throw HttpRequestException <StatusV1> .Create(responseMessage.StatusCode, await responseMessage.ReadContentAsStatusV1Async().ConfigureAwait(false) ); } MediaTypeHeaderValue contentTypeHeader = responseMessage.Content.Headers.ContentType; if (contentTypeHeader == null) { throw new KubeClientException($"Unable to {operationDescription} (response is missing 'Content-Type' header)."); } Encoding encoding = !String.IsNullOrWhiteSpace(contentTypeHeader.CharSet) ? Encoding.GetEncoding(contentTypeHeader.CharSet) : Encoding.UTF8; Decoder decoder = encoding.GetDecoder(); using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false)) { StringBuilder lineBuilder = new StringBuilder(); byte[] buffer = new byte[bufferSize]; int bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); while (bytesRead > 0) { // AF: Slightly inefficient because we wind up scanning the buffer twice. char[] decodedCharacters = new char[decoder.GetCharCount(buffer, 0, bytesRead)]; int charactersDecoded = decoder.GetChars(buffer, 0, bytesRead, decodedCharacters, 0); for (int charIndex = 0; charIndex < charactersDecoded; charIndex++) { const char CR = '\r'; const char LF = '\n'; char decodedCharacter = decodedCharacters[charIndex]; switch (decodedCharacter) { case CR: { if (charIndex < charactersDecoded - 1 && decodedCharacters[charIndex + 1] == LF) { charIndex++; goto case LF; } break; } case LF: { string line = lineBuilder.ToString(); lineBuilder.Clear(); subscriber.OnNext(line); break; } default: { lineBuilder.Append(decodedCharacter); break; } } } bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } // If stream doesn't end with a line-terminator sequence, publish trailing characters as the last line. if (lineBuilder.Length > 0) { subscriber.OnNext( lineBuilder.ToString() ); } } } } catch (OperationCanceledException operationCanceled) when(operationCanceled.CancellationToken != cancellationToken) { if (!cancellationToken.IsCancellationRequested) // Don't bother publishing if subscriber has already disconnected. { subscriber.OnError(operationCanceled); } } catch (HttpRequestException <StatusV1> requestError) { if (!cancellationToken.IsCancellationRequested) { subscriber.OnError( new KubeClientException($"Unable to {operationDescription} (unexpected error while streaming from the Kubernetes API).", requestError) ); } } catch (Exception exception) { if (!cancellationToken.IsCancellationRequested) // Don't bother publishing if subscriber has already disconnected. { subscriber.OnError(exception); } } finally { if (!cancellationToken.IsCancellationRequested) // Don't bother publishing if subscriber has already disconnected. { subscriber.OnCompleted(); } } })); }
public static bool IsNull(Expression exp, Decoder decoder) { return(Decode(exp, decoder.visitorForIsNull, decoder)); }
public static bool IsBinary(Expression exp, out BinaryOperator op, out Expression left, out Expression right, Decoder decoder) { VisitorForIsBinaryExpression visitor = decoder.visitorForIsBinaryExpression; bool result = Decode(exp, visitor, decoder); op = visitor.Operator; left = visitor.Left; right = visitor.Right; return(result); }