Example #1
0
        public async Task <IActionResult> Post([FromBody] Ruling ruling)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                if (!AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditCardRuling))
                {
                    return(Forbid("You are not allowed to create rulings."));
                }

                if (ruling.Card == null)
                {
                    return(BadRequest("The card is required."));
                }

                if (string.IsNullOrWhiteSpace(ruling.RuleText))
                {
                    return(BadRequest("The rule text is required."));
                }

                var cardModel = await repository.Context.Cards.FindByGuidAsync(ruling.Card.Guid);

                if (cardModel == null)
                {
                    return(BadRequest("The card is not found."));
                }

                var ruleModel = repository.CreateRuling(cardModel, ruling.RuleText, Guid.NewGuid());
                await repository.Context.SaveChangesAsync();

                return(Ok(ruleModel.FromDal()));
            }
        }
Example #2
0
        public void ContructorTest()
        {
            Ruling model;

            try
            {
                // Test exception is thrown.
                model = new Ruling(null);
                Assert.Fail();
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual("item", ex.ParamName);
            }
            catch
            {
                Assert.Fail();
            }

            var dto = new RulingDto()
            {
                Date = "2016, 10, 2",
                Text = "testing"
            };

            model = new Ruling(dto);

            Assert.AreEqual(dto.Date, model.Date);
            Assert.AreEqual(dto.Text, model.Text);
        }
Example #3
0
        public void TestAlmostIntersectingRulingsShouldIntersect()
        {
            Ruling v = new Ruling(new PdfPoint(555.960876f, 271.569641f), new PdfPoint(555.960876f, 786.899902f));
            Ruling h = new Ruling(new PdfPoint(25.620499f, 786.899902f), new PdfPoint(555.960754f, 786.899902f));
            SortedDictionary <PdfPoint, Ruling[]> m = Ruling.FindIntersections(new Ruling[] { h }.ToList(), new Ruling[] { v }.ToList());

            Assert.Single(m.Values);
        }
Example #4
0
        public override bool SetRuleSet(Ruling.RuleSet rules)
        {
            if (rules.MultipleShoots)
                return false;
            if (rules.Size.Depth != 1)
                return false;

            return base.SetRuleSet(rules);
        }
        private void InsertInReferential(Ruling ruling)
        {
            if (_cardsbyId.GetOrDefault(ruling.IdCard) is not Card card)
            {
                throw new ApplicationDbException("Can't find card with id " + ruling.IdCard);
            }

            card.AddRuling(ruling);

            _cacheForAllDbInfos = null;
        }
Example #6
0
        public static void Patch(this RulingModel rulingModel, Ruling ruling, CardModel cardModel, UserModel user)
        {
            if (rulingModel == null)
            {
                return;
            }
            rulingModel.RuleText = ruling.RuleText;

            if (cardModel != null)
            {
                rulingModel.Card = cardModel;
            }
            rulingModel.PatchBase(user);
        }
Example #7
0
        public static Ruling FromDal(this RulingModel rulingModel)
        {
            if (rulingModel == null)
            {
                return(null);
            }
            var result = new Ruling()
            {
                Guid     = rulingModel.Guid,
                Id       = rulingModel.RulingId,
                RuleText = rulingModel.RuleText,
                Card     = rulingModel.Card?.FromDal()
            };

            result.SyncBase(rulingModel, true, true);
            return(result);
        }
        public void InsertNewRuling(int idGatherer, DateTime addDate, string text)
        {
            ICard card = GetCard(idGatherer);

            if (card == null || string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            using (new WriterLock(_lock))
            {
                if (!card.HasRuling(addDate, text))
                {
                    Ruling ruling = new Ruling {
                        IdCard = card.Id, AddDate = addDate, Text = text
                    };
                    AddToDbAndUpdateReferential(ruling, InsertInReferential);
                }
            }
        }
Example #9
0
 public static RulingModel GetRulingModel(Ruling ruling, RulingSource rulingSource, RulingType rulingType, CardType cardType)
 {
     return(new RulingModel()
     {
         RulingId = ruling.RulingId,
         RulingType = RulingTypeService.GetRulingSourceModel(rulingType),
         RulingSource = RulingSourceService.GetRulingSourceModel(rulingSource),
         CardType = cardType == null ? null : TypeService.GetCardTypeModel(cardType),
         Question = ruling.Question,
         Answer = ruling.Answer,
         Ruling = ruling.Ruling1,
         GeneralInfo = ruling.GeneralInfo,
         RulingDate = ruling.RulingDate,
         LanguageId = ruling.LanguageId,
         CreatedById = ruling.CreatedById,
         CreatedDate = ruling.CreatedDate,
         UpdatedById = ruling.UpdatedById,
         UpdatedDate = ruling.UpdatedDate
     });
 }
Example #10
0
        public async Task <IActionResult> Patch(Guid id, [FromBody] Ruling ruling)
        {
            using (var repository = new Repository(HttpContext.GetUserGuid()))
            {
                if (!AuthorizeService.HashRight(repository.ServiceUser?.Role, Rights.EditCardRuling))
                {
                    return(Forbid("You are not allowed to change rulings."));
                }

                if (string.IsNullOrWhiteSpace(ruling.RuleText))
                {
                    return(BadRequest("The rule text is required."));
                }

                var rulingModel = await repository.Context.Rulings
                                  .Include(x => x.Card)
                                  .Include(x => x.Creator)
                                  .Include(x => x.LastModifiedBy)
                                  .Where(x => x.Guid == id).FirstOrDefaultAsync();

                if (rulingModel == null)
                {
                    return(NotFound());
                }

                CardModel cardModel = null;
                if (ruling.Card != null)
                {
                    cardModel = await repository.Context.Cards.FindByGuidAsync(ruling.Card.Guid);
                }

                rulingModel.Patch(ruling, cardModel, repository.ServiceUser);
                ruling = rulingModel.FromDal();

                await repository.Context.SaveChangesAsync();

                return(Ok(ruling));
            }
        }
Example #11
0
        public bool UpdateCardRulings(Guid authToken, int mvid, Ruling[] rulings)
        {
            bool end = false;

            System.Collections.Specialized.NameValueCollection reqparm = 
                new System.Collections.Specialized.NameValueCollection();


            reqparm.Add("AuthToken", authToken.ToString());

            int i = 0; 
            foreach(Ruling ruling in rulings)
            {
                reqparm.Add (string.Format ("ReleasedAt[{0}]", i), ruling.ReleasedAt);
                reqparm.Add (string.Format ("Rule[{0}]", i), ruling.Rule);
                ++i;
            }

            string responsebody = "";

            using (WebClient client = new WebClient ()) 
            {
                try 
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate {
                        return true;
                    };

                    byte[] responsebytes = 
                        client.UploadValues (string.Format ("{0}/cards/{1}/rulings", _apiUrl, mvid), 
                            "Post", reqparm);

                    responsebody = Encoding.UTF8.GetString (responsebytes);

                } 
                catch (WebException e) 
                {
                    throw e;
                }

                end = JsonConvert.DeserializeObject<bool>(responsebody);
            }

            return end;
        }
