static void CreateSelfSignCertificate(CertOption option) { var fileName = option.CertFileName; var subject = option.Subject; var password = option.Password; try { var securePassword = Certificate.ConvertSecureString(password); var startDate = DateTime.Now; var endDate = startDate.AddYears(option.Years); var certData = Certificate.CreateSelfSignCertificatePfx(subject, startDate, endDate, securePassword); using (var writer = new System.IO.BinaryWriter(System.IO.File.Open(fileName, System.IO.FileMode.Create))) { writer.Write(certData); writer.Flush(); writer.Close(); } securePassword = Certificate.ConvertSecureString(password); } catch (Exception e) { Console.WriteLine(e.Message); } }
public static void Assemble(string infile, string outfile, string origin) { CurrentNdx = 0; AsLength = Convert.ToUInt16(origin, 16); IsEnd = false; ExecutionAddress = 0; LabelTable = new System.Collections.Hashtable(50); System.IO.BinaryWriter output; System.IO.TextReader input; System.IO.FileStream fs = new System.IO.FileStream(outfile, System.IO.FileMode.Create); output = new System.IO.BinaryWriter(fs); input = System.IO.File.OpenText(infile); SourceProgram = input.ReadToEnd(); input.Close(); output.Write('B'); output.Write('3'); output.Write('2'); output.Write(Convert.ToUInt16(origin, 16)); output.Write((ushort)0); Parse(output, origin); output.Seek(5, System.IO.SeekOrigin.Begin); output.Write(ExecutionAddress); output.Close(); fs.Close(); }
public static byte[] SerializeVoxelAreaCompactData (VoxelArea v) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.compactCells.Length); writer.Write(v.compactSpans.Length); writer.Write(v.areaTypes.Length); for (int i=0;i<v.compactCells.Length;i++) { writer.Write(v.compactCells[i].index); writer.Write(v.compactCells[i].count); } for (int i=0;i<v.compactSpans.Length;i++) { writer.Write(v.compactSpans[i].con); writer.Write(v.compactSpans[i].h); writer.Write(v.compactSpans[i].reg); writer.Write(v.compactSpans[i].y); } for (int i=0;i<v.areaTypes.Length;i++) { //TODO: RLE encoding writer.Write(v.areaTypes[i]); } writer.Close(); return stream.ToArray(); }
public void getPdfFile(string fileName) { using (SqlConnection cn = new SqlConnection(ConnectionString)) { cn.Open(); using (SqlCommand cmd = new SqlCommand($"select FileSource from PdfDocumentFiles where Name='{fileName}' ", cn)) { using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.Default)) { if (dr.Read()) { byte[] fileData = (byte[])dr.GetValue(0); using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData); bw.Close(); } } } dr.Close(); } } } }
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray) { try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(_FileStream); // Writes a block of bytes to this stream using data from // a byte array. bw.Write(_ByteArray, 0, _ByteArray.Length); // close file stream bw.Close(); return true; } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } // error occured, return false return false; }
public static byte[] SerializeVoxelAreaCompactData (VoxelArea v) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.compactCells.Length); writer.Write(v.compactSpans.Length); writer.Write(v.areaTypes.Length); for (int i=0;i<v.compactCells.Length;i++) { writer.Write(v.compactCells[i].index); writer.Write(v.compactCells[i].count); } for (int i=0;i<v.compactSpans.Length;i++) { writer.Write(v.compactSpans[i].con); writer.Write(v.compactSpans[i].h); writer.Write(v.compactSpans[i].reg); writer.Write(v.compactSpans[i].y); } for (int i=0;i<v.areaTypes.Length;i++) { //TODO: RLE encoding writer.Write(v.areaTypes[i]); } writer.Close(); return stream.ToArray(); #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
public static void PNGtoBIN(string path_in, string path_out, string[] param = null) { Image png = Image.FromFile(path_in); Bitmap bmp = new Bitmap(png); if ((png.Width != 128) && (png.Height != 32)) return; int tiles_w = png.Width / 4; int tiles_h = png.Height / 8; ushort[] binary = new ushort[256]; for (int y = 0; y < tiles_h; y++) { for (int x = 0; x < tiles_w; x++) { ushort[] tile = new ushort[2]; for (int iY = 0; iY < 8; iY++) { for (int iX = 0; iX < 4; iX++) { Color color = bmp.GetPixel(x * 4 + iX, y * 8 + iY); if (color.R + color.G + color.B > 0x0100) tile[(iY / 4)] |= (ushort)(1 << ((iY % 4) * 4 + iX)); } } binary[y * tiles_w * 2 + x * 2 + 0] = tile[0]; binary[y * tiles_w * 2 + x * 2 + 1] = tile[1]; } } System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(path_out, System.IO.FileMode.Create)); for (int i = 0; i < 256; i++) writer.Write(binary[i]); writer.Close(); }
public override void calcbodysize() { System.IO.BinaryWriter bw = new System.IO.BinaryWriter(new System.IO.MemoryStream()); ToStream(bw); size = Convert.ToInt32(bw.BaseStream.Length); bw.Close(); bw.Dispose(); }
public static void Save(string directory, string file,string ext, XCImageCollection images) { System.IO.BinaryWriter bw = new System.IO.BinaryWriter(System.IO.File.Create(directory+"\\"+file+ext)); foreach(XCImage tile in images) bw.Write(tile.Bytes); bw.Flush(); bw.Close(); }
public void WriteZippedResources() { using (var binWriter = new System.IO.BinaryWriter(this.fileSystem.File.OpenWrite(MyDhtmlResourceSet.ZippedResources.LocalPath))) { binWriter.Write(Properties.Resources.Pickles_BaseDhtmlFiles); binWriter.Flush(); binWriter.Close(); } }
/// <summary> /// 将Base64编码字符串解码并存储到一个文件中 /// </summary> /// <param name="Base64String">经过Base64编码后的字符串</param> /// <param name="strSaveFileName">要输出的文件路径,如果文件存在,将被重写</param> /// <returns>如果操作成功,则返回True</returns> public static bool DecodingFileFromString(string Base64String, string strSaveFileName) { System.IO.FileStream fs = new System.IO.FileStream(strSaveFileName, System.IO.FileMode.Create); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs); bw.Write(Convert.FromBase64String(Base64String)); //bw.Write(Convert.ToBase64String) bw.Close(); fs.Close(); return true; }
static void Main(string[] args) { var options = new SwitchOptions(); if (!CommandLine.ParseArguments(args, options)) return; try { if (String.IsNullOrEmpty(options.outFile)) { Console.WriteLine("You must supply an outfile."); return; } var source = new System.IO.StreamReader(options.inFile); var lexed = new LexResult(); var r = Lexer.Lex(source, lexed); if (r == 0x00) { var destination = System.IO.File.Open(options.outFile, System.IO.FileMode.Create); var writer = new System.IO.BinaryWriter(destination); r = Assembler.Assemble(lexed, writer); writer.Flush(); destination.Flush(); writer.Close(); } Console.WriteLine("Finished with code " + r); } /*case "emulate": { var source = System.IO.File.Open(options.inFile, System.IO.FileMode.Open); var emulator = new IN8(); source.Read(emulator.MEM, 0, 0xFFFF); // Attach devices var teletypeTerminal = new TT3(); emulator.AttachHardware(teletypeTerminal, 0x04); while (emulator.STATE_FLAGS == 0x00) emulator.Step(); Console.WriteLine(String.Format("Finished in state {0:X2}", emulator.STATE_FLAGS)); Console.WriteLine(String.Format("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2}", emulator.A, emulator.B, emulator.C, emulator.D, emulator.E, emulator.H, emulator.L, emulator.O)); Console.WriteLine(String.Format("{0:X4} {1:X4} {2:X8}", emulator.IP, emulator.SP, emulator.CLOCK)); break; } } }*/ catch (Exception e) { Console.WriteLine("An error occured."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } }
/// <summary> /// 将 Stream 写入文件 /// </summary> /// <param name="stream"></param> /// <param name="fileName"></param> public static void StreamToFile(this System.IO.Stream stream, string fileName) { // 把 Stream 转换成 byte[] var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, System.IO.SeekOrigin.Begin); // 把 byte[] 写入文件 var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create); var bw = new System.IO.BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); }
private void btnExport_Click(object sender, EventArgs e) { System.IO.BinaryWriter bw = new System.IO.BinaryWriter(System.IO.File.Open("export.txt", System.IO.FileMode.Create)); bw.Write(width);//columns bw.Write(height);//rows for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bw.Write(mapData[x, y]); } } bw.Close(); }
/// <summary> /// ファイルにデータをセーブ /// </summary> public static void SaveData() { using(var fs = System.IO.File.Open(@SAVEFILE,System.IO.FileMode.CreateNew)){ // バイナリライター作成 var bw = new System.IO.BinaryWriter(fs); // Write data bw.Write(Global.isStageOpened[(int)StageID.Stage1]); bw.Write(Global.isStageOpened[(int)StageID.Stage2]); bw.Write(Global.isStageOpened[(int)StageID.Stage3]); bw.Write(Global.characterLevel); bw.Write(Global.characterExp); bw.Close(); } }
public void save() { Data.sName = "aa"; Data.dBaseRadius = 2; Data.dNoseRadius = .5; String x = ""; foreach (string key in HttpContext.Current.Session.Keys) { x += key + " - " + HttpContext.Current.Session[key] + ";"; } //SessionStateItemCollection items = HttpContext.Current.Session. SessionStateItemCollection items = new SessionStateItemCollection(); items["Name"] = "NN"; items["Desc"] = "DD"; try { System.IO.BinaryWriter writer = new System.IO.BinaryWriter( System.IO.File.Open(HttpContext.Current.Server.MapPath("./session_collection.bin"), System.IO.FileMode.Create)); items.Serialize(writer); writer.Close(); items["Name"] = ""; items["Desc"] = ""; System.IO.BinaryReader reader = new System.IO.BinaryReader( System.IO.File.Open(HttpContext.Current.Server.MapPath("./session_collection.bin"), System.IO.FileMode.Open)); items = SessionStateItemCollection.Deserialize(reader); String x2 = items["Name"].ToString(); String y2 = items["Desc"].ToString(); } catch (Exception e) { String err = e.StackTrace; } }
public static System.Drawing.Image ProductImage(Lfx.Data.Connection dataBase, int productId, DownloadImage downloadImage) { string CachePath = Lfx.Environment.Folders.CacheFolder; string ImageFileName = "product_" + productId.ToString() + ".jpg"; bool ImageInCache = System.IO.File.Exists(CachePath + ImageFileName); if(downloadImage == DownloadImage.Always || (downloadImage == DownloadImage.OnlyIfNotInCache && ImageInCache == false) || ((downloadImage == DownloadImage.PreferCacheOnSlowLinks && ImageInCache == false) || Lfx.Workspace.Master.SlowLink == false)) { //Download image and save to cache Lfx.Data.Row ImagenDB = dataBase.Row("articulos_imagenes", "imagen", "id_articulo", productId); if (ImagenDB != null && ImagenDB.Fields["imagen"].Value != null && ((byte[])(ImagenDB.Fields["imagen"].Value)).Length > 5) { //Guardar imagen en cache System.IO.BinaryWriter wr = new System.IO.BinaryWriter(System.IO.File.OpenWrite(CachePath + ImageFileName), System.Text.Encoding.Default); wr.Write(((byte[])(ImagenDB.Fields["imagen"].Value))); wr.Close(); byte[] ByteArr = ((byte[])(ImagenDB.Fields["imagen"].Value)); System.Drawing.Image Img; using (System.IO.MemoryStream loStream = new System.IO.MemoryStream(ByteArr)) { Img = System.Drawing.Image.FromStream(loStream); } return Img; } else { //Devuelve la imagen de la categoría, en lugar de la del artículo int CategoriaArticulo = dataBase.FieldInt("SELECT id_categoria FROM articulos WHERE id_articulo=" + productId.ToString()); return CategoryImage(dataBase, CategoriaArticulo, downloadImage); } } //Serve only from cache if(ImageInCache) { return System.Drawing.Image.FromFile(CachePath + ImageFileName); } return null; }
/// <summary> /// 构造函数 /// </summary> /// <param name="index">USB设备索引</param> public UsbCanDevice(DeviceType deviceType, uint index) { #region 判断CanCmd.dll是否存在,不存在生成一个 Debug.WriteLine(System.IO.File.Exists(@"CanCmd.dll"), "判断是否存在CanCmd.dll库文件"); if (System.IO.File.Exists(@"CanCmd.dll") == false) { byte[] buf = CsmProtocl.Properties.Resources.CanCmd; System.IO.FileStream f = new System.IO.FileStream(@".\CanCmd.dll", System.IO.FileMode.Create); System.IO.BinaryWriter br = new System.IO.BinaryWriter(f); br.Write(buf, 0, buf.Length); br.Close(); f.Close(); } #endregion this._index = index; this._deviceType = (uint)deviceType; Open(); }
public static void Palette_ToRGB444(string path_in, string path_out, string[] param = null) { string[] lines = System.IO.File.ReadAllLines(path_in); byte[][] palette = new byte[0x10][]; int current = 0; for (int i = 0; i < lines.Length; i++) { if ((lines[i] == string.Empty) || (lines[i].Trim()[0] == ';')) { // ignore this line - empty or comment } else { string line = lines[i].Trim(); string[] rgb = line.Split(','); if (rgb.Length != 3) continue; // should only have three elements. byte[] pal_entry = new byte[4]; pal_entry[0] = 0xFF; pal_entry[1] = byte.Parse(rgb[0].Trim()); pal_entry[2] = byte.Parse(rgb[1].Trim()); pal_entry[3] = byte.Parse(rgb[2].Trim()); palette[current++] = pal_entry; } if (current == 16) break; } ushort[] pal_16bit = new ushort[0x10]; for (int i = 0; i < 0x10; i++) { int r = palette[i][3] >> 4; int g = palette[i][2] >> 4; int b = palette[i][1] >> 4; pal_16bit[i] = (ushort)((r << 8) | (g << 4) | b); } System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(path_out, System.IO.FileMode.Create)); for (int i = 0; i < 0x10; i++) writer.Write(pal_16bit[i]); writer.Close(); }
public void Start(string InputFilename, string OutputFilename, UInt64 Key, DESMode.DESMode Mode, bool Decode) { using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(System.IO.File.Open(InputFilename, System.IO.FileMode.Open))) { using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(System.IO.File.Open(OutputFilename, System.IO.FileMode.OpenOrCreate))) { const int MaxSize = 1048576; int n = 0; byte[] buffer = new byte[MaxSize]; int size = 0; int k = 0; UInt64 DESResult = 0; while ((n = Reader.Read(buffer, 0, MaxSize)) > 0) { k = 0; while (n > 0) { if ((n / 8) > 0) size = 8; else size = n; byte[] tempArray = new byte[size]; for (int i = 0; i != size; ++i, ++k) tempArray[i] = buffer[k]; if (!Decode) DESResult = Mode.EncodeBlock(GetUIntFromByteArray(tempArray), Key); else DESResult = Mode.DecodeBlock(GetUIntFromByteArray(tempArray), Key); Writer.Write(GetByteArrayFromUInt(DESResult, size), 0, size); n -= 8; } } Writer.Close(); } Reader.Close(); } }
private void button11_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.AddExtension = true; dlg.FileName = vdxChooser.SelectedItem.ToString(); dlg.OverwritePrompt = true; dlg.Title = "Export VDX audio stream"; dlg.Filter = "WAV (*.wav)|*.wav"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { byte[] stream = vdx.GetAudioStream(); if (stream.Length > 0) { System.IO.FileStream fs = System.IO.File.Open(dlg.FileName, System.IO.FileMode.Create); System.IO.BinaryWriter wr = new System.IO.BinaryWriter(fs); wr.Write(stream, 0, stream.Length); wr.Close(); fs.Close(); } else MessageBox.Show("Bad audio stream?"); } }
protected override void Update() { this.activeWormWalkers.RemoveAll((GameObject o) => o == null); this.activeWormTrees.RemoveAll((GameObject o) => o == null); this.activeWormSingle.RemoveAll((GameObject o) => o == null); this.activeWormAngels.RemoveAll((GameObject o) => o == null); if (this.activeWormWalkers.Count > 0 || this.activeWormAngels.Count > 0 || this.activeWormTrees.Count > 0) { this.anyFormSpawned = true; } else { this.anyFormSpawned = false; } if (this.activeWormSingle.Count == 0 && this.init) { if (GameSetup.IsMpServer || GameSetup.IsSinglePlayer) { long Exp; switch (ModSettings.difficulty) { case ModSettings.Difficulty.Normal: Exp = 5000; break; case ModSettings.Difficulty.Hard: Exp = 20000; break; case ModSettings.Difficulty.Elite: Exp = 100000; break; case ModSettings.Difficulty.Master: Exp = 3000000; break; case ModSettings.Difficulty.Challenge1: Exp = 50000000; break; case ModSettings.Difficulty.Challenge2: Exp = 100000000; break; case ModSettings.Difficulty.Challenge3: Exp = 500000000; break; case ModSettings.Difficulty.Challenge4: Exp = 1000000000; break; case ModSettings.Difficulty.Challenge5: Exp = 5000000000; break; default: Exp = 10000000000; break; } if (GameSetup.IsMpServer) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(10); w.Write(Exp); w.Close(); } ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone); answerStream.Close(); } } else { ModdedPlayer.instance.AddKillExperience(Exp); } int itemCount = UnityEngine.Random.Range(15, 26); for (int i = 0; i < itemCount; i++) { Network.NetworkManager.SendItemDrop(ItemDataBase.GetRandomItem(Exp), LocalPlayer.Transform.position + Vector3.up * 2); } ModAPI.Console.Write("Worm Died"); } UnityEngine.Object.Destroy(base.gameObject); } }
//These functions are for serialization, the static ones are there so other graphs using mesh nodes can serialize them more easily public static byte[] SerializeMeshNodes (NavMeshGraph graph, GraphNode[] nodes) { System.IO.MemoryStream mem = new System.IO.MemoryStream(); System.IO.BinaryWriter stream = new System.IO.BinaryWriter(mem); for (int i=0;i<nodes.Length;i++) { TriangleMeshNode node = nodes[i] as TriangleMeshNode; if (node == null) { Debug.LogError ("Serialization Error : Couldn't cast the node to the appropriate type - NavMeshGenerator. Omitting node data."); return null; } stream.Write (node.v0); stream.Write (node.v1); stream.Write (node.v2); } Int3[] vertices = graph.vertices; if (vertices == null) { vertices = new Int3[0]; } stream.Write (vertices.Length); for (int i=0;i<vertices.Length;i++) { stream.Write (vertices[i].x); stream.Write (vertices[i].y); stream.Write (vertices[i].z); } stream.Close (); return mem.ToArray(); }
bool ConnectCmd(bool reloadFlag) { ConnectWindow dlg = new ConnectWindow(); PresentationSource topWindow = PresentationSource.FromVisual(this); if (topWindow != null) { dlg.Owner = (Window)topWindow.RootVisual; } if (dlg.ShowDialog() == true) { bool connected = false; String srvIP = Settings.Instance.NWServerIP; try { foreach (IPAddress address in Dns.GetHostAddresses(srvIP)) { srvIP = address.ToString(); if (CommonManager.Instance.NW.ConnectServer(srvIP, Settings.Instance.NWServerPort, Settings.Instance.NWWaitPort, OutsideCmdCallback, this) == true) { connected = true; break; } } } catch { } if (connected == false) { MessageBox.Show("サーバーへの接続に失敗しました"); } else { if (reloadFlag == true) { byte[] binData; if (cmd.SendFileCopy("ChSet5.txt", out binData) == 1) { string filePath = SettingPath.SettingFolderPath; System.IO.Directory.CreateDirectory(filePath); filePath += "\\ChSet5.txt"; using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(System.IO.File.Create(filePath))) { w.Write(binData); w.Close(); } ChSet5.LoadFile(); } CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.ReserveInfo); CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.RecInfo); CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.AutoAddEpgInfo); CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.AutoAddManualInfo); CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.EpgData); CommonManager.Instance.DB.SetUpdateNotify((UInt32)UpdateNotifyItem.PlugInFile); reserveView.UpdateReserveData(); epgView.UpdateReserveData(); tunerReserveView.UpdateReserveData(); autoAddView.UpdateAutoAddInfo(); recInfoView.UpdateInfo(); epgView.UpdateEpgData(); } return true; } } return false; }
private void cmdEncStart_Click(object sender, EventArgs e) { //mencoder shana.avi -o shana.flv -af resample=44100:0:0 -sws 9 -vf expand=448:336 -of lavf -ovc lavc //-lavcopts vcodec=flv:vbitrate=1000:trell:v4mv:mv0:mbd=2:cbp:aic:cmp=3:subcmp=3:vpass=1 //-oac mp3lame -lameopts abr:br=128:mode=3 if (txtFileSource.Text == "") { cmdFileSourceLoad_Click(new object(), new EventArgs()); } if (txtFileSource.Text == "") { MessageBox.Show("Please click \"Load file\" to select a video."); return; } if (txtFileDestination.Text == "") { MessageBox.Show("Please select a destination for the encoded file."); return; } if (ddWidth.Text == "" || ddHeight.Text == "") { MessageBox.Show("Please enter the source file's horizontal and vertical resolution."); return; } if (txtMinutes.Text == "" || txtSeconds.Text == "") { MessageBox.Show("Please enter the source file's length."); return; } if (ddVideoRate.Text == "" || ddAudioRate.Text == "") { MessageBox.Show("Please select the preferred compression levels (bitrates)."); return; } if (chkResize.Checked && (ddResizeX.Text == "" || ddResizeY.Text == "")) { MessageBox.Show("If you want to resize, please select preferred resolution."); return; } bStopEncode = false; double dX = Convert.ToDouble(ddWidth.Text); double dY = dX / ((double)4 / (double)3); string cmd1 = "\"" + txtFileSource.Text + "\" -o \"" + txtFileDestination.Text + "\"" + " -af resample=44100:0:0 -sws 9 -vf expand=" + dX + ":" + dY; if (chkResize.Checked) { cmd1 += ",scale=" + ddResizeX.Text + ":" + ddResizeY.Text; } cmd1 += " -of lavf -ovc lavc -lavcopts vcodec=flv:vbitrate=" + ddVideoRate.Text + ":trell:v4mv:mv0:mbd=2:cbp:aic:cmp=3:subcmp=3"; string cmd2 = " -oac mp3lame -lameopts abr:br=" + ddAudioRate.Text + ":mode=3"; Clipboard.Clear(); Clipboard.SetText(cmd1 + "\r\n\r\n" + cmd2); return; if (chkTwopass.Checked) { DoEnc(cmd1, cmd2, ":vpass=1", "Encoding 1st pass (1/2) - %p"); DoEnc(cmd1, cmd2, ":vpass=2", "Encoding 2nd pass (2/2) - %p"); } else { DoEnc(cmd1, cmd2, "", "Encoding 1st pass (1/1) - %p"); } int Iterations = 0; while (true) { try { byte[] FakeLen = new byte[] { 0x84, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; System.IO.FileStream FStream = new System.IO.FileStream(txtFileDestination.Text, System.IO.FileMode.Open); System.IO.BinaryWriter BinWri = new System.IO.BinaryWriter(FStream); //BinWri.Seek(0x36, System.IO.SeekOrigin.Begin); BinWri.Write(FakeLen); BinWri.Flush(); BinWri.Close(); FStream.Dispose(); break; } catch { Iterations++; Application.DoEvents(); System.Threading.Thread.Sleep(100); } } lblStatus.Text = "Done!"; System.Media.SystemSounds.Exclamation.Play(); System.Threading.Thread.Sleep(1000); if (Iterations > 0) { MessageBox.Show("DEBUG: Had to sleep " + Iterations + "x100 miliseconds."); } }
/// <summary>Saves the current in-game black box log</summary> internal static void SaveLogs() { if (Interface.CurrentOptions.BlackBox == false) { return; } string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin"); using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { //TODO: This code recreates the file every frame..... //It should be possible to spin up a stream in a separate thread which then continously appends using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(Stream, System.Text.Encoding.UTF8)) { byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 }; const short Version = 1; Writer.Write(Identifier); Writer.Write(Version); Writer.Write(Game.LogRouteName); Writer.Write(Game.LogTrainName); Writer.Write(Game.LogDateTime.ToBinary()); Writer.Write((short)Interface.CurrentOptions.GameMode); Writer.Write(Game.BlackBoxEntryCount); for (int i = 0; i < Game.BlackBoxEntryCount; i++) { Writer.Write(Game.BlackBoxEntries[i].Time); Writer.Write(Game.BlackBoxEntries[i].Position); Writer.Write(Game.BlackBoxEntries[i].Speed); Writer.Write(Game.BlackBoxEntries[i].Acceleration); Writer.Write(Game.BlackBoxEntries[i].ReverserDriver); Writer.Write(Game.BlackBoxEntries[i].ReverserSafety); Writer.Write((short)Game.BlackBoxEntries[i].PowerDriver); Writer.Write((short)Game.BlackBoxEntries[i].PowerSafety); Writer.Write((short)Game.BlackBoxEntries[i].BrakeDriver); Writer.Write((short)Game.BlackBoxEntries[i].BrakeSafety); Writer.Write((short)Game.BlackBoxEntries[i].EventToken); } Writer.Write(Game.ScoreLogCount); for (int i = 0; i < Game.ScoreLogCount; i++) { Writer.Write(Game.ScoreLogs[i].Time); Writer.Write(Game.ScoreLogs[i].Position); Writer.Write(Game.ScoreLogs[i].Value); Writer.Write((short)Game.ScoreLogs[i].TextToken); } Writer.Write(Game.CurrentScore.Maximum); Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 }; Writer.Write(Identifier); Writer.Close(); } Stream.Close(); } }
protected override bool Equip(InventoryItemView itemView, bool pickedUpFromWorld) { if (!ModSettings.IsDedicated) { if (GreatBow.instance != null) { GreatBow.instance.SetActive(false); } if (itemView != null) { EquippedModel = BaseItem.WeaponModelType.None; if (itemView._heldWeaponInfo.transform.parent.name == "AxePlaneHeld") { if (BoltNetwork.isRunning) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(28); w.Write(ModReferences.ThisPlayerID); w.Write((int)PlayerInventoryMod.ToEquipWeaponType); w.Close(); } ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others); answerStream.Close(); } } if (ModReferences.rightHandTransform == null) { try { ModReferences.rightHandTransform = itemView._heldWeaponInfo.transform.parent.gameObject.transform.parent.transform; } catch (System.Exception) { } } if (!SetupComplete) { try { if (instance == null) { instance = this; } SetupComplete = true; customWeapons.Clear(); originalPlaneAxe = itemView; originalPlaneAxeModel = itemView._heldWeaponInfo.transform.parent.GetChild(2).gameObject; originalRotation = originalPlaneAxeModel.transform.localRotation; OriginalOffset = originalPlaneAxeModel.transform.localPosition; originalParrent = originalPlaneAxeModel.transform.parent; OriginalTreeDmg = itemView._heldWeaponInfo.treeDamage; originalMesh = originalPlaneAxeModel.GetComponent <MeshFilter>().mesh; noMesh = new Mesh(); //Creating custom weapons--------- CreateCustomWeapons(); } catch (System.Exception eee) { ModAPI.Log.Write("Error with setting up custom weaponry " + eee.ToString()); } } if (ToEquipWeaponType != BaseItem.WeaponModelType.None) { EquippedModel = ToEquipWeaponType; try { foreach (CustomWeapon item in customWeapons.Values) { item.obj.SetActive(false); } CustomWeapon cw = customWeapons[ToEquipWeaponType]; cw.obj.SetActive(true); itemView._heldWeaponInfo.weaponSpeed = itemView._heldWeaponInfo.baseWeaponSpeed * cw.swingspeed; itemView._heldWeaponInfo.tiredSpeed = itemView._heldWeaponInfo.baseTiredSpeed * cw.tiredswingspeed; itemView._heldWeaponInfo.smashDamage = cw.smashDamage; itemView._heldWeaponInfo.weaponDamage = cw.damage; itemView._heldWeaponInfo.treeDamage = cw.treeDamage; itemView._heldWeaponInfo.weaponRange = cw.ColliderScale * 3; itemView._heldWeaponInfo.staminaDrain = cw.staminaDrain; itemView._heldWeaponInfo.noTreeCut = cw.blockTreeCut; itemView._heldWeaponInfo.transform.localScale = Vector3.one * cw.ColliderScale; originalPlaneAxeModel.GetComponent <MeshFilter>().mesh = noMesh; } catch (System.Exception exc) { ModAPI.Log.Write("Error with EQUIPPING custom weaponry " + exc.ToString()); } } else { itemView._heldWeaponInfo.transform.parent.GetChild(2).gameObject.SetActive(true); foreach (CustomWeapon item in customWeapons.Values) { item.obj.SetActive(false); } itemView._heldWeaponInfo.weaponSpeed = itemView._heldWeaponInfo.baseWeaponSpeed; itemView._heldWeaponInfo.tiredSpeed = itemView._heldWeaponInfo.baseTiredSpeed; itemView._heldWeaponInfo.smashDamage = itemView._heldWeaponInfo.baseSmashDamage; itemView._heldWeaponInfo.weaponDamage = itemView._heldWeaponInfo.baseWeaponDamage; itemView._heldWeaponInfo.treeDamage = OriginalTreeDmg; itemView._heldWeaponInfo.weaponRange = itemView._heldWeaponInfo.baseWeaponRange; itemView._heldWeaponInfo.staminaDrain = itemView._heldWeaponInfo.baseStaminaDrain; itemView._heldWeaponInfo.noTreeCut = false; itemView._heldWeaponInfo.transform.localScale = Vector3.one * 0.6f; originalPlaneAxeModel.GetComponent <MeshFilter>().mesh = originalMesh; } } else if (BoltNetwork.isRunning) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(28); w.Write(ModReferences.ThisPlayerID); w.Write(0); w.Close(); } ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others); answerStream.Close(); } } } } return(base.Equip(itemView, pickedUpFromWorld)); }
protected unsafe override void OnLoad(EventArgs e) { base.OnLoad(e); using (fftwlib.FFT2D FFT = new fftwlib.FFT2D(256, 256)) { // Build the source data // FillInput( FFT.Input ); { const double Lx = 400.0; const double Lz = Lx; const double WindAngle = 45.0 * Math.PI / 180.0; const double WindVelocity = 20.0; double Wx = Math.Cos(WindAngle); double Wz = Math.Sin(WindAngle); double U1, U2, fX, fZ; Random RNG = new Random(1); FFT.FillInputFrequency((int Fx, int Fy, out float r, out float i) => { double kx = (2.0 * Math.PI / Lx) * Fx; double kz = (2.0 * Math.PI / Lz) * Fy; // Build white gaussian noise // (source: http://www.dspguru.com/dsp/howtos/how-to-generate-white-gaussian-noise) U1 = 1e-10 + RNG.NextDouble(); U2 = RNG.NextDouble(); fX = Math.Sqrt(-2.0 * Math.Log(U1)) * Math.Sin(2.0 * Math.PI * U2); U1 = 1e-10 + RNG.NextDouble(); U2 = RNG.NextDouble(); fZ = Math.Sqrt(-2.0 * Math.Log(U1)) * Math.Sin(2.0 * Math.PI * U2); fX = fZ = 1.0; // Build Phillips spectrum double SqrtPhillips = Math.Sqrt(Phillips(kx, kz, WindVelocity, Wx, Wz)); r = (float)(1.0 / Math.Sqrt(2.0) * fX * SqrtPhillips); i = (float)(1.0 / Math.Sqrt(2.0) * fZ * SqrtPhillips); r = (float)(U1); // * Math.Exp( -0.001 * Math.Abs( Fx ) )); i = 0.0f; //(float) U2; // r = 0.0; // for ( int j=1; j < 100; j++ ) // r += 0.25 * Math.Cos( 2.0 * Math.PI * -j * (X+2*Y) / 256.0 ) / j; // i = 0.0; // r = Math.Exp( -0.1 * kx ); // i = Math.Exp( -0.1 * kz ); }); } // Fill in bitmap outputPanelFrequency.FillBitmap((int _X, int _Y, int _Width, int _Height) => { int X = 256 * _X / _Width; int Y = 256 * _Y / _Height; byte R = (byte)(255 * Math.Min(1.0, Math.Abs(FFT.Input[2 * (256 * Y + X) + 0]))); byte I = (byte)(255 * Math.Min(1.0, Math.Abs(FFT.Input[2 * (256 * Y + X) + 1]))); return(0xFF000000 | (uint)((R << 16) | (I << 8))); }); // Inverse FFT FFT.InputIsSpatial = false; // We fed frequencies and need an inverse transform FFT.Execute(fftwlib.FFT2D.Normalization.SQUARE_ROOT_OF_DIMENSIONS_PRODUCT); // DEBUG: Test we get back what we fed! // FFT.SwapInputOutput(); // FFT.InputIsSpatial = false; // FFT.Execute( fftwlib.FFT2D.Normalization.SQUARE_ROOT_OF_DIMENSIONS_PRODUCT ); // Retrieve results outputPanelSpatial.FillBitmap((int _X, int _Y, int _Width, int _Height) => { int X = 256 * _X / _Width; int Y = 256 * _Y / _Height; byte R = (byte)(255 * Math.Min(1.0f, Math.Abs(FFT.Output[2 * (256 * Y + X) + 0]))); byte I = (byte)(255 * Math.Min(1.0f, Math.Abs(FFT.Output[2 * (256 * Y + X) + 1]))); // byte R = (byte) (255 * Math.Min( 1.0f, 1.0e6 * Math.Abs( FFT.Output[2*(256*Y+X)+0] ) )); // byte I = (byte) (255 * Math.Min( 1.0f, 1.0e6 * Math.Abs( FFT.Output[2*(256*Y+X)+1] ) )); return(0xFF000000 | (uint)((R << 16) | (I << 8))); }); ////////////////////////////////////////////////////////////////////////// // Save the results System.IO.FileInfo F = new System.IO.FileInfo(@".\Water0_256x256.complex"); System.IO.FileStream S = F.Create(); System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(S); for (int Y = 0; Y < 256; Y++) { for (int X = 0; X < 256; X++) { Writer.Write(FFT.Output[2 * (256 * Y + X) + 0]); Writer.Write(FFT.Output[2 * (256 * Y + X) + 1]); } } Writer.Close(); S.Close(); } }
public void DumpString() { ElfHDR elfhdr = header; ElfPHDR elfphdr; ElfSHDR elfshdr; // Initialze output file System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Create("dump.txt")); // Write Elf writer.Write("****ELF HEADER****\n"); writer.Write(String.Format("ID: {0}\nType: {1}\nMachine: {2}\nVersion: {3}\nEntryPoint: 0x{4:X8}\nPHOffset: 0x{5:X8}\nSHOffset: 0x{6:X8}\nFlags: 0x{7:X4}\nHeaderSize: 0x{8:X2}\nPHSize: 0x{9:X2}\nPHCount: 0x{10:X2}\nSHSize: 0x{11:X2}\nSHCount: 0x{12:X2}\nStringTable: 0x{13:X2}\n\n", BitConverter.ToString(elfhdr.Identification), elfhdr.Type.ToString(), elfhdr.MachineType.ToString(), elfhdr.Version.ToString(), elfhdr.EntryPoint, elfhdr.ProgramHeaderOffset, elfhdr.SectionHeaderOffset, elfhdr.Flags, elfhdr.HeaderSize, elfhdr.ProgramHeaderSize, elfhdr.ProgramHeaderCount, elfhdr.SectionHeaderSize, elfhdr.SectionHeaderCount, elfhdr.StringTable)); // Write PHDR writer.Write("****PROGRAM HEADERS****\n"); for (int i = 0; i < elfhdr.ProgramHeaderCount; i++) { elfphdr = programs[i].Header; writer.Write(String.Format("Program[{10}]\nType = {0}\nFlags = {1}\nOffset = 0x{2:X8} => 0x{8:X8} => 0x{9:X8}\nVaddr = 0x{3:X8}\nPaddr = 0x{4:X8}\nFilesz = 0x{5:X8}\nMemsz = 0x{6:X8}\nAlign = 0x{7:X8}\n\n", elfphdr.Type.ToString(), elfphdr.Flags.ToString(), elfphdr.FileOffset, elfphdr.VirtualAddress, elfphdr.PhysicalAddress, elfphdr.FileSize, elfphdr.MemorySize, elfphdr.Align, elfphdr.FileOffset + elfphdr.FileSize, (elfphdr.FileOffset + elfphdr.FileSize + elfphdr.Align - 1) & ~(elfphdr.Align - 1), i)); } // WRITE SHDR writer.Write("****SECTION HEADERS****\n"); for (int i = 0; i < elfhdr.SectionHeaderCount; i++) { elfshdr = sections[i].Header; writer.Write(String.Format("Section[{12}]\nName: 0x{0:X4}\nType: {1}\nFlags: {2}\nAddress: 0x{3:X8}\nOffset: 0x{4:X8} => 0x{10:X8} => 0x{11:X8}\nSize: 0x{5:X8}\nLink: 0x{6:X4}\nInfo: 0x{7:X4}\nAlign: 0x{8:X8}\nEntries: 0x{9:X8}\n\n", elfshdr.Name, elfshdr.Type.ToString(), elfshdr.Flags.ToString(), elfshdr.Address, elfshdr.FileOffset, elfshdr.Size, elfshdr.Link, elfshdr.Info, elfshdr.Align, elfshdr.EntrySize, elfshdr.FileOffset + elfshdr.Size, (elfshdr.FileOffset + elfshdr.Size + elfshdr.Align - 1) & ~(elfshdr.Align - 1), i)); } // Close writer writer.Close(); writer.Dispose(); }
public void GenerateTextureWithDataFromPath() { try { List <Color> colors = null; byte[] bytes; using (System.IO.FileStream fsSource = new System.IO.FileStream(m_SourcePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { // Read the source file into a byte array. bytes = new byte[fsSource.Length]; int numBytesToRead = (int)fsSource.Length; int numBytesRead = 0; string result = null; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. int n = fsSource.Read(bytes, numBytesRead, numBytesToRead); // Break when the end of the file is reached. if (n == 0) { break; } numBytesRead += n; numBytesToRead -= n; result = System.Text.Encoding.UTF8.GetString(bytes); } numBytesToRead = bytes.Length; string[] colorValues = result.Split('\n'); colors = new List <Color>(colorValues.Length); for (int i = 0; i < colorValues.Length; i++) { colorValues[i] = colorValues[i].Replace("\r", string.Empty); if (string.IsNullOrWhiteSpace(colorValues[i])) { continue; } if (colorValues[i].Length != 6) { continue; } int[] rgb = new int[3]; for (int j = 0; j < 6; j += 2) { string value = colorValues[i].Substring(j, 2); int intValue = int.Parse(value, System.Globalization.NumberStyles.HexNumber); rgb[j / 2] = intValue; } colors.Add(new Color(rgb[0] / 255f, rgb[1] / 255f, rgb[2] / 255f)); } } if (colors != null) { for (int i = 0; i < colors.Count; i++) { Debug.Log(colors[i].r + " :: " + colors[i].g + " :: " + colors[i].b); } } int nearestSquareRoot = (int)Mathf.Ceil(Mathf.Sqrt(colors.Count)); int delta = (nearestSquareRoot * nearestSquareRoot) - colors.Count; if (delta > 0) { for (int i = 0; i < delta; i++) { colors.Add(Color.black); } } Texture2D tex = new Texture2D(nearestSquareRoot, nearestSquareRoot); tex.SetPixels(colors.ToArray()); tex.Apply(); bytes = tex.EncodeToPNG(); System.IO.FileStream stream = new System.IO.FileStream(m_OutputPath + "Palette.png", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); for (int i = 0; i < bytes.Length; i++) { writer.Write(bytes[i]); } writer.Close(); stream.Close(); DestroyImmediate(tex); //I can't figure out how to import the newly created .png file as a texture #if UNITY_EDITOR UnityEditor.AssetDatabase.Refresh(); #endif } catch (System.IO.FileNotFoundException ioEx) { Debug.Log(ioEx.Message); } }
private void bEdit_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count == 0) { return; } int i = (int)dataGridView1.SelectedRows[0].Tag; switch (mode) { case Mode.Arrays: { DataType[] types = new DataType[connection.ArrayLengths[i]]; int[] lenType = new int[connection.ArrayLengths[i]]; string[] strings = new string[connection.ArrayLengths[i]]; connection.WriteDataType(DataTypeSend.GetArray); // code connection.WriteInt(i); // index int lenData = 0; for (int j = 0; j < strings.Length; j++) { types[j] = (DataType)connection.ReadInt(); lenType[j] = connection.ReadInt(); // len data of type lenData += lenType[j]; } byte[] buf = connection.ReadBytes(lenData); // read data BinaryReader br = new BinaryReader(new MemoryStream(buf)); for (int j = 0; j < strings.Length; j++) { switch (types[j]) { case DataType.None: br.BaseStream.Position += 4; break; case DataType.Int: strings[j] = br.ReadInt32().ToString(); break; case DataType.Float: strings[j] = br.ReadSingle().ToString(); break; case DataType.String: byte[] bytes = br.ReadBytes(lenType[j]); strings[j] = System.Text.Encoding.ASCII.GetString(bytes, 0, Array.IndexOf <byte>(bytes, 0)); break; } } br.Close(); strings = EditorWindow.ShowEditor(this, null, types, strings, connection.ArrayIsMap[i]); if (strings != null) // save { MemoryStream ms = new MemoryStream(lenData); BinaryWriter bw = new BinaryWriter(ms); for (int j = 0; j < strings.Length; j++) { switch (types[j]) { case DataType.None: bw.BaseStream.Position += 4; break; case DataType.Int: bw.Write(int.Parse(strings[j])); break; case DataType.Float: bw.Write(float.Parse(strings[j])); break; case DataType.String: byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strings[j]); if (bytes.Length < lenType[j]) { bw.Write(bytes); } else { bw.Write(bytes, 0, lenType[j] - 1); } bw.Write((byte)0); break; } } // send data to sfall connection.WriteDataType(DataTypeSend.SetArray); connection.WriteInt(i); // index connection.WriteInt(lenData); connection.WriteBytes(ms.GetBuffer(), 0, lenData); bw.Close(); } } break; case Mode.Critters: { DataType[] types = new DataType[33]; string[] strings = new string[33]; string[] names = new string[33]; connection.WriteDataType(DataTypeSend.RetrieveCritter); connection.WriteInt(i); BinaryReader br = new BinaryReader(new System.IO.MemoryStream(connection.ReadBytes(33 * 4))); for (int j = 0; j < 33; j++) { types[j] = DataType.Int; strings[j] = br.ReadInt32().ToString(); } br.Close(); names[0] = " ID"; names[1] = " Tile"; names[6] = " Current frame"; names[7] = " Rotation"; names[8] = " FID"; names[9] = " Flags"; names[10] = " Elevation"; names[11] = " Inventory count"; names[13] = " Inventory pointer"; names[14] = " Reaction"; names[15] = " Combat state"; names[16] = " Current AP"; names[17] = " Combat flags"; names[18] = " Last Turn Damage"; names[19] = " AI Packet"; names[20] = " Team"; names[21] = " Who hit me"; names[22] = " HP"; names[23] = " Rads"; names[24] = " Poison"; names[25] = " Proto ID"; names[26] = " Combat ID"; names[29] = " Outline flags"; names[30] = " Script ID"; names[32] = " Script index"; strings = EditorWindow.ShowEditor(this, names, types, strings); if (strings != null) { MemoryStream ms = new MemoryStream(33 * 4); BinaryWriter bw = new BinaryWriter(ms); for (int j = 0; j < 33; j++) { bw.Write(int.Parse(strings[j])); } connection.WriteDataType(DataTypeSend.SetCritter); connection.WriteInt(i); connection.WriteBytes(ms.GetBuffer(), 0, 33 * 4); bw.Close(); } } break; } }
protected override void ReadXmlBase(System.Xml.XmlReader reader) { base.ReadXmlBase(reader); if (reader.LocalName == "alternate_text") { this.alternateText = reader.ReadElementString("alternate_text", RmXmlSerializer.OpenEhrNamespace); } reader.MoveToContent(); if (reader.LocalName == "uri") { string uriType = reader.GetAttribute("type", RmXmlSerializer.XsiNamespace); if (uriType != null) { Check.Assert(uriType.IndexOf("DV_EHR_URI") > 0, "uriType must be DV_EHR_URI, but it is " + uriType); this.uri = new OpenEhr.RM.DataTypes.Uri.DvEhrUri(); } this.uri = new OpenEhr.RM.DataTypes.Uri.DvUri(); this.uri.ReadXml(reader); } if (reader.LocalName == "data") { reader.MoveToContent(); reader.ReadStartElement(); byte[] buffer = new byte[1024]; System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); int bytesRead = reader.ReadContentAsBase64(buffer, 0, 1024); while (bytesRead > 0) { writer.Write(buffer, 0, bytesRead); bytesRead = reader.ReadContentAsBase64(buffer, 0, 1024); } writer.Close(); reader.MoveToContent(); reader.ReadEndElement(); this.data = stream.ToArray(); } reader.MoveToContent(); if (reader.LocalName == "media_type") { this.mediaType = new OpenEhr.RM.DataTypes.Text.CodePhrase(); this.mediaType.ReadXml(reader); } if (reader.LocalName == "compression_algorithm") { this.compressionAlgorithm = new OpenEhr.RM.DataTypes.Text.CodePhrase(); this.compressionAlgorithm.ReadXml(reader); } if (reader.LocalName == "integrity_check") { reader.ReadElementContentAsBase64(this.integrityCheck, 0, this.integrityCheck.Length); } reader.MoveToContent(); if (reader.LocalName == "integrity_check_algorithm") { this.integrityCheckAlgorithm = new OpenEhr.RM.DataTypes.Text.CodePhrase(); this.integrityCheckAlgorithm.ReadXml(reader); } Check.Assert(reader.LocalName == "size", "Expected LocalName is 'size', not " + reader.LocalName); this.size = reader.ReadElementContentAsInt("size", RmXmlSerializer.OpenEhrNamespace); reader.MoveToContent(); if (reader.LocalName == "thumbnail") { this.thumbnail = new DvMultimedia(); this.thumbnail.ReadXml(reader); } }
public bool SaveArchive(string fPath) { if (ArchiveOpen == 0) { return(false); } try { if (System.IO.File.Exists(fPath)) { System.IO.File.Delete(fPath); } } catch { return(false); } System.IO.BinaryWriter bw; try { bw = new System.IO.BinaryWriter(System.IO.File.Open(fPath, System.IO.FileMode.Create)); } catch { return(false); } if (ArchiveOpen == 1) { bw.Write(Convert.ToUInt32(0x000000c8)); // Header Size bw.Write(Convert.ToUInt32(0x00000058)); // File Headers Size bw.Write(Convert.ToUInt32(0x00000006)); // Version bw.Write(Convert.ToUInt32((ArchiveHead1.FileCount * 0x58) + 0xc8)); // Full Head Size uint fEntry = 0; uint bodySize = 0; for (int i = 0; i < ArchiveHead1.FileCount; i++) { bodySize += ArchiveFiles1[i].Size; fEntry += bodySize; while ((fEntry & 0xF) != 0) { fEntry += 4; bodySize += 4; } } bw.Write(bodySize); // Body Size bw.Write(Convert.ToUInt32(0x4532abcd)); // ? bw.Write(Convert.ToUInt32(0)); // Compression bw.Write(Convert.ToUInt16(0x0000)); // Errors bw.Write(Convert.ToUInt16(0x0000)); // Warnings for (uint i = 0x20; i < 0xc4; i += 4) { bw.Write(Convert.ToUInt32(0)); } bw.Write(ArchiveHead1.FileCount); // File Count /* * public uint MainHeaderSize; * public uint FileHeaderSize; * * public uint unknown1; * * public uint ArchiveHeaderSize; * public uint BodySize; * * public uint unknownID; * * public uint empty; * public uint unknown2; * * public uint[] padding; * * public uint FileCount; */ fEntry = 0; for (int i = 0; i < ArchiveHead1.FileCount; i++) { bw.Write(ArchiveFiles1[i].FullPath.ToCharArray()); for (int i2 = ArchiveFiles1[i].FullPath.Length; i2 < 0x40; i2++) { bw.Write(Convert.ToChar(0)); } bw.Write(ArchiveFiles1[i].VarName); bw.Write(ArchiveFiles1[i].dbID); bw.Write(fEntry); bw.Write(ArchiveFiles1[i].Size); bw.Write(ArchiveFiles1[i].ChecksumV1); bw.Write(ArchiveFiles1[i].Empty); fEntry += ArchiveFiles1[i].Size; while ((fEntry & 0xF) != 0) { fEntry += 4; } /* * public string Name; * public string FullPath; * public byte[] Padding; * public uint VarName; * public uint unknown1; * public uint Entry; * public uint Size; * public uint ChecksumV1; * public uint Empty; * public byte[] Contents; */ } fEntry = 0; for (int i = 0; i < ArchiveHead1.FileCount; i++) { bw.Write(ArchiveFiles1[i].Contents); fEntry += ArchiveFiles1[i].Size; while ((fEntry & 0xF) != 0) { fEntry += 4; bw.Write(Convert.ToUInt32(0)); } } bw.Close(); } else if (ArchiveOpen == 2) { bw.Write(Convert.ToUInt32(0x000000fc)); bw.Write(ArchiveHead2.unknown1); bw.Write(Convert.ToUInt32(0x12345678)); bw.Write(ArchiveHead2.unknown2); bw.Write(ArchiveHead2.unknown3); if (ArchiveHead2.Version.Length > 0) { bw.Write(ArchiveHead2.Version.ToCharArray()); for (int i = (ArchiveHead2.Version.Length + 0x14); i < 0x98; i++) { bw.Write(Convert.ToChar(0)); } } else { for (int i = 0x14; i < 0x98; i += 4) { bw.Write(Convert.ToUInt32(0x00000000)); } } bw.Write(ArchiveHead2.FileCount); bw.Write(Convert.ToUInt32(0x0000005c)); uint Entry = (ArchiveHead2.FileCount * 0x5c) + 0xa0; for (int i = 0; i < ArchiveHead2.FileCount; i++) { bw.Write(Convert.ToUInt32(0x0000005c)); bw.Write(ArchiveFiles2[i].FullPath.ToCharArray()); for (int i2 = ArchiveFiles2[i].FullPath.Length; i2 < 0x40; i2++) { bw.Write(Convert.ToChar(0)); } bw.Write(Entry); bw.Write(ArchiveFiles2[i].Size); bw.Write(Convert.ToUInt32(0x00000000)); bw.Write(Convert.ToUInt32(0x00000000)); bw.Write(Convert.ToUInt32(0x00000000)); bw.Write(Convert.ToUInt32(0x00000000)); Entry += ArchiveFiles2[i].Size; } for (int i = 0; i < ArchiveHead2.FileCount; i++) { bw.Write(ArchiveFiles2[i].Contents); } bw.Close(); } return(true); }
public MATWriter(string name, string filepath, ushort[] data, int height, int width) { #region HeaderFields // allocate headerTextField headerTextField = new byte[128]; // allocate tagField tagField = new byte[8]; // Set default string headerTextFieldDefault = "MATLAB 5.0 MAT-file, Platform: WIN64, Created on: Thu Nov 13 10:10:27 1997"; // Write header string (ASCII) System.Buffer.BlockCopy(Encoding.ASCII.GetBytes(headerTextFieldDefault), 0, headerTextField, 0, headerTextFieldDefault.Length); // Write standard header for creating a MAT-file System.Buffer.BlockCopy(new byte[] { 0x01, 0x00 }, 0, headerTextField, 124, 2); // Write MI characters, to signify, that a small endian is used. System.Buffer.BlockCopy(Encoding.ASCII.GetBytes("MI"), 0, headerTextField, 126, 2); // Write the data type field (Uint16) System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x00, 0x0E }, 0, tagField, 0, 4); #endregion #region Array type field // allocate arrayTagField arrayTagField = new byte[8]; // allocate arrayField arrayField = new byte[8]; // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x08 }, 0, arrayTagField, 0, 8); // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x04, 0x0B, 0x00, 0x00, 0x00, 0x00 }, 0, arrayField, 0, 8); #endregion #region Dimensions field // allocate arrayTagField dimTagField = new byte[8]; // allocate arrayField dimField = new byte[8]; // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x08 }, 0, dimTagField, 0, 8); // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(BitConverter.GetBytes((uint)width).Reverse().ToArray(), 0, dimField, 0, 4); System.Buffer.BlockCopy(BitConverter.GetBytes((uint)height).Reverse().ToArray(), 0, dimField, 4, 4); #endregion #region name field // allocate arrayTagField nameTagField = new byte[8]; // allocate arrayField nameField = new byte[8]; // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08 }, 0, nameTagField, 0, 8); if (name.Length < 8) { name = name + "________"; // adds spaces, to fill out the name (has to be 8 characters) } // write the needed values for a standard Uint16 array System.Buffer.BlockCopy(Encoding.ASCII.GetBytes(name.ToCharArray(0, 8)), 0, nameField, 0, 8); #endregion #region DataType // Allocate datatype dataType = new byte[8]; // write the datatype for a standard Uint16 array System.Buffer.BlockCopy(new byte[] { 0x00, 0x00, 0x00, 0x04 }, 0, dataType, 0, 4); #endregion #region DataPadding int dataLength = 2 * width * height; int rem = (dataLength + 4) % 8; if (rem > 0) { dataPadding = new byte[rem]; } #endregion #region Data length calculation int length = arrayField.Length + arrayTagField.Length + dimField.Length + dimTagField.Length + nameField.Length + nameTagField.Length + dataType.Length + dataPadding.Length + 2 * width * height; #endregion #region Writing to the .mat file // Open and ready it for file writing System.IO.FileStream mlFile = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(mlFile); // Write the amount of data of the complete matrix (with array headers and so on) System.Buffer.BlockCopy(BitConverter.GetBytes((uint)length).Reverse().ToArray(), 0, tagField, 4, 4); // write the amount of actual data bytes System.Buffer.BlockCopy(BitConverter.GetBytes((uint)dataLength).Reverse().ToArray(), 0, dataType, 4, 4); // Open file and write to it bw.Write(headerTextField); bw.Write(tagField); bw.Write(arrayTagField); bw.Write(arrayField); bw.Write(dimTagField); bw.Write(dimField); bw.Write(nameTagField); bw.Write(nameField); bw.Write(dataType); foreach (ushort depthpixel in data) { bw.Write(BitConverter.GetBytes(depthpixel).Reverse().ToArray()); } if (rem > 0) { bw.Write(dataPadding); } bw.Close(); mlFile.Close(); #endregion }
public override void Close() { base.Close(); file.Close(); System.GC.SuppressFinalize(this); }
/// <summary> /// Recebe um arquivo. /// </summary> /// <returns>Nome do arquivo.</returns> /// <param name="p_endpoint">Ponto de comunicação.</param> /// <exception cref="Spartacus.Net.Exception">Exceção pode ocorrer quando não conseguir receber o arquivo.</exception> public string RecvFile(int p_endpoint) { System.IO.FileStream v_file; System.IO.BinaryWriter v_writer; Spartacus.Net.Packet v_packetrecv, v_packetsend; int v_numpackets, v_sequence; try { // recebendo nome do arquivo v_packetrecv = this.Recv(p_endpoint); if (v_packetrecv.v_type != Spartacus.Net.PacketType.FILE) { return(null); } v_file = new System.IO.FileStream(v_packetrecv.GetString(), System.IO.FileMode.Create, System.IO.FileAccess.Write); v_writer = new System.IO.BinaryWriter(v_file); // enviando ack v_packetsend = new Spartacus.Net.Packet(Spartacus.Net.PacketType.ACK, ""); this.Send(p_endpoint, v_packetsend); // recebendo primeiro pacote de dados do arquivo v_packetrecv = this.Recv(p_endpoint); v_sequence = 0; v_numpackets = v_packetrecv.v_numpackets; // se a sequencia estah errada, entao precisa tratar um erro // if (v_packet.v_sequence != v_sequence) v_writer.Write(v_packetrecv.v_data); // enviando ack v_packetsend = new Spartacus.Net.Packet(Spartacus.Net.PacketType.ACK, v_sequence, v_numpackets, ""); this.Send(p_endpoint, v_packetsend); v_sequence++; while (v_sequence < v_numpackets) { // recebendo pacote v_packetrecv = this.Recv(p_endpoint); // se a sequencia estah errada, entao precisa tratar um erro // if (v_packet.v_sequence != v_sequence) // se o numero de pacotes estah errado, entao precisa tratar um erro // if (v_packet.v_numpackets != v_numpackets) // acumulando conteudo dos dados do pacote na string v_writer.Write(v_packetrecv.v_data); // enviando ack v_packetsend = new Spartacus.Net.Packet(Spartacus.Net.PacketType.ACK, v_sequence, v_numpackets, ""); this.Send(p_endpoint, v_packetsend); v_sequence++; } v_writer.Flush(); v_writer.Close(); return(v_file.Name); } catch (Spartacus.Net.Exception e) { throw e; } catch (System.Exception e) { throw new Spartacus.Net.Exception(e); } }
/// <summary> /// Writes a Pac1 file. [Useable by scripts and interface components alike.] /// </summary> /// <param name="filename">The location of the final saved file...</param> /// <param name="Direct_Data">Array of Completed Direct Sound Simulations Required</param> /// <param name="IS_Data">Array of Completed Image Source Simulations. Enter null if opted out.</param> /// <param name="Receiver">Array of Completed Ray-Tracing Simulation Receivers. Enter null if opted out.</param> public static void Write_Pac1(string filename, Direct_Sound[] Direct_Data, ImageSourceData[] IS_Data = null, Environment.Receiver_Bank[] Receiver = null) { if (Direct_Data == null && IS_Data == null && IS_Data == null && Receiver != null) { System.Windows.Forms.MessageBox.Show("There is no simulated data to save."); return; } Pachyderm_Acoustic.UI.PachydermAc_PlugIn plugin = Pachyderm_Acoustic.UI.PachydermAc_PlugIn.Instance; System.IO.BinaryWriter sw = new System.IO.BinaryWriter(System.IO.File.Open(filename, System.IO.FileMode.Create)); //1. Date & Time sw.Write(System.DateTime.Now.ToString()); //2. Plugin Version... if less than 1.1, assume only 1 source. sw.Write(plugin.Version); //3. Cut off Time (seconds) and SampleRate sw.Write((double)Receiver[0].CO_Time);//CO_TIME.Value); sw.Write(Receiver[0].SampleRate); //4.0 Source Count(int) Rhino.Geometry.Point3d[] SRC; plugin.SourceOrigin(out SRC); sw.Write(SRC.Length); for (int i = 0; i < SRC.Length; i++) { //4.1 Source Location x (double) sw.Write(SRC[i].X); //4.2 Source Location y (double) sw.Write(SRC[i].Y); //4.3 Source Location z (double) sw.Write(SRC[i].Z); } //5. No of Receivers sw.Write(Receiver[0].Rec_List.Length); //6. Write the coordinates of each receiver point //6b. Write the environmental characteristics at each receiver point (Rho * C); V2.0 only... for (int q = 0; q < Receiver[0].Rec_List.Length; q++) { sw.Write(Receiver[0].Rec_List[q].H_Origin.x); sw.Write(Receiver[0].Rec_List[q].H_Origin.y); sw.Write(Receiver[0].Rec_List[q].H_Origin.z); sw.Write(Receiver[0].Rec_List[q].Rho_C); } for (int s = 0; s < SRC.Length; s++) { if (Direct_Data != null) { //7. Write Direct Sound Data Direct_Data[s].Write_Data(ref sw); } if (IS_Data[0] != null) { //8. Write Image Source Sound Data IS_Data[s].Write_Data(ref sw); } if (Receiver != null) { //9. Write Ray Traced Sound Data Receiver[s].Write_Data(ref sw); } } sw.Write("End"); sw.Close(); }
public bool DownloadFile(long nFileSize) { System.Net.WebClient webClient = null; System.IO.Stream stream = null; System.IO.BinaryWriter m_strmFileWriter = null; byte[] strBuffer = new byte[1025]; int length = 1024, bytesread; long fileSize = 0, contentLength, nTotalBytesPerInterval; System.DateTime dtTempoAnterior, dtTempoAtual; double dTaxa; m_nTentaivas++; if (m_arrURLSorted == null) { if (SetupURLList() == false) { return(false); } if (m_arrURLSorted == null || m_arrURLSorted.Count == 0) { return(false); } } webClient = new System.Net.WebClient(); for (int i = 0; i < m_arrURLSorted.Count; i++) { try { try { stream = webClient.OpenRead((string)m_arrURLSorted.GetByIndex(i)); } catch (System.Net.WebException) { continue; } catch (System.Exception) { webClient = null; return(false); } contentLength = System.Int64.Parse(webClient.ResponseHeaders.Get("Content-Length")); if (nFileSize >= 0) { if (System.IO.File.Exists(m_strFile)) { System.IO.FileInfo tmpFile = new System.IO.FileInfo(m_strFile); long nDiscFileSize = tmpFile.Length; if (nFileSize == contentLength && nDiscFileSize == contentLength) { OnCallFeedback(nFileSize, nFileSize); m_bOK = true; return(true); } if (nFileSize != contentLength) { fileSize = contentLength; } else { fileSize = nFileSize; } if (fileSize != nDiscFileSize) { System.IO.File.Delete(m_strFile); } } else { fileSize = contentLength; } } else { m_nFileSize = fileSize; fileSize = contentLength; } try { m_strmFileWriter = new System.IO.BinaryWriter(new System.IO.FileStream(m_strFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None)); if (m_strmFileWriter == null) { webClient = null; return(false); } } catch (System.Exception) { webClient = null; return(false); } dtTempoAnterior = System.DateTime.Now; nTotalBytesPerInterval = 0; do { bytesread = stream.Read(strBuffer, 0, length); if (bytesread > 0) { dtTempoAtual = System.DateTime.Now; m_strmFileWriter.Write(strBuffer, 0, bytesread); fileSize -= bytesread; nTotalBytesPerInterval += bytesread; OnCallFeedback(nFileSize, nFileSize - fileSize); System.TimeSpan tDiff = dtTempoAtual.Subtract(dtTempoAnterior); if (tDiff.TotalSeconds >= 0.5) { dTaxa = nTotalBytesPerInterval / tDiff.TotalSeconds; OnCallTimeFeedback(dTaxa, fileSize / dTaxa, nFileSize - fileSize); dtTempoAnterior = dtTempoAtual; nTotalBytesPerInterval = 0; } } } while (bytesread > 0); } finally { if (m_strmFileWriter != null) { m_strmFileWriter.Close(); } if (stream != null) { stream.Close(); } } if (fileSize == 0) { webClient = null; m_bOK = true; return(true); } } webClient = null; return(false); }
public bool Save(string baseDir) { if (!modified) { return(true); // doh } if (!saveEnabled) { //don't save return(true); } string fileName = FileName(); string filename = baseDir + fileName; System.IO.Stream fileout = null; System.IO.BinaryWriter file = null; //try { if (!System.IO.Directory.Exists(baseDir)) { System.IO.Directory.CreateDirectory(baseDir); } //} catch { }; int n_spots = 0; int n_steps = 0; try { fileout = System.IO.File.Create(filename + ".new"); if (fileout != null) { file = new System.IO.BinaryWriter(fileout); if (file != null) { file.Write(FILE_MAGIC); List <Spot> spots = GetAllSpots(); foreach (Spot s in spots) { file.Write(SPOT_MAGIC); file.Write((uint)0); // reserved file.Write((uint)s.flags); file.Write((float)s.X); file.Write((float)s.Y); file.Write((float)s.Z); uint n_paths = (uint)s.n_paths; file.Write((uint)n_paths); for (uint i = 0; i < n_paths; i++) { uint off = i * 3; file.Write((float)s.paths[off]); file.Write((float)s.paths[off + 1]); file.Write((float)s.paths[off + 2]); n_steps++; } n_spots++; } file.Write(FILE_ENDMAGIC); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } String old = filename + ".bak"; if (System.IO.File.Exists(old)) { System.IO.File.Delete(old); } if (System.IO.File.Exists(filename)) { System.IO.File.Move(filename, old); } System.IO.File.Move(filename + ".new", filename); if (System.IO.File.Exists(old)) { System.IO.File.Delete(old); } modified = false; } else { Log("Save failed"); } Log("Saved " + fileName + " " + n_spots + " spots " + n_steps + " steps"); } catch (Exception e) { Log("Save failed " + e); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } return(false); }
public void SetDataOld(List <ResourceLocationData> locations, List <string> labels) { var tmpEntries = new List <Entry>(locations.Count); var providers = new List <string>(10); var providerIndices = new Dictionary <string, int>(10); var countEstimate = locations.Count * 2 + labels.Count; var internalIdToEntryIndex = new Dictionary <string, int>(countEstimate); var internalIdList = new List <string>(countEstimate); List <object> keys = new List <object>(countEstimate); var keyToIndex = new Dictionary <object, int>(countEstimate); var tmpBuckets = new Dictionary <int, List <int> >(countEstimate); for (int i = 0; i < locations.Count; i++) { var rld = locations[i]; int providerIndex = 0; if (!providerIndices.TryGetValue(rld.m_provider, out providerIndex)) { providerIndices.Add(rld.m_provider, providerIndex = providers.Count); providers.Add(rld.m_provider); } int internalIdIndex = 0; if (!internalIdToEntryIndex.TryGetValue(rld.m_internalId, out internalIdIndex)) { internalIdToEntryIndex.Add(rld.m_internalId, internalIdIndex = internalIdList.Count); internalIdList.Add(rld.m_internalId); } var e = new Entry() { internalId = internalIdIndex, providerIndex = (byte)providerIndex, dependency = -1 }; if (rld.m_type == ResourceLocationData.LocationType.Int) { AddToBucket(tmpBuckets, keyToIndex, keys, int.Parse(rld.m_address), tmpEntries.Count, 1); } else if (rld.m_type == ResourceLocationData.LocationType.String) { AddToBucket(tmpBuckets, keyToIndex, keys, rld.m_address, tmpEntries.Count, 1); } if (!string.IsNullOrEmpty(rld.m_guid)) { AddToBucket(tmpBuckets, keyToIndex, keys, Hash128.Parse(rld.m_guid), tmpEntries.Count, 1); } if (rld.m_labelMask != 0) { for (int t = 0; t < labels.Count; t++) { if ((rld.m_labelMask & (1 << t)) != 0) { AddToBucket(tmpBuckets, keyToIndex, keys, labels[t], tmpEntries.Count, 100); } } } tmpEntries.Add(e); } for (int i = 0; i < locations.Count; i++) { var rld = locations[i]; int dependency = -1; if (rld.m_dependencies != null && rld.m_dependencies.Length > 0) { if (rld.m_dependencies.Length == 1) { dependency = keyToIndex[rld.m_dependencies[0]]; } else { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (var d in rld.m_dependencies) { sb.Append(d); } var key = sb.ToString().GetHashCode(); int keyIndex = -1; foreach (var d in rld.m_dependencies) { var ki = keyToIndex[d]; var depBucket = tmpBuckets[ki]; keyIndex = AddToBucket(tmpBuckets, keyToIndex, keys, key, depBucket[0], 10); } dependency = keyIndex; } var e = tmpEntries[i]; e.dependency = dependency; tmpEntries[i] = e; } } m_internalIds = internalIdList.ToArray(); m_providerIds = providers.ToArray(); var entryData = new byte[tmpEntries.Count * 4 * 3 + 4]; var offset = Serialize(entryData, tmpEntries.Count, 0); for (int i = 0; i < tmpEntries.Count; i++) { var e = tmpEntries[i]; offset = Serialize(entryData, e.internalId, offset); offset = Serialize(entryData, e.providerIndex, offset); offset = Serialize(entryData, e.dependency, offset); } m_entryDataString = Convert.ToBase64String(entryData); int bucketEntryCount = 0; var bucketList = new List <Bucket>(keys.Count); for (int i = 0; i < keys.Count; i++) { var bucketIndex = keyToIndex[keys[i]]; List <int> entries = tmpBuckets[bucketIndex]; bucketList.Add(new Bucket() { entries = entries.ToArray() }); bucketEntryCount += entries.Count; } var keyData = new List <byte>(bucketList.Count * 10); keyData.AddRange(BitConverter.GetBytes(bucketList.Count)); int dataOffset = 4; for (int i = 0; i < bucketList.Count; i++) { var bucket = bucketList[i]; bucket.dataOffset = dataOffset; bucketList[i] = bucket; var key = keys[i]; var kt = key.GetType(); if (kt == typeof(string)) { string str = key as string; byte[] tmp = System.Text.Encoding.Unicode.GetBytes(str); byte[] tmp2 = System.Text.Encoding.ASCII.GetBytes(str); if (System.Text.Encoding.Unicode.GetString(tmp) == System.Text.Encoding.ASCII.GetString(tmp2)) { keyData.Add((byte)KeyType.ASCIIString); keyData.AddRange(tmp2); dataOffset += tmp2.Length + 1; } else { keyData.Add((byte)KeyType.UnicodeString); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } } else if (kt == typeof(UInt32)) { byte[] tmp = BitConverter.GetBytes((UInt32)key); keyData.Add((byte)KeyType.UInt32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(UInt16)) { byte[] tmp = BitConverter.GetBytes((UInt16)key); keyData.Add((byte)KeyType.UInt16); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(Int32)) { byte[] tmp = BitConverter.GetBytes((Int32)key); keyData.Add((byte)KeyType.Int32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(int)) { byte[] tmp = BitConverter.GetBytes((UInt32)key); keyData.Add((byte)KeyType.UInt32); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } else if (kt == typeof(Hash128)) { var guid = (Hash128)key; byte[] tmp = System.Text.Encoding.ASCII.GetBytes(guid.ToString()); keyData.Add((byte)KeyType.Hash128); keyData.AddRange(tmp); dataOffset += tmp.Length + 1; } } m_keyDataString = Convert.ToBase64String(keyData.ToArray()); var bucketData = new byte[4 + bucketList.Count * 8 + bucketEntryCount * 4]; offset = Serialize(bucketData, bucketList.Count, 0); for (int i = 0; i < bucketList.Count; i++) { offset = Serialize(bucketData, bucketList[i].dataOffset, offset); offset = Serialize(bucketData, bucketList[i].entries.Length, offset); foreach (var e in bucketList[i].entries) { offset = Serialize(bucketData, e, offset); } } m_bucketDataString = Convert.ToBase64String(bucketData); #if SERIALIZE_CATALOG_AS_BINARY //TODO: investigate saving catalog as binary - roughly 20% size decrease, still needs a provider implementation var stream = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(stream); foreach (var i in m_internalIds) { bw.Write(i); } foreach (var p in m_providerIds) { bw.Write(p); } bw.Write(entryData); bw.Write(keyData.ToArray()); bw.Write(bucketData); bw.Flush(); bw.Close(); stream.Flush(); System.IO.File.WriteAllBytes("Library/catalog_binary.bytes", stream.ToArray()); System.IO.File.WriteAllText("Library/catalog_binary.txt", Convert.ToBase64String(stream.ToArray())); stream.Close(); #endif }
//File I/O Utilities private void Write_File() { if (Direct_Data == null && IS_Data == null && IS_Data == null && this.Receiver != null) { System.Windows.Forms.MessageBox.Show("There is no simulated data to save."); return; } System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog(); sf.DefaultExt = ".pac1"; sf.AddExtension = true; sf.Filter = "Pachyderm Ray Data file (*.pac1)|*.pac1|" + "All Files|"; if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK) { System.IO.BinaryWriter sw = new System.IO.BinaryWriter(System.IO.File.Open(sf.FileName, System.IO.FileMode.Create)); //1. Date & Time sw.Write(System.DateTime.Now.ToString()); //2. Plugin Version... if less than 1.1, assume only 1 source. sw.Write(plugin.Version); //3. Cut off Time (seconds) and SampleRate sw.Write((double)CO_TIME.Value); sw.Write(SampleRate); //4.0 Source Count(int) Hare.Geometry.Point[] SRC; plugin.SourceOrigin(out SRC); sw.Write(SRC.Length); for (int i = 0; i < SRC.Length; i++) { //4.1 Source Location x (double) sw.Write(SRC[i].x); //4.2 Source Location y (double) sw.Write(SRC[i].y); //4.3 Source Location z (double) sw.Write(SRC[i].z); } //5. No of Receivers sw.Write(Recs.Length); //6. Write the coordinates of each receiver point for (int q = 0; q < Recs.Length; q++) { sw.Write(Recs[q].x); sw.Write(Recs[q].y); sw.Write(Recs[q].z); sw.Write(Receiver[0].Rec_List[q].Rho_C); } for (int s = 0; s < SRC.Length; s++) { if (Direct_Data != null) { //7. Write Direct Sound Data Direct_Data[s].Write_Data(ref sw); } if (IS_Data[0] != null) { //8. Write Image Source Sound Data IS_Data[s].Write_Data(ref sw); } if (Receiver != null) { //9. Write Ray Traced Sound Data Receiver[s].Write_Data(ref sw); } } sw.Write("End"); sw.Close(); } }
public bool Save(string baseDir) { if (!modified) return true; // doh string fileName = FileName(); string filename = baseDir + fileName; System.IO.Stream fileout = null; System.IO.BinaryWriter file = null; //try { if (!System.IO.Directory.Exists(baseDir)) System.IO.Directory.CreateDirectory(baseDir); //} catch { }; int n_spots = 0; int n_steps = 0; try { fileout = System.IO.File.Create(filename + ".new"); if (fileout != null) { file = new System.IO.BinaryWriter(fileout); if (file != null) { file.Write(FILE_MAGIC); List<Spot> spots = GetAllSpots(); foreach (Spot s in spots) { file.Write(SPOT_MAGIC); file.Write((uint)0); // reserved file.Write((uint)s.flags); file.Write((float)s.X); file.Write((float)s.Y); file.Write((float)s.Z); uint n_paths = (uint)s.n_paths; file.Write((uint)n_paths); for (uint i = 0; i < n_paths; i++) { uint off = i * 3; file.Write((float)s.paths[off]); file.Write((float)s.paths[off + 1]); file.Write((float)s.paths[off + 2]); n_steps++; } n_spots++; } file.Write(FILE_ENDMAGIC); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } String old = filename + ".bak"; if (System.IO.File.Exists(old)) System.IO.File.Delete(old); if (System.IO.File.Exists(filename)) System.IO.File.Move(filename, old); System.IO.File.Move(filename + ".new", filename); if (System.IO.File.Exists(old)) System.IO.File.Delete(old); modified = false; } else { Log("Save failed"); } Log("Saved " + fileName + " " + n_spots + " spots " + n_steps + " steps"); } catch (Exception e) { Log("Save failed " + e); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } return false; }
public bool PickUp() { COTFEvents.Instance.OnLootPickup.Invoke(); if (item.PickUpAll) { if (!GameSetup.IsMpClient) { if (Player.Inventory.Instance.AddItem(item, amount)) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(4); w.Write(ID); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Others); answerStream.Close(); } PickUpManager.RemovePickup(ID); Destroy(gameObject); return(true); } } else if (Player.Inventory.Instance.HasSpaceFor(item, amount)) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(25); w.Write(ID); w.Write(amount); w.Write(ModReferences.ThisPlayerID); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.OnlyServer); answerStream.Close(); } } } else { if (!GameSetup.IsMpClient) { if (Player.Inventory.Instance.AddItem(item)) { amount--; if (amount <= 0) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(4); w.Write(ID); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.Everyone); answerStream.Close(); } PickUpManager.RemovePickup(ID); Destroy(gameObject); } return(true); } } else if (Player.Inventory.Instance.HasSpaceFor(item)) { using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(25); w.Write(ID); w.Write(1); w.Write(ModReferences.ThisPlayerID); w.Close(); } Network.NetworkManager.SendLine(answerStream.ToArray(), Network.NetworkManager.Target.OnlyServer); answerStream.Close(); } } } return(false); }
private void Window_Loaded(object sender, RoutedEventArgs e) { if (CommonManager.Instance.NWMode == true) { if (iniConnectNW == false) { if (ConnectCmd(false) == true) { byte[] binData; if (cmd.SendFileCopy("ChSet5.txt", out binData) == 1) { string filePath = SettingPath.SettingFolderPath; System.IO.Directory.CreateDirectory(filePath); filePath += "\\ChSet5.txt"; using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(System.IO.File.Create(filePath))) { w.Write(binData); w.Close(); } ChSet5.LoadFile(); } iniConnectNW = true; } } } // foreach (KeyValuePair<string, Button> kvp1 in this.buttonList) { switch (kvp1.Key) { case "設定": kvp1.Value.ToolTip = "Ctrl + C"; break; case "検索": kvp1.Value.ToolTip = "Ctrl + F"; break; case "終了": kvp1.Value.ToolTip = "Alt + F4"; break; } } }
public static void CreatePlayerBlackHole() { float damage = (ModdedPlayer.Stats.spell_blackhole_damage + ModdedPlayer.Stats.spellFlatDmg * ModdedPlayer.Stats.spell_blackhole_damageScaling) * ModdedPlayer.Stats.TotalMagicDamageMultiplier; Transform t = Camera.main.transform; Vector3 point = Vector3.zero; var hits1 = Physics.RaycastAll(t.position, t.forward, 35f); foreach (var hit in hits1) { if (hit.transform.root != LocalPlayer.Transform.root) { point = hit.point; break; } } if (point == Vector3.zero) { point = LocalPlayer.Transform.position + t.forward * 30; } //RaycastHit[] hits = Physics.RaycastAll(Camera.main.transform.position,Camera.main.transform.forward, 160f); //for (int i = 0; i < hits.Length; i++) //{ // if (hits[i].transform.root != LocalPlayer.Transform.root) //{ using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) { w.Write(3); w.Write(1); w.Write(point.x); w.Write(point.y - 1); w.Write(point.z); w.Write(false); w.Write(damage); w.Write(ModdedPlayer.Stats.spell_blackhole_duration); w.Write(ModdedPlayer.Stats.spell_blackhole_radius); w.Write(ModdedPlayer.Stats.spell_blackhole_pullforce); w.Write(ModdedPlayer.Stats.i_sparkOfLightAfterDark ? ModReferences.ThisPlayerID : ""); w.Close(); } NetworkManager.SendLine(answerStream.ToArray(), NetworkManager.Target.Everyone); answerStream.Close(); } // return; // } //} //Vector3 pos = Camera.main.transform.position + Camera.main.transform.forward * 10; //using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream()) //{ // using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream)) // { // w.Write(3); // w.Write(1); // w.Write(pos.x); // w.Write(pos.y); // w.Write(pos.z); // w.Write(false); // w.Write(damage); // w.Write(BLACKHOLE_duration); // w.Write(BLACKHOLE_radius); // w.Write(BLACKHOLE_pullforce); // w.Close(); // } // ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Everyone); // answerStream.Close(); //} }
private void PrintRow(System.Data.DataTable pDataTable, System.Data.DataRow pRow, StringBuilder pBuilder) { pBuilder.Append("<tr>"); //object[] Items = pRow.ItemArray; for (int i = 0; i < this.IdentifierList.Count; i++) { string ColumnName = this.IdentifierList[i]; DataColumn C = pDataTable.Columns[ColumnName]; if (C == null) { continue; } if (PrintColumn(C.ColumnName)) { string columnDataType = C.DataType.ToString(); switch (columnDataType) { case "System.Int16": case "System.Int32": case "System.Int64": case "System.Double": case "System.Single": case "System.Decimal": pBuilder.Append("<td align=\"right\">"); break; default: pBuilder.Append("<td>"); break; } //pBuilder.Append("<td>"); if (pRow[C.ColumnName] == DBNull.Value) { pBuilder.Append(repOfMissing); } else { switch (C.DataType.Name) { case "Boolean": pBuilder.Append((Convert.ToBoolean(pRow[C.ColumnName]) ? repOfYes : repOfNo)); break; case "Byte": if (this.isEpi7Project) { pBuilder.Append((Convert.ToBoolean(pRow[C.ColumnName]) ? repOfYes : repOfNo)); } else { pBuilder.Append(pRow[C.ColumnName]); } break; case "Byte[]": string extension = GetImageExtension(new System.IO.MemoryStream((byte[])pRow[C.ColumnName])); string imgFileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N") + "." + extension; System.IO.FileStream imgStream = System.IO.File.OpenWrite(imgFileName); System.IO.BinaryWriter imgWriter = new System.IO.BinaryWriter(imgStream); imgWriter.Write((byte[])pRow[C.ColumnName]); imgWriter.Close(); imgStream.Close(); pBuilder.Append("<img src=\"" + imgFileName + "\"/>"); break; case "Single": pBuilder.Append(string.Format("{0:0.##}", pRow[C.ColumnName])); break; case "Double": case "Float": pBuilder.Append(string.Format("{0:0.##########}", pRow[C.ColumnName])); break; case "DateTime": if (this.CurrentView == null) { pBuilder.Append(pRow[C.ColumnName]); } else { IVariable var = (IVariable)this.Context.GetVariable(C.ColumnName); if (var == null) { break; } if (var.VarType == VariableType.DataSource) { try { if (this.CurrentView.Fields.Exists(C.ColumnName) && this.CurrentView.Fields[C.ColumnName] is Epi.Fields.DateField) { pBuilder.Append(((DateTime)pRow[C.ColumnName]).ToShortDateString()); // } else if (this.CurrentView.Fields.Exists(C.ColumnName) && this.CurrentView.Fields[C.ColumnName] is Epi.Fields.TimeField) { pBuilder.Append(((DateTime)pRow[C.ColumnName]).ToShortTimeString()); // } else { pBuilder.Append(pRow[C.ColumnName]); } } catch (Exception ex) { pBuilder.Append(pRow[C.ColumnName]); } } else { if (pRow[C.ColumnName] != DBNull.Value) { System.DateTime PrintDate = (System.DateTime)pRow[C.ColumnName]; if (var.DataType == DataType.Date) { pBuilder.Append(PrintDate.ToShortDateString()); } else if (var.DataType == DataType.Time) { pBuilder.Append(PrintDate.ToShortTimeString()); } else { pBuilder.Append(pRow[C.ColumnName]); } } else { pBuilder.Append(pRow[C.ColumnName]); } } } break; default: pBuilder.Append(pRow[C.ColumnName]); break; } } pBuilder.Append("</td>"); } } pBuilder.Append("</tr>"); }
/// <summary>check that the query weight is serializable. </summary> /// <throws> IOException if serialization check fail. </throws> private static void CheckSerialization(Query q, Searcher s) { Weight w = q.Weight(s); try { System.IO.MemoryStream bos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(oos.BaseStream, w); oos.Close(); System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray())); formatter.Deserialize(ois.BaseStream); ois.Close(); //skip rquals() test for now - most weights don't overide equals() and we won't add this just for the tests. //TestCase.assertEquals("writeObject(w) != w. ("+w+")",w2,w); } catch (System.Exception e) { System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e); throw e2; } }
/// <summary> /// decrypt /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click_2(object sender, RoutedEventArgs e) { byte[] buffer = null; using (System.IO.FileStream fs = System.IO.File.OpenRead(tbPrivate.Text.Trim())) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs)) { buffer = br.ReadBytes((int)fs.Length); helper.PrivateKey = encoding.GetString(buffer); } } string decFilePath = tbDec.Text.Trim(); //get file which is being encrypting using (System.IO.FileStream fs = System.IO.File.OpenRead(decFilePath)) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs)) { buffer = br.ReadBytes((int)fs.Length); } } using (System.IO.FileStream fs = System.IO.File.OpenWrite(decFilePath + decSuffix)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { int i = 0; //每次加密的block 大小 int blocksize = RSAHelper.KeySize / 8; int currentSize; do { if (i + blocksize <= buffer.Length) { currentSize = blocksize; } else { currentSize = buffer.Length % blocksize; } byte[] blockBuffer = new byte[currentSize]; Array.Copy(buffer, i, blockBuffer, 0, currentSize); var temp = helper.DecryptData(blockBuffer); bw.Write(temp); i += blocksize; } while (i < buffer.Length); bw.Close(); } tbResult.Text = "操作完成"; } }
public MainWindow() { CommonManager.Instance.NWMode = true; Settings.LoadFromXmlFileNW(); ChSet5.LoadFile(); cmd.SetSendMode(true); cmd.SetNWSetting(Settings.Instance.NWServerIP, Settings.Instance.NWServerPort); CommonManager.Instance.ReloadCustContentColorList(); CommonManager.Instance.DB.SetNoAutoReloadEPG(Settings.Instance.NgAutoEpgLoadNW); if (Settings.Instance.NoStyle == 0) { ResourceDictionary rd = new ResourceDictionary(); rd.MergedDictionaries.Add( Application.LoadComponent(new Uri("/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35;component/themes/aero.normalcolor.xaml", UriKind.Relative)) as ResourceDictionary //Application.LoadComponent(new Uri("/PresentationFramework.Classic, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Classic.xaml", UriKind.Relative)) as ResourceDictionary ); this.Resources = rd; } mutex = new System.Threading.Mutex(false, "Global\\EpgTimer_BonNW"); if (!mutex.WaitOne(0, false)) { CheckCmdLine(); mutex.Close(); mutex = null; closeFlag = true; Close(); return; } if (CommonManager.Instance.NWMode == false) { bool startExe = false; try { if (ServiceCtrlClass.ServiceIsInstalled("EpgTimer Service") == true) { if (ServiceCtrlClass.IsStarted("EpgTimer Service") == false) { bool check = false; for (int i = 0; i < 5; i++) { if (ServiceCtrlClass.StartService("EpgTimer Service") == true) { check = true; } System.Threading.Thread.Sleep(1000); if (ServiceCtrlClass.IsStarted("EpgTimer Service") == true) { check = true; } } if (check == false) { MessageBox.Show("サービスの開始に失敗しました。\r\nVista以降のOSでは、管理者権限で起動されている必要があります。"); closeFlag = true; Close(); return; } else { serviceMode = true; startExe = true; } } else { serviceMode = true; startExe = true; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); serviceMode = false; } try { if (serviceMode == false) { String moduleFolder = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); String exePath = moduleFolder + "\\EpgTimerSrv.exe"; System.Diagnostics.Process process = System.Diagnostics.Process.Start(exePath); startExe = true; } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); startExe = false; } if (startExe == false) { MessageBox.Show("EpgTimerSrv.exeの起動ができませんでした"); closeFlag = true; Close(); return; } } InitializeComponent(); initExe = true; try { if (Settings.Instance.WakeMin == true) { this.Visibility = System.Windows.Visibility.Hidden; } //ウインドウ位置の復元 if (Settings.Instance.MainWndTop != -100) { this.Top = Settings.Instance.MainWndTop; } if (Settings.Instance.MainWndLeft != -100) { this.Left = Settings.Instance.MainWndLeft; } if (Settings.Instance.MainWndWidth != -100) { this.Width = Settings.Instance.MainWndWidth; } if (Settings.Instance.MainWndHeight != -100) { this.Height = Settings.Instance.MainWndHeight; } this.WindowState = Settings.Instance.LastWindowState; //上のボタン Button settingButton = new Button(); settingButton.MinWidth = 75; settingButton.Margin = new Thickness(2, 2, 2, 5); settingButton.Click += new RoutedEventHandler(settingButton_Click); settingButton.Content = "設定"; if (Settings.Instance.NoStyle == 0) { settingButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("設定", settingButton); Button searchButton = new Button(); searchButton.MinWidth = 75; searchButton.Margin = new Thickness(2, 2, 2, 5); searchButton.Click += new RoutedEventHandler(searchButton_Click); searchButton.Content = "検索"; if (Settings.Instance.NoStyle == 0) { searchButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("検索", searchButton); Button closeButton = new Button(); closeButton.MinWidth = 75; closeButton.Margin = new Thickness(2, 2, 2, 5); closeButton.Click += new RoutedEventHandler(closeButton_Click); closeButton.Content = "終了"; if (Settings.Instance.NoStyle == 0) { closeButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("終了", closeButton); Button stanbyButton = new Button(); stanbyButton.MinWidth = 75; stanbyButton.Margin = new Thickness(2, 2, 2, 5); stanbyButton.Click += new RoutedEventHandler(standbyButton_Click); stanbyButton.Content = "スタンバイ"; if (Settings.Instance.NoStyle == 0) { stanbyButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("スタンバイ", stanbyButton); Button suspendButton = new Button(); suspendButton.MinWidth = 75; suspendButton.Margin = new Thickness(2, 2, 2, 5); suspendButton.Click += new RoutedEventHandler(suspendButton_Click); suspendButton.Content = "休止"; if (Settings.Instance.NoStyle == 0) { suspendButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("休止", suspendButton); Button epgCapButton = new Button(); epgCapButton.MinWidth = 75; epgCapButton.Margin = new Thickness(2, 2, 2, 5); epgCapButton.Click += new RoutedEventHandler(epgCapButton_Click); epgCapButton.Content = "EPG取得"; if (Settings.Instance.NoStyle == 0) { epgCapButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("EPG取得", epgCapButton); Button epgReloadButton = new Button(); epgReloadButton.MinWidth = 75; epgReloadButton.Margin = new Thickness(2, 2, 2, 5); epgReloadButton.Click += new RoutedEventHandler(epgReloadButton_Click); epgReloadButton.Content = "EPG再読み込み"; if (Settings.Instance.NoStyle == 0) { epgReloadButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("EPG再読み込み", epgReloadButton); Button custum1Button = new Button(); custum1Button.MinWidth = 75; custum1Button.Margin = new Thickness(2, 2, 2, 5); custum1Button.Click += new RoutedEventHandler(custum1Button_Click); custum1Button.Content = "カスタム1"; if (Settings.Instance.NoStyle == 0) { custum1Button.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("カスタム1", custum1Button); Button custum2Button = new Button(); custum2Button.MinWidth = 75; custum2Button.Margin = new Thickness(2, 2, 2, 5); custum2Button.Click += new RoutedEventHandler(custum2Button_Click); custum2Button.Content = "カスタム2"; if (Settings.Instance.NoStyle == 0) { custum2Button.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("カスタム2", custum2Button); Button nwTVEndButton = new Button(); nwTVEndButton.MinWidth = 75; nwTVEndButton.Margin = new Thickness(2, 2, 2, 5); nwTVEndButton.Click += new RoutedEventHandler(nwTVEndButton_Click); nwTVEndButton.Content = "NetworkTV終了"; if (Settings.Instance.NoStyle == 0) { nwTVEndButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("NetworkTV終了", nwTVEndButton); Button logViewButton = new Button(); logViewButton.MinWidth = 75; logViewButton.Margin = new Thickness(2, 2, 2, 5); logViewButton.Click += new RoutedEventHandler(logViewButton_Click); logViewButton.Content = "情報通知ログ"; if (Settings.Instance.NoStyle == 0) { logViewButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("情報通知ログ", logViewButton); Button connectButton = new Button(); connectButton.MinWidth = 75; connectButton.Margin = new Thickness(2, 2, 2, 5); connectButton.Click += new RoutedEventHandler(connectButton_Click); connectButton.Content = "再接続"; if (Settings.Instance.NoStyle == 0) { connectButton.Style = (Style)App.Current.Resources["ButtonStyle1"]; } buttonList.Add("再接続", connectButton); ResetButtonView(); //タスクトレイの表示 taskTray = new TaskTrayClass(this); taskTray.Icon = Properties.Resources.TaskIconBlue; taskTray.Visible = true; taskTray.ContextMenuClick += new EventHandler(taskTray_ContextMenuClick); if (CommonManager.Instance.NWMode == false) { pipeServer = new PipeServer(); pipeName += System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); pipeEventName += System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); pipeServer.StartServer(pipeEventName, pipeName, OutsideCmdCallback, this); cmd.SendRegistGUI((uint)System.Diagnostics.Process.GetCurrentProcess().Id); CommonManager.Instance.DB.ReloadReserveInfo(); ReserveData item = new ReserveData(); if (CommonManager.Instance.DB.GetNextReserve(ref item) == true) { String timeView = item.StartTime.ToString("yyyy/MM/dd(ddd) HH:mm:ss ~ "); DateTime endTime = item.StartTime + TimeSpan.FromSeconds(item.DurationSecond); timeView += endTime.ToString("HH:mm:ss"); taskTray.Text = "次の予約:" + item.StationName + " " + timeView + " " + item.Title; } else { taskTray.Text = "次の予約なし"; } } ResetTaskMenu(); CheckCmdLine(); if (CommonManager.Instance.NWMode == true) { if (Settings.Instance.WakeReconnectNW == false) { return; } if (CommonManager.Instance.NW.ConnectServer(Settings.Instance.NWServerIP, Settings.Instance.NWServerPort, Settings.Instance.NWWaitPort, OutsideCmdCallback, this) == false) { return; } iniConnectNW = true; byte[] binData; if (cmd.SendFileCopy("ChSet5.txt", out binData) == 1) { string filePath = SettingPath.SettingFolderPath; System.IO.Directory.CreateDirectory(filePath); filePath += "\\ChSet5.txt"; using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(System.IO.File.Create(filePath))) { w.Write(binData); w.Close(); } ChSet5.LoadFile(); } CommonManager.Instance.DB.ReloadReserveInfo(); ReserveData item = new ReserveData(); if (CommonManager.Instance.DB.GetNextReserve(ref item) == true) { String timeView = item.StartTime.ToString("yyyy/MM/dd(ddd) HH:mm:ss ~ "); DateTime endTime = item.StartTime + TimeSpan.FromSeconds(item.DurationSecond); timeView += endTime.ToString("HH:mm:ss"); taskTray.Text = "次の予約:" + item.StationName + " " + timeView + " " + item.Title; } else { taskTray.Text = "次の予約なし"; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
public override void OnDone(Epoch time) { writer.Flush(); writer.Close(); }
private void OnToolbarItemClicked(object sender, ToolStripItemClickedEventArgs e) { //Toolbar handler - forward to main menu handler long actionID = 0; Action action = null; System.IO.FileStream fs = null; byte[] bytes = null; try { //Get the current action actionID = Convert.ToInt64(this.lsvActions.SelectedItems[0].Name); switch (e.ClickedItem.Name) { case "btnNew": this.ctxActionsNew.PerformClick(); break; case "btnPrint": this.ctxActionsPrint.PerformClick(); break; case "btnRefresh": this.ctxRefresh.PerformClick(); break; case "btnOpen": //Open the selected attachment int attachmentID = Convert.ToInt32(this.lsvAttachments.SelectedItems[0].Name); bytes = CustomerProxy.GetAttachment(attachmentID); string file = CustomerProxy.TempFolder + this.lsvAttachments.SelectedItems[0].Text.Trim(); fs = new System.IO.FileStream(file, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); writer.Write(bytes); writer.Flush(); writer.Close(); System.Diagnostics.Process.Start(file); break; case "btnAttach": //Save an attachment to the selected action OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.AddExtension = true; dlgOpen.Filter = "All Files (*.*) | *.*"; dlgOpen.FilterIndex = 0; dlgOpen.Title = "Select Attachment to Save..."; dlgOpen.FileName = ""; if (dlgOpen.ShowDialog(this) == DialogResult.OK) { string name = new System.IO.FileInfo(dlgOpen.FileName).Name; fs = new System.IO.FileStream(dlgOpen.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(fs); bytes = reader.ReadBytes((int)fs.Length); reader.Close(); bool created = CustomerProxy.CreateIssueAttachment(name, bytes, actionID); loadActions(); } break; case "btnSend": if (this.lsvActions.SelectedItems.Count > 0) { //Create new mail item if (OutlookApp == null) { return; } Outlook.MailItem item = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem); item.Subject = this.mIssue.Subject; item.Body = action.Comment; item.To = CustomerProxy.GetContact(this.mIssue.ContactID).Email; item.Display(false); } break; } } catch (Exception ex) { reportError(new ControlException("Unexpected error in IssueInspector.", ex)); } finally { if (fs != null) { fs.Close(); } } }
static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("子文件导入.exe PAK目录 子文件目录 新PAK目录 补丁数据输出"); return; } string dir_subs = args[1]; string dir_pak = args[0]; string dir_pak_new = args[2]; string data1 = args[3]; const string pa = @"\PSP_GAME\USRDIR\X0DATA\"; if (!System.IO.Directory.Exists(dir_pak) || !System.IO.Directory.Exists(dir_subs)) { Console.WriteLine("文件夹不存在!"); return; } System.IO.Directory.CreateDirectory(dir_pak_new); PAK.Pak pak = null; string pak_name = null; int count = 0; int count_p = 0; int off_subs = 4; System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.FileStream fs_data1 = new System.IO.FileStream(data1, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs_data1); fs_data1.Seek(8, 0); string[] subs = System.IO.Directory.GetFiles(dir_subs); foreach (string sub in subs) { Console.WriteLine("导入{0}...", sub.Substring(sub.LastIndexOf('\\') + 1)); string subname = sub.Substring(sub.LastIndexOf('\\') + 1).ToUpper(); string father; int id; bool zip; if (subname[0] >= '0' && subname[0] <= '9') { father = "SCRIPT.PAK"; } else { father = subname.Substring(0, subname.IndexOf('#')); father = father.Replace('_', '.'); subname = subname.Substring(subname.IndexOf('#') + 1); } string[] ts = subname.Split('.', '_', '#'); id = int.Parse(ts[0]); zip = subname.ToLower().IndexOf("_dat_gim") != -1 || subname.IndexOf(".dat.gim") != -1; if (pak_name != father) { if (pak != null) { pak.WriteTo(dir_pak_new + "\\" + pak_name); pak.Close(); fs_data1.Seek(off_subs, 0); bw.Write(pak.Num); bw.Write(count); fs_data1.Seek(count * 12, System.IO.SeekOrigin.Current); } pak_name = father; pak = new PAK.Pak(dir_pak + "\\" + pak_name); bw.Write(pa + father); off_subs = (int)fs_data1.Position; fs_data1.Seek(8, System.IO.SeekOrigin.Current); count = 0; count_p++; } System.IO.FileStream fs = System.IO.File.OpenRead(sub); byte[] t = new byte[(int)fs.Length]; fs.Read(t, 0, t.Length); fs.Close(); if (zip) { t = LB_ZIP.LB_ZIP.Zip(t, 0, t.Length); } pak.Replace(id, t, 0, t.Length); bw.Write(id); bw.Write((int)ms.Position); bw.Write(t.Length); ms.Write(t, 0, t.Length); count++; } if (pak != null) { pak.WriteTo(dir_pak_new + "\\" + pak_name); pak.Close(); } fs_data1.Seek(off_subs, 0); bw.Write(pak.Num); bw.Write(count); fs_data1.Seek(0, 0); bw.Write(count_p); bw.Write((int)fs_data1.Length); fs_data1.Seek(fs_data1.Length, 0); byte[] t2 = new byte[(int)ms.Length]; ms.Seek(0, 0); ms.Read(t2, 0, t2.Length); fs_data1.Write(t2, 0, t2.Length); ms.Close(); bw.Close(); fs_data1.Close(); }
public override bool DbgSaveToBitmap(string fileName) { try { System.IO.BinaryWriter byteBuffer = new System.IO.BinaryWriter(System.IO.File.Open(fileName, System.IO.FileMode.OpenOrCreate)); int height = m_width; int width = m_width; int sz = 14 + 40 + 4 * m_width * height; // Write the BITMAPFILEHEADER //System.IO.MemoryStream byteBuffer = System.IO.MemoryStream.Allocate(sz); //byteBuffer.Write(java.nio.ByteOrder.LITTLE_ENDIAN); // byteBuffer.put((byte) 'M'); byteBuffer.Write(unchecked ((byte)66)); byteBuffer.Write(unchecked ((byte)77)); // fwrite("BM", 1, 2, f); //bfType byteBuffer.Write(sz); // fwrite(&sz, 1, 4, f);//bfSize short zero16 = 0; byteBuffer.Write(zero16); // fwrite(&zero16, 1, 2, f);//bfReserved1 byteBuffer.Write(zero16); // fwrite(&zero16, 1, 2, f);//bfReserved2 int offset = 14 + 40; byteBuffer.Write(offset); // fwrite(&offset, 1, 4, f);//bfOffBits // Write the BITMAPINFOHEADER int biSize = 40; int biWidth = width; int biHeight = -height; short biPlanes = 1; short biBitCount = 32; int biCompression = 0; int biSizeImage = 4 * width * height; int biXPelsPerMeter = 0; int biYPelsPerMeter = 0; int biClrUsed = 0; int biClrImportant = 0; byteBuffer.Write(biSize); byteBuffer.Write(biWidth); byteBuffer.Write(biHeight); byteBuffer.Write(biPlanes); byteBuffer.Write(biBitCount); byteBuffer.Write(biCompression); byteBuffer.Write(biSizeImage); byteBuffer.Write(biXPelsPerMeter); byteBuffer.Write(biYPelsPerMeter); byteBuffer.Write(biClrUsed); byteBuffer.Write(biClrImportant); int[] colors = new int[] { unchecked ((int)(0xFFFFFFFF)), unchecked ((int)(0xFF000000)), unchecked ((int)(0xFFFF0000)), unchecked ((int)(0xFF00FF00)) }; // int32_t* rgb4 = (int32_t*)malloc(biSizeImage); for (int y = 0; y < height; y++) { int scanlineIn = y * ((width * 2 + 31) / 32); int scanlineOut = offset + width * y; for (int x = 0; x < width; x++) { int res = (m_bitmap[scanlineIn + (x >> 4)] >> ((x & 15) * 2)) & 3; byteBuffer.Write(colors[res]); } } //byte[] b = ((byte[])byteBuffer.Write()); // byteBuffer.Close(); return(true); } catch (System.IO.IOException) { return(false); } }
/// Matlab.PutSparseMatrix("H", H.GetMatrixSparse(), 3, 3); //public static void PutSparseMatrix<MATRIX>(string name, MatrixSparse<MATRIX> real, int elemColSize, int elemRowSize) //public static void PutSparseMatrix<MATRIX>(string name, IMatrixSparse<MATRIX> real, int elemColSize, int elemRowSize) // where MATRIX : Matrix public static void PutSparseMatrix(string name, IMatrixSparse <MatrixByArr> real, int elemColSize, int elemRowSize, string opt = null) { /// http://www.mathworks.com/help/matlab/ref/sparse.html /// S = sparse(i,j,s,m,n) /// * create m-by-n sparse matrix /// * where S(i(k),j(k)) = s(k) /// * Vectors i, j, and s are all the same length. /// * Any elements of s that are zero are ignored. /// * Any elementsof s that have duplicate values of i and j are added together. if (opt == null) { int m = real.ColSize * elemColSize; int n = real.RowSize * elemRowSize; //if(opt == null) { List <int> i = new List <int>(); List <int> j = new List <int>(); List <double> s = new List <double>(); foreach (var c_r_val in real.EnumElements()) { int c = c_r_val.Item1; int r = c_r_val.Item2; Matrix hesscr = c_r_val.Item3; HDebug.Assert(hesscr != null); HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); for (int dc = 0; dc < elemColSize; dc++) { for (int dr = 0; dr < elemRowSize; dr++) { i.Add(c * elemColSize + dc); j.Add(r * elemRowSize + dr); s.Add(hesscr[dc, dr]); } } } //for(int ii=0; ii<i.Count; ii++) //{ // if(i[ii] == j[ii]) // HDebug.Assert(s[ii] != 0); //} PutVector("htlib2_matlab_PutSparseMatrix.i", i.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.j", j.ToArray()); PutVector("htlib2_matlab_PutSparseMatrix.s", s.ToArray()); } //else //{ // Execute("htlib2_matlab_PutSparseMatrix.i = [];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [];"); // // int maxleng = 10_000_000; // Count = 134217728 (maximum) // List<int > i = new List<int >(maxleng); // List<int > j = new List<int >(maxleng); // List<double> s = new List<double>(maxleng); // foreach(var c_r_val in real.EnumElements()) // { // int c = c_r_val.Item1; // int r = c_r_val.Item2; // Matrix hesscr = c_r_val.Item3; // HDebug.Assert(hesscr != null); // HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); // for(int dc=0; dc<elemColSize; dc++) // for(int dr=0; dr<elemRowSize; dr++) // { // if(i.Count == maxleng) // { // PutVector("htlib2_matlab_PutSparseMatrix.ix", i.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.jx", j.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.sx", s.ToArray()); // Execute("htlib2_matlab_PutSparseMatrix.i = [htlib2_matlab_PutSparseMatrix.i; htlib2_matlab_PutSparseMatrix.ix];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [htlib2_matlab_PutSparseMatrix.j; htlib2_matlab_PutSparseMatrix.jx];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [htlib2_matlab_PutSparseMatrix.s; htlib2_matlab_PutSparseMatrix.sx];"); // Execute("clear htlib2_matlab_PutSparseMatrix.ix;"); // Execute("clear htlib2_matlab_PutSparseMatrix.jx;"); // Execute("clear htlib2_matlab_PutSparseMatrix.sx;"); // i.Clear(); // j.Clear(); // s.Clear(); // } // i.Add(c*elemColSize+dc); // j.Add(r*elemRowSize+dr); // s.Add(hesscr[dc, dr]); // } // } // if(i.Count != 0) // { // PutVector("htlib2_matlab_PutSparseMatrix.ix", i.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.jx", j.ToArray()); // PutVector("htlib2_matlab_PutSparseMatrix.sx", s.ToArray()); // Execute("htlib2_matlab_PutSparseMatrix.i = [htlib2_matlab_PutSparseMatrix.i; htlib2_matlab_PutSparseMatrix.ix];"); // Execute("htlib2_matlab_PutSparseMatrix.j = [htlib2_matlab_PutSparseMatrix.j; htlib2_matlab_PutSparseMatrix.jx];"); // Execute("htlib2_matlab_PutSparseMatrix.s = [htlib2_matlab_PutSparseMatrix.s; htlib2_matlab_PutSparseMatrix.sx];"); // Execute("htlib2_matlab_PutSparseMatrix.ix = [];"); // Execute("htlib2_matlab_PutSparseMatrix.jx = [];"); // Execute("htlib2_matlab_PutSparseMatrix.sx = [];"); // i.Clear(); // j.Clear(); // s.Clear(); // } // HDebug.Assert(i.Count == 0); // HDebug.Assert(j.Count == 0); // HDebug.Assert(s.Count == 0); //} PutValue("htlib2_matlab_PutSparseMatrix.m", m); PutValue("htlib2_matlab_PutSparseMatrix.n", n); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.i+1, htlib2_matlab_PutSparseMatrix.j+1, htlib2_matlab_PutSparseMatrix.s, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name + " = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } else if (opt == "use file") { string i_path = HFile.GetTempPath(_path_temporary, ".dat"); string j_path = HFile.GetTempPath(_path_temporary, ".dat"); string s_path = HFile.GetTempPath(_path_temporary, ".dat"); ulong count = 0; { System.IO.BinaryWriter i_writer = new System.IO.BinaryWriter(new System.IO.FileStream(i_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter j_writer = new System.IO.BinaryWriter(new System.IO.FileStream(j_path, System.IO.FileMode.CreateNew)); System.IO.BinaryWriter s_writer = new System.IO.BinaryWriter(new System.IO.FileStream(s_path, System.IO.FileMode.CreateNew)); foreach (var c_r_val in real.EnumElements()) { int c = c_r_val.Item1; int r = c_r_val.Item2; Matrix hesscr = c_r_val.Item3; HDebug.Assert(hesscr != null); HDebug.Assert(hesscr.ColSize == elemColSize, hesscr.RowSize == elemRowSize); for (int dc = 0; dc < elemColSize; dc++) { for (int dr = 0; dr < elemRowSize; dr++) { count++; double i = (c * elemColSize + dc); double j = (r * elemRowSize + dr); double s = (hesscr[dc, dr]); i_writer.Write(i); j_writer.Write(j); s_writer.Write(s); HDebug.Exception(count > 0); } } } i_writer.Flush(); i_writer.Close(); j_writer.Flush(); j_writer.Close(); s_writer.Flush(); s_writer.Close(); } { int m = real.ColSize * elemColSize; int n = real.RowSize * elemRowSize; PutValue("htlib2_matlab_PutSparseMatrix.m", m); PutValue("htlib2_matlab_PutSparseMatrix.n", n); Execute("htlib2_matlab_PutSparseMatrix.ifid=fopen('" + i_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.jfid=fopen('" + j_path + "','r');"); Execute("htlib2_matlab_PutSparseMatrix.sfid=fopen('" + s_path + "','r');"); // A = fread(fileID) reads all the data in the file into a vector of class double. By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer (uint8), and returns a double array. Execute("htlib2_matlab_PutSparseMatrix.imat=fread(htlib2_matlab_PutSparseMatrix.ifid, [" + count + "],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.jmat=fread(htlib2_matlab_PutSparseMatrix.jfid, [" + count + "],'*double')';"); Execute("htlib2_matlab_PutSparseMatrix.smat=fread(htlib2_matlab_PutSparseMatrix.sfid, [" + count + "],'*double')';"); Execute("fclose(htlib2_matlab_PutSparseMatrix.ifid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.jfid);"); Execute("fclose(htlib2_matlab_PutSparseMatrix.sfid);"); Execute("htlib2_matlab_PutSparseMatrix = sparse(htlib2_matlab_PutSparseMatrix.imat+1, htlib2_matlab_PutSparseMatrix.jmat+1, htlib2_matlab_PutSparseMatrix.smat, htlib2_matlab_PutSparseMatrix.m, htlib2_matlab_PutSparseMatrix.n);"); Execute(name + " = htlib2_matlab_PutSparseMatrix;"); Execute("clear htlib2_matlab_PutSparseMatrix;"); } HFile.Delete(i_path); HFile.Delete(j_path); HFile.Delete(s_path); } }
public byte[] Dump() { System.IO.MemoryStream s = new System.IO.MemoryStream(); System.IO.BinaryWriter w = new System.IO.BinaryWriter(s); w.Write((int)this.dimensions); w.Write((int)this.XSize); w.Write((int)this.YSize); w.Write((int)this.ZSize); w.Write((int)this.XSize * this.YSize * this.ZSize); for (int i = 0; i < this.ZSize; i++) { for (int j = 0; j < this.YSize; j++) { for (int k = 0; k < this.XSize; k++) { w.Write(this[k, j, i]); } } } w.Close(); return s.ToArray(); }
/// <summary>Saves the current in-game black box log</summary> internal static void SaveLogs() { if (Interface.CurrentOptions.BlackBox == false) { return; } string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin"); try { using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { //TODO: This code recreates the file every frame..... //It should be possible to spin up a stream in a separate thread which then continously appends using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(Stream, System.Text.Encoding.UTF8)) { byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 }; const short Version = 1; Writer.Write(Identifier); Writer.Write(Version); Writer.Write(Game.LogRouteName); Writer.Write(Game.LogTrainName); Writer.Write(Game.LogDateTime.ToBinary()); Writer.Write((short)Interface.CurrentOptions.GameMode); Writer.Write(Game.BlackBoxEntryCount); for (int i = 0; i < Game.BlackBoxEntryCount; i++) { Writer.Write(Game.BlackBoxEntries[i].Time); Writer.Write(Game.BlackBoxEntries[i].Position); Writer.Write(Game.BlackBoxEntries[i].Speed); Writer.Write(Game.BlackBoxEntries[i].Acceleration); Writer.Write(Game.BlackBoxEntries[i].ReverserDriver); Writer.Write(Game.BlackBoxEntries[i].ReverserSafety); Writer.Write((short)Game.BlackBoxEntries[i].PowerDriver); Writer.Write((short)Game.BlackBoxEntries[i].PowerSafety); Writer.Write((short)Game.BlackBoxEntries[i].BrakeDriver); Writer.Write((short)Game.BlackBoxEntries[i].BrakeSafety); Writer.Write((short)Game.BlackBoxEntries[i].EventToken); } Writer.Write(Game.ScoreLogCount); for (int i = 0; i < Game.ScoreLogCount; i++) { Writer.Write(Game.ScoreLogs[i].Time); Writer.Write(Game.ScoreLogs[i].Position); Writer.Write(Game.ScoreLogs[i].Value); Writer.Write((short)Game.ScoreLogs[i].TextToken); } Writer.Write(Game.CurrentScore.Maximum); Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 }; Writer.Write(Identifier); Writer.Close(); } Stream.Close(); } } catch { Interface.CurrentOptions.BlackBox = false; Interface.AddMessage(MessageType.Error, false, "An unexpected error occurred whilst attempting to write to the black box log- Black box has been disabled."); } }
protected override void OnDoWork(DoWorkEventArgs e) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_downloadURL); string postKey = "streamKey=" + _streamKey; req.Method = "POST"; req.ContentLength = postKey.Length; req.ContentType = "application/x-www-form-urlencoded"; System.IO.Stream postWriteStream = req.GetRequestStream(); postWriteStream.Write(Encoding.ASCII.GetBytes(postKey), 0, Encoding.ASCII.GetBytes(postKey).Length); postWriteStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); System.IO.Stream responseStream = res.GetResponseStream(); string directoryModifier = Information.BaseDownloadDirectory + (_fileName.LastIndexOf('\\') == -1 ? "" : _fileName.Substring(0, _fileName.LastIndexOf('\\') + 1)); string actualFile = directoryModifier + (_fileName.LastIndexOf('\\') == -1 ? _fileName : _fileName.Substring(_fileName.LastIndexOf('\\')+1)); System.IO.FileStream fs = new System.IO.FileStream(actualFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs); int bytesRead = 0; int count = 0; byte[] buf = new byte[8192]; while ((bytesRead = responseStream.Read(buf, 0, buf.Length)) > 0) { count += bytesRead; object[] numbers = new object[2]{count, res.ContentLength}; OnProgressChanged(new ProgressChangedEventArgs(0, numbers)); writer.Write(buf, 0, bytesRead); if (CancellationPending) { writer.Close(); System.IO.File.Delete(actualFile); e.Cancel = true; break; } } responseStream.Close(); writer.Close(); res.Close(); }
/// <summary> /// Writes pachyderm mapping file. /// </summary> /// <param name="filename">The location the new file is to be written to.</param> /// <param name="Rec_List">The list of receivers to be written.</param> public static void Write_pachm(string filename, Mapping.PachMapReceiver[] Rec_List) { System.IO.BinaryWriter sw = new System.IO.BinaryWriter(System.IO.File.Open(filename, System.IO.FileMode.Create)); //1. Write calculation type. (string) sw.Write(Rec_List[0].Data_Type()); Boolean Directional = Rec_List[0].Data_Type() == "Type;Map_Data"; //2. Write the number of samples in each histogram. (int) sw.Write((UInt32)Rec_List[0].SampleCT); //3. Write the sample rate. (int) sw.Write((UInt32)Rec_List[0].SampleRate); //4. Write the number of Receivers (int) int Rec_Ct = Rec_List[0].Rec_List.Length; sw.Write((UInt32)Rec_Ct); //4.5 Announce the Version sw.Write("Version"); sw.Write(UI.PachydermAc_PlugIn.Instance.Version); //5. Announce that the following data pertains to the form of the analysis mesh. (string) sw.Write("Mesh Information"); //6. Announce Mesh Vertices (string) sw.Write("Mesh Vertices"); //Write the number of vertices & faces (int) (int) sw.Write((UInt32)Rec_List[0].Map_Mesh.Vertices.Count); sw.Write((UInt32)Rec_List[0].Map_Mesh.Faces.Count); for (int i = 0; i < Rec_List[0].Map_Mesh.Vertices.Count; i++) { //Write Vertex: (double) (double) (double) sw.Write(Rec_List[0].Map_Mesh.Vertices[i].X); sw.Write(Rec_List[0].Map_Mesh.Vertices[i].Y); sw.Write(Rec_List[0].Map_Mesh.Vertices[i].Z); } //7. Announce Mesh Faces (string) sw.Write("Mesh Faces"); for (int i = 0; i < Rec_List[0].Map_Mesh.Faces.Count; i++) { // Write mesh vertex indices: (int) (int) (int) (int) sw.Write((UInt32)Rec_List[0].Map_Mesh.Faces[i][0]); sw.Write((UInt32)Rec_List[0].Map_Mesh.Faces[i][1]); sw.Write((UInt32)Rec_List[0].Map_Mesh.Faces[i][2]); sw.Write((UInt32)Rec_List[0].Map_Mesh.Faces[i][3]); } //7.5: Announce the number of sources. //sw.Write("Sources"); sw.Write("SourceswLoc"); sw.Write(Rec_List.Length); //7.5a: Announce the Type of Source for (int i = 0; i < Rec_List.Length; i++) { /////////////////////// sw.Write(Rec_List[i].Src.X); sw.Write(Rec_List[i].Src.Y); sw.Write(Rec_List[i].Src.Z); /////////////////////// sw.Write(Rec_List[i].SrcType); sw.Write(Rec_List[i].delay_ms);//v.2.0.0.1 for (int j = 0; j < 8; j++) { sw.Write(Rec_List[i].SWL[j]); //v.2.0.0.2 } } //8. Announce that the following data pertains to the receiver histograms (string) sw.Write("Receiver Hit Data"); //8a. Announce whether or not data is linked to vertices rather than faces (bool) sw.Write(Rec_List[0].Rec_Vertex); for (int s = 0; s < Rec_List.Length; s++) { for (int i = 0; i < Rec_Ct; i++) { //Write Receiver Index (int) sw.Write((UInt32)i); //Write the direct sound arrival time. sw.Write((Rec_List[s].Rec_List[i] as Mapping.PachMapReceiver.Map_Receiver).Direct_Time); //Write Impedance of Air sw.Write(Rec_List[0].Rec_List[i].Rho_C); for (int Octave = 0; Octave < 8; Octave++) { //Write Octave (int) sw.Write((UInt32)Octave); double[] Hist = Rec_List[s].Rec_List[i].GetEnergyHistogram(Octave); for (int e = 0; e < Rec_List[s].SampleCT; e++) { //Write each energy value in the histogram (double)... sw.Write(Hist[e]); //Write each directional value in the histogram (double) (double) (double); if (Directional) { Hare.Geometry.Vector DirPos = Rec_List[s].Directions_Pos(Octave, e, i); Hare.Geometry.Vector DirNeg = Rec_List[s].Directions_Neg(Octave, e, i); sw.Write(DirPos.x); sw.Write(DirPos.y); sw.Write(DirPos.z); sw.Write(DirNeg.x); sw.Write(DirNeg.y); sw.Write(DirNeg.z); } } } sw.Write("End_Receiver_Hits"); } } sw.Write("End_of_File"); sw.Close(); }
public static void ConvertToHilbert(this string prefix) { var graph = new FileGraphScanner(prefix); var High32 = new Dictionary <UInt32, UInt32>(); graph.ForEach((vertex, degree, offset, neighbors) => { //if (vertex < 1000000) { for (int i = 0; i < degree; i++) { var neighbor = neighbors[offset + i]; var high32 = (uint)(HilbertCurve.xy2dByte((uint)vertex, (uint)neighbor) >> 32); if (!High32.ContainsKey(high32)) { High32.Add(high32, 0); } High32[high32] = High32[high32] + 1; } } }); Console.WriteLine("Assesed prefix sizes"); var pairs = High32.OrderBy(x => x.Key).ToArray(); var edgeCount = 0L; var lowIndex = (uint)0; var high32Stream = new System.IO.BinaryWriter(System.IO.File.OpenWrite(prefix + "-high32")); var next16Stream = new System.IO.BinaryWriter(System.IO.File.OpenWrite(prefix + "-next16")); var next08Stream = new System.IO.BinaryWriter(System.IO.File.OpenWrite(prefix + "-next08")); var last08Stream = new System.IO.BinaryWriter(System.IO.File.OpenWrite(prefix + "-last08")); for (uint i = 0; i < pairs.Length; i++) { // if we would have too many edges, do work if (edgeCount + pairs[i].Value > 1 << 29) { var edges = new ulong[edgeCount]; var cursor = 0; graph.ForEach((vertex, degree, offset, neighbors) => { //if (vertex < 1000000) { for (int j = 0; j < degree; j++) { var transform = HilbertCurve.xy2dByte((uint)vertex, (uint)neighbors[offset + j]); if ((transform >> 32) >= pairs[lowIndex].Key && (transform >> 32) < pairs[i].Key) { edges[cursor++] = transform; } } } }); if (cursor != edges.Length) { Console.WriteLine("Somehow read the wrong number of edges {0} vs {1}", cursor, edges.Length); } Array.Sort(edges); Console.WriteLine("About to process {0} high32 blocks", i - lowIndex); // traverse edges in order and write out when interesting things happen. WriteTransformed(edges, high32Stream, next16Stream, next08Stream, last08Stream); edgeCount = 0; lowIndex = i; } edgeCount += pairs[i].Value; } var edges2 = new ulong[edgeCount]; var cursor2 = 0; graph.ForEach((vertex, degree, offset, neighbors) => { //if (vertex < 1000000) { for (int j = 0; j < degree; j++) { var transform = HilbertCurve.xy2dByte((uint)vertex, (uint)neighbors[offset + j]); if ((transform >> 32) >= pairs[lowIndex].Key) { edges2[cursor2++] = transform; } } } }); Array.Sort(edges2); if (cursor2 != edges2.Length) { Console.WriteLine("Somehow read the wrong number of edges {0} vs {1}", cursor2, edges2.Length); } // traverse edges in order and write out when interesting things happen. WriteTransformed(edges2, high32Stream, next16Stream, next08Stream, last08Stream); high32Stream.Close(); next16Stream.Close(); next08Stream.Close(); last08Stream.Close(); }
public static void WriteTextFile(string fileName, string content) { System.IO.BinaryWriter wr = new System.IO.BinaryWriter(new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate)); wr.Write(System.Text.Encoding.Default.GetBytes(content)); wr.Close(); }