Esempio n. 1
0
 public void testRecursing()
 {
     Parse p = new Parse("leader<table><TR><Td>body</tD></TR></table>trailer");
     Assert.AreEqual(null, p.body);
     Assert.AreEqual(null, p.parts.body);
     Assert.AreEqual("body", p.parts.parts.body);
 }
Esempio n. 2
0
 public void testIterating()
 {
     Parse p = new Parse("leader<table><tr><td>one</td><td>two</td><td>three</td></tr></table>trailer");
     Assert.AreEqual("one", p.parts.parts.body);
     Assert.AreEqual("two", p.parts.parts.more.body);
     Assert.AreEqual("three", p.parts.parts.more.more.body);
 }
Esempio n. 3
0
    public void testText()
    {
        string[] tags ={"td"};
        Parse p = new Parse("<td>a&lt;b</td>", tags);
        Assert.AreEqual("a&lt;b", p.body);
        Assert.AreEqual("a<b", p.text());
        p = new Parse("<td>\ta&gt;b&nbsp;&amp;&nbsp;b>c &&&lt;</td>", tags);
        Assert.AreEqual("a>b & b>c &&<", p.text());
        p = new Parse("<td>\ta&gt;b&nbsp;&amp;&nbsp;b>c &&lt;</td>", tags);
        Assert.AreEqual("a>b & b>c &<", p.text());
        p = new Parse("<TD><P><FONT FACE=\"Arial\" SIZE=2>GroupTestFixture</FONT></TD>", tags);
        Assert.AreEqual("GroupTestFixture",p.text());

        Assert.AreEqual("", Parse.htmlToText("&nbsp;"));
        Assert.AreEqual("a b", Parse.htmlToText("a <tag /> b"));
        Assert.AreEqual("a", Parse.htmlToText("a &nbsp;"));
        Assert.AreEqual("a", Parse.htmlToText("\u00a0 a \u00a0"));
        Assert.AreEqual("&nbsp;", Parse.htmlToText("&amp;nbsp;"));
        Assert.AreEqual("1     2", Parse.htmlToText("1 &nbsp; &nbsp; 2"));
        Assert.AreEqual("1     2", Parse.htmlToText("1 \u00a0\u00a0\u00a0\u00a02"));
        Assert.AreEqual("a", Parse.htmlToText("  <tag />a"));
        Assert.AreEqual("a\nb", Parse.htmlToText("a<br />b"));

        Assert.AreEqual("ab", Parse.htmlToText("<font size=+1>a</font>b"));
        Assert.AreEqual("ab", Parse.htmlToText("a<font size=+1>b</font>"));
        Assert.AreEqual("a<b", Parse.htmlToText("a<b"));

        Assert.AreEqual("a\nb\nc\nd", Parse.htmlToText("a<br>b<br/>c<  br   /   >d"));
        Assert.AreEqual("a\nb", Parse.htmlToText("a</p><p>b"));
        Assert.AreEqual("a\nb", Parse.htmlToText("a< / p >   <   p  >b"));
    }
Esempio n. 4
0
 public override Tree<Cell> MakeCell(string text, string tag, IEnumerable<Tree<Cell>> branches) {
     var result = new Parse(tag, text, null, null);
     foreach (var branch in branches) {
         result.Add(branch);
     }
     return result;
 }
Esempio n. 5
0
    /*
    ** Given table pTab, return a list of all the triggers attached to
    ** the table. The list is connected by Trigger.pNext pointers.
    **
    ** All of the triggers on pTab that are in the same database as pTab
    ** are already attached to pTab.pTrigger.  But there might be additional
    ** triggers on pTab in the TEMP schema.  This routine prepends all
    ** TEMP triggers on pTab to the beginning of the pTab.pTrigger list
    ** and returns the combined list.
    **
    ** To state it another way:  This routine returns a list of all triggers
    ** that fire off of pTab.  The list will include any TEMP triggers on
    ** pTab as well as the triggers lised in pTab.pTrigger.
    */
    static Trigger sqlite3TriggerList( Parse pParse, Table pTab )
    {
      Schema pTmpSchema = pParse.db.aDb[1].pSchema;
      Trigger pList = null;                  /* List of triggers to return */

      if ( pParse.disableTriggers != 0 )
      {
        return null;
      }

      if ( pTmpSchema != pTab.pSchema )
      {
        HashElem p;
        Debug.Assert( sqlite3SchemaMutexHeld( pParse.db, 0, pTmpSchema ) );
        for ( p = sqliteHashFirst( pTmpSchema.trigHash ); p != null; p = sqliteHashNext( p ) )
        {
          Trigger pTrig = (Trigger)sqliteHashData( p );
          if ( pTrig.pTabSchema == pTab.pSchema
          && pTrig.table.Equals( pTab.zName, StringComparison.InvariantCultureIgnoreCase ) )
          {
            pTrig.pNext = ( pList != null ? pList : pTab.pTrigger );
            pList = pTrig;
          }
        }
      }

      return ( pList != null ? pList : pTab.pTrigger );
    }
Esempio n. 6
0
 public Parse TestResult(Parse theTest)
 {
     resultTables = null;
     var story = new StoryTest(new Parse("div", string.Empty, theTest, null), SaveTestResult);
     story.Execute(Processor.Configuration);
     return resultTables;
 }
Esempio n. 7
0
        public virtual Expression CompileOperator(Expression left, Expression right, Parse.Operator op)
        {
            switch (op)
            {
                case Parse.Operator.Addition: return Expression.Add(left, right);
                case Parse.Operator.Subtract: return Expression.Subtract(left, right);
                case Parse.Operator.Multiply: return Expression.Multiply(left, right);
                case Parse.Operator.Modulo: return Expression.Modulo(left, right);
                case Parse.Operator.Divide: return Expression.Divide(left, right);
                case Parse.Operator.Power: return Expression.Power(left, right);

                case Parse.Operator.BitwiseAnd:
                case Parse.Operator.And: return Expression.And(left, right);
                case Parse.Operator.BitwiseOr:
                case Parse.Operator.Or: return Expression.Or(left, right);
                case Parse.Operator.BitwiseXor:
                case Parse.Operator.Xor: return Expression.ExclusiveOr(left, right);
                case Parse.Operator.ShiftLeft: return Expression.LeftShift(left, right);
                case Parse.Operator.ShiftRight: return Expression.RightShift(left, right);

                case Parse.Operator.Equal: return Expression.Equal(left, right);
                case Parse.Operator.NotEqual: return Expression.NotEqual(left, right);
                case Parse.Operator.InclusiveGreater: return Expression.GreaterThanOrEqual(left, right);
                case Parse.Operator.InclusiveLess: return Expression.LessThanOrEqual(left, right);
                case Parse.Operator.Greater: return Expression.GreaterThan(left, right);
                case Parse.Operator.Less: return Expression.LessThan(left, right);

                default: throw new NotSupportedException();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Parses the specified <see cref="ISentence"/> object using a given <paramref name="parser"/>.
        /// </summary>
        /// <param name="sentence">The sentence to be parsed.</param>
        /// <param name="parser">The parser.</param>
        /// <param name="numParses">The number parses. Usually 1.</param>
        /// <returns>An array with the parsed results.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="sentence"/>
        /// or
        /// <paramref name="parser"/>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">numParses</exception>
        /// <exception cref="System.InvalidOperationException">The sentence is not tokenized.</exception>
        public static Parse[] ParseLine(ISentence sentence, IParser parser, int numParses) {
            if (sentence == null)
                throw new ArgumentNullException("sentence");

            if (parser == null)
                throw new ArgumentNullException("parser");

            if (numParses < 0)
                throw new ArgumentOutOfRangeException("numParses");

            if (sentence.Tokens == null || sentence.Tokens.Count == 0)
                throw new InvalidOperationException("The sentence is not tokenized.");

            var sb = new StringBuilder(sentence.Length);
            for (var i = 0; i < sentence.Tokens.Count; i++) {
                sb.Append(sentence.Tokens[i].Lexeme).Append(' ');
            }
            sb.Remove(sb.Length - 1, 1);

            var start = 0;
            var p = new Parse(sb.ToString(), new Span(0, sb.Length), AbstractBottomUpParser.INC_NODE, 0, 0);

            for (var i = 0; i < sentence.Tokens.Count; i++) {
                p.Insert(
                    new Parse(
                        sb.ToString(), 
                        new Span(start, start + sentence.Tokens[i].Lexeme.Length),
                        AbstractBottomUpParser.TOK_NODE, 0, i));

                start += sentence.Tokens[i].Lexeme.Length + 1;
            }

            return numParses == 1 ? new[] { parser.Parse(p) } : parser.Parse(p, numParses);
        }
Esempio n. 9
0
    /*
    ** Check to make sure the given table is writable.  If it is not
    ** writable, generate an error message and return 1.  If it is
    ** writable return 0;
    */
    static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk )
    {
      /* A table is not writable under the following circumstances:
      **
      **   1) It is a virtual table and no implementation of the xUpdate method
      **      has been provided, or
      **   2) It is a system table (i.e. sqlite_master), this call is not
      **      part of a nested parse and writable_schema pragma has not
      **      been specified.
      **
      ** In either case leave an error message in pParse and return non-zero.
      */
      if (
         ( IsVirtual( pTab )
          && sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null )
        || ( ( pTab.tabFlags & TF_Readonly ) != 0
      && ( pParse.db.flags & SQLITE_WriteSchema ) == 0
      && pParse.nested == 0 )
      )
      {
        sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName );
        return true;
      }

#if !SQLITE_OMIT_VIEW
      if ( viewOk == 0 && pTab.pSelect != null )
      {
        sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName );
        return true;
      }
#endif
      return false;
    }
Esempio n. 10
0
 public void MarksSameStringCellAsRight()
 {
     var cell = new Parse("td", "something", null, null);
     var fixture = new Fixture {Processor = new Service.Service()};
     fixture.CellOperation.Check(new TypedValue("something"), cell);
     Assert.AreEqual("\n<td class=\"pass\">something</td>", cell.ToString());
 }