Example #12
0
        /// <summary>
        /// Extracts the tables in the page using rulings as separators.
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rulings"></param>
        public List <Table> Extract(PageArea page, IReadOnlyList <Ruling> rulings)
        {
            // split rulings into horizontal and vertical
            List <Ruling> horizontalR = new List <Ruling>();
            List <Ruling> verticalR   = new List <Ruling>();

            foreach (Ruling r in rulings)
            {
                if (r.IsHorizontal)
                {
                    horizontalR.Add(r);
                }
                else if (r.IsVertical)
                {
                    verticalR.Add(r);
                }
            }

            horizontalR = Ruling.CollapseOrientedRulings(horizontalR);
            verticalR   = Ruling.CollapseOrientedRulings(verticalR);

            List <Cell>           cells            = FindCells(horizontalR, verticalR);
            List <TableRectangle> spreadsheetAreas = FindSpreadsheetsFromCells(cells.Cast <TableRectangle>().ToList());

            List <Table> spreadsheets = new List <Table>();

            foreach (TableRectangle area in spreadsheetAreas)
            {
                List <Cell> overlappingCells = new List <Cell>();
                foreach (Cell c in cells)
                {
                    if (c.Intersects(area))
                    {
                        c.SetTextElements(TextElement.MergeWords(page.GetText(c.BoundingBox)));
                        overlappingCells.Add(c);
                    }
                }

                List <Ruling> horizontalOverlappingRulings = new List <Ruling>();
                foreach (Ruling hr in horizontalR)
                {
                    if (area.IntersectsLine(hr))
                    {
                        horizontalOverlappingRulings.Add(hr);
                    }
                }

                List <Ruling> verticalOverlappingRulings = new List <Ruling>();
                foreach (Ruling vr in verticalR)
                {
                    if (area.IntersectsLine(vr))
                    {
                        verticalOverlappingRulings.Add(vr);
                    }
                }

                TableWithRulingLines t = new TableWithRulingLines(area, overlappingCells, horizontalOverlappingRulings, verticalOverlappingRulings, this);
                spreadsheets.Add(t);
            }

            Utils.Sort(spreadsheets, new TableRectangle.ILL_DEFINED_ORDER());
            return(spreadsheets);
        }
