text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.UI
{
    /// <summary>
    /// Add to any Object to spawn ToolTips on tap or on focus, according to preference
    /// Applies its follow settings to the spawned ToolTip's ToolTipConnector component
    /// </summary>
    [AddComponentMenu("Scripts/MRTK/SDK/ToolTipSpawner")]
    public class ToolTipSpawner : PrefabSpawner
    {
        private enum SettingsMode
        {
            UseDefaults = 0,
            Override
        }

        [Header("ToolTip Override Settings")]
        [Tooltip("Prefab's settings will be used unless this is set to Override")]
        [SerializeField]
        private SettingsMode settingsMode = SettingsMode.UseDefaults;
        [SerializeField]
        private bool showBackground = true;
        [SerializeField]
        private bool showOutline = false;
        [SerializeField]
        private bool showConnector = true;
        [SerializeField]
        private ConnectorFollowType followType = ConnectorFollowType.AnchorOnly;
        [SerializeField]
        private ConnectorPivotMode pivotMode = ConnectorPivotMode.Manual;
        [SerializeField]
        private ConnectorPivotDirection pivotDirection = ConnectorPivotDirection.North;
        [SerializeField]
        private ConnectorOrientType pivotDirectionOrient = ConnectorOrientType.OrientToObject;
        [SerializeField]
        private Vector3 manualPivotDirection = Vector3.up;
        [SerializeField]
        private Vector3 manualPivotLocalPosition = Vector3.up;
        [SerializeField]
        [Range(0f, 2f)]
        private float pivotDistance = 0.25f;

        [SerializeField]
        private string toolTipText = "New Tooltip";

        [SerializeField]
        private Transform anchor = null;

        protected override void SpawnableActivated(GameObject spawnable)
        {
            var toolTip = spawnable.GetComponent<ToolTip>();

            toolTip.ToolTipText = toolTipText;
            var connector = toolTip.GetComponent<ToolTipConnector>();
            connector.Target = (anchor != null) ? anchor.gameObject : gameObject;

            switch (settingsMode)
            {
                case SettingsMode.UseDefaults:
                    break;

                case SettingsMode.Override:
                    toolTip.ShowBackground = showBackground;
                    toolTip.ShowHighlight = showOutline;
                    toolTip.ShowConnector = showConnector;

                    connector.PivotDirection = pivotDirection;
                    connector.PivotDistance = pivotDistance;
                    connector.PivotDirectionOrient = pivotDirectionOrient;
                    connector.ManualPivotLocalPosition = manualPivotLocalPosition;
                    connector.ManualPivotDirection = manualPivotDirection;
                    connector.ConnectorFollowingType = followType;
                    connector.PivotMode = pivotMode;

                    if (connector.PivotMode == ConnectorPivotMode.Manual)
                    {
                        toolTip.PivotPosition = transform.TransformPoint(manualPivotLocalPosition);
                    }
                    break;
            }
        }

#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            if (Application.isPlaying) { return; }

            if (prefab == null) { return; }

            if (gameObject == UnityEditor.Selection.activeGameObject)
            {
                Gizmos.color = Color.cyan;
                Transform relativeTo = null;

                ConnectorFollowType followType = this.followType;
                ConnectorOrientType pivotDirectionOrient = this.pivotDirectionOrient;
                ConnectorPivotDirection pivotDirection = this.pivotDirection;
                ConnectorPivotMode pivotMode = this.pivotMode;
                Vector3 manualPivotDirection = this.manualPivotDirection;
                Vector3 manualPivotLocalPosition = this.manualPivotLocalPosition;
                float pivotDistance = this.pivotDistance;

                switch (settingsMode)
                {
                    case SettingsMode.UseDefaults:
                        ToolTipConnector connector = prefab.GetComponent<ToolTipConnector>();
                        followType = connector.ConnectorFollowingType;
                        pivotDirectionOrient = connector.PivotDirectionOrient;
                        pivotDirection = connector.PivotDirection;
                        pivotMode = connector.PivotMode;
                        manualPivotDirection = connector.ManualPivotDirection;
                        manualPivotLocalPosition = connector.ManualPivotLocalPosition;
                        pivotDistance = connector.PivotDistance;
                        break;
                }

                switch (pivotDirectionOrient)
                {
                    case ConnectorOrientType.OrientToCamera:
                        relativeTo = CameraCache.Main.transform;
                        break;

                    case ConnectorOrientType.OrientToObject:
                        relativeTo = (anchor != null) ? anchor.transform : transform;
                        break;
                }

                Vector3 targetPosition = (anchor != null) ? anchor.transform.position : transform.position;

                switch (followType)
                {
                    case ConnectorFollowType.AnchorOnly:
                        Gizmos.DrawLine(targetPosition, transform.TransformPoint(manualPivotLocalPosition));
                        Gizmos.DrawWireCube(transform.TransformPoint(manualPivotLocalPosition), Vector3.one * 0.05f);
                        break;

                    case ConnectorFollowType.Position:
                    case ConnectorFollowType.PositionAndXYRotation:
                    case ConnectorFollowType.PositionAndYRotation:
                        if (pivotMode == ConnectorPivotMode.Automatic)
                        {
                            Vector3 toolTipPosition = targetPosition + ToolTipConnector.GetDirectionFromPivotDirection(
                                            pivotDirection,
                                            manualPivotDirection,
                                            relativeTo) * pivotDistance;
                            Gizmos.DrawLine(targetPosition, toolTipPosition);
                            Gizmos.DrawWireCube(toolTipPosition, Vector3.one * 0.05f);
                        }
                        else
                        {
                            Vector3 toolTipPosition = transform.TransformPoint(manualPivotLocalPosition);
                            Gizmos.DrawLine(targetPosition, toolTipPosition);
                            Gizmos.DrawWireCube(toolTipPosition, Vector3.one * 0.05f);
                        }
                        break;
                }
            }
        }
#endif // UNITY_EDITOR
    }
}


text:
#ifndef SEARCH_MATCH_POINTS
#define SEARCH_MATCH_POINTS

#include "config.h"
#include "SearchTypes.h"
#include "ItemTypes.h"
#include "StringTable.h"

#define BPR(x) ( (x) ? "true" : "false" )

class Packet;

// - Class SearchMatchPoints ---

/**
 *   Class containing the points for a SearchMatchLink
 *   or SearchMatch. Move to another file later.
 */
class SearchMatchPoints {
public:

   /**
    *   Type of match.
    */
   enum matchedString_t {
      unknown    = 0,
      exact      = 1,
      close      = 2,
      full_close = 3,
      full_exact = 4
   };

   /**
    *   Constructor. Initializes values.
    */
   inline SearchMatchPoints();

   /**
    *   Initializes values to default.
    */
   inline void reset();

   /**
    *   Returns the calculated number of points.
    *   Moved to the cpp-file by pi to avoid too much
    *   recompiling. Move back when speed is important.
    */
   uint16 getPoints(bool debugp = false) const;

   /**
    *   Sets the itemtype and item subtype for the points.
    */
   void setTypes(uint32 searchType,
                 ItemTypes::itemType itemType,
                 uint16 subType);

   /**
    *   Sets the distance from the origin in meters.
    */
   inline void setDistanceMeters(uint32 meters);

   /**
    *   Sets the stringmatching used for finding the
    *   match.
    */
   inline void setMatching(SearchTypes::StringMatching m);

   /**
    *   Sets the type of string matched. Close or exact.
    */
   inline void setMatchedStringIs(SearchMatchPoints::matchedString_t x);

   /**
    *   Returns true if the match is full.
    */
   inline bool isFullMatch() const;

   /**
    *   Sets if the location is correct or not.
    */
   inline void setCorrectLocation(bool correct);

   /**
    *   Sets the number of points obtained from the BSSSElement
    *   in the SearchModule.
    */
   inline void setElemPoints(uint16 elemPoints);

   /**
    *   Sets the difference in house numbers if a house number
    *   was found.
    *   @param houseNbrDiff The difference in house numbers.
    */
   inline void setHouseNbrDiff(int16 houseNbrDiff);

   /**
    *   Sets the editdistance.
    */
   inline void setEditDistance(uint16 editDistance);

   /**
    *   Returns the edit distance.
    */
   inline uint16 getEditDistance() const;

   /**
    *   Sets the position in the string the match was.
    */
   inline void setPositionInString(uint8 pos);

   /**
    *   Returns the position in the string where the match was.
    */
   inline uint8 getPositionInString() const;

   /**
    *   Sets if the found ssi was in the correct region.
    */
   inline void setSSICorrectLocation( bool correctRegion );

   /**
    *   Sets if the correct order of the words were found.
    */
   inline void setAllWordsCorrectOrder(bool correctOrder);

   /**
    *   Saves the points in a packet.
    *   @param p   The packet to save the points in.
    *   @param pos Starting position of the points. Will
    *              be updated.
    *   @param matchInfoHere True if information that also
    *                        exists in the VanillaMatches should
    *                        be saved or false if it is set later.
    *   @return True if successful.
    */
   bool save(Packet* p, int& pos, bool matchInfoHere) const;

   /**
    *   Loads the points from a packet.
    *   @param p   Packet to load from.
    *   @param pos Position to start at. Will be updated.
    *   @param matchInfoHere True if information that also
    *                        exists in the VanillaMatches was
    *                        saved or false if it is set later.
    */
   bool load(const Packet* p, int& pos, bool matchInfoHere);

   /**
    *   Returns the size of the points in the packet.
    *   @param matchInfoHere True if information that also
    *                        exists in the VanillaMatches is to
    *                        be saved or false if it is set later.
    */
   int getSizeInPacket(bool matchInfoHere) const;

   /**
    *   Returns true if the match matches the end of
    *   a word.
    */
   inline void setMatchesEndOfWord(bool doesIt);

   /**
    *   Returns true if the match matches the beginning
    *   a word.
    */
   inline void setMatchesBeginningOfWord(bool doesIt);

   /**
    *   Returns true if the number of points for this match
    *   is less than the number of points for the other one.
    *   Should be removed later.
    */
   inline bool operator< ( const SearchMatchPoints& other ) const {
      return getPoints() < other.getPoints();
   }

