text:
<?xml version="1.0" encoding="UTF-8"?>
<chapter version="5.0"
         xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd"
         xml:base="../" xml:id="moveAndNeighborhoodSelection" xmlns="http://docbook.org/ns/docbook"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:ns="http://docbook.org/ns/docbook">
  <title><literal>Move</literal> and neighborhood selection</title>

    <title><literal>Move</literal> and neighborhood introduction</title>

      <title>What is a <literal>Move</literal>?</title>

      <para>A <literal>Move</literal> is a change (or set of changes) from a solution A to a solution B. For example,
      the move below changes queen <literal>C</literal> from row <literal>0</literal> to row
      <literal>2</literal>:</para>

      <mediaobject>
        <imageobject>
          <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/singleMoveNQueens04.png"/>
        </imageobject>
      </mediaobject>

      <para>The new solution is called a <emphasis>neighbor</emphasis> of the original solution, because it can be
      reached in a single <literal>Move</literal>. Although a single move can change multiple queens, the neighbors of a
      solution should always be a very small subset of all possible solutions. For example, on that original solution,
      these are all possible <literal>changeMove</literal>'s:</para>

      <mediaobject>
        <imageobject>
          <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/possibleMovesNQueens04.png"/>
        </imageobject>
      </mediaobject>

      <para>If we ignore the 4 <literal>changeMove</literal>'s that have not impact and are therefore not doable, we can
      see that number of moves is <literal>n * (n - 1) = 12</literal>. This is far less than the number of possible
      solutions, which is <literal>n ^ n = 256</literal>. As the problem scales out, the number of possible moves
      increases far less than the number of possible solutions.</para>

      <para>Yet, in 4 <literal>changeMove</literal>'s or less we can reach any solution. For example we can reach a very
      different solution in 3 <literal>changeMove</literal>'s:</para>

      <mediaobject>
        <imageobject>
          <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/sequentialMovesNQueens04.png"/>
        </imageobject>
      </mediaobject>

      <note>
        <para>There are many other types of moves besides <literal>changeMove</literal>'s. Many move types are included
        out-of-the-box, but you can also implement custom moves.</para>

        <para>A <literal>Move</literal> can affect multiple entities or even create/delete entities. But it must not
        change the problem facts.</para>
      </note>

      <para>All optimization algorithms use <literal>Move</literal>'s to transition from one solution to a neighbor
      solution. Therefor, all the optimization algorithms are confronted with <literal>Move</literal> selection: the
      craft of creating and iterating moves efficiently and the art of finding the most promising subset of random moves
      to evaluate first.</para>

      <title>What is a <literal>MoveSelector</literal>?</title>

      <para>A <literal>MoveSelector</literal>'s main function is to create <literal>Iterator<Move></literal> when
      needed. An optimization algorithm will iterate through a subset of those moves.</para>

      <para>Here's an example how to configure a <literal>changeMoveSelector</literal> for the optimization algorithm
      Local Search:</para>

      <programlisting language="xml">  <localSearch>
    <changeMoveSelector/>
    ...
  </localSearch></programlisting>

      <para>Out of the box, this works and all properties of the <literal>changeMoveSelector</literal> are defaulted
      sensibly (unless that fails fast due to ambiguity). On the other hand, the configuration can be customized
      significantly for specific use cases. For example: you want want to configure a filter to discard pointless
      moves.</para>

      <title>Subselecting of entities, values and other moves</title>

      <para>To create a <literal>Move</literal>, we need to select 1 or more planning entities and/or planning values to
      move. Just like <literal>MoveSelector</literal>s, <literal>EntitySelector</literal>s and
      <literal>ValueSelector</literal>s need to support a similar feature set (such as scalable just-in-time selection).
      Therefor, they implement a common interface <literal>Selector</literal> and they are configured similarly.</para>

      <para>A MoveSelector is often composed out of <literal>EntitySelector</literal>s,
      <literal>ValueSelector</literal>s or even other <literal>MoveSelector</literal>s, which can be configured
      individually if desired:</para>

      <programlisting language="xml">    <unionMoveSelector>
      <changeMoveSelector>
        <entitySelector>
          ...
        </entitySelector>
        <valueSelector>
          ...
        </valueSelector>
        ...
      </changeMoveSelector>
      ...
    </unionMoveSelector></programlisting>

      <para>Together, this structure forms a <literal>Selector</literal> tree:</para>

      <mediaobject>
        <imageobject>
          <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/selectorTree.png"/>
        </imageobject>
      </mediaobject>

      <para>The root of this tree is a <literal>MoveSelector</literal> which is injected into the optimization algorithm
      implementation to be (partially) iterated in every step.</para>

    <title>General <literal>Selector</literal> features</title>

      <title><literal>CacheType</literal>: Create moves in advance or Just In Time</title>

      <para>A <literal>Selector</literal>'s <literal>cacheType</literal> determines when a selection (such as a
      <literal>Move</literal>, an entity, a value, ...) is created and how long it lives.</para>

      <para>Almost every <literal>Selector</literal> supports setting a <literal>cacheType</literal>:</para>

      <programlisting language="xml">    <changeMoveSelector>
      <cacheType>PHASE</cacheType>
      ...
    </changeMoveSelector></programlisting>

      <para>The following <literal>cacheType</literal>s are supported:</para>

      <itemizedlist>
        <listitem>
          <para><literal>JUST_IN_TIME</literal> (default): Not cached. Construct each selection
          (<literal>Move</literal>, ...) just before it's used. This scales up well in memory footprint.</para>
        </listitem>

        <listitem>
          <para><literal>STEP</literal>: Cached. Create each selection (<literal>Move</literal>, ...) at the beginning
          of a step and cache them in a list for the remainder of the step. This scales up badly in memory
          footprint.</para>
        </listitem>

        <listitem>
          <para><literal>PHASE</literal>: Cached. Create each selection (<literal>Move</literal>, ...) at the beginning
          of a <literal>SolverPhase</literal> and cache them in a list for the remainder of the
          <literal>SolverPhase</literal>. Some selections cannot be phase cached because the list changes every step.
          This scales up badly in memory footprint, but has a slight performance gain.</para>
        </listitem>

        <listitem>
          <para><literal>SOLVER</literal>: Cached. Create each selection (<literal>Move</literal>, ...) at the beginning
          of a <literal>Solver</literal> and cache them in a list for the remainder of the <literal>Solver</literal>.
          Some selections cannot be solver cached because the list changes every step. This scales up badly in memory
          footprint, but has a slight performance gain.</para>
        </listitem>
      </itemizedlist>

      <para>A <literal>cacheType</literal> can be set on composite selectors too:</para>

      <programlisting language="xml">    <unionMoveSelector>
      <cacheType>PHASE</cacheType>
      <changeMoveSelector/>
      <swapMoveSelector/>
      ...
    </unionMoveSelector></programlisting>

      <para>Nested selectors of a cached selector cannot be configured to be cached themselves, unless it's a higher
      <literal>cacheType</literal>. For example: a <literal>STEP</literal> cached <literal>unionMoveSelector</literal>
      can hold a <literal>PHASE</literal> cached <literal>changeMoveSelector</literal>, but not a
      <literal>STEP</literal> cached <literal>changeMoveSelector</literal>.</para>

      <title>SelectionOrder: original, random or shuffled selection</title>

      <para>A <literal>Selector</literal>'s <literal>selectionOrder</literal> determines the order in which the
      selections (such as <literal>Move</literal>s, entities, values, ...) are iterated. An optimization algorithm will
      usually only iterate through a subset of its <literal>MoveSelector</literal>'s selections, starting from the
      start, so the <literal>selectionOrder</literal> is critical to decide which <literal>Move</literal>s are
      evaluated.</para>

      <para>Almost every <literal>Selector</literal> supports setting a <literal>selectionOrder</literal>:</para>

      <programlisting language="xml">    <changeMoveSelector>
      ...
      <selectionOrder>ORIGINAL</selectionOrder>
      ...
    </changeMoveSelector></programlisting>

      <para>The following <literal>selectionOrder</literal>s are supported:</para>

      <itemizedlist>
        <listitem>
          <para><literal>ORIGINAL</literal>: Select the selections (<literal>Move</literal>s, ...) in default order.
          Each selection will be selected only once.</para>

          <itemizedlist>
            <listitem>
              <para>For example: A0, A1, A2, A3, ..., B0, B1, B2, B3, ...</para>
            </listitem>
          </itemizedlist>
        </listitem>

        <listitem>
          <para>RANDOM (default): Select the selections (<literal>Move</literal>s, ...) in non-shuffled random order. A
          selection might be selected multiple times. This scales up well in performance.</para>

          <itemizedlist>
            <listitem>
              <para>For example: C2, A3, C2, B1, A0, C0, ...</para>
            </listitem>
          </itemizedlist>
        </listitem>

        <listitem>
          <para>SHUFFLED: Select the selections (<literal>Move</literal>s, ...) in shuffled random order. Each selection
          will be selected only once. Requires <literal>cacheType >= STEP</literal>. This scales up badly in
          performance because a random number is generated for each element, even if it's not selected (which is the
          grand majority when scaling up).</para>

          <itemizedlist>
            <listitem>
              <para>For example: C2, A3, B1, A0, C0, ...</para>
            </listitem>
          </itemizedlist>
        </listitem>
      </itemizedlist>

      <para>A <literal>selectionOrder</literal> can be set on composite selectors too.</para>

      <note>
        <para>When a <literal>Selector</literal> is cached, all of its nested <literal>Selector</literal>s will
        naturally default to <literal>selectionOrder</literal> <literal>ORIGINAL</literal>. Avoid overwriting the
        <literal>selectionOrder</literal> of those nested <literal>Selector</literal>s.</para>
      </note>

      <title>Recommended combinations of <literal>CacheType</literal> and <literal>SelectionOrder</literal></title>

        <title>Just in time random selection (default)</title>

        <para>This combination is great for big use cases (10 000 entities or more), as it scales up well in memory
        footprint and performance. Other combinations are often not even viable on such sizes. It works for smaller use
        cases too, so it's a good way to start out. It's the default, so this explicit configuration of
        <literal>cacheType</literal> and <literal>selectionOrder</literal> is actually obsolete:</para>

        <programlisting language="xml">    <unionMoveSelector>
      <cacheType>JUST_IN_TIME</cacheType>
      <selectionOrder>RANDOM</selectionOrder>

      <changeMoveSelector/>
      <swapMoveSelector/>
    </unionMoveSelector></programlisting>

        <para>Here's how it works. When <literal>Iterator<Move>.next()</literal> is called, a child
        <literal>MoveSelector</literal> is randomly selected (1), which creates a random <literal>Move</literal> is
        created (2, 3, 4) and is then returned (5):</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/jitRandomSelection.png"/>
          </imageobject>
        </mediaobject>

        <para>Notice that <emphasis role="bold">it never creates a list of <literal>Move</literal>s</emphasis> and it
        generates random numbers only for <literal>Move</literal>s that are actually selected.</para>

        <title>Cached shuffled selection</title>

        <para>This combination often wins for small and medium use cases (5000 entities or less). Beyond that size, it
        scales up badly in memory footprint and performance.</para>

        <programlisting language="xml">    <unionMoveSelector>
      <cacheType>PHASE</cacheType>
      <selectionOrder>SHUFFLED</selectionOrder>

      <changeMoveSelector/>
      <swapMoveSelector/>
    </unionMoveSelector></programlisting>

        <para>Here's how it works. At the start of the phase (or step depending on the <literal>cacheType</literal>),
        all moves are created (1) and cached (2). When <literal>MoveSelector.iterator()</literal> is called, the moves
        are shuffled (3). When <literal>Iterator<Move>.next()</literal> is called, the next element in the
        shuffled list is returned (4):</para>

        <mediaobject>
          <imageobject>
            <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/cachedShuffledSelection.png"/>
          </imageobject>
        </mediaobject>

        <para>Notice that <emphasis role="bold">each <literal>Move</literal> will only be selected once</emphasis>, even
        though they are selected in random order.</para>

        <para>Use cacheType PHASE if none of the (possibly nested) Selectors require <literal>STEP</literal>. Otherwise,
        do something like this:</para>

        <programlisting language="xml">    <unionMoveSelector>
      <cacheType>STEP</cacheType>
      <selectionOrder>SHUFFLED</selectionOrder>

      <changeMoveSelector>
        <cacheType>PHASE</cacheType>
      </changeMoveSelector>
      <swapMoveSelector/>
        <cacheType>PHASE</cacheType>
      </swapMoveSelector>
      <pillarSwapMoveSelector/><!-- Does not support cacheType PHASE -->
    </unionMoveSelector></programlisting>

        <title>Cached random selection</title>

        <para>This combination is often a worthy competitor for medium use cases, especially with fast stepping
        optimization algorithms (such as simulated annealing). Unlike cached shuffled selection, it doesn't waste time
        shuffling the move list at the beginning of every step.</para>

        <programlisting language="xml">    <unionMoveSelector>
      <cacheType>PHASE</cacheType>
      <selectionOrder>RANDOM</selectionOrder>

      <changeMoveSelector/>
      <swapMoveSelector/>
    </unionMoveSelector></programlisting>

      <title>Filtered selection</title>

      <para>There are certain moves that you don't want to select, because:</para>

      <itemizedlist>
        <listitem>
          <para>The move is pointless and would only waste CPU time. For example, swapping 2 lectures of the same course
          will result in the same score and the same schedule because all lectures of 1 course are interchangeable (same
          teacher, same students, same topic).</para>
        </listitem>

        <listitem>
          <para>Doing the move would break <link linkend="buildInHardConstraint">a build-in hard constraint</link>, so
          the solution would be infeasible but the score function doesn't check build-in hard constraints (for
          performance gain). For example, don't change a gym lecture to a room which is not a gym room.</para>

          <itemizedlist>
            <listitem>
              <para>Note that any build-in hard constraint must usually be filtered on every move type. For example,
              don't swap the room of a gym lecture with another lecture if the other lecture's original room isn't a gym
              room.</para>
            </listitem>
          </itemizedlist>
        </listitem>
      </itemizedlist>

      <para>Filtered selection can happen on any Selector in the selector tree, including any
      <literal>MoveSelector</literal>, <literal>EntitySelector</literal> or <literal>ValueSelector</literal>:</para>

      <mediaobject>
        <imageobject>
          <imagedata fileref="images/Chapter-Move_and_neighborhood_selection/filteredSelection.png"/>
        </imageobject>
      </mediaobject>

      <para>Filtering us the interface <literal>SelectionFilter</literal>:</para>

      <programlisting language="java">public interface SelectionFilter<T> {

    boolean accept(ScoreDirector scoreDirector, T selection);

}</programlisting>

      <para>Implement the method <literal>accept</literal> to return <literal>false</literal> on a discarded
      <literal>selection</literal>. Unaccepted moves will not be selected and will therefore never have their method
      <literal>doMove</literal> called.</para>

      <programlisting language="java">public class DifferentCourseSwapMoveFilter implements SelectionFilter<SwapMove> {

    public boolean accept(ScoreDirector scoreDirector, SwapMove move) {
        Lecture leftLecture = (Lecture) move.getLeftEntity();
        Lecture rightLecture = (Lecture) move.getRightEntity();
        return !leftLecture.getCourse().equals(rightLecture.getCourse());
    }

}</programlisting>

      <para>Apply the filter on the lowest level possible. In most cases, you 'll need to know both the entity and the
      value involved and you'll have to apply a <literal>moveFilterClass</literal> on the
      <literal>moveSelector</literal>:</para>

      <programlisting language="xml">    <swapMoveSelector>
      <moveFilterClass>org.drools.planner.examples.curriculumcourse.solver.move.DifferentCourseSwapMoveFilter</moveFilterClass>
    </swapMoveSelector></programlisting>

      <para>But if possible apply it on a lower levels, such as an <literal>entityFilterClass</literal> on the
      <literal>entitySelector</literal> or a <literal>valueFilterClass</literal> on the
      <literal>valueSelector</literal>:</para>

      <programlisting language="xml">    <changeMoveSelector>
      <entitySelector>
        <entityFilterClass>...EntityFilter</entityFilterClass>
      </entitySelector>
    </changeMoveSelector></programlisting>

      <para>Filtered selection works with any kind of <literal>cacheType</literal> and
      <literal>selectionOrder</literal>. You can configure multiple <literal>*FilterClass</literal> elements on a single
      selector.</para>

      <title>Sorted selection</title>

      <para>TODO Not yet implemented.</para>

      <title>Probability selection</title>

      <para>TODO</para>

    <title>Generic MoveSelectors</title>

      <title><literal>changeMoveSelector</literal></title>

      <para>For 1 planning variable, the <literal>ChangeMove</literal> selects 1 planning entity and 1 planning value
      and assigns the entity's variable to that value.</para>

      <para>Simplest configuration:</para>

      <programlisting language="xml">    <changeMoveSelector/></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <changeMoveSelector>
      ... <!-- Normal moveSelector properties -->
      <entitySelector>
        ...
      </entitySelector>
      <valueSelector>
        ...
      </valueSelector>
    </changeMoveSelector></programlisting>

      <para>A <literal>ChangeMove</literal> is the finest grained move.</para>

      <important>
        <para>Almost every <literal>moveSelector</literal> configuration injected into a metaheuristic algorithm should
        include a changeMoveSelector or a custom implementation. This guarantees that every possible
        <literal>Solution</literal> can be reached through applying a number of moves in sequence (not taking <link
        linkend="scoreTrap">score traps</link> into account). Of course, normally it is unioned with other, more course
        grained moves.</para>
      </important>

      <title>swapMoveSelector</title>

      <para>The <literal>SwapMove</literal> selects 2 different planning entities and swaps the planning values of all
      their planning variables.</para>

      <para>Simplest configuration:</para>

      <programlisting language="xml">    <swapMoveSelector/></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <swapMoveSelector>
      ... <!-- Normal moveSelector properties -->
      <entitySelector>
        ...
      </entitySelector>
      <secondaryEntitySelector>
        ...
      </secondaryEntitySelector>
    </swapMoveSelector></programlisting>

      <para>The <literal>secondaryEntitySelector</literal> is rarely needed: if it is not specified, entities from the
      same <literal>entitySelector</literal> are swapped.</para>

      <para>Although a <literal>SwapMove</literal> on a single variable is essentially just 2
      <literal>ChangeMove</literal>s, it's often the winning step where the first of the 2
      <literal>ChangeMove</literal>s would not be the winning step because it leave the solution in a state with broken
      hard constraints. For example: swapping the room of 2 lectures doesn't bring the solution in a intermediate state
      where both lectures are in the same room which breaks a hard constraint.</para>

      <title>pillarSwapMoveSelector</title>

      <para>A <emphasis>pillar</emphasis> is a set of planning entities which have the same planning value(s) for each
      of their planning variables. The <literal>pillarSwapMove</literal> selects 2 different entity pillars and swaps
      the values of all their variables for all their entities.</para>

      <para>Simplest configuration:</para>

      <programlisting language="xml">    <pillarSwapMoveSelector/></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <pillarSwapMoveSelector>
      ... <!-- Normal moveSelector properties -->
      <pillarSelector>
        <entitySelector>
          ...
        </entitySelector>
      </pillarSelector>
      <secondaryPillarSelector>
        <entitySelector>
          ...
        </entitySelector>
      </secondaryPillarSelector>
    </pillarSwapMoveSelector></programlisting>

      <para>The <literal>secondaryPillarSelector</literal> is rarely needed: if it is not specified, entities from the
      same <literal>pillarSelector</literal> are swapped.</para>

      <title>subChainChangeMoveSelector</title>

      <para>TODO</para>

      <title>subChainSwapMoveSelector</title>

      <para>TODO</para>

    <title>Combining multiple <literal>MoveSelector</literal>s</title>

      <title>unionMoveSelector</title>

      <para>A <literal>unionMoveSelector</literal> selects a <literal>Move</literal> by selecting 1 of its child
      <literal>MoveSelector</literal>s to supply the next <literal>Move</literal>.</para>

      <para>Simplest configuration:</para>

      <programlisting language="xml">    <unionMoveSelector>
      <...MoveSelector/>
      <...MoveSelector/>
      <...MoveSelector/>
      ...
    </unionMoveSelector></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <unionMoveSelector>
      ... <!-- Normal moveSelector properties -->
      <selectorProbabilityWeightFactoryClass>...ProbabilityWeightFactory</selectorProbabilityWeightFactoryClass>
      <changeMoveSelector>
        <fixedProbabilityWeight>...</fixedProbabilityWeight>
        ...
      </changeMoveSelector>
      <swapMoveSelector>
        <fixedProbabilityWeight>...</fixedProbabilityWeight>
        ...
      </swapMoveSelector>
      <...MoveSelector>
        <fixedProbabilityWeight>...</fixedProbabilityWeight>
        ...
      </...MoveSelector>
      ...
    </unionMoveSelector></programlisting>

      <para>In <literal>selectionOrder</literal> <literal>RANDOM</literal>, the
      <literal>selectorProbabilityWeightFactory</literal> determines how often a child MoveSelector is selected to
      supply the next Move. By default, each child <literal>MoveSelector</literal> has the same chance of being
      selected. Change the fixedProbabilityWeight of such a child to select it more often. For example, the
      <literal>unionMoveSelector</literal> can return a <literal>SwapMove</literal> twice as often as a
      <literal>ChangeMove</literal>:</para>

      <programlisting language="xml">    <unionMoveSelector>
      <changeMoveSelector>
        <fixedProbabilityWeight>1.0</fixedProbabilityWeight>
        ...
      </changeMoveSelector>
      <swapMoveSelector>
        <fixedProbabilityWeight>2.0</fixedProbabilityWeight>
        ...
      </swapMoveSelector>
    </unionMoveSelector></programlisting>

      <para>The number of possible <literal>ChangeMove</literal>s is very different from the number of possible
      <literal>SwapMove</literal>s and it's problem dependent. To give each individual <literal>Move</literal> the same
      selection chance (as opposed to each <literal>MoveSelector</literal>), use the
      <literal>FairSelectorProbabilityWeightFactory</literal>:</para>

      <programlisting language="xml">    <unionMoveSelector>
      <selectorProbabilityWeightFactoryClass>org.drools.planner.core.heuristic.selector.common.decorator.FairSelectorProbabilityWeightFactory</selectorProbabilityWeightFactoryClass>
      <changeMoveSelector/>
      <swapMoveSelector/>
    </unionMoveSelector></programlisting>

      <title>cartesianProductMoveSelector</title>

      <para>A <literal>cartesianProductMoveSelector</literal> selects a new <literal>CompositeMove</literal>. It builds
      that <literal>CompositeMove</literal> by selecting 1 <literal>Move</literal> per child
      <literal>MoveSelector</literal> and adding it to the <literal>CompositiveMove</literal>.</para>

      <para>Simplest configuration:</para>

      <programlisting language="xml">    <cartesianProductMoveSelector>
      <...MoveSelector/>
      <...MoveSelector/>
      <...MoveSelector/>
      ...
    </cartesianProductMoveSelector></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <cartesianProductMoveSelector>
      ... <!-- Normal moveSelector properties -->
      <changeMoveSelector>
        ...
      </changeMoveSelector>
      <swapMoveSelector>
        ...
      </swapMoveSelector>
      <...MoveSelector>
        ...
      </...MoveSelector>
      ...
    </cartesianProductMoveSelector></programlisting>

    <title>EntitySelector</title>

      <title>TODO</title>

      <para>TODO</para>

    <title>ValueSelector</title>

      <title>TODO</title>

      <para>TODO</para>

    <title>Custom moves</title>

      <title>Which move types might be missing in my implementation?</title>

      <para>To determine which move types might be missing in your implementation, run a benchmarker <emphasis>for a
      short amount of time</emphasis> and <link linkend="writingTheOutputSolutionOfTheBenchmarkRuns">configure it to
      write the best solutions to disk</link>. Take a look at such a best solution: it will likely be a local optima.
      Try to figure out if there's a move that could get out of that local optima faster.</para>

      <para>If you find one, implement that course-grained move, mix it with the existing moves and benchmark it against
      the previous configurations to see if you want to keep it.</para>

      <title>Custom moves introduction</title>

      <para>Instead of reusing the generic <literal>Move</literal>s (such as <literal>ChangeMove</literal>) you can also
      implement your own <literal>Move</literal>s. Generic and custom <literal>MoveSelector</literal>s can be combined
      as wanted.</para>

      <para>A custom <literal>Move</literal> can be tailored to work to the advantage of your constraints. For example,
      in examination scheduling, changing the period of an exam A also changes te period of all the exams that need to
      coincide with exam A.</para>

      <para>A custom <literal>Move</literal> is also slightly faster than a generic <literal>Move</literal>. However,
      it's far more work to implement and much harder to avoid bugs. After implementing a custom
      <literal>Move</literal>, make sure to turn on <literal>environmentMode</literal> <literal>TRACE</literal> to check
      for score corruptions.</para>

      <title>The interface <literal>Move</literal></title>

      <para>Your custom moves must implement the <literal>Move</literal> interface:</para>

      <programlisting language="java">public interface Move {

    boolean isMoveDoable(ScoreDirector scoreDirector);

    Move createUndoMove(ScoreDirector scoreDirector);
    void doMove(ScoreDirector scoreDirector);

    Collection<? extends Object> getPlanningEntities();
    Collection<? extends Object> getPlanningValues();

}</programlisting>

      <para>Let's take a look at the <literal>Move</literal> implementation for 4 queens which moves a queen to a
      different row:</para>

      <programlisting language="java">public class RowChangeMove implements Move {

    private Queen queen;
    private Row toRow;

    public RowChangeMove(Queen queen, Row toRow) {
        this.queen = queen;
        this.toRow = toRow;
    }

    // ... see below

}</programlisting>

      <para>An instance of <literal>RowChangeMove</literal> moves a queen from its current row to a different
      row.</para>

      <para>Planner calls the <literal>doMove(ScoreDirector)</literal> method to do a move. The <literal>Move</literal>
      implementation must notify the <literal>ScoreDirector</literal> of any changes it make to the planning entities's
      variables:</para>

      <programlisting language="java">    public void doMove(ScoreDirector scoreDirector) {
        scoreDirector.beforeVariableChanged(queen, "row"); // before changes are made to the queen.row
        queen.setRow(toRow);
        scoreDirector.afterVariableChanged(queen, "row"); // after changes are made to the queen.row
    }</programlisting>

      <para>You need to call the methods <literal>scoreDirector.beforeVariableChanged(Object, String)</literal> and
      <literal>scoreDirector.afterVariableChanged(Object, String)</literal> directly before and after modifying the
      entity. Alternatively, you can also call the methods
      <literal>scoreDirector.beforeAllVariablesChanged(Object)</literal> and
      <literal>scoreDirector.afterAllVariablesChanged(Object)</literal>.</para>

      <note>
        <para>You can alter multiple entities in a single move and effectively create a big move (also known as a
        coarse-grained move).</para>
      </note>

      <warning>
        <para>A <literal>Move</literal> can only change/add/remove planning entities, it must not change any of the
        problem facts.</para>
      </warning>

      <para>Planner automatically filters out <emphasis>non doable moves</emphasis> by calling the
      <literal>isDoable(ScoreDirector)</literal> method on a move. A <emphasis>non doable move</emphasis> is:</para>

      <itemizedlist>
        <listitem>
          <para>A move that changes nothing on the current solution. For example, moving queen B0 to row 0 is not
          doable, because it is already there.</para>
        </listitem>

        <listitem>
          <para>A move that is impossible to do on the current solution. For example, moving queen B0 to row 10 is not
          doable because it would move it outside the board limits.</para>
        </listitem>
      </itemizedlist>

      <para>In the n queens example, a move which moves the queen from its current row to the same row isn't
      doable:</para>

      <programlisting language="java">    public boolean isMoveDoable(ScoreDirector scoreDirector) {
        return !ObjectUtils.equals(queen.getRow(), toRow);
    }</programlisting>

      <para>Because we won't generate a move which can move a queen outside the board limits, we don't need to check it.
      A move that is currently not doable could become doable on the working <literal>Solution</literal> of a later
      step.</para>

      <para>Each move has an <emphasis>undo move</emphasis>: a move (normally of the same type) which does the exact
      opposite. In the example above the undo move of <emphasis>C0 to C2</emphasis> would be the move <emphasis>C2 to
      C0</emphasis>. An undo move is created from a <literal>Move</literal>, before the <literal>Move</literal> has been
      done on the current solution.</para>

      <programlisting language="java">    public Move createUndoMove(ScoreDirector scoreDirector) {
        return new RowChangeMove(queen, queen.getRow());
    }</programlisting>

      <para>Notice that if C0 would have already been moved to C2, the undo move would create the move <emphasis>C2 to
      C2</emphasis>, instead of the move <emphasis>C2 to C0</emphasis>.</para>

      <para>A solver phase might do and undo the same <literal>Move</literal> more than once. In fact, many solver
      phases will iteratively do an undo a number of moves to evaluate them, before selecting one of those and doing
      that move again (without undoing it this time).</para>

      <para>A <literal>Move</literal> must implement the <literal>getPlanningEntities()</literal> and
      <literal>getPlanningValues()</literal> methods. They are used by entity tabu and value tabu respectively. When
      they are called, the <literal>Move</literal> has already been done.</para>

      <programlisting language="java">    public List<? extends Object> getPlanningEntities() {
        return Collections.singletonList(queen);
    }

    public Collection<? extends Object> getPlanningValues() {
        return Collections.singletonList(toRow);
    }</programlisting>

      <para>If your <literal>Move</literal> changes multiple planning entities, return all of them in
      <literal>getPlanningEntities()</literal> and return all their values (to which they are changing) in
      <literal>getPlanningValues()</literal>.</para>

      <programlisting language="java">    public Collection<? extends Object> getPlanningEntities() {
        return Arrays.asList(leftCloudProcess, rightCloudProcess);
    }

    public Collection<? extends Object> getPlanningValues() {
        return Arrays.asList(leftCloudProcess.getComputer(), rightCloudProcess.getComputer());
    }</programlisting>

      <para>A <literal>Move</literal> must implement the <literal>equals()</literal> and <literal>hashCode()</literal>
      methods. 2 moves which make the same change on a solution, should be equal.</para>

      <programlisting language="java">    public boolean equals(Object o) {
        if (this == o) {
            return true;
        } else if (o instanceof RowChangeMove) {
            RowChangeMove other = (RowChangeMove) o;
            return new EqualsBuilder()
                    .append(queen, other.queen)
                    .append(toRow, other.toRow)
                    .isEquals();
        } else {
            return false;
        }
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(queen)
                .append(toRow)
                .toHashCode();
    }</programlisting>

      <para>Notice that it checks if the other move is an instance of the same move type. This
      <literal>instanceof</literal> check is important because a move will be compared to a move with another move type
      if you're using more then 1 move type.</para>

      <para>It's also recommended to implement the <literal>toString()</literal> method as it allows you to read
      Planner's logging more easily:</para>

      <programlisting language="java">    public String toString() {
        return queen + " => " + toRow;
    }</programlisting>

      <para>Now that we can implement a single custom <literal>Move</literal>, let's take a look at generating such
      custom moves.</para>

      <title><literal>MoveListFactory</literal>: the easy way to generate custom moves</title>

      <para>The easiest way to generate custom moves is by implementing the interface
      <literal>MoveListFactory</literal>:</para>

      <programlisting language="java">public interface MoveListFactory {

    List<Move> createMoveList(Solution solution);

}</programlisting>

      <para>For example:</para>

      <programlisting language="java">public class RowChangeMoveFactory implements MoveListFactory {

    public List<Move> createMoveList(Solution solution) {
        NQueens nQueens = (NQueens) solution;
        List<Move> moveList = new ArrayList<Move>();
        for (Queen queen : nQueens.getQueenList()) {
            for (Row toRow : nQueens.getRowList()) {
                moveList.add(new RowChangeMove(queen, toRow));
            }
        }
        return moveList;
    }

}</programlisting>

      <para>Simple configuration (which can be nested in a <literal>unionMoveSelector</literal> just like any other
      <literal>MoveSelector</literal>):</para>

      <programlisting language="xml">    <moveListFactory>
      <moveListFactoryClass>org.drools.planner.examples.nqueens.solver.move.factory.RowChangeMoveFactory</moveListFactoryClass>
    </moveListFactory></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <moveListFactory>
      ... <!-- Normal moveSelector properties -->
      <moveListFactoryClass>org.drools.planner.examples.nqueens.solver.move.factory.RowChangeMoveFactory</moveListFactoryClass>
    </moveListFactory></programlisting>

      <para>Because the <literal>MoveListFactory</literal> generates all moves at once in a List<Move>, it does
      not support <literal>cacheType</literal> <literal>JUST_IN_TIME</literal>. Therefore,
      <literal>moveListFactory</literal> uses <literal>cacheType</literal> <literal>STEP</literal> by default and it
      scales badly in memory footprint.</para>

      <title><literal>MoveIteratorFactory</literal>: generate custom moves just in time</title>

      <para>Use this advanced form to generate custom moves by implementing the interface
      <literal>MoveIteratorFactory</literal>:</para>

      <programlisting language="java">public interface MoveIteratorFactory {

    long getSize(ScoreDirector scoreDirector);

    Iterator<Move> createOriginalMoveIterator(ScoreDirector scoreDirector);

    Iterator<Move> createRandomMoveIterator(ScoreDirector scoreDirector, Random workingRandom);

}</programlisting>

      <para>The method <literal>getSize()</literal> must give an estimation of the size. It doesn't need to be correct.
      The method <literal>createOriginalMoveIterator</literal> is called if the <literal>selectionOrder is</literal>
      <literal>ORIGINAL</literal> or if it is cached. The method <literal>createRandomMoveIterator</literal> is called
      for <literal>selectionOrder</literal> <literal>RANDOM</literal> combined with cacheType
      <literal>JUST_IN_TIME</literal>.</para>

      <important>
        <para>Don't create a collection (list, array, map, set) of <literal>Move</literal>s when creating the
        <literal>Iterator<Move></literal>: the whole purpose of <literal>MoveIteratorFactory</literal> over
        <literal>MoveListFactory</literal> is giving you the ability to create a <literal>Move</literal> just in time in
        the <literal>Iterator</literal>'s method <literal>next()</literal>.</para>
      </important>

      <para>Simple configuration (which can be nested in a <literal>unionMoveSelector</literal> just like any other
      <literal>MoveSelector</literal>):</para>

      <programlisting language="xml">    <moveIteratorFactory>
      <moveIteratorFactoryClass>...</moveIteratorFactoryClass>
    </moveIteratorFactory></programlisting>

      <para>Advanced configuration:</para>

      <programlisting language="xml">    <moveIteratorFactory>
      ... <!-- Normal moveSelector properties -->
      <moveIteratorFactoryClass>...</moveIteratorFactoryClass>
    </moveIteratorFactory></programlisting>

      <title>Move generation through DRL</title>

      <para>Not yet supported.</para>