Esempio n. 11
0
        public override void DoTable(Parse theTable)
        {
            Parse embeddedTables = GetEmbeddedTables(theTable);
            Parse expectedCell = GetExpectedCell(theTable);

            var writer = new StoryTestCopyWriter();
            var storyTest = new StoryTest(Processor, writer)
                .WithParsedInput(new Parse("div", string.Empty, embeddedTables, null));
            storyTest.Execute(new Service.Service(Processor));

            SetEmbeddedTables(theTable, writer.ResultTables);

            if (expectedCell != null) {
                var actual = new FixtureTable(writer.ResultTables);
                var expected = new FixtureTable(expectedCell.Parts);
                string differences = actual.Differences(expected);
                if (differences.Length == 0) {
                    Right(expectedCell);
                }
                else {
                    Wrong(expectedCell);
                    expectedCell.More = ParseNode.MakeCells(Escape(differences));
                    expectedCell.More.SetAttribute(CellAttribute.Status, TestStatus.Wrong);
                }
            }
        }
Esempio n. 12
0
    /*
    ** Given table pTab, return a list of all the triggers attached to
    ** the table. The list is connected by Trigger.pNext pointers.
    **
    ** All of the triggers on pTab that are in the same database as pTab
    ** are already attached to pTab.pTrigger.  But there might be additional
    ** triggers on pTab in the TEMP schema.  This routine prepends all
    ** TEMP triggers on pTab to the beginning of the pTab.pTrigger list
    ** and returns the combined list.
    **
    ** To state it another way:  This routine returns a list of all triggers
    ** that fire off of pTab.  The list will include any TEMP triggers on
    ** pTab as well as the triggers lised in pTab.pTrigger.
    */
    static Trigger sqlite3TriggerList( Parse pParse, Table pTab )
    {
      Schema pTmpSchema = pParse.db.aDb[1].pSchema;
      Trigger pList = null;                  /* List of triggers to return */

  if( pParse.disableTriggers !=0){
    return null;
  }

      if ( pTmpSchema != pTab.pSchema )
      {
        HashElem p;
        for ( p = sqliteHashFirst( pTmpSchema.trigHash ) ; p != null ; p = sqliteHashNext( p ) )
        {
          Trigger pTrig = (Trigger)sqliteHashData( p );
          if ( pTrig.pTabSchema == pTab.pSchema
          && 0 == sqlite3StrICmp( pTrig.table, pTab.zName )
          )
          {
            pTrig.pNext = ( pList != null ? pList : pTab.pTrigger );
            pList = pTrig;
          }
        }
      }

      return ( pList != null ? pList : pTab.pTrigger );
    }
Esempio n. 13
0
 public void MarksDifferentStringCellAsWrong()
 {
     var cell = new Parse("td", "something else", null, null);
     var fixture = new Fixture {Processor = new Service.Service()};
     fixture.CellOperation.Check(new TypedValue("something"), cell);
     Assert.AreEqual("\n<td class=\"fail\">something else <span class=\"fit_label\">expected</span><hr />something <span class=\"fit_label\">actual</span></td>", cell.ToString());
 }
Esempio n. 14
0
        protected virtual Expression CompileDereference(Compiler compiler, Frame frame, Expression left, Parse.BinaryExpression expression, System.Type typeHint)
        {
            left = compiler.MaterializeReference(left);

            var local = compiler.AddFrame(frame, expression);
            var memberType = left.Type.GenericTypeArguments[0];
            var parameters = new List<ParameterExpression>();

            var valueParam = compiler.CreateValueParam(expression, local, left, memberType);
            parameters.Add(valueParam);

            var indexParam = compiler.CreateIndexParam(expression, local);
            parameters.Add(indexParam);

            var right =
                compiler.MaterializeReference
                (
                    compiler.CompileExpression(local, expression.Right, typeHint)
                );

            var selection = Expression.Lambda(right, parameters);
            var select =
                typeof(Enumerable).GetMethodExt
                (
                    "Select",
                    new System.Type[] { typeof(IEnumerable<ReflectionUtility.T>), typeof(Func<ReflectionUtility.T, int, ReflectionUtility.T>) }
                );
            select = select.MakeGenericMethod(memberType, selection.ReturnType);
            return Expression.Call(select, left, selection);
        }
Esempio n. 15
0
 public static void AssertValuesInBody(Parse cell, string[] values)
 {
     foreach (string value in values)
     {
         AssertValueInBody(cell, value);
     }
 }
Esempio n. 16
0
    /*
    ** 2008 August 18
    **
    ** The author disclaims copyright to this source code.  In place of
    ** a legal notice, here is a blessing:
    **
    **    May you do good and not evil.
    **    May you find forgiveness for yourself and forgive others.
    **    May you share freely, never taking more than you give.
    **
    *************************************************************************
    **
    ** This file contains routines used for walking the parser tree and
    ** resolve all identifiers by associating them with a particular
    ** table and column.
    *************************************************************************
    **  Included in SQLite3 port to C#-SQLite;  2008 Noah B Hart
    **  C#-SQLite is an independent reimplementation of the SQLite software library
    **
    **  SQLITE_SOURCE_ID: 2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7
    **
    **  $Header$
    *************************************************************************
    */
    //#include "sqliteInt.h"
    //#include <stdlib.h>
    //#include <string.h>

    /*
    ** Turn the pExpr expression into an alias for the iCol-th column of the
    ** result set in pEList.
    **
    ** If the result set column is a simple column reference, then this routine
    ** makes an exact copy.  But for any other kind of expression, this
    ** routine make a copy of the result set column as the argument to the
    ** TK_AS operator.  The TK_AS operator causes the expression to be
    ** evaluated just once and then reused for each alias.
    **
    ** The reason for suppressing the TK_AS term when the expression is a simple
    ** column reference is so that the column reference will be recognized as
    ** usable by indices within the WHERE clause processing logic.
    **
    ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
    ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
    **
    **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
    **
    ** Is equivalent to:
    **
    **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
    **
    ** The result of random()%5 in the GROUP BY clause is probably different
    ** from the result in the result-set.  We might fix this someday.  Or
    ** then again, we might not...
    */
    static void resolveAlias(
    Parse pParse,         /* Parsing context */
    ExprList pEList,      /* A result set */
    int iCol,             /* A column in the result set.  0..pEList.nExpr-1 */
    Expr pExpr,       /* Transform this into an alias to the result set */
    string zType          /* "GROUP" or "ORDER" or "" */
    )
    {
      Expr pOrig;           /* The iCol-th column of the result set */
      Expr pDup;            /* Copy of pOrig */
      sqlite3 db;           /* The database connection */

      Debug.Assert( iCol >= 0 && iCol < pEList.nExpr );
      pOrig = pEList.a[iCol].pExpr;
      Debug.Assert( pOrig != null );
      Debug.Assert( ( pOrig.flags & EP_Resolved ) != 0 );
      db = pParse.db;
      if ( pOrig.op != TK_COLUMN && ( zType.Length == 0 || zType[0] != 'G' ) )
      {
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        pDup = sqlite3PExpr( pParse, TK_AS, pDup, null, null );
        if ( pDup == null ) return;
        if ( pEList.a[iCol].iAlias == 0 )
        {
          pEList.a[iCol].iAlias = (u16)( ++pParse.nAlias );
        }
        pDup.iTable = pEList.a[iCol].iAlias;
      }
      else if ( ExprHasProperty( pOrig, EP_IntValue ) || pOrig.u.zToken == null )
      {
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        if ( pDup == null ) return;
      }
      else
      {
        string zToken = pOrig.u.zToken;
        Debug.Assert( zToken != null );
        pOrig.u.zToken = null;
        pDup = sqlite3ExprDup( db, pOrig, 0 );
        pOrig.u.zToken = zToken;
        if ( pDup == null ) return;
        Debug.Assert( ( pDup.flags & ( EP_Reduced | EP_TokenOnly ) ) == 0 );
        pDup.flags2 |= EP2_MallocedToken;
        pDup.u.zToken = zToken;// sqlite3DbStrDup( db, zToken );
      }
      if ( ( pExpr.flags & EP_ExpCollate ) != 0 )
      {
        pDup.pColl = pExpr.pColl;
        pDup.flags |= EP_ExpCollate;
      }

      /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
      ** prevents ExprDelete() from deleting the Expr structure itself,
      ** allowing it to be repopulated by the memcpy() on the following line.
      */
      ExprSetProperty( pExpr, EP_Static );
      sqlite3ExprDelete( db, ref pExpr );
      pExpr.CopyFrom( pDup ); //memcpy(pExpr, pDup, sizeof(*pExpr));
      sqlite3DbFree( db, ref pDup );
    }
Esempio n. 17
0
 // Generate VDBE code that prepares for doing an operation that might change the database.
 //
 // This routine starts a new transaction if we are not already within a transaction.  If we are already within a transaction, then a checkpoint
 // is set if the setStatement parameter is true.  A checkpoint should be set for operations that might fail (due to a constraint) part of
 // the way through and which will need to undo some writes without having to rollback the whole transaction.  For operations where all constraints
 // can be checked before any changes are made to the database, it is never necessary to undo a write and the checkpoint should not be set.
 internal static void sqlite3BeginWriteOperation(Parse pParse, int setStatement, int iDb)
 {
     var pToplevel = sqlite3ParseToplevel(pParse);
     sqlite3CodeVerifySchema(pParse, iDb);
     pToplevel.writeMask |= ((yDbMask)1) << iDb;
     pToplevel.isMultiWrite |= (byte)setStatement;
 }
Esempio n. 18
0
 public void MarksSameArrayCellAsRight()
 {
     var cell = new Parse("td", "something,more", null, null);
     var fixture = new Fixture {Processor = new Service.Service()};
     fixture.Processor.Check(new TypedValue(new [] {"something", "more"}), cell);
     Assert.AreEqual("\n<td class=\"pass\">something,more</td>", cell.ToString());
 }
Esempio n. 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Parse myParser = new Parse();
            string[] filenames = { "test1.cir", "multiparams.cir", "test2.cir", "test3.cir", "q2n222a.cir", "missing.cir", "nocircuit.cir",
                                 "shortSubcircuit.cir", "bogusName.cir", "bogusparams1.cir", "firstLineCommentTest.cir", 
                                 "nameCharsTestFail.cir", "nameCharsTestPass.cir", "braceTest.cir" };
            foreach( string filename in filenames )
            {
                try
                {
                    ComponentInfo result = myParser.ParseFile(filename );
                    Console.WriteLine("Parsing file '{0}' found {1}",
                        filename, result.ToString() );
                }
                catch (Exception e)
                {
                    // Let the user know what went wrong.
                    Console.WriteLine("ParseFile( {0} ) error:", filename);
                    Console.WriteLine(e.Message);
                }
            }
            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

        }