   inline bool operator== ( const SearchMatchPoints& other) const {
      return getPoints() == other.getPoints();
   }

   inline bool operator!= ( const SearchMatchPoints& other) const {
      return getPoints() != other.getPoints();
   }

   inline bool operator> ( const SearchMatchPoints& other) const {
      return getPoints() > other.getPoints();
   }

   /**
    *   Prints the points on the stream.
    *   @param stream The stream to print to.
    *   @param points The points to print.
    *   @return The stream.
    */
   inline friend ostream& operator<<( ostream& stream,
                                      const SearchMatchPoints& points);

private:
   /**
    *   The distance in meters from the
    */
   uint32 m_distanceMeters;

   /**
    *   Difference in housenumber.
    */
   int16 m_houseNbrDiff;

   /**
    *   The number of points stored in the
    *   binarystringsearchstruct.
    */
   uint16 m_elemPoints;

   /**
    *   The edit distance. MAX_UINT16 = invalid.
    */
   uint16 m_editDistance;

   /**
    *   Position in string where the match was.
    */
   uint8 m_positionInString;

   /**
    *   Measure of the string difference.
    */
   uint8 m_stringDiff;

   /**
    *   The matching used.
    */
   SearchTypes::StringMatching m_matching;

   /**
    *   The type of match (close/exact).
    */
   matchedString_t m_matchedStringIs;

   /**
    *   True if the location is correct.
    */
   bool m_correctLocation;

   /**
    *   True if the best SSI (according to housenumbers )
    *   of a street is in the correct region. Only valid
    *   if m_houseNbrDiff is set.
    */
   bool m_ssiCorrectLocation;

   /**
    *   True if the match matches the end of a word.
    */
   bool m_matchesEndOfWord;

   /**
    *   True if the match matches the beginning of a word.
    */
   bool m_matchesBeginningOfWord;

   /**
    *   True if allwords matching was in the correct order.
    *   Only valid if matching = allwords.
    */
   bool m_allWordsCorrectOrder;

   /**
    *   The searchtype of the points.
    */
   uint32 m_searchType;

   /**
    *   The itemType of the points.
    */
   ItemTypes::itemType m_itemType;

   /**
    *   The itemsubtype.
    */
   uint16 m_itemSubType;

};

inline void
SearchMatchPoints::reset()
{
   m_distanceMeters         = MAX_UINT32;
   m_houseNbrDiff           = MAX_INT16;
   m_editDistance           = MAX_UINT16;
   m_stringDiff             = MAX_UINT8;
   m_positionInString       = MAX_UINT8;
   m_matching               = SearchTypes::MaxDefinedMatching;
   m_matchedStringIs        = unknown;
   m_elemPoints             = 0;
   m_correctLocation        = false;
   m_ssiCorrectLocation     = false;
   m_matchesEndOfWord       = false;
   m_matchesBeginningOfWord = false;
   m_allWordsCorrectOrder   = true;
   m_itemType               = ItemTypes::numberOfItemTypes;
   m_itemSubType            = MAX_UINT16;
   m_searchType             = 0;
}

inline
SearchMatchPoints::SearchMatchPoints()
{
   reset();
}

inline void
SearchMatchPoints::setDistanceMeters(uint32 dist)
{
   m_distanceMeters = dist;
}

inline void
SearchMatchPoints::setMatching(SearchTypes::StringMatching m)
{
   m_matching = m;
}

inline void
SearchMatchPoints::setMatchedStringIs(SearchMatchPoints::matchedString_t x)
{
   m_matchedStringIs = x;
}

inline bool
SearchMatchPoints::isFullMatch() const
{
   return m_matchedStringIs == full_close ||
      m_matchedStringIs == full_exact;
}

inline void
SearchMatchPoints::setElemPoints(uint16 elemPoints)
{
   m_elemPoints = elemPoints;
}

inline void
SearchMatchPoints::setCorrectLocation(bool correct)
{
   m_correctLocation = correct;
}

inline void
SearchMatchPoints::setSSICorrectLocation(bool correctRegion)
{
   m_ssiCorrectLocation = correctRegion;
}

inline void
SearchMatchPoints::setAllWordsCorrectOrder(bool correctOrder)
{
   m_allWordsCorrectOrder = correctOrder;
}

inline void
SearchMatchPoints::setHouseNbrDiff(int16 houseDiff)
{
   m_houseNbrDiff = houseDiff;
}

inline void
SearchMatchPoints::setEditDistance(uint16 editDistance)
{
   m_editDistance = editDistance;
}

inline uint16
SearchMatchPoints::getEditDistance() const
{
   return m_editDistance;
}

inline void
SearchMatchPoints::setPositionInString(uint8 pos)
{
   m_positionInString = pos;
}

inline uint8
SearchMatchPoints::getPositionInString() const
{
   return m_positionInString;
}

inline void
SearchMatchPoints::setMatchesEndOfWord(bool doesIt)
{
   m_matchesEndOfWord = doesIt;
}

inline void
SearchMatchPoints::setMatchesBeginningOfWord(bool doesIt)
{
   m_matchesBeginningOfWord = doesIt;
}

inline ostream&
operator<<( ostream& stream,
            const SearchMatchPoints& points)
{
   return
      stream << "( m_matching = "
             << SearchTypes::getMatchingString(points.m_matching) << endl
             << "  m_correctLocation = "
             << BPR(points.m_correctLocation) << endl
             << "  m_correctSSILocation = "
             << BPR(points.m_ssiCorrectLocation) << endl
             << "  m_matchedStringIs = "
             << int(points.m_matchedStringIs) << endl
             << "  m_editDistance = " << points.m_editDistance << endl
             << "  m_houseNbrDiff = " << points.m_houseNbrDiff << endl
             << "  m_elemPoints = " << points.m_elemPoints << endl
             << "  m_positionInString = " << int(points.m_positionInString)
             << endl
             << "  m_matchesBegin = " << BPR(points.m_matchesBeginningOfWord)
             << endl
             << "  m_matchesEnd = " << BPR(points.m_matchesEndOfWord)
             << endl
             << "  m_stringDiff = " << int(points.m_stringDiff)
             << "  m_allWordsCorrectOrder = "
             << BPR(points.m_allWordsCorrectOrder)
             << "  m_searchType = " << hex << points.m_searchType
             << dec << endl
             << "  m_itemType   = "
             << ItemTypes::getItemTypeAsString( points.m_itemType )
             << "  m_itemSubType = " << StringTable::getString(
                ItemTypes::getPOIStringCode(
                   ItemTypes::pointOfInterest_t( points.m_itemSubType ) ),
                StringTable::ENGLISH )
             << " )";

}

// - End of SearchMatchPoints

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.rules.coercer;

import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.filesystems.ForwardRelPath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.coercer.TypeCoercer.Traversal;
import com.facebook.buck.rules.macros.OutputMacro;
import com.google.common.collect.ImmutableList;

/**
 * Handles '$(output ...)' macro.
 *
 * @see com.facebook.buck.rules.macros.OutputMacroExpander
 */
public class OutputMacroTypeCoercer implements MacroTypeCoercer<OutputMacro, OutputMacro> {

  @Override
  public boolean hasElementClass(Class<?>[] types) {
    for (Class<?> type : types) {
      if (type.isAssignableFrom(getOutputClass())) {
        return true;
      }
    }
    return false;
  }

  @Override
  public Class<OutputMacro> getUnconfiguredOutputClass() {
    return OutputMacro.class;
  }

  @Override
  public Class<OutputMacro> getOutputClass() {
    return OutputMacro.class;
  }

  @Override
  public void traverseUnconfigured(
      CellNameResolver cellRoots, OutputMacro macro, Traversal traversal) {
    traversal.traverse(macro);
  }

  @Override
  public void traverse(CellNameResolver cellRoots, OutputMacro macro, Traversal traversal) {
    traversal.traverse(macro);
  }

  @Override
  public OutputMacro coerceToUnconfigured(
      CellNameResolver cellNameResolver,
      ProjectFilesystem filesystem,
      ForwardRelPath pathRelativeToProjectRoot,
      ImmutableList<String> args)
      throws CoerceFailedException {
    if (args.size() != 1 || args.get(0).isEmpty()) {
      throw new CoerceFailedException(
          String.format("expected exactly one argument (found %d)", args.size()));
    }
    return OutputMacro.of(args.get(0));
  }
}


text:
using System;
using YesSql.Filters.Abstractions.Nodes;

namespace OrchardCore.Contents.Services
{
    /// <summary>
    /// Provides a content type node is used when a filter has not been selected
    /// </summary>
    public class ContentTypeFilterNode : TermOperationNode
    {
        public ContentTypeFilterNode(string selectedContentType) : base("type", new UnaryNode(selectedContentType, OperateNodeQuotes.None))
        {
        }

        public override string ToNormalizedString()
            => String.Empty;

        public override string ToString()
            => String.Empty;
    }
}


text:
package controller

import (
	"context"

	"github.com/kyma-project/kyma/common/logging/logger"
	"github.com/kyma-project/kyma/components/application-operator/pkg/apis/applicationconnector/v1alpha1"
	gocache "github.com/patrickmn/go-cache"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

type Controller interface {
	Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error)
	SetupWithManager(mgr ctrl.Manager) error
}

type controller struct {
	cacheSync CacheSync
}

func NewController(log *logger.Logger, client client.Client, appCache *gocache.Cache) Controller {
	return &controller{
		cacheSync: NewCacheSync(log, client, appCache, "cache_sync_controller"),
	}
}

func (c *controller) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
	return ctrl.Result{}, c.cacheSync.Sync(ctx, request.Name)
}

func (c *controller) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&v1alpha1.Application{}).
		Complete(c)
}


text:
layout: "docs"
page_title: "Tips & Tricks - Vagrantfile"
sidebar_current: "vagrantfile-tips"
description: |-
  The Vagrantfile is a very flexible configuration format. Since it is just
  Ruby, there is a lot you can do with it. However, in that same vein, since
  it is Ruby, there are a lot of ways you can shoot yourself in the foot. When
  using some of the tips and tricks on this page, please take care to use them
  correctly.