</chapter>


text:
[clappr](../../../index.md) / [io.clappr.player.playback](../../index.md) / [NoOpPlayback](../index.md) / [Companion](index.md) / [supportsSource](./supports-source.md)

# supportsSource

`fun supportsSource(source: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`, mimeType: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`?): `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)

Overrides [PlaybackSupportInterface.supportsSource](../../../io.clappr.player.components/-playback-support-interface/supports-source.md)

redpajama_set_name: RedPajamaGithub


text:
namespace media {

class DummyDemuxerStream : public DemuxerStream {
 public:
  explicit DummyDemuxerStream(Type type);

  // DemuxerStream implementation.
  virtual void Read(const ReadCallback& read_callback) OVERRIDE;
  virtual Type type() OVERRIDE;
  virtual const AudioDecoderConfig& audio_decoder_config() OVERRIDE;
  virtual const VideoDecoderConfig& video_decoder_config() OVERRIDE;
  virtual void EnableBitstreamConverter() OVERRIDE;

 private:
  virtual ~DummyDemuxerStream();

  Type type_;
  AudioDecoderConfig audio_config_;
  VideoDecoderConfig video_config_;

  DISALLOW_COPY_AND_ASSIGN(DummyDemuxerStream);
};

class DummyDemuxer : public Demuxer {
 public:
  DummyDemuxer(bool has_video, bool has_audio, bool local_source);
  virtual ~DummyDemuxer();