Example #13
0
        /// <summary>
        /// Find cells from horizontal and vertical ruling lines.
        /// </summary>
        /// <param name="horizontalRulingLines"></param>
        /// <param name="verticalRulingLines"></param>
        public static List <Cell> FindCells(IReadOnlyList <Ruling> horizontalRulingLines, IReadOnlyList <Ruling> verticalRulingLines)
        {
            List <Cell> cellsFound = new List <Cell>();
            SortedDictionary <PdfPoint, Ruling[]> intersectionPoints = Ruling.FindIntersections(horizontalRulingLines, verticalRulingLines);
            List <PdfPoint> intersectionPointsList = new List <PdfPoint>(intersectionPoints.Keys);

            intersectionPointsList.Sort(new POINT_COMPARER());

            for (int i = 0; i < intersectionPointsList.Count; i++)
            {
                PdfPoint topLeft = intersectionPointsList[i];
                Ruling[] hv      = intersectionPoints[topLeft];
                bool     doBreak = false;

                // CrossingPointsDirectlyBelow( topLeft );
                List <PdfPoint> xPoints = new List <PdfPoint>();
                // CrossingPointsDirectlyToTheRight( topLeft );
                List <PdfPoint> yPoints = new List <PdfPoint>();

                foreach (PdfPoint p in intersectionPointsList.SubList(i, intersectionPointsList.Count))
                {
                    if (p.X == topLeft.X && p.Y < topLeft.Y) //  p.Y > topLeft.Y
                    {
                        xPoints.Add(p);
                    }
                    if (p.Y == topLeft.Y && p.X > topLeft.X)
                    {
                        yPoints.Add(p);
                    }
                }

                //outer:
                foreach (PdfPoint xPoint in xPoints)
                {
                    if (doBreak)
                    {
                        break;
                    }

                    // is there a vertical edge b/w topLeft and xPoint?
                    if (!hv[1].Equals(intersectionPoints[xPoint][1]))
                    {
                        continue;
                    }

                    foreach (PdfPoint yPoint in yPoints)
                    {
                        // is there an horizontal edge b/w topLeft and yPoint ?
                        if (!hv[0].Equals(intersectionPoints[yPoint][0]))
                        {
                            continue;
                        }

                        PdfPoint btmRight = new PdfPoint(yPoint.X, xPoint.Y);
                        if (intersectionPoints.ContainsKey(btmRight) &&
                            intersectionPoints[btmRight][0].Equals(intersectionPoints[xPoint][0]) &&
                            intersectionPoints[btmRight][1].Equals(intersectionPoints[yPoint][1]))
                        {
                            cellsFound.Add(new Cell(topLeft, btmRight));
                            doBreak = true;
                            //break outer;
                            break;
                        }
                    }
                }
            }

            // TODO create cells for vertical ruling lines with aligned endpoints at the top/bottom of a grid
            // that aren't connected with an horizontal ruler?
            // see: https://github.com/jazzido/tabula-extractor/issues/78#issuecomment-41481207

            return(cellsFound);
        }