Esempio n. 20
0
 public Parse TestResult(Parse theTest) {
     var writer = new StoryTestCopyWriter();
     var storyTest = new StoryTest(Processor, writer)
         .WithParsedInput(new Parse("div", string.Empty, theTest, null));
     storyTest.Execute(new Service.Service(Processor));
     return writer.ResultTables;
 }
Esempio n. 21
0
 public override Tree<Cell> MakeCell(string text, IEnumerable<Tree<Cell>> branches)
 {
     var result = new Parse("td", text, null, null);
     var firstBranch = branches.FirstOrDefault();
     if (firstBranch != null) result.Parts = (Parse) firstBranch;
     return result;
 }
Esempio n. 22
0
 public ExpressionContext(Parse.Expression expression, Type.BaseType type, Characteristic characteristics, Action<MethodContext> emitGet)
 {
     Expression = expression;
     Type = type;
     Characteristics = characteristics;
     EmitGet = emitGet;
 }
Esempio n. 23
0
 private void MakeFixture()
 {
     MakeStringFixture();
     cell = TestUtils.CreateCell("abc..");
     service.AddOperator(new CompareSubstring());
     service.AddOperator(new CompareStartsWith());
 }
Esempio n. 24
0
 public LocalBuilder DeclareLocal(Parse.Statement statement, System.Type type, string name)
 {
     var local = IL.DeclareLocal(type);
     if (!String.IsNullOrEmpty(name) && statement != null)
         local.SetLocalSymInfo(name, statement.Line, statement.LinePos);
     return local;
 }
Esempio n. 25
0
        public void DoTable(Fixture fixture, Parse tables, object[] businessObjects, int right, int wrong, int ignores, int exceptions)
        {
            BusinessObjectRowFixture.objects = businessObjects;
            RunTest(fixture, tables);

            TestUtils.CheckCounts(resultCounts, right, wrong, ignores, exceptions);
        }
Esempio n. 26
0
        private static string Differences(Parse theActual, Parse theExpected)
        {
            if (theActual == null) {
                return (theExpected != null ? FormatNodeDifference(theActual, theExpected) : string.Empty);
            }
            if (theExpected == null) {
                return FormatNodeDifference(theActual, theExpected);
            }
            var actualString = theActual.ToString().Replace("\n", string.Empty).Replace("\r", string.Empty);
            var expectedString = theExpected.ToString().Replace("\n", string.Empty).Replace("\r", string.Empty);
            if (actualString == expectedString) return string.Empty;

            var expected = new Expected(theExpected);
            if (theActual.Tag != expected.Node.Tag) {
                return FormatNodeDifference(theActual, expected.Node);
            }
            string result = BodyDifferences(theActual.Body,  expected.Node.Body);
            if (result.Length > 0) {
                return string.Format("in {0} body, {1}", theActual.Tag, result);
            }
            result = Differences(theActual.Parts,  theExpected.Parts);
            if (result.Length > 0) {
                return string.Format("in {0}, {1}", theActual.Tag, result);
            }
            return Differences(theActual.More, theExpected.More);
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            var articles = GetArticles(@"./Articles");
            int index = 0;

            //Get overall most used character in all articles
            var parse = new Parse(articles);
            Console.WriteLine("Overall most used character in articles: " + parse.GetCharacter());
            Console.WriteLine("Character was used: " + parse.GetNumber());

            //Get overall most used character in each articles
            var text = GetNextArticle(articles);
            while (text != null)
            {
                index++;
                var mostUsed = new Parse(text);

                Console.WriteLine("The most used character in article " + index + " : " + mostUsed.GetCharacter() + " repeated " + mostUsed.GetNumber() + " times");

                text = GetNextArticle(articles);
            }

            Console.WriteLine("Press any key to quit");
            Console.ReadLine();
        }
Esempio n. 28
0
        public void EmitName(Parse.Statement statement, string[] components)
        {
            // var nameVar = new Name();
            var nameVar = DeclareLocal(statement, typeof(Name), null);
            IL.Emit(OpCodes.Ldloca, nameVar);
            IL.Emit(OpCodes.Initobj, typeof(Name));

            // <stack> = new string[components.Length];
            IL.Emit(OpCodes.Ldloca, nameVar);
            IL.Emit(OpCodes.Ldc_I4, components.Length);
            IL.Emit(OpCodes.Newarr, typeof(string));

            for (int i = 0; i < components.Length; i++)
            {
                // <stack>[i] = components[i]
                IL.Emit(OpCodes.Dup);
                IL.Emit(OpCodes.Ldc_I4, i);
                IL.Emit(OpCodes.Ldstr, components[i]);
                IL.Emit(OpCodes.Stelem_Ref);
            }

            // nameVar.Components = <stack>
            IL.Emit(OpCodes.Stfld, ReflectionUtility.NameComponents);

            // return nameVar;
            IL.Emit(OpCodes.Ldloc, nameVar);
        }
Esempio n. 29
0
        /*
        ** Do an authorization check using the code and arguments given.  Return
        ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
        ** is returned, then the error count and error message in pParse are
        ** modified appropriately.
        */
        int sqlite3AuthCheck(
Parse *pParse,
int code,
string zArg1,
string zArg2,
string zArg3
)
        {
            sqlite3 db = pParse->db;
            int rc;

            /* Don't do any authorization checks if the database is initialising
            ** or if the parser is being invoked from within sqlite3_declare_vtab.
            */
            if( db->init.busy || IN_DECLARE_VTAB ){
            return SQLITE_OK;
            }

            if( db->xAuth==0 ){
            return SQLITE_OK;
            }
            rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
            if( rc==SQLITE_DENY ){
            sqlite3ErrorMsg(pParse, "not authorized");
            pParse->rc = SQLITE_AUTH;
            }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
            rc = SQLITE_DENY;
            sqliteAuthBadReturnCode(pParse);
            }
            return rc;
        }
Esempio n. 30
0
 public void PartsShouldReturnCellsWhenTheParseRepresentsARow()
 {
     Parse row = new Parse("<tr><td>one</td><td>two</td><td>three</td></tr>", new string[]{"tr", "td"});
     Assert.AreEqual("one", row.Parts.Body);
     Assert.AreEqual("two", row.Parts.More.Body);
     Assert.AreEqual("three", row.Parts.More.More.Body);
 }
Esempio n. 31
0
 public override bool Equals(object obj) => obj is string s?Equals(Parse(s)) : obj is NodeIds i && Equals(i);
Esempio n. 32
0
        /* Make sure "isView" and other macros defined above are undefined. Otherwise
        ** thely may interfere with compilation of other functions in this file
        ** (or in another file, if this file becomes part of the amalgamation).  */
        //#ifdef isView
        // #undef isView
        //#endif
        //#ifdef pTrigger
        // #undef pTrigger
        //#endif

        /*
        ** This routine generates VDBE code that causes a single row of a
        ** single table to be deleted.
        **
        ** The VDBE must be in a particular state when this routine is called.
        ** These are the requirements:
        **
        **   1.  A read/write cursor pointing to pTab, the table containing the row
        **       to be deleted, must be opened as cursor number $iCur.
        **
        **   2.  Read/write cursors for all indices of pTab must be open as
        **       cursor number base+i for the i-th index.
        **
        **   3.  The record number of the row to be deleted must be stored in
        **       memory cell iRowid.
        **
        ** This routine generates code to remove both the table record and all
        ** index entries that point to that record.
        */
        static void sqlite3GenerateRowDelete(
            Parse pParse,     /* Parsing context */
            Table pTab,       /* Table containing the row to be deleted */
            int iCur,         /* VdbeCursor number for the table */
            int iRowid,       /* Memory cell that contains the rowid to delete */
            int count,        /* If non-zero, increment the row change counter */
            Trigger pTrigger, /* List of triggers to (potentially) fire */
            int onconf        /* Default ON CONFLICT policy for triggers */
            )
        {
            Vdbe v    = pParse.pVdbe; /* Vdbe */
            int  iOld = 0;            /* First register in OLD.* array */
            int  iLabel;              /* Label resolved to end of generated code */

            /* Vdbe is guaranteed to have been allocated by this stage. */
            Debug.Assert(v != null);

            /* Seek cursor iCur to the row to delete. If this row no longer exists
            ** (this can happen if a trigger program has already deleted it), do
            ** not attempt to delete it or fire any DELETE triggers.  */
            iLabel = sqlite3VdbeMakeLabel(v);
            sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);

            /* If there are any triggers to fire, allocate a range of registers to
            ** use for the old.* references in the triggers.  */
            if (sqlite3FkRequired(pParse, pTab, null, 0) != 0 || pTrigger != null)
            {
                u32 mask;             /* Mask of OLD.* columns in use */
                int iCol;             /* Iterator used while populating OLD.* */

                /* TODO: Could use temporary registers here. Also could attempt to
                ** avoid copying the contents of the rowid register.  */
                mask = sqlite3TriggerColmask(
                    pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
                    );
                mask        |= sqlite3FkOldmask(pParse, pTab);
                iOld         = pParse.nMem + 1;
                pParse.nMem += (1 + pTab.nCol);

                /* Populate the OLD.* pseudo-table register array. These values will be
                ** used by any BEFORE and AFTER triggers that exist.  */
                sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
                for (iCol = 0; iCol < pTab.nCol; iCol++)
                {
                    if (mask == 0xffffffff || (mask & (1 << iCol)) != 0)
                    {
                        int iTarget = iOld + iCol + 1;
                        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
                        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
                    }
                }

                /* Invoke BEFORE DELETE trigger programs. */
                sqlite3CodeRowTrigger(pParse, pTrigger,
                                      TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
                                      );

                /* Seek the cursor to the row to be deleted again. It may be that
                ** the BEFORE triggers coded above have already removed the row
                ** being deleted. Do not attempt to delete the row a second time, and
                ** do not fire AFTER triggers.  */
                sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);

                /* Do FK processing. This call checks that any FK constraints that
                ** refer to this table (i.e. constraints attached to other tables)
                ** are not violated by deleting this row.  */
                sqlite3FkCheck(pParse, pTab, iOld, 0);
            }

            /* Delete the index and table entries. Skip this step if pTab is really
            ** a view (in which case the only effect of the DELETE statement is to
            ** fire the INSTEAD OF triggers).  */
            if (pTab.pSelect == null)
            {
                sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
                sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count != 0 ? (int)OPFLAG_NCHANGE : 0));
                if (count != 0)
                {
                    sqlite3VdbeChangeP4(v, -1, pTab.zName, P4_STATIC);
                }
            }

            /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
            ** handle rows (possibly in other tables) that refer via a foreign key
            ** to the row just deleted. */
            sqlite3FkActions(pParse, pTab, null, iOld);

            /* Invoke AFTER DELETE trigger programs. */
            sqlite3CodeRowTrigger(pParse, pTrigger,
                                  TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
                                  );

            /* Jump here if the row had already been deleted before any BEFORE
            ** trigger programs were invoked. Or if a trigger program throws a
            ** RAISE(IGNORE) exception.  */
            sqlite3VdbeResolveLabel(v, iLabel);
        }