  // Demuxer implementation.
  virtual scoped_refptr<DemuxerStream> GetStream(
      DemuxerStream::Type type) OVERRIDE;
  virtual void set_host(DemuxerHost* demuxer_host) OVERRIDE;
  virtual void SetPreload(Preload preload) OVERRIDE;
  virtual base::TimeDelta GetStartTime() const OVERRIDE;
  virtual int GetBitrate() OVERRIDE;
  virtual bool IsLocalSource() OVERRIDE;
  virtual bool IsSeekable() OVERRIDE;

 private:
  bool has_video_;
  bool has_audio_;
  bool local_source_;
  std::vector< scoped_refptr<DummyDemuxerStream> > streams_;

  DISALLOW_COPY_AND_ASSIGN(DummyDemuxer);
};

}  // namespace media

#endif  // MEDIA_FILTERS_DUMMY_DEMUXER_H_


text:
#include "rosplan_planning_system/EsterelPlanDispatcher.h"
#include <stdlib.h>
#include <map>
#include <iostream>
#include <string>
#include <boost/regex.hpp>

namespace KCL_rosplan {

	/*-------------*/
	/* constructor */
	/*-------------*/

	EsterelPlanDispatcher::EsterelPlanDispatcher() {
		ros::NodeHandle nh("~");
		nh.param("strl_file_path", strl_file, std::string("common/plan.strl"));
	}