---

# Tips & Tricks

The Vagrantfile is a very flexible configuration format. Since it is just
Ruby, there is a lot you can do with it. However, in that same vein, since
it is Ruby, there are a lot of ways you can shoot yourself in the foot. When
using some of the tips and tricks on this page, please take care to use them
correctly.

## Loop Over VM Definitions

If you want to apply a slightly different configuration to many
multi-machine machines, you can use a loop to do this. For example, if
you wanted to create three machines:

```ruby
(1..3).each do |i|
  config.vm.define "node-#{i}" do |node|
    node.vm.provision "shell",
      inline: "echo hello from node #{i}"
  end
end
```

~> **Warning:** The inner portion of multi-machine definitions
and provider overrides are lazy-loaded. This can cause issues if you change
the value of a variable used within the configs. For example, the loop below
does not work:

```ruby
# THIS DOES NOT WORK!
for i in 1..3 do
  config.vm.define "node-#{i}" do |node|
    node.vm.provision "shell",
      inline: "echo hello from node #{i}"
  end
end
```

The `for i in  ...` construct in Ruby actually modifies the value of `i`
for each iteration, rather than making a copy. Therefore, when you run this,
every node will actually provision with the same text.

This is an easy mistake to make, and Vagrant cannot really protect against it,
so the best we can do is mention it here.

## Overwrite host locale in ssh session

Usually, host locale environment variables are passed to guest. It may cause
failures if the guest software do not support host locale. One possible solution
is override locale in the `Vagrantfile`:

```ruby
ENV["LC_ALL"] = "en_US.UTF-8"

Vagrant.configure(2) do |config|
  # ...
end
```

The change is only visible within the `Vagrantfile`.


text:
var Nocks = require('../../nocks.js');

module.exports = {
  setUp: function (callback) {
    this.client = require('../../nightwatch.js').init();
    callback();
  },

  'to be [PASSED]' : function(test) {
    Nocks.elementFound().name('input');
    var expect = this.client.api.expect.element('#weblogin').to.be.an('input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, true);
      test.equals(expect.assertion.article, 'an');
      test.equals(expect.assertion.resultValue, 'input');
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 1);
      test.equals(results.failed, 0);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to be an input');
      test.done();
    })
  },

  'to be [FAILED]' : function(test) {
    Nocks.elementFound().name('input');

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'be an input');
      test.equals(expect.assertion.actual, null);
      test.equals(expect.assertion.article, 'an');
      test.equals(expect.assertion.resultValue, null);
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to be an input');
      test.done();
    })
  },

  'to not be [PASSED]' : function(test) {
    Nocks.elementFound().name('input');

    var expect = this.client.api.expect.element('#weblogin').to.not.be.a('div');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.article, 'a');
      test.equals(expect.assertion.negate, true);
      test.equals(expect.assertion.passed, true);
      test.equals(expect.assertion.expected, 'not be a div');
      test.equals(expect.assertion.actual, 'input');
      test.equals(expect.assertion.resultValue, 'input');
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to not be a div');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 1);
      test.equals(results.failed, 0);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to not be a div');
      test.done();
    })
  },

  'to be [FAILED]' : function(test) {
    Nocks.elementFound().name('div');

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'be an input');
      test.equals(expect.assertion.actual, 'div');
      test.equals(expect.assertion.resultValue, 'div');
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to be an input');
      test.done();
    })
  },

  'to not be - element not found' : function(test) {
    Nocks.elementNotFound();

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'present');
      test.equals(expect.assertion.actual, 'not present');
      test.equals(expect.assertion.resultValue, null);
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input - element was not found');
      test.deepEqual(expect.assertion.messageParts, [' - element was not found']);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to be an input - element was not found');
      test.done();
    })
  },

  'to not be - element not found' : function(test) {
    Nocks.elementNotFound();

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'present');
      test.equals(expect.assertion.actual, 'not present');
      test.equals(expect.assertion.resultValue, null);
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input - element was not found');
      test.deepEqual(expect.assertion.messageParts, [' - element was not found']);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'Expected element <#weblogin> to be an input - element was not found');
      test.done();
    })
  },

  'to be with message [PASSED]' : function(test) {
    Nocks.elementFound().name('input');

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input', 'weblogin should be an input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, true);
      test.equals(expect.assertion.article, 'an');
      test.equals(expect.assertion.resultValue, 'input');
      test.equals(expect.assertion.message, 'weblogin should be an input');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 1);
      test.equals(results.failed, 0);
      test.equals(results.tests[0].message, 'weblogin should be an input');
      test.done();
    })
  },

  'to be with message [FAILED]' : function(test) {
    Nocks.elementFound().name('div');

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input', 'weblogin should be an input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'be an input');
      test.equals(expect.assertion.actual, 'div');
      test.equals(expect.assertion.article, 'an');
      test.equals(expect.assertion.resultValue, 'div');
      test.equals(expect.assertion.message, 'weblogin should be an input');
      test.deepEqual(expect.assertion.elementResult, { ELEMENT: '0' });
      test.deepEqual(expect.assertion.messageParts, []);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'weblogin should be an input');
      test.done();
    })
  },

  'to be with message - element not found' : function(test) {
    Nocks.elementNotFound();

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input', 'weblogin should be an input');
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equals(expect.assertion.selector, '#weblogin');
      test.equals(expect.assertion.negate, false);
      test.equals(expect.assertion.waitForMs, null);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.expected, 'present');
      test.equals(expect.assertion.actual, 'not present');
      test.equals(expect.assertion.resultValue, null);
      test.equals(expect.assertion.message, 'weblogin should be an input - element was not found');
      test.deepEqual(expect.assertion.messageParts, [' - element was not found']);
      test.equals(results.passed, 0);
      test.equals(results.failed, 1);
      test.equals(results.tests[0].message, 'weblogin should be an input - element was not found');
      test.done();
    })
  },

  'to be with waitFor - element not found' : function(test) {
    this.client.api.globals.waitForConditionPollInterval = 50;

    Nocks.elementNotFound().elementNotFound().elementNotFound();

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input').before(60);
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equal(expect.assertion.waitForMs, 60);
      test.equals(expect.assertion.passed, false);
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input in 60ms - element was not found');
      test.done();
    })
  },

  'to be with waitFor - element found on retry' : function(test) {
    this.client.api.globals.waitForConditionPollInterval = 50;

    Nocks.elementNotFound().elementFound().name('input');

    var expect = this.client.api.expect.element('#weblogin').to.be.an('input').before(60);
    this.client.on('nightwatch:finished', function(results, errors) {
      test.equal(expect.assertion.waitForMs, 60);
      test.equals(expect.assertion.passed, true);
      test.equals(expect.assertion.message, 'Expected element <#weblogin> to be an input in 60ms - condition was met in ' + expect.assertion.elapsedTime + 'ms');
      test.done();
    })
  },

  tearDown : function(callback) {
    this.client = null;
    // clean up
    callback();
  }
};


text:
<?php

namespace WS\Migrations\Builder\Entity;
use WS\Migrations\Builder\BuilderException;

/**
 * Class FormField
 * @property int id
 * @property int sort
 * @property int formId
 * @property string sid
 * @property string title
 * @property string titleType
 * @property string active
 * @property string additional
 * @property string fieldType
 * @property string required
 * @property string filterTitle
 * @property string inResultsTable
 * @property string inExcelTable
 * @property string resultsTableTitle
 * @property string comments
 * @property array arImage
 * @property array arFilterUser
 * @property array arFilterAnswerText
 * @property array arFilterAnswerValue
 * @property array arFilterField
 * @package WS\Migrations\Builder\Entity
 */
class FormField extends Base {

    const FIELD_TYPE_TEXT = 'text';
    const FIELD_TYPE_INTEGER = 'integer';
    const FIELD_TYPE_DATE = 'date';
    /** @var  FormAnswer[] */
    private $answers;

    public function __construct($sid, $data = array()) {
        $this->sid = $sid;
        $this->answers = array();
        $this->setSaveData($data);
    }

    public function getMap() {
        return array(
            'id' => 'ID',
            'sort' => 'C_SORT',
            'sid' => 'SID',
            'formId' => 'FORM_ID',
            'active' => 'ACTIVE',
            'additional' => 'ADDITIONAL',
            'fieldType' => 'FIELD_TYPE',
            'title' => 'TITLE',
            'titleType' => 'TITLE_TYPE',
            'required' => 'REQUIRED',
            'filterTitle' => 'FILTER_TITLE',
            'inResultsTable' => 'IN_RESULTS_TABLE',
            'inExcelTable' => 'IN_EXCEL_TABLE',
            'resultsTableTitle' => 'RESULTS_TABLE_TITLE',
            'comments' => 'COMMENTS',
            'arImage' => 'arIMAGE',
            'arFilterUser' => 'arFILTER_USER',
            'arFilterAnswerText' => 'arFILTER_ANSWER_TEXT',
            'arFilterAnswerValue' => 'arFILTER_ANSWER_VALUE',
            'arFilterField' => 'arFILTER_FIELD',
        );
    }

    /**
     * @param int $id
     * @return FormField
     */
    public function setId($id) {
        $this->id = $id;
        return $this;
    }

    /**
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @param int $sort
     * @return FormField
     */
    public function setSort($sort) {
        $this->sort = $sort;
        return $this;
    }

    /**
     * @param string $sid
     * @return FormField
     */
    public function setSid($sid) {
        $this->sid = $sid;
        return $this;
    }

    /**
     * @param string $title
     * @return FormField
     */
    public function setTitle($title) {
        $this->title = $title;
        return $this;
    }

    /**
     * @param string $titleType
     * @return FormField
     */
    public function setTitleType($titleType) {
        $this->titleType = $titleType;
        return $this;
    }

    /**
     * @param bool $active
     * @return FormField
     */
    public function setActive($active) {
        $this->active = $active ? 'Y' : 'N';
        return $this;
    }

    /**
     * @return FormField
     */
    public function setAsQuestion() {
        $this->additional = 'N';
        return $this;
    }

    /**
     * @return FormField
     */
    public function setAsField() {
        $this->additional = 'Y';
        return $this;
    }

