private void stopProcessing(object sender, EventArgs e) { CommandChannel.SetCommand(1); stopButton.Enabled = false; saveResultButton.Enabled = true; timer1.Stop(); }
private async Task PlayHandlerAsync() { var itemN = this.Dequeue(); if (itemN == null) { await Task.Delay(500); await DestroyPlayerAsync(); return; } var item = itemN.Value; this.NowPlaying = item; this.IsPlaying = true; await this.Player.PlayAsync(item.Track); if (IsMeme) { return; } var builder = new DiscordEmbedBuilder(); builder.Color = CommandChannel.Guild.CurrentMember.Color; builder.AddField("Now Playing:", item.Track.Title, true); builder.AddField("Queued By:", item.RequestedBy.Mention, true); builder.AddField("URL:", item.Track.Uri.ToString(), false); builder.WithThumbnail(item.RequestedBy.AvatarUrl); await CommandChannel.SendMessageAsync(embed : builder.Build()); }
/// <summary> /// Queues a message to be sent to this discord client. /// </summary> /// <param name="msg">Text to send.</param> public void SendMessage(string msg) { if (AutoFlush) { Task.Run(async() => { try { Message m = await CommandChannel.SendMessage(msg); if (m?.State == MessageState.Failed) { TShock.Log.Error($"discord-bridge: Message broadcasting to channel '{CommandChannel.Name}' failed!"); } } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } }); } else { _messages.Add(msg); } }
public Mediator() { _commands = new CommandChannel(); _commands.EntryAvailable += EntryAvailableHandler; _commands.Enabled = true; _observers = new List<ISystemObserver>(); }
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); CommandChannel.SetCommand(1); }
//public Command( // string sourceCharacter, // string name, // IEnumerable<string> arguments, // string rawValue, // CommandType commandType, // CommandChannel channel, // CommandTargetType targetType) // : this(sourceCharacter, name, arguments, rawValue, commandType, channel, null, targetType, null) //{ //} #endregion #region Public Static Methods public static ICommand Create( string sourceCharacter, string name, IEnumerable<string> arguments, string rawValue, CommandType commandType, CommandChannel channel, object channelTag, TargetType targetType, object targettingTag) { return new Command(sourceCharacter, name, arguments, rawValue, commandType, channel, channelTag, targetType, targettingTag); }
public ICommandChannel Create(CreationParameters <SqliteConnectionStringBuilder> creationParameters) { if (creationParameters.ConnectionString.DataSource == ":memory:") { throw new NotSupportedException("Use " + nameof(MemorySqliteCommandChannelFactory)); } CreationOrDeletionLock.EnterUpgradeableReadLock(); try { if (creationParameters.EraseIfExists) { DeleteIfExists(creationParameters.ConnectionString); } CreationOrDeletionLock.EnterWriteLock(); try { var derivedConnectionString = new SqliteConnectionStringBuilder(creationParameters.ConnectionString.ToString()) { Mode = SqliteOpenMode.ReadWriteCreate }; var connection = new SqliteConnection(derivedConnectionString.ToString()); connection.Open(); var adapter = new CommandChannel(new ThreadSafeConnection(new Connection(new SqliteConnection(creationParameters.ConnectionString.ToString())))); foreach (var script in creationParameters.AdditionalScripts.Prepend(creationParameters.Script)) { if (!string.IsNullOrWhiteSpace(script)) { adapter.Execute(script); } } return(adapter); } finally { CreationOrDeletionLock.ExitWriteLock(); } } finally { CreationOrDeletionLock.ExitUpgradeableReadLock(); } }
void timer1_Tick(object sender, EventArgs e) { if (CommandChannel.GetCommand() == 2) { timer1.Stop(); return; } Gene gene = GeneContainer.Instance.GetGene(); if (gene != null) { Graphics graphics = drawingImagePanel.CreateGraphics(); graphics.Clear(Color.Black); Bitmap bmp = new Bitmap(originalImage.Width, originalImage.Height); Graphics drawingGraphics = Graphics.FromImage(bmp); graphics.Clear(Color.Black); drawingGraphics.Clear(Color.Black); for (int ip = 0; ip < gene.Polygons.Count; ip++) { if (gene.Polygons[ip] != null && gene.Brushes[ip] != null) { drawingGraphics.DrawPolygon(new Pen(gene.Brushes[ip]), gene.Polygons[ip]); drawingGraphics.FillPolygon(gene.Brushes[ip], gene.Polygons[ip]); graphics.DrawImage(bmp, new Point(0, 0)); } Thread.Sleep(100); } if (oldNegativeFitness != gene.NegativeFitness) { Console.WriteLine("[MainThread],NF: {0}", gene.NegativeFitness); oldNegativeFitness = gene.NegativeFitness; ((Bitmap)bmp.Clone()).Save("_" + gene.Polygons.Count.ToString() + ".bmp"); fileNameCounter++; if (fileNameCounter % 10 == 0) { intFileNameCounter++; ((Bitmap)bmp.Clone()).Save(intFileNameCounter.ToString() + ".bmp"); } } graphics.Clear(Color.Black); Bitmap demoBmp = (Bitmap)bmp.Clone(); workingImagePanel.BackColor = Color.Black; workingImagePanel.BackgroundImage = demoBmp; label1.Text = "Error: " + gene.NegativeFitness.ToString() + " " + gene.Polygons.Count + " polygons used"; } }
public async Task <bool> CreatePlayerAsync(DiscordChannel channel) { if (this.Player != null && this.Player.IsConnected) { return(false); } this.Player = await this.Lavalink.LavalinkNode.ConnectAsync(channel); if (this.Volume != 100) { await this.Player.SetVolumeAsync(this.Volume); } this.Player.PlaybackFinished += this.PlaybackFinished; await CommandChannel.SendMessageAsync($"A music session has started in {channel.Name}!"); return(true); }
public async Task DestroyPlayerAsync() { if (this.Player == null) { return; } if (this.Player.IsConnected) { await this.Player.DisconnectAsync(); } this.Player = null; this.Host = null; await CommandChannel.SendMessageAsync($"The previously active music session has been terminated"); this.CommandChannel = null; }
public async Task FlushMessages() { if (_messages.Count > 0) { try { Message m = await CommandChannel.SendMessage(String.Join("\n", _messages)); if (m?.State == MessageState.Failed) { TShock.Log.Error($"discord-bridge: Message broadcasting to channel '{CommandChannel.Name}' failed!"); } } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } _messages.Clear(); } }
public Command( string sourceCharacter, string name, IEnumerable<string> arguments, string rawValue, CommandType commandType, CommandChannel channel, object channelTag, TargetType targetType, object targettingTag) { this.SourceCharacter = sourceCharacter; this.FromSelf = sourceCharacter == CommandHelpers.DefaultYouValue; this.Name = name; this.Arguments = arguments.ToList().AsReadOnly(); this.RawValue = rawValue; this.CommandType = commandType; this.Channel = channel; this.ChannelTag = channelTag; this.UsesChannelTag = channelTag != null; this.CommandTargetType = targetType; this.ExplicitTargettingTag = targettingTag; this.UsesExplicitTargettingTag = targettingTag != null; }
public ICommandChannel Create(CreationParameters <MemorySqliteConnectionStringBuilder> creationParameters) { var mustPlayCreationScripts = true; var connection = Instances.AddOrUpdate( creationParameters.ConnectionString.MemoryInstanceGuid, guid => new SqliteConnection(creationParameters.ConnectionString.ConnectionString), (guid, previous) => { mustPlayCreationScripts = creationParameters.EraseIfExists; return(creationParameters.EraseIfExists ? new SqliteConnection(creationParameters.ConnectionString.ConnectionString) : previous); }); var channel = new CommandChannel(new MemoryConnection(connection)); if (mustPlayCreationScripts) { channel.Execute(creationParameters.Script); foreach (var creationParametersAdditionalScript in creationParameters.AdditionalScripts) { channel.Execute(creationParametersAdditionalScript); } } return(channel); }
CommandMessage ReadMessage() { byte[] header = new byte[MercurialHeaderLength]; long bytesRead = 0; try { bytesRead = ReadAll(_Process.StandardOutput.BaseStream, header, 0, MercurialHeaderLength); } catch (Exception ex) { throw new ServerException("Error reading from command server", ex); } if (MercurialHeaderLength != bytesRead) { throw new ServerException(string.Format("Received malformed header from command server: {0} bytes", bytesRead)); } CommandChannel channel = CommandChannelFromFirstByte(header); long messageLength = (long)ReadUint(header, 1); if (CommandChannel.Input == channel || CommandChannel.Line == channel) { return(new CommandMessage(channel, messageLength.ToString())); } byte[] messageBuffer = new byte[messageLength]; try { if (messageLength > int.MaxValue) { // .NET hates uints int firstPart = (int)(messageLength / 2); int secondPart = (int)(messageLength - firstPart); bytesRead = ReadAll(_Process.StandardOutput.BaseStream, messageBuffer, 0, firstPart); if (bytesRead == firstPart) { bytesRead += ReadAll(_Process.StandardOutput.BaseStream, messageBuffer, firstPart, secondPart); } } else { bytesRead = ReadAll(_Process.StandardOutput.BaseStream, messageBuffer, 0, (int)messageLength); } } catch (Exception ex) { throw new ServerException("Error reading from command server", ex); } if (bytesRead != messageLength) { throw new ServerException(string.Format("Error reading from command server: Expected {0} bytes, read {1}", messageLength, bytesRead)); } CommandMessage message = new CommandMessage(CommandChannelFromFirstByte(header), messageBuffer); // Console.WriteLine ("READ: {0} {1}", message, message.Message); return(message); }
public CommandMessage(CommandChannel channel, string message) { Channel = channel; _message = message; }
public void Run(object obj_iterations) { int nrOfIterations = (int)obj_iterations; double referenceNegativeIndex = double.MaxValue; double referenceComeback = NrOfPolygons; bool nrOfMutationsTryChanged = false; int limit = 0; int shakeTheImageCounter = 0; double currentNegativeFitness = workingGene.NegativeFitness; for (int i = 0; i < nrOfIterations; i++) { if (CommandChannel.GetCommand() == 1) { break; } List <int> mutationsList = retrieveMutationsList(); for (int mi = 0; mi < mutationsList.Count; mi++) { int mutationStep = mutationsList[mi]; switch (mutationStep) { case 1: performAddPolygon(workingGene); break; case 2: performMutateColor(workingGene); break; case 3: performMutatePolygon(workingGene); break; case 4: performMutatePolygonAndColor(workingGene); break; case 5: performMutateColorParam(workingGene); break; case 6: performMutatePolygonPoint(workingGene); break; } } #region check if the gene had evolved in the last 250 iterations; comment this region if you don't one to have momentum in your app if (currentNegativeFitness != workingGene.NegativeFitness) { currentNegativeFitness = workingGene.NegativeFitness; shakeTheImageCounter = 0; } else { //that means the in the last 250 iterations nothing changed in the gene fitness. if (shakeTheImageCounter > 250) { int nrOfPolysToBeRemoved = workingGene.NrOfPolygons / 10; for (int ix = 0; ix < nrOfPolysToBeRemoved; ix++) { randomlyRemovePolygons(workingGene); } referenceComeback = workingGene.Polygons.Count + 1; } shakeTheImageCounter++; } #endregion //if gene is more fit, we added to the container; Console.WriteLine("Negative fitness: {0} , {1}", workingGene.NegativeFitness, workingGene.Polygons.Count); if (workingGene.NegativeFitness < referenceNegativeIndex) { GeneContainer.Instance.AddGene(workingGene.Clone()); referenceNegativeIndex = workingGene.NegativeFitness; } #region every 100 iterations we increase the number of polygons, till we reach 50 if (workingGene.Polygons.Count < 50 && this.NrOfPolygons < 50) { if (i % 100 == 0 && i != 0) { this.NrOfPolygons++; workingGene.NrOfPolygons++; } } #endregion //if every time the number of polygons in the gene reaches the max number of polygons, then we increase the nr of polygons and //we remove the less fit individuals if (workingGene.Polygons.Count < 50) { if (workingGene.Polygons.Count == referenceComeback) { limit = workingGene.Polygons.Count / 10; for (int ix = 0; ix < limit; ix++) { removeLessFitPolys(workingGene); } Console.WriteLine("-------- [ReferenceComeback] :" + referenceComeback); referenceComeback++; } } // when 50 poly are reached, we double the nr of mutations tries; // and we remove a larger number of less fit individuals; else if (workingGene.Polygons.Count >= 50) { if (nrOfMutationsTryChanged == false) { NrOfMutationsTries = NrOfMutationsTries * 2; nrOfMutationsTryChanged = true; } limit = workingGene.Polygons.Count / 8; for (int ix = 0; ix < limit; ix++) { removeLessFitPolys(workingGene); } } } CommandChannel.SetCommand(2); //tell timer to stop }
public CommandMessage(CommandChannel channel, byte[] buffer) { Channel = channel; _buffer = buffer; }