	/*---------------*/
	/* public access */
	/*---------------*/

	int EsterelPlanDispatcher::getCurrentAction() {
		return current_action;
	}

	void EsterelPlanDispatcher::reset() {
		replan_requested = false;
		dispatch_paused = false;
		plan_cancelled = false;
		current_action = 0;
		action_received.clear();
		action_completed.clear();
	}

	/*---------------*/
	/* parse esterel */
	/*---------------*/

	bool EsterelPlanDispatcher::readEsterelFile(std::string strlFile) {

		// open file
		std::ifstream planfile;
		std::cout << strlFile.c_str() << std::endl;
		planfile.open(strlFile.c_str());

		int curr, next;
		std::string line;

		double planDuration;
		double expectedPlanDuration = 0;
		plan_description.clear();
		plan_edges.clear();

		bool readingModule = false;
		std::string currentNode;

		if(!planfile.is_open())
			return false;

		while(!planfile.eof()) {

			getline(planfile, line);

			boost::regex e_whitespace("^[\f\r\t\v]*\%.*");
			if (boost::regex_match(line,e_whitespace)) {
				// line is a comment
				continue;
			}

			boost::smatch what;
			boost::regex e_parameters("[\\s]*([^,;]+)[,;]");
			if(readingModule) {
  				// "end module"
				boost::regex e_module_end("^end module[\\s]*");
				if (boost::regex_match(line,e_module_end))
					readingModule = false;
				// "input [i0], [i1], [i2];"
				boost::regex e_input("^([\\s]*input[\\s]+).*$");
				if (boost::regex_match(line,what,e_input)) {
					std::string params = line.substr(what[1].length());
					boost::sregex_iterator iter(params.begin(), params.end(), e_parameters);
					boost::sregex_iterator end;
					for(; iter != end; ++iter ) {
						if(plan_edges.find((*iter)[1]) == plan_edges.end()) {
							StrlEdge edge;
							edge.edge_name = (*iter)[1];
							plan_edges[(*iter)[1]] = edge;
						}
						plan_description[currentNode].input.push_back((*iter)[1]);
						plan_description[currentNode].await_input.push_back(true);
					}
				}
				// "output [i0], [i1], [i2];"
				boost::regex e_output("^([\\s]*output[\\s]+).*$");
				if (boost::regex_match(line,what,e_output)) {
					std::string params = line.substr(what[1].length());
					boost::sregex_iterator iter(params.begin(), params.end(), e_parameters);
					boost::sregex_iterator end;
					for(; iter != end; ++iter ) {
						if(plan_edges.find((*iter)[1]) == plan_edges.end()) {
							StrlEdge edge;
							edge.edge_name = (*iter)[1];
							plan_edges[(*iter)[1]] = edge;
						}
						plan_description[currentNode].output.push_back((*iter)[1]);
					}
				}
			} else {
  				// "module [module_name]:"
				boost::regex e_module("^[\\s]*module[\\s+]([^:]+):.*");
				if (boost::regex_match(line,what,e_module)) {
					StrlNode node;
					node.node_name = what[1];
					plan_description[node.node_name] = node;
					currentNode = node.node_name;
					node.dispatched = false;
					node.completed = false;
					readingModule = true;
				}
			}
		}
		planfile.close();
	}