    /**
     * @param string $fieldType
     * @return FormField
     */
    public function setFieldType($fieldType) {
        $this->fieldType = $fieldType;
        return $this;
    }

    /**
     * @param bool $required
     * @return FormField
     */
    public function setRequired($required) {
        $this->required = $required ? "Y" : "N";
        return $this;
    }

    /**
     * @param string $filterTitle
     * @return FormField
     */
    public function setFilterTitle($filterTitle) {
        $this->filterTitle = $filterTitle;
        return $this;
    }

    /**
     * @param bool $inResultsTable
     * @return FormField
     */
    public function setInResultsTable($inResultsTable) {
        $this->inResultsTable = $inResultsTable ? "Y" : "N";;
        return $this;
    }

    /**
     * @param bool $inExcelTable
     * @return FormField
     */
    public function setInExcelTable($inExcelTable) {
        $this->inExcelTable = $inExcelTable ? "Y" : "N";;
        return $this;
    }

    /**
     * @param string $resultsTableTitle
     * @return FormField
     */
    public function setResultsTableTitle($resultsTableTitle) {
        $this->resultsTableTitle = $resultsTableTitle;
        return $this;
    }

    /**
     * @param string $comments
     * @return FormField
     */
    public function setComments($comments) {
        $this->comments = $comments;
        return $this;
    }

    /**
     * @param array $arImage
     * @return FormField
     */
    public function setArImage($arImage) {
        $this->arImage = $arImage;
        return $this;
    }

    /**
     * @param array $arFilterUser
     * @return FormField
     */
    public function setArFilterUser($arFilterUser) {
        $this->arFilterUser = $arFilterUser;
        return $this;
    }

    /**
     * @param array $arFilterAnswerText
     * @return FormField
     */
    public function setArFilterAnswerText($arFilterAnswerText) {
        $this->arFilterAnswerText = $arFilterAnswerText;
        return $this;
    }

    /**
     * @param array $arFilterAnswerValue
     * @return FormField
     */
    public function setArFilterAnswerValue($arFilterAnswerValue) {
        $this->arFilterAnswerValue = $arFilterAnswerValue;
        return $this;
    }

    /**
     * @param array $arFilterField
     * @return FormField
     */
    public function setArFilterField($arFilterField) {
        $this->arFilterField = $arFilterField;
        return $this;
    }

    /**
     * @param $message
     * @return FormAnswer
     */
    public function addAnswer($message) {
        $answer = new FormAnswer($message);
        $this->answers[] = $answer;
        return $answer;
    }

    /**
     * @param $message
     * @return FormAnswer
     * @throws BuilderException
     */
    public function updateAnswer($message) {
        if (!$this->id) {
            throw new BuilderException("Can't update answer. Form Field not saved");
        }
        $data = $this->findAnswer($message);
        $answer = new FormAnswer($message, $data);
        $this->answers[] = $answer;
        return $answer;
    }

    public function removeAnswer($message) {
        if (!$this->id) {
            throw new BuilderException("Can't remove answer. Form Field not saved");
        }
        $data = $this->findAnswer($message);
        $data['DEL'] = 'Y';
        $answer = new FormAnswer($message, $data);
        $this->answers[] = $answer;
        return $answer;
    }

    private function findAnswer($message) {
        $data = \CFormAnswer::GetList($this->id, $by, $order, array(
            'MESSAGE' => $message
        ), $isFiltered)->Fetch();

        if (empty($data)) {
            throw new BuilderException("Answer '{$message}' not found");
        }
        return $data;
    }

    /**
     * @return FormAnswer[]
     */
    public function getAnswers() {
        return $this->answers;
    }

}


text:
package com.stackexchange.stacman;

import java.util.concurrent.Future;

public final class FilterMethods {
    private StacManClient client;

    FilterMethods(StacManClient client) {
        this.client = client;
    }

    public Future<StacManResponse<Filter>> read(String[] filters, String filter) {
        return read(StacManClient.toIter(filters), filter);
    }

    public Future<StacManResponse<Filter>> read(Iterable<String> filters, String filter)
    {
        client.validateEnumerable(filters, "filters");

        ApiUrlBuilder ub = new ApiUrlBuilder(String.format("/filters/%1$S", StacManClient.join(";", filters)), false);

        ub.addParameter("filter", filter);

        return client.createApiTask(Types.Filter, ub, "/filters/{filters}");
    }

    public Future<StacManResponse<Filter>> create(String filter, String[] include, String[] exclude, String base, Boolean unsafe) {
        return create(filter, StacManClient.toIter(include), StacManClient.toIter(exclude), base, unsafe);
    }

    public Future<StacManResponse<Filter>> create(String filter, Iterable<String> include, Iterable<String> exclude, String base, Boolean unsafe)
    {
        ApiUrlBuilder ub = new ApiUrlBuilder("/filters/create", false);

        ub.addParameter("filter", filter);
        ub.addParameter("include", include);
        ub.addParameter("exclude", exclude);
        ub.addParameter("base", base);
        ub.addParameter("unsafe", unsafe);

        return client.createApiTask(Types.Filter, ub, "/filters/create");
    }
}


text:
#LOreal Likourgos
#IS640 Project

__author__ = "LOreal Likourgos"

import wsgiref.handlers
from google.appengine.api import urlfetch
import webapp2

urlfetch.set_default_fetch_deadline(60)

########## CHANGE THESE TO REFLECT YOUR PERSONAL SETTINGS ##############
# Your Dropbox user-id  and folder-name.
# Your public folder will have the following syntax:
# dl.dropboxusercontent.com/u/<USERID>/<YOURFOLDER>/examplefile
# If you want to use the entire "Public" folder, set DROPBOX_FOLDER = ""
DROPBOX_USERID = "1988gtachick@gmail.com"
DROPBOX_FOLDER = "https://www.dropbox.com/sh/g3xzguwn9rdyu6c/AABK9p4yER5VnRENRkY1HsXTa?dl=0"
########################################################################

class DboxHandler(webapp2.RequestHandler):
  def get(self, url_path):
    slash_position = self.request.url.find("/", len(self.request.scheme + "://"))
    if slash_position == -1:
      dropbox_url = "https://"
    else:
      dropbox_path = "" if DROPBOX_FOLDER == "" else "/" + DROPBOX_FOLDER
      dropbox_url = "https://dl.dropbox.com/u/" + DROPBOX_USERID + dropbox_path + self.request.url[slash_position:]

    fetched = urlfetch.fetch(dropbox_url)

    if fetched.status_code == 200:
      for key, value in fetched.headers.iteritems():
        self.response.headers[key] = value
      self.response.out.write(fetched.content)

    else:
      self.response.status = fetched.status_code
      self.response.out.write("Error: status code:" + str(fetched.status_code))

