text:
/*
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone.Controls;
using System.Diagnostics;

namespace WP7CordovaClassLib.Cordova.Commands
{
    /// <summary>
    /// Implements audio record and play back functionality.
    /// </summary>
    internal class AudioPlayer : IDisposable
    {
        #region Constants

        // AudioPlayer states
        private const int MediaNone = 0;
        private const int MediaStarting = 1;
        private const int MediaRunning = 2;
        private const int MediaPaused = 3;
        private const int MediaStopped = 4;

        // AudioPlayer messages
        private const int MediaState = 1;
        private const int MediaDuration = 2;
        private const int MediaPosition = 3;
        private const int MediaError = 9;

        // AudioPlayer errors
        private const int MediaErrorPlayModeSet = 1;
        private const int MediaErrorAlreadyRecording = 2;
        private const int MediaErrorStartingRecording = 3;
        private const int MediaErrorRecordModeSet = 4;
        private const int MediaErrorStartingPlayback = 5;
        private const int MediaErrorResumeState = 6;
        private const int MediaErrorPauseState = 7;
        private const int MediaErrorStopState = 8;

        //TODO: get rid of this callback, it should be universal
        private const string CallbackFunction = "CordovaMediaonStatus";

        #endregion

        /// <summary>
        /// The AudioHandler object
        /// </summary>
        private Media handler;

        /// <summary>
        /// Temporary buffer to store audio chunk
        /// </summary>
        private byte[] buffer;

        /// <summary>
        /// Xna game loop dispatcher
        /// </summary>
        DispatcherTimer dtXna;

        /// <summary>
        /// Output buffer
        /// </summary>
        private MemoryStream memoryStream;

        /// <summary>
        /// The id of this player (used to identify Media object in JavaScript)
        /// </summary>
        private String id;

        /// <summary>
        /// State of recording or playback
        /// </summary>
        private int state = MediaNone;

        /// <summary>
        /// File name to play or record to
        /// </summary>
        private String audioFile = null;

        /// <summary>
        /// Duration of audio
        /// </summary>
        private double duration = -1;

        /// <summary>
        /// Audio player object
        /// </summary>
        private MediaElement player = null;

        /// <summary>
        /// Audio source
        /// </summary>
        private Microphone recorder;

        /// <summary>
        /// Internal flag specified that we should only open audio w/o playing it
        /// </summary>
        private bool prepareOnly = false;

        /// <summary>
        /// Creates AudioPlayer instance
        /// </summary>
        /// <param name="handler">Media object</param>
        /// <param name="id">player id</param>
        public AudioPlayer(Media handler, String id)
        {
            this.handler = handler;
            this.id = id;
        }

        /// <summary>
        /// Destroys player and stop audio playing or recording
        /// </summary>
        public void Dispose()
        {
            Debug.WriteLine("Dispose :: " + this.audioFile);
            if (this.player != null)
            {
                this.stopPlaying();
                this.player = null;
            }
            if (this.recorder != null)
            {
                this.stopRecording();
                this.recorder = null;
            }

            this.FinalizeXnaGameLoop();
        }

        /// <summary>
        /// Starts recording, data is stored in memory
        /// </summary>
        /// <param name="filePath"></param>
        public void startRecording(string filePath)
        {
            if (this.player != null)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorPlayModeSet));
            }
            else if (this.recorder == null)
            {
                try
                {
                    this.audioFile = filePath;
                    this.InitializeXnaGameLoop();
                    this.recorder = Microphone.Default;
                    this.recorder.BufferDuration = TimeSpan.FromMilliseconds(500);
                    this.buffer = new byte[recorder.GetSampleSizeInBytes(this.recorder.BufferDuration)];
                    this.recorder.BufferReady += new EventHandler<EventArgs>(recorderBufferReady);
                    this.memoryStream = new MemoryStream();
                    this.WriteWavHeader(this.memoryStream, this.recorder.SampleRate);
                    this.recorder.Start();
                    FrameworkDispatcher.Update();
                    this.SetState(MediaRunning);
                }
                catch (Exception)
                {
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingRecording));
                }
            }
            else
            {

                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorAlreadyRecording));
            }
        }

        /// <summary>
        /// Stops recording
        /// </summary>
        public void stopRecording()
        {
            if (this.recorder != null)
            {
                if (this.state == MediaRunning)
                {
                    try
                    {
                        this.recorder.Stop();
                        this.recorder.BufferReady -= recorderBufferReady;
                        this.recorder = null;
                        SaveAudioClipToLocalStorage();
                        this.FinalizeXnaGameLoop();
                        this.SetState(MediaStopped);
                    }
                    catch (Exception)
                    {
                        //TODO
                    }
                }
            }
        }

        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <summary>
        /// Starts or resume playing audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        public void startPlaying(string filePath)
        {
            if (this.recorder != null)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet));
                return;
            }

            if (this.player == null)
            {
                try
                {
                    if (this.player == null)
                    {
                        // this.player is a MediaElement, it must be added to the visual tree in order to play
                        PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                        if (frame != null)
                        {
                            PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
                            if (page != null)
                            {
                                Grid grid = page.FindName("LayoutRoot") as Grid;
                                if (grid != null)
                                {

                                    this.player = new MediaElement();
                                    this.player.Name = "playerMediaElement";
                                    grid.Children.Add(this.player);
                                    this.player.Visibility = Visibility.Collapsed;
                                    this.player.MediaOpened += MediaOpened;
                                    this.player.MediaEnded += MediaEnded;
                                    this.player.MediaFailed += MediaFailed;
                                }
                            }
                        }

                    }
                    this.audioFile = filePath;

                    Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
                    if (uri.IsAbsoluteUri)
                    {
                        this.player.Source = uri;
                    }
                    else
                    {
                        using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (isoFile.FileExists(filePath))
                            {
                                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile))
                                {
                                    this.player.SetSource(stream);
                                }
                            }
                            else
                            {
                                Debug.WriteLine("Error: source doesn't exist :: " + filePath);
                                throw new ArgumentException("Source doesn't exist");
                            }
                        }
                    }
                    this.SetState(MediaStarting);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error: " + e.Message);
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback));
                }
            }
            else
            {
                if (this.state != MediaRunning)
                {
                    this.player.Play();
                    this.SetState(MediaRunning);
                }
                else
                {
                    this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState));
                }
            }
        }

        /// <summary>
        /// Callback to be invoked when the media source is ready for playback
        /// </summary>
        private void MediaOpened(object sender, RoutedEventArgs arg)
        {
            if (!this.prepareOnly)
            {
                this.player.Play();
                this.SetState(MediaRunning);
            }

            this.duration = this.player.NaturalDuration.TimeSpan.TotalSeconds;
            this.prepareOnly = false;
            this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaDuration, this.duration));
        }

        /// <summary>
        /// Callback to be invoked when playback of a media source has completed
        /// </summary>
        private void MediaEnded(object sender, RoutedEventArgs arg)
        {
            this.SetState(MediaStopped);
        }

        /// <summary>
        /// Callback to be invoked when playback of a media source has failed
        /// </summary>
        private void MediaFailed(object sender, RoutedEventArgs arg)
        {
            player.Stop();
            this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError.ToString(), "Media failed"));
        }

        /// <summary>
        /// Seek or jump to a new time in the track
        /// </summary>
        /// <param name="milliseconds">The new track position</param>
        public void seekToPlaying(int milliseconds)
        {
            if (this.player != null)
            {
                TimeSpan tsPos = new TimeSpan(0, 0, 0, 0, milliseconds);
                this.player.Position = tsPos;
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaPosition, milliseconds / 1000.0f));
            }
        }

        /// <summary>
        /// Set the volume of the player
        /// </summary>
        /// <param name="vol">volume 0.0-1.0, default value is 0.5</param>
        public void setVolume(double vol)
        {
            if (this.player != null)
            {
                this.player.Volume = vol;
            }
        }

        /// <summary>
        /// Pauses playing
        /// </summary>
        public void pausePlaying()
        {
            if (this.state == MediaRunning)
            {
                this.player.Pause();
                this.SetState(MediaPaused);
            }
            else
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorPauseState));
            }
        }

        /// <summary>
        /// Stops playing the audio file
        /// </summary>
        public void stopPlaying()
        {
            if ((this.state == MediaRunning) || (this.state == MediaPaused))
            {
                this.player.Stop();

                this.player.Position = new TimeSpan(0L);
                this.SetState(MediaStopped);
            }
            else
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStopState));
            }
        }

        /// <summary>
        /// Gets current position of playback
        /// </summary>
        /// <returns>current position</returns>
        public double getCurrentPosition()
        {
            if ((this.state == MediaRunning) || (this.state == MediaPaused))
            {
                double currentPosition = this.player.Position.TotalSeconds;
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaPosition, currentPosition));
                return currentPosition;
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// Gets the duration of the audio file
        /// </summary>
        /// <param name="filePath">The name of the audio file</param>
        /// <returns>track duration</returns>
        public double getDuration(string filePath)
        {
            if (this.recorder != null)
            {
                return (-2);
            }

            if (this.player != null)
            {
                return this.duration;

            }
            else
            {
                this.prepareOnly = true;
                this.startPlaying(filePath);
                return this.duration;
            }
        }

        /// <summary>
        /// Sets the state and send it to JavaScript
        /// </summary>
        /// <param name="state">state</param>
        private void SetState(int state)
        {
            if (this.state != state)
            {
                this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaState, state));
            }

            this.state = state;
        }

        #region record methods

        /// <summary>
        /// Copies data from recorder to memory storages and updates recording state
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void recorderBufferReady(object sender, EventArgs e)
        {
            this.recorder.GetData(this.buffer);
            this.memoryStream.Write(this.buffer, 0, this.buffer.Length);
        }

        /// <summary>
        /// Writes audio data from memory to isolated storage
        /// </summary>
        /// <returns></returns>
        private void SaveAudioClipToLocalStorage()
        {
            if (this.memoryStream == null || this.memoryStream.Length <= 0)
            {
                return;
            }

            this.UpdateWavHeader(this.memoryStream);

            try
            {
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string directory = Path.GetDirectoryName(audioFile);

                    if (!isoFile.DirectoryExists(directory))
                    {
                        isoFile.CreateDirectory(directory);
                    }

                    this.memoryStream.Seek(0, SeekOrigin.Begin);

                    using (IsolatedStorageFileStream fileStream = isoFile.CreateFile(audioFile))
                    {
                        this.memoryStream.CopyTo(fileStream);
                    }
                }
            }
            catch (Exception)
            {
                //TODO: log or do something else
                throw;
            }
        }

        #region Wav format
        // Original source http://damianblog.com/2011/02/07/storing-wp7-recorded-audio-as-wav-format-streams/

        /// <summary>
        /// Adds wav file format header to the stream
        /// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
        /// </summary>
        /// <param name="stream">Wav stream</param>
        /// <param name="sampleRate">Sample Rate</param>
        private void WriteWavHeader(Stream stream, int sampleRate)
        {
            const int bitsPerSample = 16;
            const int bytesPerSample = bitsPerSample / 8;
            var encoding = System.Text.Encoding.UTF8;

            // ChunkID Contains the letters "RIFF" in ASCII form (0x52494646 big-endian form).
            stream.Write(encoding.GetBytes("RIFF"), 0, 4);

            // NOTE this will be filled in later
            stream.Write(BitConverter.GetBytes(0), 0, 4);

            // Format Contains the letters "WAVE"(0x57415645 big-endian form).
            stream.Write(encoding.GetBytes("WAVE"), 0, 4);

            // Subchunk1ID Contains the letters "fmt " (0x666d7420 big-endian form).
            stream.Write(encoding.GetBytes("fmt "), 0, 4);

            // Subchunk1Size 16 for PCM.  This is the size of therest of the Subchunk which follows this number.
            stream.Write(BitConverter.GetBytes(16), 0, 4);

            // AudioFormat PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);

            // NumChannels Mono = 1, Stereo = 2, etc.
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);

            // SampleRate 8000, 44100, etc.
            stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);

            // ByteRate =  SampleRate * NumChannels * BitsPerSample/8
            stream.Write(BitConverter.GetBytes(sampleRate * bytesPerSample), 0, 4);

            // BlockAlign NumChannels * BitsPerSample/8 The number of bytes for one sample including all channels.
            stream.Write(BitConverter.GetBytes((short)(bytesPerSample)), 0, 2);

            // BitsPerSample    8 bits = 8, 16 bits = 16, etc.
            stream.Write(BitConverter.GetBytes((short)(bitsPerSample)), 0, 2);

            // Subchunk2ID Contains the letters "data" (0x64617461 big-endian form).
            stream.Write(encoding.GetBytes("data"), 0, 4);

            // NOTE to be filled in later
            stream.Write(BitConverter.GetBytes(0), 0, 4);
        }

        /// <summary>
        /// Updates wav file format header
        /// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
        /// </summary>
        /// <param name="stream">Wav stream</param>
        private void UpdateWavHeader(Stream stream)
        {
            if (!stream.CanSeek) throw new Exception("Can't seek stream to update wav header");

            var oldPos = stream.Position;

            // ChunkSize  36 + SubChunk2Size
            stream.Seek(4, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 8), 0, 4);

            // Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8 This is the number of bytes in the data.
            stream.Seek(40, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 44), 0, 4);

            stream.Seek(oldPos, SeekOrigin.Begin);
        }

        #endregion

        #region Xna loop
        /// <summary>
        /// Special initialization required for the microphone: XNA game loop
        /// </summary>
        private void InitializeXnaGameLoop()
        {
            // Timer to simulate the XNA game loop (Microphone is from XNA)
            this.dtXna = new DispatcherTimer();
            this.dtXna.Interval = TimeSpan.FromMilliseconds(33);
            this.dtXna.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
            this.dtXna.Start();
        }
        /// <summary>
        /// Finalizes XNA game loop for microphone
        /// </summary>
        private void FinalizeXnaGameLoop()
        {
            // Timer to simulate the XNA game loop (Microphone is from XNA)
            this.dtXna.Stop();
            this.dtXna = null;
        }

        #endregion

        #endregion
    }
}


text:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {FORM_DIRECTIVES} from 'angular2/common';
import {ShoppingListService, ShoppingList, ShoppingListLine} from '../../../services/shopping_list.service';
import {ProductService, Product} from '../../../services/product.service';
import {ShoppingListLineComponent} from './line/line.component';

@Component({
  providers: [ShoppingListService, ProductService],
  selector: 'shopping-list-details',
  templateUrl: './components/shopping_list/details/details.html',
  directives: [FORM_DIRECTIVES, ShoppingListLineComponent],
  inputs: ['id']
})

export class ShoppingListDetailsComponent implements OnInit {
  constructor(private _routeParams:RouteParams, private _shoppingListService:ShoppingListService,
              private _productService:ProductService) { }

  public id:string;
  public shoppingList:ShoppingList = <ShoppingList>{ title: 'placeholder', lines: [] };
  public lines:Array<ShoppingListLine> = [];
  public products:Array<Product> = [];
  public selectedProduct:Product = null;

  total():number {
    if (this.shoppingList.lines.length !== 0) {
      return this.shoppingList.lines
        .map(line => line.amount * line.product.price)
        .reduce((rTotal, lTotal) => rTotal + lTotal);
    }else {
      return 0;
    }
  }

  stringify(object:any):string {
    return JSON.stringify(object);
  }

  updateSelectedValue(event:string):void {
    this.selectedProduct = JSON.parse(event);
  }

  ngOnInit() {
    this.id = this._routeParams.get('id');

    this._shoppingListService.details(Number.parseInt(this.id))
      .subscribe((shoppingList) => {
        this.shoppingList = shoppingList;
        this.lines = shoppingList.lines;
      });
    this._productService.index()
      .subscribe((products) => {
        this.products = products;
      });
  }

  removeLine(id:number) {
    this.shoppingList.lines = this.shoppingList.lines.filter(line => line.id !== id);
    this.lines = this.shoppingList.lines;
  }

  newShoppingListLine() {
    if (this.selectedProduct !== null) {
      let product = this.selectedProduct;
      this._shoppingListService.addLine(Number.parseInt(this.id), this.selectedProduct.id, 1)
        .subscribe(line => {
          line.product = product;
          console.log('line ::: ' + JSON.stringify(line));
          if(this.shoppingList.lines.find(innerLine => innerLine.id === line.id)) {
            this.shoppingList.lines.find(innerLine => innerLine.id === line.id).amount += 1;
          } else {
            this.shoppingList.lines.push(line);
          }

          this.lines = this.shoppingList.lines;
        });

    } else {
      //todo show toast message
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ProKill</string>
    <string name="title_section1">Section 1</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section3">Section 3</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>


text:
package org.zmlx.hg4idea;

import com.intellij.openapi.options.ConfigurableBase;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.zmlx.hg4idea.ui.HgConfigurationProjectPanel;

public class HgProjectConfigurable extends ConfigurableBase<HgConfigurationProjectPanel, HgProjectConfigurable.HgSettingsHolder> {
  @NotNull private final Project myProject;
  @NotNull private final HgSettingsHolder mySettingsHolder;

  public HgProjectConfigurable(@NotNull Project project,
                               @NotNull HgGlobalSettings globalSettings,
                               @NotNull HgProjectSettings projectSettings) {
    super("vcs.Mercurial", getDISPLAY_NAME(), "project.propVCSSupport.VCSs.Mercurial");
    myProject = project;
    mySettingsHolder = new HgSettingsHolder(globalSettings, projectSettings);
  }

  @NotNull
  @Override
  protected HgSettingsHolder getSettings() {
    return mySettingsHolder;
  }

  @Override
  protected HgConfigurationProjectPanel createUi() {
    return new HgConfigurationProjectPanel(myProject);
  }

  public static class HgSettingsHolder {
    @NotNull private final HgGlobalSettings myGlobalSettings;
    @NotNull private final HgProjectSettings myProjectSettings;

    HgSettingsHolder(@NotNull HgGlobalSettings globalSettings, @NotNull HgProjectSettings projectSettings) {
      myGlobalSettings = globalSettings;
      myProjectSettings = projectSettings;
    }

    @NotNull
    public HgGlobalSettings getGlobalSettings() {
      return myGlobalSettings;
    }

    @NotNull
    public HgProjectSettings getProjectSettings() {
      return myProjectSettings;
    }
  }

  public static String getDISPLAY_NAME() {
    return HgBundle.message("hg4idea.mercurial");
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.f1x.v1;

import org.f1x.api.FixParserException;
import org.f1x.api.FixSettings;
import org.f1x.api.FixVersion;
import org.f1x.api.message.MessageBuilder;
import org.f1x.api.message.MessageParser;
import org.f1x.api.message.fields.EncryptMethod;
import org.f1x.api.message.fields.FixTags;
import org.f1x.api.message.fields.MsgType;
import org.f1x.api.message.fields.SessionRejectReason;
import org.f1x.api.session.*;
import org.f1x.io.InputChannel;
import org.f1x.io.LoggingOutputChannel;
import org.f1x.io.OutputChannel;
import org.f1x.log.MessageLog;
import org.f1x.log.MessageLogFactory;
import org.f1x.log.file.LogUtils;
import org.f1x.store.EmptyMessageStore;
import org.f1x.store.MessageStore;
import org.f1x.store.SafeMessageStore;
import org.f1x.util.AsciiUtils;
import org.f1x.util.ByteArrayReference;
import org.f1x.util.RealTimeSource;
import org.f1x.util.TimeSource;
import org.f1x.util.timer.GlobalTimer;
import org.f1x.v1.schedule.SessionSchedule;
import org.f1x.v1.state.MemorySessionState;
import org.gflogger.GFLog;
import org.gflogger.GFLogEntry;
import org.gflogger.GFLogFactory;
import org.gflogger.Loggable;

import java.io.IOException;
import java.net.SocketException;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Common networking code for FIX Acceptor and FIX Initiator
 */
