text:
//#define DEBUG_BARSCOPIED
//#define BarStruct
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Reactive.Subjects;
using LionFire.Validation;
using LionFire.Instantiating;
using LionFire;
using System.Collections.Concurrent;
using LionFire.Execution;
using LionFire.Execution.Jobs;
#if BarStruct
using BarType = LionFire.Trading.TimedBarStruct;
#else
using BarType = LionFire.Trading.TimedBar;
#endif
using System.Threading.Tasks;
using TickType = LionFire.Trading.Tick;
using LionFire.Trading.Data;
using System.Threading;
using System.ComponentModel;

namespace LionFire.Trading
{
    public class TMarketSeries : TMarketSeriesBase, ITemplate<MarketSeries>, IValidatesCreate
    {
        public ValidationContext ValidateCreate(ValidationContext context)
        {
            context.MemberNonNull(Feed, nameof(Feed));
            if (TimeFrame == "t1")
            {
                context.AddIssue(new ValidationIssue
                {
                    Message = "t1 not supported for TMarketSeries.  Use TMarketTickSeries instead.",
                    VariableName = nameof(TimeFrame),
                    Kind = ValidationIssueKind.InvalidConfiguration | ValidationIssueKind.ParameterOutOfRange,
                });
            }
            return context;
        }
    }

    public sealed class MarketSeries : MarketSeriesBase<TMarketSeries, TimedBar>, IMarketSeries, IMarketSeriesInternal, ITemplateInstance<TMarketSeries>
    {

        #region Configuration

        public static readonly bool FillMissingBars = false; // REVIEW -
        // If true, each index represents an increment of the TimeFrame.
        public static readonly bool UniformBars = false;

        #endregion

        #region Construction

        public MarketSeries() : base() { }
        public MarketSeries(IFeed account, string key) : base(account, key)
        {
        }
        public MarketSeries(IFeed market, string symbol, TimeFrame timeFrame) : base(market, symbol, timeFrame)
        {
        }

        #endregion

        #region Data

        public BarType this[DateTime time]
        {
            get
            {
                var index = FindIndex(time);
                if (index < 0) return default(BarType);
                return this[index];
            }
        }

        public IBarSeries Bars
        {
            get
            {
                if (bars == null)
                {
                    bars = new BarSeriesAdapter(this);
                }
                return bars;
            }
        }
        private BarSeriesAdapter bars; // TOOPTIMIZE: switch to BarSeries

        public DataSeries Open
        {
            get { return open; }
        }
        private DataSeries open = new DataSeries();

        public DataSeries High
        {
            get { return high; }
        }
        private DataSeries high = new DataSeries();

        public DataSeries Low
        {
            get { return low; }
        }
        private DataSeries low = new DataSeries();

        public DataSeries Close
        {
            get { return close; }
        }
        private DataSeries close = new DataSeries();

        public DataSeries TickVolume
        {
            get { return tickVolume; }
        }
        private DataSeries tickVolume = new DataSeries();

        #region Derived

        public override BarType this[int index]
        {
            get
            {
#if BarStruct
                return bars[index];
#else
                return new TimedBar
                {
                    OpenTime = openTime[index],
                    Open = open[index],
                    High = high[index],
                    Low = low[index],
                    Close = close[index],
                    Volume = tickVolume[index],
                };
#endif
            }
            set
            {
                openTime[index] = value.OpenTime;
                open[index] = value.Open;
                high[index] = value.High;
                low[index] = value.Low;
                close[index] = value.Close;
                tickVolume[index] = value.Volume;
            }
        }
        private IEnumerable<DataSeries> AllDataSeries
        {
            get
            {
                yield return open;
                yield return high;
                yield return low;
                yield return close;
                yield return tickVolume;
            }
        }

        #endregion

        #endregion

        #region Backtesting

        public HistoricalPlaybackState HistoricalPlaybackState { get; set; }

        #endregion

        #region Events

        public event Action<TimedBar> Bar
        {
            add
            {
                bool last = BarHasObservers;
                timedBar += value;
                if (last != BarHasObservers)
                {
                    BarHasObserversChanged?.Invoke(this, BarHasObservers);
                }
            }
            remove
            {
                bool last = BarHasObservers;
                timedBar -= value;
                if (last != BarHasObservers)
                {
                    BarHasObserversChanged?.Invoke(this, BarHasObservers);
                }
            }
        }
        event Action<TimedBar> timedBar;

        //public event Action<SymbolBar> SymbolBar
        //{
        //    add
        //    {
        //        bool last = BarHasObservers;
        //        symbolBar += value;
        //        if (last != BarHasObservers)
        //        {
        //            BarHasObserversChanged?.Invoke(this, BarHasObservers);
        //        }
        //    }
        //    remove
        //    {
        //        bool last = BarHasObservers;
        //        symbolBar -= value;
        //        if (last != BarHasObservers)
        //        {
        //            BarHasObserversChanged?.Invoke(this, BarHasObservers);
        //        }
        //    }
        //}
        //event Action<SymbolBar> symbolBar;
        private const object symbolBar = null;

        public bool BarHasObservers
        {
            get
            {
                return symbolBar != null || timedBar != null;
            }
        }

        public event Action<IMarketSeries, bool> BarHasObserversChanged;

        public bool LatestBarHasObservers { get { return barSubject.HasObservers; } }
        public IObservable<TimedBar> LatestBar
        {
            get
            {
                return barSubject;
            }
        }

        BehaviorSubject<TimedBar> barSubject = new BehaviorSubject<BarType>(TimedBar.Invalid);

        //public event Action<MarketSeries> BarReceived;
        public event Action<MarketSeries, double/*bid*/, double/*ask*/> TickReceived;
        //public event Action<TimedBar> BarFinished;
        //public event Action<TimedBar> InterimBarReceived;
        #endregion

        #region Methods

        // OLD - this is also in base class
        ///// <param name="time"></param>
        ///// <param name="loadHistoricalData">If true, this may block for a long time!</param>
        ///// <returns></returns>
        //public int FindIndex(DateTime time, bool loadHistoricalData = false)
        //{
        //    var result = openTime.FindIndex(time);
        //    if (result == -1 && loadHistoricalData)
        //    {
        //        var first = OpenTime.First();
        //        if (time < first)
        //        {
        //            //var span = time - first;
        //            //var estimatedBars = span.TotalMilliseconds / TimeFrame.TimeSpan.TotalMilliseconds;
        //            EnsureDataAvailable(time, first).Wait(); // BLOCKING!
        //        }
        //        result = openTime.FindIndex(time);
        //    }
        //    //else
        //    //{

        //    //}
        //    return result;
        //}
        #endregion

        //public IEnumerable<SymbolBar> GetBars(DateTime fromTimeExclusive, DateTime endTimeInclusive)
        //{
        //    return null;
        //    //SymbolBar bar = null;
        //    //bar.Yield();
        //}

        #region (Internal) Methods - Data input

        /// <summary>
        ///
        /// </summary>
        /// <param name="bar"></param>
        /// <param name="barOpenTime"></param>
        /// <param name="finishedBar">True if backtesting with data that has one bar per time step.</param>
        public void OnBar(TimedBar bar, bool finishedBar = false)
        {
            if (OpenTime.LastValue != bar.OpenTime)
            {
                if (FillMissingBars)
                {
                    // REVIEW
                    Console.WriteLine("WARN: Bug exists when trying to fill from year 0 to present when FillMissingBars enabled.");
                    for (var nextTime = OpenTime.LastValue + TimeFrameTimeSpan; nextTime < bar.OpenTime; nextTime += TimeFrameTimeSpan)
                    {
                        AddDataPointAtTime(nextTime);
                    }
                }
                if (OpenTime.LastValue != bar.OpenTime)
                {
                    AddDataPointAtTime(bar.OpenTime);
                }
            }

            // Replace last values
            open.LastValue = bar.Open;
            high.LastValue = bar.High;
            low.LastValue = bar.Low;
            close.LastValue = bar.Close;
            tickVolume.LastValue = bar.Volume;

            if (finishedBar)
            {
                //BarReceived?.Invoke(this);
                this.barSubject.OnNext(bar);
                //this.symbolBar?.Invoke(new SymbolBar(SymbolCode, bar));
                this.timedBar?.Invoke(bar);
            }
        }

        private void StartNewBar(DateTime? time = null)
        {
            if (open.Count > 0)
            {
                AddDataPointAtTime(openTime.LastValue + TimeFrameTimeSpan);
                open.LastValue = high.LastValue = low.LastValue = close.LastValue = close.Last(1);
            }
            else
            {
                if (!time.HasValue) throw new ArgumentNullException("value for time required when series is empty");

                var roundedTime = this.TimeFrame.Round(time.Value);
                AddDataPointAtTime(roundedTime);
                // bar = NaN
            }
            tickVolume.LastValue = 0;

        }
        public void OnTick(DateTime time, double bid, double ask)
        {
            if ((openTime.LastValue + TimeFrameTimeSpan) <= time)
            {
                StartNewBar(time);
            }
            tickVolume.LastValue++;
            TickReceived?.Invoke(this, bid, ask);
        }

        internal void AddDataPointAtTime(DateTime time)
        {
            OpenTime.Add(time);
            foreach (var ds in AllDataSeries)
            {
                ds.Add();
            }
        }
        /*
        public void Add(List<TimedBar> bars, DateTime? startDate = null, DateTime? endDate = null)
        {
            // TODO: Fill range from startDate to endDate with "NoData" and if a range is loaded that creates a gap with existing ranges, fill that with "MissingData"

            //if (bars.Count == 0) return;
            var resultsStartDate = bars.Count == 0 ? default(DateTime):bars[0].OpenTime;
            var resultsEndDate = bars.Count == 0 ? default(DateTime) : bars[bars.Count - 1].OpenTime;
            if (!startDate.HasValue) { startDate = resultsStartDate; Debug.WriteLine("WARN -!startDate.HasValue in MarketSeries.Add"); }
            if (!endDate.HasValue) { endDate = resultsEndDate; Debug.WriteLine("WARN -!endDate.HasValue in MarketSeries.Add"); }

#if DEBUG_BARSCOPIED
            int barsCopied = 0;
#endif

            if (this.Count == 0 && DataEndDate == default(DateTime) && DataStartDate == default(DateTime))
            {
                foreach (var b in bars)
                {
                    //Add(b.Time,b.Open,b.High,b.Low,b.Close,b.Volume);
                    this.openTime.Add(b.Time);
                    this.open.Add(b.Open);
                    this.high.Add(b.High);
                    this.low.Add(b.Low);
                    this.close.Add(b.Close);
                    this.tickVolume.Add(b.Volume);
                }
            }
            else
            {

                if (startDate <= DataStartDate) // prepending data
                {
                    int lastIndexToCopy;
                    for (lastIndexToCopy = bars.Count - 1; lastIndexToCopy >= 0 && bars[lastIndexToCopy].OpenTime >= DataStartDate; lastIndexToCopy--) ; // OPTIMIZE?

                    for (int dataIndex = OpenTime.MinIndex - 1; lastIndexToCopy >= 0; dataIndex--, lastIndexToCopy--)
                    {
                        //var bar = bars[lastIndexToCopy] as TimedBar;
                        //if (bar == null)
                        //{
                        //    bar = new TimedBar(bars[lastIndexToCopy]);
                        //}
                        this[dataIndex] = bars[lastIndexToCopy];
#if DEBUG_BARSCOPIED
                        barsCopied++;
#endif
                    }

                    if (DataStartDate != default(DateTime) && endDate.Value + TimeFrame.TimeSpan < DataStartDate)
                    {
                        Debug.WriteLine($"[DATA GAP] endDate: {endDate.Value}, DataStartDate: {DataStartDate}");
                        AddGap(endDate.Value + TimeFrame.TimeSpan, DataStartDate - TimeFrame.TimeSpan);
                    }

                }

                // Both above and below may get run

                if (endDate >= DataEndDate) // append data
                {
                    int lastIndexToCopy;
                    for (lastIndexToCopy = 0; lastIndexToCopy < bars.Count && bars[lastIndexToCopy].OpenTime <= DataEndDate; lastIndexToCopy++) ; // OPTIMIZE?

                    for (int dataIndex = OpenTime.LastIndex + 1; lastIndexToCopy < bars.Count; dataIndex++, lastIndexToCopy++)
                    {
                        //var bar = bars[lastIndexToCopy] as TimedBar;
                        //if (bar == null)
                        //{
                        //    bar = new TimedBar(bars[lastIndexToCopy]);
                        //}
                        this[dataIndex] = bars[lastIndexToCopy];
#if DEBUG_BARSCOPIED
                        barsCopied++;
#endif
                    }

                    if (DataEndDate != default(DateTime) && startDate.Value - TimeFrame.TimeSpan > DataEndDate)
                    {
                        Debug.WriteLine($"[DATA GAP] startDate: {startDate.Value}, DataEndDate: {DataEndDate}");
                        AddGap(DataEndDate + TimeFrame.TimeSpan, startDate.Value - TimeFrame.TimeSpan);
                    }
                }
            }

            var oldEnd = DataEndDate;
            var oldStart = DataStartDate;
            if (DataEndDate == default(DateTime) || startDate.Value - TimeFrame.TimeSpan <= DataEndDate && endDate.Value > DataEndDate)
            {
                DataEndDate = endDate.Value;
            }
            if (DataStartDate == default(DateTime) || endDate.Value + TimeFrame.TimeSpan >= DataStartDate && startDate.Value < DataStartDate)
            {
                DataStartDate = startDate.Value;
            }

            Debug.WriteLine($"[{this}] New data range: {DataStartDate} - {DataEndDate}  (was {oldStart} - {oldEnd})");
#if DEBUG_BARSCOPIED
            Debug.WriteLine($"{SymbolCode}-{TimeFrame.Name} Imported {barsCopied} bars");
#endif
            EraseGap(startDate.Value, endDate.Value);
        }
        */