class IndexPageHandler(webapp2.RequestHandler):
  def get(self, base_url=None):
    #Use HTML code below to conjure link to dropbox
	self.response.out.write("")
	self.response.out.write("
Welcome to Nimbus Store
")
	self.response.out.write("
Click  HERE  to access my files.
")
	self.response.out.write("")

app = webapp2.WSGIApplication([
  (r"/", IndexPageHandler),
  (r"/(.*)", DboxHandler)
], debug=False)

# Base code cited to Arjun Sreedharan


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.Text;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions
{
    using RegexToken = EmbeddedSyntaxToken<RegexKind>;
    using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>;

    public partial class CSharpRegexParserTests
    {
        private readonly IVirtualCharService _service = CSharpVirtualCharService.Instance;
        private const string _statmentPrefix = "var v = ";

        private SyntaxToken GetStringToken(string text)
        {
            var statement = _statmentPrefix + text;
            var parsedStatement = SyntaxFactory.ParseStatement(statement);
            var token = parsedStatement.DescendantTokens().ToArray()[3];
            Assert.True(token.Kind() == SyntaxKind.StringLiteralToken);

            return token;
        }

        private void Test(string stringText, string expected, RegexOptions options,
            bool runSubTreeTests = true, [CallerMemberName]string name = "",
            bool allowIndexOutOfRange = false,
            bool allowNullReference = false,
            bool allowOutOfMemory = false)
        {
            var (tree, sourceText) = TryParseTree(stringText, options, conversionFailureOk: false,
                allowIndexOutOfRange, allowNullReference, allowOutOfMemory);

            // Tests are allowed to not run the subtree tests.  This is because some
            // subtrees can cause the native regex parser to exhibit very bad behavior
            // (like not ever actually finishing compiling).
            if (runSubTreeTests)
            {
                TryParseSubTrees(stringText, options,
                    allowIndexOutOfRange,
                    allowNullReference,
                    allowOutOfMemory);
            }

            var actual = TreeToText(sourceText, tree).Replace("\"", "\"\"");
            Assert.Equal(expected.Replace("\"", "\"\""), actual);
        }

        private void TryParseSubTrees(
            string stringText, RegexOptions options,
            bool allowIndexOutOfRange,
            bool allowNullReference,
            bool allowOutOfMemory)
        {
            // Trim the input from the right and make sure tree invariants hold
            var current = stringText;
            while (current != "@\"\"" && current != "\"\"")
            {
                current = current.Substring(0, current.Length - 2) + "\"";
                TryParseTree(current, options, conversionFailureOk: true,
                    allowIndexOutOfRange,
                    allowNullReference,
                    allowOutOfMemory);
            }

            // Trim the input from the left and make sure tree invariants hold
            current = stringText;
            while (current != "@\"\"" && current != "\"\"")
            {
                if (current[0] == '@')
                {
                    current = "@\"" + current.Substring(3);
                }
                else
                {
                    current = "\"" + current.Substring(2);
                }

                TryParseTree(current, options, conversionFailureOk: true,
                    allowIndexOutOfRange,
                    allowNullReference,
                    allowOutOfMemory);
            }

            for (int start = stringText[0] == '@' ? 2 : 1; start < stringText.Length - 1; start++)
            {
                TryParseTree(
                    stringText.Substring(0, start) +
                    stringText.Substring(start + 1, stringText.Length - (start + 1)),
                    options, conversionFailureOk: true,
                    allowIndexOutOfRange,
                    allowNullReference,
                    allowOutOfMemory);
            }
        }

        private (SyntaxToken, RegexTree, VirtualCharSequence) JustParseTree(
            string stringText, RegexOptions options, bool conversionFailureOk)
        {
            var token = GetStringToken(stringText);
            var allChars = _service.TryConvertToVirtualChars(token);
            if (allChars.IsDefault)
            {
                Assert.True(conversionFailureOk, "Failed to convert text to token.");
                return (token, null, allChars);
            }

            var tree = RegexParser.TryParse(allChars, options);
            return (token, tree, allChars);
        }

        private (RegexTree, SourceText) TryParseTree(
            string stringText, RegexOptions options,
            bool conversionFailureOk,
            bool allowIndexOutOfRange,
            bool allowNullReference,
            bool allowOutOfMemeory)
        {
            var (token, tree, allChars) = JustParseTree(stringText, options, conversionFailureOk);
            if (tree == null)
            {
                Assert.True(allChars.IsDefault);
                return default;
            }

            CheckInvariants(tree, allChars);
            var sourceText = token.SyntaxTree.GetText();
            var treeAndText = (tree, sourceText);

            Regex regex = null;
            try
            {
                regex = new Regex(token.ValueText, options);
            }
            catch (IndexOutOfRangeException) when (allowIndexOutOfRange)
            {
                // bug with .NET regex parser.  Can happen with patterns like: (?<-0
                Assert.NotEmpty(tree.Diagnostics);
                return treeAndText;
            }
            catch (NullReferenceException) when (allowNullReference)
            {
                // bug with .NET regex parser.  can happen with patterns like: (?(?S))
                return treeAndText;
            }
            catch (OutOfMemoryException) when (allowOutOfMemeory)
            {
                // bug with .NET regex parser.  can happen with patterns like: a{2147483647,}
                return treeAndText;
            }
            catch (ArgumentException ex)
            {
                Assert.NotEmpty(tree.Diagnostics);

                // Ensure the diagnostic we emit is the same as the .NET one. Note: we can only
                // do this in en-US as that's the only culture where we control the text exactly
                // and can ensure it exactly matches Regex.  We depend on localization to do a
                // good enough job here for other languages.
                if (Thread.CurrentThread.CurrentCulture.Name == "en-US")
                {
                    Assert.True(tree.Diagnostics.Any(d => ex.Message.Contains(d.Message)));
                }

                return treeAndText;
            }

            Assert.Empty(tree.Diagnostics);

            Assert.True(regex.GetGroupNumbers().OrderBy(v => v).SequenceEqual(
                tree.CaptureNumbersToSpan.Keys.OrderBy(v => v)));

            Assert.True(regex.GetGroupNames().Where(v => !int.TryParse(v, out _)).OrderBy(v => v).SequenceEqual(
                tree.CaptureNamesToSpan.Keys.OrderBy(v => v)));

            return treeAndText;
        }

        private string TreeToText(SourceText text, RegexTree tree)
        {
            var element = new XElement("Tree",
                NodeToElement(tree.Root));

            if (tree.Diagnostics.Length > 0)
            {
                element.Add(new XElement("Diagnostics",
                    tree.Diagnostics.Select(d =>
                        new XElement("Diagnostic",
                            new XAttribute("Message", d.Message),
                            new XAttribute("Span", d.Span),
                            GetTextAttribute(text, d.Span)))));
            }

            element.Add(new XElement("Captures",
                tree.CaptureNumbersToSpan.OrderBy(kvp => kvp.Key).Select(kvp =>
                    new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value))),
                tree.CaptureNamesToSpan.OrderBy(kvp => kvp.Key).Select(kvp =>
                    new XElement("Capture", new XAttribute("Name", kvp.Key), new XAttribute("Span", kvp.Value), GetTextAttribute(text, kvp.Value)))));

            return element.ToString();
        }

        private static XAttribute GetTextAttribute(SourceText text, TextSpan span)
            => new XAttribute("Text", text.ToString(span));

        private XElement NodeToElement(RegexNode node)
        {
            var element = new XElement(node.Kind.ToString());
            foreach (var child in node)
            {
                element.Add(child.IsNode ? NodeToElement(child.Node) : TokenToElement(child.Token));
            }

            return element;
        }

        private XElement TokenToElement(RegexToken token)
        {
            var element = new XElement(token.Kind.ToString());

            if (token.Value != null)
            {
                element.Add(new XAttribute("value", token.Value));
            }

            if (token.LeadingTrivia.Length > 0)
            {
                element.Add(new XElement("Trivia", token.LeadingTrivia.Select(t => TriviaToElement(t))));
            }

            if (token.VirtualChars.Length > 0)
            {
                element.Add(token.VirtualChars.CreateString());
            }

            return element;
        }

        private XElement TriviaToElement(RegexTrivia trivia)
            => new XElement(
                trivia.Kind.ToString(),
                trivia.VirtualChars.CreateString());

        private void CheckInvariants(RegexTree tree, VirtualCharSequence allChars)
        {
            var root = tree.Root;
            var position = 0;
            CheckInvariants(root, ref position, allChars);
            Assert.Equal(allChars.Length, position);
        }

        private void CheckInvariants(RegexNode node, ref int position, VirtualCharSequence allChars)
        {
            foreach (var child in node)
            {
                if (child.IsNode)
                {
                    CheckInvariants(child.Node, ref position, allChars);
                }
                else
                {
                    CheckInvariants(child.Token, ref position, allChars);
                }
            }
        }

        private void CheckInvariants(RegexToken token, ref int position, VirtualCharSequence allChars)
        {
            CheckInvariants(token.LeadingTrivia, ref position, allChars);
            CheckCharacters(token.VirtualChars, ref position, allChars);
        }

        private void CheckInvariants(ImmutableArray<RegexTrivia> leadingTrivia, ref int position, VirtualCharSequence allChars)
        {
            foreach (var trivia in leadingTrivia)
            {
                CheckInvariants(trivia, ref position, allChars);
            }
        }

        private void CheckInvariants(RegexTrivia trivia, ref int position, VirtualCharSequence allChars)
        {
            switch (trivia.Kind)
            {
                case RegexKind.CommentTrivia:
                case RegexKind.WhitespaceTrivia:
                    break;
                default:
                    Assert.False(true, "Incorrect trivia kind");
                    return;
            }

            CheckCharacters(trivia.VirtualChars, ref position, allChars);
        }

        private static void CheckCharacters(VirtualCharSequence virtualChars, ref int position, VirtualCharSequence allChars)
        {
            for (var i = 0; i < virtualChars.Length; i++)
            {
                Assert.Equal(allChars[position + i], virtualChars[i]);
            }

            position += virtualChars.Length;
        }

        [Fact]
        public void TestDeepRecursion()
        {
            var (token, tree, chars) =
                JustParseTree(
@"@""((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((""", RegexOptions.None, conversionFailureOk: false);
            Assert.False(token.IsMissing);
            Assert.False(chars.IsDefaultOrEmpty);
            Assert.Null(tree);
        }
    }
}


text:
package main

import (
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/ci-pipeline/cloudformation-resource/utils"
	"github.com/concourse/atc"
)

func main() {
	utils.Logln("Change to build directory")
	utils.GoToBuildDirectory()
	cwd, _ := os.Getwd()
	utils.Logln(cwd)
	input := utils.GetInput()
	svc := utils.GetCloudformationService(input)
	metadata, success, version := out(input, svc)
	result := utils.VersionResult{Metadata: metadata, Version: atc.Version{"sha1": version}}
	output, _ := json.Marshal(result)
	fmt.Printf("%s", string(output))
	if !success {
		os.Exit(1)
	}
}

type Parameter struct {
	ParameterValue   string
	ParameterKey     string
	UsePreviousValue bool
}

type Tag struct {
	TagKey   string
	TagValue string
}

type ApiInputs struct {
	Capabilities         []*string
	CloudformationParams []*cloudformation.Parameter
	TemplateBody         string
	CloudformationTags   []*cloudformation.Tag
}

func stackExists(svc *cloudformation.CloudFormation, stackName string) bool {
	params := &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	}
	resp, err := svc.DescribeStacks(params)
	if err != nil {
		return false
	}
	utils.Logln(resp)

	return resp.Stacks[0] != nil
}

func waitForStack(svc *cloudformation.CloudFormation, input utils.Input) (success bool, arn, timestamp string) {
	success = true
	params := &cloudformation.DescribeStackEventsInput{
		StackName: aws.String(input.Source.Name),
	}

	pos := 0
	var stackEvents []*cloudformation.StackEvent
	for {
		resp, err := svc.DescribeStackEvents(params)
		if err != nil {
			if input.Params.Delete {
				success = true
				utils.Logln("Stack deleted")
				return
			}
			utils.Logf("An error occured: %v\n", err)
			return
		}
		stackEvents = resp.StackEvents
		for j := len(stackEvents) - 1 - pos; j > -1; j-- {
			utils.Logln(stackEvents[j])
		}
		pos = len(stackEvents)

		arn = *stackEvents[0].StackId
		timestamp = stackEvents[0].Timestamp.String()

		if *stackEvents[0].ResourceType == "AWS::CloudFormation::Stack" {
			if *stackEvents[0].ResourceStatus == "CREATE_COMPLETE" {
				return
			} else if *stackEvents[0].ResourceStatus == "UPDATE_COMPLETE" {
				return
			} else if *stackEvents[0].ResourceStatus == "ROLLBACK_COMPLETE" {
				success = false
				return
			} else if *stackEvents[0].ResourceStatus == "UPDATE_ROLLBACK_COMPLETE" {
				success = false
				return
			} else if strings.HasSuffix(*stackEvents[0].ResourceStatus, "_FAILED") {
				success = false
				return
			}
		}

		time.Sleep(500 * time.Millisecond)
	}
}