	/*-----------------*/
	/* action dispatch */
	/*-----------------*/

	/*
	 * Loop through and publish planned actions
	 */
	bool EsterelPlanDispatcher::dispatchPlan(const std::vector<rosplan_dispatch_msgs::ActionDispatch> &actionList, double missionStart, double planStart) {

		ros::NodeHandle nh("~");
		ros::Rate loop_rate(10);

		// parse strl file
		ROS_INFO("KCL: (PS) Parsing STRL file: %s", strl_file.c_str());
		readEsterelFile(strl_file);

		// dispatch plan
		ROS_INFO("KCL: (PS) Dispatching plan");
		replan_requested = false;
		bool repeatAction = false;

		// initialise machine
		std::map<std::string,bool> edge_values;
		std::map<std::string,StrlEdge>::iterator eit = plan_edges.begin();
		for(; eit!=plan_edges.end(); eit++)
			edge_values[eit->second.edge_name] = false;

		while (ros::ok() && actionList.size() > current_action) {

			// loop while dispatch is paused
			while (ros::ok() && dispatch_paused) {
				ros::spinOnce();
				loop_rate.sleep();
			}

			// cancel plan
			if(plan_cancelled) {
				break;
			}

			// for each module
			std::map<std::string,StrlNode>::iterator it = plan_description.begin();
			for(; it!=plan_description.end(); it++) {

				if(!it->second.dispatched) {

					// activate waiting nodes
					bool activate = true;
					for(int i=0;i<it->second.await_input.size();i++) {
						if(!plan_edges[it->second.input[i]].active)
							activate = false;
					}
					if(activate) {

						// activate action
						it->second.dispatched = true;
						current_action = atoi(it->second.node_name.substr(0,6).c_str());
						rosplan_dispatch_msgs::ActionDispatch currentMessage = actionList[current_action];
						action_received[current_action] = false;
						action_completed[current_action] = false;

						// dispatch action
						ROS_INFO("KCL: (PS) Dispatching action [%i, %s, %f, %f]", currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration);
						action_publisher.publish(currentMessage);
						double late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time + planStart));
						if(late_print>0.1) ROS_INFO("KCL: (PS) Action [%i] is %f second(s) late", currentMessage.action_id, late_print);

					}

				} else if(!it->second.completed) {

					// check action completion
					int actionID = atoi(it->second.node_name.substr(0,6).c_str());
					if(action_completed[current_action]) {
						it->second.completed = true;

						// emit output edges
						for(int i=0;i<it->second.output.size();i++)
							edge_values[it->second.output[i]] = true;
					}
				}

				ros::spinOnce();
				loop_rate.sleep();
			}

			// copy new edge values
			std::map<std::string,StrlEdge>::iterator eit = plan_edges.begin();
			for(; eit!=plan_edges.end(); eit++) {
				eit->second.active = edge_values[eit->second.edge_name];
				edge_values[eit->second.edge_name] = false;
			}

			if(replan_requested) return false;
		}
		return true;
	}

	/*------------------*/
	/* general feedback */
	/*------------------*/

	/**
	 * listen to and process actionFeedback topic.
	 */
	void EsterelPlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {

		// create error if the action is unrecognised
		ROS_INFO("KCL: (PS) Feedback received [%i, %s]", msg->action_id, msg->status.c_str());
		if(current_action != (unsigned int)msg->action_id)
			ROS_ERROR("KCL: (PS) Unexpected action ID: %d; current action: %zu", msg->action_id, current_action);

		// action enabled
		if(!action_received[msg->action_id] && (0 == msg->status.compare("action enabled")))
			action_received[msg->action_id] = true;

		// more specific feedback
		actionFeedback(msg);

		// action completed (successfuly)
		if(!action_completed[msg->action_id] && 0 == msg->status.compare("action achieved"))
			action_completed[msg->action_id] = true;

		// action completed (failed)
		if(!action_completed[msg->action_id] && 0 == msg->status.compare("action failed")) {
			replan_requested = true;
			action_completed[msg->action_id] = true;
		}
	}

	/*---------------------------*/
	/* Specific action responses */
	/*---------------------------*/

	/**
	 * processes single action feedback message.
	 * This method serves as the hook for defining more interesting behaviour on action feedback.
	 */
	void EsterelPlanDispatcher::actionFeedback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) {
		// nothing yet...
	}
} // close namespace


text:
using MvcBloggy.API.Model.RequestCommands;
using MvcBloggy.Domain.Entities;
using MvcBloggy.Domain.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace MvcBloggy.API.Controllers {

    public class BlogPostCommentsController : ApiController {

        private readonly IBlogService _blogService;

        public BlogPostCommentsController(
            IBlogService blogService) {

            _blogService = blogService;
        }

        //GET /api/blogposts/a063e488-3125-4999-a317-1943cecfd591/comments?lang=en&page=2&take=10
        public HttpResponseMessage GetComments(Guid blogPostKey, [FromUri]PaginatedRequestCommand requestCmd) {

            //TODO: Implement the real logic here

            return Request.CreateResponse(HttpStatusCode.OK, new { key = blogPostKey, command = requestCmd });
        }
    }
}


text:
======
pysqlw
======

.. _MySQLdb: http://sourceforge.net/projects/mysql-python/
.. _This link: http://blog.mysqlboy.com/2010/08/installing-mysqldb-python-module.html
.. _readthedocs: https://pysqlw.readthedocs.org
.. _pysqlw wrappers: https://pysqlw.readthedocs.org/en/latest/wrappers.html
.. _github repo: https://github.com/plausibility/pysqlw
.. _with: https://pysqlw.readthedocs.org/en/latest/usage.html#with-pysqlw-as-p

A Python based wrapper (meta-wrapper, even) allowing easy MySQL and SQLite interactions.

Requirements
============

-  Python 2.7.3 (this is what I test with, should work with most 2.x; 3.x not guaranteed without porting)
-  sqlite3 module (comes with Python installs)
-  Install `MySQLdb`_ if you want MySQL support

   -  If you're using a Debian-like distro (Ubuntu, Debian, Crunchbang, etc), install the package **python-mysqldb**

      - ``$ sudo apt-get install python-mysqldb``

   -  There is no pypi package (someone get on this)
   -  If that didn't work, or you're not using a Debian-like distro:

      -  Build and install the MySQLdb module from source.
      -  `This link`_ explains better than I could.

   -  Verify it's installed: ``$ python -c 'import MySQLdb'``

      -  If nothing shows up, you're good!
      -  If you get an ImportError, think, do you **really** need MySQL?
      -  If yes, this is a problem, and I can't really help. :(
      -  If you don't, just use sqlite, it's much easier.

Usage
=====

-  Install pysqlw: ``$ pip install pysqlw``
-  Import pysqlw:

   - ``import pysqlw``

-  Create a new instance:

   -  ``p = pysqlw.pysqlw(db_type="sqlite", db_path="/home/user/example.db")``
   -  If you want to use MySQL you need to supply more details:
   -  ``p = pysqlw.pysqlw(db_type="mysql", db_host="localhost", db_user="username", db_pass="password", db_name="database_name")``
   -  Alternatively, you can use it with Python's `with`_ statement.

-  Documentation is now on the pysqlw `readthedocs`_ entry.

Contributing
============
If you're interested, you can write extra meta-wrappers for foreign database types.
They're pretty simple, look at the `pysqlw wrappers`_ documentation page for an example.

If there's not a wrapper for a database type you'd like (that is, an actual wrapper, not just a meta-wrapper), you should make one of those and send in some pull requests with meta-wrappers! More coverage is great.

If you wish to help contribute to the base wrapper functions, feel free to fork the `github repo`_ and send in pull requests!


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>spring_08</groupId>
	<artifactId>spring_08</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>spring_08</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<springframework.version>4.3.4.RELEASE</springframework.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.4.RELEASE</version>
        </dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.40</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.5</version>
				<configuration>
					<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package network

import (
	"net"
	"net/http"
)

// implements io.Closer that gracefully closes an http server
type GracefulHttpCloser struct {
	Server   *http.Server
	Listener net.Listener
}

func (c *GracefulHttpCloser) Close() error {
	c.Listener.Close()
	return c.Server.Shutdown(nil)
}


text:
class CBC_PDF417ErrorCorrection {
 public:
  CBC_PDF417ErrorCorrection() = delete;
  ~CBC_PDF417ErrorCorrection() = delete;

  static int32_t GetErrorCorrectionCodewordCount(int32_t errorCorrectionLevel);
  static Optional<WideString> GenerateErrorCorrection(
      const WideString& dataCodewords,
      int32_t errorCorrectionLevel);
};

#endif  // FXBARCODE_PDF417_BC_PDF417ERRORCORRECTION_H_


text:
/* eslint-env mocha */
const path = require('path')
const chai = require('chai')
const chimera = require('../index.js')
const assert = chai.assert

// 1. upgrade(options, '003', callback): should have 3 records
// 2. downgrade(options, '002', callback): should have 1 records
// 3. upgrade(options, callback): should have 4 records
// 4. downgrade(options, callback): should have 0 records