        protected override void Add(TimedBar dataPoint)
        {
            var bar = dataPoint;
            // TODO: Don't split into 6 bidirectional arrays -- use one pair of arrays for TimedBar
            //this.bars.Add((TimedBar)dataPoint);
            this.openTime.Add(bar.OpenTime);
            this.open.Add(bar.Open);
            this.high.Add(bar.High);
            this.low.Add(bar.Low);
            this.close.Add(bar.Close);
            this.tickVolume.Add(bar.Volume);
        }

        public void Add(DateTime time, double open, double high, double low, double close, double volume)
        {
            this.openTime.Add(time);
            this.open.Add(open);
            this.high.Add(high);
            this.low.Add(low);
            this.close.Add(close);
            this.tickVolume.Add(volume);
        }

        private void Add(DateTime[] time, double[] open, double[] high, double[] low, double[] close, double[] volume)
        {
            this.openTime.Add(time);
            this.open.Add(open);
            this.high.Add(high);
            this.low.Add(low);
            this.close.Add(close);
            this.tickVolume.Add(volume);
        }
        private void Add(DateTime[] time, double[] open, double[] high, double[] low, double[] close, double[] volume, int count)
        {
            for (int i = 0; i < count; i++)
            {
                this.openTime.Add(time[i]);
                this.open.Add(open[i]);
                this.high.Add(high[i]);
                this.low.Add(low[i]);
                this.close.Add(close[i]);
                this.tickVolume.Add(volume[i]);
            }
        }

        #endregion

        #region Methods - Import

        // MOVE to file importer

        public const char csvSeparator = ',';

        private DateTime ParseDate(string line /*, bool fastDate, bool hasSeconds*/)
        {
            var cells = line.Split(csvSeparator);
            var dateString = cells[0] + " " + cells[1];
            DateTime result;
            DateTime.TryParse(dateString, out result);
            return result;
        }

        public DateTime? GetFirstDateFromPosition(FileStream fs, long position)
        {
            fs.Position = position;

            byte[] buffer = new byte[256];
            fs.Read(buffer, 0, buffer.Length);
            var str = UTF8Encoding.UTF8.GetString(buffer);
            var lines = str.Split('\n');
            if (lines.Length < 2) return null;
            var dateTime = ParseDate(lines[1]);
            return dateTime;
        }
        public long FindPositionForDate(FileStream fs, DateTime seekDate, bool getPreviousBar = true)
        {
            int rewindAmount = 100000;

            DateTime firstDate;
            DateTime lastDate;
            string line;

            fs.Seek(0, SeekOrigin.Begin);
            using (var sr = new StreamReader(fs, UTF8Encoding.UTF8, true, 1024, true))
            {
                line = sr.ReadLine().Trim();

                if (line.Length == 0 || !char.IsNumber(line[0])) // Skip header row
                {
                    line = sr.ReadLine();
                }
                firstDate = ParseDate(line);
                //Console.WriteLine($"First date: {firstDate}");
            }

            fs.Seek(-512, SeekOrigin.End);
            List<string> lastLines = new List<string>();
            using (var sr = new StreamReader(fs, UTF8Encoding.UTF8, true, 1024, true))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    lastLines.Add(line);
                }
                int index = lastLines.Count - 1;
                while (lastLines[index].Trim().Length == 0)
                {
                    index--;
                }
                string lastLine = lastLines[index];
                lastDate = ParseDate(lastLine);
                //Console.WriteLine($"Last date: {lastDate}");
            }

            var fileTimeSpan = lastDate - firstDate;
            var seekTimeSpan = seekDate - firstDate;
            if (seekTimeSpan < TimeSpan.Zero) return -1;
            if (seekDate > lastDate)
            {
                return fs.Length;
            }

            var seekPercent = seekTimeSpan.TotalMilliseconds / fileTimeSpan.TotalMilliseconds;
            var seekBytes = Math.Max(0, (long)(fs.Length * (seekPercent - 0.005)) - 100);

            long bytesDelta;
            while (true)
            {
                fs.Seek(seekBytes, SeekOrigin.Begin);

                bytesDelta = 0;
                using (var sr = new StreamReader(fs, UTF8Encoding.UTF8, true, 1024, true))
                {
                    line = sr.ReadLine(); // Skip first line, probably partial.
                    bytesDelta += line.Length + 2;

                    DateTime date1;
                    DateTime date2;

                    line = sr.ReadLine();
                    bytesDelta += line.Length + 2;
                    date1 = ParseDate(line);

                    line = sr.ReadLine();
                    bytesDelta += line.Length + 2;
                    date2 = ParseDate(sr.ReadLine());

                    while (date2 < seekDate)
                    {
                        date1 = date2;
                        line = sr.ReadLine();
                        bytesDelta += line.Length + 2;
                        date2 = ParseDate(line);
                    }

                    if (date2 > seekDate && date1 > seekDate && seekBytes > 0)
                    {
                        seekBytes -= rewindAmount;
                        if (seekBytes < 0) seekBytes = 0;
                        //Console.WriteLine($"Overshot.  Rewinding by {rewindAmount} to {seekBytes}.");
                        continue;
                    }
                    else
                    {
                        if (getPreviousBar)
                        {
                            bytesDelta -= line.Length + 2;
                            if (bytesDelta < 0) bytesDelta = 0;
                        }
                        //Console.WriteLine($"date1 {date1}, seekDate {seekDate}, date2 {date2} at byte {seekBytes + bytesDelta}");
                        break;
                    }
                }
            }
            return Math.Max(0, seekBytes + bytesDelta - 2); // Minus 2 for \r\n -- first line is discarded.
        }

        public void ImportFromFile(string path, DateTime? startDate = null, DateTime? endDate = null, bool getPreviousBar = true)
        {
            int lines = 0;
            long totalBytes = new FileInfo(path).Length;
            long bytes = 0;
            long bytesToRead = totalBytes;
            long startPos = 0;
            long endPos = totalBytes;

            var sw = Stopwatch.StartNew();

            int bufferSize = 128;
            DateTime[] openTimeBuffer = new DateTime[bufferSize];
            double[] openBuffer = new double[bufferSize];
            double[] highBuffer = new double[bufferSize];
            double[] lowBuffer = new double[bufferSize];
            double[] closeBuffer = new double[bufferSize];
            double[] volumeBuffer = new double[bufferSize];
            int bufferIndex = 0;

            bool fastDate = false;
            bool hasSeconds = false;

            try
            {
                string line;

                FileStream fs;
                using (fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    if (startDate.HasValue)
                    {
                        startPos = Math.Max(0, FindPositionForDate(fs, startDate.Value));
                    }
                    if (endDate.HasValue)
                    {
                        endPos = FindPositionForDate(fs, endDate.Value);
                    }

                    fs.Seek(startPos, SeekOrigin.Begin);

                    bytesToRead = endPos - startPos;

                    Console.Write($"Reading {bytesToRead} bytes from '{Path.GetFileName(path)}'   00.0%");

                    using (var sr = new StreamReader(fs))
                    {
                        line = sr.ReadLine(); // Discard first line
                        if (line != null)
                        {
                            bytes += line.Length + 2;
                        }

                        bool isFirstLine = true;
                        for (string previousLine = null; (line = sr.ReadLine()) != null; previousLine = line)
                        {
                            bytes += line.Length + 2;
                            if (++lines % 32768 == 0 || bytes >= totalBytes)
                            {
                                Console.Write("\b\b\b\b\b" + (100.0 * bytes / bytesToRead).ToString("N1").PadLeft(4) + "%");
                            }

                            if (String.IsNullOrWhiteSpace(line)) continue;
                            var cells = line.Split(',');
                            if (isFirstLine)
                            {
                                isFirstLine = false;
                                var trimmed = line.TrimStart();
                                if (!char.IsNumber(trimmed[0]))
                                {
                                    continue; // Skip header line
                                }

                                if (cells[0][4] == '.')
                                {
                                    fastDate = true;
                                }
                                else
                                {
                                    Console.Write(" (slow parsing mode) ");
                                }
                                if (cells[1].Length > 6)
                                {
                                    hasSeconds = true;
                                }
                            }

                            DateTime time;
                            if (fastDate)
                            {
                                time = new DateTime(
                                        Convert.ToInt32(cells[0].Substring(0, 4)),
                                        Convert.ToInt32(cells[0].Substring(5, 2)),
                                        Convert.ToInt32(cells[0].Substring(8, 2)),
                                        Convert.ToInt32(cells[1].Substring(0, 2)),
                                        Convert.ToInt32(cells[1].Substring(3, 2)),
                                        hasSeconds ? Convert.ToInt32(cells[1].Substring(6, 2)) : 0);
                            }
                            else
                            {
                                time = DateTime.Parse(cells[0] + " " + cells[1]);
                            }

                            // FUTURE: option to get the previous bar before the startdate.  getPreviousBar
                            if (startDate.HasValue && time < startDate.Value) continue;

#if true
                            if (endDate.HasValue && time > endDate.Value)
                            {
                                this.Add(openTimeBuffer, openBuffer, highBuffer, lowBuffer, closeBuffer, volumeBuffer, bufferIndex);
                                break;
                            }

                            openTimeBuffer[bufferIndex] = time;
                            openBuffer[bufferIndex] = Convert.ToDouble(cells[2]);
                            highBuffer[bufferIndex] = Convert.ToDouble(cells[3]);
                            lowBuffer[bufferIndex] = Convert.ToDouble(cells[4]);
                            closeBuffer[bufferIndex] = Convert.ToDouble(cells[5]);
                            volumeBuffer[bufferIndex] = Convert.ToDouble(cells[6]);
                            if (++bufferIndex == bufferSize)
                            {
                                bufferIndex = 0;
                                this.Add(openTimeBuffer, openBuffer, highBuffer, lowBuffer, closeBuffer, volumeBuffer);
                            }
#else
                        if (endDate.HasValue && time > endDate.Value) break;

                        var Open = Convert.ToDouble(cells[2]);
                        var High = Convert.ToDouble(cells[3]);
                        var Low = Convert.ToDouble(cells[4]);
                        var Close = Convert.ToDouble(cells[5]);
                        var Volume = Convert.ToDouble(cells[6]);
                        this.Add(Time, Open, High, Low, Close, Volume);
#endif
                        }
                    }
                }

                var elapsed = Math.Max(1, sw.ElapsedMilliseconds);

                Console.WriteLine($"\b\b\b\b\b ...done. ({lines} lines in {elapsed / 1000}s, {lines * 1000 / elapsed } lines/sec)");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public static MarketSeries ImportFromFile(string symbolCode, TimeFrame timeFrame, string path, DateTime? startDate = null, DateTime? endDate = null)
        {
            var series = new MarketSeries(null, symbolCode, timeFrame);
            series.ImportFromFile(path, startDate, endDate);
            GC.Collect();

            if (series != null && series.OpenTime.Count > 0)
            {
                Console.WriteLine($"Imported {timeFrame} {symbolCode} ({series.OpenTime.Count} data points from {series.OpenTime[0]} to {series.OpenTime.LastValue})");
            }
            else
            {
                Console.WriteLine($"Could not import {timeFrame} {symbolCode}");
            }
            return series;
        }

        #endregion

        #region Misc

        public override string DataPointName { get { return "bars"; } }

        #endregion
    }

}