Example #14
0
        /// <summary>
        /// Detects the tables in the page.
        /// </summary>
        /// <param name="page"></param>
        public List <TableRectangle> Detect(PageArea page)
        {
            // get horizontal & vertical lines
            // we get these from an image of the PDF and not the PDF itself because sometimes there are invisible PDF
            // instructions that are interpreted incorrectly as visible elements - we really want to capture what a
            // person sees when they look at the PDF
            // BobLd: hack here, we don't convert to an image
            var           pageRulings       = page.GetRulings();
            List <Ruling> horizontalRulings = this.getHorizontalRulings(pageRulings);
            List <Ruling> verticalRulings   = this.getVerticalRulings(pageRulings);
            // end hack here

            List <Ruling> allEdges = new List <Ruling>(horizontalRulings);

            allEdges.AddRange(verticalRulings);

            List <TableRectangle> tableAreas = new List <TableRectangle>();

            // if we found some edges, try to find some tables based on them
            if (allEdges.Count > 0)
            {
                // now we need to snap edge endpoints to a grid
                Utils.SnapPoints(allEdges, POINT_SNAP_DISTANCE_THRESHOLD, POINT_SNAP_DISTANCE_THRESHOLD);

                // normalize the rulings to make sure snapping didn't create any wacky non-horizontal/vertical rulings
                foreach (List <Ruling> rulings in new[] { horizontalRulings, verticalRulings }) //Arrays.asList(horizontalRulings, verticalRulings))
                {
                    //for (Iterator<Ruling> iterator = rulings.iterator(); iterator.hasNext();)
                    foreach (var ruling in rulings.ToList()) // use ToList to be able to remove
                    {
                        ruling.Normalize();
                        if (ruling.IsOblique)
                        {
                            rulings.Remove(ruling);
                        }
                    }
                }

                // merge the edge lines into rulings - this makes finding edges between crossing points in the next step easier
                // we use a larger pixel expansion than the normal spreadsheet extraction method to cover gaps in the
                // edge detection/pixel snapping steps
                horizontalRulings = Ruling.CollapseOrientedRulings(horizontalRulings, 5);
                verticalRulings   = Ruling.CollapseOrientedRulings(verticalRulings, 5);

                // use the rulings and points to find cells
                List <TableRectangle> cells = SpreadsheetExtractionAlgorithm.FindCells(horizontalRulings, verticalRulings).Cast <TableRectangle>().ToList();

                // then use those cells to make table areas
                tableAreas = getTableAreasFromCells(cells);
            }

            // next find any vertical rulings that intersect tables - sometimes these won't have completely been captured as
            // cells if there are missing horizontal lines (which there often are)
            // let's assume though that these lines should be part of the table
            foreach (Ruling verticalRuling in verticalRulings) // Line2D.Float
            {
                foreach (TableRectangle tableArea in tableAreas)
                {
                    if (verticalRuling.Intersects(tableArea) &&
                        !(tableArea.Contains(verticalRuling.P1) && tableArea.Contains(verticalRuling.P2)))
                    {
                        tableArea.SetTop(Math.Ceiling(Math.Max(tableArea.Top, verticalRuling.Y2)));     // bobld: Floor and Min, Y1
                        tableArea.SetBottom(Math.Floor(Math.Min(tableArea.Bottom, verticalRuling.Y1))); // bobld: Ceiling and Max, Y2
                        break;
                    }
                }
            }

            /* BobLd: not sure this is the case in tabula-sharp/PdfPig
             * // the tabula Page coordinate space is half the size of the PDFBox image coordinate space
             * // so halve the table area size before proceeding and add a bit of padding to make sure we capture everything
             * foreach (TableRectangle area in tableAreas)
             * {
             *  area.x = (float)Math.floor(area.x / 2) - TABLE_PADDING_AMOUNT;
             *  area.y = (float)Math.floor(area.y / 2) - TABLE_PADDING_AMOUNT;
             *  area.width = (float)Math.ceil(area.width / 2) + TABLE_PADDING_AMOUNT;
             *  area.height = (float)Math.ceil(area.height / 2) + TABLE_PADDING_AMOUNT;
             * }
             *
             * // we're going to want halved horizontal lines later too
             * foreach (Ruling ruling in horizontalRulings) // Line2D.Float
             * {
             *  ruling.x1 = ruling.x1 / 2;
             *  ruling.y1 = ruling.y1 / 2;
             *  ruling.x2 = ruling.x2 / 2;
             *  ruling.y2 = ruling.y2 / 2;
             * }
             */

            // now look at text rows to help us find more tables and flesh out existing ones
            List <TextChunk> textChunks = TextElement.MergeWords(page.GetText());
            List <TableLine> lines      = TextChunk.GroupByLines(textChunks);

            // first look for text rows that intersect an existing table - those lines should probably be part of the table
            foreach (TableLine textRow in lines)
            {
                foreach (TableRectangle tableArea in tableAreas)
                {
                    if (!tableArea.Contains(textRow) && textRow.Intersects(tableArea))
                    {
                        tableArea.SetLeft(Math.Floor(Math.Min(textRow.Left, tableArea.Left)));
                        tableArea.SetRight(Math.Ceiling(Math.Max(textRow.Right, tableArea.Right)));
                    }
                }
            }

            // get rid of tables that DO NOT intersect any text areas - these are likely graphs or some sort of graphic
            //for (Iterator<Rectangle> iterator = tableAreas.iterator(); iterator.hasNext();)
            foreach (TableRectangle table in tableAreas.ToList()) // use tolist to be able to remove
            {
                bool intersectsText = false;
                foreach (TableLine textRow in lines)
                {
                    if (table.Intersects(textRow))
                    {
                        intersectsText = true;
                        break;
                    }
                }

                if (!intersectsText)
                {
                    tableAreas.Remove(table);
                }
            }

            // lastly, there may be some tables that don't have any vertical rulings at all
            // we'll use text edges we've found to try and guess which text rows are part of a table

            // in his thesis nurminen goes through every row to try to assign a probability that the line is in a table
            // we're going to try a general heuristic instead, trying to find what type of edge (left/right/mid) intersects
            // the most text rows, and then use that magic number of "relevant" edges to decide what text rows should be
            // part of a table.

            bool foundTable;

            do
            {
                foundTable = false;

                // get rid of any text lines contained within existing tables, this allows us to find more tables
                //for (Iterator<TableLine> iterator = lines.iterator(); iterator.hasNext();)
                foreach (var textRow in lines.ToList())
                {
                    foreach (TableRectangle table in tableAreas)
                    {
                        if (table.Contains(textRow))
                        {
                            lines.Remove(textRow);
                            break;
                        }
                    }
                }

                // get text edges from remaining lines in the document
                TextEdges textEdges = getTextEdges(lines);
                //List<TextEdge> leftTextEdges = textEdges[TextEdge.LEFT];
                //List<TextEdge> midTextEdges = textEdges[TextEdge.MID];
                //List<TextEdge> rightTextEdges = textEdges[TextEdge.RIGHT];

                // find the relevant text edges (the ones we think define where a table is)
                RelevantEdges relevantEdgeInfo = getRelevantEdges(textEdges, lines);

                // we found something relevant so let's look for rows that fit our criteria
                if (relevantEdgeInfo.edgeType != -1)
                {
                    List <TextEdge> relevantEdges = null;
                    switch (relevantEdgeInfo.edgeType)
                    {
                    case TextEdge.LEFT:
                        relevantEdges = textEdges[TextEdge.LEFT];       // leftTextEdges;
                        break;

                    case TextEdge.MID:
                        relevantEdges = textEdges[TextEdge.MID];        // midTextEdges;
                        break;

                    case TextEdge.RIGHT:
                        relevantEdges = textEdges[TextEdge.RIGHT];      // rightTextEdges;
                        break;
                    }

                    TableRectangle table = getTableFromText(lines, relevantEdges, relevantEdgeInfo.edgeCount, horizontalRulings);

                    if (table != null)
                    {
                        foundTable = true;
                        tableAreas.Add(table);
                    }
                }
            } while (foundTable);

            // create a set of our current tables that will eliminate duplicate tables
            SortedSet <TableRectangle> tableSet = new SortedSet <TableRectangle>(new TreeSetComparer()); //Set<Rectangle> tableSet = new TreeSet<>(new Comparator<Rectangle>() {...

            foreach (var table in tableAreas.OrderByDescending(t => t.Area))
            {
                tableSet.Add(table);
            }

            return(tableSet.ToList());
        }