func createChangeSet(input utils.Input, svc *cloudformation.CloudFormation, apiInputs ApiInputs) error {
	utils.Logln("Create Change Set")
	var changeSetType string
	if stackExists(svc, input.Source.Name) {
		utils.Logln("ChangeSetTypeUpdate")
		changeSetType = cloudformation.ChangeSetTypeUpdate
	} else {
		utils.Logln("ChangeSetTypeCreate")
		changeSetType = cloudformation.ChangeSetTypeCreate
	}
	changeSetName := "concourse-" + time.Now().Format("20060102150405")
	utils.Logln("Change Set Name: " + changeSetName)
	resp, err := svc.CreateChangeSet(&cloudformation.CreateChangeSetInput{
		Capabilities:  apiInputs.Capabilities,
		ChangeSetName: aws.String(changeSetName),
		ChangeSetType: aws.String(changeSetType),
		Description:   aws.String("Changeset created by concourse"),
		Parameters:    apiInputs.CloudformationParams,
		StackName:     aws.String(input.Source.Name),
		Tags:          apiInputs.CloudformationTags,
		TemplateBody:  aws.String(apiInputs.TemplateBody),
	})
	if err != nil {
		utils.Logln(fmt.Sprintf("Failed to create change set: %v\n", err))
		return err
	}
	utils.Logln(resp)

	describeChangeSetInput := &cloudformation.DescribeChangeSetInput{
		ChangeSetName: aws.String(changeSetName),
		StackName:     aws.String(input.Source.Name),
	}
	err = svc.WaitUntilChangeSetCreateComplete(describeChangeSetInput)
	if err != nil {
		utils.Logln("Failed to wait for change set create to complete")
		if awsErr, ok := err.(awserr.Error); ok {
			utils.Logln(awsErr.Code())
			utils.Logln(awsErr.Error())
			utils.Logln(awsErr.Message())
			if awsErr.Code() == "ResourceNotReady" {
				describeChangeSetOutput, err := svc.DescribeChangeSet(describeChangeSetInput)
				if err != nil {
					return err
				}

				if *describeChangeSetOutput.Status == cloudformation.ChangeSetStatusFailed {
					utils.Logln("Deleting change set because the status is failed")
					_, err := svc.DeleteChangeSet(&cloudformation.DeleteChangeSetInput{
						ChangeSetName: aws.String(changeSetName),
						StackName:     aws.String(input.Source.Name),
					})
					if err != nil {
						utils.Logln("Failed to delete change set")
						return err
					}
				}
			}
		}
		return err
	}

	return nil
}

func executeChangeSet(input utils.Input, svc *cloudformation.CloudFormation, apiInputs ApiInputs) error {
	changeSets, err := svc.ListChangeSets(&cloudformation.ListChangeSetsInput{
		StackName: aws.String(input.Source.Name),
	})
	if err != nil {
		return err
	}
	if len(changeSets.Summaries) != 1 {
		return errors.New("There must only be 1 changeset associated with a stack to execute")
	}
	resp, err := svc.ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
		StackName:     aws.String(input.Source.Name),
		ChangeSetName: changeSets.Summaries[0].ChangeSetName,
	})
	if err != nil {
		return err
	}
	utils.Logln(resp)
	return nil
}

func createStack(input utils.Input, svc *cloudformation.CloudFormation, apiInputs ApiInputs) error {
	utils.Logln("Creating stack")
	params := &cloudformation.CreateStackInput{
		StackName:    aws.String(input.Source.Name),
		Capabilities: apiInputs.Capabilities,
		Parameters:   apiInputs.CloudformationParams,
		Tags:         apiInputs.CloudformationTags,
		TemplateBody: aws.String(apiInputs.TemplateBody),
	}
	resp, err := svc.CreateStack(params)
	if err != nil {
		utils.Logln(err.Error())
	}
	utils.Logln(resp)
	return nil
}

func updateStack(input utils.Input, svc *cloudformation.CloudFormation, apiInputs ApiInputs) error {
	utils.Logln("Updating stack")
	params := &cloudformation.UpdateStackInput{
		StackName:    aws.String(input.Source.Name),
		Capabilities: apiInputs.Capabilities,
		Parameters:   apiInputs.CloudformationParams,
		Tags:         apiInputs.CloudformationTags,
		TemplateBody: aws.String(apiInputs.TemplateBody),
	}
	_, err := svc.UpdateStack(params)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == "ValidationError" && awsErr.Message() == "No updates are to be performed." {
				utils.Logln("No updates to be performed")
				return nil
			} else {
				return errors.New(fmt.Sprintf("An AWS error occured whilst updating stack: %v", err))
			}
		} else {
			return errors.New(fmt.Sprintf("An error occured whilst updating stack: %v", err))
		}
	}
	return nil
}
func deleteStack(input utils.Input, svc *cloudformation.CloudFormation, apiInputs ApiInputs) error {
	utils.Logln("Deleting stack")
	resp, err := svc.DeleteStack(&cloudformation.DeleteStackInput{
		StackName: aws.String(input.Source.Name),
	})
	if err != nil {
		return err
	}
	utils.Logln(resp)
	return nil
}

func out(input utils.Input, svc *cloudformation.CloudFormation) (metadata []atc.MetadataField, success bool, sha string) {

	var apiInputs ApiInputs

	apiInputs.Capabilities = nil
	if input.Params.Capabilities != nil {
		for _, c := range input.Params.Capabilities {
			apiInputs.Capabilities = append(apiInputs.Capabilities, aws.String(c))
		}
	}

	if input.Params.Template != "" {
		bytes, err := ioutil.ReadFile(input.Params.Template)
		if err != nil {
			panic(err)
		}
		apiInputs.TemplateBody = string(bytes)
	}

	parameters := []Parameter{}
	if input.Params.Parameters != "" {
		bytes, err := ioutil.ReadFile(input.Params.Parameters)
		err = json.Unmarshal(bytes, &parameters)
		if err != nil {
			utils.Logln("Could not unmarshal parameters file, path = ", input.Params.Parameters)
			utils.Logln("contents:")
			utils.Logln(string(bytes))
			utils.Logln("error: ", err)
			os.Exit(1)
		}
	}
	for _, p := range parameters {
		param := cloudformation.Parameter{
			ParameterKey:     aws.String(p.ParameterKey),
			ParameterValue:   aws.String(p.ParameterValue),
			UsePreviousValue: aws.Bool(p.UsePreviousValue),
		}
		apiInputs.CloudformationParams = append(apiInputs.CloudformationParams, &param)
	}

	tags := []Tag{}
	if input.Params.Tags != "" {
		bytes, err := ioutil.ReadFile(input.Params.Tags)
		err = json.Unmarshal(bytes, &tags)
		if err != nil {
			panic(err)
		}
	}
	for _, t := range tags {
		tag := cloudformation.Tag{
			Key:   aws.String(t.TagKey),
			Value: aws.String(t.TagValue),
		}
		apiInputs.CloudformationTags = append(apiInputs.CloudformationTags, &tag)
	}

	if input.Params.Delete == true {
		err := deleteStack(input, svc, apiInputs)
		if err != nil {
			utils.Logln("Could not delete stack: ", err)
		}
	} else if input.ChangesetCreate() || input.ChangesetExecute() {
		if input.ChangesetCreate() {
			err := createChangeSet(input, svc, apiInputs)
			if err != nil {
				utils.Logln("Could not create Change Set: ", err)
			}
		}
		if input.ChangesetExecute() {
			err := executeChangeSet(input, svc, apiInputs)
			if err != nil {
				utils.Logln("Could not execute Change Set: ", err)
			}
		}
	} else {
		if !stackExists(svc, input.Source.Name) {
			err := createStack(input, svc, apiInputs)
			if err != nil {
				utils.Logln("Could not create stack: ", err)
			}
		} else {
			err := updateStack(input, svc, apiInputs)
			if err != nil {
				utils.Logln("Could not update stack: ", err)
			}
		}
	}

	success, arn, timestamp := waitForStack(svc, input)
	result := make([]atc.MetadataField, 2)
	result[0].Name = "arn"
	result[0].Value = arn
	result[1].Name = "timestamp"
	result[1].Value = timestamp

	// SHA1 template, parameters and tags and use as version
	hasher := sha1.New()
	hasher.Write([]byte(fmt.Sprintf("%s%v%v", apiInputs.TemplateBody, parameters, tags)))
	sha = base64.URLEncoding.EncodeToString(hasher.Sum(nil))
	return result, success, sha
}


text:
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;

namespace Com.Loonytone.Droid.PullToRefresh
{

	/// <summary>
	/// Created by zwenkai on 2015/12/19.
	/// </summary>
	public abstract class LoadingLayoutBase : FrameLayout, ILoadingLayout
	{
		public abstract string ReleaseLabel {set;}
		public abstract string RefreshingLabel {set;}
		public abstract string PullLabel {set;}

		public LoadingLayoutBase(Context context) : base(context)
		{
		}

		public LoadingLayoutBase(Context context, IAttributeSet attrs) : base(context, attrs)
		{
		}