text:
#include "syshdrs.h"
#ifdef PRAGMA_HDRSTOP
#	pragma hdrstop
#endif

#define _CRT_SECURE_NO_WARNINGS 1

#ifndef O_BINARY
	/* Needed for platforms using different EOLN sequence (i.e. DOS) */
#	ifdef _O_BINARY
#		define O_BINARY _O_BINARY
#	else
#		define O_BINARY 0
#	endif
#endif

static int
FTPASCIILocalFileSeek(const int fd, const longest_int howMuchToSkip, char *const inbuf, const size_t bufsize)
{
	int c;
	longest_int count = howMuchToSkip;
	longest_int startpos, endpos, backskip;
	const char *src = NULL, *srclim = NULL;
	read_return_t nread;

	if (count == 0)
		return (0);
	if (count < 0)
		return (-1);
	startpos = (longest_int) Lseek(fd, 0, SEEK_CUR);
	if (startpos == (longest_int) -1)
		return (-1);

	while (count > 0) {
		nread = read(fd, inbuf, (read_size_t) bufsize);
		if (nread <= 0) {
			count = -1;
			break;
		}
		for (src = inbuf, srclim = inbuf + nread; src < srclim; ) {
			c = (int) *src++;
			if (c == '\r') {
				/* Oh dear... what's this doing in here? */
				count = -1;
			} else if (c == '\n') {
				count -= 2;
				/* If count is now < 0, then the file
				 * was corrupt and cannot be resumed.
				 */
			} else {
				--count;
			}
			if (count <= 0)
				break;
		}
	}
	if (count < 0) {
		endpos = (longest_int) Lseek(fd, startpos, SEEK_SET);
		if (endpos != startpos)
			return (-2);
		return (-1);
	}

	if (src != NULL) {
		backskip = (longest_int) -(srclim - src);
		if (backskip != 0) {
			endpos = (longest_int) Lseek(fd, backskip,  SEEK_CUR);
			if (endpos == (longest_int) -1)
				return (-2);
		}
	}

	return (0);
}	/* FTPASCIILocalFileSeek */

static int
FTPPutBlock(
	const FTPCIPtr cip,
	const char *cp,
	write_size_t ntowrite
)
{
	write_return_t nwrote;
	int result = kNoErr;

	do {
		if (! WaitForRemoteOutput(cip)) {	/* could set cancelXfer */
			cip->errNo = result = kErrDataTimedOut;
			FTPLogError(cip, kDontPerror, "Remote write timed out after " PRINTF_LONG_LONG " bytes had been sent.\n", cip->bytesTransferred);
			return (result);
		}
		if (cip->cancelXfer > 0) {
			FTPAbortDataTransfer(cip);
			result = cip->errNo = kErrDataTransferAborted;
			return (result);
		}

		nwrote = (write_return_t) SWrite(cip->dataSocket, cp, (size_t) ntowrite, (int) cip->xferTimeout, kNoFirstSelect);
		if (nwrote < 0) {
			if (nwrote == kTimeoutErr) {
				cip->errNo = result = kErrDataTimedOut;
				FTPLogError(cip, kDontPerror, "Remote write timed out after " PRINTF_LONG_LONG " bytes had been sent.\n", cip->bytesTransferred);
			} else if (errno == EPIPE) {
				cip->errNo = result = kErrSocketWriteFailed;
				errno = EPIPE;
				FTPLogError(cip, kDoPerror, "Lost data connection to remote host after " PRINTF_LONG_LONG " bytes had been sent.\n", cip->bytesTransferred);
			} else if (errno == EINTR) {
				continue;
			} else {
				cip->errNo = result = kErrSocketWriteFailed;
				FTPLogError(cip, kDoPerror, "Remote write failed after " PRINTF_LONG_LONG " bytes had been sent.\n", cip->bytesTransferred);
			}
			(void) shutdown(cip->dataSocket, 2);
			return (result);
		}
		cp += nwrote;
		ntowrite -= (write_size_t) nwrote;
	} while (ntowrite != 0);
	FTPUpdateIOTimer(cip);

	return (result);
}	/* FTPPutBlock */