Example #15
0
        private TableRectangle getTableFromText(List <TableLine> lines, List <TextEdge> relevantEdges, int relevantEdgeCount, List <Ruling> horizontalRulings)
        {
            TableRectangle table = new TableRectangle();

            TableLine prevRow       = null;
            TableLine firstTableRow = null;
            TableLine lastTableRow  = null;

            int    tableSpaceCount = 0;
            double totalRowSpacing = 0;

            // go through the lines and find the ones that have the correct count of the relevant edges
            foreach (TableLine textRow in lines)
            {
                int numRelevantEdges = 0;

                if (firstTableRow != null && tableSpaceCount > 0)
                {
                    // check to make sure this text row is within a line or so of the other lines already added
                    // if it's not, we should stop the table here
                    double tableLineThreshold = (totalRowSpacing / tableSpaceCount) * 2.5;
                    double lineDistance       = prevRow.Bottom - textRow.Bottom; // bobld: textRow.Top - prevRow.Top

                    System.Diagnostics.Debug.Assert(lineDistance >= 0);

                    if (lineDistance > tableLineThreshold)
                    {
                        lastTableRow = prevRow;
                        break;
                    }
                }

                // for larger tables, be a little lenient on the number of relevant rows the text intersects
                // for smaller tables, not so much - otherwise we'll end up treating paragraphs as tables too
                int relativeEdgeDifferenceThreshold = 1;
                if (relevantEdgeCount <= 3)
                {
                    relativeEdgeDifferenceThreshold = 0;
                }

                foreach (TextEdge edge in relevantEdges)
                {
                    if (textRow.IntersectsLine(edge.Line))
                    {
                        numRelevantEdges++;
                    }
                }

                // see if we have a candidate text row
                if (numRelevantEdges >= (relevantEdgeCount - relativeEdgeDifferenceThreshold))
                {
                    // keep track of table row spacing
                    if (prevRow != null && firstTableRow != null)
                    {
                        tableSpaceCount++;
                        totalRowSpacing += prevRow.Bottom - textRow.Bottom; // bobld: textRow.Top - prevRow.Top
                    }

                    // row is part of a table
                    if (table.Area == 0)
                    {
                        firstTableRow = textRow;
                        table.SetRect(textRow);
                    }
                    else
                    {
                        table.SetLeft(Math.Min(table.Left, textRow.Left));
                        table.SetBottom(Math.Min(table.Bottom, textRow.Bottom)); // bobld: Max
                        table.SetRight(Math.Max(table.Right, textRow.Right));
                    }
                }
                else
                {
                    // no dice
                    // if we're at the end of the table, save the last row
                    if (firstTableRow != null && lastTableRow == null)
                    {
                        lastTableRow = prevRow;
                    }
                }

                prevRow = textRow;
            }

            // if we don't have a table now, we won't after the next step either
            if (table.Area == 0)
            {
                return(null);
            }

            if (lastTableRow == null)
            {
                // takes care of one-row tables or tables that end at the bottom of a page
                lastTableRow = prevRow;
            }

            // use the average row height and nearby horizontal lines to extend the table area
            double avgRowHeight;

            if (tableSpaceCount > 0)
            {
                System.Diagnostics.Debug.Assert(totalRowSpacing >= 0);
                avgRowHeight = totalRowSpacing / tableSpaceCount;
            }
            else
            {
                avgRowHeight = lastTableRow.Height;
            }

            double rowHeightThreshold = avgRowHeight * 1.5;

            // check lines after the bottom of the table
            //foreach (Ruling ruling in sortedHorizontalRulings) //Line2D.Float
            for (int i = horizontalRulings.Count - 1; i >= 0; i--) // reverse order
            {
                var ruling = horizontalRulings[i];
                if (ruling.Y1 > table.Bottom) // bobld: <
                {
                    continue;
                }

                double distanceFromTable = table.Bottom - ruling.Y2; // bobld: Y1
                System.Diagnostics.Debug.Assert(distanceFromTable >= 0);
                if (distanceFromTable <= rowHeightThreshold)
                {
                    // use this ruling to help define the table
                    table.SetBottom(Math.Min(table.Bottom, ruling.Y2));  // bobld: Max Y1
                    table.SetLeft(Math.Min(table.Left, ruling.X1));
                    table.SetRight(Math.Max(table.Right, ruling.X2));
                }
                else
                {
                    // no use checking any further
                    break;
                }
            }

            // do the same for lines at the top, but make the threshold greater since table headings tend to be
            // larger to fit up to three-ish rows of text (at least but we don't want to grab too much)
            rowHeightThreshold = avgRowHeight * 3.8;

            //for (int i = horizontalRulings.Count - 1; i >= 0; i--)
            for (int i = 0; i < horizontalRulings.Count; i++)
            {
                Ruling ruling = horizontalRulings[i];

                if (ruling.Y1 < table.Top) //bobld: >
                {
                    continue;
                }

                double distanceFromTable = ruling.Y1 - table.Top; // bobld: table.Top - ruling.Y1
                System.Diagnostics.Debug.Assert(distanceFromTable >= 0);
                if (distanceFromTable <= rowHeightThreshold)
                {
                    table.SetTop(Math.Max(table.Top, ruling.Y2));  // bobld: Min Y1
                    table.SetLeft(Math.Min(table.Left, ruling.X1));
                    table.SetRight(Math.Max(table.Right, ruling.X2));
                }
                else
                {
                    break;
                }
            }

            // add a bit of padding since the halved horizontal lines are a little fuzzy anyways
            table.SetTop(Math.Ceiling(table.Top) + TABLE_PADDING_AMOUNT);       // bobld: Floor -
            table.SetBottom(Math.Floor(table.Bottom) - TABLE_PADDING_AMOUNT);   // bobld: Ceiling +
            table.SetLeft(Math.Floor(table.Left) - TABLE_PADDING_AMOUNT);
            table.SetRight(Math.Ceiling(table.Right) + TABLE_PADDING_AMOUNT);

            return(table);
        }