public abstract class FixCommunicator implements FixSession, Loggable {
    private static final int MIN_FIX_MESSAGE_LENGTH = 63; // min message example: 8=FIX.4.?|9=??|35=?|34=?|49=?|56=?|52=YYYYMMDD-HH:MM:SS|10=???|
    static final int CHECKSUM_LENGTH = 7; // length("10=123|") --check sum always expressed using 3 digits

    protected static final GFLog LOGGER = GFLogFactory.getLog(FixCommunicator.class);

    private SessionEventListener eventListener;

    private final FixSettings settings;
    private MessageLogFactory messageLogFactory;
    private MessageLog messageLog;
    protected SessionState sessionState;

    // Defined during initialization
    private volatile InputChannel in;
    private volatile OutputChannel out;

    protected MessageStore messageStore;
    protected SessionSchedule schedule;

    // used by receiver thread only
    private final DefaultMessageParser parserForResend = new DefaultMessageParser();
    private final ByteArrayReference msgTypeForResend = new ByteArrayReference();
    private final byte[] messageBufferForResend;
    private final MessageBuilder messageBuilderForResend;

    private AtomicReference<SessionStatus> status = new AtomicReference<>(SessionStatus.Disconnected);

    /** This flag is set when communicator is going though graceful disconnect initiated by this side.
     * We continue to process inbound requests but do not make new attempts to establish socket connections.
     * Typically inbound LOGOUT in this state causes disconnect.
      */
    protected volatile boolean closeInProgress = false;