let migrationPath = path.join(__dirname, 'fractures/migrations')
let mongoUrl = 'mongodb://localhost/test'
let collectionName = 'chimera_migrations'
let migrationConfig = {migrationPath, mongoUrl}
let dbConfig = {mongoUrl, collectionName}
describe('migration', function () {
  it('should be able to upgrade to certain version', function (done) {
    chimera.mongo.execute(dbConfig, 'remove', {}, function (error) {
      if (error) {
        return done(error)
      }
      return chimera.migration.upgrade(migrationConfig, '003', function (error) {
        if (error) {
          return done(error)
        }
        return chimera.mongo.execute(dbConfig, 'count', {}, function (error, result) {
          if (error) {
            return done(error)
          }
          assert.equal(result, 3)
          return done()
        })
      })
    })
  })

  it('should be able to downgrade to certain version', function (done) {
    chimera.migration.downgrade(migrationConfig, '002', function (error) {
      if (error) {
        return done(error)
      }
      return chimera.mongo.execute(dbConfig, 'count', {}, function (error, result) {
        if (error) {
          return done(error)
        }
        assert.equal(result, 1)
        return done()
      })
    })
  })

  it('should be able to upgrade to latest version', function (done) {
    chimera.migration.upgrade(migrationConfig, function (error) {
      if (error) {
        return done(error)
      }
      return chimera.mongo.execute(dbConfig, 'count', {}, function (error, result) {
        if (error) {
          return done(error)
        }
        assert.equal(result, 4)
        return done()
      })
    })
  })

  it('should be able to downgrade to first version', function (done) {
    chimera.migration.downgrade(migrationConfig, function (error) {
      if (error) {
        return done(error)
      }
      return chimera.mongo.execute(dbConfig, 'count', {}, function (error, result) {
        if (error) {
          return done(error)
        }
        assert.equal(result, 0)
        return chimera.mongo.execute(dbConfig, 'remove', {}, function (error) {
          if (error) {
            return done(error)
          }
          return done()
        })
      })
    })
  })
})


text:
FindLerc
--------

Find the native Lerc includes and library.

IMPORTED Targets
^^^^^^^^^^^^^^^^

This module defines :prop_tgt:`IMPORTED` target ``LERC::LERC``, if
CMath has been found.

Result Variables
^^^^^^^^^^^^^^^^

This module defines the following variables:

::

  LERC_INCLUDE_DIRS   - where to find Lerc_c_api.h, etc.
  LERC_LIBRARIES      - List of libraries when using LERC.
  LERC_FOUND          - True if LERC found.

#]=======================================================================]

# Standard names to search for
set(LERC_NAMES LercLib Lerc)

find_path(LERC_INCLUDE_DIR
          NAMES Lerc_c_api.h
          PATH_SUFFIXES include)

# Allow LERC_LIBRARY to be set manually, as the location of the deflate library
if(NOT LERC_LIBRARY)
  find_library(LERC_LIBRARY_RELEASE
               NAMES ${LERC_NAMES}
               PATH_SUFFIXES lib)

  include(SelectLibraryConfigurations)
  select_library_configurations(LERC)
endif()

unset(LERC_NAMES)

mark_as_advanced(LERC_INCLUDE_DIR)

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LERC
        REQUIRED_VARS LERC_LIBRARY LERC_INCLUDE_DIR
        VERSION_VAR LERC_VERSION_STRING)

if(LERC_FOUND)
    set(LERC_INCLUDE_DIRS ${LERC_INCLUDE_DIR})

    if(NOT LERC_LIBRARIES)
        set(LERC_LIBRARIES ${LERC_LIBRARY})
    endif()

    if(NOT TARGET LERC::LERC)
        add_library(LERC::LERC UNKNOWN IMPORTED)
        set_target_properties(LERC::LERC PROPERTIES
                INTERFACE_INCLUDE_DIRECTORIES "${LERC_INCLUDE_DIRS}")

        if(LERC_LIBRARY_RELEASE)
            set_property(TARGET LERC::LERC APPEND PROPERTY
                    IMPORTED_CONFIGURATIONS RELEASE)
            set_target_properties(LERC::LERC PROPERTIES
                    IMPORTED_LOCATION_RELEASE "${LERC_LIBRARY_RELEASE}")
        endif()

        if(LERC_LIBRARY_DEBUG)
            set_property(TARGET LERC::LERC APPEND PROPERTY
                    IMPORTED_CONFIGURATIONS DEBUG)
            set_target_properties(LERC::LERC PROPERTIES
                    IMPORTED_LOCATION_DEBUG "${LERC_LIBRARY_DEBUG}")
        endif()

        if(NOT LERC_LIBRARY_RELEASE AND NOT LERC_LIBRARY_DEBUG)
            set_target_properties(LERC::LERC PROPERTIES
                    IMPORTED_LOCATION_RELEASE "${LERC_LIBRARY}")
        endif()
    endif()
endif()


text:
#include <unistd.h>
#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions
#include <time.h>
#include <stdint.h>

#include "lcd.h"

// Global variables
static int fd_lcd_G = 0;

// Constant values
static const char *lcd_port = "/dev/ttyO1";
static const float zeros_13 = 10000000000.0;
static const float zeros_4 = 10000.0;

#pragma pack(1)
// Structure definitions
typedef struct raw_node_data_s{
    int16_t accel_x;
    int16_t accel_y;
    int16_t accel_z;
    uint16_t temp;
    uint32_t pressure;
    //float humidity;
    //float luminosity;
    uint16_t humidity;
    uint16_t luminosity;
    unsigned char addr[16]; /* IPv6 address */
}raw_node_data_t;

typedef struct time_llh_s{
    int combinerID;
    int number_of_nodes;
    //float latitude;
    //float longitude;
    long long latitude;
    long long longitude;
}time_llh_t;

#pragma pack()

// Private function prototypes
static int set_interface_attribs (int fd, int speed, int parity);
static void set_blocking (int fd, int should_block);

static int set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                printf ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

static void set_blocking(int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                printf ("error %d setting term attributes", errno);
}

int send_data_2_lcd(uint8_t *buf, int size)
{
    int n = 0;
    n = write(fd_lcd_G, buf, size);
    return n;
}

int initiate_lcd_comm(void)
{
    printf("initiating lcd stuff\n");
    fd_lcd_G = open( lcd_port, O_RDWR | O_NOCTTY | O_SYNC);
    set_interface_attribs(fd_lcd_G, B115200, 0);
    set_blocking(fd_lcd_G, 0); // set to no blocking
    return 0;
}

int dismiss_lcd_comm(void)
{
    close(fd_lcd_G);
    return 0;
}


text:
<?php

namespace TwbBundle\Form\View\Helper;

use DomainException;
use Zend\Form\View\Helper\FormRow;
use Zend\Form\ElementInterface;
use Zend\Form\LabelAwareInterface;
use Zend\Form\Element\Button;
use Zend\Form\Element\Submit;

class TwbBundleFormRow extends FormRow
{

    /**
     * @var string
     */
    protected static $formGroupFormat = '
%s
';

    /**
     * @var string
     */
    protected static $horizontalLayoutFormat = '
%s
';

    /**
     * @var string
     */
    protected static $checkboxFormat = '
%s
';

    /**
     * @var string
     */
    protected static $helpBlockFormat = '
%s
';

    /**
     * The class that is added to element that have errors
     * @var string
     */
    protected $inputErrorClass = '';

    /**
     * @var string
     */
    protected $requiredFormat = null;

    /**
     * @see FormRow::render()
     * @param ElementInterface $oElement
     * @return string
     */
    public function render(ElementInterface $oElement, $sLabelPosition = null)
    {
        // Retrieve element type
        $sElementType = $oElement->getAttribute('type');

        // Nothing to do for hidden elements which have no messages
        if ($sElementType === 'hidden' && !$oElement->getMessages()) {
            return parent::render($oElement, $sLabelPosition);
        }

        // Retrieve expected layout
        $sLayout = $oElement->getOption('twb-layout');

        // Define label position
        if ($sLabelPosition === null) {
            $sLabelPosition = $this->getLabelPosition();
        }

        // Partial rendering
        if ($this->partial) {
            return $this->view->render($this->partial, array(
                        'element' => $oElement,
                        'label' => $this->renderLabel($oElement),
                        'labelAttributes' => $this->labelAttributes,
                        'labelPosition' => $sLabelPosition,
                        'renderErrors' => $this->renderErrors,
            ));
        }

        // "has-error" validation state case
        if ($oElement->getMessages()) {
            //Element have errors
            if ($sInputErrorClass = $this->getInputErrorClass()) {
                if ($sElementClass = $oElement->getAttribute('class')) {
                    if (!preg_match('/(\s|^)' . preg_quote($sInputErrorClass, '/') . '(\s|$)/', $sElementClass)) {
                        $oElement->setAttribute('class', trim($sElementClass . ' ' . $sInputErrorClass));
                    }
                } else {
                    $oElement->setAttribute('class', $sInputErrorClass);
                }
            }
        }

        // Render element
        $sElementContent = $this->renderElement($oElement, $sLabelPosition);

        // Render form row
        switch (true) {
            // Checkbox element not in horizontal form
            case $sElementType === 'checkbox' && $sLayout !== TwbBundleForm::LAYOUT_HORIZONTAL:
            // All "button" elements in inline form
            case in_array($sElementType, array('submit', 'button', 'reset'), true) && $sLayout === TwbBundleForm::LAYOUT_INLINE:
                return $sElementContent . PHP_EOL;
            default:
                // Render element into form group
                return $this->renderElementFormGroup($sElementContent, $this->getRowClassFromElement($oElement));
        }
    }

    /**
     * @param ElementInterface $oElement
     * @return string
     */
    public function getRowClassFromElement(\Zend\Form\ElementInterface $oElement)
    {
        $sRowClass = '';
        if ($sFormGroupSize = $oElement->getOption('twb-form-group-size')) {
            $sRowClass = $sFormGroupSize;
        }

        // Validation state
        if (($sValidationState = $oElement->getOption('validation-state'))) {
            $sRowClass .= ' has-' . $sValidationState;
        }
        if ($oElement->getMessages()) {
            $sRowClass .= ' has-error';
        }

        // Column size
        if (($sColumSize = $oElement->getOption('column-size')) && $oElement->getOption('twb-layout') !== TwbBundleForm::LAYOUT_HORIZONTAL
        ) {
            $sRowClass .= ' col-' . $sColumSize;
        }
        return $sRowClass;
    }

    /**
     * @param string $sElementContent
     * @param string $sRowClass
     * @return string
     * @throws \InvalidArgumentException
     */
    public function renderElementFormGroup($sElementContent, $sRowClass)
    {
        if (!is_string($sElementContent)) {
            throw new \InvalidArgumentException('Argument "$sElementContent" expects a string, "' . (is_object($sElementContent) ? get_class($sElementContent) : gettype($sElementContent)) . '" given');
        }
        if (!is_string($sRowClass)) {
            throw new \InvalidArgumentException('Argument "$sRowClass" expects a string, "' . (is_object($sRowClass) ? get_class($sRowClass) : gettype($sRowClass)) . '" given');
        }
        return sprintf(self::$formGroupFormat, $sRowClass, $sElementContent) . PHP_EOL;
    }