Example #16
0
 public Playground(Ruling.RuleSet.FieldSize size, FieldState initial = FieldState.Empty)
     : this(size.Width, size.Height, size.Depth, initial)
 {
 }
Example #17
0
        public void PlaceShip(Ruling.ShipType shiptype, Tuple<int, int, int> pos)
        {
            Contract.Requires(shiptype != null);
            Contract.Requires(pos != null);
            Contract.Requires(CanPlaceShip(shiptype, pos));

            for (int x = 0; x < shiptype.Width; x++)
                for (int y = 0; y < shiptype.Height; y++)
                    for (int z = 0; z < shiptype.Depth; z++)
                        if (shiptype.fields[x, y, z])
                            Field[pos.Item1 + x, pos.Item2 + y, pos.Item3 + z] = FieldState.Ship;
        }
Example #18
0
        // Identifies type given and parses into type. expContext is context that it will run on
        public static IdentifyResponse Identify(string context, string expContext, string[] parts, int start)
        {
            // If it is a reserved keyword
            if (Reserved.reservedKeywords.Contains(parts[start]))
            {
                /*  Main File   */
                // If declaring desig
                if (context == "mainfile" && parts[start] == "desig")
                {
                    DesigDeclaration dd = new DesigDeclaration();
                    return(new IdentifyResponse(dd, expContext, dd.Parse(parts, start)));
                }
                // If declaring variable
                else if (context == "mainfile" && parts[start] == "var")
                {
                    VariableDeclaration vd = new VariableDeclaration();
                    return(new IdentifyResponse(vd, expContext, vd.Parse(parts, start)));
                }
                // If declaring function
                else if (context == "mainfile" && parts[start] == "func")
                {
                    FunctionDeclaration fd = new FunctionDeclaration();
                    return(new IdentifyResponse(fd, expContext, fd.Parse(parts, start)));
                }
                // If declaring ruling
                else if (context == "mainfile" && parts[start] == "rule")
                {
                    RulingResponse rr = Ruling.IdentifyRuling(parts, start);

                    return(new IdentifyResponse(rr.icmf, expContext, rr.start));
                }
                /*  Function    */
                // If it is a function call
                else if (context == "function" && parts[start] == "call")
                {
                    FuncCall fc = new FuncCall();
                    fc.context = expContext;
                    return(new IdentifyResponse(fc, expContext, fc.Parse(parts, start)));
                }
                // If it is a context change
                else if (context == "function" && parts[start] == "context")
                {
                    ContextChange cc = new ContextChange();
                    cc.context = expContext;
                    return(new IdentifyResponse(cc, expContext, cc.Parse(parts, start)));
                }
                // If it is a specified command
                else if (context == "function" && parts[start] == "run")
                {
                    RunCommand rc = new RunCommand();
                    rc.context = expContext;
                    return(new IdentifyResponse(rc, expContext, rc.Parse(parts, start)));
                }
                /*  Variable Assignation    */
                // If it is a literal
                else if (context == "variable expression" && parts[start] == "lit")
                {
                    Literal lit = new Literal();
                    return(new IdentifyResponse(lit, expContext, lit.Parse(parts, start)));
                }
                /*  Desig Assignation   */
                // If it is a literal
                else if (context == "desig expression" && parts[start] == "lit")
                {
                    Literal lit = new Literal();
                    return(new IdentifyResponse(lit, expContext, lit.Parse(parts, start)));
                }
            }
            // Else if it is a Var assignation
            else if (context == "function" && Reserved.vEx.Exists(vd => vd.varName == parts[start]))
            {
                VariableAssignation va = new VariableAssignation();
                va.context = expContext;
                return(new IdentifyResponse(va, expContext, va.Parse(parts, start)));
            }
            // Else if it is a Desig assignation
            else if (context == "function" && Reserved.dEx.Exists(dd => dd.desigName == parts[start]))
            {
                DesigAssignation da = new DesigAssignation();
                da.context = expContext;
                return(new IdentifyResponse(da, expContext, da.Parse(parts, start)));
            }
            // If it is a variable
            else if (context == "variable expression" && Reserved.vEx.Exists(v => v.varName == parts[start]))
            {
                VarSubExpression vse = new VarSubExpression();
                return(new IdentifyResponse(vse, expContext, vse.Parse(parts, start)));
            }
            // If it is a variable
            else if (context == "desig expression" && Reserved.vEx.Exists(v => v.varName == parts[start]))
            {
                VarSubExpression vse = new VarSubExpression();
                return(new IdentifyResponse(vse, expContext, vse.Parse(parts, start)));
            }
            // If it is a desig
            else if (context == "desig expression" && Reserved.dEx.Exists(d => d.desigName == parts[start]))
            {
                DesigSubExpression dse = new DesigSubExpression();
                return(new IdentifyResponse(dse, expContext, dse.Parse(parts, start)));
            }
            // Nonsensical answer
            throw new Exception("Inrecognized expression '" + parts[start] + "' in context '" + context + "'");
        }
Example #19
0
 public virtual bool SetRuleSet(Ruling.RuleSet rules)
 {
     if (rules.IsValid) {
         RuleSet = rules;
         EnemyPlayground = new Playground(RuleSet.Size, Playground.FieldState.Unknown);
         return true;
     }
     return false;
 }