Esempio n. 33
0
 public override void DoCell(Parse cell, int column)
 {
     currentHeader = headerCells.At(column);
     base.DoCell(cell, column);
 }
Esempio n. 34
0
        public void Return(Parse cells)
        {
            var result = new MethodPhrase(new CellRange(cells)).Evaluate(fixture, processor);

            processor.CallStack.SetReturn(new TypedValue(result));
        }
Esempio n. 35
0
 private static Parser <Dictionary <string, string[]> > Node() =>
 from _ in Parse.Char(';')
 from properties in Properties()
 select properties;
Esempio n. 36
0
 private static Parser <string> Value() =>
 CValueType.Contained(Parse.Char('['), Parse.Char(']'));
Esempio n. 37
0
 private static (WriteAction <T>, ReadAction <T>) GetActions <TReal>(WriteAction <TReal> write, Parse <TReal> read) => (
     (WriteAction <T>)(Delegate) write,
Esempio n. 38
0
 public Fixture Ignored(Parse cells)
 {
     return(new Fixture());
 }
Esempio n. 39
0
 public CommentFixture Comment(Parse cells)
 {
     return(new CommentFixture());
 }
Esempio n. 40
0
 public void Set(Parse theCells)
 {
     ExecuteEmbeddedMethod(theCells);
 }
Esempio n. 41
0
 public void Check(Parse theCells)
 {
     DoCheckOperation(theCells, false);
 }
Esempio n. 42
0
 public List <object> CheckFieldsFor(Parse cells)
 {
     return(new List <object> {
         ExecuteEmbeddedMethod(cells)
     });
 }
Esempio n. 43
0
 public void AbandonStoryTest(Parse theCells)
 {
     processor.TestStatus.MarkIgnore(theCells);
     processor.TestStatus.IsAbandoned = true;
     throw new AbandonStoryTestException();
 }
Esempio n. 44
0
 public Fixture Calculate(Parse theCells)
 {
     return(new CalculateFixture(fixture.SystemUnderTest ?? fixture));
 }
Esempio n. 45
0
 void AddCell(Parse theCells, object theNewValue)
 {
     theCells.Last.More = (Parse)processor.Compose(theNewValue);
 }
Esempio n. 46
0
 public object ExecuteEmbeddedMethod(Parse theCells)
 {
     return(fixture.ExecuteFlowRowMethod(processor, new CellRange(theCells)));
 }
Esempio n. 47
0
 public void WaitUntil(Parse cells)
 {
     DoCheckOperation(cells, true);
 }
Esempio n. 48
0
 public void With(Parse theCells)
 {
     fixture.SetSystemUnderTest(new MethodPhrase(new CellRange(theCells)).Evaluate(fixture, processor));
 }
Esempio n. 49
0
 public void Note(Parse theCells)
 {
 }
Esempio n. 50
0
 public void Reject(Parse theCells)
 {
     Not(theCells);
 }
Esempio n. 51
0
/*
** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse.pNewTable was extended to include
** the new column during parsing.
*/
        static void sqlite3AlterFinishAddColumn(Parse pParse, Token pColDef)
        {
            Table   pNew;        /* Copy of pParse.pNewTable */
            Table   pTab;        /* Table being altered */
            int     iDb;         /* Database number */
            string  zDb;         /* Database name */
            string  zTab;        /* Table name */
            string  zCol;        /* Null-terminated column definition */
            Column  pCol;        /* The new column */
            Expr    pDflt;       /* Default value for the new column */
            sqlite3 db;          /* The database connection; */

            db = pParse.db;
            if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */)
            {
                return;
            }
            pNew = pParse.pNewTable;
            Debug.Assert(pNew != null);
            Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
            iDb   = sqlite3SchemaToIndex(db, pNew.pSchema);
            zDb   = db.aDb[iDb].zName;
            zTab  = pNew.zName.Substring(16);// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
            pCol  = pNew.aCol[pNew.nCol - 1];
            pDflt = pCol.pDflt;
            pTab  = sqlite3FindTable(db, zTab, zDb);
            Debug.Assert(pTab != null);

#if !SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
            if (sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0))
            {
                return;
            }
#endif

            /* If the default value for the new column was specified with a
            ** literal NULL, then set pDflt to 0. This simplifies checking
            ** for an SQL NULL default below.
            */
            if (pDflt != null && pDflt.op == TK_NULL)
            {
                pDflt = null;
            }

            /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
            ** If there is a NOT NULL constraint, then the default value for the
            ** column must not be NULL.
            */
            if (pCol.isPrimKey != 0)
            {
                sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
                return;
            }
            if (pNew.pIndex != null)
            {
                sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
                return;
            }
            if ((db.flags & SQLITE_ForeignKeys) != 0 && pNew.pFKey != null && pDflt != null)
            {
                sqlite3ErrorMsg(pParse,
                                "Cannot add a REFERENCES column with non-NULL default value");
                return;
            }
            if (pCol.notNull != 0 && pDflt == null)
            {
                sqlite3ErrorMsg(pParse,
                                "Cannot add a NOT NULL column with default value NULL");
                return;
            }

            /* Ensure the default expression is something that sqlite3ValueFromExpr()
            ** can handle (i.e. not CURRENT_TIME etc.)
            */
            if (pDflt != null)
            {
                sqlite3_value pVal = null;
                if (sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal) != 0)
                {
                    //		db.mallocFailed = 1;
                    return;
                }
                if (pVal == null)
                {
                    sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
                    return;
                }
                sqlite3ValueFree(ref pVal);
            }

            /* Modify the CREATE TABLE statement. */
            zCol = pColDef.z.Substring(0, pColDef.n).Replace(";", " ").Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n);
            if (zCol != null)
            {
                //  char zEnd = zCol[pColDef.n-1];
                int savedDbFlags = db.flags;
                //	  while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
                //	zEnd-- = '\0';
                //  }
                db.flags |= SQLITE_PreferBuiltin;
                sqlite3NestedParse(pParse,
                                   "UPDATE \"%w\".%s SET " +
                                   "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " +
                                   "WHERE type = 'table' AND name = %Q",
                                   zDb, SCHEMA_TABLE(iDb), pNew.addColOffset, zCol, pNew.addColOffset + 1,
                                   zTab
                                   );
                sqlite3DbFree(db, ref zCol);
                db.flags = savedDbFlags;
            }

            /* If the default value of the new column is NULL, then set the file
            ** format to 2. If the default value of the new column is not NULL,
            ** the file format becomes 3.
            */
            sqlite3MinimumFileFormat(pParse, iDb, pDflt != null ? 3 : 2);

            /* Reload the schema of the modified table. */
            reloadTableSchema(pParse, pTab, pTab.zName);
        }
Esempio n. 52
0
/*
** This function is called by the parser after the table-name in
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
** pSrc is the full-name of the table being altered.
**
** This routine makes a (partial) copy of the Table structure
** for the table being altered and sets Parse.pNewTable to point
** to it. Routines called by the parser as the column definition
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
** the copy. The copy of the Table structure is deleted by tokenize.c
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
        static void sqlite3AlterBeginAddColumn(Parse pParse, SrcList pSrc)
        {
            Table   pNew;
            Table   pTab;
            Vdbe    v;
            int     iDb;
            int     i;
            int     nAlloc;
            sqlite3 db = pParse.db;

            /* Look up the table being altered. */
            Debug.Assert(pParse.pNewTable == null);
            Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
            //	  if ( db.mallocFailed != 0 ) goto exit_begin_add_column;
            pTab = sqlite3LocateTable(pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase);
            if (pTab == null)
            {
                goto exit_begin_add_column;
            }

            if (IsVirtual(pTab))
            {
                sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
                goto exit_begin_add_column;
            }

            /* Make sure this is not an attempt to ALTER a view. */
            if (pTab.pSelect != null)
            {
                sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
                goto exit_begin_add_column;
            }
            if (SQLITE_OK != isSystemTable(pParse, pTab.zName))
            {
                goto exit_begin_add_column;
            }

            Debug.Assert(pTab.addColOffset > 0);
            iDb = sqlite3SchemaToIndex(db, pTab.pSchema);

            /* Put a copy of the Table struct in Parse.pNewTable for the
            ** sqlite3AddColumn() function and friends to modify.  But modify
            ** the name by adding an "sqlite_altertab_" prefix.  By adding this
            ** prefix, we insure that the name will not collide with an existing
            ** table because user table are not allowed to have the "sqlite_"
            ** prefix on their name.
            */
            pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table))
            if (pNew == null)
            {
                goto exit_begin_add_column;
            }
            pParse.pNewTable = pNew;
            pNew.nRef        = 1;
            pNew.nCol        = pTab.nCol;
            Debug.Assert(pNew.nCol > 0);
            nAlloc = (((pNew.nCol - 1) / 8) * 8) + 8;
            Debug.Assert(nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8);
            pNew.aCol  = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc );
            pNew.zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab.zName);
            if (pNew.aCol == null || pNew.zName == null)
            {
                //		db.mallocFailed = 1;
                goto exit_begin_add_column;
            }
            // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol );
            for (i = 0; i < pNew.nCol; i++)
            {
                Column pCol = pTab.aCol[i].Copy();
                // sqlite3DbStrDup( db, pCol.zName );
                pCol.zColl   = null;
                pCol.zType   = null;
                pCol.pDflt   = null;
                pCol.zDflt   = null;
                pNew.aCol[i] = pCol;
            }
            pNew.pSchema      = db.aDb[iDb].pSchema;
            pNew.addColOffset = pTab.addColOffset;
            pNew.nRef         = 1;

            /* Begin a transaction and increment the schema cookie.  */
            sqlite3BeginWriteOperation(pParse, 0, iDb);
            v = sqlite3GetVdbe(pParse);
            if (v == null)
            {
                goto exit_begin_add_column;
            }
            sqlite3ChangeCookie(pParse, iDb);