    // used by receiver thread only
    private final DefaultMessageParser parser = new DefaultMessageParser();
    private final byte [] inboundMessageBuffer;
    private final ByteArrayReference msgType = new ByteArrayReference();
    private final byte [] beginString;

    // Used by inbound message processing thread only
    private final ByteArrayReference temporaryByteArrayReference = new ByteArrayReference();

    // Used by senders
    private final MessageBuilder sessionMessageBuilder;
    private final RawMessageAssembler messageAssembler;

    protected final TimeSource timeSource;
    private final AtomicReference<TimerTask> sessionMonitoringTask = new AtomicReference<>();
    private final AtomicReference<TimerTask> sessionEndTask = new AtomicReference<>();

    private final Object sendLock = new Object();

    public FixCommunicator (FixVersion fixVersion, FixSettings settings) {
        this(fixVersion, settings, RealTimeSource.INSTANCE);
    }

    protected FixCommunicator (FixVersion fixVersion, FixSettings settings, TimeSource timeSource) {
        this.settings = settings;

//        this.logInboundMessages = settings.isLogInboundMessages();
//        this.logOutboundMessages = settings.isLogOutboundMessages();
//        if (logInboundMessages || logOutboundMessages)
//            messageLogFactory = new FileMessageLogFactory(settings.getLogDirectory());
//        else
//            messageLogFactory = null;

        this.beginString = AsciiUtils.getBytes(fixVersion.getBeginString());

        sessionMessageBuilder = new ByteBufferMessageBuilder(settings.getMaxOutboundMessageSize(), settings.getDoubleFormatterPrecision());
        messageBuilderForResend = new ByteBufferMessageBuilder(settings.getMaxOutboundMessageSize(), settings.getDoubleFormatterPrecision());
        messageAssembler = new RawMessageAssembler(fixVersion, settings.getMaxOutboundMessageSize());
        inboundMessageBuffer = new byte [settings.getMaxInboundMessageSize()];
        messageBufferForResend = new byte[settings.getMaxOutboundMessageSize()];
        this.timeSource = timeSource;
    }

    @Override
    public MessageBuilder createMessageBuilder() {
        return new ByteBufferMessageBuilder(settings.getMaxOutboundMessageSize(), settings.getDoubleFormatterPrecision());
    }

    @Override
    public void setEventListener(SessionEventListener eventListener) {
        this.eventListener = eventListener;
    }

    @Override
    public abstract SessionID getSessionID();

    @Override
    public FixSettings getSettings() {
        return settings;
    }

    @Override
    public SessionStatus getSessionStatus() {
        return status.get();
    }

    public void setMessageLogFactory(MessageLogFactory messageLogFactory) {
        this.messageLogFactory = messageLogFactory;
    }

    public void setSessionState(SessionState sessionState){
        this.sessionState = sessionState;
    }

    public void setMessageStore(MessageStore messageStore) {
        this.messageStore = messageStore;
    }

    public void setSessionSchedule(SessionSchedule schedule) {
        this.schedule = schedule;
        if (schedule != null)
            LOGGER.info().append("Session ").append(this).append(" schedule: ").append(schedule).commit();
        else
            LOGGER.info().append("Session ").append(this).append(" will have 'run-forever' schedule").commit();
    }

    //@Deprecated // TODO: Switch to use CAS version
    protected void setSessionStatus(SessionStatus newStatus) {
        final SessionStatus oldStatus = this.status.get();
        if (oldStatus == newStatus) {
            LOGGER.warn().append(this).append(" Already in the status ").append(newStatus).commit();
        } else {
            this.status.set(newStatus);
            onSessionStatusChanged(oldStatus, newStatus);
        }
    }

    /** Attempts to change state from expected current state to given one (CAS) */
    protected boolean setSessionStatus(SessionStatus expectedStatus, SessionStatus newStatus) {
        assert expectedStatus != newStatus;

        boolean result = this.status.compareAndSet(expectedStatus, newStatus);
        if (result) {
            onSessionStatusChanged(expectedStatus, newStatus);
        }
        return result;
    }

    protected void onSessionStatusChanged(final SessionStatus oldStatus, final SessionStatus newStatus) {
        SessionID sessionID = getSessionID();
        LOGGER.info().append("Session ").append(this).append(" changed status ").append(oldStatus).append(" => ").append(newStatus).commit();
        if (eventListener != null) {
            try {
                eventListener.onStatusChanged(sessionID, oldStatus, newStatus);
            } catch (Throwable e) {
                LOGGER.error().append(this).append(" Error notifying about status change ").append(e).commit();
            }
        }
    }

    protected final void assertSessionStatus(SessionStatus expectedStatus) {
        final SessionStatus actualStatus = getSessionStatus();
        if (actualStatus != expectedStatus)
            throw new IllegalStateException("Expecting " + expectedStatus + " status instead of " + actualStatus);
    }

    protected final void assertSessionStatus2(SessionStatus expectedStatus1, SessionStatus expectedStatus2) {
        final SessionStatus actualStatus = getSessionStatus();
        if (actualStatus != expectedStatus1 && actualStatus != expectedStatus2)
            throw new IllegalStateException("Expecting " + expectedStatus1 + " or " + expectedStatus2 + " status instead of " + actualStatus);
    }

    protected void connect(InputChannel in, OutputChannel out) {
        this.messageLog = (messageLogFactory != null) ? messageLogFactory.create(getSessionID()) : null;

        this.in = in;
        this.out = (messageLog != null) ? new LoggingOutputChannel(messageLog, out) : out;
    }

    protected void init() {
        if (sessionState == null)
            sessionState = new MemorySessionState();

        messageStore = messageStore == null ?
                EmptyMessageStore.getInstance() :
                new SafeMessageStore(messageStore);
    }

    protected void destroy(){
    }

    /** Process inbound messages until session ends */
    protected final boolean processInboundMessages() {
        return processInboundMessages(null, 0);
    }

    /** Process inbound messages until session ends
     * @param logonBuffer buffer containing session LOGON message and may be some other messages or a part of them (can be null)
     * @param length actual number of bytes that should be consumed from logonBuffer
     */
    protected final boolean processInboundMessages(byte[] logonBuffer, int length) {
        LOGGER.info().append(this).append("Processing FIX Session").commit();
        boolean normalExit = false;
        try {
            int offset = 0;
            if (logonBuffer != null) {
                System.arraycopy(logonBuffer, 0, inboundMessageBuffer, 0, length);
                offset = processInboundMessages(length);
            }

            while (in != null) {
                int bytesRead = in.read(inboundMessageBuffer, offset, inboundMessageBuffer.length - offset);
                if (bytesRead <= 0) {
                    if (closeInProgress){
                        disconnect("No socket data"); // TODO: disconnect?
                        break;
                    }
                    throw ConnectionProblemException.NO_SOCKET_DATA;
                } else {
                    offset = processInboundMessages(offset + bytesRead);
                }
            }
            LOGGER.error().append(this).append("Finishing FIX session").commit();
            normalExit = true;
        } catch (InvalidFixMessageException e) {
            errorProcessingMessage("Protocol Error", e, false);
        } catch (ConnectionProblemException e) {
            errorProcessingMessage("Connection Problem", e, false);
        } catch (SocketException e) {
            errorProcessingMessage("Socket Error (Other side disconnected?)", e, false);
        } catch (Exception e) {
            errorProcessingMessage("General error", e, true);
        }

        assertSessionStatus(SessionStatus.Disconnected);
        return normalExit;
    }

    protected void errorProcessingMessage(String errorText, Exception e, boolean logStackTrace) {
        //if (active) {
            if (logStackTrace)
                LOGGER.error().append(this).append(errorText).append(" : ").append(e).commit();
            else
                LOGGER.error().append(this).append(errorText).append(" : ").append(e.getMessage()).commit();
            disconnect(errorText);
        //}
    }