Example #20
0
        public Card GetCard(MtgJsonCard source, string setName, string setCode)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (string.IsNullOrEmpty(setName))
            {
                throw new ArgumentException("setName");
            }

            if (string.IsNullOrEmpty(setCode))
            {
                throw new ArgumentException("setCode");
            }

            Card card = new Card();

            card.Artist = source.Artist;
            card.Cmc    = Convert.ToInt32(source.CMC);

            if (source.Colors != null)
            {
                card.Colors = source.Colors.ToList();
            }

            card.Cost     = source.ManaCost;
            card.Desc     = source.Text;
            card.Flavor   = source.Flavor;
            card.Img      = this.mImageUrl.Replace("%ID%", source.MultiverseId);
            card.ImgHires = this.ImageHiResUrl.Replace("%ID%", source.MultiverseId);

            card.Loyalty       = source.Loyalty;
            card.MultiverseId  = Convert.ToInt32(source.MultiverseId);
            card.Name          = source.Name;
            card.SearchName    = this.mSearchUtility.GetSearchValue(source.Name);
            card.SetId         = setCode;
            card.SetName       = setName;
            card.SetSearchName = this.mSearchUtility.GetSearchValue(setName);
            card.Power         = source.Power;
            card.Rarity        = source.Rarity;

            if (source.SubTypes != null)
            {
                card.SubType = string.Join(" ", source.SubTypes.ToArray());
            }

            card.Token     = false;
            card.Toughness = source.Toughness;
            card.Type      = string.Join(" ", source.Types.ToArray());
            card.Types     = source.Types.ToList();

            if (source.Rulings != null)
            {
                List <Ruling> rulings = new List <Ruling>();
                foreach (MtgJsonRuling r in source.Rulings)
                {
                    Ruling ruling = new Ruling()
                    {
                        ReleasedOn = r.Date,
                        Rule       = r.Text
                    };

                    rulings.Add(ruling);
                }
                card.Rulings = rulings;
            }

            card.Number    = source.Number;
            card.McINumber = source.McINumber;

            if (source.ColorIdentity != null)
            {
                card.ColorIdentity = source.ColorIdentity.ToList();
            }

            if (source.Variations != null)
            {
                card.Variations = source.Variations.ToList();
            }

            return(card);
        }
Example #21
0
 public GameConfigMessageRequest(Ruling.RuleSet rules)
 {
     Rules = rules;
 }
Example #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start");

            var serializer = new JsonSerializer();
            Dictionary <string, Models.Set> data = new Dictionary <string, Models.Set>();

            using (var s = File.Open(_path, FileMode.Open))
                using (var sr = new StreamReader(s))
                    using (var reader = new JsonTextReader(sr))
                    {
                        while (reader.Read())
                        {
                            if (reader.TokenType == JsonToken.StartObject)
                            {
                                data = serializer.Deserialize <Dictionary <string, Models.Set> >(reader);
                            }
                        }
                    }

            foreach (var set in data.OrderBy(x => x.Value.ReleaseDate))
            {
                Console.WriteLine("Inserting set: " + set.Value.Name);

                using (var context = new Context())
                {
                    if (context.Sets.Any(s => s.Name == set.Value.Name))
                    {
                        Console.WriteLine("Skipping set: " + set.Value.Name);
                    }
                    else
                    {
                        var newSet = new Set
                        {
                            Block              = set.Value.Block,
                            Booster            = set.Value.Booster,
                            Border             = set.Value.Border,
                            Code               = set.Value.Code,
                            GathererCode       = set.Value.GathererCode,
                            MagicCardsInfoCode = set.Value.MagicCardsInfoCode,
                            Name               = set.Value.Name,
                            OldCode            = set.Value.OldCode,
                            OnlineOnly         = set.Value.OnlineOnly,
                            ReleaseDate        = set.Value.ReleaseDate,
                            Type               = set.Value.Type,
                            Cards              = new List <Card>()
                        };
                        foreach (var card in set.Value.Cards)
                        {
                            Console.WriteLine("\tInserting card: " + card.Name);

                            var newCard = new Card
                            {
                                Artist        = card.Artist,
                                Border        = card.Border,
                                CardId        = card.Id,
                                Cmc           = card.Cmc,
                                ColorIdentity = card.ColorIdentity,
                                Colors        = card.Colors,
                                Flavor        = card.Flavor,
                                Hand          = card.Hand,
                                ImageName     = card.ImageName,
                                Layout        = card.Layout,
                                Life          = card.Life,
                                Loyalty       = card.Loyalty,
                                ManaCost      = card.ManaCost,
                                MciNumber     = card.MciNumber,
                                MultiverseId  = card.MultiverseId,
                                Name          = card.Name,
                                Names         = card.Names,
                                Number        = card.Number,
                                OriginalText  = card.OriginalText,
                                OriginalType  = card.OriginalType,
                                Power         = card.Power,
                                Printings     = card.Printings,
                                Rarity        = card.Rarity,
                                ReleaseDate   = card.ReleaseDate,
                                Reserved      = card.Reserved,
                                Source        = card.Source,
                                Starter       = card.Starter,
                                SubTypes      = card.SubTypes,
                                SuperTypes    = card.SuperTypes,
                                Text          = card.Text,
                                TimeShifted   = card.TimeShifted,
                                Toughness     = card.Toughness,
                                Type          = card.Type,
                                Types         = card.Types,
                                Variations    = card.Variations,
                                WaterMark     = card.WaterMark,
                                ForeignNames  = new List <ForeignName>(),
                                Legalities    = new List <Legality>(),
                                Rulings       = new List <Ruling>()
                            };

                            if (card.ForeignNames != null)
                            {
                                foreach (var name in card.ForeignNames)
                                {
                                    var newName = new ForeignName
                                    {
                                        Language     = name.Language,
                                        MultiverseId = name.MultiverseId,
                                        Name         = name.Name
                                    };

                                    newCard.ForeignNames.Add(newName);
                                }
                            }

                            if (card.Legalities != null)
                            {
                                foreach (var legality in card.Legalities)
                                {
                                    var newLegal = new Legality
                                    {
                                        Format         = legality.Format,
                                        LegalityDetail = legality.LegalityDetail
                                    };

                                    newCard.Legalities.Add(newLegal);
                                }
                            }

                            if (card.Rulings != null)
                            {
                                foreach (var ruling in card.Rulings)
                                {
                                    var newRuling = new Ruling
                                    {
                                        Date = ruling.Date,
                                        Text = ruling.Text
                                    };

                                    newCard.Rulings.Add(newRuling);
                                }
                            }

                            newSet.Cards.Add(newCard);
                        }

                        context.Sets.Add(newSet);
                        context.SaveChanges();
                    }
                }
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }
Example #23
0
        public void TestEqualsOther()
        {
            Ruling other = new Ruling(0, 0, 11, 10);

            Assert.True(ruling.Equals(ruling));
        }