exit_begin_add_column:
            sqlite3SrcListDelete(db, ref pSrc);
            return;
        }
Esempio n. 53
0
    private void LoadData(bool excel)
    {
        if (divTabel.Visible == true)
        {
            using (DataClassesDatabaseDataContext db = new DataClassesDatabaseDataContext())
            {
                #region DEFAULT
                TextBoxTanggalAwal.Text  = ((DateTime)ViewState["TanggalAwal"]).ToString("d MMMM yyyy");
                TextBoxTanggalAkhir.Text = ((DateTime)ViewState["TanggalAkhir"]).ToString("d MMMM yyyy");

                if (ViewState["TanggalAwal"].ToString() == ViewState["TanggalAkhir"].ToString())
                {
                    LabelPeriode.Text = ViewState["TanggalAwal"].ToFormatTanggal();
                }
                else
                {
                    LabelPeriode.Text = ViewState["TanggalAwal"].ToFormatTanggal() + " - " + ViewState["TanggalAkhir"].ToFormatTanggal();
                }

                string Pencarian = "";
                #endregion

                var DataJenisPembayaran = db.TBTransaksiJenisPembayarans
                                          .Where(item =>
                                                 item.TBTransaksi.IDStatusTransaksi == (int)EnumStatusTransaksi.Complete &&
                                                 item.Tanggal.Value.Date >= (DateTime)ViewState["TanggalAwal"] &&
                                                 item.Tanggal.Value.Date <= (DateTime)ViewState["TanggalAkhir"])
                                          .ToArray();

                Pencarian += "?Awal=" + ViewState["TanggalAwal"];
                Pencarian += "&Akhir=" + ViewState["TanggalAkhir"];

                #region FILTER
                if (DropDownListTempat.SelectedValue != "0")
                {
                    DataJenisPembayaran = DataJenisPembayaran
                                          .Where(item => item.TBTransaksi.IDTempat == DropDownListTempat.SelectedValue.ToInt()).ToArray();

                    Pencarian += "&IDTempat=" + DropDownListTempat.SelectedValue;
                }

                if (DropDownListJenisTransaksi.SelectedValue != "0")
                {
                    DataJenisPembayaran = DataJenisPembayaran
                                          .Where(item => item.TBTransaksi.IDJenisTransaksi == DropDownListJenisTransaksi.SelectedValue.ToInt()).ToArray();

                    Pencarian += "&IDJenisPembayaran=" + DropDownListJenisTransaksi.SelectedValue;
                }
                #endregion

                var ListJenisPembayaran = DataJenisPembayaran
                                          .GroupBy(item => new
                {
                    IDJenisPembayaran = item.IDJenisPembayaran,
                    Tanggal           = item.Tanggal.Value.Date
                })
                                          .Select(item => new
                {
                    Key   = item.Key,
                    Total = item.Sum(item2 => item2.Total)
                });

                //ButtonPrint.OnClientClick = "return popitup('JenisPembayaranPrint.aspx" + _tempPencarian + "')";

                JenisPembayaran_Class ClassJenisPembayaran = new JenisPembayaran_Class(db);
                var JenisPembayaran = ClassJenisPembayaran.Data();

                #region USER INTERFACE
                LiteralHeaderTabel.Text = string.Empty;
                LiteralLaporan.Text     = string.Empty;

                foreach (var item in JenisPembayaran)
                {
                    LiteralHeaderTabel.Text += "<th class='text-right'>" + item.Nama + "</th>";
                }

                LiteralHeaderTabel.Text += "<th class='text-right'>TOTAL</th>";

                int index = 1;

                #region SUMARY
                string JumlahTotal = string.Empty;
                JumlahTotal += "<tr>";
                JumlahTotal += "<td class='text-right' colspan='3'></td>";

                foreach (var item in JenisPembayaran)
                {
                    JumlahTotal += "<td class='text-right table-success' style='font-size: 12px;'><b>" + ListJenisPembayaran.Where(item2 => item2.Key.IDJenisPembayaran == item.IDJenisPembayaran).Sum(item2 => item2.Total).ToFormatHarga() + "</b></td>";
                }

                JumlahTotal += "<td class='text-right table-success' style='font-size: 12px;'><b>" + ListJenisPembayaran.Sum(item2 => item2.Total).ToFormatHarga() + "</b></td>";
                JumlahTotal += "</tr>";

                LiteralLaporan.Text += JumlahTotal;
                #endregion

                #region PERSENTASE
                string  JumlahPersentase = string.Empty;
                decimal GrandTotal       = ListJenisPembayaran.Sum(item => item.Total.Value);

                if (GrandTotal > 0)
                {
                    JumlahPersentase += "<tr>";
                    JumlahPersentase += "<td class='text-right' colspan='3'></td>";

                    decimal TotalPersentase = 0;

                    foreach (var item in JenisPembayaran)
                    {
                        decimal Persentase = ListJenisPembayaran.Where(item2 => item2.Key.IDJenisPembayaran == item.IDJenisPembayaran).Sum(item2 => item2.Total.Value) / GrandTotal * 100;
                        JumlahPersentase += "<td class='text-right table-secondary' style='font-size: 10px;'><b>" + Persentase.ToFormatHarga() + " %</b></td>";

                        TotalPersentase += Persentase;
                    }

                    JumlahPersentase += "<td class='text-right table-secondary' style='font-size: 10px;'><b>" + TotalPersentase.ToFormatHarga() + " %</b></td>";
                    JumlahPersentase += "</tr>";
                }

                LiteralLaporan.Text += JumlahPersentase;
                #endregion

                #region JENIS PEMBAYARAN
                for (DateTime i = (DateTime)ViewState["TanggalAwal"]; i <= (DateTime)ViewState["TanggalAkhir"]; i = i.AddDays(1))
                {
                    LiteralLaporan.Text += "<tr>";

                    LiteralLaporan.Text += "<td>" + index++ + "</td>";
                    LiteralLaporan.Text += "<td>" + i.ToString("dddd") + "</td>";
                    LiteralLaporan.Text += "<td>" + i.ToFormatTanggal() + "</td>";

                    decimal Total = 0;

                    foreach (var item in JenisPembayaran)
                    {
                        var Pembayaran = ListJenisPembayaran.FirstOrDefault(item2 => item2.Key.Tanggal == i.Date && item2.Key.IDJenisPembayaran == item.IDJenisPembayaran);

                        if (Pembayaran != null)
                        {
                            LiteralLaporan.Text += "<td class='text-right'>" + Pembayaran.Total.ToFormatHarga() + "</td>";
                            Total += Pembayaran.Total.Value;
                        }
                        else
                        {
                            LiteralLaporan.Text += "<td></td>";
                        }
                    }

                    LiteralLaporan.Text += "<td class='text-right table-warning'><b>" + (Total > 0 ? Total.ToFormatHarga() : "") + "</b></td>";

                    LiteralLaporan.Text += "</tr>";
                }
                #endregion

                LiteralLaporan.Text += JumlahPersentase;
                LiteralLaporan.Text += JumlahTotal;
                #endregion

                #region EXCEL
                if (excel)
                {
                    PenggunaLogin Pengguna = (PenggunaLogin)Session["PenggunaLogin"];

                    string FileNama   = "Laporan Jenis Pembayaran " + DateTime.Now.ToString("d MMMM yyyy hh.mm.ss") + ".xlsx";
                    string FolderPath = Server.MapPath("~/file_excel/Jenis Pembayaran/Export/");

                    if (!Directory.Exists(FolderPath))
                    {
                        Directory.CreateDirectory(FolderPath);
                    }

                    string FilePath      = FolderPath + FileNama;
                    string WorksheetNama = "Laporan Jenis Pembayaran";
                    string Judul         = "Laporan Jenis Pembayaran " + Pengguna.Store + " - " + Pengguna.Tempat + " " + DateTime.Now.ToString("d MMMM yyyy");

                    FileInfo newFile = new FileInfo(FilePath);

                    using (ExcelPackage package = new ExcelPackage(newFile))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(WorksheetNama);

                        worksheet.Cells[1, 1].Value = "No.";
                        worksheet.Cells[1, 2].Value = "Hari";
                        worksheet.Cells[1, 3].Value = "Tanggal";

                        int Kolom = 4;

                        foreach (var item in JenisPembayaran)
                        {
                            worksheet.Cells[1, Kolom++].Value = item.Nama;
                        }

                        worksheet.Cells[1, Kolom].Value = "TOTAL";

                        index = 2;

                        for (DateTime i = (DateTime)ViewState["TanggalAwal"]; i <= (DateTime)ViewState["TanggalAkhir"]; i = i.AddDays(1))
                        {
                            worksheet.Cells[index, 1].Value = index - 1;
                            worksheet.Cells[index, 1].Style.Numberformat.Format = "@";

                            worksheet.Cells[index, 2].Value = i.ToString("dddd");
                            worksheet.Cells[index, 2].Style.Numberformat.Format = "@";

                            worksheet.Cells[index, 3].Value = i;
                            worksheet.Cells[index, 3].Style.Numberformat.Format = "d MMMM yyyy";

                            decimal Total  = 0;
                            int     index2 = 4;

                            foreach (var item in JenisPembayaran)
                            {
                                var Pembayaran = ListJenisPembayaran.FirstOrDefault(item2 => item2.Key.Tanggal == i.Date && item2.Key.IDJenisPembayaran == item.IDJenisPembayaran);

                                if (Pembayaran != null)
                                {
                                    worksheet.Cells[index, index2].Value = Pembayaran.Total.Value;
                                    if (Pembayaran.Total.Value.ToFormatHarga().Contains(","))
                                    {
                                        worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0.00";
                                    }
                                    else
                                    {
                                        worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0";
                                    }

                                    Total += Pembayaran.Total.Value;
                                }
                                else
                                {
                                    worksheet.Cells[index, index2].Value = 0;
                                    if (Parse.ToFormatHarga(0).Contains(","))
                                    {
                                        worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0.00";
                                    }
                                    else
                                    {
                                        worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0";
                                    }
                                }

                                index2++;
                            }

                            worksheet.Cells[index, index2].Value = Total;
                            if (Total.ToFormatHarga().Contains(","))
                            {
                                worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0.00";
                            }
                            else
                            {
                                worksheet.Cells[index, index2].Style.Numberformat.Format = "#,##0";
                            }

                            index++;
                        }

                        using (var range = worksheet.Cells[1, 1, 1, Kolom])
                        {
                            range.Style.Font.Bold        = true;
                            range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            range.Style.Fill.BackgroundColor.SetColor(Color.Black);
                            range.Style.Font.Color.SetColor(Color.White);
                        }

                        worksheet.Cells.AutoFitColumns(0);

                        worksheet.HeaderFooter.OddHeader.CenteredText    = "&16&\"Tahoma,Regular Bold\"" + Judul;
                        worksheet.HeaderFooter.OddFooter.LeftAlignedText = "Print : " + Pengguna.NamaLengkap + " - " + Pengguna.Tempat + " - " + DateTime.Now.ToString("d MMMM yyyy hh:mm");

                        worksheet.HeaderFooter.OddFooter.RightAlignedText = "WIT. Warehouse Management System - " + string.Format("Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

                        package.Workbook.Properties.Title    = WorksheetNama;
                        package.Workbook.Properties.Author   = "WIT. Warehouse Management System";
                        package.Workbook.Properties.Comments = Judul;

                        package.Workbook.Properties.Company = "WIT. Warehouse Management System";
                        package.Save();
                    }

                    LinkDownload.Visible = true;
                    LinkDownload.HRef    = "/file_excel/Jenis Pembayaran/Export/" + FileNama;
                }
                #endregion
            }
        }
        else if (divChart.Visible == true)
        {
            #region DEFAULT
            TextBoxTanggalAwal.Text  = ((DateTime)ViewState["TanggalAwal"]).ToString("d MMMM yyyy");
            TextBoxTanggalAkhir.Text = ((DateTime)ViewState["TanggalAkhir"]).ToString("d MMMM yyyy");

            if (ViewState["TanggalAwal"].ToString() == ViewState["TanggalAkhir"].ToString())
            {
                LabelPeriode.Text = ViewState["TanggalAwal"].ToFormatTanggal();
            }
            else
            {
                LabelPeriode.Text = ViewState["TanggalAwal"].ToFormatTanggal() + " - " + ViewState["TanggalAkhir"].ToFormatTanggal();
            }
            #endregion

            //Literal LiteralChart = (Literal)Page.Master.FindControl("LiteralChart");
            LiteralChart.Text = string.Empty;

            using (DataClassesDatabaseDataContext db = new DataClassesDatabaseDataContext())
            {
                var DataJenisPembayaran = db.TBTransaksiJenisPembayarans
                                          .Where(item =>
                                                 item.TBTransaksi.IDStatusTransaksi == (int)EnumStatusTransaksi.Complete &&
                                                 item.Tanggal.Value.Date >= (DateTime)ViewState["TanggalAwal"] &&
                                                 item.Tanggal.Value.Date <= (DateTime)ViewState["TanggalAkhir"])
                                          .ToArray();

                #region FILTER
                if (DropDownListTempat.SelectedValue != "0")
                {
                    DataJenisPembayaran = DataJenisPembayaran.Where(item => item.TBTransaksi.IDTempat == DropDownListTempat.SelectedValue.ToInt()).ToArray();
                }

                if (DropDownListJenisTransaksi.SelectedValue != "0")
                {
                    DataJenisPembayaran = DataJenisPembayaran.Where(item => item.TBTransaksi.IDJenisTransaksi == DropDownListJenisTransaksi.SelectedValue.ToInt()).ToArray();
                }
                #endregion

                var JenisPembayaran = DataJenisPembayaran
                                      .GroupBy(item => new
                {
                    item.IDJenisPembayaran,
                    item.TBJenisPembayaran.Nama
                })
                                      .Select(item => new
                {
                    item.Key,
                    Total = item.Sum(item2 => item2.Total)
                })
                                      .OrderByDescending(item => item.Total)
                                      .ToArray();

                int Height = JenisPembayaran.Count() * 30;
                divChart.Attributes.Add("style", "width: auto; height: " + (Height > 600 ? Height : 600) + "px; margin: 0 auto;");

                string Judul    = "";
                string SubJudul = "";
                string JudulX   = "Jenis Pembayaran";
                string DataX    = "";

                string JudulY = "Total Jenis Pembayaran";

                string DataY   = "";
                string Tooltip = "";

                foreach (var item in JenisPembayaran)
                {
                    DataX += "'" + item.Key.Nama + "',";
                    DataY += item.Total + ",";
                }

                LiteralChart.Text += "<script type=\"text/javascript\">";
                LiteralChart.Text += "$(function () { $('#divChart').highcharts({";
                LiteralChart.Text += "        chart: { type: 'bar' },";
                LiteralChart.Text += "        title: { text: '" + Judul + "' },";
                LiteralChart.Text += "        subtitle: { text: '" + SubJudul + "' },";
                LiteralChart.Text += "        xAxis: { categories: [" + DataX + "] },";
                LiteralChart.Text += "        yAxis: { min: 0, title: { text: '" + JudulY + "' } },";
                LiteralChart.Text += "        tooltip: { valueSuffix: '" + Tooltip + "' },";
                LiteralChart.Text += "        legend: { reversed: true },";
                LiteralChart.Text += "        plotOptions: { series: { stacking: 'normal' } },";
                LiteralChart.Text += "        credits: { enabled: false },";
                LiteralChart.Text += "        exporting: { enabled: false },";
                LiteralChart.Text += "        series: [";
                LiteralChart.Text += "		{";
                LiteralChart.Text += "            name: '" + JudulX + "',";
                LiteralChart.Text += "            data: [" + DataY + "]";
                LiteralChart.Text += "        },";
                LiteralChart.Text += "		]";
                LiteralChart.Text += "    }); });";
                LiteralChart.Text += "</script>";
            }
        }
    }
