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

<!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
<concept id="refresh">

  <title>REFRESH Statement</title>
  <titlealts audience="PDF"><navtitle>REFRESH</navtitle></titlealts>
  <prolog>
    <metadata>
      <data name="Category" value="Impala"/>
      <data name="Category" value="SQL"/>
      <data name="Category" value="DDL"/>
      <data name="Category" value="Tables"/>
      <data name="Category" value="Hive"/>
      <data name="Category" value="Metastore"/>
      <data name="Category" value="ETL"/>
      <data name="Category" value="Ingest"/>
      <data name="Category" value="Developers"/>
      <data name="Category" value="Data Analysts"/>
    </metadata>
  </prolog>

  <conbody>

      <indexterm audience="hidden">REFRESH statement</indexterm>
      To accurately respond to queries, the Impala node that acts as the coordinator (the node to which you are
      connected through <cmdname>impala-shell</cmdname>, JDBC, or ODBC) must have current metadata about those
      databases and tables that are referenced in Impala queries. If you are not familiar with the way Impala uses
      metadata and how it shares the same metastore database as Hive, see
      <xref href="impala_hadoop.xml#intro_metastore"/> for background information.

<codeblock rev="IMPALA-1683">REFRESH [<varname>db_name</varname>.]<varname>table_name</varname> [PARTITION (<varname>key_col1</varname>=<varname>val1</varname> [, <varname>key_col2</varname>=<varname>val2</varname>...])]</codeblock>

      Use the <codeph>REFRESH</codeph> statement to load the latest metastore metadata and block location data for
      a particular table in these scenarios:

        After loading new data files into the HDFS data directory for the table. (Once you have set up an ETL
        pipeline to bring data into Impala on a regular basis, this is typically the most frequent reason why
        metadata needs to be refreshed.)

        After issuing <codeph>ALTER TABLE</codeph>, <codeph>INSERT</codeph>, <codeph>LOAD DATA</codeph>, or other
        table-modifying SQL statement in Hive.

    <note rev="2.3.0">

        In <keyword keyref="impala23_full"/> and higher, the syntax <codeph>ALTER TABLE <varname>table_name</varname> RECOVER PARTITIONS</codeph>
        is a faster alternative to <codeph>REFRESH</codeph> when the only change to the table data is the addition of
        new partition directories through Hive or manual HDFS operations.
        See <xref href="impala_alter_table.xml#alter_table"/> for details.

    </note>

      You only need to issue the <codeph>REFRESH</codeph> statement on the node to which you connect to issue
      queries. The coordinator node divides the work among all the Impala nodes in a cluster, and sends read
      requests for the correct HDFS blocks without relying on the metadata on the other nodes.

      <codeph>REFRESH</codeph> reloads the metadata for the table from the metastore database, and does an
      incremental reload of the low-level block location data to account for any new data files added to the HDFS
      data directory for the table. It is a low-overhead, single-table operation, specifically tuned for the common
      scenario where new data files are added to HDFS.

      Only the metadata for the specified table is flushed. The table must already exist and be known to Impala,
      either because the <codeph>CREATE TABLE</codeph> statement was run in Impala rather than Hive, or because a
      previous <codeph>INVALIDATE METADATA</codeph> statement caused Impala to reload its entire metadata catalog.

    <note>

        The catalog service broadcasts any changed metadata as a result of Impala
        <codeph>ALTER TABLE</codeph>, <codeph>INSERT</codeph> and <codeph>LOAD DATA</codeph> statements to all
        Impala nodes. Thus, the <codeph>REFRESH</codeph> statement is only required if you load data through Hive
        or by manipulating data files in HDFS directly. See <xref href="impala_components.xml#intro_catalogd"/> for
        more information on the catalog service.

        Another way to avoid inconsistency across nodes is to enable the
        <codeph>SYNC_DDL</codeph> query option before performing a DDL statement or an <codeph>INSERT</codeph> or
        <codeph>LOAD DATA</codeph>.

        The table name is a required parameter. To flush the metadata for all tables, use the
        <codeph><xref href="impala_invalidate_metadata.xml#invalidate_metadata">INVALIDATE METADATA</xref></codeph>
        command.

    </note>

      A metadata update for an <codeph>impalad</codeph> instance is required if:

        A metadata change occurs.

        and the change is made through Hive.

        and the change is made to a metastore database to which clients such as the Impala shell or ODBC directly
        connect.

      A metadata update for an Impala node is not required after you run <codeph>ALTER TABLE</codeph>,
      <codeph>INSERT</codeph>, or other table-modifying statement in Impala rather than Hive. Impala handles the
      metadata synchronization automatically through the catalog service.

      Database and table metadata is typically modified by:

        Hive - through <codeph>ALTER</codeph>, <codeph>CREATE</codeph>, <codeph>DROP</codeph> or
        <codeph>INSERT</codeph> operations.

        Impalad - through <codeph>CREATE TABLE</codeph>, <codeph>ALTER TABLE</codeph>, and <codeph>INSERT</codeph>
        operations. <ph rev="1.2">Such changes are propagated to all Impala nodes by the
        Impala catalog service.</ph>

      <codeph>REFRESH</codeph> causes the metadata for that table to be immediately reloaded. For a huge table,
      that process could take a noticeable amount of time; but doing the refresh up front avoids an unpredictable
      delay later, for example if the next reference to the table is during a benchmark test.

      Refreshing a single partition:

      In <keyword keyref="impala27_full"/> and higher, the <codeph>REFRESH</codeph> statement can apply to a single partition at a time,
      rather than the whole table. Include the optional <codeph>PARTITION (<varname>partition_spec</varname>)</codeph>
      clause and specify values for each of the partition key columns.

      The following examples show how to make Impala aware of data added to a single partition, after data is loaded into
      a partition's data directory using some mechanism outside Impala, such as Hive or Spark. The partition can be one that
      Impala created and is already aware of, or a new partition created through Hive.

<codeblock rev="IMPALA-1683"><![CDATA[
impala> create table p (x int) partitioned by (y int);
impala> insert into p (x,y) values (1,2), (2,2), (2,1);
impala> show partitions p;
+-------+-------+--------+------+...
| y     | #Rows | #Files | Size |...
+-------+-------+--------+------+...
| 1     | -1    | 1      | 2B   |...
| 2     | -1    | 1      | 4B   |...
| Total | -1    | 2      | 6B   |...
+-------+-------+--------+------+...

-- ... Data is inserted into one of the partitions by some external mechanism ...
beeline> insert into p partition (y = 1) values(1000);

impala> refresh p partition (y=1);
impala> select x from p where y=1;
+------+
| x    |
+------+
| 2    | <- Original data created by Impala
| 1000 | <- Additional data inserted through Beeline
+------+
]]>
</codeblock>

      The same applies for tables with more than one partition key column.
      The <codeph>PARTITION</codeph> clause of the <codeph>REFRESH</codeph>
      statement must include all the partition key columns.

<codeblock rev="IMPALA-1683"><![CDATA[
impala> create table p2 (x int) partitioned by (y int, z int);
impala> insert into p2 (x,y,z) values (0,0,0), (1,2,3), (2,2,3);
impala> show partitions p2;
+-------+---+-------+--------+------+...
| y     | z | #Rows | #Files | Size |...
+-------+---+-------+--------+------+...
| 0     | 0 | -1    | 1      | 2B   |...
| 2     | 3 | -1    | 1      | 4B   |...
| Total |   | -1    | 2      | 6B   |...
+-------+---+-------+--------+------+...

-- ... Data is inserted into one of the partitions by some external mechanism ...
beeline> insert into p2 partition (y = 2, z = 3) values(1000);

impala> refresh p2 partition (y=2, z=3);
impala> select x from p where y=2 and z = 3;
+------+
| x    |
+------+
| 1    | <- Original data created by Impala
| 2    | <- Original data created by Impala
| 1000 | <- Additional data inserted through Beeline
+------+
]]>
</codeblock>

      The following examples show how specifying a nonexistent partition does not cause any error,
      and the order of the partition key columns does not have to match the column order in the table.
      The partition spec must include all the partition key columns; specifying an incomplete set of
      columns does cause an error.

<codeblock rev="IMPALA-1683"><![CDATA[
-- Partition doesn't exist.
refresh p2 partition (y=0, z=3);
refresh p2 partition (y=0, z=-1)
-- Key columns specified in a different order than the table definition.
refresh p2 partition (z=1, y=0)
-- Incomplete partition spec causes an error.
refresh p2 partition (y=0)
ERROR: AnalysisException: Items in partition spec must exactly match the partition columns in the table definition: default.p2 (1 vs 2)
]]>
</codeblock>

      The following example shows how you might use the <codeph>REFRESH</codeph> statement after manually adding
      new HDFS data files to the Impala data directory for a table:

<codeblock>[impalad-host:21000] > refresh t1;
[impalad-host:21000] > refresh t2;
[impalad-host:21000] > select * from t1;
...
[impalad-host:21000] > select * from t2;
... </codeblock>

      For more examples of using <codeph>REFRESH</codeph> and <codeph>INVALIDATE METADATA</codeph> with a
      combination of Impala and Hive operations, see <xref href="impala_tutorial.xml#tutorial_impala_hive"/>.

      Related impala-shell options:

      The <cmdname>impala-shell</cmdname> option <codeph>-r</codeph> issues an <codeph>INVALIDATE METADATA</codeph> statement
      when starting up the shell, effectively performing a <codeph>REFRESH</codeph> of all tables.
      Due to the expense of reloading the metadata for all tables, the <cmdname>impala-shell</cmdname> <codeph>-r</codeph>
      option is not recommended for day-to-day use in a production environment. (This option was mainly intended as a workaround
      for synchronization issues in very old Impala versions.)

      The user ID that the <cmdname>impalad</cmdname> daemon runs under,
      typically the <codeph>impala</codeph> user, must have execute
      permissions for all the relevant directories holding table data.
      (A table could have data spread across multiple directories,
      or in unexpected paths, if it uses partitioning or
      specifies a <codeph>LOCATION</codeph> attribute for
      individual partitions or the entire table.)
      Issues with permissions might not cause an immediate error for this statement,
      but subsequent statements such as <codeph>SELECT</codeph>
      or <codeph>SHOW TABLE STATS</codeph> could fail.

      All HDFS and Sentry permissions and privileges are the same whether you refresh the entire table
      or a single partition.

      The <codeph>REFRESH</codeph> command checks HDFS permissions of the underlying data files and directories,
      caching this information so that a statement can be cancelled immediately if for example the
      <codeph>impala</codeph> user does not have permission to write to the data directory for the table. Impala
      reports any lack of write permissions as an <codeph>INFO</codeph> message in the log file, in case that
      represents an oversight. If you change HDFS permissions to make data readable or writeable by the Impala
      user, issue another <codeph>REFRESH</codeph> to make Impala aware of the change.

    <note conref="../shared/impala_common.xml#common/compute_stats_next"/>

      <xref href="impala_hadoop.xml#intro_metastore"/>,
      <xref href="impala_invalidate_metadata.xml#invalidate_metadata"/>

  </conbody>
</concept>


text: Kivy Python App for fitness

redpajama_set_name: RedPajamaGithub


text:
require_relative '../core/CursorRequest'

class FollowersIds < CursorRequest

  def initialize(args)
    super args
    params[:count] = 5000
    @count = 0
  end

  def request_name
    "FollowersIds"
  end

  def twitter_endpoint
    "/followers/ids"
  end

  def url
    'https://api.twitter.com/1.1/followers/ids.json'
  end

  def success(response)
    log.info("SUCCESS")
    ids = JSON.parse(response.body)['ids']
    @count += ids.size
    log.info("#{ids.size} ids received.")
    log.info("#{@count} total ids received.")
    yield ids
  end

end


text:
#include "Ampel_Behaviors.h"

#include "Ampel.h"

void behavior_red(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(true);
    a->setYellowLight(false);
    a->setGreenLight(false);
}

void behavior_redtogreen(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(true);
    a->setYellowLight(true);
    a->setGreenLight(false);
}

void behavior_green(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(false);
    a->setYellowLight(false);
    a->setGreenLight(true);
}

void behavior_greentored(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(false);
    a->setYellowLight(true);
    a->setGreenLight(false);
}

void behavior_offline_check(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(false);
    a->setYellowLight(true);
    a->setGreenLight(false);
}

void behavior_offline(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    a->setRedLight(false);
    a->setYellowLight(false);
    a->setGreenLight(false);
}

bool guard_hasController(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    return a->hasController();
}

bool guard_hasNoController(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    return !(a->hasController());
}

bool guard_greenPhaseRequested(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    return (a->getPhaseCommand() == PHASE_GREEN);
}