    protected int processInboundMessages(int bytesRead) throws IOException, InvalidFixMessageException, ConnectionProblemException {
        assert bytesRead > 0;
        int messageStart = 0;
        int readMessageLength;
        while ((readMessageLength = bytesRead - messageStart) >= MIN_FIX_MESSAGE_LENGTH) {

            parser.set(inboundMessageBuffer, messageStart, readMessageLength);

            // All FIX messages begin with 3 required tags: BeginString, BodyLength, and MsgType.
            FixCommunicatorHelper.parseBeginString(parser, beginString);
            final int bodyLength = FixCommunicatorHelper.parseBodyLength(parser);
            final int msgTypeStart = parser.getOffset();

            final int lengthOfBeginStringAndBodyLength = msgTypeStart - messageStart;
            final int messageLength = lengthOfBeginStringAndBodyLength + bodyLength + CHECKSUM_LENGTH; // BodyLength is the number of characters in the message following the BodyLength field up to, and including, the delimiter immediately preceding the CheckSum tag ("10=123|")
            FixCommunicatorHelper.checkMessageLength(messageLength, inboundMessageBuffer.length);

            if (readMessageLength < messageLength)
                break; // retry after we read full message in the buffer

            parser.set(inboundMessageBuffer, msgTypeStart, bodyLength);

            if ( ! parser.next())
                throw InvalidFixMessageException.MISSING_MSG_TYPE;

            parser.getByteSequence(msgType);

            if (messageLog != null)
                messageLog.log(true, inboundMessageBuffer, messageStart, messageLength);

            final int msgSeqNum = FixCommunicatorHelper.findMsgSeqNum(parser);

            // set parser limit to consume single message
            parser.set(inboundMessageBuffer, messageStart, messageLength);

            processInboundMessage(parser, msgType, msgSeqNum);

            messageStart += messageLength; // go to next message
        }

        // Move remaining part at the beginning of buffer
        int remainingSize = bytesRead - messageStart;
        if (remainingSize > 0 && messageStart != 0)
            System.arraycopy(inboundMessageBuffer, messageStart, inboundMessageBuffer, 0, remainingSize);
        return remainingSize;
    }

    /** Send LOGOUT but do not drop socket connection (session enters {@link org.f1x.api.session.SessionStatus#InitiatedLogout} state)*/
    @Override
    public void logout(CharSequence cause) {
        sendLogout(cause);
    }

    /**
     * Terminate socket connection immediately (no LOGOUT message is sent if session is in process).
     * Session enters {@link org.f1x.api.session.SessionStatus#Disconnected} state.
     * Initiator will try to re-connect after little delay (delay is configurable, subject to session schedule).
     */
    @Override
    public void disconnect(CharSequence cause) {
        LOGGER.info().append(this).append("FIX Disconnect due to ").append(cause).commit();

        setSessionStatus(SessionStatus.Disconnected);
        long now = timeSource.currentTimeMillis();
        sessionState.setLastConnectionTimestamp(now);
        try {
            if (in != null) { //TODO: Volatile
                in.close();
                in = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }

            if (messageLog != null) {
                messageLog.close();
                messageLog = null;
            }
        } catch (IOException e) {
            LOGGER.warn().append(this).append("Error closing socket: ").append(e).commit();
        }
    }

    /** Logout current session (if needed) and terminate socket connection. */
    @Override
    public void close() {
        this.closeInProgress = true;
        sendLogout("Goodbye");
    }

    /**
     * Sends a message using next sequence number. This message is persisted in message store
     */
    @Override
    public void send(MessageBuilder messageBuilder) throws IOException {
        long now = timeSource.currentTimeMillis();
        synchronized (sendLock) {
            int msgSeqNum = sessionState.consumeNextSenderSeqNum();
            messageAssembler.send(getSessionID(), msgSeqNum, messageBuilder, messageStore, now, out);
        }
        sessionState.setLastSentMessageTimestamp(now);
    }

    /**
     * Resend a message with given sequence number. The message is not persisted in message store.
     */
    protected void resend(MessageBuilder messageBuilder, int forcedMsgSeqNum) throws IOException {
        long now = timeSource.currentTimeMillis();
        synchronized (sendLock) {
            messageAssembler.send(getSessionID(), forcedMsgSeqNum, messageBuilder, null, now, out);
        }
        sessionState.setLastSentMessageTimestamp(now);
    }

    /** @param forceResetSequenceNumbers pass true to force sequence numbers reset, otherwise implementation will rely on {@link org.f1x.api.FixSettings#isResetSequenceNumbersOnEachLogon()} */
    protected void sendLogon(boolean forceResetSequenceNumbers) throws IOException {
        if ( ! forceResetSequenceNumbers)
            forceResetSequenceNumbers = settings.isResetSequenceNumbersOnEachLogon();

        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.LOGON);
            sessionMessageBuilder.add(FixTags.EncryptMethod, EncryptMethod.NONE_OTHER);
            sessionMessageBuilder.add(FixTags.HeartBtInt, settings.getHeartBeatIntervalSec());
            sessionMessageBuilder.add(FixTags.ResetSeqNumFlag, forceResetSequenceNumbers);

            if (settings.isLogonWithNextExpectedMsgSeqNum())
                sessionMessageBuilder.add(FixTags.NextExpectedMsgSeqNum, sessionState.getNextTargetSeqNum());

            sessionMessageBuilder.add(FixTags.MaxMessageSize, settings.getMaxInboundMessageSize());