Esempio n. 54
0
/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
** command.
*/
        static void sqlite3AlterRenameTable(
            Parse pParse,        /* Parser context. */
            SrcList pSrc,        /* The table to rename. */
            Token pName          /* The new table name. */
            )
        {
            int     iDb;               /* Database that contains the table */
            string  zDb;               /* Name of database iDb */
            Table   pTab;              /* Table being renamed */
            string  zName = null;      /* NULL-terminated version of pName */
            sqlite3 db    = pParse.db; /* Database connection */
            int     nTabName;          /* Number of UTF-8 characters in zTabName */
            string  zTabName;          /* Original name of the table */
            Vdbe    v;

#if !SQLITE_OMIT_TRIGGER
            string zWhere = "";  /* Where clause to locate temp triggers */
#endif
            VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */
            int    savedDbFlags; /* Saved value of db->flags */

            savedDbFlags = db.flags;

            //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table;
            Debug.Assert(pSrc.nSrc == 1);
            Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
            pTab = sqlite3LocateTable(pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase);
            if (pTab == null)
            {
                goto exit_rename_table;
            }
            iDb       = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
            zDb       = db.aDb[iDb].zName;
            db.flags |= SQLITE_PreferBuiltin;

            /* Get a NULL terminated version of the new table name. */
            zName = sqlite3NameFromToken(db, pName);
            if (zName == null)
            {
                goto exit_rename_table;
            }

            /* Check that a table or index named 'zName' does not already exist
            ** in database iDb. If so, this is an error.
            */
            if (sqlite3FindTable(db, zName, zDb) != null || sqlite3FindIndex(db, zName, zDb) != null)
            {
                sqlite3ErrorMsg(pParse,
                                "there is already another table or index with this name: %s", zName);
                goto exit_rename_table;
            }

            /* Make sure it is not a system table being altered, or a reserved name
            ** that the table is being renamed to.
            */
            if (SQLITE_OK != isSystemTable(pParse, pTab.zName))
            {
                goto exit_rename_table;
            }
            if (SQLITE_OK != sqlite3CheckObjectName(pParse, zName))
            {
                goto exit_rename_table;
            }

#if !SQLITE_OMIT_VIEW
            if (pTab.pSelect != null)
            {
                sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab.zName);
                goto exit_rename_table;
            }
#endif

#if !SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
            if (sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0))
            {
                goto exit_rename_table;
            }
#endif

            if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
            {
                goto exit_rename_table;
            }
#if !SQLITE_OMIT_VIRTUALTABLE
            if (IsVirtual(pTab))
            {
                pVTab = sqlite3GetVTable(db, pTab);
                if (pVTab.pVtab.pModule.xRename == null)
                {
                    pVTab = null;
                }
            }
#endif

            /* Begin a transaction and code the VerifyCookie for database iDb.
            ** Then modify the schema cookie (since the ALTER TABLE modifies the
            ** schema). Open a statement transaction if the table is a virtual
            ** table.
            */
            v = sqlite3GetVdbe(pParse);
            if (v == null)
            {
                goto exit_rename_table;
            }
            sqlite3BeginWriteOperation(pParse, pVTab != null ? 1 : 0, iDb);
            sqlite3ChangeCookie(pParse, iDb);

            /* If this is a virtual table, invoke the xRename() function if
            ** one is defined. The xRename() callback will modify the names
            ** of any resources used by the v-table implementation (including other
            ** SQLite tables) that are identified by the name of the virtual table.
            */
#if  !SQLITE_OMIT_VIRTUALTABLE
            if (pVTab != null)
            {
                int i = ++pParse.nMem;
                sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
                sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0, pVTab, P4_VTAB);
                sqlite3MayAbort(pParse);
            }