int
FTPPutOneF(
	const FTPCIPtr cip,
	const char *const file,
	const char *volatile dstfile,
	int xtype,
	const int fdtouse,
	const int appendflag,
	const char *volatile tmppfx,
	const char *volatile tmpsfx,
	const int resumeflag,
	const int deleteflag,
	const FTPConfirmResumeUploadProc resumeProc)
{
	char *buf, *cp;
	const char *cmd;
	const char *odstfile;
	const char *tdstfile;
	size_t bufSize;
	size_t l;
	int tmpResult, result, pbrc;
	read_return_t nread;
	volatile int fd;
	char dstfile2[512];
	char *src, *srclim, *dst;
	write_size_t ntowrite;
	char inbuf[256], crlf[4];
	int lastch_of_prev_block, lastch_of_cur_block;
	int fstatrc, statrc;
	longest_int startPoint = 0;
	longest_int localsize;
	struct Stat st;
	time_t mdtm;
	volatile int vzaction;
	int zaction = kConfirmResumeProcSaidBestGuess;
	int sameAsRemote;
	int skiprc;
	size_t skipbufsize;
	longstring cmdStr;

	if (cip->buf == NULL) {
		FTPLogError(cip, kDoPerror, "Transfer buffer not allocated.\n");
		cip->errNo = kErrNoBuf;
		return (cip->errNo);
	}

	cip->usingTAR = 0;
	if (fdtouse < 0) {
		fd = Open(file, O_RDONLY|O_BINARY, 0);
		if (fd < 0) {
			FTPLogError(cip, kDoPerror, "Cannot open local file %s for reading.\n", file);
			cip->errNo = kErrOpenFailed;
			return (cip->errNo);
		}
	} else {
		fd = fdtouse;
	}

	fstatrc = Fstat(fd, &st);
	if ((fstatrc == 0) && (S_ISDIR(st.st_mode))) {
		if (fdtouse < 0) {
			(void) close(fd);
		}
		FTPLogError(cip, kDontPerror, "%s is a directory.\n", (file != NULL) ? file : "that");
		cip->errNo = kErrOpenFailed;
		return (cip->errNo);
	}

	localsize = (longest_int) st.st_size;
	if ((xtype == kTypeAscii) && (file != NULL) && (file[0] != '\0')) {
		localsize = FTPLocalASCIIFileSize(file, cip->buf, cip->bufSize);
	}

	/* For Put, we can't recover very well if it turns out restart
	 * didn't work, so check beforehand.
	 */
	if ((resumeflag == kResumeYes) || (resumeProc != kNoFTPConfirmResumeUploadProc)) {
		FTPCheckForRestartModeAvailability(cip);
	}

	odstfile = dstfile;
	if (((tmppfx != NULL) && (tmppfx[0] != '\0')) || ((tmpsfx != NULL) && (tmpsfx[0] != '\0'))) {
		cp = strrchr(dstfile, '/');
		if (cp == NULL)
			cp = strrchr(dstfile, '\\');
		if (cp == NULL) {
			(void) STRNCPY(dstfile2, ((tmppfx == NULL) ? "" : tmppfx));
			(void) STRNCAT(dstfile2, dstfile);
			(void) STRNCAT(dstfile2, ((tmpsfx == NULL) ? "" : tmpsfx));
		} else {
			cp++;
			l = (size_t) (cp - dstfile);
			(void) STRNCPY(dstfile2, dstfile);
			dstfile2[l] = '\0';	/* Nuke stuff after / */
			(void) STRNCAT(dstfile2, ((tmppfx == NULL) ? "" : tmppfx));
			(void) STRNCAT(dstfile2, cp);
			(void) STRNCAT(dstfile2, ((tmpsfx == NULL) ? "" : tmpsfx));
		}
		dstfile = dstfile2;
	}

	if (fdtouse < 0) {
		AutomaticallyUseASCIIModeDependingOnExtension(cip, dstfile, &xtype);
		mdtm = kModTimeUnknown;
		if ((cip->progress != (FTPProgressMeterProc) 0) || (resumeflag == kResumeYes) || (resumeProc != kNoFTPConfirmResumeUploadProc)) {
			(void) FTPFileSizeAndModificationTime(cip, dstfile, &startPoint, xtype, &mdtm);
		}

		if (appendflag == kAppendYes) {
			zaction = kConfirmResumeProcSaidAppend;
		} else if (
		/*		(cip->hasREST == kCommandNotAvailable) || We can now try to use APPE when REST is not availble. */
		/*		(xtype != kTypeBinary) || We can now resume in ASCII too. */
				(fstatrc < 0)
		) {
			zaction = kConfirmResumeProcSaidOverwrite;
		} else if (resumeflag == kResumeYes) {
			zaction = kConfirmResumeProcSaidBestGuess;
		} else {
			zaction = kConfirmResumeProcSaidOverwrite;
		}

		statrc = -1;
		if ((mdtm != kModTimeUnknown) || (startPoint != kSizeUnknown)) {
			/* Then we know the file exists.  We will
			 * ask the user what to do, if possible, below.
			 */
			statrc = 0;
		} else if ((resumeProc != kNoFTPConfirmResumeUploadProc) && (cip->hasMDTM != kCommandAvailable) && (cip->hasSIZE != kCommandAvailable)) {
			/* We already checked if the file had a filesize
			 * or timestamp above, but if the server indicated
			 * it did not support querying those directly,
			 * we now need to try to determine if the file
			 * exists in a few other ways.
			 */
			statrc = FTPFileExists2(cip, dstfile, 0, 0, 0, 1, 1);
		}

		sameAsRemote = 0;
		if (
			(resumeProc != kNoFTPConfirmResumeUploadProc) &&
			(statrc == 0)
		) {
			tdstfile = dstfile;
			zaction = (*resumeProc)(cip, file, (longest_int) st.st_size, st.st_mtime, &tdstfile, startPoint, mdtm, &startPoint);
			dstfile = tdstfile;
		}

		if (zaction == kConfirmResumeProcSaidCancel) {
			/* User wants to cancel this file and any
			 * remaining in batch.
			 */
			cip->errNo = kErrUserCanceled;
			return (cip->errNo);
		}

		if (zaction == kConfirmResumeProcSaidBestGuess) {
			if ((mdtm != kModTimeUnknown) && (st.st_mtime > (mdtm + 1))) {
				/* Local file is newer than remote,
				 * overwrite the remote file instead
				 * of trying to resume it.
				 *
				 * Note:  Add one second fudge factor
				 * for Windows' file timestamps being
				 * imprecise to one second.
				 */
				zaction = kConfirmResumeProcSaidOverwrite;
			} else if (localsize == startPoint) {
				/* Already sent file, done. */
				zaction = kConfirmResumeProcSaidSkip;
				sameAsRemote = 1;
			} else if ((startPoint != kSizeUnknown) && (localsize > startPoint)) {
				zaction = kConfirmResumeProcSaidResume;
			} else {
				zaction = kConfirmResumeProcSaidOverwrite;
			}
		}

		if (zaction == kConfirmResumeProcSaidSkip) {
			/* Nothing done, but not an error. */
			if (fdtouse < 0) {
				(void) close(fd);
			}
			if (deleteflag == kDeleteYes) {
				if (unlink(file) < 0) {
					cip->errNo = kErrLocalDeleteFailed;
					return (cip->errNo);
				}
			}
			if (sameAsRemote != 0) {
				cip->errNo = kErrRemoteSameAsLocal;
				return (cip->errNo);
			}
			return (kNoErr);
		} else if (zaction == kConfirmResumeProcSaidResume) {
			/* Resume; proc set the startPoint. */
			if (localsize == startPoint) {
				/* Already sent file, done. */
				if (fdtouse < 0) {
					(void) close(fd);
				}

				if (deleteflag == kDeleteYes) {
					if (unlink(file) < 0) {
						cip->errNo = kErrLocalDeleteFailed;
						return (cip->errNo);
					}
				}
				return (kNoErr);
			} else if (xtype == kTypeAscii) {
				skipbufsize = cip->bufSize;
				if ((fdtouse >= 0) && (skipbufsize > 4096))
					skipbufsize = 4096;

				skiprc = FTPASCIILocalFileSeek(fd, startPoint, cip->buf, skipbufsize);
				if (skiprc == -2) {
					cip->errNo = kErrAsciiSeekErr;
					return (cip->errNo);
				} else if (skiprc == -1) {
					/* Overwrite */
					cip->startPoint = startPoint = 0;
				} else {
					/* It worked */
					/* We could do: cip->startPoint = startPoint;
					 * and let it do a REST with STOR,
					 * but it is safer to use APPE only.
					 */
					zaction = kConfirmResumeProcSaidAppend;
					cip->startPoint = startPoint = 0;
				}
			} else if (Lseek(fd, startPoint, SEEK_SET) != -1) {
				cip->startPoint = startPoint;
			}
		} else if (zaction == kConfirmResumeProcSaidAppend) {
			/* append: leave startPoint at zero, we will append everything. */
			cip->startPoint = startPoint = 0;
		} else /* if (zaction == kConfirmResumeProcSaidOverwrite) */ {
			/* overwrite: leave startPoint at zero */
			cip->startPoint = startPoint = 0;
		}
	} else if (appendflag == kAppendYes) {
		zaction = kConfirmResumeProcSaidAppend;
	}

	FTPSetUploadSocketBufferSize(cip);

	vzaction = zaction;
	if (vzaction == kConfirmResumeProcSaidAppend) {
		cmd = "APPE ";
		tmppfx = "";	/* Can't use that here. */
		tmpsfx = "";
	} else {
		cmd = "STOR ";
		if (tmppfx == NULL)
			tmppfx = "";
		if (tmpsfx == NULL)
			tmpsfx = "";
	}

	memcpy(cmdStr, cmd, 4 + 1 /* space */ + 1 /* nul byte */);
	STRNCAT(cmdStr, dstfile);

	tmpResult = FTPStartDataCmd2(
		cip,
		kNetWriting,
		xtype,
		startPoint,
		cmdStr,
		sizeof(cmdStr),
		"(not used)"
	);

	if (tmpResult < 0) {
		cip->errNo = tmpResult;
		if (fdtouse < 0) {
			(void) close(fd);
		}
		return (cip->errNo);
	}

	if ((startPoint != 0) && (cip->startPoint == 0)) {
		/* Remote could not or would not set the start offset
		 * to what we wanted.
		 *
		 * So now we have to undo our seek.
		 */
		if (Lseek(fd, 0, SEEK_SET) != 0) {
			cip->errNo = kErrLseekFailed;
			if (fdtouse < 0) {
				(void) close(fd);
			}
			return (cip->errNo);
		}
		startPoint = 0;
	}

	result = kNoErr;
	buf = cip->buf;
	bufSize = cip->bufSize;

	FTPInitIOTimer(cip);
	if ((fstatrc == 0) && (S_ISREG(st.st_mode) != 0)) {
		cip->expectedSize = st.st_size;
		cip->mdtm = st.st_mtime;
	}
	cip->lname = file;	/* could be NULL */
	cip->rname = odstfile;
	if (fdtouse >= 0)
		cip->useProgressMeter = 0;
	FTPStartIOTimer(cip);

	/* Note: On Windows, we don't have to do anything special
	 * for ASCII mode, since Net ASCII's end-of-line sequence
	 * corresponds to the same thing used for DOS/Windows.
	 */

	if (xtype == kTypeAscii) {
		/* ascii */

		if (cip->asciiTranslationMode == kAsciiTranslationModeNone) {
			/* Warning: this is really just for testing FTP server software.
			 * Do not use this mode for your FTP client program!
			 */
			for (;;) {
				nread = read(fd, inbuf, (read_size_t) sizeof(inbuf));
				if (nread < 0) {
					if (errno == EINTR) {
						continue;
					} else {
						result = kErrReadFailed;
						cip->errNo = kErrReadFailed;
						FTPLogError(cip, kDoPerror, "Local read failed.\n");
					}
					break;
				} else if (nread == 0) {
					break;
				}
				cip->bytesTransferred += (longest_int) nread;

				ntowrite = (write_size_t) nread;
				cp = inbuf;

				if ((pbrc = FTPPutBlock(cip, cp, ntowrite)) < 0) {
					result = pbrc;
					goto brk;
				}
			}
		} else if ((cip->asciiTranslationMode == kAsciiTranslationModeStripCRs) || (cip->asciiTranslationMode == kAsciiTranslationModeFixEOLNs)) {
			/* TO-DO: Really add the fix mode, kAsciiTranslationModeFixEOLNs. */
			lastch_of_prev_block = 0;
			for (;;) {
				nread = read(fd, inbuf, (read_size_t) sizeof(inbuf));
				if (nread < 0) {
					if (errno == EINTR) {
						continue;
					} else {
						result = kErrReadFailed;
						cip->errNo = kErrReadFailed;
						FTPLogError(cip, kDoPerror, "Local read failed.\n");
					}
					break;
				} else if (nread == 0) {
					break;
				}
				cip->bytesTransferred += (longest_int) nread;

				src = inbuf;
				srclim = src + nread;
				lastch_of_cur_block = srclim[-1];
				if (lastch_of_cur_block == '\r') {
					srclim[-1] = '\0';
					srclim--;
					nread--;
					if (nread == 0) {
						lastch_of_prev_block = lastch_of_cur_block;
						break;
					}
				}
				dst = cip->buf;		/* must be 2x sizeof inbuf or more. */

				if (*src == '\n') {
					src++;
					*dst++ = '\r';
					*dst++ = '\n';
				} else if (lastch_of_prev_block == '\r') {
					/* Raw CR at end of last block,
					 * no LF at the start of this block.
					 */
					*dst++ = '\r';
					*dst++ = '\n';
				}

				/* Prepare the buffer, converting end-of-lines
				 * to CR+LF format as required by protocol.
				 */
				while (src < srclim) {
					if (*src == '\r') {
						if (src[1] == '\n') {
							/* CR+LF pair */
							*dst++ = *src++;
							*dst++ = *src++;
						} else {
							/* raw CR */
							*dst++ = *src++;
							*dst++ = '\n';
						}
					} else if (*src == '\n') {
						/* LF only; expected for UNIX text. */
						*dst++ = '\r';
						*dst++ = *src++;
					} else {
						*dst++ = *src++;
					}
				}
				lastch_of_prev_block = lastch_of_cur_block;

				ntowrite = (write_size_t) (dst - cip->buf);
				cp = cip->buf;

				if ((pbrc = FTPPutBlock(cip, cp, ntowrite)) < 0) {
					result = pbrc;
					goto brk;
				}
			}

			if (lastch_of_prev_block == '\r') {
				/* Very rare, but if the file's last byte is a raw CR
				 * we need to write out one more line since we
				 * skipped it earlier.
				 */
				crlf[0] = '\r';
				crlf[1] = '\n';
				crlf[2] = '\0';
				cp = crlf;
				ntowrite = 2;

				if ((pbrc = FTPPutBlock(cip, cp, ntowrite)) < 0) {
					result = pbrc;
					goto brk;
				}
			}
		}
	} else {
		/* binary */
		for (;;) {
			cp = buf;
			nread = read(fd, cp, (read_size_t) bufSize);
			if (nread < 0) {
				if (errno == EINTR) {
					continue;
				} else {
					result = kErrReadFailed;
					cip->errNo = kErrReadFailed;
					FTPLogError(cip, kDoPerror, "Local read failed.\n");
				}
				break;
			} else if (nread == 0) {
				break;
			}
			cip->bytesTransferred += (longest_int) nread;

			ntowrite = (write_size_t) nread;
			if ((pbrc = FTPPutBlock(cip, cp, ntowrite)) < 0) {
				result = pbrc;
				goto brk;
			}
		}
	}
brk:

	/* This looks very bizarre, since
	 * we will be checking the socket
	 * for readability here!
	 *
	 * The reason for this is that we
	 * want to be able to timeout a
	 * small put.  So, we close the
	 * write end of the socket first,
	 * which tells the server we're
	 * done writing.  We then wait
	 * for the server to close down
	 * the whole socket (we know this
	 * when the socket is ready for
	 * reading an EOF), which tells
	 * us that the file was completed.
	 */
	(void) shutdown(cip->dataSocket, 1);
	(void) WaitForRemoteInput(cip);

	tmpResult = FTPEndDataCmd(cip, 1);
	if ((tmpResult < 0) && (result == kNoErr)) {
		cip->errNo = result = kErrSTORFailed;
	}
	FTPStopIOTimer(cip);

	if (fdtouse < 0) {
		/* If they gave us a descriptor (fdtouse >= 0),
		 * leave it open, otherwise we opened it, so
		 * we need to dispose of it.
		 */
		(void) Fstat(fd, &st);
		(void) close(fd);
		fd = -1;
	}

	if (result == kNoErr) {
		/* The store succeeded;  If we were
		 * uploading to a temporary file,
		 * move the new file to the new name.
		 */
		cip->numUploads++;

		if ((tmppfx[0] != '\0') || (tmpsfx[0] != '\0')) {
			if ((result = FTPRename(cip, dstfile, odstfile)) < 0) {
				/* May fail if file was already there,
				 * so delete the old one so we can move
				 * over it.
				 */
				if (FTPDelete(cip, odstfile, kRecursiveNo, kGlobNo) == kNoErr) {
					result = FTPRename(cip, dstfile, odstfile);
					if (result < 0) {
						FTPLogError(cip, kDontPerror, "Could not rename %s to %s: %s.\n", dstfile, odstfile, FTPStrError(cip->errNo));
					}
				} else {
					FTPLogError(cip, kDontPerror, "Could not delete old %s, so could not rename %s to that: %s\n", odstfile, dstfile, FTPStrError(cip->errNo));
				}
			}
		}

		if (FTPUtime(cip, odstfile, st.st_atime, st.st_mtime, st.st_ctime) != kNoErr) {
			if (cip->errNo != kErrUTIMENotAvailable)
				FTPLogError(cip, kDontPerror, "Could not preserve times for %s: %s.\n", odstfile, FTPStrError(cip->errNo));
		}

		if ((result == kNoErr) && (deleteflag == kDeleteYes)) {
			if (unlink(file) < 0) {
				result = cip->errNo = kErrLocalDeleteFailed;
			}
		}
	}

	return (result);
}	/* FTPPutOneF */

redpajama_set_name: RedPajamaGithub