            synchronized (sendLock) {
                if (forceResetSequenceNumbers) {
                    sessionState.setNextSenderSeqNum(1);
                    messageStore.clean();
                }

                send(sessionMessageBuilder);
            }
        }
    }

    protected void sendLogout(CharSequence cause) {
        if (setSessionStatus(SessionStatus.ApplicationConnected, SessionStatus.InitiatedLogout)) {
            LOGGER.info().append(this).append("Initiating LOGOUT: ").append(cause).commit();

            try {
                synchronized (sessionMessageBuilder) {
                    sessionMessageBuilder.clear();
                    sessionMessageBuilder.setMessageType(MsgType.LOGOUT);
                    if (cause != null)
                        sessionMessageBuilder.add(FixTags.Text, cause);
                    send(sessionMessageBuilder);
                }
            } catch (IOException e) {
                LOGGER.warn().append(this).append("Error logging out from FIX session: ").append(e).commit();
            }
        } else {
            LOGGER.info().append(this).append("Skipping LOGOUT (Not connected)").commit();
        }
    }

    /**
     * Sends FIX Heartbeat(0) message
     * @param testReqId required when heartbeat is sent in response to TestRequest(1)
     */
    protected void sendHeartbeat(CharSequence testReqId) throws IOException {
        assertSessionStatus(SessionStatus.ApplicationConnected);
        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.HEARTBEAT);
            if (testReqId!= null)
                sessionMessageBuilder.add(FixTags.TestReqID, testReqId);
            send(sessionMessageBuilder);
        }
    }

    /**
     * Sends FIX TestRequest(1) message.
     * @param testReqId Verifies that the opposite application is generating the heartbeat as the result of Test Request (1) and not a normal timeout.
     *                  The opposite application includes the TestReqID (112) in the resulting Heartbeat(0).
     *                  Any string can be used as the TestReqID (112) (one suggestion is to use a timestamp string).
     */
    protected void sendTestRequest(CharSequence testReqId) throws IOException {
        assertSessionStatus(SessionStatus.ApplicationConnected);
        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.TEST_REQUEST);
            sessionMessageBuilder.add(FixTags.TestReqID, testReqId);
            send(sessionMessageBuilder);
        }
    }

    /**
     * @param rejectedMsgSeqNum MsgSeqNum(34) of rejected message
     * This method sends FIX Reject(3).
     * @param rejectReason optional reject reason
     * @param text optional explanation message
     */
    protected void sendReject(int rejectedMsgSeqNum, SessionRejectReason rejectReason, CharSequence text) throws IOException {
        assertSessionStatus(SessionStatus.ApplicationConnected);
        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.REJECT);
            sessionMessageBuilder.add(FixTags.RefSeqNum, rejectedMsgSeqNum);

            if (rejectReason != null)
                sessionMessageBuilder.add(FixTags.SessionRejectReason, rejectReason);

            if (text != null)
                sessionMessageBuilder.add(FixTags.Text, text);
            send(sessionMessageBuilder);
        }
    }

    /**
     * This method sends ResendRequest(2).
     * @param beginSeqNo start of range to resend (inclusive)
     * @param endSeqNo end of range to resend (inclusive). Zero means infinity (resend up to the latest).
     */
    protected void sendResendRequest(int beginSeqNo, int endSeqNo) throws IOException {

        LOGGER.warn().append(this).append("Requesting RESEND from ").append(beginSeqNo).append(" to ").append(endSeqNo).commit();

        assertSessionStatus2(SessionStatus.ApplicationConnected, SessionStatus.InitiatedLogout);
        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.RESEND_REQUEST);

            sessionMessageBuilder.add(FixTags.BeginSeqNo, beginSeqNo);
            sessionMessageBuilder.add(FixTags.EndSeqNo, endSeqNo-1);
            send(sessionMessageBuilder);
        }

    }

    /**
     * Sends SequenceReset(4) in response to ResendRequest when
     * resending a range of administrative messages or when resending actual application messages is not appropriate (e.g. stale messages).
     *
     * @param msgSeqNum message sequence number of this message
     * @param newSeqNo new sequence number
     */
    protected void sendGapFill(int msgSeqNum, int newSeqNo) throws IOException {
        assertSessionStatus2(SessionStatus.ApplicationConnected, SessionStatus.InitiatedLogout);

        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.SEQUENCE_RESET);

            sessionMessageBuilder.add(FixTags.PossDupFlag, true);
            sessionMessageBuilder.add(FixTags.NewSeqNo, newSeqNo);
            sessionMessageBuilder.add(FixTags.GapFillFlag, true);
            resend(sessionMessageBuilder, msgSeqNum);
        }
    }

    /**
     * Sends SequenceReset(4) in response to ResendRequest when
     * resending a range of administrative messages or when resending actual application messages is not appropriate (e.g. stale messages).
     * Sets sender message sequence num to newSeqNo
     * @param newSeqNo new sequence number
     */
    protected void sendSequenceReset(int newSeqNo) throws IOException {
        assertSessionStatus(SessionStatus.ApplicationConnected);
        synchronized (sessionMessageBuilder) {
            sessionMessageBuilder.clear();
            sessionMessageBuilder.setMessageType(MsgType.SEQUENCE_RESET);

            sessionMessageBuilder.add(FixTags.NewSeqNo, newSeqNo);
            sessionMessageBuilder.add(FixTags.GapFillFlag, false);

            synchronized (sendLock) {
                sessionState.setNextSenderSeqNum(newSeqNo - 1);
                send(sessionMessageBuilder); // In reset mode MsgSeqNum should be ignored
            }
        }
    }

    protected void processInboundMessage(MessageParser parser, CharSequence msgType, int msgSeqNumX) throws IOException, InvalidFixMessageException, ConnectionProblemException {
        long now = timeSource.currentTimeMillis();
        sessionState.setLastReceivedMessageTimestamp(now); //? maybe extract from message SendingTime(52) field?

        SessionStatus currentStatus = getSessionStatus();
        switch (currentStatus) {
            case ApplicationConnected:
            case InitiatedLogout:
                processInSessionMessage(msgSeqNumX, msgType, parser);
                break;
            case SocketConnected:
                if (FixCommunicatorHelper.isLogon(msgType))
                    processInboundLogon(msgSeqNumX, parser);
                else
                    throw InvalidFixMessageException.EXPECTING_LOGON_MESSAGE;

                break;
            case InitiatedLogon:
                if(FixCommunicatorHelper.isLogon(msgType))
                    processInboundLogon(msgSeqNumX, parser);
                else if(FixCommunicatorHelper.isLogout(msgType))
                    processInboundLogout(msgSeqNumX, parser);
                else
                    throw InvalidFixMessageException.EXPECTING_LOGON_MESSAGE;
                break;
            default:
                LOGGER.warn().append(this).append("Received unexpected message (35=").append(msgType).append(") in status ").append(currentStatus).commit();
        }

    }

    private void processInSessionMessage(int msgSeqNumX, CharSequence msgType, MessageParser parser) throws IOException, InvalidFixMessageException, ConnectionProblemException {
        boolean processed = true;
        if (msgType.length() == 1) { // All session-level messages have MsgType expressed using single char
            switch (msgType.charAt(0)) {
                case AdminMessageTypes.LOGON:
                    processInboundLogon(msgSeqNumX, parser); break;
                case AdminMessageTypes.LOGOUT:
                    processInboundLogout(msgSeqNumX, parser); break;
                case AdminMessageTypes.HEARTBEAT:
                    processInboundHeartbeat(msgSeqNumX, parser);
                    break;
                case AdminMessageTypes.TEST:
                    processInboundTestRequest(msgSeqNumX, parser); break;
                case AdminMessageTypes.RESEND:
                    processInboundResendRequest(msgSeqNumX, parser); break;
                case AdminMessageTypes.REJECT:
                    processInboundReject(msgSeqNumX, parser); break;
                case AdminMessageTypes.RESET:
                    processInboundSequenceReset(msgSeqNumX, parser); break;
                default:
                    processed = false;
            }
        } else {
            processed = false;
        }
        if ( ! processed)
            _processInboundAppMessage(msgType, msgSeqNumX, parser);
    }

    /**
     * @param msgSeqNumX message sequence number (negative for messages that have PossDupFlag=Y).
     */
    private void _processInboundAppMessage(CharSequence msgType, int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException {
        LOGGER.debug().append(this).append("Processing inbound message with type: ").append(msgType).commit();

        final boolean possDup;
        if (msgSeqNumX > 0) { // PossDupFlag=N
            int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
            if ( ! checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum)) //Let's imagine we expected MsgSeqNum=5 but received 10
                sendResendRequest(expectedTargetSeqNum, msgSeqNumX - 1);   //This will send ResendRequest(5, 0) and set currentResendEndSeqNo=9

            sessionState.setNextTargetSeqNum(msgSeqNumX + 1);
            possDup = false;
        } else {
            msgSeqNumX = -msgSeqNumX;
            possDup = true;
        }

        processInboundAppMessage(msgType, msgSeqNumX, possDup, parser);
    }

    /**
     *
     * @param msgType type of the message [tag MsgType(35)].
     * @param msgSeqNum message sequence number [tag MsgSeqNum(34)].
     * @param possDup <code>true</code> if this message is marked as a duplicate using tag PossDupFlag(43)
     */
    protected void processInboundAppMessage(CharSequence msgType, int msgSeqNum, boolean possDup, MessageParser parser) throws IOException {
        assert msgSeqNum > 0; // by default do nothing
    }

    /**
     * Handle inbound LOGON message depending on FIX session role (acceptor/initator) and current status
     */
    protected void processInboundLogon(int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException, ConnectionProblemException {
        LOGGER.debug().append(this).append("Processing inbound LOGON(A)").commit();

        if (msgSeqNumX < 0) {
            LOGGER.warn().append(this).append("Received LOGON(A) message with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        boolean heartbeatIntervalPresent = false;
        boolean resetSeqNum = false;
        while (parser.next()) {
            switch (parser.getTagNum()) {
                case FixTags.HeartBtInt:
                    if (parser.getIntValue() != settings.getHeartBeatIntervalSec())
                        throw ConnectionProblemException.HEARTBEAT_INTERVAL_MISMATCH; //TODO: Allow initiator to override heartbeat interval for acceptor

                    heartbeatIntervalPresent = true;
                    break;
                case FixTags.ResetSeqNumFlag:
                    resetSeqNum = parser.getBooleanValue();
                    //if (getSessionStatus() != SessionStatus.ApplicationConnected) // Unless we are dealing with In-Session sequence reset
                        if(resetSeqNum && msgSeqNumX != 1)
                           throw InvalidFixMessageException.MSG_SEQ_NUM_MUST_BE_ONE;

                    break;
            }
        }

        if (!heartbeatIntervalPresent)
            throw InvalidFixMessageException.NO_HEARTBEAT_INTERVAL;

        if (resetSeqNum)
            sessionState.setNextTargetSeqNum(1); //TODO: This is wrong 141=Y means that both sides should reset sequence numbers

        SessionStatus currentStatus = getSessionStatus();
        if (currentStatus == SessionStatus.ApplicationConnected && !resetSeqNum)
            throw InvalidFixMessageException.IN_SESSION_LOGON_MESSAGE_WITHOUT_MSG_SEQ_RESET_NOT_EXPECTED;

        int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
        boolean expectedTargetMsgSeqNum = checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum);
        sessionState.setNextTargetSeqNum(msgSeqNumX + 1);

        if (currentStatus == SessionStatus.SocketConnected) {
            setSessionStatus(SessionStatus.ReceivedLogon);
            sendLogon(resetSeqNum);
            setSessionStatus(SessionStatus.ApplicationConnected);
        } else if (currentStatus == SessionStatus.InitiatedLogon) {
            setSessionStatus(SessionStatus.ApplicationConnected);
        } else if (currentStatus == SessionStatus.ApplicationConnected) {
            sendLogon(resetSeqNum);
        } else {
            LOGGER.warn().append(this).append("Unexpected LOGON(A) in status: ").append(currentStatus).commit();
            return;
        }

        // *After* sending a Logon confirmation back, send a ResendRequest
        if (!expectedTargetMsgSeqNum)
            sendResendRequest(expectedTargetSeqNum, msgSeqNumX);
    }

    @SuppressWarnings("unused")
    protected void processInboundLogout(int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException {
        LOGGER.debug().append(this).append("Processing inbound LOGOUT(5)").commit();

        if (msgSeqNumX < 0) {
            LOGGER.warn().append(this).append("Received LOGOUT(5) message with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
        boolean expectedTargetMsgSeqNum = checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum);

        temporaryByteArrayReference.clear();
        while (parser.next()) {
            if (parser.getTagNum() == FixTags.Text) {
                parser.getByteSequence(temporaryByteArrayReference);
                break;
            }
        }

        LOGGER.info().append(this).append("LOGOUT(5) received: ").append(temporaryByteArrayReference).commit();

        SessionStatus currentStatus = getSessionStatus();
        if (currentStatus == SessionStatus.ApplicationConnected) {
            sessionState.setNextTargetSeqNum(msgSeqNumX + 1);
            // If a message gap was detected, issue a ResendRequest to retrieve all missing messages followed by a Logout message which serves as a confirmation of the logout request.
            // DO NOT terminate the session.  The initiator of the Logout sequence has responsibility to terminate the session.
            // This allows the Logout initiator to respond to any ResendRequest message.
            if ( ! expectedTargetMsgSeqNum)
                sendResendRequest(expectedTargetSeqNum, msgSeqNumX);

            sendLogout("Responding to LOGOUT(5) request");
            if ( expectedTargetMsgSeqNum)
                setSessionStatus(SessionStatus.SocketConnected);
        } else if (currentStatus == SessionStatus.InitiatedLogout) {
            if (expectedTargetMsgSeqNum)
                sessionState.consumeNextTargetSeqNum();
            // If this side was the initiator of the Logout sequence,
            // then this is a Logout confirmation and the session should be immediately terminated upon receipt.
            disconnect("Both sides exchanged LOGOUT(5)");
        } else if (currentStatus == SessionStatus.InitiatedLogon){
            if (expectedTargetMsgSeqNum)
                sessionState.consumeNextTargetSeqNum();
            disconnect("LOGON(A) rejected");
        } else {
            LOGGER.info().append(this).append("Unexpected LOGOUT(5) message in status: ").append(currentStatus).commit();
        }
    }

    @SuppressWarnings("unused")
    protected void processInboundHeartbeat(int msgSeqNumX, MessageParser parser) throws InvalidFixMessageException, IOException {
        LOGGER.debug().append(this).append("Processing Inbound HEARTBEAT(0)").commit();

        if (msgSeqNumX < 0) {
            LOGGER.warn().append(this).append("Received HEARTBEAT(0) message with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
        if( ! checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum))
            sendResendRequest(expectedTargetSeqNum, msgSeqNumX);

        sessionState.setNextTargetSeqNum(msgSeqNumX + 1);
    }

    protected void processInboundTestRequest(int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException {
        LOGGER.debug().append("Processing inbound TEST(1) request").commit();

        if (msgSeqNumX < 0) {
            LOGGER.warn().append(this).append("Received TEST(1) request with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
        boolean expectedTargetMsgSeqNum = checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum);
        sessionState.setNextTargetSeqNum(msgSeqNumX + 1);
        if (expectedTargetMsgSeqNum) {

            temporaryByteArrayReference.clear();
            while (parser.next()) {
                if (parser.getTagNum() == FixTags.TestReqID) {
                    parser.getByteSequence(temporaryByteArrayReference);
                    break;
                }
            }

            if (temporaryByteArrayReference.length() == 0)
                sendReject(msgSeqNumX, SessionRejectReason.REQUIRED_TAG_MISSING, "Missing TestReqID(112)");
            else
                sendHeartbeat(temporaryByteArrayReference);
        } else {
            sendResendRequest(expectedTargetSeqNum, msgSeqNumX);
        }
    }

    private void processInboundResendRequest(int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException {
        LOGGER.debug().append("Processing inbound RESEND(2) request").commit();

        int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();

        if (msgSeqNumX < 0) {
            LOGGER.warn().append(this).append("Received RESEND(2) message with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        boolean expectedTargetMsgSeqNum = checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum);
        sessionState.setNextTargetSeqNum(msgSeqNumX + 1);

        int beginSeqNo = -1;
        int endSeqNo = -1;
        while (parser.next()) {
            switch (parser.getTagNum()) {
                case FixTags.BeginSeqNo:  // required
                    beginSeqNo = parser.getIntValue();
                    break;
                case FixTags.EndSeqNo:  // required
                    endSeqNo = parser.getIntValue();
                    break;
            }
        }

        // If message gap is detected, perform the Resend processing first, followed by a ResendRequest of  your own in order to fill the incoming message gap.
        if (beginSeqNo == -1)
            sendReject(msgSeqNumX, SessionRejectReason.REQUIRED_TAG_MISSING, "Missing BeginSeqNo(7)");
        else if (beginSeqNo == 0)
            sendReject(msgSeqNumX, SessionRejectReason.VALUE_IS_INCORRECT, "Invalid BeginSeqNo(7)");
        else if (endSeqNo == -1)
            sendReject(msgSeqNumX, SessionRejectReason.REQUIRED_TAG_MISSING, "Missing EndSeqNo(16)");
        else
            resendMessages(beginSeqNo, endSeqNo != 0 ? endSeqNo : (sessionState.getNextSenderSeqNum() - 1));

        if( ! expectedTargetMsgSeqNum)
            sendResendRequest(expectedTargetSeqNum, msgSeqNumX);
    }

    protected void resendMessages(int beginSeqNo, int endSeqNo) throws IOException {
        if(beginSeqNo > endSeqNo){
            LOGGER.warn().append(this).append("Resending messages was skipped: beginSeqNo > endSeqNo").commit();
            return;
        }

        MessageStore.MessageStoreIterator iterator = messageStore.iterator(beginSeqNo, endSeqNo);

        int msgSeqNumOfLastResentMessage = beginSeqNo - 1;
        int msgSeqNum;
        while ((msgSeqNum = iterator.next(messageBufferForResend)) > 0) {
            if(resend(messageBufferForResend, msgSeqNum, msgSeqNumOfLastResentMessage))
                msgSeqNumOfLastResentMessage = msgSeqNum;
        }

        if (msgSeqNumOfLastResentMessage < endSeqNo)
            sendGapFill(msgSeqNumOfLastResentMessage + 1, endSeqNo + 1);
    }

    /**
     * @return true if message was resent otherwise false
     */
    private boolean resend(byte[] message, int msgSeqNum, int msgSeqNumOfLastResentMessage) throws IOException {
        try {
            parserForResend.set(message, 0 , message.length);

            FixCommunicatorHelper.parseBeginString(parserForResend, beginString);
            final int bodyLength = FixCommunicatorHelper.parseBodyLength(parserForResend);

            final int lengthOfBeginStringAndBodyLength = parserForResend.getOffset();
            final int messageLength = lengthOfBeginStringAndBodyLength + bodyLength + CHECKSUM_LENGTH;

            if (!parserForResend.next())
                throw InvalidFixMessageException.MISSING_MSG_TYPE;

            parserForResend.getByteSequence(msgTypeForResend);

            parserForResend.set(message, 0, messageLength);

            messageBuilderForResend.clear();
            if( ! onMessageResend(msgTypeForResend, parserForResend, messageBuilderForResend))
                return false;

            int msgSeqNumGap = msgSeqNum - msgSeqNumOfLastResentMessage;
            if(msgSeqNumGap > 1)
                sendGapFill(msgSeqNumOfLastResentMessage + 1, msgSeqNum);

            resend(messageBuilderForResend, msgSeqNum);
            return true;
        } catch (InvalidFixMessageException | FixParserException e) {
            LOGGER.warn().append(this).append("Got invalid message #").append(msgSeqNum).append(" from message store : ").append(e).commit();
            return false;
        }
    }

    /**
     * @param parser of resending message
     * @param messageBuilder that will be sent
     * @return true if a message requires the resending otherwise false
     */
    protected boolean onMessageResend(CharSequence msgType, MessageParser parser, MessageBuilder messageBuilder) {
        if(!isResendRequired(msgType))
            return false;

        messageBuilder.setMessageType(msgType);
        messageBuilder.add(FixTags.PossDupFlag, true);
        while (parser.next()) {
            int tagNum = parser.getTagNum();
            switch (tagNum) {
                case FixTags.MsgType:
                case FixTags.MsgSeqNum:
                case FixTags.BeginString:
                case FixTags.BodyLength:
                case FixTags.SendingTime:
                case FixTags.SenderCompID:
                case FixTags.SenderSubID:
                case FixTags.TargetCompID:
                case FixTags.TargetSubID:
                case FixTags.CheckSum:
                    break;
                default:
                    messageBuilder.add(tagNum, parser.getCharSequenceValue());
            }
        }

        return true;
    }

    /**
     * @return true if a message with this msgType requires the resending otherwise false
     */
    protected boolean isResendRequired(CharSequence msgType){
        return ! AdminMessageTypes.isAdmin(msgType) || msgType.charAt(0) == AdminMessageTypes.REJECT; // do not resend Admin message unless it is a REJECT(3)
    }

    private void processInboundSequenceReset(int msgSeqNumX, MessageParser parser) throws IOException, InvalidFixMessageException {
        LOGGER.debug().append(this).append("Processing inbound Sequence Reset").commit();

        boolean isGapFill = false;
        int newSeqNum = -1;
        while (parser.next()) {
            switch (parser.getTagNum()) {
                case FixTags.NewSeqNo:  // required
                    newSeqNum = parser.getIntValue();
                    break;
                case FixTags.GapFillFlag:
                    isGapFill = parser.getBooleanValue();
                    break;
            }
        }

        if (msgSeqNumX < 0) {
            // Normal for gap fill to have PossDupFlag=Y
            if (isGapFill)
                LOGGER.debug().append(this).append("Ignoring GapFill from").append(-msgSeqNumX).append(" to ").append(newSeqNum).commit();
            else
                LOGGER.info().append(this).append("Received RESET message with PossDupFlag=Y - ignoring. MsgSeqNum ").append(-msgSeqNumX).commit();
            return;
        }

        LOGGER.info().append(this).append("Processing inbound message sequence reset to ").append(newSeqNum).commit();
        //noinspection StatementWithEmptyBody
        if (isGapFill) {
            int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
            if( ! checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum)){
                sendResendRequest(expectedTargetSeqNum, msgSeqNumX);
            }
        } else {
            // If message gap is detected Ignore the incoming sequence number.
            // The NewSeqNo field of the SeqReset message will contain the sequence number of the next message to be transmitted.
        }

        try {
            if (newSeqNum <= sessionState.getNextTargetSeqNum())
               throw InvalidFixMessageException.RESET_BELOW_CURRENT_SEQ_LARGE;

            sessionState.setNextTargetSeqNum(newSeqNum);
        } catch (InvalidFixMessageException e) {
            sendReject(msgSeqNumX, SessionRejectReason.INCORRECT_DATA_FORMAT_FOR_VALUE, e.getMessage());
        }
    }

    protected void processInboundReject(int msgSeqNumX, MessageParser parser) throws InvalidFixMessageException, IOException {
        LOGGER.debug().append(this).append("Processing inbound REJECT(3)").commit();

        // Skip sequence number checking if we are dealing with GapFill
        if (msgSeqNumX > 0) {
            int expectedTargetSeqNum = sessionState.getNextTargetSeqNum();
            if ( ! checkTargetMsgSeqNum(msgSeqNumX, expectedTargetSeqNum)) {
                sendResendRequest(expectedTargetSeqNum, msgSeqNumX);
            }
            sessionState.setNextTargetSeqNum(msgSeqNumX + 1);
        }

        int refSeqNum = -1;
        temporaryByteArrayReference.clear();
        while (parser.next()) {
            switch (parser.getTagNum()) {
                case FixTags.RefSeqNum:
                    refSeqNum = parser.getIntValue();
                    break;
                case FixTags.Text:
                    parser.getByteSequence(temporaryByteArrayReference);
                    break;
            }
        }

        // NOTE: some brokers use session-level REJECT to reject abnormal app-level messages
        //This default implementation simply log REJECT messages:
        if (temporaryByteArrayReference.length() != 0)
            LOGGER.warn().append(this).append("Received REJECT(3):").append(refSeqNum).append(": ").append(temporaryByteArrayReference).commit();
        else
            LOGGER.warn().append(this).append("Received REJECT(3):").append(refSeqNum).commit();

    }

    /// Timers

    /** Schedules a timer to finish current FIX session according to FIX Session Schedule */
    protected void scheduleSessionEnd(long timeout) {
        SessionEndTask timer = new SessionEndTask(this);
        GlobalTimer.getInstance().schedule(timer, timeout);

        sessionEndTask.set(timer);
    }

    /** Cancels a timer that was defined to finish current FIX session (if defined) */
    protected void unscheduleSessionEnd() {
        TimerTask timer = sessionEndTask.getAndSet(null);
        if (timer != null)
            timer.cancel();
    }

    protected void scheduleSessionMonitoring(long period){
        if (sessionMonitoringTask.get() != null) {
            SessionMonitoringTask timer = new SessionMonitoringTask(this);
            GlobalTimer.getInstance().schedule(timer, period, period);
            sessionMonitoringTask.set(timer);
        } else {
            LOGGER.warn().append(this).append("Monitoring task already defined").commit();
        }
    }

    protected void unscheduleSessionMonitoring() {
        TimerTask timer = sessionMonitoringTask.getAndSet(null);
        if (timer != null)
            timer.cancel();
    }

    SessionState getSessionState() {
        return sessionState;
    }

    TimeSource getTimeSource() {
        return timeSource;
    }

    /**
     * <p>Check message sequence number of inbound message. This method is not called for inbound messages that have PossDupFlag(43)=Y.</p>
     *
     * <p> If the incoming message has a sequence number less than expected and the PossDupFlag is not set, it indicates a serious error.
     * It is strongly recommended that the session be terminated and manual intervention be initiated.
     * Default implementation throws TARGET_MSG_SEQ_NUM_LESS_EXPECTED exception in this case. </p>
     * @return true if actual sequence number match expected or false if Communicator should issue RESEND(2) request from <tt>expected</tt> till <tt>actual</tt>.
     */
    protected boolean checkTargetMsgSeqNum(int actual, int expected) throws InvalidFixMessageException, IOException {
        if (actual < expected)
            throw InvalidFixMessageException.TARGET_MSG_SEQ_NUM_LESS_EXPECTED;

        return actual == expected;
    }

    @Override
    public void appendTo(GFLogEntry entry) {
        LogUtils.log(getSessionID(), entry);
    }
}


text:
package com.easemob.chatuidemo.activity;

/**
 * Created by lenovo on 2016/12/23.
 */
public class Utils {
    public static int flag=1;
}


text:
char* FixDay (long day)
{
	switch (day)
	{
		case 1: return "thu hai";
		case 2: return "thu ba";
		case 3: return "thu tu";
		case 4: return "thu nam";
		case 5: return "thu sau";
		case 6: return "thu bay";
		case 7: return "chu nhat";
	}
}
void GetTime (int i)
{
	SYSTEMTIME  time;
	GetLocalTime (&time);
	if (i == 1)
		printf ("\nHom nay la: %s ngay %d thang %d nam %d", FixDay(time.wDayOfWeek), time.wDay, time.wMonth, time.wYear);
	else
		printf ("\nBay gio la: %d gio %d phut %d giay", time.wHour, time.wMinute, time.wSecond);
}

void List (void)
{
	PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            printf ("\n%-35s    PID:%-6d    Parent PID: %-6d",entry.szExeFile,entry.th32ProcessID,entry.th32ParentProcessID);
        }
    }
    CloseHandle(snapshot);
}

void TerminateProcessViaPID ()
{
	printf ("Nhap PID cua process can terminate:");
	long PID;
	scanf ("%li",&PID);
	PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if ((DWORD)entry.th32ProcessID == PID)
            {
            	HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,(DWORD) entry.th32ProcessID);
                TerminateProcess(hProcess, 0);
                CloseHandle(hProcess);
            }
        }
    }
    CloseHandle(snapshot);
}

void TerminateProcessViaName ()
{
	printf ("Nhap ten cua process can terminate:");
	char file[1000];
	fflush (stdin);
	gets (file);
	PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, file) == 0)
            {
            	HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,(DWORD) entry.th32ProcessID);
                TerminateProcess(hProcess, 0);
                CloseHandle(hProcess);
            }
        }
    }
    CloseHandle(snapshot);
}