#endif

            /* figure out how many UTF-8 characters are in zName */
            zTabName = pTab.zName;
            nTabName = sqlite3Utf8CharLen(zTabName, -1);

#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
            if ((db.flags & SQLITE_ForeignKeys) != 0)
            {
                /* If foreign-key support is enabled, rewrite the CREATE TABLE
                ** statements corresponding to all child tables of foreign key constraints
                ** for which the renamed table is the parent table.  */
                if ((zWhere = whereForeignKeys(pParse, pTab)) != null)
                {
                    sqlite3NestedParse(pParse,
                                       "UPDATE \"%w\".%s SET " +
                                       "sql = sqlite_rename_parent(sql, %Q, %Q) " +
                                       "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
                    sqlite3DbFree(db, ref zWhere);
                }
            }
#endif

            /* Modify the sqlite_master table to use the new table name. */
            sqlite3NestedParse(pParse,
                               "UPDATE %Q.%s SET " +
#if SQLITE_OMIT_TRIGGER
                               "sql = sqlite_rename_table(sql, %Q), " +
#else
                               "sql = CASE " +
                               "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" +
                               "ELSE sqlite_rename_table(sql, %Q) END, " +
#endif
                               "tbl_name = %Q, " +
                               "name = CASE " +
                               "WHEN type='table' THEN %Q " +
                               "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " +
                               "'sqlite_autoindex_' || %Q || substr(name,%d+18) " +
                               "ELSE name END " +
                               "WHERE tbl_name=%Q AND " +
                               "(type='table' OR type='index' OR type='trigger');",
                               zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
#if !SQLITE_OMIT_TRIGGER
                               zName,
#endif
                               zName, nTabName, zTabName
                               );

#if !SQLITE_OMIT_AUTOINCREMENT
            /* If the sqlite_sequence table exists in this database, then update
            ** it with the new table name.
            */
            if (sqlite3FindTable(db, "sqlite_sequence", zDb) != null)
            {
                sqlite3NestedParse(pParse,
                                   "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
                                   zDb, zName, pTab.zName
                                   );
            }
#endif

#if !SQLITE_OMIT_TRIGGER
            /* If there are TEMP triggers on this table, modify the sqlite_temp_master
            ** table. Don't do this if the table being ALTERed is itself located in
            ** the temp database.
            */
            if ((zWhere = whereTempTriggers(pParse, pTab)) != "")
            {
                sqlite3NestedParse(pParse,
                                   "UPDATE sqlite_temp_master SET " +
                                   "sql = sqlite_rename_trigger(sql, %Q), " +
                                   "tbl_name = %Q " +
                                   "WHERE %s;", zName, zName, zWhere);
                sqlite3DbFree(db, ref zWhere);
            }
#endif

#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
            if ((db.flags & SQLITE_ForeignKeys) != 0)
            {
                FKey p;
                for (p = sqlite3FkReferences(pTab); p != null; p = p.pNextTo)
                {
                    Table pFrom = p.pFrom;
                    if (pFrom != pTab)
                    {
                        reloadTableSchema(pParse, p.pFrom, pFrom.zName);
                    }
                }
            }
#endif

            /* Drop and reload the internal table schema. */
            reloadTableSchema(pParse, pTab, zName);

exit_rename_table:
            sqlite3SrcListDelete(db, ref pSrc);
            sqlite3DbFree(db, ref zName);
            db.flags = savedDbFlags;
        }
Esempio n. 55
0
        private void SaveDailyOrHour(
            List <Symbol> symbols,
            Symbol canonicalSymbol,
            IReadOnlyDictionary <Symbol, List <BaseData> > historyBySymbol)
        {
            var zipFileName = Path.Combine(
                _dataDirectory,
                LeanData.GenerateRelativeZipFilePath(canonicalSymbol, DateTime.MinValue, _resolution, _tickType));

            var folder = Path.GetDirectoryName(zipFileName);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            using (var zip = new ZipFile(zipFileName))
            {
                foreach (var symbol in symbols)
                {
                    // Load new data rows into a SortedDictionary for easy merge/update
                    var newRows = new SortedDictionary <DateTime, string>(historyBySymbol[symbol]
                                                                          .ToDictionary(x => x.Time, x => LeanData.GenerateLine(x, _securityType, _resolution)));

                    var rows = new SortedDictionary <DateTime, string>();

                    var zipEntryName = LeanData.GenerateZipEntryName(symbol, DateTime.MinValue, _resolution, _tickType);

                    if (zip.ContainsEntry(zipEntryName))
                    {
                        // If file exists, we load existing data and perform merge
                        using (var stream = new MemoryStream())
                        {
                            zip[zipEntryName].Extract(stream);
                            stream.Seek(0, SeekOrigin.Begin);

                            using (var reader = new StreamReader(stream))
                            {
                                string line;
                                while ((line = reader.ReadLine()) != null)
                                {
                                    var time = Parse.DateTimeExact(line.Substring(0, DateFormat.TwelveCharacter.Length), DateFormat.TwelveCharacter);
                                    rows[time] = line;
                                }
                            }
                        }

                        foreach (var kvp in newRows)
                        {
                            rows[kvp.Key] = kvp.Value;
                        }
                    }
                    else
                    {
                        // No existing file, just use the new data
                        rows = newRows;
                    }

                    // Loop through the SortedDictionary and write to zip entry
                    var sb = new StringBuilder();
                    foreach (var kvp in rows)
                    {
                        // Build the line and append it to the file
                        sb.AppendLine(kvp.Value);
                    }

                    // Write the zip entry
                    if (sb.Length > 0)
                    {
                        if (zip.ContainsEntry(zipEntryName))
                        {
                            zip.RemoveEntry(zipEntryName);
                        }

                        zip.AddEntry(zipEntryName, sb.ToString());
                    }
                }

                if (zip.Count > 0)
                {
                    zip.Save();
                }
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Parses file name into a <see cref="Security"/> and DateTime
        /// </summary>
        /// <param name="fileName">File name to be parsed</param>
        /// <param name="symbol">The symbol as parsed from the fileName</param>
        /// <param name="date">Date of data in the file path. Only returned if the resolution is lower than Hourly</param>
        /// <param name="resolution">The resolution of the symbol as parsed from the filePath</param>
        public static bool TryParsePath(string fileName, out Symbol symbol, out DateTime date, out Resolution resolution)
        {
            symbol     = null;
            resolution = Resolution.Daily;
            date       = default(DateTime);

            var pathSeparators = new[] { '/', '\\' };

            try
            {
                // Removes file extension
                fileName = fileName.Replace(fileName.GetExtension(), "");

                // remove any relative file path
                while (fileName.First() == '.' || pathSeparators.Any(x => x == fileName.First()))
                {
                    fileName = fileName.Remove(0, 1);
                }

                // split path into components
                var info = fileName.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries).ToList();

                // find where the useful part of the path starts - i.e. the securityType
                var startIndex = info.FindIndex(x => SecurityTypeAsDataPath.Contains(x.ToLowerInvariant()));

                var securityType = ParseDataSecurityType(info[startIndex]);

                var    market = Market.USA;
                string ticker;
                if (securityType == SecurityType.Base)
                {
                    if (!Enum.TryParse(info[startIndex + 2], true, out resolution))
                    {
                        resolution = Resolution.Daily;
                    }

                    // the last part of the path is the file name
                    var fileNameNoPath = info[info.Count - 1].Split('_').First();

                    if (!DateTime.TryParseExact(fileNameNoPath,
                                                DateFormat.EightCharacter,
                                                DateTimeFormatInfo.InvariantInfo,
                                                DateTimeStyles.None,
                                                out date))
                    {
                        // if parsing the date failed we assume filename is ticker
                        ticker = fileNameNoPath;
                    }
                    else
                    {
                        // ticker must be the previous part of the path
                        ticker = info[info.Count - 2];
                    }
                }
                else
                {
                    resolution = (Resolution)Enum.Parse(typeof(Resolution), info[startIndex + 2], true);

                    // Gather components used to create the security
                    market = info[startIndex + 1];
                    ticker = info[startIndex + 3];

                    // If resolution is Daily or Hour, we do not need to set the date and tick type
                    if (resolution < Resolution.Hour)
                    {
                        date = Parse.DateTimeExact(info[startIndex + 4].Substring(0, 8), DateFormat.EightCharacter);
                    }

                    if (securityType == SecurityType.Crypto)
                    {
                        ticker = ticker.Split('_').First();
                    }
                }

                symbol = Symbol.Create(ticker, securityType, market);
            }
            catch (Exception ex)
            {
                Log.Error($"LeanData.TryParsePath(): Error encountered while parsing the path {fileName}. Error: {ex.GetBaseException()}");
                return(false);
            }

            return(true);
        }
Esempio n. 57
0
/*
** Generate an expression tree to implement the WHERE, ORDER BY,
** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
**
**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
**                            \__________________________/
**                               pLimitWhere (pInClause)
*/
        Expr sqlite3LimitWhere(
            Parse pParse,      /* The parser context */
            SrcList pSrc,      /* the FROM clause -- which tables to scan */
            Expr pWhere,       /* The WHERE clause.  May be null */
            ExprList pOrderBy, /* The ORDER BY clause.  May be null */
            Expr pLimit,       /* The LIMIT clause.  May be null */
            Expr pOffset,      /* The OFFSET clause.  May be null */
            char zStmtType     /* Either DELETE or UPDATE.  For error messages. */
            )
        {
            Expr     pWhereRowid  = null; /* WHERE rowid .. */
            Expr     pInClause    = null; /* WHERE rowid IN ( select ) */
            Expr     pSelectRowid = null; /* SELECT rowid ... */
            ExprList pEList       = null; /* Expression list contaning only pSelectRowid */
            SrcList  pSelectSrc   = null; /* SELECT rowid FROM x ... (dup of pSrc) */
            Select   pSelect      = null; /* Complete SELECT tree */

/* Check that there isn't an ORDER BY without a LIMIT clause.
 */

            if (pOrderBy != null && (pLimit == null))
            {
                sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
                pParse.parseError = 1;
                goto limit_where_cleanup_2;
            }

/* We only need to generate a select expression if there
** is a limit/offset term to enforce.
*/
            if (pLimit == null)
            {
/* if pLimit is null, pOffset will always be null as well. */
                Debug.Assert(pOffset == null);
                return(pWhere);
            }

/* Generate a select expression tree to enforce the limit/offset
** term for the DELETE or UPDATE statement.  For example:
**   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** becomes:
**   DELETE FROM table_a WHERE rowid IN (
**     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
**   );
*/

            pSelectRowid = sqlite3PExpr(pParse, TK_ROW, null, null, null);
            if (pSelectRowid == null)
            {
                goto limit_where_cleanup_2;
            }
            pEList = sqlite3ExprListAppend(pParse, null, pSelectRowid);
            if (pEList == null)
            {
                goto limit_where_cleanup_2;
            }

/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
** and the SELECT subtree. */
            pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc, 0);
            if (pSelectSrc == null)
            {
                sqlite3ExprListDelete(pParse.db, pEList);
                goto limit_where_cleanup_2;
            }

/* generate the SELECT expression tree. */
            pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, null, null,
                                       pOrderBy, 0, pLimit, pOffset);
            if (pSelect == null)
            {
                return(null);
            }