		public LoadingLayoutBase(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
		{
		}

		public void SetHeight(int value)
		{
            ViewGroup.LayoutParams lp = LayoutParameters;
            lp.Height = value;
            RequestLayout();
        }

		public void  SetWidth(int value)
		{
            ViewGroup.LayoutParams lp = LayoutParameters;
            lp.Width = value;
            RequestLayout();
        }

		public virtual string LastUpdatedLabel
		{
			set
			{

			}
		}

		public virtual Drawable LoadingDrawable
		{
			set
			{

			}
		}

		public virtual Typeface TextTypeface
		{
			set
			{

			}
		}

		/// <summary>
		/// get the LoadingLayout height or width
		/// </summary>
		/// <returns> size </returns>
		public abstract int ContentSize {get;}

		/// <summary>
		/// Call when the widget begins to slide
		/// </summary>
		public abstract void pullToRefresh();

		/// <summary>
		/// Call when the LoadingLayout is fully displayed
		/// </summary>
		public abstract void releaseToRefresh();

		/// <summary>
		/// Call when the LoadingLayout is sliding
		/// </summary>
		/// <param name="scaleOfLayout"> scaleOfLayout </param>
		public abstract void onPull(float scaleOfLayout);

		/// <summary>
		/// Call when the LoadingLayout is fully displayed and the widget has released.
		/// Used to prompt the user loading data
		/// </summary>
		public abstract void refreshing();

		/// <summary>
		/// Call when the data has loaded
		/// </summary>
		public abstract void reset();

		public virtual void hideAllViews()
		{
			hideAllViews(this);
		}

		public virtual void showInvisibleViews()
		{
			showAllViews(this);
		}

		private void hideAllViews(View view)
		{
			if (view is ViewGroup)
			{
				for (int i = 0; i < ((ViewGroup)view).ChildCount; i++)
				{
					hideAllViews(((ViewGroup)view).GetChildAt(i));
				}
			}
			else
			{
				if (ViewStates.Visible == view.Visibility)
				{
					view.Visibility = ViewStates.Invisible;
				}
			}
		}

		private void showAllViews(View view)
		{
			if (view is ViewGroup)
			{
				for (int i = 0; i < ((ViewGroup)view).ChildCount; i++)
				{
					showAllViews(((ViewGroup) view).GetChildAt(i));
				}
			}
			else
			{
				if (ViewStates.Invisible == view.Visibility)
				{
					view.Visibility = ViewStates.Visible;
				}
			}
		}

	}

}


text:
"""Tests for tfx.utils.dependency_utils."""

import os
import sys
from unittest import mock

from absl import logging
from absl.testing import parameterized
import tensorflow as tf
from tfx.dsl.io import fileio
from tfx.utils import dependency_utils

class DependencyUtilsTest(tf.test.TestCase, parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self._tmp_dir = os.path.join(
        os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()),
        self._testMethodName)

  @mock.patch('tfx.utils.dependency_utils.build_ephemeral_package')
  def testMakeBeamDependencyFlags(self, mock_build_ephemeral_package):
    mock_build_ephemeral_package.return_value = 'mock_file'
    beam_flags = dependency_utils.make_beam_dependency_flags(
        beam_pipeline_args=[])
    self.assertListEqual(['--extra_package=mock_file'], beam_flags)
    mock_build_ephemeral_package.assert_called_with()

  # TODO(zhitaoli): Add check on 'sdk_container_image' once supported version of
  #                 Beam converges.
  @parameterized.named_parameters(
      ('ExtraPackages', '--extra_packages=foo'),
      ('SetupFile', '--setup_file=foo'),
      ('RequirementsFile', '--requirements_file=foo'),
  )
  def testNoActionOnFlag(self, flag_value):
    beam_pipeline_args = [flag_value]
    self.assertListEqual(
        [flag_value],
        dependency_utils.make_beam_dependency_flags(beam_pipeline_args),
    )

  @mock.patch('tempfile.mkdtemp')
  def testEphemeralPackage(self, mock_mkdtemp):
    mock_mkdtemp.return_value = self._tmp_dir
    if os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR'):
      # This test requires setuptools which is not available.
      logging.info('Skipping testEphemeralPackage')
      return
    package = dependency_utils.build_ephemeral_package()
    self.assertRegex(os.path.basename(package), r'tfx_ephemeral-.*\.tar.gz')

  @mock.patch('tempfile.mkdtemp')
  @mock.patch('subprocess.call')
  def testEphemeralPackageMocked(self, mock_subprocess_call, mock_mkdtemp):
    source_data_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'testdata')
    test_file = os.path.join(source_data_dir, 'test.csv')
    expected_package = 'mypackage.tar.gz'

    def side_effect(cmd, stdout, stderr):
      self.assertLen(cmd, 3)
      self.assertEqual(sys.executable, cmd[0])
      self.assertEqual('sdist', cmd[2])
      self.assertEqual(stdout, stderr)
      setup_file = cmd[1]
      dist_dir = os.path.join(os.path.dirname(setup_file), 'dist')
      fileio.makedirs(dist_dir)
      dest_file = os.path.join(dist_dir, expected_package)
      fileio.copy(test_file, dest_file)

    mock_subprocess_call.side_effect = side_effect
    mock_mkdtemp.return_value = self._tmp_dir
    package = dependency_utils.build_ephemeral_package()
    self.assertEqual(expected_package, os.path.basename(package))

if __name__ == '__main__':
  tf.test.main()


text:
layout: post
title: "Server and a Movie"
date: 2014-01-03T21:57:49-08:00
comments: false
categories: [ movies]
---