text:
@implementation BXPGKeypathExpressionValueType
- (NSString *) expressionSQL: (id <BXPGExpressionHandler>) visitor
{
	return [visitor handlePGKeyPathExpressionValue: mValue];
}
@end


text:
require "test_helper"
require "models/name/as_typeahead/name_parent/name_parent_test_helper"

# Single Name typeahead test.
class NameParentSubformaIsOfferedForUnrankedTest < ActiveSupport::TestCase
  test "name parent suggestion for unranked include subforma" do
    typeahead = Name::AsTypeahead::ForParent.new(
      term: "a_subforma",
      avoid_id: 1,
      rank_id: NameRank.find_by(name: "[unranked]").id
    )
    expected_ranks = %w(Subforma)
    suggestions_should_only_include(
      typeahead.suggestions, "[unranked]", expected_ranks
    )
  end
end


text:
package co.cask.cdap.internal.app;

import org.apache.twill.api.EventHandlerSpecification;
import org.apache.twill.api.RuntimeSpecification;
import org.apache.twill.api.TwillSpecification;

import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * Forwarding TwillSpecification implementation.
 */
public abstract class ForwardingTwillSpecification implements TwillSpecification {

  private final TwillSpecification delegate;

  protected ForwardingTwillSpecification(TwillSpecification specification) {
    this.delegate = specification;
  }

  @Override
  public String getName() {
    return delegate.getName();
  }

  @Override
  public Map<String, RuntimeSpecification> getRunnables() {
    return delegate.getRunnables();
  }

  @Override
  public List<Order> getOrders() {
    return delegate.getOrders();
  }

  @Override
  public List<PlacementPolicy> getPlacementPolicies() {
    return delegate.getPlacementPolicies();
  }

  @Nullable
  @Override
  public EventHandlerSpecification getEventHandler() {
    return delegate.getEventHandler();
  }
}


text:
Dashboard

	<form class="navbar-form" role="search" action="<?php echo base_url('admin/company');?>" method = "get">

					<input type="text"  class="form-control" placeholder="Search" name="q" value="<?php echo $_GET['q'];?>" size="13px; ">

						<button class="btn btn-default " type="submit" value = "Search"></button>

			</form>

			 <?php if($this->session->flashdata('error')) { ?>

		×
		<?php echo $this->session->flashdata('error') ;?>

	<?php }
	if($this->session->flashdata('success')) { ?>

		<button class="close" data-dismiss="alert">×</button>
		<?php echo $this->session->flashdata('success') ;?>

	<?php }
	if($this->session->flashdata('info')) { ?>

		×
		<?php echo $this->session->flashdata('info') ;?>

	<?php } ?>

			<form class="navbar-form"  action="<?php echo base_url('admin/company');?>" method="GET">
				<input type='hidden' name='q' value='<?php echo $_GET['q'];?>'/>
				<select  class="form-control"  name="select_val" id="select_val" onchange="this.form.submit()">
					<option value=''>Filter By Status</option>

					<option value="1">Active</option>
					<option value='2'>Disabled</option>

				</select>

			</form>

Company ManagementCompany List

				Sr.
				Name
				Email
				Address
				Pin
				Contact
				Username
				Status
				Action

			 <?php

				if(!empty($company)){
					$s_no =1;
					if($start)
					{
					$s_no =$start+$s_no;

					}
					foreach($company as $comp)
					{

						$strtotime = $comp->createtime;
						$date = date('d M Y',$strtotime);
						echo '
';
						echo " {$s_no}	";
						echo " {$comp->name}	";
						echo " {$comp->email}	";
						echo " {$comp->address}	";
						echo " {$comp->pin}	";
						echo " {$comp->contact}	";
						echo " {$comp->username}	";
						echo " {$comp->printStatus()}	";

						?>
						<a class='btn btn-primary btn-mini' href='<?php echo  base_url("admin/company/edit/{$comp->id}");?>'> Edit
						<button onclick='page_delete("<?php echo $comp->email;?>")' class='btn btn-primary btn-mini'> Delete</button>

					<?php
						$s_no++;
					}
				}else{
					echo '
';
					echo " No record found	";
					echo "
";
				}

			 ?>

	<?php echo $this->pagination->create_links();?>


text:
'use strict';