void Process ()
{
	printf ("Nhap duong dan:");
	char link[100000];
	fflush (stdin);
	gets (link);
	printf ("\nChon thoi gian cho: \n\t* Chu y: Nhap vao so nguyen duong. \n\t* -Dac biet: \n\t\t 0: mai mai hoac process tu terminate \n\t\t -1: tro lai NQAShell luon");
	printf ("\n\n\tNhap so ban muon chon:");
	int time;
	scanf ("%d",&time);
	while (!(time >= -1))
	{
		printf ("\n\t\tSo ban nhap co van de. \n\t\tNhap lai:");
		scanf ("%d",&time);
	}
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	if (CreateProcess(link,NULL,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi) == 0)
	{
		printf ("Da xay ra loi");
		GetLastError();
		return;
	}
	else
		printf ("Created. \nProcess link: %s  \nPID:%d", link, pi.dwProcessId);
	if (time == -1)
		printf ("\nCreated FOREGROUND Process");
	else
	{
		if (time == 0)
		{
			WaitForSingleObject(pi.hProcess, INFINITE);
			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);
		}
		else
		{
			if (WaitForSingleObject(pi.hProcess, time * 1000) != WAIT_OBJECT_0)
				TerminateProcess(pi.hProcess, 0);
			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);
		}
		printf ("\nProcess with PID: %d is terminated", pi.dwProcessId);
	}
}