Example #24
0
        /// <summary>
        /// Extracts the tables in the page.
        /// </summary>
        /// <param name="page">The page where to extract the tables.</param>
        public List <Table> Extract(PageArea page)
        {
            List <TextElement> textElements = page.GetText();

            if (textElements.Count == 0)
            {
                return(new Table[] { Table.EMPTY }.ToList());
            }

            List <TextChunk> textChunks = this.verticalRulings == null?TextElement.MergeWords(page.GetText()) : TextElement.MergeWords(page.GetText(), this.verticalRulings);

            List <TableLine> lines = TextChunk.GroupByLines(textChunks);

            List <double> columns;

            if (this.verticalRulings != null)
            {
                // added by bobld: clipping verticalRulings because testExtractColumnsCorrectly2() fails
                var clippedVerticalRulings = Ruling.CropRulingsToArea(this.verticalRulings, page.BoundingBox);
                clippedVerticalRulings.Sort(new VerticalRulingComparer());
                columns = new List <double>(clippedVerticalRulings.Count);
                foreach (Ruling vr in clippedVerticalRulings)
                {
                    columns.Add(vr.Left);
                }

                /*
                 * this.verticalRulings.Sort(new VerticalRulingComparer());
                 * columns = new List<double>(this.verticalRulings.Count);
                 * foreach (Ruling vr in this.verticalRulings)
                 * {
                 *  columns.Add(vr.getLeft());
                 * }
                 */
            }
            else
            {
                columns = ColumnPositions(lines);
            }

            // added by bobld: remove duplicates because testExtractColumnsCorrectly2() fails,
            // why do we need it here and not in the java version??
            columns = columns.Distinct().ToList();

            Table table = new Table(this);

            table.SetRect(page.BoundingBox);

            for (int i = 0; i < lines.Count; i++)
            {
                TableLine        line     = lines[i];
                List <TextChunk> elements = line.TextElements.ToList();

                elements.Sort(new TextChunkComparer());

                foreach (TextChunk tc in elements)
                {
                    if (tc.IsSameChar(TableLine.WHITE_SPACE_CHARS))
                    {
                        continue;
                    }

                    int  j     = 0;
                    bool found = false;
                    for (; j < columns.Count; j++)
                    {
                        if (tc.Left <= columns[j])
                        {
                            found = true;
                            break;
                        }
                    }

                    table.Add(new Cell(tc), i, found ? j : columns.Count);
                }
            }

            return(new Table[] { table }.ToList());
        }
Example #25
0
        public void TestNearlyIntersects()
        {
            Ruling another = new Ruling(0, 0, 11, 10);

            Assert.True(ruling.NearlyIntersects(another));
        }
 public GameConfigConfirmationMessage(Ruling.RuleSet rules, bool accept)
     : base(rules)
 {
     Accept = accept;
 }
Example #27
0
        public void TestGetStartError()
        {
            Ruling other = new Ruling(0, 0, 1, 1);

            Assert.Throws <InvalidOperationException>(() => other.Start);
        }
Example #28
0
        public void TestSetEndError()
        {
            Ruling other = new Ruling(0, 0, 1, 1);

            Assert.Throws <InvalidOperationException>(() => other.SetEnd(5f));
        }
Example #29
0
 public bool CanPlaceShip(Ruling.ShipType shiptype, Tuple<int, int, int> pos)
 {
     for (int x = 0; x < shiptype.Width; x++)
         for (int y = 0; y < shiptype.Height; y++)
             for (int z = 0; z < shiptype.Depth; z++)
                 if (shiptype.fields[x, y, z])
                     if (pos.Item1 + x >= Width ||
                         pos.Item2 + y >= Height ||
                         pos.Item3 + z >= Depth ||
                         Field[pos.Item1 + x, pos.Item2 + y, pos.Item3 + z] != FieldState.Empty)
                         return false;
     return true;
 }