/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
            pWhereRowid = sqlite3PExpr(pParse, TK_ROW, null, null, null);
            if (pWhereRowid == null)
            {
                goto limit_where_cleanup_1;
            }
            pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, null, null);
            if (pInClause == null)
            {
                goto limit_where_cleanup_1;
            }

            pInClause->x.pSelect = pSelect;
            pInClause->flags    |= EP_xIsSelect;
            sqlite3ExprSetHeight(pParse, pInClause);
            return(pInClause);

/* something went wrong. clean up anything allocated. */
limit_where_cleanup_1:
            sqlite3SelectDelete(pParse.db, pSelect);
            return(null);

limit_where_cleanup_2:
            sqlite3ExprDelete(pParse.db, ref pWhere);
            sqlite3ExprListDelete(pParse.db, pOrderBy);
            sqlite3ExprDelete(pParse.db, ref pLimit);
            sqlite3ExprDelete(pParse.db, ref pOffset);
            return(null);
        }
Esempio n. 58
0
        /*
        ** Generate code for a DELETE FROM statement.
        **
        **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
        **                 \________/       \________________/
        **                  pTabList              pWhere
        */
        static void sqlite3DeleteFrom(
            Parse pParse,     /* The parser context */
            SrcList pTabList, /* The table from which we should delete things */
            Expr pWhere       /* The WHERE clause.  May be null */
            )
        {
            Vdbe        v;             /* The virtual database engine */
            Table       pTab;          /* The table from which records will be deleted */
            string      zDb;           /* Name of database holding pTab */
            int         end, addr = 0; /* A couple addresses of generated code */
            int         i;             /* Loop counter */
            WhereInfo   pWInfo;        /* Information about the WHERE clause */
            Index       pIdx;          /* For looping over indices of the table */
            int         iCur;          /* VDBE VdbeCursor number for pTab */
            sqlite3     db;            /* Main database structure */
            AuthContext sContext;      /* Authorization context */
            NameContext sNC;           /* Name context to resolve expressions in */
            int         iDb;           /* Database number */
            int         memCnt = -1;   /* Memory cell used for change counting */
            int         rcauth;        /* Value returned by authorization callback */

#if !SQLITE_OMIT_TRIGGER
            bool    isView;               /* True if attempting to delete from a view */
            Trigger pTrigger;             /* List of table triggers, if required */
#endif
            sContext = new AuthContext(); //memset(&sContext, 0, sizeof(sContext));

            db = pParse.db;
            if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */)
            {
                goto delete_from_cleanup;
            }
            Debug.Assert(pTabList.nSrc == 1);

            /* Locate the table which we want to delete.  This table has to be
            ** put in an SrcList structure because some of the subroutines we
            ** will be calling are designed to work with multiple tables and expect
            ** an SrcList* parameter instead of just a Table* parameter.
            */
            pTab = sqlite3SrcListLookup(pParse, pTabList);
            if (pTab == null)
            {
                goto delete_from_cleanup;
            }

            /* Figure out if we have any triggers and if the table being
            ** deleted from is a view
            */
#if !SQLITE_OMIT_TRIGGER
            int iDummy = 0;
            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, null, ref iDummy);
            isView   = pTab.pSelect != null;
#else
            const Trigger pTrigger = null;
            bool          isView   = false;
#endif
#if SQLITE_OMIT_VIEW
//# undef isView
            isView = false;
#endif

            /* If pTab is really a view, make sure it has been initialized.
             */
            if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
            {
                goto delete_from_cleanup;
            }

            if (sqlite3IsReadOnly(pParse, pTab, (pTrigger != null ? 1 : 0)))
            {
                goto delete_from_cleanup;
            }
            iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
            Debug.Assert(iDb < db.nDb);
            zDb = db.aDb[iDb].zName;
#if !SQLITE_OMIT_AUTHORIZATION
            rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
#else
            rcauth = SQLITE_OK;
#endif
            Debug.Assert(rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE);
            if (rcauth == SQLITE_DENY)
            {
                goto delete_from_cleanup;
            }
            Debug.Assert(!isView || pTrigger != null);

            /* Assign  cursor number to the table and all its indices.
             */
            Debug.Assert(pTabList.nSrc == 1);
            iCur = pTabList.a[0].iCursor = pParse.nTab++;
            for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
            {
                pParse.nTab++;
            }

#if !SQLITE_OMIT_AUTHORIZATION
/* Start the view context
 */
            if (isView)
            {
                sqlite3AuthContextPush(pParse, sContext, pTab.zName);
            }
#endif

            /* Begin generating code.
             */
            v = sqlite3GetVdbe(pParse);
            if (v == null)
            {
                goto delete_from_cleanup;
            }
            if (pParse.nested == 0)
            {
                sqlite3VdbeCountChanges(v);
            }
            sqlite3BeginWriteOperation(pParse, 1, iDb);

            /* If we are trying to delete from a view, realize that view into
            ** a ephemeral table.
            */
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
            if (isView)
            {
                sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
            }
#endif

            /* Resolve the column names in the WHERE clause.
             */
            sNC          = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
            sNC.pParse   = pParse;
            sNC.pSrcList = pTabList;
            if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0)
            {
                goto delete_from_cleanup;
            }


            /* Initialize the counter of the number of rows deleted, if
            ** we are counting rows.
            */
            if ((db.flags & SQLITE_CountRows) != 0)
            {
                memCnt = ++pParse.nMem;
                sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
            }

#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION
            /* Special case: A DELETE without a WHERE clause deletes everything.
            ** It is easier just to erase the whole table. Prior to version 3.6.5,
            ** this optimization caused the row change count (the value returned by
            ** API function sqlite3_count_changes) to be set incorrectly.  */
            if (rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual(pTab) &&
                0 == sqlite3FkRequired(pParse, pTab, null, 0)
                )
            {
                Debug.Assert(!isView);
                sqlite3VdbeAddOp4(v, OP_Clear, pTab.tnum, iDb, memCnt,
                                  pTab.zName, P4_STATIC);
                for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
                {
                    Debug.Assert(pIdx.pSchema == pTab.pSchema);
                    sqlite3VdbeAddOp2(v, OP_Clear, pIdx.tnum, iDb);
                }
            }
            else
#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */

            /* The usual case: There is a WHERE clause so we have to scan through
            ** the table and pick which records to delete.
            */
            {
                int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
                int iRowid  = ++pParse.nMem; /* Used for storing rowid values. */
                int regRowid;                /* Actual register containing rowids */

                /* Collect rowids of every row to be deleted.
                 */
                sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
                ExprList elDummy = null;
                pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK);
                if (pWInfo == null)
                {
                    goto delete_from_cleanup;
                }
                regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
                sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
                if ((db.flags & SQLITE_CountRows) != 0)
                {
                    sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
                }

                sqlite3WhereEnd(pWInfo);

                /* Delete every item whose key was written to the list during the
                ** database scan.  We have to delete items after the scan is complete
                ** because deleting an item can change the scan order. */
                end = sqlite3VdbeMakeLabel(v);

                /* Unless this is a view, open cursors for the table we are
                ** deleting from and all its indices. If this is a view, then the
                ** only effect this statement has is to fire the INSTEAD OF
                ** triggers.  */
                if (!isView)
                {
                    sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
                }

                addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);

                /* Delete the row */
#if !SQLITE_OMIT_VIRTUALTABLE
                if (IsVirtual(pTab))
                {
                    const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
                    sqlite3VtabMakeWritable(pParse, pTab);
                    sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
                    sqlite3MayAbort(pParse);
                }
                else
#endif
                {
                    int count = (pParse.nested == 0) ? 1 : 0; /* True to count changes */
                    sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
                }

                /* End of the delete loop */
                sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
                sqlite3VdbeResolveLabel(v, end);

                /* Close the cursors open on the table and its indexes. */
                if (!isView && !IsVirtual(pTab))
                {
                    for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext)
                    {
                        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx.tnum);
                    }
                    sqlite3VdbeAddOp1(v, OP_Close, iCur);
                }
            }

            /* Update the sqlite_sequence table by storing the content of the
            ** maximum rowid counter values recorded while inserting into
            ** autoincrement tables.
            */
            if (pParse.nested == 0 && pParse.pTriggerTab == null)
            {
                sqlite3AutoincrementEnd(pParse);
            }

            /* Return the number of rows that were deleted. If this routine is
            ** generating code because of a call to sqlite3NestedParse(), do not
            ** invoke the callback function.
            */

            if ((db.flags & SQLITE_CountRows) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab)
            {
                sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
                sqlite3VdbeSetNumCols(v, 1);
                sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
            }

delete_from_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
            sqlite3AuthContextPop(sContext);
#endif
            sqlite3SrcListDelete(db, ref pTabList);
            sqlite3ExprDelete(db, ref pWhere);
            return;
        }
Esempio n. 59
0
 private static Parser <SgfTree> Tree() =>
 from open in Parse.Char('(')
 from nodes in Node().Many()
 from children in Tree().Many()
 from close in Parse.Char(')')
 select NodesToTree(nodes, children);
 public override void DoRow(Parse row)
 {
     base.DoRow(row);
     EnterRow();
 }