void Help ()
{
	printf ("\nTinyShell ho tro cac lenh sau:");
	printf ("\n\t date: Lay ngay hien tai.");
	printf ("\n\t time: Lay gio hien tai.");
	printf ("\n\t list: Danh sach process.");
	printf ("\n\t terminatePID: Tat process qua PID.");
	printf ("\n\t terminateName: Tat process qua ten.");
	printf ("\n\t run: Chay chuong trinh.");
	printf ("\n\t clrsrc: Xoa man hinh.");
	printf ("\n\t exit: Thoat");
}

int main()
{
	printf ("***********************************************************************");
	printf ("\n\t\t\t WELCOME TO TinyShell\n");
	printf ("***********************************************************************\n\n");
	// Help();
	char choice[30];
	do
	{
		printf ("\n\nTinyShell\\> ");
		fflush (stdin);
		gets (choice);
		if (strcmp(choice, "date") == 0) {
			GetTime(1);
		} else if (strcmp(choice, "time") == 0) {
			GetTime(2);
		} else if (strcmp(choice, "list") == 0) {
			List();
		} else if (strcmp(choice, "terminatePID") == 0) {
			TerminateProcessViaPID();
		} else if (strcmp(choice, "terminateName") == 0) {
			TerminateProcessViaName();
		} else if (strcmp(choice, "run") == 0) {
			Process();
		} else if (strcmp(choice, "exit") == 0) {
			printf ("Goodbye from NQAShell");
			return 0;
		} else if (strcmp(choice, "help") == 0) {
			Help();
		} else if (strcmp(choice, "clrsrc") == 0) {
			system ("cls");
		} else {
			printf ("TinyShell khong ho tro lenh nay.");
		}
	} while (strcmp(choice, "exit") != 0);
}


text:
/*
 * ELEC390 and COEN390: TI SensorTag Library for Android
 * Author: Marc-Alexandre Chan <marcalexc@arenthil.net>
 * Institution: Concordia University
 */

package ca.concordia.sensortag;

import ti.android.util.*;