describe('Usercomments E2E Tests:', function () {
  describe('Test Usercomments page', function () {
    it('Should report missing credentials', function () {
      browser.get('http://localhost:3001/usercomments');
      expect(element.all(by.repeater('usercomment in usercomments')).count()).toEqual(0);
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->
<ruleset name="Magento">
    <description>Magento coding standard.</description>
    <rule ref="Zend.Files.ClosingTag"/>
    <rule ref="Generic.WhiteSpace.DisallowTabIndent"/>
    <rule ref="Generic.WhiteSpace.ScopeIndent"/>
    <rule ref="Generic.Files.LineLength">
        <properties>
            <property name="lineLimit" value="120"/>
            <property name="absoluteLineLimit" value="120"/>
        </properties>
    </rule>
    <rule ref="Generic.Files.LineEndings"/>
    <rule ref="PEAR.NamingConventions.ValidClassName"/>
    <rule ref="Squiz.Functions.GlobalFunction"/>
    <rule ref="Zend.NamingConventions.ValidVariableName">
        <!-- Excluding as it conflicts with the PSR2 standard which over rides this one -->
        <exclude name="Zend.NamingConventions.ValidVariableName.PrivateNoUnderscore"/>
    </rule>
    <rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
    <rule ref="Generic.PHP.DisallowShortOpenTag"/>
    <rule ref="PEAR.Classes.ClassDeclaration"/>
    <rule ref="PEAR.Functions.FunctionDeclaration"/>
    <rule ref="Squiz.Scope.MethodScope"/>
    <rule ref="Generic.Functions.CallTimePassByReference"/>
    <rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
    <rule ref="PEAR.WhiteSpace.ScopeClosingBrace"/>
    <rule ref="Generic.ControlStructures.InlineControlStructure"/>
    <rule ref="PEAR.ControlStructures.ControlSignature"/>
    <rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/>
    <rule ref="Squiz.Commenting.DocCommentAlignment"/>
    <rule ref="Generic.PHP.DeprecatedFunctions"/>
    <rule ref="../../../../../../framework/Magento"/>
</ruleset>


text:
using CharacterGen.Races;
using NUnit.Framework;

namespace CharacterGen.Tests.Unit.Generators.Races
{
    [TestFixture]
    public class RaceTests
    {
        private Race race;

        [SetUp]
        public void Setup()
        {
            race = new Race();
        }

        [Test]
        public void RaceInitialized()
        {
            Assert.That(race.BaseRace, Is.Empty);
            Assert.That(race.Metarace, Is.Empty);
            Assert.That(race.IsMale, Is.False);
            Assert.That(race.HasWings, Is.False);
            Assert.That(race.Size, Is.Empty);
            Assert.That(race.MetaraceSpecies, Is.Empty);
            Assert.That(race.Age, Is.Not.Null);
            Assert.That(race.Age.Unit, Is.EqualTo("Years"));
            Assert.That(race.MaximumAge, Is.Not.Null);
            Assert.That(race.MaximumAge.Unit, Is.EqualTo("Years"));
            Assert.That(race.Height, Is.Not.Null);
            Assert.That(race.Height.Unit, Is.EqualTo("Inches"));
            Assert.That(race.Weight, Is.Not.Null);
            Assert.That(race.Weight.Unit, Is.EqualTo("Pounds"));
            Assert.That(race.LandSpeed, Is.Not.Null);
            Assert.That(race.LandSpeed.Unit, Is.EqualTo("feet per round"));
            Assert.That(race.AerialSpeed, Is.Not.Null);
            Assert.That(race.AerialSpeed.Unit, Is.EqualTo("feet per round"));
            Assert.That(race.ChallengeRating, Is.EqualTo(0));
            Assert.That(race.SwimSpeed, Is.Not.Null);
            Assert.That(race.SwimSpeed.Unit, Is.EqualTo("feet per round"));
        }

        [Test]
        public void GenderIsFemale()
        {
            race.IsMale = false;
            Assert.That(race.Gender, Is.EqualTo("Female"));
        }

        [Test]
        public void GenderIsMale()
        {
            race.IsMale = true;
            Assert.That(race.Gender, Is.EqualTo("Male"));
        }

        [Test]
        public void MaleSummary()
        {
            race.IsMale = true;
            race.BaseRace = "base race";

            Assert.That(race.Summary, Is.EqualTo("Male base race"));
        }

        [Test]
        public void FemaleSummary()
        {
            race.IsMale = false;
            race.BaseRace = "base race";

            Assert.That(race.Summary, Is.EqualTo("Female base race"));
        }

        [Test]
        public void MaleSummaryWithMetarace()
        {
            race.IsMale = true;
            race.BaseRace = "base race";
            race.Metarace = "metarace";

            Assert.That(race.Summary, Is.EqualTo("Male metarace base race"));
        }

        [Test]
        public void FemaleSummaryWithMetarace()
        {
            race.IsMale = false;
            race.BaseRace = "base race";
            race.Metarace = "metarace";

            Assert.That(race.Summary, Is.EqualTo("Female metarace base race"));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Imml.ComponentModel;

namespace Imml
{
    public class ElementNotFoundException : Exception
    {
        public IImmlContext Container { get; private set; }

        public ElementNotFoundException(string message, IImmlContext container)
            : base(message)
        {
            this.Container = container;
        }
    }
}


text:
static const BOOL kLoggingSwitchOn = YES;

#define IH_LOG_FILE_NAME       @"iHLogs"
#define IH_LOG_FILE_EXT        @"html"

#endif


text:
#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequest.h>
#else
#import "AmazonServiceRequest.h"
#endif

#import "SESRequest.h"
#import "SESSendEmailRequest.h"
#import "SESDestination.h"
#import "SESContent.h"
#import "SESContent.h"
#import "SESContent.h"
#import "SESBody.h"
#import "SESContent.h"
#import "SESContent.h"
#import "SESMessage.h"
#import "SESContent.h"
#import "SESContent.h"
#import "SESContent.h"
#import "SESBody.h"
#import "SESContent.h"
#import "SESContent.h"

/**
 * Send Email Request Marshaller
 */
@interface SESSendEmailRequestMarshaller:NSObject {
}

+(AmazonServiceRequest *)createRequest:(SESSendEmailRequest *)sendEmailRequest;

@end


text:
'use strict';
var file = require('file');
var path = require('path');
var generators = require('yeoman-generator');
var camelcase = require('lodash.camelcase');
var kebabCase = require('lodash.kebabCase');
var gitConfig = require('git-config');

module.exports = generators.Base.extend({
  prompting() {
    if(!this.options.child) {
      this.log(yosay(
        'Welcome to the ' + chalk.cyan('RoviSys') + ' ' + chalk.red('JS Library') + ' generator!'
      ));
    }

    var config = gitConfig.sync();
    config.user = config.user || {};
    var prompts = [{
      type: 'input',
      name: 'variable',
      message: 'What is the name of this project\'s default export?',
      default: camelcase(this.appname)
    }];

    return new Promise(resolve => {
      this.prompt(prompts, (props) => {
        Object.assign(props, this.options);
        this.user = props.user;
        this.repo = props.repo;
        this.description = props.description;
        this.author = props.author;
        this.variable = props.variable;
        this.variable_kb = kebabCase(props.variable);
        resolve();
      });
    });
  },

  writing: {
    lib() {
      this.log('lib repo: ' + this.repo);

      var src = this.sourceRoot();
      file.walkSync(src, (dirPath, dirs, files) => {
        var relativeDir = path.relative(src, dirPath);
        files.forEach(filename => {
          var dest = filename;
          if(filename.indexOf('MyComponent') === 0) {
            dest = filename.replace('MyComponent', this.variable);
          }
          var kc = kebabCase('MyComponent');
          if(filename.indexOf(kc) === 0) {
            dest = filename.replace(kc, this.variable_kb);
          }
          this.template(path.join(relativeDir, filename), path.join(relativeDir, dest));
        });
      });
    }
  },

  install() {
    if(!this.options.child) {
      this.installDependencies({
        bower: false,
        npm: true,
        skipInstall: this.options['skip-install']
      });
    }
  }
});


text:
      Drag and drop a trace file into this area, or click to choose from disk.

    <input id="file" type="file" name="file" />


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.industrieit.ohr.coherence;

import com.industrieit.ohr.Reifier;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;

/**
 *
 * @author rudi
 */
public class CoherTest {

    public static void main(String[] args) throws Exception
    {
        System.setProperty("tangosol.coherence.cacheconfig","/coherence/coherence.xml");
        System.out.println("a");
        int num=100;
        NamedCache cache = CacheFactory.getCache("rudtest");
        System.out.println("b");
        for (int x=0;x<num;x++)
        {
            System.out.println("adding to cache "+x);
            CoHR c=(CoHR) Reifier.reify(CoHR.class);
            c.setX(x);
            c.setY(2*x);
            cache.put(c, c);
        }
        System.out.println(cache.size());

        CoHR tester=(CoHR) Reifier.reify(CoHR.class);

        for (int x=0;x<num;x++)
        {

            tester.setX(x);

            CoHR c=(CoHR) cache.get(tester);
            System.out.println("res "+c.getX()+" "+c.getY());
            cache.put(c, c);
        }

        Reifier.freeOHR(tester);
    }

}


text:
namespace {

// Markup for the text of the Omnibox search label
const char kSearchLabelMarkup[] = "<big><b>%s</b></big>";

}  // namespace

// static
void FirstRunBubble::Show(Browser* browser,
                          GtkWidget* anchor,
                          const gfx::Rect& rect) {
  first_run::LogFirstRunMetric(first_run::FIRST_RUN_BUBBLE_SHOWN);

  new FirstRunBubble(browser, anchor, rect);
}

void FirstRunBubble::BubbleClosing(BubbleGtk* bubble, bool closed_by_escape) {
  // TODO(port): Enable parent window
}

FirstRunBubble::FirstRunBubble(Browser* browser,
                               GtkWidget* anchor,
                               const gfx::Rect& rect)
    : browser_(browser),
      bubble_(NULL) {
  GtkThemeService* theme_service = GtkThemeService::GetFrom(browser->profile());
  GtkWidget* title = theme_service->BuildLabel("", ui::kGdkBlack);
  char* markup = g_markup_printf_escaped(kSearchLabelMarkup,
      l10n_util::GetStringFUTF8(IDS_FR_BUBBLE_TITLE,
          GetDefaultSearchEngineName(browser->profile())).c_str());
  gtk_label_set_markup(GTK_LABEL(title), markup);
  g_free(markup);

  GtkWidget* change = theme_service->BuildChromeLinkButton(
      l10n_util::GetStringUTF8(IDS_FR_BUBBLE_CHANGE));
  g_signal_connect(change, "clicked", G_CALLBACK(&HandleChangeLinkThunk), this);

  GtkWidget* subtext = theme_service->BuildLabel(
      l10n_util::GetStringUTF8(IDS_FR_BUBBLE_SUBTEXT), ui::kGdkBlack);

  GtkWidget* top_line = gtk_hbox_new(FALSE, ui::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(top_line), title, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(top_line), change, FALSE, FALSE, 0);

  GtkWidget* content = gtk_vbox_new(FALSE, ui::kControlSpacing);
  gtk_container_set_border_width(GTK_CONTAINER(content),
                                 ui::kContentAreaBorder);
  g_signal_connect(content, "destroy", G_CALLBACK(&HandleDestroyThunk), this);
  gtk_box_pack_start(GTK_BOX(content), top_line, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(content), subtext, FALSE, FALSE, 0);

  bubble_ = BubbleGtk::Show(anchor,
                            &rect,
                            content,
                            BubbleGtk::ANCHOR_TOP_LEFT,
                            BubbleGtk::MATCH_SYSTEM_THEME |
                                BubbleGtk::POPUP_WINDOW |
                                BubbleGtk::GRAB_INPUT,
                            theme_service,
                            this);
  DCHECK(bubble_);
}

FirstRunBubble::~FirstRunBubble() {
}

void FirstRunBubble::HandleDestroy(GtkWidget* sender) {
  delete this;
}

void FirstRunBubble::HandleChangeLink(GtkWidget* sender) {
  first_run::LogFirstRunMetric(first_run::FIRST_RUN_BUBBLE_CHANGE_INVOKED);

  // Cache browser_ before closing the bubble, which deletes |this|.
  Browser* browser = browser_;
  bubble_->Close();
  if (browser)
    chrome::ShowSearchEngineSettings(browser);
}


text:
require 'test_helper'
# Test the Polei Class
class PoleiTest < Minitest::Test
  def test_it_returns_name
    polei = Poleica::Polei.new("#{Support.support_path}/files/example.mp3")
    assert_equal('example', polei.name)
  end

  def test_it_returns_path
    file_path = "#{Support.support_path}/files/example.mp3"
    polei     = Poleica::Polei.new(file_path)
    assert_equal(file_path, polei.path)
  end
end # class PoleiTest


text:
package com.example.office.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import com.example.office.logger.Logger;

/**
 * Helper class to work with dates for example formats date to string.
 */
public class DateTimeUtils {

    /**
     * Default time date format.
     */
    private static final String DEFAULT_TIME_DATE_FORMAT = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";

    /**
     * Private constructor to prevent creating an instance of the class.
     */
    private DateTimeUtils() {}

    /**
     * Formats date to the string with default time date format.
     *
     * @param time Date to format.
     *
     * @return Result string.
     */
    public static String formatDate(Date time) {
        SimpleDateFormat dateformat = new SimpleDateFormat(DEFAULT_TIME_DATE_FORMAT);
        return dateformat.format(time);
    }

    public static Date parseDate(String ts) {
        SimpleDateFormat dateformat = new SimpleDateFormat(DEFAULT_TIME_DATE_FORMAT);
        try {
            return dateformat.parse(ts);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * Retrieves UTC time as string.
     *
     * @param date Date to parse.
     *
     * @return UTC time as string for given time.
     */
    public static String getUtcTimeStringFromDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH':'mm':'ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
        return dateFormat.format(date);

    }

    /**
     * Formats date to the string with specific time date format.
     *
     * @param date Date to format.
     * @param format Format of result string.
     *
     * @return Formatted date string.
     */
    public static String formatDate(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * Saves date in originalDate, but applies time from appliedDate.
     *
     * @param originalDate Date where time will be changed.
     * @param appliedDate Date which will be used to get time and copy it.
     *
     * @return Date with date from original date and new time.
     */
    @SuppressWarnings("deprecation")
    public static Date copyTime(Date originalDate, Date appliedDate) {
        Date date = new Date(originalDate.getTime());
        date.setHours(appliedDate.getHours());
        date.setMinutes(appliedDate.getMinutes());
        date.setSeconds(appliedDate.getSeconds());
        return date;
    }

    /**
     * Returns {@link SimpleDateFormat} instance that formats date in default application format (time only for recent dates, day and month
     * for messages earlier than year and month/day/year for older)
     *
     * @param date Date will be formatted
     * @return Formatter which will be format dates in default application format or null if something went wrong
     */
    public static SimpleDateFormat getDefaultFormatter(Date date) {
        try {
            Date now = new Date();
            if (now.before(date)) {
                // Message from future!
                // Specify locale explicitly, otherwise formatter will use system locale.
                // Can format month as "nov." instead of "Nov"
                return new SimpleDateFormat("MM/dd/yyyy h:mm:ss a", Locale.US);
            }

            // ignore leap years and leap seconds
            long ms = now.getTime() - date.getTime();
            long seconds = ms / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
            long days = hours / 24;
            long years = days / 365;
            days %= 365;
            hours %= 24;
            minutes %= 60;
            seconds %= 60;
            ms %= 1000;

            SimpleDateFormat formatter;
            if (years >= 1) {
                formatter = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
            } else if (days >= 1) {
                formatter = new SimpleDateFormat("MMM, d", Locale.US);
            } else {
                // TODO should we use 24 hour format?
                formatter = new SimpleDateFormat("h:mm:ss a", Locale.US);
            }

            formatter.setTimeZone(TimeZone.getDefault());
            return formatter;
        } catch (Exception e) {
            Logger.logApplicationException(e, DateTimeUtils.class.getSimpleName() + ".getFormatter(): Error.");
        }
        return null;
    }
}


text:
package distributions;

import utility.RNG;

/**
 *
 * @author James Elderfield
 */
public class BinomialDistribution implements DiscreteDistribution {
    public BinomialDistribution(double p, int k) {
        _p = p;
        _k = k;
    }

    public double p() {
        return _p;
    }

    public int k() {
        return _k;
    }

    @Override
    public int getVariate(RNG rng) {
        int successes = 0;

        for(int i = 0; i < _k; i++) {
            if(rng.bernoulliTrial(_p)) {
                successes++;
            }
        }

        return successes;
    }

    int _k;
    double _p;
}


text:
#ifndef __GTLS_H
#define __GTLS_H

#ifdef USE_GNUTLS

int Curl_gtls_init(void);
int Curl_gtls_cleanup(void);
CURLcode Curl_gtls_connect(struct connectdata *conn, int sockindex);

/* tell GnuTLS to close down all open information regarding connections (and
   thus session ID caching etc) */
void Curl_gtls_close_all(struct SessionHandle *data);

 /* close a SSL connection */
void Curl_gtls_close(struct connectdata *conn, int sockindex);

/* return number of sent (non-SSL) bytes */
ssize_t Curl_gtls_send(struct connectdata *conn, int sockindex,
                       const void *mem, size_t len);
ssize_t Curl_gtls_recv(struct connectdata *conn, /* connection data */
                       int num,                  /* socketindex */
                       char *buf,                /* store read data here */
                       size_t buffersize,        /* max amount to read */
                       bool *wouldblock);
void Curl_gtls_session_free(void *ptr);
size_t Curl_gtls_version(char *buffer, size_t size);
int Curl_gtls_shutdown(struct connectdata *conn, int sockindex);
int Curl_gtls_seed(struct SessionHandle *data);

/* API setup for GnuTLS */
#define curlssl_init Curl_gtls_init
#define curlssl_cleanup Curl_gtls_cleanup
#define curlssl_connect Curl_gtls_connect
#define curlssl_session_free(x)  Curl_gtls_session_free(x)
#define curlssl_close_all Curl_gtls_close_all
#define curlssl_close Curl_gtls_close
#define curlssl_shutdown(x,y) Curl_gtls_shutdown(x,y)
#define curlssl_set_engine(x,y) (x=x, y=y, CURLE_FAILED_INIT)
#define curlssl_set_engine_default(x) (x=x, CURLE_FAILED_INIT)
#define curlssl_engines_list(x) (x=x, (struct curl_slist *)NULL)
#define curlssl_send Curl_gtls_send
#define curlssl_recv Curl_gtls_recv
#define curlssl_version Curl_gtls_version
#define curlssl_check_cxn(x) (x=x, -1)
#define curlssl_data_pending(x,y) (x=x, y=y, 0)

#endif /* USE_GNUTLS */
#endif


text:
<!DOCTYPE html>

    <title>Blank Standard HTML5 Web App Template</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=no">

Hello, Intel XDK!


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>PyObjCTools.KeyValueCoding – Key-Value Coding API — PyObjC-Core 2.5.0b1 documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="PyObjC-Core 2.5.0b1 documentation" href="../index.html" />
    <link rel="up" title="PyObjCTools – Utilities" href="module-PyObjCTools.html" />
    <link rel="next" title="PyObjCTools.AppHelper – Work with AppKit" href="module-PyObjCTools.AppHelper.html" />
    <link rel="prev" title="PyObjCTools – Utilities" href="module-PyObjCTools.html" />

Navigation

          index

          modules |

          next |

          previous |

PyObjC-Core 2.5.0b1 documentation »

Python API »

<tt class="docutils literal docutils literal docutils literal docutils literal docutils literal">PyObjCTools</tt> – Utilities »

<tt class="xref py py-mod docutils literal">PyObjCTools.KeyValueCoding</tt> – Key-Value Coding API¶

Support for Key-Value Coding in Python. This provides a simple functional
interface to Cocoa’s Key-Value coding that also works for regular Python
objects.

Key-Value Coding is Cocoa functionality that is simular to
the <tt class="xref py py-func docutils literal">getattr()</tt> and <tt class="xref py py-func docutils literal">setattr()</tt> functions in Python. The APIs
in this module are modelled on those functions and work on
Cocoa objects as well as basic Python objects.

Key-Value Coding works with keys, basically attribute names, as well as
key-paths. A key-path is a string that contains a sequence of dot-separated
keys and is used to chain a number of keys together.

Accessor functions¶

<tt class="descclassname">PyObjCTools.KeyValueCoding.</tt><tt class="descname">getKey</tt><big>(</big>object, key<big>)</big>¶

Return the value of the attribute referenced by <tt class="docutils literal">key</tt>. The key
is used to build the name of an accessor method or attribute name.

The following methods are tried for regular Python objects:

Accessor method <tt class="docutils literal">getKey</tt>

Accessor method <tt class="docutils literal">get_key</tt>

Accessor method or attribute <tt class="docutils literal">key</tt>

Accessor meethod or attribute <tt class="docutils literal">isKey</tt>

Attribute <tt class="docutils literal">_key</tt>

(In all of these “key” is replaced by the value of <tt class="docutils literal">key</tt>).

This function calls the regular Key-Value Coding methods for Cocoa objects,
including those implemented in Python.

<col class="field-name" />
<col class="field-body" />

Parameters:

object – An arbitrary object

key (string) – name of a key

Result :
the value of a key

Raise :
<tt class="xref py py-exc docutils literal">KeyError</tt> when the key does not exist.

<tt class="descclassname">PyObjCTools.KeyValueCoding.</tt><tt class="descname">setKey</tt><big>(</big>object, key, value<big>)</big>¶

Set the value of the attribute referenced by <tt class="docutils literal">key</tt> to
<tt class="docutils literal">key</tt>. The key is used to build the name of an accessor
method or attribute name.

When the object is a Cocoa object (including those implemented in
Python) this method calls the regular Cocoa API for setting a property.

When the object is an instance of <tt class="xref py py-class docutils literal">collections.Mapping</tt>
this function uses <tt class="xref py py-func docutils literal">operator.setitem()</tt> to update the
dictionary.

The following methods are tried for regular Python objects:

Accessor method <tt class="docutils literal">setKey</tt>

Accessor method <tt class="docutils literal">set_key</tt>

attribute <tt class="docutils literal">key</tt> when that already exists (and is not a method)

attribute <tt class="docutils literal">_key</tt> when that already exists

Attribute <tt class="docutils literal">key</tt>

(In all of these “key” is replaced by the value of <tt class="docutils literal">key</tt>).

<col class="field-name" />
<col class="field-body" />

Parameters:

object – An arbitrary object

key (string) – name of a key

value – The value to set

Result :
the value of a key

Raise :
<tt class="xref py py-exc docutils literal">KeyError</tt> when the key does not exist.

<tt class="descclassname">PyObjCTools.KeyValueCoding.</tt><tt class="descname">getKeyPath</tt><big>(</big>object, keypath<big>)</big>¶

The <tt class="docutils literal">keypath</tt> is a string containing a path of keys. The keys
are separated by colons, for example <tt class="xref py py-data docutils literal">"owner.firstName"</tt>.

The key path is used to traverse an object graph to an attribute. This
function also supports set and array operators. Those are keys of
the form <tt class="docutils literal">@operator</tt> are are used as <tt class="docutils literal">pathToArray.@operator.pathToProperty</tt>,
for example <tt class="docutils literal">system.disks.@max.capacity</tt>.

The table below lists the supported array operators

<colgroup>
<col width="33%" />
<col width="67%" />
</colgroup>

Operator

<tt class="docutils literal">avg</tt>
Use the rest of the keypath to fetch the value
of each item in the container and returns the
average of those values.

<tt class="docutils literal">count</tt>
Returns the number of items in the container

<tt class="docutils literal">distinctUnionOfArrays</tt>
Use the rest of the keypath to fetch the value of
each item, which must be a sequence. Those sequences
are merged into an array with distict values.

<tt class="docutils literal">distinctUnionOfObjects</tt>
Use the rest of the keypath to fetch the value of
each item and return an array with all distinct
values.

<tt class="docutils literal">max</tt>
Use the rest of the keypath to fetch the value
of each item in the container and returns the
maximum of those values.

<tt class="docutils literal">min</tt>
Use the rest of the keypath to fetch the value
of each item in the container and returns the
minimum of those values.

<tt class="docutils literal">sum</tt>
Use the rest of the keypath to fetch the value
of each item in the container and returns the
sum of those values.

<tt class="docutils literal">unionOfArrays</tt>
Like <tt class="docutils literal">distinctUnionOfArrays</tt>, but without
removing duplicates.

<tt class="docutils literal">unionOfObjects</tt>
Like <tt class="docutils literal">distinctUnionOfObjects</tt>, but without
removing duplicates

This function calls the regular Key-Value Coding method for Cocoa objects.

<col class="field-name" />
<col class="field-body" />

Parameters:

object – An arbitrary object

keypath (string) – The keypath, colon seperated keys

Key-Value Coding wrapper¶

class <tt class="descclassname">PyObjCTools.KeyValueCoding.</tt><tt class="descname">kvc</tt><big>(</big>value<big>)</big>¶

This wrappers <tt class="docutils literal">value</tt> in an object that uses KeyValue Coding
to implement the attribute and item accessors.

Table Of Contents

<tt class="docutils literal">PyObjCTools.KeyValueCoding</tt> – Key-Value Coding API

Accessor functions

Key-Value Coding wrapper

Previous topic

<tt class="docutils literal docutils literal docutils literal docutils literal">PyObjCTools</tt> – Utilities

Next topic

<tt class="docutils literal docutils literal docutils literal">PyObjCTools.AppHelper</tt> – Work with AppKit

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

PyObjC-Core 2.5.0b1 documentation »

Python API »

<tt class="docutils literal docutils literal docutils literal docutils literal docutils literal">PyObjCTools</tt> – Utilities »

        © Copyright 2009-2012, Ronald Oussoren.
      Created using Sphinx 1.1.3.


text:
package com.communote.server.persistence.property;

/**
 * @see com.communote.server.model.property.StringProperty
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class StringPropertyDaoImpl extends
        com.communote.server.persistence.property.StringPropertyDaoBase {
}


text:
set -x

#source gskey.sh

sudo gsutil version -l

harbor_logs_bucket="harbor-ci-logs"
# GC credentials
#keyfile="/home/travis/harbor-ci-logs.key"
#botofile="/home/travis/.boto"
#echo -en $GS_PRIVATE_KEY > $keyfile
#sudo chmod 400 $keyfile
#echo "[Credentials]" >> $botofile
#echo "gs_service_key_file = $keyfile" >> $botofile
#echo "gs_service_client_id = $GS_CLIENT_EMAIL" >> $botofile
#echo "[GSUtil]" >> $botofile
#echo "content_language = en" >> $botofile
#echo "default_project_id = $GS_PROJECT_ID" >> $botofile
DIR="$(cd "$(dirname "$0")" && pwd)"
E2E_IMAGE="goharbor/harbor-e2e-engine:3.0.0-api"

# GS util
function uploader {
   sudo gsutil cp $1 gs://$2/$1
   sudo gsutil acl ch -u AllUsers:R gs://$2/$1
}

set +e

docker ps
# run db auth api cases
if [ "$1" = 'DB' ]; then
    docker run -i --privileged -v $DIR/../../:/drone -v $DIR/../:/ca -w /drone $E2E_IMAGE robot --exclude proxy_cache -v DOCKER_USER:${DOCKER_USER} -v DOCKER_PWD:${DOCKER_PWD} -v ip:$2  -v ip1: -v http_get_ca:false -v HARBOR_PASSWORD:Harbor12345 /drone/tests/robot-cases/Group1-Nightly/Setup.robot /drone/tests/robot-cases/Group0-BAT/API_DB.robot
elif [ "$1" = 'PROXY_CACHE' ]; then
    docker run -i --privileged -v $DIR/../../:/drone -v $DIR/../:/ca -w /drone $E2E_IMAGE robot --include setup  --include proxy_cache -v DOCKER_USER:${DOCKER_USER} -v DOCKER_PWD:${DOCKER_PWD} -v ip:$2  -v ip1: -v http_get_ca:false -v HARBOR_PASSWORD:Harbor12345 /drone/tests/robot-cases/Group1-Nightly/Setup.robot /drone/tests/robot-cases/Group0-BAT/API_DB.robot
elif [ "$1" = 'LDAP' ]; then
    # run ldap api cases
    python $DIR/../../tests/configharbor.py -H $IP -u $HARBOR_ADMIN -p $HARBOR_ADMIN_PASSWD -c auth_mode=ldap_auth \
                                  ldap_url=ldap://$IP \
                                  ldap_search_dn=cn=admin,dc=example,dc=com \
                                  ldap_search_password=admin \
                                  ldap_base_dn=dc=example,dc=com \
                                  ldap_uid=cn
    docker run -i --privileged -v $DIR/../../:/drone -v $DIR/../:/ca -w /drone $E2E_IMAGE robot -v DOCKER_USER:${DOCKER_USER} -v DOCKER_PWD:${DOCKER_PWD} -v ip:$2  -v ip1: -v http_get_ca:false -v HARBOR_PASSWORD:Harbor12345 /drone/tests/robot-cases/Group1-Nightly/Setup.robot /drone/tests/robot-cases/Group0-BAT/API_LDAP.robot
else
    rc=999
fi
rc=$?
## --------------------------------------------- Upload Harbor CI Logs -------------------------------------------
timestamp=$(date +%s)
outfile="integration_logs_$timestamp$TRAVIS_COMMIT.tar.gz"
sudo tar -zcvf $outfile output.xml log.html /var/log/harbor/*
if [ -f "$outfile" ]; then
   uploader $outfile $harbor_logs_bucket
   echo "----------------------------------------------"
   echo "Download test logs:"
   echo "https://storage.googleapis.com/harbor-ci-logs/$outfile"
   echo "----------------------------------------------"
else
   echo "No log output file to upload"
fi

exit $rc


text:
#include "multi_lidar_calibrator.h"

int main(int argc, char **argv)
{
	ros::init(argc, argv, __APP_NAME__);

	RosMultiLidarCalibratorApp app;

	app.Run();

	return 0;
}


text:
Sequel.migration do
  up do
    Sequel::Model.db.tables
                    .reject{|t_name| t_name.in?([:tariff_updates, :sections, :schema_migrations])}
                    .reject{|t| t.to_s =~ /chief|chapter_notes|section_notes|chapters_sections|hidden|search/}.each do |table_name|
      alter_table table_name do
        add_index :operation_date, name: :"#{table_name.to_s.split("_").map(&:first).join}_operation_date"
      end
    end
  end

  down do
    Sequel::Model.db.tables
                    .reject{|t_name| t_name.in?([:tariff_updates, :sections, :schema_migrations])}
                    .reject{|t| t.to_s =~ /chief|chapter_notes|section_notes|chapters_sections|hidden|search/}.each do |table_name|
      alter_table table_name do
        drop_index :operation_date, name: :"#{table_name.to_s.split("_").map(&:first).join}_operation_date"
      end
    end
  end
end


text:
SoftwareSerial commSerial(10, 11);

void comm_init() {
  commSerial.begin(9600);
}

void command_send(byte cmd, byte len, void *data) {
  struct command send_data;
  send_data.checksum = 0;
  send_data.checksum += (send_data.id = 0xFF); // TODO: Read ID
  send_data.checksum += (send_data.cmd = cmd);
  send_data.checksum += (send_data.len = len);
  for (int i = 0; i < len; i++)
    send_data.checksum += (((char *)data)[i]);
  send_data.checksum = -send_data.checksum;

  commSerial.write((byte *)&send_data, sizeof(send_data));
  commSerial.write((byte *)data, len);
}

bool command_receive(struct command *recv_data, byte *buf_len, char *buffer) {
  commSerial.readBytes((char *)recv_data, 4);
  if (*buf_len < recv_data->len) {
    *buf_len = 0;
    char empty_buffer[recv_data->len];
    commSerial.readBytes(empty_buffer, recv_data->len);
    return false;
  }

  commSerial.readBytes(buffer, recv_data->len);
  *buf_len = recv_data->len;

  byte checksum = recv_data->id + recv_data->cmd + recv_data->len + recv_data->checksum;
  for (int i = 0; i < recv_data->len; i++)
    checksum += buffer[i];

  if (checksum != recv_data->checksum) {
    return false;
  }

  return true;
}

bool command_ready() {
  return Serial.available() > 3;
}


text:
package org.switchyard.quickstarts.transform.dozer;

import javax.xml.namespace.QName;

import org.junit.Assert;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;

/**
 * Test JSON transformations around a service.
 */
@RunWith(SwitchYardRunner.class)
@SwitchYardTestCaseConfig(config = SwitchYardTestCaseConfig.SWITCHYARD_XML, mixins = CDIMixIn.class)
public class DozerTransformationTest {

    @ServiceOperation("OrderService.submitOrder")
    private Invoker submitOrder;

    private SwitchYardTestKit _testKit;

    // Message types being transformed
    public static final QName FROM_TYPE =
        new QName("urn:switchyard-quickstart:transform-dozer:1.0", "order");
    public static final QName TO_TYPE =
        new QName("urn:switchyard-quickstart:transform-dozer:1.0", "orderResponse");

    // Paths to JSON test files
    final String ORDER_JSON = "/json/order.json";
    final String ORDER_ACK_JSON = "/json/orderAck.json";

    @Test
    public void testTransformJSONtoJava() throws Exception {
        OrderAck orderAck = submitOrder
            .inputType(FROM_TYPE)
            .sendInOut(_testKit.readResourceString(ORDER_JSON))
            .getContent(OrderAck.class);

        Assert.assertTrue(orderAck.isAccepted());
    }

    @Test
    public void testTransformJavaToJson() throws Exception {
        Order testOrder = new Order()
            .setItem("BUTTER")
            .setQuantity(100);

        String result = submitOrder
            .expectedOutputType(TO_TYPE)
            .sendInOut(testOrder)
            .getContent(String.class);

        // parse the reference and returned JSON strings and compare for equality
        ObjectMapper mapper = new ObjectMapper();
        OrderAck expected = mapper.readValue(
            _testKit.readResourceString(ORDER_ACK_JSON), OrderAck.class);
        OrderAck returned = mapper.readValue(result, OrderAck.class);

        Assert.assertEquals(expected, returned);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item
        android:id="@+id/wallet_context_edit"
        android:title="Edit Wallet"/>
    <item
        android:id="@+id/wallet_context_delete"
        android:title="Delete Wallet"/>
</menu>


text:
from glanceclient.common import progressbar
from glanceclient.common import utils
from glanceclient import exc

@utils.arg('--page-size', metavar='<SIZE>', default=None, type=int,
           help='Number of images to request in each paginated request.')
@utils.arg('--visibility', metavar='<VISIBILITY>',
           help='The visibility of the images to display.')
@utils.arg('--member-status', metavar='<MEMBER_STATUS>',
           help='The status of images to display.')
@utils.arg('--owner', metavar='<OWNER>',
           help='Display images owned by <OWNER>.')
@utils.arg('--checksum', metavar='<CHECKSUM>',
           help='Display images matching the checksum')
def do_image_list(gc, args):
    """List images you can access."""
    filter_keys = ['visibility', 'member_status', 'owner', 'checksum']
    filter_items = [(key, getattr(args, key)) for key in filter_keys]
    filters = dict([item for item in filter_items if item[1] is not None])

    kwargs = {'filters': filters}
    if args.page_size is not None:
        kwargs['page_size'] = args.page_size

    images = gc.images.list(**kwargs)
    columns = ['ID', 'Name']
    utils.print_list(images, columns)

@utils.arg('id', metavar='<IMAGE_ID>', help='ID of image to describe.')
def do_image_show(gc, args):
    """Describe a specific image."""
    image = gc.images.get(args.id)
    ignore = ['self', 'access', 'file', 'schema']
    image = dict([item for item in image.iteritems() if item[0] not in ignore])
    utils.print_dict(image)

@utils.arg('--image-id', metavar='<IMAGE_ID>', required=True,
           help='Image to display members of.')
def do_member_list(gc, args):
    """Describe sharing permissions by image."""

    members = gc.image_members.list(args.image_id)
    columns = ['Image ID', 'Member ID', 'Status']
    utils.print_list(members, columns)

@utils.arg('image_id', metavar='<IMAGE_ID>',
           help='Image from which to remove member')
@utils.arg('member_id', metavar='<MEMBER_ID>',
           help='Tenant to remove as member')
def do_member_delete(gc, args):
    """Delete image member"""
    if not (args.image_id and args.member_id):
        utils.exit('Unable to delete member. Specify image_id and member_id')
    else:
        gc.image_members.delete(args.image_id, args.member_id)

@utils.arg('image_id', metavar='<IMAGE_ID>',
           help='Image from which to update member')
@utils.arg('member_id', metavar='<MEMBER_ID>',
           help='Tenant to update')
@utils.arg('member_status', metavar='<MEMBER_STATUS>',
           help='Updated status of member')
def do_member_update(gc, args):
    """Update the status of a member for a given image."""
    if not (args.image_id and args.member_id and args.member_status):
        utils.exit('Unable to update member. Specify image_id, member_id and'
                   ' member_status')
    else:
        member = gc.image_members.update(args.image_id, args.member_id,
                                         args.member_status)
        member = [member]
        columns = ['Image ID', 'Member ID', 'Status']
        utils.print_list(member, columns)

@utils.arg('image_id', metavar='<IMAGE_ID>',
           help='Image on which to create member')
@utils.arg('member_id', metavar='<MEMBER_ID>',
           help='Tenant to add as member')
def do_member_create(gc, args):
    """Create member for a given image."""
    if not (args.image_id and args.member_id):
        utils.exit('Unable to create member. Specify image_id and member_id')
    else:
        member = gc.image_members.create(args.image_id, args.member_id)
        member = [member]
        columns = ['Image ID', 'Member ID', 'Status']
        utils.print_list(member, columns)

@utils.arg('model', metavar='<MODEL>', help='Name of model to describe.')
def do_explain(gc, args):
    """Describe a specific model."""
    try:
        schema = gc.schemas.get(args.model)
    except exc.HTTPNotFound:
        utils.exit('Unable to find requested model \'%s\'' % args.model)
    else:
        formatters = {'Attribute': lambda m: m.name}
        columns = ['Attribute', 'Description']
        utils.print_list(schema.properties, columns, formatters)

@utils.arg('--file', metavar='<FILE>',
           help='Local file to save downloaded image data to. '
                'If this is not specified the image data will be '
                'written to stdout.')
@utils.arg('id', metavar='<IMAGE_ID>', help='ID of image to download.')
@utils.arg('--progress', action='store_true', default=False,
           help='Show download progress bar.')
def do_image_download(gc, args):
    """Download a specific image."""
    body = gc.images.data(args.id)
    if args.progress:
        body = progressbar.VerboseIteratorWrapper(body, len(body))
    utils.save_image(body, args.file)

@utils.arg('id', metavar='<IMAGE_ID>', help='ID of image to delete.')
def do_image_delete(gc, args):
    """Delete specified image."""
    gc.images.delete(args.id)

@utils.arg('image_id', metavar='<IMAGE_ID>',
           help='Image to be updated with the given tag')
@utils.arg('tag_value', metavar='<TAG_VALUE>',
           help='Value of the tag')
def do_image_tag_update(gc, args):
        """Update an image with the given tag."""
        if not (args.image_id and args.tag_value):
            utils.exit('Unable to update tag. Specify image_id and tag_value')
        else:
            gc.image_tags.update(args.image_id, args.tag_value)
            image = gc.images.get(args.image_id)
            image = [image]
            columns = ['ID', 'Tags']
            utils.print_list(image, columns)

@utils.arg('image_id', metavar='<IMAGE_ID>',
           help='Image whose tag to be deleted')
@utils.arg('tag_value', metavar='<TAG_VALUE>',
           help='Value of the tag')
def do_image_tag_delete(gc, args):
    """Delete the tag associated with the given image."""
    if not (args.image_id and args.tag_value):
        utils.exit('Unable to delete tag. Specify image_id and tag_value')
    else:
        gc.image_tags.delete(args.image_id, args.tag_value)


text:
package ca.mcgill.cs.sel.ram.impl;

import ca.mcgill.cs.sel.ram.LiteralBoolean;
import ca.mcgill.cs.sel.ram.RamPackage;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Literal Boolean'.
 *
 *

 * The following features are implemented:
 *

 *
{@link ca.mcgill.cs.sel.ram.impl.LiteralBooleanImpl#isValue Value}

 *

 *

 *
 * @generated
 */
public class LiteralBooleanImpl extends LiteralSpecificationImpl implements LiteralBoolean {
    /**
     * The default value of the '{@link #isValue() Value}' attribute.
     *
     *
     * @see #isValue()
     * @generated
     * @ordered
     */
    protected static final boolean VALUE_EDEFAULT = false;

    /**
     * The cached value of the '{@link #isValue() Value}' attribute.
     *
     *
     * @see #isValue()
     * @generated
     * @ordered
     */
    protected boolean value = VALUE_EDEFAULT;

    /**
     *
     *
     * @generated
     */
    protected LiteralBooleanImpl() {
        super();
    }

    /**
     *
     *
     * @generated
     */
    @Override
    protected EClass eStaticClass() {
        return RamPackage.Literals.LITERAL_BOOLEAN;
    }

    /**
     *
     *
     * @generated
     */
    public boolean isValue() {
        return value;
    }

    /**
     *
     *
     * @generated
     */
    public void setValue(boolean newValue) {
        boolean oldValue = value;
        value = newValue;
        if (eNotificationRequired())
            eNotify(new ENotificationImpl(this, Notification.SET, RamPackage.LITERAL_BOOLEAN__VALUE, oldValue, value));
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public Object eGet(int featureID, boolean resolve, boolean coreType) {
        switch (featureID) {
            case RamPackage.LITERAL_BOOLEAN__VALUE:
                return isValue();
        }
        return super.eGet(featureID, resolve, coreType);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public void eSet(int featureID, Object newValue) {
        switch (featureID) {
            case RamPackage.LITERAL_BOOLEAN__VALUE:
                setValue((Boolean)newValue);
                return;
        }
        super.eSet(featureID, newValue);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public void eUnset(int featureID) {
        switch (featureID) {
            case RamPackage.LITERAL_BOOLEAN__VALUE:
                setValue(VALUE_EDEFAULT);
                return;
        }
        super.eUnset(featureID);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public boolean eIsSet(int featureID) {
        switch (featureID) {
            case RamPackage.LITERAL_BOOLEAN__VALUE:
                return value != VALUE_EDEFAULT;
        }
        return super.eIsSet(featureID);
    }

    /**
     *
     *
     * @generated
     */
    @Override
    public String toString() {
        if (eIsProxy()) return super.toString();

        StringBuffer result = new StringBuffer(super.toString());
        result.append(" (value: ");
        result.append(value);
        result.append(')');
        return result.toString();
    }

} //LiteralBooleanImpl