bool guard_redPhaseRequested(const AutomatonElement& ae, const string& ActionID)
{
    Ampel *a = static_cast<Ampel*>(ae.getHandle());
    return (a->getPhaseCommand() == PHASE_RED);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface org.openxava.tab.impl.IXTableModel (OpenXava 4.9.1 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.openxava.tab.impl.IXTableModel

Packages that use IXTableModel

org.openxava.tab

org.openxava.tab.impl

Uses of IXTableModel in org.openxava.tab

Methods in org.openxava.tab that return IXTableModel

 IXTableModel
Tab.getAllDataTableModel()

          A table model with load all data at once.

 IXTableModel
Tab.getTableModel()

          A table model with on-demand data reading.

Methods in org.openxava.tab with parameters of type IXTableModel

 void
Tab.setTableModel(IXTableModel tableModel)

Uses of IXTableModel in org.openxava.tab.impl

Classes in org.openxava.tab.impl that implement IXTableModel

 class
HiddenXTableModel

          Decorate an IXTableModel to hidden columns.

 class
SelectedRowsXTableModel

 class
TableModelBean

          IXTableModel implementation in JavaBean format.

 class
XTableModelDecoratorBase

          Base class to create IXTableModel decorators.

Methods in org.openxava.tab.impl that return IXTableModel

 IXTableModel
EntityTab.getTable()

 IXTableModel
IWithXTableModel.getTable()

Constructors in org.openxava.tab.impl with parameters of type IXTableModel

HiddenXTableModel(IXTableModel toDecorate,
                  int[] hiddenIndexes)

SelectedRowsXTableModel(IXTableModel toDecorate,
                        int[] selectedRows)

XTableModelDecoratorBase(IXTableModel toDecorate)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Canthium vacciniifolium F.Muell.

### Remarks
null


text:
namespace Week1.Example3a
{
    using System;

    class Program
    {
        const int NB_CASES = 10;
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int[] tableau = null;
            tableau = new int[NB_CASES];

            Afficher(tableau);

            // On passe en paramètre par valeur la référence du tableau. Ceci implique que dans une nouvelle variable
            // (le paramètre leTableau), on recopie le contenu de la variable originale (tableau).
            // Nous avons donc deux variables qui contiennent la même référence qui mène au même tableau en mémoire, ce qui
            // explique que les changements apportés via leTableau auront des répercussions sur tableau.
            RemplirDeValeursAléatoires(tableau);
            Afficher(tableau);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="leTableau"></param>
        static void RemplirDeValeursAléatoires(int[] leTableau)
        {
            Random générateur = new Random();

            for (int i = 0; i < leTableau.Length; ++i)
            {
                leTableau[i] = générateur.Next(0, 101);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="leTableau"></param>
        static void Afficher(int[] leTableau)
        {
            Console.WriteLine(new string('-', 60));
            for (int i = 0; i < leTableau.Length; ++i)
            {
                Console.WriteLine(leTableau[i]);
            }
        }
    }
}


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Events;
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Areas.Admin.Features.Organizations;
using AllReady.Areas.Admin.Features.Requests;
using AllReady.Areas.Admin.Features.TaskSignups;
using AllReady.Areas.Admin.ViewModels.Itinerary;
using AllReady.Areas.Admin.ViewModels.Request;
using AllReady.Areas.Admin.ViewModels.Validators;
using AllReady.Models;
using AllReady.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AllReady.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Authorize("OrgAdmin")]
    public class ItineraryController : Controller
    {
        private readonly IMediator _mediator;
        private readonly IItineraryEditModelValidator _itineraryValidator;

        public ItineraryController(IMediator mediator, IItineraryEditModelValidator itineraryValidator)
        {
            _mediator = mediator;
            _itineraryValidator = itineraryValidator;
        }

        [HttpGet]
        [Route("Admin/Itinerary/Details/{id}")]
        public async Task<IActionResult> Details(int id)
        {
            var itinerary = await _mediator.SendAsync(new ItineraryDetailQuery { ItineraryId = id });
            if (itinerary == null)
            {
                return NotFound();
            }

            if (!User.IsOrganizationAdmin(itinerary.OrganizationId))
            {
                return Unauthorized();
            }

            return View("Details", itinerary);
        }

        [HttpPost]
        [Route("Admin/Itinerary/Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(ItineraryEditViewModel model)
        {
            if (model == null)
            {
                return BadRequest();
            }

            var campaignEvent = await _mediator.SendAsync(new EventSummaryQuery { EventId = model.EventId });
            if (campaignEvent == null)
            {
                return BadRequest();
            }

            if (!User.IsOrganizationAdmin(campaignEvent.OrganizationId))
            {
                return Unauthorized();
            }

            var errors = _itineraryValidator.Validate(model, campaignEvent);
            errors.ToList().ForEach(e => ModelState.AddModelError(e.Key, e.Value));

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _mediator.SendAsync(new EditItineraryCommand { Itinerary = model });
            if (result > 0)
            {
                return Ok(result);
            }

            return BadRequest();
        }

        [HttpPost]
        [Route("Admin/Itinerary/AddTeamMember")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddTeamMember(int id, int selectedTeamMember)
        {
            // todo: sgordon: This is not a very elegant at the moment as a failure would redirect without any feedback to the user
            // this flow should be reviews and enhanced in a future PR using knockout to send and handle the error messaging on the details page
            // for the purpose of the upcoming red cross testing I chose to leave this since a failure here would be an edge case

            var orgId = await GetOrganizationIdBy(id);
            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            if (id == 0 || selectedTeamMember == 0)
            {
                return RedirectToAction("Details", new { id });
            }

            var isSuccess = await _mediator.SendAsync(new AddTeamMemberCommand { ItineraryId = id, TaskSignupId = selectedTeamMember });

            return RedirectToAction("Details", new { id });
        }

        [HttpGet]
        [Route("Admin/Itinerary/{id}/[Action]")]
        public async Task<IActionResult> SelectRequests(int id)
        {
            var orgId = await GetOrganizationIdBy(id);
            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var model = await BuildSelectItineraryRequestsModel(id, new RequestSearchCriteria { Status = RequestStatus.Unassigned });

            return View("SelectRequests", model);
        }

        [HttpPost]
        [Route("Admin/Itinerary/{id}/[Action]")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SelectRequests(int id, SelectItineraryRequestsViewModel model)
        {
            var newModel = await BuildSelectItineraryRequestsModel(id, new RequestSearchCriteria { Status = RequestStatus.Unassigned, Keywords = model.KeywordsFilter });

            return View("SelectRequests", newModel);
        }

        [HttpPost]
        [Route("Admin/Itinerary/{id}/[Action]")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddRequests(int id, string[] selectedRequests)
        {
            // todo - error handling
            var orgId = await GetOrganizationIdBy(id);
            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            if (selectedRequests.Any())
            {
                await _mediator.SendAsync(new AddRequestsCommand { ItineraryId = id, RequestIdsToAdd = selectedRequests.ToList() });
            }

            return RedirectToAction(nameof(Details), new { id });
        }

        [HttpGet]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{taskSignupId}")]
        public async Task<IActionResult> ConfirmRemoveTeamMember(int itineraryId, int taskSignupId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var model = await _mediator.SendAsync(new TaskSignupSummaryQuery { TaskSignupId = taskSignupId });

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

            return View("ConfirmRemoveTeamMember", model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{taskSignupId}")]
        public async Task<IActionResult> RemoveTeamMember(int itineraryId, int taskSignupId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var result = await _mediator.SendAsync(new RemoveTeamMemberCommand { TaskSignupId = taskSignupId });

            return RedirectToAction("Details", new { id = itineraryId });
        }

        [HttpGet]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> ConfirmRemoveRequest(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var model = await _mediator.SendAsync(new RequestSummaryQuery { RequestId = requestId });

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

            return View("ConfirmRemoveRequest", model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> RemoveRequest(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var result = await _mediator.SendAsync(new RemoveRequestCommand { RequestId = requestId, ItineraryId = itineraryId });

            return RedirectToAction("Details", new { id = itineraryId });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> MoveRequestUp(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var result = await _mediator.SendAsync(new ReorderRequestCommand { RequestId = requestId, ItineraryId = itineraryId, ReOrderDirection = ReorderRequestCommand.Direction.Up });

            return RedirectToAction("Details", new { id = itineraryId });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> MoveRequestDown(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            var result = await _mediator.SendAsync(new ReorderRequestCommand { RequestId = requestId, ItineraryId = itineraryId, ReOrderDirection = ReorderRequestCommand.Direction.Down });

            return RedirectToAction("Details", new { id = itineraryId });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> MarkComplete(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            // todo: sgordon - Extend this to return success / failure message to the user

            await _mediator.SendAsync(new RequestStatusChangeCommand() { RequestId = requestId, NewStatus = RequestStatus.Completed});

            return RedirectToAction("Details", new { id = itineraryId });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("Admin/Itinerary/{itineraryId}/[Action]/{requestId}")]
        public async Task<IActionResult> MarkIncomplete(int itineraryId, Guid requestId)
        {
            var orgId = await GetOrganizationIdBy(itineraryId);

            if (orgId == 0 || !User.IsOrganizationAdmin(orgId))
            {
                return Unauthorized();
            }

            // todo: sgordon - Extend this to return success / failure message to the user

            await _mediator.SendAsync(new RequestStatusChangeCommand() { RequestId = requestId, NewStatus = RequestStatus.Assigned });

            return RedirectToAction("Details", new { id = itineraryId });
        }

        private async Task<SelectItineraryRequestsViewModel> BuildSelectItineraryRequestsModel(int itineraryId, RequestSearchCriteria criteria)
        {
            var model = new SelectItineraryRequestsViewModel();

            var itinerary = await _mediator.SendAsync(new ItineraryDetailQuery { ItineraryId = itineraryId });

            model.CampaignId = itinerary.CampaignId;
            model.CampaignName = itinerary.CampaignName;
            model.EventId = itinerary.EventId;
            model.EventName = itinerary.EventName;
            model.ItineraryName = itinerary.Name;

            criteria.EventId = itinerary.EventId;

            var requests = await _mediator.SendAsync(new RequestListItemsQuery { Criteria = criteria });

            foreach (var request in requests)
            {
                var selectItem = new RequestSelectViewModel
                {
                    Id = request.Id,
                    Name = request.Name,
                    DateAdded = request.DateAdded,
                    City = request.City,
                    Address = request.Address,
                    Latitude = request.Latitude,
                    Longitude = request.Longitude,
                    Postcode = request.Postcode
                };

                model.Requests.Add(selectItem);
            }

            return model;
        }

        private async Task<int> GetOrganizationIdBy(int intinerayId)
        {
            return await _mediator.SendAsync(new OrganizationIdQuery { ItineraryId = intinerayId });
        }
    }
}


text:
package com.blnz.xsl.sax2;

import org.xml.sax.*;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * performs "pretty-printing" by wrapping  another
 * ContentHandler, intercepting SAX events,
 * and inserting whitespace events as appropriate.
 *
 * ... (Actually, I don't think it adds any
 * indenting, just newlines)
 */
public class Indenter
    implements OutputContentHandler, CommentHandler,
               RawCharactersHandler
{
    private ContentHandler _contentHandler = null;
    private CommentHandler _commentHandler = null;
    private RawCharactersHandler _rawCharactersHandler;
    private char[] _newline = new char[]{'\n'};

    static private final byte IN_PCDATA_CHUNK = 0;
    static private final byte JUST_HAD_START_TAG = 1;
    static private final byte OTHER = 2;

    private byte _state = IN_PCDATA_CHUNK;

    public Indenter(ContentHandler handler,
                    RawCharactersHandler rawCharactersHandler)
    {
        _contentHandler = handler;
        if (handler instanceof CommentHandler) {
            _commentHandler = (CommentHandler)handler;
        } else {
            _commentHandler = null;
        }
        _rawCharactersHandler = rawCharactersHandler;
    }

    public ContentHandler init(Destination dest, Properties atts)
        throws IOException, SAXException
    {
        if (_contentHandler instanceof OutputContentHandler) {
            _contentHandler =
                ( (OutputContentHandler) _contentHandler).init(dest, atts);
        }
        return this;
    }

    public void setDocumentLocator(Locator locator)
    {
        _contentHandler.setDocumentLocator(locator);
    }

    public void startDocument()
        throws SAXException
    {
        _contentHandler.startDocument();
    }

    public void endDocument()
        throws SAXException
    {
        maybeNewline();
        _contentHandler.endDocument();
    }

    public void startElement(String namespaceURI,
                             String localName,
                             String qName,
                             Attributes atts)
        throws SAXException
    {
        maybeNewline();
        _state = JUST_HAD_START_TAG;
        _contentHandler.startElement(namespaceURI, localName, qName, atts);
    }

    public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException
    {
        if (_state == JUST_HAD_START_TAG) {
            _state = OTHER;
        } else {
            maybeNewline();
        }
        _contentHandler.endElement(namespaceURI, localName, qName);
    }

    public void characters(char ch[], int start, int length)
        throws SAXException
    {
        if (length > 0) {
            _contentHandler.characters(ch, start, length);
            _state = IN_PCDATA_CHUNK;
        }
    }

    public void ignorableWhitespace(char ch[], int start, int length)
        throws SAXException
    {
        if (length > 0) {
            _contentHandler.ignorableWhitespace(ch, start, length);
            _state = IN_PCDATA_CHUNK;
        }

    }

    public void rawCharacters(String chars) throws SAXException
    {
        if (chars.length() > 0) {
            _rawCharactersHandler.rawCharacters(chars);
            _state = IN_PCDATA_CHUNK;
        }
    }

    public void startPrefixMapping(String prefix, String namespaceURI)
        throws SAXException
    {
        _contentHandler.startPrefixMapping(prefix, namespaceURI);
    }

    public void endPrefixMapping(String prefix)
        throws SAXException
    {
        _contentHandler.endPrefixMapping(prefix);
    }

    public void skippedEntity(String name)
        throws SAXException
    {
        _contentHandler.skippedEntity(name);
    }

    //
    //
    private final void maybeNewline() throws SAXException
    {
        if (_state != IN_PCDATA_CHUNK) {
            _contentHandler.characters(_newline, 0, 1);
            _newline[0] = '\n';
        }
        _state = OTHER;
    }

    public void processingInstruction(String target, String data)
        throws SAXException
    {
        maybeNewline();
        _contentHandler.processingInstruction(target, data);
    }

    public void comment(String contents)
        throws SAXException
    {
        if (_commentHandler != null) {
            maybeNewline();
            _commentHandler.comment(contents);
        }
    }
}


text:
from __future__ import print_function
import unittest
import numpy as np
import paddle.fluid.core as core
from op_test import OpTest

class TestElementwiseAddOp(OpTest):
    def init_kernel_type(self):
        self.use_mkldnn = False

    def setUp(self):
        self.op_type = "elementwise_add"
        self.dtype = np.float32
        self.axis = -1
        self.init_dtype()
        self.init_input_output()
        self.init_kernel_type()
        self.init_axis()

        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(self.x),
            'Y': OpTest.np_dtype_to_fluid_dtype(self.y)
        }
        self.attrs = {'axis': self.axis, 'use_mkldnn': self.use_mkldnn}
        self.outputs = {'Out': self.out}

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
        if self.dtype == np.float16:
            return
        self.check_grad(['X', 'Y'], 'Out', max_relative_error=0.005)

    def test_check_grad_ingore_x(self):
        if self.dtype == np.float16:
            return
        self.check_grad(
            ['Y'], 'Out', max_relative_error=0.005, no_grad_set=set("X"))

    def test_check_grad_ingore_y(self):
        if self.dtype == np.float16:
            return
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.005, no_grad_set=set('Y'))

    def init_input_output(self):
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)
        self.out = np.add(self.x, self.y)

    def init_dtype(self):
        pass

    def init_axis(self):
        pass

class TestFP16ElementwiseAddOp(TestElementwiseAddOp):
    def init_dtype(self):
        self.dtype = np.float16

    def test_check_output(self):
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
                self.check_output_with_place(place, atol=1e-3)

class TestElementwiseAddOp_scalar(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y

class TestFP16ElementwiseAddOp_scalar(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y

class TestElementwiseAddOp_scalar2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1, 1).astype(self.dtype)
        self.out = self.x + self.y

class TestFP16ElementwiseAddOp_scalar2(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(1, 1).astype(self.dtype)
        self.out = self.x + self.y

class TestElementwiseAddOp_Vector(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.random((32, )).astype(self.dtype)
        self.y = np.random.random((32, )).astype(self.dtype)
        self.out = np.add(self.x, self.y)

class TestFP16ElementwiseAddOp_Vector(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.random((32, )).astype(self.dtype)
        self.y = np.random.random((32, )).astype(self.dtype)
        self.out = np.add(self.x, self.y)

class TestElementwiseAddOp_broadcast_0(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(2).astype(self.dtype)
        self.out = self.x + self.y.reshape(2, 1, 1)

    def init_axis(self):
        self.axis = 0

class TestFP16ElementwiseAddOp_broadcast_0(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(2).astype(self.dtype)
        self.out = self.x + self.y.reshape(2, 1, 1)

    def init_axis(self):
        self.axis = 0

class TestElementwiseAddOp_broadcast_1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(3).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 1)

    def init_axis(self):
        self.axis = 1

class TestFP16ElementwiseAddOp_broadcast_1(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(3).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 1)

    def init_axis(self):
        self.axis = 1

class TestElementwiseAddOp_broadcast_2(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1, 4)

class TestFP16ElementwiseAddOp_broadcast_2(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1, 4)

class TestElementwiseAddOp_broadcast_3(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(3, 4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 4, 1)

    def init_axis(self):
        self.axis = 1

class TestFP16ElementwiseAddOp_broadcast_3(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(3, 4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 4, 1)

    def init_axis(self):
        self.axis = 1

class TestElementwiseAddOp_broadcast_4(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(2, 1).astype(self.dtype)
        self.out = self.x + self.y.reshape(2, 1, 1, 1)

    def init_axis(self):
        self.axis = 0

class TestFP16ElementwiseAddOp_broadcast_4(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(2, 1).astype(self.dtype)
        self.out = self.x + self.y.reshape(2, 1, 1, 1)

    def init_axis(self):
        self.axis = 0

class TestElementwiseAddOp_broadcast_5(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(2, 1, 4).astype(self.dtype)
        self.out = self.x + self.y

class TestFP16ElementwiseAddOp_broadcast_5(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(2, 1, 4).astype(self.dtype)
        self.out = self.x + self.y

class TestElementwiseAddOp_broadcast_6(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(2, 3, 1, 5).astype(self.dtype)
        self.out = self.x + self.y

class TestFP16ElementwiseAddOp_broadcast_6(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4, 5).astype(self.dtype)
        self.y = np.random.rand(2, 3, 1, 5).astype(self.dtype)
        self.out = self.x + self.y

class TestElementwiseAddOp_rowwise_add_0(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(3, 4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 4)

    def init_axis(self):
        self.axis = 1

class TestFP16ElementwiseAddOp_rowwise_add_0(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 3, 4).astype(self.dtype)
        self.y = np.random.rand(3, 4).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 3, 4)

    def init_axis(self):
        self.axis = 1

class TestElementwiseAddOp_rowwise_add_1(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 1).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1)

    def init_axis(self):
        self.axis = 1

class TestFP16ElementwiseAddOp_rowwise_add_1(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(2, 1).astype(self.dtype)
        self.y = np.random.rand(1).astype(self.dtype)
        self.out = self.x + self.y.reshape(1, 1)

    def init_axis(self):
        self.axis = 1

class TestElementwiseAddOp_channelwise_add(TestElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(3, 20, 20).astype(self.dtype)
        self.y = np.random.rand(3, 1, 1).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1

class TestFP16ElementwiseAddOp_channelwise_add(TestFP16ElementwiseAddOp):
    def init_input_output(self):
        self.x = np.random.rand(3, 10, 20).astype(self.dtype)
        self.y = np.random.rand(3, 1, 1).astype(self.dtype)
        self.out = self.x + self.y

    def init_axis(self):
        self.axis = -1

if __name__ == '__main__':
    unittest.main()


text:
// @flow
import Project from '../../Project';
import * as options from '../../utils/options';
import * as yarn from '../../utils/yarn';
import { BoltError } from '../../utils/errors';

export type WorkspaceRunOptions = {
  cwd?: string,
  pkgName: string,
  script: string,
  scriptArgs: options.Args
};

export function toWorkspaceRunOptions(
  args: options.Args,
  flags: options.Flags
): WorkspaceRunOptions {
  /**
   * Unfortunately, in run commands, we are unable to use meow's parsed flags and args as we really
   * want to be able to pass all args and flags to yarn without modification. For example, we could
   * get a flag called `t` and we wont know if `t` was passed in with `--t` or `-t` and could pass it in
   * incorrectly. The only other alternative would be to pass in all flags using the `--` separator
   * and args on the other side e.g `bolt run test src/* -- --watch --bail` which is further away from
   * how yarn handles things and is more complicated for the consumer.
   */
  let [pkgName, script, ...rest] = args;

  const scriptArgIdx = process.argv.indexOf(script);
  // the flags that we'll be passing in as args start after the script name, and we'll pass them all directly
  const scriptArgs = process.argv.slice(scriptArgIdx + 1);

  return {
    cwd: options.string(flags.cwd, 'cwd'),
    pkgName,
    script,
    scriptArgs
  };
}

export async function workspaceRun(opts: WorkspaceRunOptions) {
  let cwd = opts.cwd || process.cwd();
  let project = await Project.init(cwd);
  let packages = await project.getPackages();
  let pkg = await project.getPackageByName(packages, opts.pkgName);

  if (!pkg) {
    throw new BoltError(
      `Could not find a workspace named "${opts.pkgName}" from "${cwd}"`
    );
  }

  let validScript = await yarn.getScript(pkg, opts.script);

  if (!validScript) {
    throw new BoltError(
      `Package at "${pkg.dir}" does not have a script named "${opts.script}"`
    );
  }

  await yarn.run(pkg, opts.script, opts.scriptArgs);
}


text:
'Imports DevExpress.CodeRush.Core
'Imports DevExpress.CodeRush.Menus
'Imports System.Drawing

'Public Class Settings
'#Region "Fields"
'    Private mEnabled As Boolean = True ' Default to On
'    Private mMetric As ICodeMetricProvider
'    Private mVisualizeButton As IMenuButton
'    Private mFirstBoundary As Double = 0.25
'    Private mSecondBoundary As Double = 0.5
'    Private mThirdBoundary As Double = 0.75
'    Private mOpacity1 As Integer = 30
'    Private mOpacity2 As Integer = 50
'    Private mOpacity3 As Integer = 75
'    Private mColor1 As Color = Color.Green
'    Private mColor2 As Color = Color.Orange
'    Private mColor3 As Color = Color.Red
'#End Region
'#Region "Simple Properties"
'    Public Property Enabled() As Boolean
'        Get
'            Return mEnabled
'        End Get
'        Set(ByVal value As Boolean)
'            mEnabled = value
'        End Set
'    End Property
'    Public Property Metric() As ICodeMetricProvider
'        Get
'            Return mMetric
'        End Get
'        Set(ByVal value As ICodeMetricProvider)
'            mMetric = value
'        End Set
'    End Property
'    Public Property VisualizeButton() As IMenuButton
'        Get
'            Return mVisualizeButton
'        End Get
'        Set(ByVal value As IMenuButton)
'            mVisualizeButton = value
'        End Set
'    End Property
'    Public Property FirstBoundary() As Double
'        Get
'            Return mFirstBoundary
'        End Get
'        Set(ByVal value As Double)
'            mFirstBoundary = value
'        End Set
'    End Property
'    Public Property SecondBoundary() As Double
'        Get
'            Return mSecondBoundary
'        End Get
'        Set(ByVal value As Double)
'            mSecondBoundary = value
'        End Set
'    End Property
'    Public Property ThirdBoundary() As Double
'        Get
'            Return mThirdBoundary
'        End Get
'        Set(ByVal value As Double)
'            mThirdBoundary = value
'        End Set
'    End Property
'    Public Property Opacity1() As Integer
'        Get
'            Return mOpacity1
'        End Get
'        Set(ByVal value As Integer)
'            mOpacity1 = value
'        End Set
'    End Property
'    Public Property Opacity2() As Integer
'        Get
'            Return mOpacity2
'        End Get
'        Set(ByVal value As Integer)
'            mOpacity2 = value
'        End Set
'    End Property
'    Public Property Opacity3() As Integer
'        Get
'            Return mOpacity3
'        End Get
'        Set(ByVal value As Integer)
'            mOpacity3 = value
'        End Set
'    End Property
'    Public Property Color1() As Color
'        Get
'            Return mColor1
'        End Get
'        Set(ByVal value As Color)
'            mColor1 = value
'        End Set
'    End Property
'    Public Property Color2() As Color
'        Get
'            Return mColor2
'        End Get
'        Set(ByVal value As Color)
'            mColor2 = value
'        End Set
'    End Property
'    Public Property Color3() As Color
'        Get
'            Return mColor3
'        End Get
'        Set(ByVal value As Color)
'            mColor3 = value
'        End Set
'    End Property
'#End Region
'End Class


text:
/* stats.h - statistics from the bus driver
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#ifndef BUS_STATS_H
#define BUS_STATS_H

#include "bus.h"

#define BUS_INTERFACE_STATS "org.freedesktop.DBus.Debug.Stats"

dbus_bool_t bus_stats_handle_get_stats (DBusConnection *connection,
                                        BusTransaction *transaction,
                                        DBusMessage    *message,
                                        DBusError      *error);

dbus_bool_t bus_stats_handle_get_connection_stats (DBusConnection *connection,
                                                   BusTransaction *transaction,
                                                   DBusMessage    *message,
                                                   DBusError      *error);

#endif /* multiple-inclusion guard */


text:
namespace LearningSystem.Web.Models.Account
{
    using System.ComponentModel.DataAnnotations;

    public class LoginViewModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }
}


text:
####
# 06/2010 Nic Wolfe <nic@wolfeden.ca>
# 02/2006 Will Holcomb <wholcomb@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#

import urllib
import urllib2
import mimetools, mimetypes
import os, sys

# Controls how sequences are uncoded. If true, elements may be given multiple values by
#  assigning a sequence.
doseq = 1

class MultipartPostHandler(urllib2.BaseHandler):
    handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first

    def http_request(self, request):
        data = request.get_data()
        if data is not None and type(data) != str:
            v_files = []
            v_vars = []
            try:
                for(key, value) in data.items():
                    if type(value) in (file, list, tuple):
                        v_files.append((key, value))
                    else:
                        v_vars.append((key, value))
            except TypeError:
                systype, value, traceback = sys.exc_info()
                raise TypeError, "not a valid non-string sequence or mapping object", traceback

            if len(v_files) == 0:
                data = urllib.urlencode(v_vars, doseq)
            else:
                boundary, data = MultipartPostHandler.multipart_encode(v_vars, v_files)
                contenttype = 'multipart/form-data; boundary=%s' % boundary
                if(request.has_header('Content-Type')
                   and request.get_header('Content-Type').find('multipart/form-data') != 0):
                    print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data')
                request.add_unredirected_header('Content-Type', contenttype)

            request.add_data(data)
        return request

    @staticmethod
    def multipart_encode(vars, files, boundary = None, buffer = None):
        if boundary is None:
            boundary = mimetools.choose_boundary()
        if buffer is None:
            buffer = ''
        for(key, value) in vars:
            buffer += '--%s\r\n' % boundary
            buffer += 'Content-Disposition: form-data; name="%s"' % key
            buffer += '\r\n\r\n' + value + '\r\n'
        for(key, fd) in files:

            # allow them to pass in a file or a tuple with name & data
            if type(fd) == file:
                name_in = fd.name
                fd.seek(0)
                data_in = fd.read()
            elif type(fd) in (tuple, list):
                name_in, data_in = fd

            filename = os.path.basename(name_in)
            contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
            buffer += '--%s\r\n' % boundary
            buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
            buffer += 'Content-Type: %s\r\n' % contenttype
            # buffer += 'Content-Length: %s\r\n' % file_size
            buffer += '\r\n' + data_in + '\r\n'
        buffer += '--%s--\r\n\r\n' % boundary
        return boundary, buffer

    https_request = http_request


text:
<?php

namespace AppBundle\Service;

use Doctrine\Bundle\DoctrineBundle\Registry;
use DataBundle\Entity\Application;

class ExceptionTypeGraphService
{
    /**
     * @var Registry
     */
    private $doctrine;

    public function __construct($doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function getData(Application $application = null)
    {
        if (!$application) {
            $sql = sprintf(
                    'select class as label, count(*) as value from incident group by class'
            );
        } else {
            $sql = sprintf(
                    'select class as label, count(*) as value from incident where application_id = %s group by class', $application->getId()
            );
        }

        $stmt = $this->doctrine->getManager()->getConnection()->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll();

        return $result;
    }
}


text:
# frozen_string_literal: true

require 'spec_helper'

require File.expand_path('../pages/base_page.rb', __FILE__)
Dir.glob(File.expand_path('../pages/**/*.rb', __FILE__)).each do |filename|
  require filename
end

Dir.glob(File.expand_path('../utilities/**/*.rb', __FILE__)).each do |filename|
  require filename
end

Capybara.register_driver :poltergeist do |app|
  options = {
    phantomjs_options: [
      '--ssl-protocol=tlsv1.2'
    ]
  }
  Capybara::Poltergeist::Driver.new(app, options)
end

RSpec.configure do |config|
  config.before(:example) do
    InitializeExample.require_version_number
  end
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Claim Your APIs and Microservices Certificate</title>

Go to
        Claim Your APIs and Microservices Certificate
        and get your certificate.

        Congratulations


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="reportMngr" class="org.webcurator.core.report.ReportManager">
		<property name="reports">
			<list>
				<ref bean="systemUsageReport"/>
				<ref bean="systemActivityReport"/>
				<ref bean="crawlerActivityReport"/>
				<ref bean="targetGroupSchedulesReport"/>
				<ref bean="summaryTargetSchedulesReport"/>
			</list>
		</property>
	</bean>

	<bean id="systemUsageReport" class="org.webcurator.core.report.Report">
		<property name="name" value="System Usage Report"></property>
		<property name="description" value="A report showing who logged in to the system."></property>
		<property name="info" value=" Start Date is inclusive.
End Date is exclusive "></property>
		<property name="reportGenerator">
			<ref bean="systemUsageReportGeneratorImpl" />
		</property>
		<property name="parameters">
			<list>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="startDate"></property>
					<property name="description" value="Start Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="endDate"></property>
					<property name="description" value="End Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.AgencyParameter">
					<property name="name" value="agency"></property>
					<property name="description" value="Agencies"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
			</list>
		</property>
	</bean>

	<bean id="systemUsageReportGeneratorImpl" class="org.webcurator.core.report.impl.SystemUsageReportGeneratorImpl">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

	<bean id="systemActivityReport" class="org.webcurator.core.report.Report">
		<property name="name" value="System Activity Report"></property>
		<property name="description" value="A report showing the actions performed by users of the system."></property>
		<property name="info" value=" Start Date is inclusive.
End Date is exclusive "></property>
		<property name="reportGenerator">
			<ref bean="systemActivityReportGeneratorImpl" />
		</property>
		<property name="parameters">
			<list>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="startDate"></property>
					<property name="description" value="Start Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="endDate"></property>
					<property name="description" value="End Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.AgencyParameter">
					<property name="name" value="agency"></property>
					<property name="description" value="Agencies"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.UserParameter">
					<property name="name" value="user"></property>
					<property name="description" value="Users"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
			</list>
		</property>
	</bean>

	<bean id="systemActivityReportGeneratorImpl" class="org.webcurator.core.report.impl.SystemActivityReportGeneratorImpl">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>

	<bean id="crawlerActivityReport" class="org.webcurator.core.report.Report">
		<property name="name" value="Crawler Activity Report"/>
		<property name="description" value="A report showing which sites have been crawled, and some statistics on those crawls."/>
		<property name="info" value=" Start Date is inclusive.
End Date is exclusive "/>
		<property name="parameters">
			<list>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="startDate"></property>
					<property name="description" value="Start Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.DateParameter">
					<property name="name" value="endDate"></property>
					<property name="description" value="End Date"></property>
					<property name="optional" value="false"></property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.AgencyParameter">
					<property name="name" value="agency"></property>
					<property name="description" value="Agencies"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.UserParameter">
					<property name="name" value="user"></property>
					<property name="description" value="Users"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
			</list>
		</property>
		<property name="reportGenerator">
			<bean class="org.webcurator.core.report.impl.CrawlerActivityReport">
				<property name="sessionFactory" ref="sessionFactory"/>
			</bean>
		</property>
	</bean>

	<bean id="targetGroupSchedulesReport" class="org.webcurator.core.report.Report">
		<property name="name" value="Target/Group Schedules Report"></property>
		<property name="description" value="A report showing the harvest schedules for `Approved’ Targets/Groups."></property>
		<property name="info" value=""></property>
		<property name="parameters">
			<list>
				<bean class="org.webcurator.core.report.parameter.AgencyParameter">
					<property name="name" value="agency"></property>
					<property name="description" value="Agencies"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.UserParameter">
					<property name="name" value="user"></property>
					<property name="description" value="Users"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
				<bean class="org.webcurator.core.report.parameter.TargetTypeParameter">
					<property name="name" value="targettype"></property>
					<property name="description" value="Target Types"></property>
					<property name="optional" value="true"></property>
				</bean>
			</list>
		</property>
		<property name="reportGenerator">
			<bean class="org.webcurator.core.report.impl.TargetGroupSchedulesReport">
				<property name="sessionFactory" ref="sessionFactory"/>
			</bean>
		</property>
	</bean>

	<bean id="summaryTargetSchedulesReport" class="org.webcurator.core.report.Report">
		<property name="name" value="Summary Target Schedules Report"></property>
		<property name="description" value="A summary report showing the harvest schedules for `Approved’ Targets/Groups."></property>
		<property name="info" value=""></property>
		<property name="parameters">
			<list>
				<bean class="org.webcurator.core.report.parameter.AgencyParameter">
					<property name="name" value="agency"></property>
					<property name="description" value="Agencies"></property>
					<property name="optional" value="true"></property>
					<property name="agencyUserManager">
						<ref bean="agencyUserManager"/>
					</property>
					<property name="authorityManager">
						<ref bean="authorityManager"/>
					</property>
				</bean>
			</list>
		</property>
		<property name="reportGenerator">
			<bean class="org.webcurator.core.report.impl.SummaryTargetSchedulesReport">
				<property name="sessionFactory" ref="sessionFactory"/>
			</bean>
		</property>
	</bean>

</beans>


text:
page_type: sample
products:
- office-sp
languages:
- javascript
- typescript
extensions:
  contentType: samples
  technologies:
  - SharePoint Framework
  platforms:
  - React
  createdDate: 1/1/2016 12:00:00 AM
---
# Multi-page Web Parts

## Summary

Sample SharePoint Framework client-side web parts built using React illustrating building multi-page web parts.

### Poll

Sample poll web part allowing users to vote and view the results.

![Poll web part built on the SharePoint Framework using React](./assets/poll-preview.gif)

## Compatibility

![SPFx 1.0.0](https://img.shields.io/badge/SPFx-1.0.0-green.svg)
![Node.js v6](https://img.shields.io/badge/Node.js-v6-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Compatible SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Compatible-green.svg)
![Compatible with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Compatible-green.svg)
![Local Workbench Compatible](https://img.shields.io/badge/Local%20Workbench-Compatible-green.svg)
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)

## Applies to

* [SharePoint Framework Developer Preview](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)

## Solution

Solution|Author(s)
--------|---------
react-multipage|[Waldek Mastykarz](https://github.com/waldekmastykarz) (MVP, Rencore, @waldekm)

## Version history

Version|Date|Comments
-------|----|--------
1.0.1|May 1 2017|Updated to SPFx GA
1.0.0|November 15, 2016|Initial release

## Prerequisites

- Site Collection created under the **/sites/** Managed Path

## Minimal Path to Awesome

### Poll web part

>  This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.

- create list for the poll
  - in SharePoint create a new list
  - in the list add new column called `NumVotes` of type **Number** (you can change the name later if you want)
  - in the list add a few items - each representing one of the vote options in your poll (for example for a poll about favorite JavaScript frameworks you would add items like _Angular_, _React_, _jQuery_, etc.)
- deploy SharePoint workbench
  - clone this repo
  - in the command line run
    - `npm i`
    - `gulp serve --nobrowser`
  - from the **./temp** directory create a copy of the **workbench.html** file and rename it to **workbench.aspx**
  - in the **workbench.aspx** file change the value of the **webAbsoluteUrl** property to the absolute URL of your SharePoint site
  - upload the **workbench.aspx** file to a document library in your site
- use the web part
  - in your web browser navigate to the **workbench.aspx** page uploaded in your SharePoint site
  - add the Poll web part to the canvas
  - in the configuration specify the **Poll title** and optionally the **Poll description**. Also specify the title of your poll list
  - confirm the changes by clicking the **Apply** button
  - select one of the vote options and click the **Vote** button to submit your vote

![Poll web part built on the SharePoint Framework using React](./assets/poll-preview.gif)

## Features

This project contains sample client-side web parts built on the SharePoint Framework using React illustrating working with multi-page web parts.

This sample illustrates the following concepts on top of the SharePoint Framework:

- using React for building SharePoint Framework client-side web parts
- using React components for building multi-page web parts
- using React spread operator for passing multiple properties to React components
- conditionally rendering React components
- managing state in a parent component
- navigating between the different pages without changing the URL
- styling React applications using Office UI Fabric
- using non-reactive web part property pane
- chaining multiple ES6 promises
- reading and updating SharePoint list items using the SharePoint Framework HttpClient
- showing charts using [Chart.js](http://www.chartjs.org) and [React wrapper for Chart.js](https://github.com/gor181/react-chartjs-2)

## Help

We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for  community members to volunteer their time and help resolve issues.

If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.

You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-multipage%22) to see if anybody else is having the same issues.

You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-multipage) and see what the community is saying.

If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-multipage&template=bug-report.yml&sample=react-multipage&authors=@waldekmastykarz&title=react-multipage%20-%20).

For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-multipage&template=question.yml&sample=react-multipage&authors=@waldekmastykarz&title=react-multipage%20-%20).

Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-multipage&template=suggestion.yml&sample=react-multipage&authors=@waldekmastykarz&title=react-multipage%20-%20).

## Disclaimer

**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

<img src="https://pnptelemetry.azurewebsites.net/sp-dev-fx-webparts/samples/react-multipage" />


text:
import AV from 'leancloud-storage';
import { APP_ID, APP_KEY } from '../../../test/configs';

import './file-message-and-subclasses';
import './location-message';

AV.init({
  appId: APP_ID,
  appKey: APP_KEY,
});


text:
#include "emailmessagelistmodel.h"
//#include <QMailMessage>
//#include <QMailMessageKey>
#include <qmailstore.h>
//#include <QMailServiceAction>
#include <QDateTime>
#include <QTimer>
#include <QProcess>
#include <qmailnamespace.h>

QString EmailMessageListModel::bodyHtmlText(QMailMessagePartContainer *container) const
{
    QMailMessageContentType contentType = container->contentType();

    if (container->multipartType() == QMailMessagePartContainerFwd::MultipartNone)
    {
        if (contentType.subType().toLower() == "html")
        {
            if (container->hasBody() && container->body().data().size() > 1)
                return container->body().data();
            else
            {
                connect (m_retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
                                            this, SLOT(downloadActivityChanged(QMailServiceAction::Activity)));
                QMailMessage *msg = (QMailMessage *)container;
                QMailMessageIdList ids;
                ids << msg->id();
                m_retrievalAction->retrieveMessages(ids, QMailRetrievalAction::Content);
                return " ";  // Put a space here as a place holder to notify UI that we do have html body.
                             // Should find a better way.
            }
        }
        return "";
    }

    if (!container->contentAvailable())
    {
        // if content is not available, attempts to downlaod from the server.
        connect (m_retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
                                            this, SLOT(downloadActivityChanged(QMailServiceAction::Activity)));
        QMailMessage *msg = (QMailMessage *)container;
        QMailMessageIdList ids;
        ids << msg->id();
        m_retrievalAction->retrieveMessages(ids, QMailRetrievalAction::Content);
        return " ";  // Put a space here as a place holder to notify UI that we do have html body.
    }

    QString text("");
    for ( uint i = 0; i < container->partCount(); i++ )
    {
        QMailMessagePart messagePart = container->partAt(i);
        contentType = messagePart.contentType();
        if (contentType.type().toLower() == "text" && contentType.subType().toLower() == "html")
        {
            if (messagePart.hasBody())
            {
                text += messagePart.body().data();
            }
            else
            {
                connect (m_retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
                                            this, SLOT(downloadActivityChanged(QMailServiceAction::Activity)));

                QMailMessagePart::Location location = messagePart.location();
                m_retrievalAction->retrieveMessagePart(location);
                text = " ";
                break;
            }
        }
        QMailMessagePart subPart;
        for (uint j = 0; j < messagePart.partCount(); j++)
        {
            subPart = messagePart.partAt(j);
            contentType = subPart.contentType();
            if (contentType.type().toLower() == "text" && contentType.subType().toLower() == "html")
            {
                if (subPart.hasBody())
                {
                    text += subPart.body().data();
                }
                else
                {
                    connect (m_retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
                                                this, SLOT(downloadActivityChanged(QMailServiceAction::Activity)));
                    QMailMessagePart::Location location = subPart.location();
                    m_retrievalAction->retrieveMessagePart(location);
                    text = " ";
                    break;
                }
            }
        }
    }
    return text;
}

QString EmailMessageListModel::bodyPlainText(const QMailMessage &mailMsg) const
{
    QMailMessagePartContainer *container = (QMailMessagePartContainer *)&mailMsg;
    QMailMessageContentType contentType = container->contentType();
    if (container->hasBody() && contentType.type().toLower() == "text" &&
               contentType.subType().toLower() == "plain")
    {
        return container->body().data();

    }

    QString text("");
    for ( uint i = 0; i < container->partCount(); i++ )
    {
        QMailMessagePart messagePart = container->partAt(i);

        contentType = messagePart.contentType();
        if (messagePart.hasBody() && contentType.type().toLower() == "text" &&
                                     contentType.subType().toLower() == "plain")
        {
            text += messagePart.body().data() + "\n";
        }
        QMailMessagePart subPart;
        for (uint j = 0; j < messagePart.partCount(); j++)
        {
            subPart = messagePart.partAt(j);
            contentType = subPart.contentType();
            if (subPart.hasBody() && contentType.type().toLower() == "text" &&
                                     contentType.subType().toLower() == "plain")
                text += subPart.body().data() + "\n";
        }
    }
    return text;
}

//![0]
EmailMessageListModel::EmailMessageListModel(QObject *parent)
    : QMailMessageListModel(parent),
      m_retrievalAction(new QMailRetrievalAction(this)),
      m_storageAction(new QMailStorageAction(this))
{
    QHash<int, QByteArray> roles;
    roles[QMailMessageModelBase::MessageAddressTextRole] = "sender";
    roles[QMailMessageModelBase::MessageSubjectTextRole] = "subject";
    roles[QMailMessageModelBase::MessageFilterTextRole] = "messageFilter";
    roles[QMailMessageModelBase::MessageTimeStampTextRole] = "timeStamp";
    roles[QMailMessageModelBase::MessageSizeTextRole] = "size";
    roles[QMailMessageModelBase::MessageTypeIconRole] = "icon";
    roles[QMailMessageModelBase::MessageStatusIconRole] = "statusIcon";
    roles[QMailMessageModelBase::MessageDirectionIconRole] = "directionIcon";
    roles[QMailMessageModelBase::MessagePresenceIconRole] = "presenceIcon";
    roles[QMailMessageModelBase::MessageBodyTextRole] = "body";
    roles[QMailMessageModelBase::MessageIdRole] = "messageId";
    roles[MessageAttachmentCountRole] = "numberOfAttachments";
    roles[MessageAttachmentsRole] = "listOfAttachments";
    roles[MessageRecipientsRole] = "recipients";
    roles[MessageRecipientsDisplayNameRole] = "recipientsDisplayName";
    roles[MessageReadStatusRole] = "readStatus";
    roles[MessageHtmlBodyRole] = "htmlBody";
    roles[MessageQuotedBodyRole] = "quotedBody";
    roles[MessageUuidRole] = "messageUuid";
    roles[MessageSenderDisplayNameRole] = "senderDisplayName";
    roles[MessageSenderEmailAddressRole] = "senderEmailAddress";
    roles[MessageCcRole] = "cc";
    roles[MessageBccRole] = "bcc";
    roles[MessageTimeStampRole] = "qDateTime";
    roles[MessageSelectModeRole] = "selected";
    setRoleNames(roles);

    initMailServer();
    QMailAccountIdList ids = QMailStore::instance()->queryAccounts(
            QMailAccountKey::status(QMailAccount::Enabled, QMailDataComparator::Includes),
            QMailAccountSortKey::name());

    QMailMessageKey accountKey = QMailMessageKey::parentAccountId(ids);
    QMailMessageListModel::setKey(accountKey);
    m_key = key();
    QMailMessageSortKey sortKey = QMailMessageSortKey::timeStamp(Qt::DescendingOrder);
    QMailMessageListModel::setSortKey(sortKey);
    m_selectedMsgIds.clear();
}

EmailMessageListModel::~EmailMessageListModel()
{
    delete m_retrievalAction;
    delete m_storageAction;
}

int EmailMessageListModel::rowCount(const QModelIndex & parent) const {
    return QMailMessageListModel::rowCount(parent);
}

QVariant EmailMessageListModel::data(const QModelIndex & index, int role) const {
    if (!index.isValid() || index.row() > rowCount(parent(index)))
        return QVariant();

    if (role == QMailMessageModelBase::MessageTimeStampTextRole)
    {
        QMailMessageId msgId = idFromIndex(index);
        QMailMessage message(msgId);
        QDateTime timeStamp = message.receivedDate().toLocalTime();
        return (timeStamp.toString("hh:mm MM/dd/yyyy"));
    }
    else if (role == MessageAttachmentCountRole)
    {
        // return number of attachments
        QMailMessage message(idFromIndex(index));
        if (!message.status() & QMailMessageMetaData::HasAttachments)
            return 0;

        int numberOfAttachments = 0;
        for (uint i = 1; i < message.partCount(); i++)
        {
            QMailMessagePart sourcePart = message.partAt(i);
            if (!(sourcePart.multipartType() == QMailMessagePartContainer::MultipartNone))
                continue;

            QMailMessageContentType contentType = sourcePart.contentType();
            if (sourcePart.hasBody() && contentType.type().toLower() == "text" &&
                                     contentType.subType().toLower() == "plain")
                continue;

            if (i == 1 && contentType.type().toLower() == "text" && contentType.subType().toLower() == "html")
                continue;

            numberOfAttachments += 1;
        }
        return numberOfAttachments;
    }
    else if (role == MessageAttachmentsRole)
    {
        // return a stringlist of attachments
        QMailMessage message(idFromIndex(index));
        if (!message.status() & QMailMessageMetaData::HasAttachments)
            return QStringList();

        QStringList attachments;
        for (uint i = 1; i < message.partCount(); i++)
        {
            QMailMessagePart sourcePart = message.partAt(i);
            if (!(sourcePart.multipartType() == QMailMessagePartContainer::MultipartNone))
                continue;

            QMailMessageContentType contentType = sourcePart.contentType();
            if (sourcePart.hasBody() && contentType.type().toLower() == "text" &&
                                     contentType.subType().toLower() == "plain")
                continue;

            if (i == 1 && contentType.type().toLower() == "text" && contentType.subType().toLower() == "html")
                continue;

            attachments << sourcePart.displayName();
        }

        return attachments;
    }
    else if (role == MessageRecipientsRole)
    {
        QMailMessage message (idFromIndex(index));
        QStringList recipients;
        QList<QMailAddress> addresses = message.to();
        foreach (QMailAddress address, addresses)
        {
            recipients << address.address();
        }
        return recipients;
    }
    else if (role == MessageRecipientsDisplayNameRole)
    {
        QMailMessage message (idFromIndex(index));
        QStringList recipients;
        QList<QMailAddress> addresses = message.to();
        foreach (QMailAddress address, addresses)
        {
            recipients << address.name();
        }
        return recipients;
    }
    else if (role == MessageReadStatusRole)
    {
        QMailMessage message (idFromIndex(index));
        quint64 status = message.status();

        if (status & QMailMessage::Read)
            return 1;			// 1 for read
        else
            return 0;			// 0 for unread
    }
    else if (role == QMailMessageModelBase::MessageBodyTextRole)
    {
        QMailMessage message (idFromIndex(index));
        return (bodyPlainText(message));
    }
    else if (role == MessageHtmlBodyRole)
    {
        QMailMessage message (idFromIndex(index));
        return (bodyHtmlText(&message));
    }
    else if (role == MessageQuotedBodyRole)
    {
        QMailMessage message (idFromIndex(index));
        QString body = bodyPlainText(message);
        body.prepend('\n');
        body.replace('\n', "\n>");
        body.truncate(body.size() - 1);  // remove the extra ">" put there by QString.replace
        return body;
    }
    else if (role == MessageUuidRole)
    {
        QMailMessageId messageId = idFromIndex(index);
        QString uuid = QString::number(messageId.toULongLong());
        QMailMessage newId = QMailMessageId (uuid.toULongLong());
        QMailMessage message (newId);
        QString body = message.body().data();
        return uuid;
    }
    else if (role == MessageSenderDisplayNameRole)
    {
        QMailMessage message (idFromIndex(index));
        return message.from().name();
    }
    else if (role == MessageSenderEmailAddressRole)
    {
        QMailMessage message (idFromIndex(index));
        return message.from().address();
    }
    else if (role == MessageCcRole)
    {
        QMailMessage message (idFromIndex(index));
        return QMailAddress::toStringList (message.cc());
    }
    else if (role == MessageBccRole)
    {
        QMailMessage message (idFromIndex(index));
        return QMailAddress::toStringList (message.bcc());
    }
    else if (role == MessageTimeStampRole)
    {
        QMailMessage message (idFromIndex(index));
        return (message.date().toLocalTime());
    }
    else if (role == MessageSelectModeRole)
    {
       int selected = 0;
       QMailMessageId msgId = idFromIndex(index);
       if (m_selectedMsgIds.contains(msgId) == true)
           selected = 1;
        return (selected);
    }

    return QMailMessageListModel::data(index, role);
}

void EmailMessageListModel::setSearch(const QString search)
{

    if(search.isEmpty())
    {
        setKey(QMailMessageKey::nonMatchingKey());
    }else
    {
        if(m_search == search)
            return;
        QMailMessageKey subjectKey = QMailMessageKey::subject(search, QMailDataComparator::Includes);
        QMailMessageKey toKey = QMailMessageKey::recipients(search, QMailDataComparator::Includes);
        QMailMessageKey fromKey = QMailMessageKey::sender(search, QMailDataComparator::Includes);
        setKey(m_key & (subjectKey | toKey | fromKey));
    }
    m_search = search;
}

void EmailMessageListModel::setFolderKey (QVariant id)
{
    m_currentFolderId = id.value<QMailFolderId>();
    if (!m_currentFolderId.isValid())
        return;
    QMailMessageKey folderKey = QMailMessageKey::parentFolderId(m_currentFolderId);
    QMailMessageListModel::setKey(folderKey);
    m_key=key();
    QMailMessageSortKey sortKey = QMailMessageSortKey::timeStamp(Qt::DescendingOrder);
    QMailMessageListModel::setSortKey(sortKey);
}

void EmailMessageListModel::setAccountKey (QVariant id)
{
    QMailAccountId accountId = id.value<QMailAccountId>();
    QMailAccountIdList ids;
    if (!accountId.isValid() || id == -1)
    {
        ids = QMailStore::instance()->queryAccounts(
                QMailAccountKey::status(QMailAccount::Enabled, QMailDataComparator::Includes),
                QMailAccountSortKey::name());
    }
    else
        ids << accountId;

    QMailFolderIdList folderIdList;

    for (int i = 0; i < ids.size(); i++)
    {
        QMailFolderKey key = QMailFolderKey::parentAccountId(accountId);
        QMailFolderIdList  mailFolderIds = QMailStore::instance()->queryFolders(key);
        foreach (QMailFolderId folderId, mailFolderIds)
        {
            QMailFolder folder(folderId);
            if (QString::compare(folder.displayName(), "INBOX", Qt::CaseInsensitive) == 0)
            {
                folderIdList << folderId;
                break;
            }
        }
    }

    QMailMessageKey accountKey = QMailMessageKey::parentAccountId(ids);
    QMailMessageListModel::setKey(accountKey);

    // default to INBOX for now
    QMailMessageKey folderKey = QMailMessageKey::parentFolderId(folderIdList);
    QMailMessageListModel::setKey(folderKey);//!FIXME: should this be folderKey&accountKey?

    QMailMessageSortKey sortKey = QMailMessageSortKey::timeStamp(Qt::DescendingOrder);
    QMailMessageListModel::setSortKey(sortKey);

    m_key= key();

}

void EmailMessageListModel::sortBySender(int key)
{
    impl()->reset();
    QMailMessageSortKey sortKey;
    if (key == 0)  // descending
        sortKey = QMailMessageSortKey::sender(Qt::DescendingOrder);
    else
        sortKey = QMailMessageSortKey::sender(Qt::AscendingOrder);

    QMailMessageListModel::setSortKey(sortKey);
}

void EmailMessageListModel::sortBySubject(int key)
{
    QMailMessageSortKey sortKey;
    if (key == 0)  // descending
        sortKey = QMailMessageSortKey::subject(Qt::DescendingOrder);
    else
        sortKey = QMailMessageSortKey::subject(Qt::AscendingOrder);

    QMailMessageListModel::setSortKey(sortKey);
}

void EmailMessageListModel::sortByDate(int key)
{
    QMailMessageSortKey sortKey;
    if (key == 0)  // descending
        sortKey = QMailMessageSortKey::timeStamp(Qt::DescendingOrder);
    else
        sortKey = QMailMessageSortKey::timeStamp(Qt::AscendingOrder);

    QMailMessageListModel::setSortKey(sortKey);
}

void EmailMessageListModel::sortByAttachment(int key)
{
    // TDB
    Q_UNUSED(key);
}

void EmailMessageListModel::initMailServer()
{
    QString lockfile = "messageserver-instance.lock";
    int id = QMail::fileLock(lockfile);
    if (id == -1) {
        // Server is currently running
        return;
    }
    QMail::fileUnlock(id);

    m_messageServerProcess.start("/usr/bin/messageserver");
    m_messageServerProcess.waitForStarted();
    return;
}

QVariant EmailMessageListModel::indexFromMessageId (QString uuid)
{
    quint64 id = uuid.toULongLong();
    QMailMessageId msgId (id);
    for (int row = 0; row < rowCount(); row++)
    {
        QVariant vMsgId = data(index(row), QMailMessageModelBase::MessageIdRole);

        if (msgId == vMsgId.value<QMailMessageId>())
            return row;
    }
    return -1;
}

QVariant EmailMessageListModel::messageId (int idx)
{
    QMailMessageId id = idFromIndex (index(idx));
    return id;
}

QVariant EmailMessageListModel::subject (int idx)
{
    QMailMessageId id = idFromIndex (index(idx));
    QMailMessage msg(id);
    return msg.subject();
}

QVariant EmailMessageListModel::mailSender (int idx)
{
    return data(index(idx), QMailMessageModelBase::MessageAddressTextRole);
}

QVariant EmailMessageListModel::timeStamp (int idx)
{
    return data(index(idx), QMailMessageModelBase::MessageTimeStampTextRole);
}

QVariant EmailMessageListModel::body (int idx)
{
    return data(index(idx), QMailMessageModelBase::MessageBodyTextRole);
}

QVariant EmailMessageListModel::quotedBody (int idx)
{
    return data(index(idx), MessageQuotedBodyRole);
}

QVariant EmailMessageListModel::htmlBody (int idx)
{
    return data(index(idx), MessageHtmlBodyRole);
}

QVariant EmailMessageListModel::attachments (int idx)
{
    return data(index(idx), MessageAttachmentsRole);
}

QVariant EmailMessageListModel::numberOfAttachments (int idx)
{
    return data(index(idx), MessageAttachmentCountRole);
}

QVariant EmailMessageListModel::toList (int idx)
{
    return data(index(idx), MessageRecipientsRole);
}

QVariant EmailMessageListModel::recipients (int idx)
{
    QMailMessageId msgId = idFromIndex(index(idx));
    QMailMessage message(msgId);
    QStringList recipients;

    QMailAccount mailAccount (message.parentAccountId());
    QString myEmailAddress = mailAccount.fromAddress().address();

    QList<QMailAddress> addresses;
    addresses = message.to() + message.cc() + message.bcc();
    foreach (QMailAddress address, addresses)
    {
        QString emailAddress = address.address();
        if (QString::compare(myEmailAddress, emailAddress, Qt::CaseInsensitive) != 0)
            recipients << address.toString();
    }
    return recipients;
}

QVariant EmailMessageListModel::ccList (int idx)
{
    return data(index(idx), MessageCcRole);
}

QVariant EmailMessageListModel::bccList (int idx)
{
    return data(index(idx), MessageBccRole);
}

QVariant EmailMessageListModel::messageRead (int idx)
{
    return data(index(idx), MessageReadStatusRole);
}

int EmailMessageListModel::messagesCount ()
{
    return rowCount();
}

void EmailMessageListModel::deSelectAllMessages()
{
    if (m_selectedMsgIds.size() == 0)
        return;

    QMailMessageIdList msgIds = m_selectedMsgIds;
    m_selectedMsgIds.clear();
    foreach (QMailMessageId msgId,  msgIds)
    {
        for (int row = 0; row < rowCount(); row++)
        {
            QVariant vMsgId = data(index(row), QMailMessageModelBase::MessageIdRole);

            if (msgId == vMsgId.value<QMailMessageId>())
                dataChanged (index(row), index(row));
        }
    }
}

void EmailMessageListModel::selectMessage( int idx )
{
    QMailMessageId msgId = idFromIndex(index(idx));

    if (!m_selectedMsgIds.contains (msgId))
    {
        m_selectedMsgIds.append(msgId);
    dataChanged(index(idx), index(idx));
    }
}

void EmailMessageListModel::deSelectMessage (int idx )
{
    QMailMessageId msgId = idFromIndex(index(idx));

    m_selectedMsgIds.removeOne(msgId);
    dataChanged(index(idx), index(idx));
}

void EmailMessageListModel::deleteSelectedMessageIds()
{
    if (m_selectedMsgIds.size() == 0)
        return;
    QMailMessage msg (m_selectedMsgIds[0]);
    m_storageAction->deleteMessages(m_selectedMsgIds);
    m_selectedMsgIds.clear();
    m_retrievalAction->exportUpdates(msg.parentAccountId());
}

void EmailMessageListModel::downloadActivityChanged(QMailServiceAction::Activity activity)
{
    if (QMailServiceAction *action = static_cast<QMailServiceAction*>(sender()))
    {
        if (activity == QMailServiceAction::Successful)
        {
            if (action == m_retrievalAction)
            {
                emit messageDownloadCompleted();
            }
        }
        else if (activity == QMailServiceAction::Failed)
        {
            //  Todo:  hmm.. may be I should emit an error here.
            emit messageDownloadCompleted();
        }
    }
}