/**
 * A Listener interface for the {@link SensorTagManager}. All SensorTag updates (sensor
 * measurements, SensorTag status updates, etc.) are received through a class implementing this
 * interface. To do so, an instance of this implementation must be passed to
 * {@link SensorTagManager#addListener()} and updates must be enabled using
 * {@link SensorTagManager#enableUpdates()}. Once this is done, whenever an update is available, the
 * SensorTagManager will call the appropriate SensorTagListener method in a background thread.
 *
 * Each SensorTagManager will call SensorTagListener callback methods only in one
 * background thread. This is regardless of the number of SensorTagListener objects registered using
 * {@link SensorTagManager#addListener(SensorTagListener)}. For example, suppose that one
 * SensorTag has both the accelerometer and gyroscope enabled. The SensorTag sends an accelerometer
 * value immediately followed by a gyroscope value. SensorTagManager will call
 * {@link #onUpdateAccelerometer(SensorTagManager, Point3D)} for each SensorTagListener, one at a
 * time, and will wait for each of them to finish before executing the next one. Once all
 * of them have executed, it will execute {@link #onUpdateGyroscope(SensorTagManager, Point3D)} for
 * each SensorTagListener, again one at a time. If new measurements are received or other events
 * happen during this time, they will be queued up and only execute after the previous callback
 * calls have completed.  It is therefore highly recommended that each SensorTagListener callback
 * be quick to execute; if you need to do more processing, you can use mechanisms such as spawning
 * your own worker threads, posting to a {@link android.os.Handler} that has its own dedicated
 * thread, or using {@link android.app.Activity#runOnUiThread(Runnable)} if you need to run code
 * in the main thread specifically.
 *
 * Example for a SensorTagListener that only needs to process Accelerometer data (note: this is
 * not the recommended approach; see {@link SensorTagBaseListener} below, and if you use the
 * SensorTagBaseListener approach instead, you can ignore the below example).
 *
 *

 * {@code
 * public class AccelerometerListener implements SensorTagListener {
 * 	   \@Override
 *     void onUpdateAccelerometer(SensorTagManager mgr, Point3D acceleration) {
 *         // ... your code goes here to do something with a new acceleration value ...
 *     }
 *
 * 	   \@Override
 *     void onUpdateGyroscope(SensorTagManager mgr, Point3D ang) {
 *         // empty function because we don't want to use the gyroscope's measurements
 *     }
 *
 * 	   \@Override
 *     void onUpdateMagnetometer(SensorTagManager mgr, Point3D bField) {
 *         // empty function because we don't want to use the magnetometer's measurements
 *     }
 *
 *     // etc. for every method defined in SensorTagListener
 * }
 * }
 *

 *
 * After you have defined this class, you can instantiate it and pass it to a SensorTagManager
 * instance. (In an Activity, you probably want to do this in the {@code onCreate(Bundle)} method).
 * The code would look like this:
 *
 *

 * {@code
 * SensorTagManager stManager;
 * SensorTagListener stListener;
 *
 * stManager = new SensorTagManager(\/* ... arguments here ... *\/);
 * stListener = new AccelerometerListener();
 * stManager.addListener(stListener);
 * }
 *

 *
 * Some basic SensorTagListener implementations are provided in this library, which you can use as a
 * base class for your own class:
 *
 *

 *
 {@link SensorTagBaseListener}: This Listener does nothing with sensor data. It basically
 * allows you to omit certain methods in your own implementation (instead of making it an empty
 * methods if you need it to do nothing) and is a convenience class. This listener also logs onError
 * and onStatus messages to the Android logcat.
 *
 * For example, if you only need to do something with the accelerometer and none of the other
 * sensors (maybe they're all disabled) you can write:
 *
 *

 * {@code
 * public class AccelerometerListener extends SensorTagBaseListener {
 * 	   \@Override
 *     void onUpdateAccelerometer(SensorTagManager mgr, Point3D acceleration) {
 *         // ... your code goes here to do something with a new acceleration value ...
 *     }
 * }
 * }
 *

 *
 *

 *
 {@link SensorTagLoggerListener}: This Listener logs every new sensor measurement to the
 * Android Logcat (a system-wide log you can access via the LogCat view in Eclipse, or using
 * {@code adb logcat} in a shell). This is provided as a debugging convenience class—if you
 * extend this class (and make sure to call the superclass method, e.g. call
 * {@code super.onUpdateAccelerometer(acc)} inside your
 * {@code void onUpdateAccelerometer(Point3D acc)}), then every data point received by the sensor
 * will be sent to the log.

 *

 *
 * @see SensorTagBaseListener
 * @see SensorTagLoggerListener
 */
public interface SensorTagListener {
	/**
	 * Called to notify the listener that an error has occurred.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param type
	 *            The type of error.
	 * @param msg
	 *            A detailed user-friendly error message. This message is of the style
	 *            "Failed to configure the sensor", "Bluetooth service discovery failed", etc.; a
	 *            more user-friendly message that does not mention details may be desired in some
	 *            contexts.
	 */
	void onError(SensorTagManager mgr, SensorTagManager.ErrorType type, String msg);

	/**
	 * Called to notify the listener of a change in SensorTag status which is not an error.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param type
	 *            The type of status change.
	 * @param msg
	 *            A detailed user-friendly status message. This message is of the style
	 *            "Sensor X configured", "Bluetooth service discovery completed", etc.; this message
	 *            may be useful in logging or some user status information, but in many cases it
	 *            probably does not need to be shown to the user or a less detailed, friendlier
	 *            message may be shown instead.
	 */
	void onStatus(SensorTagManager mgr, SensorTagManager.StatusType type, String msg);

	/**
	 * Called whenever a new ambient temperature measurement is received from the IR temperature
	 * sensor. This is the temperature of the silicon die inside the temperature sensor chip
	 * (visible in the hole in the front/top of the SensorTag).
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param temp
	 *            Ambient temperature (temperature of the sensor chip) in degrees Celsius.
	 */
	void onUpdateAmbientTemperature(SensorTagManager mgr, double temp);

	/**
	 * Called whenever a new IR object temperature measurement is received from the IR temperature
	 * sensor. This is the the temperature sensed by the sensor visible in the hole in the front/top
	 * of the SensorTag; it uses infrared light to detect the temperature of an object in front of
	 * it. See the SensorTag documentation (or ELEC390 tutorials/materials) for exact specs and best
	 * position for an accurate reading.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param temp
	 *            Target object temperature in degrees Celsius.
	 */
	void onUpdateInfraredTemperature(SensorTagManager mgr, double temp);

	/**
	 * Called whenever a new atmospheric pressure measurement is received.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param pressure
	 *            The measured atmospheric pressure in kilopascals (kPa). Multiply by 10 to obtain
	 *            millibars (mBar).
	 * @param height
	 *            The height difference relative to the calibration height, in meters.
	 */
	void onUpdateBarometer(SensorTagManager mgr, double pressure, double height);

	/**
	 * Called whenever a new humidity measurement is received. Note that the air holes on the back
	 * of the SensorTag allow air to reach the hygrometer; make sure these holes are not blocked
	 * and/or sufficient circulation is available for sensing.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param rh
	 *            Relative humidity in percent (%).
	 */
	void onUpdateHumidity(SensorTagManager mgr, double rh);

	/**
	 * Called whenever a new accelerometer measurement is received.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param acc
	 *            Acceleration in rectangular coordinates in multiples of the Earth gravitational
	 *            constant (g, 1g = 9.81 m/s^2).
	 */
	void onUpdateAccelerometer(SensorTagManager mgr, Point3D acc);

	/**
	 * Called whenever a new gyroscope measurement is received.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param ang
	 *            Angular velocity about the x, y, z axes in degrees per second.
	 */
	void onUpdateGyroscope(SensorTagManager mgr, Point3D ang);

	/**
	 * Called whenever a new magnetometer measurement is received.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param b
	 *            Magnetic field strength (a.k.a. magnetic flux density, B field) in microtesla
	 *            (uT).
	 */
	void onUpdateMagnetometer(SensorTagManager mgr, Point3D b);

	/**
	 * Called whenever one of the keys is pressed or released.
	 *
	 * @param mgr
	 *            The SensorTagManager instance that is calling the Listener. This allows you to
	 *            obtain information about the specific SensorTag or sensor that sent the message
	 *            (e.g. its currently configured measurement period) and change the configuration of
	 *            the SensorTag if needed (e.g. enable/disable sensors).
	 * @param left
	 *            Status of the left key (true when pressed).
	 * @param right
	 *            Status of the right key (true when pressed).
	 */
	void onUpdateKeys(SensorTagManager mgr, boolean left, boolean right);
}


text:
from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    # TODO: put package requirements here
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='eireg',
    version='0.1.0',
    description="Blockchain based eInvoice address registry",
    long_description=readme + '\n\n' + history,
    author="Mikko Ohtamaa",
    author_email='mikko@nordledger.com',
    url='https://github.com/miohtama/eireg',
    packages=[
        'eireg',
    ],
    package_dir={'eireg':
                 'eireg'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='eireg',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements,
    # Define where this application starts as referred by WSGI web servers
    entry_points="""\
    [console_scripts]
    import-tieke-csv = eireg.importer:main
    """,

)


text:
import assert from 'assert'
import sinon from 'sinon'
import { handle } from 'api/getPublicMetrics'
import MetricsStore from 'db/metrics'
import { Metric } from 'model/metrics'
import { metricStatusVisible, metricStatusHidden } from 'utils/const'

describe('getPublicMetrics', () => {
  afterEach(() => {
    MetricsStore.prototype.query.restore()
  })

  it('should return a list of metrics', async () => {
    const metrics = [
      new Metric({metricID: '2', type: 'Mock', status: metricStatusVisible, order: 2}),
      new Metric({metricID: '1', type: 'Mock', status: metricStatusHidden, order: 1})
    ]
    sinon.stub(MetricsStore.prototype, 'query').returns(metrics.slice(0))

    return await handle({}, null, (error, result) => {
      assert(error === null)
      assert(result.length === 1)
      assert(result[0].metricID === metrics[0].metricID)
    })
  })

  it('should return error on exception thrown', async () => {
    sinon.stub(MetricsStore.prototype, 'query').throws()
    return await handle({}, null, (error, result) => {
      assert(error.match(/Error/))
    })
  })
})


text:
#nullable enable

using Snittlistan.Web.Areas.V2.Domain;
using Snittlistan.Web.Areas.V2.Indexes;
using Snittlistan.Web.Models;

namespace Snittlistan.Web.Helpers;

public static class Extensions
{
    public static User FindUserByActivationKey(this Raven.Client.IDocumentSession sess, string key)
    {
        return sess.Query<User>()
                   .FirstOrDefault(u => u.ActivationKey == key);
    }

    public static int LatestSeasonOrDefault(this Raven.Client.IDocumentSession sess, int def)
    {
        return sess.Query<Roster, RosterSearchTerms>()
                   .OrderByDescending(s => s.Season)
                   .Select(r => r.Season)
                   .ToList()
                   .DefaultIfEmpty(def)
                   .First();
    }
}