After a couple hours of fun messing with [ansible](http://www.ansibleworks.com/) and [node](http://nodejs.org/) deployments, I
think the rest of Friday night would be better spent watching
[Grave of the Fireflies](http://en.wikipedia.org/wiki/Grave_of_the_Fireflies).

According to [reviews](http://www.imdb.com/title/tt0095327/reviews?ref_=tt_ov_rt), I should
be a wreck in 90 minutes.

**Update:** yeah, it was depressing.

![Poster](http://upload.wikimedia.org/wikipedia/en/a/a5/Grave_of_the_Fireflies_Japanese_poster.jpg)


text:
#include "string_obj.h"

// The default constructor
CStrObj::CStrObj()
{
	// Initialize the pointer to NULL
	mStr = NULL;
}

// Copy constuctor
CStrObj::CStrObj(const CStrObj &strObj)
{
	/*
		What's going on here?  Nothing to special.  In general, the functionality of
		the copy constructor and assignment operator are the same.  So instead of
		typing the same code for both methods, we just call the assignment operator
		from the copy constructor.
	*/
	*this = strObj;

	// **NOTE**	This implementation is shown only as an alternative that you may see
	//			in different code examples.  An equivalent implementation is:
	//
	//			CStrObj::CStrObj(const CStrObj &strObj)
	//			{
	//				set(strObj.mStr);
	//			}
}

// Assignment operator
CStrObj& CStrObj::operator =(const CStrObj &strObj)
{
	set(strObj.mStr);
		return *this;
}

// Sets the string object
void CStrObj::set(const char *str)
{
	// First we need to get the length (minus the NULL character) of the
	// string we want to set
	unsigned int len = strlen(str); // Get length of "str"

	// If "mStr" is NULL, we need to allocate an appropriate length string
	if(!mStr)
	{
		// Allocate the string
		// The "+1" is for the NULL character at the end of the string
		mStr = new char[len + 1];
	}
	else // Otherwise "mStr" is already allocated.  We need to check if it's big
	{	 // enough to hold "str"

		// If "mStr" is smaller than or the same size as "str"
		if(strlen(mStr) <= len)
		{
			delete[] mStr; // Free up "mStr"

			mStr = new char[len + 1]; // Allocate a large enough string
									  // Remember the "+1" is for the NULL terminating character
		}
	}

	// Copy over the string
	strcpy(mStr, str);
}

// Print the string object
void CStrObj::print(int numBlnakLines)
{
	cout << mStr; // Print the string

	// Print "numBlankLines" after printing the string
	for(int i = 0; i < numBlnakLines; ++i)
		cout << endl;
};

// The deconstructor.  It is responsible for freeing up any dynamic
// memory allocated by the class
CStrObj::~CStrObj()
{
	// If "mStr" is not NULL, it must point to dynamic memory we
	// allocated and thus needs to be deleted
	if(mStr)
	{
		delete[] mStr; // Delete the memory
		mStr = NULL; // This is a good software development habit to get into.
					// ALWAYS set pointers to NULL, after you free the memory they point to.
	}

	// We print out this message to help visualize when destructors get called
	// in a program.
	cout << "Destructor called" << endl;
}


text:
package com.amazonaws.services.autoscaling.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * PredictiveScalingPredefinedScalingMetric StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PredictiveScalingPredefinedScalingMetricStaxUnmarshaller implements
        Unmarshaller<PredictiveScalingPredefinedScalingMetric, StaxUnmarshallerContext> {

    public PredictiveScalingPredefinedScalingMetric unmarshall(StaxUnmarshallerContext context) throws Exception {
        PredictiveScalingPredefinedScalingMetric predictiveScalingPredefinedScalingMetric = new PredictiveScalingPredefinedScalingMetric();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return predictiveScalingPredefinedScalingMetric;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("PredefinedMetricType", targetDepth)) {
                    predictiveScalingPredefinedScalingMetric.setPredefinedMetricType(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("ResourceLabel", targetDepth)) {
                    predictiveScalingPredefinedScalingMetric.setResourceLabel(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return predictiveScalingPredefinedScalingMetric;
                }
            }
        }
    }

    private static PredictiveScalingPredefinedScalingMetricStaxUnmarshaller instance;

    public static PredictiveScalingPredefinedScalingMetricStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new PredictiveScalingPredefinedScalingMetricStaxUnmarshaller();
        return instance;
    }
}


text:
import commands
import logging
import os

class xCamera(object):

    def __init__(self, photoname="photo.jpeg"):
        self.directorycurrent = os.path.dirname(os.path.realpath(__file__))
        self.directoryfiles = self.directorycurrent + '/files/'
        self.picturefswebcam = self.directoryfiles + photoname

    def __del__(self):
        pass

    def filepath(self):
        return self.picturefswebcam

    def setup(self):
        self.fswebcam = 'fswebcam'
        self.fswebcamarguments = ' '
        #self.fswebcamarguments = ' -r 1280x720 -s brightness=65% -s Contrast=50% -s Gamma=100% --jpeg 100 --no-banner '
        self.fswebcamcommand = self.fswebcam + self.fswebcamarguments + self.picturefswebcam

    def capture(self):

        self.setup()
        status, output = commands.getstatusoutput(self.fswebcamcommand)

def takePhoto():

        idCamera = xCamera()
        idCamera.capture()

if __name__ == "__main__":

        idCamera = xCamera()
        idCamera.capture()

# End of File


text:
set -e

readonly THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly THIS_FILE="$THIS_DIR/$(basename "${BASH_SOURCE[0]}")"

artifactsDir="$THIS_DIR/artifacts"

if [ -d artifactsDir ]; then
  rm -R artifactsDir
fi

build_number=${TRAVIS_BUILD_NUMBER:=1}

dotnet restore --verbosity normal /property:BuildNumber=$build_number

dotnet build --configuration Release --verbosity normal /property:BuildNumber=$build_number

dotnet pack --configuration Release --output "$artifactsDir" --no-build --verbosity normal /property:BuildNumber=$build_number


text:
JayPS Search
======

A very simple search engine for Novius OS, based on Behaviours.

Licensed under [MIT License](http://opensource.org/licenses/MIT)

Current version: 1.2

**Get started**

* Configure which models will be searchable in your bootstrap.php (see below).
 For examples, see [JayPS Search Test](https://github.com/jay3/jayps_search_test)
* Add new items or save existing ones
* Start searching using find('all', array('where' => array(array('keywords', 'keyword1 keyword2'))))

**Example with Nos\Page and Nos\Monkey**
[Nos\Monkey](https://github.com/novius-os/noviusos_monkey)

Configure which models will be searchable for example in your bootstrap.php:
```php
    \Event::register_function('config|jayps_search::config', function(&$config) {
        $config['observed_models']['noviusos_monkey::model/monkey'] = array(
            'primary_key' => 'monk_id',
            'config_behaviour' => array(
                'fields' => array('monk_name', 'monk_summary', 'wysiwygs->content'),
            ),
        );

        $config['observed_models']['noviusos_page::model/page'] = array(
            'primary_key' => 'page_id',
            'config_behaviour' => array(
                'fields' => array('page_title', 'wysiwygs->content', 'page_meta_title', 'page_meta_description', 'page_meta_keywords'),
            ),
        );

        $config['observed_models']['noviusos_news::model/post'] = array(
            'primary_key' => 'post_id',
            'config_behaviour' => array(
                'fields' => array('post_title', 'wysiwygs->content'),
            ),
        );
    });

    \JayPS\Search\Orm_Behaviour_Searchable::init();
    \Event::register_function('front.start', function() {
        // add models you want to use in your search and that are used in your template before your search enhancer
        // for example: noviusos_page::model/page

        //\JayPS\Search\Orm_Behaviour_Searchable::init_relations('noviusos_page::model/page');
        //\JayPS\Search\Orm_Behaviour_Searchable::init_relations('noviusos_news::model/post');

        \JayPS\Search\Orm_Behaviour_Searchable::init_relations();
    });
```

The config of the behaviour and the app can define score improvement as follow :

```php
    $config['observed_models']['noviusos_monkey::model/monkey'] = array(
        'primary_key' => 'monk_id',
        'config_behaviour' => array(
            'fields' => array(
                'monk_name', // as this is the title, general config already defines a boost
                'monk_summary' => 1, //
                'wysiwygs->content' => array(
                    'boost' => 0, // changes nothing, default value is 0
                    'is_html' => true // will remove html markup.
                )
            ),
        ),
    );
    $config['observed_models']['noviusos_news::model/post'] = array(
        'primary_key' => 'post_id',
        'config_behaviour' => array(
            'fields' => array(
                'post_title' => 2, // override general boost
                'wysiwygs->content' => array(
                    'boost' => 1 // gives a score for all words in the content, regardless of their nature
                    'is_html' => array(
                        'h1' => 1 // provides another boost for words un h1 markup
                    )
                )
            ),
        ),
    );
```

To use the search with find(), simply provide an array of keywords. '*' acts as a joker at the end.
```php
    \JayPS\Search\Orm_Behaviour_Searchable::init_relations();

    $pages = \Nos\Page\Model_Page::find('all', array(
        'where' => array(
            array('keywords', 'chimpa* monkey'),
            'page_published' => 1,
            'page_context'   => \Nos\Nos::main_controller()->getPage()->page_context,
        ),
        'rows_limit' => 10,
        'order_by' => array('jayps_search_score', 'page_title'),
    ));

    $news = \Nos\BlogNews\News\Model_Post::find('all', array(
        'where' => array(
            array('keywords', 'chimpa* monkey'),
            'post_published' => 1,
            'post_context'   => \Nos\Nos::main_controller()->getPage()->page_context,
        ),
        'rows_limit' => 10,
        'order_by'   => array('jayps_search_score', 'post_title'),
    ));

    $monkeys = \Nos\Monkey\Model_Monkey::find('all', array(
        'where' => array(
            array('keywords', 'chimpa* monkey'),
            'monk_published' => 1,
            'monk_context'   => \Nos\Nos::main_controller()->getPage()->page_context,
        ),
        'rows_limit' => 200,
        'order_by' => array('jayps_search_score', 'monk_name'),
    ));
```
You can also restrict search to specific fields:
```php
    $pages = \Nos\Page\Model_Page::find('all', array(
        'where' => array(
            'keywords_fields' => array(
                'page_title'                    => 'keyword1 keyword2', // keyword1 and keyword2 must appear in title
                'wysiwygs->content'             => 'keyword3',          // keyword3 must appear in description
                '*'                             => 'keyword4',          // keyword4 must appear anywhere
                'page_title|wysiwygs->content'  => 'keyword5',          // keyword5 must appear in title OR description
            ),
        ),
    ));
```


text:
// Copyright © 2011-12 Qtrac Ltd.
//
// This program or package and any associated files are licensed under the
// Apache License, Version 2.0 (the "License"); you may not use these files
// except in compliance with the License. You can get a copy of the License
// at: http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
//    "bytes"
    "encoding/gob"
    "errors"
    "fmt"
    "io"
//    "time"
)
/*
type GobInvoice struct {
    Id           int
    CustomerId   int
    DepartmentId string
    Raised       int64
    Due          int64
    Paid         bool
    Note         string
    Items        []*Item
}

func (invoice *Invoice) GobEncode() ([]byte, error) {
    gobInvoice := GobInvoice{
        invoice.Id,
        invoice.CustomerId,
        invoice.DepartmentId,
        invoice.Raised.Unix(),
        invoice.Due.Unix(),
        invoice.Paid,
        invoice.Note,
        invoice.Items,
    }
    var buffer bytes.Buffer
    encoder := gob.NewEncoder(&buffer)
    err := encoder.Encode(gobInvoice)
    return buffer.Bytes(), err
}

func (invoice *Invoice) GobDecode(data []byte) error {
    var gobInvoice GobInvoice
    buffer := bytes.NewBuffer(data)
    decoder := gob.NewDecoder(buffer)
    if err := decoder.Decode(&gobInvoice); err != nil {
        return err
    }
    raised := time.Unix(gobInvoice.Raised, 0)
    due := time.Unix(gobInvoice.Due, 0)
    *invoice = Invoice{
        gobInvoice.Id,
        gobInvoice.CustomerId,
        gobInvoice.DepartmentId,
        raised,
        due,
        gobInvoice.Paid,
        gobInvoice.Note,
        gobInvoice.Items,
    }
    return nil
}
*/
type GobMarshaler struct{}

func (GobMarshaler) MarshalInvoices(writer io.Writer,
    invoices []*Invoice) error {
    encoder := gob.NewEncoder(writer)
    if err := encoder.Encode(magicNumber); err != nil {
        return err
    }
    if err := encoder.Encode(fileVersion); err != nil {
        return err
    }
    return encoder.Encode(invoices)
}

func (GobMarshaler) UnmarshalInvoices(reader io.Reader) ([]*Invoice,
    error) {
    decoder := gob.NewDecoder(reader)
    var magic int
    if err := decoder.Decode(&magic); err != nil {
        return nil, err
    }
    if magic != magicNumber {
        return nil, errors.New("cannot read non-invoices gob file")
    }
    var version int
    if err := decoder.Decode(&version); err != nil {
        return nil, err
    }
    if version > fileVersion {
        return nil, fmt.Errorf("version %d is too new to read", version)
    }
    var invoices []*Invoice
    if err := decoder.Decode(&invoices); err != nil {
        return nil, err
    }
    if version < fileVersion {
        if err := update(invoices); err != nil {
            return nil, err
        }
    }
    return invoices, nil
}


text:
import querystring from 'querystring';

var events = {
  'route:start': function(ctx) {
    var fullUrl = ctx.path;
    var query = querystring.stringify(ctx.query);

    if (query) {
      fullUrl += '?' + query;
    }

    if (global && global.ga) {
      ga('set', 'page', fullUrl);
      ga('send', 'pageview');

      var loggedIn = !!window.bootstrap.user;

      var compactCookieValue = document.cookie.match(/\bcompact=(\w+)\b/);
      var compact = !!(compactCookieValue &&
                      compactCookieValue.length > 1 &&
                      compactCookieValue[1] === 'true');

      var compactTestCookieValue = document.cookie.match(/\bcompactTest=(\w+)\b/);
      var compactTest = compactTestCookieValue ? compactTestCookieValue[1] : 'undefined';

      ga('set', 'dimension2', loggedIn.toString());
      ga('set', 'dimension3', compact.toString());
      ga('set', 'dimension4', compactTest.toString());
    }
  },

  'compactToggle': function (compact) {
    ga('send', 'event', 'compactToggle', compact.toString());
    ga('set', 'dimension3', compact.toString());
  },

  'vote': function (vote) {
    ga('send', 'event', 'vote', vote.get('direction'));
  },

  'comment': function (comment) {
    ga('send', 'event', 'comment', 'words', comment.get('text').match(/\S+/g).length);
  },

  'comment:edit': function() {
    ga('send', 'event', 'comment', 'edit');
  },

  'search': function (query) {
    ga('send', 'event', 'search');
  },

  'goto': function (query) {
    ga('send', 'event', 'goto', query);
  },

  'report': function (query) {
    ga('send', 'event', 'report');
  },

  'post:submit': function(subreddit) {
    ga('send', 'event', 'post', 'submit', subreddit);
  },

  'post:edit': function() {
    ga('send', 'event', 'post', 'edit');
  },

  'post:selectSubreddit': function(subreddit) {
    ga('send', 'event', 'post', 'selectSubreddit', subreddit);
  },

  'post:error': function() {
    ga('send', 'event', 'post', 'captcha');
  },

  'message:submit': function() {
    ga('send', 'event', 'messages', 'submit');
  },

  'message:reply': function(message) {
    ga('send', 'event', 'messages', 'reply', message.get('text').match(/\S+/g).length);
  }
};

function trackingEvents(app) {
  for (var e in events) {
    app.on(e, events[e]);
  }
}

export default trackingEvents;