    /**
     * Render element's label
     * @param ElementInterface $oElement
     * @return string
     */
    protected function renderLabel(ElementInterface $oElement)
    {
        if (($sLabel = $oElement->getLabel()) && ($oTranslator = $this->getTranslator())) {
            $sLabel = $oTranslator->translate($sLabel, $this->getTranslatorTextDomain());
        }
        return $sLabel;
    }

    /**
     * Render element
     * @param ElementInterface $oElement
     * @param string $sLabelPosition
     * @return type
     * @throws DomainException
     */
    protected function renderElement(ElementInterface $oElement, $sLabelPosition = null)
    {
        //Retrieve expected layout
        $sLayout = $oElement->getOption('twb-layout');

        // Define label position
        if ($sLabelPosition === null) {
            $sLabelPosition = $this->getLabelPosition();
        }

        //Render label
        $sLabelOpen = $sLabelClose = $sLabelContent = $sElementType = '';
        if ($sLabelContent = $this->renderLabel($oElement)) {
            /*
             * Multicheckbox elements have to be handled differently
             * as the HTML standard does not allow nested labels.
             * The semantic way is to group them inside a fieldset
             */
            $sElementType = $oElement->getAttribute('type');

            //Button element is a special case, because label is always rendered inside it
            if (($oElement instanceof Button) or ( $oElement instanceof Submit)) {
                $sLabelContent = '';
            } else {
                $aLabelAttributes = $oElement->getLabelAttributes() ? : $this->labelAttributes;

                //Validation state
                if ($oElement->getOption('validation-state') || $oElement->getMessages()) {
                    if (empty($aLabelAttributes['class'])) {
                        $aLabelAttributes['class'] = 'control-label';
                    } elseif (!preg_match('/(\s|^)control-label(\s|$)/', $aLabelAttributes['class'])) {
                        $aLabelAttributes['class'] = trim($aLabelAttributes['class'] . ' control-label');
                    }
                }

                $oLabelHelper = $this->getLabelHelper();
                switch ($sLayout) {
                    //Hide label for "inline" layout
                    case TwbBundleForm::LAYOUT_INLINE:
                        if ($sElementType !== 'checkbox') {
                            if (empty($aLabelAttributes['class'])) {
                                $aLabelAttributes['class'] = 'sr-only';
                            } elseif (!preg_match('/(\s|^)sr-only(\s|$)/', $aLabelAttributes['class'])) {
                                $aLabelAttributes['class'] = trim($aLabelAttributes['class'] . ' sr-only');
                            }
                        }
                        break;

                    case TwbBundleForm::LAYOUT_HORIZONTAL:
                        if ($sElementType !== 'checkbox') {
                            if (empty($aLabelAttributes['class'])) {
                                $aLabelAttributes['class'] = 'control-label';
                            } else {
                                if (!preg_match('/(\s|^)control-label(\s|$)/', $aLabelAttributes['class'])) {
                                    $aLabelAttributes['class'] = trim($aLabelAttributes['class'] . ' control-label');
                                }
                            }
                        }
                        break;
                }
                if ($aLabelAttributes) {
                    $oElement->setLabelAttributes($aLabelAttributes);
                }

                $sLabelOpen = $oLabelHelper->openTag($oElement->getAttribute('id') ? $oElement : $aLabelAttributes);
                $sLabelClose = $oLabelHelper->closeTag();

                // Allow label html escape desable
                //$sLabelContent = $this->getEscapeHtmlHelper()->__invoke($sLabelContent);

                if (!$oElement instanceof LabelAwareInterface || !$oElement->getLabelOption('disable_html_escape')) {
                    $sLabelContent = $this->getEscapeHtmlHelper()->__invoke($sLabelContent);
                }
            }
        }

        //Add required string if element is required
        if ($this->requiredFormat &&
                $oElement->getAttribute('required') &&
                strpos($this->requiredFormat, $sLabelContent) === false
        ) {
            $sLabelContent .= $this->requiredFormat;
        }

        switch ($sLayout) {
            case null:
            case TwbBundleForm::LAYOUT_INLINE:

                $sElementContent = $this->getElementHelper()->render($oElement);

                // Checkbox elements are a special case, element is already rendered into label
                if ($sElementType === 'checkbox') {
                    $sElementContent = sprintf(self::$checkboxFormat, $sElementContent);
                } else {
                    if ($sLabelPosition === self::LABEL_PREPEND) {
                        $sElementContent = $sLabelOpen . $sLabelContent . $sLabelClose . $sElementContent;
                    } else {
                        $sElementContent = $sElementContent . $sLabelOpen . $sLabelContent . $sLabelClose;
                    }
                }

                //Render help block
                $sElementContent .= $this->renderHelpBlock($oElement);

                //Render errors
                if ($this->renderErrors) {
                    $sElementContent .= $this->getElementErrorsHelper()->render($oElement);
                }

                return $sElementContent;

            case TwbBundleForm::LAYOUT_HORIZONTAL:
                $sElementContent = $this->getElementHelper()->render($oElement) . $this->renderHelpBlock($oElement);

                //Render errors
                if ($this->renderErrors) {
                    $sElementContent .= $this->getElementErrorsHelper()->render($oElement);
                }

                $sClass = '';

                //Column size
                if ($sColumSize = $oElement->getOption('column-size')) {
                    $sClass .= ' col-' . $sColumSize;
                }

                // Checkbox elements are a special case, element is rendered into label
                if ($sElementType === 'checkbox') {
                    return sprintf(
                            self::$horizontalLayoutFormat, $sClass, sprintf(self::$checkboxFormat, $sElementContent)
                    );
                }

                if ($sLabelPosition === self::LABEL_PREPEND) {
                    return $sLabelOpen . $sLabelContent . $sLabelClose . sprintf(
                                    self::$horizontalLayoutFormat, $sClass, $sElementContent
                    );
                } else {
                    return sprintf(
                                    self::$horizontalLayoutFormat, $sClass, $sElementContent
                            ) . $sLabelOpen . $sLabelContent . $sLabelClose;
                }
        }
        throw new DomainException('Layout "' . $sLayout . '" is not valid');
    }

    /**
     * Render element's help block
     * @param ElementInterface $oElement
     * @return string
     */
    protected function renderHelpBlock(ElementInterface $oElement)
    {
        if ($sHelpBlock = $oElement->getOption('help-block')) {
            if ($oTranslator = $this->getTranslator()) {
                $sHelpBlock = $oTranslator->translate($sHelpBlock, $this->getTranslatorTextDomain());
            }
            $sHelpBlockString = strip_tags($sHelpBlock);
            if ($sHelpBlock === $sHelpBlockString) {
                $sHelpBlock = $this->getEscapeHtmlHelper()->__invoke($sHelpBlock);
            }
            return sprintf(self::$helpBlockFormat, $sHelpBlock);
        } else {
            return '';
        }
    }
}


text:
from custom import *
from generic import *


text:
<?php

namespace Proxies\__CG__\MyApp\ApBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class Note extends \MyApp\ApBundle\Entity\Note implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setType($type)
    {
        $this->__load();
        return parent::setType($type);
    }

    public function getType()
    {
        $this->__load();
        return parent::getType();
    }

    public function setNote($note)
    {
        $this->__load();
        return parent::setNote($note);
    }

    public function getNote()
    {
        $this->__load();
        return parent::getNote();
    }

    public function setClient(\MyApp\ApBundle\Entity\Client $client)
    {
        $this->__load();
        return parent::setClient($client);
    }

    public function getClient()
    {
        $this->__load();
        return parent::getClient();
    }

    public function setCreated($created)
    {
        $this->__load();
        return parent::setCreated($created);
    }

    public function getCreated()
    {
        $this->__load();
        return parent::getCreated();
    }

    public function setUpdated($updated)
    {
        $this->__load();
        return parent::setUpdated($updated);
    }

    public function getUpdated()
    {
        $this->__load();
        return parent::getUpdated();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'type', 'note', 'created', 'updated', 'client');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
namespace mozart {

namespace builtins {

//////////////////
// Debug module //
//////////////////

class ModDebug: public Module {
public:
  ModDebug(): Module("Debug") {}

  class GetRaiseOnBlock: public Builtin<GetRaiseOnBlock> {
  public:
    GetRaiseOnBlock(): Builtin("getRaiseOnBlock") {}

    void operator()(VM vm, In thread, Out result) {
      auto runnable = getArgument<Runnable*>(vm, thread, MOZART_STR("Thread"));

      result = build(vm, runnable->getRaiseOnBlock());
    }
  };

  class SetRaiseOnBlock: public Builtin<SetRaiseOnBlock> {
  public:
    SetRaiseOnBlock(): Builtin("setRaiseOnBlock") {}

    void operator()(VM vm, In thread, In value) {
      auto runnable = getArgument<Runnable*>(vm, thread, MOZART_STR("Thread"));
      auto boolValue = getArgument<bool>(vm, value, MOZART_STR("Boolean"));

      runnable->setRaiseOnBlock(boolValue);
    }
  };

  class SetId: public Builtin<SetId> {
  public:
    SetId(): Builtin("setId") {}

    void operator()(VM vm, In thread, In id) {
      // TODO
    }
  };

  class Breakpoint: public Builtin<Breakpoint> {
  public:
    Breakpoint(): Builtin("breakpoint") {}

    void operator()(VM vm) {
      // TODO
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODDEBUG_H


text:
using System.Collections.Generic;
using System.Web.Mvc;
using Epi.FormMetadata.DataStructures;
using Epi.Cloud.Common.Message;
using Epi.Cloud.Common.Model;

namespace Epi.Cloud.MVC.Models
{
    public class FormResponseInfoModel
    {
        public FormSettingResponse FormSettingResponse;
        public FormInfoModel FormInfoModel;
        public UserModel UserModel;
        public List<ResponseModel> ResponsesList;
        public List<KeyValuePair<int, string>> Columns;
        public List<KeyValuePair<int, FieldDigest>> ColumnDigests;
        public int NumberOfPages;
        public int CurrentPage;
        public int PageSize;
        public int NumberOfResponses;
        public int ViewId;
        public string ParentResponseId;
        public string sortOrder;
        public string sortfield;
        public SearchBoxModel SearchModel;
        public List<SelectListItem> SearchColumns1;
        public List<SelectListItem> SearchColumns2;
        public List<SelectListItem> SearchColumns3;
        public List<SelectListItem> SearchColumns4;
        public List<SelectListItem> SearchColumns5;

        public FormResponseInfoModel()
        {
            FormInfoModel = new FormInfoModel();
            ResponsesList = new List<ResponseModel>();
            Columns = new List<KeyValuePair<int, string>>();
            ColumnDigests = new List<KeyValuePair<int, FieldDigest>>();
        }
    }
}


text:
package com.github.pentadrago.fileverifier.swing;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

/**
 * provides a table model that can be appended, prepended or overwritten by each
 * new message
 *
 * @author Stefan Kloe
 */
public class MessageTableModel extends AbstractTableModel {

    /**
     * controls the behavior on inserting new messages
     */
    public enum Mode {

        APPEND, OVERWRITE, PREPEND;
    }

    private final List<String> messages = new ArrayList<>();

    private final Mode mode;

    public MessageTableModel(Mode mode) {
        this.mode = mode;
    }

    @Override
    public int getColumnCount() {
        return 1;
    }

    @Override
    public int getRowCount() {
        return messages.size();
    }

    @Override
    public Object getValueAt(int row, int column) {
        return messages.get(row);
    }

    /**
     * adds the given message according to mode
     *
     * @param message new message
     */
    public void addMessage(String message) {
        switch (mode) {
            case APPEND:
                messages.add(message);
                break;
            case PREPEND:
                messages.add(0, message);
                break;
            case OVERWRITE:
                messages.clear();
                messages.add(message);
                break;
        }
        fireTableDataChanged();
    }

    /**
     * removes all messages from table
     */
    public void clear() {
        messages.clear();
        fireTableDataChanged();
    }

}


text:
"""Common configuration constants
"""

PROJECTNAME = 'bda.plone.productshop'

ADD_PERMISSIONS = {
    # -*- extra stuff goes here -*-
}


text:
(function () {
    "use strict";

    function CompositionsController($scope, $location, $filter, $timeout, overlayService, localizationService) {

        var vm = this;
        var oldModel = null;

        vm.showConfirmSubmit = false;
        vm.loadingAlias = null;

        vm.isSelected = isSelected;
        vm.openContentType = openContentType;
        vm.selectCompositeContentType = selectCompositeContentType;
        vm.submit = submit;
        vm.close = close;

        function onInit() {

            /* make a copy of the init model so it is possible to roll
            back the changes on cancel */
            oldModel = Utilities.copy($scope.model);

            if (!$scope.model.title) {
                $scope.model.title = "Compositions";
            }

            // Group the content types by their container paths
            vm.availableGroups = $filter("orderBy")(
                _.map(
                    _.groupBy($scope.model.availableCompositeContentTypes, function (compositeContentType) {

                        compositeContentType.selected = isSelected(compositeContentType.contentType.alias);

                        return compositeContentType.contentType.metaData.containerPath;
                    }), function (group) {
                        return {
                            containerPath: group[0].contentType.metaData.containerPath,
                            compositeContentTypes: group
                        };
                    }
                ), function (group) {
                    return group.containerPath.replace(/\//g, " ");
                });
        }

        function isSelected(alias) {
            if ($scope.model.contentType.compositeContentTypes.indexOf(alias) !== -1) {
                return true;
            }
            return false;
        }

        function openContentType(contentType, section) {
            var url = (section === "documentType" ? "/settings/documenttypes/edit/" : "/settings/mediaTypes/edit/") + contentType.id;
            $location.path(url);
        }

        function selectCompositeContentType(compositeContentType) {
            vm.loadingAlias = compositeContentType.contentType.alias

            var contentType = compositeContentType.contentType;

            $scope.model.selectCompositeContentType(contentType).then(function (response) {
                vm.loadingAlias = null;
            });

            // Check if the template is already selected.
            var index = $scope.model.contentType.compositeContentTypes.indexOf(contentType.alias);

            if (index === -1) {
                $scope.model.contentType.compositeContentTypes.push(contentType.alias);
            } else {
                $scope.model.contentType.compositeContentTypes.splice(index, 1);
            }
        }

        function submit() {
            if ($scope.model && $scope.model.submit) {

                // check if any compositions has been removed
                var compositionRemoved = false;
                for (var i = 0; oldModel.compositeContentTypes.length > i; i++) {
                    var oldComposition = oldModel.compositeContentTypes[i];
                    if (_.contains($scope.model.compositeContentTypes, oldComposition) === false) {
                        compositionRemoved = true;
                    }
                }

                /* submit the form if there havne't been removed any composition
                or the confirm checkbox has been checked */
                if (compositionRemoved) {
                    vm.allowSubmit = false;
                    localizationService.localize("general_remove").then(function (value) {
                        const dialog = {
                            view: "views/common/infiniteeditors/compositions/overlays/confirmremove.html",
                            title: value,
                            submitButtonLabelKey: "general_ok",
                            submitButtonStyle: "danger",
                            closeButtonLabelKey: "general_cancel",
                            submit: function (model) {
                                $scope.model.submit($scope.model);
                                overlayService.close();
                            },
                            close: function () {
                                overlayService.close();
                            }
                        };
                        overlayService.open(dialog);
                    });
                    return;
                }

                $scope.model.submit($scope.model);
            }
        }

        function close() {
            if ($scope.model && $scope.model.close) {
                $scope.model.close(oldModel);
            }
        }

        onInit();
    }

    angular.module("umbraco").controller("Umbraco.Editors.CompositionsController", CompositionsController);

})();


text:
'''Installs beakerx_databrowser into a Jupyter and Python environment.'''

import argparse
import json
import os
import pkg_resources
import shutil
import subprocess
import sys
import pathlib
import tempfile

from string import Template
from jupyter_client.kernelspecapp import KernelSpecManager
from jupyter_core import paths
from traitlets.config.manager import BaseJSONConfigManager
from distutils import log

def _uninstall_nbextension():
    subprocess.check_call(["jupyter", "nbextension", "disable", "beakerx_databrowser", "--py", "--sys-prefix"])
    subprocess.check_call(["jupyter", "nbextension", "uninstall", "beakerx_databrowser", "--py", "--sys-prefix"])
    subprocess.check_call(["jupyter", "serverextension", "disable", "beakerx_databrowser", "--py", "--sys-prefix"])

def _install_nbextension():
    if sys.platform == 'win32':
        subprocess.check_call(["jupyter", "nbextension", "install", "beakerx_databrowser", "--py", "--sys-prefix"])
    else:
        subprocess.check_call(["jupyter", "nbextension", "install", "beakerx_databrowser", "--py", "--symlink", "--sys-prefix"])

    subprocess.check_call(["jupyter", "nbextension", "enable", "beakerx_databrowser", "--py", "--sys-prefix"])
    subprocess.check_call(["jupyter", "serverextension", "enable", "beakerx_databrowser", "--py", "--sys-prefix"])

def make_parser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--prefix",
                        help="location of the environment to install into",
                        default=sys.prefix)
    parser.add_argument("--disable",
                        help="Remove Beakerx extension",
                        action='store_true')
    return parser

def install(args):
    _install_nbextension()

def uninstall(args):
    _uninstall_nbextension()

if __name__ == "__main__":
    install()


text: export * from './scenes.component';


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using OdjfsScraper.Database;
using SmartRoutes.Demo.OdjfsDatabase.Model;
using DayCamp = OdjfsScraper.Model.ChildCares.DayCamp;
using LicensedCenter = OdjfsScraper.Model.ChildCares.LicensedCenter;
using TypeAHome = OdjfsScraper.Model.ChildCares.TypeAHome;
using TypeBHome = OdjfsScraper.Model.ChildCares.TypeBHome;

namespace SmartRoutes.Demo.OdjfsDatabase
{
    public class OdjfsDatabase : IDisposable
    {
        private readonly string _nameOrConnectionString;
        private Entities _ctx;

        public OdjfsDatabase(string nameOrConnectionString)
        {
            _nameOrConnectionString = nameOrConnectionString;
            _ctx = null;
        }

        public void Dispose()
        {
            if (_ctx != null)
            {
                _ctx.Dispose();
            }
        }

        public async Task<IEnumerable<ChildCare>> GetChildCares()
        {
            Open();

            IEnumerable<OdjfsScraper.Model.ChildCares.ChildCare> inputChildCares = await _ctx
                .ChildCares
                .AsNoTracking()
                .Where(c => c.Latitude.HasValue && c.Longitude.HasValue)
                .ToArrayAsync().ConfigureAwait(false);

            IList<ChildCare> outputChildCares = new List<ChildCare>();

            // map each child care to its appropriote wrapper type
            foreach (OdjfsScraper.Model.ChildCares.ChildCare childCare in inputChildCares)
            {
                var typeAHome = childCare as TypeAHome;
                if (typeAHome != null)
                {
                    outputChildCares.Add(new Model.TypeAHome(typeAHome));
                }

                var typeBHome = childCare as TypeBHome;
                if (typeBHome != null)
                {
                    outputChildCares.Add(new Model.TypeBHome(typeBHome));
                }

                var licensedCenter = childCare as LicensedCenter;
                if (licensedCenter != null)
                {
                    outputChildCares.Add(new Model.LicensedCenter(licensedCenter));
                }

                var dayCamp = childCare as DayCamp;
                if (dayCamp != null)
                {
                    outputChildCares.Add(new Model.DayCamp(dayCamp));
                }
            }

            return outputChildCares;
        }

        public void Close()
        {
            Dispose();
        }

        public void Open()
        {
            if (_ctx == null)
            {
                _ctx = new Entities(_nameOrConnectionString);
            }
        }
    }
}


text:
package resources

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestGetChangedServices(t *testing.T) {
	release := Release{
		Services: map[string]string{
			"service1": "1",
			"service2": "2",
			"service3": "foo",
			"service4": "4",
		},
	}

	changedServices := release.getChangedServices(&Release{
		Services: map[string]string{
			"service1": "1",
			"service2": "2",
			"service3": "3",
		},
	})

	assert.Len(t, changedServices, 2)
	assert.Contains(t, changedServices, "service3")
	assert.Contains(t, changedServices, "service4")
}