text:
package org.apache.tinkerpop.gremlin.process.traversal;

import org.apache.tinkerpop.gremlin.process.traversal.strategy.TraversalStrategyProxy;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.util.function.Lambda;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiFunction;

/**
 * A Translator will translate {@link Bytecode} into another representation. That representation may be a
 * Java instance via {@link StepTranslator} or a String script in some language via {@link ScriptTranslator}.
 * The parameterization of Translator is S (traversal source) and T (full translation).
 *
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 * @author Stark Arya (sandszhou.zj@alibaba-inc.com)
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public interface Translator<S, T> {

    /**
     * Get the {@link TraversalSource} representation rooting this translator.
     * For string-based translators ({@link ScriptTranslator}), this is typically a "g".
     * For java-based translators ({@link StepTranslator}), this is typically the {@link TraversalSource} instance
     * which the {@link Traversal} will be built from.
     *
     * @return the traversal source representation
     */
    public S getTraversalSource();

    /**
     * Translate {@link Bytecode} into a new representation. Typically, for language translations, the translation is
     * to a string representing the traversal in the respective scripting language.
     *
     * @param bytecode the bytecode representing traversal source and traversal manipulations.
     * @return the translated object
     */
    public T translate(final Bytecode bytecode);

    /**
     * Translates a {@link Traversal} into the specified form
     */
    public default T translate(final Traversal<?,?> t) {
        return translate(t.asAdmin().getBytecode());
    }

    /**
     * Get the language that the translator is converting the traversal byte code to.
     *
     * @return the language of the translation
     */
    public String getTargetLanguage();

    ///

    /**
     * Translates bytecode to a Script representation.
     */
    public interface ScriptTranslator extends Translator<String, Script> {

        /**
         * Provides a way for the {@link ScriptTranslator} to convert various data types to their string
         * representations in their target language.
         */
        public interface TypeTranslator extends BiFunction<String, Object, Script> { }

        public abstract class AbstractTypeTranslator implements ScriptTranslator.TypeTranslator {
            protected static final String ANONYMOUS_TRAVERSAL_PREFIX = "__";
            protected final boolean withParameters;
            protected final Script script;

            protected AbstractTypeTranslator(final boolean withParameters) {
                this.withParameters = withParameters;
                this.script = new Script();
            }

            @Override
            public Script apply(final String traversalSource, final Object o) {
                this.script.init();
                if (o instanceof Bytecode) {
                    return produceScript(traversalSource, (Bytecode) o);
                } else {
                    return convertToScript(o);
                }
            }

            /**
             * Gets the syntax for the spawn of an anonymous traversal which is traditionally the double underscore.
             */
            protected String getAnonymousTraversalPrefix() {
                return ANONYMOUS_TRAVERSAL_PREFIX;
            }

            /**
             * Gets the syntax for a {@code null} value as a string representation.
             */
            protected abstract String getNullSyntax();

            /**
             * Take the string argument and convert it to a string representation in the target language (i.e. escape,
             * enclose in appropriate quotes, etc.)
             */
            protected abstract String getSyntax(final String o);

            /**
             * Take the boolean argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final Boolean o);

            /**
             * Take the {@code Date} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final Date o);

            /**
             * Take the {@code Timestamp} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final Timestamp o);

            /**
             * Take the {@code UUID} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final UUID o);

            /**
             * Take the {@link Lambda} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final Lambda o);

            /**
             * Take the {@link SackFunctions.Barrier} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final SackFunctions.Barrier o);

            /**
             * Take the {@link VertexProperty.Cardinality} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final VertexProperty.Cardinality o);

            /**
             * Take the {@link Pick} argument and convert it to a string representation in the target language.
             */
            protected abstract String getSyntax(final Pick o);

            /**
             * Take the numeric argument and convert it to a string representation in the target language. Languages
             * that can discern differences in types of numbers will wish to further check the type of the
             * {@code Number} instance itself (i.e. {@code Double}, {@code Integer}, etc.)
             */
            protected abstract String getSyntax(final Number o);

            /**
             * Take the {@code Set} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Set<?> o);

            /**
             * Take the {@code List} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final List<?> o);

            /**
             * Take the {@code Map} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Map<?,?> o);

            /**
             * Take the {@code Class} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Class<?> o);

            /**
             * Take the {@code Enum} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Enum<?> o);

            /**
             * Take the {@link Vertex} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Vertex o);

            /**
             * Take the {@link Edge} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final Edge o);

            /**
             * Take the {@link VertexProperty} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final VertexProperty<?> o);

            /**
             * Take the {@link TraversalStrategyProxy} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final TraversalStrategyProxy<?> o);

            /**
             * Take the {@link Bytecode} and writes the syntax directly to the member {@link #script} variable.
             */
            protected abstract Script produceScript(final String traversalSource, final Bytecode o);

            /**
             * Take the {@link P} and writes the syntax directly to the member {@link #script} variable. This
             * implementation should also consider {@link TextP}.
             */
            protected abstract Script produceScript(final P<?> p);

            /**
             *  For each operator argument, if withParameters set true, try parametrization as follows:
             *
             *  -----------------------------------------------
             *  if unpack, why ?      ObjectType
             *  -----------------------------------------------
             *  (Yes)                 Bytecode.Binding
             *  (Recursion, No)       Bytecode
             *  (Recursion, No)       Traversal
             *  (Yes)                 String
             *  (Recursion, No)       Set
             *  (Recursion, No)       List
             *  (Recursion, No)       Map
             *  (Yes)                 Long
             *  (Yes)                 Double
             *  (Yes)                 Float
             *  (Yes)                 Integer
             *  (Yes)                 Timestamp
             *  (Yes)                 Date
             *  (Yes)                 Uuid
             *  (Recursion, No)       P
             *  (Enumeration, No)     SackFunctions.Barrier
             *  (Enumeration, No)     VertexProperty.Cardinality
             *  (Enumeration, No)     TraversalOptionParent.Pick
             *  (Enumeration, No)     Enum
             *  (Recursion, No)       Vertex
             *  (Recursion, No)       Edge
             *  (Recursion, No)       VertexProperty
             *  (Yes)                 Lambda
             *  (Recursion, No)       TraversalStrategyProxy
             *  (Enumeration, No)     TraversalStrategy
             *  (Yes)                 Other
             *  -------------------------------------------------
             *
             * @param object
             * @return String Repres
             */
            protected Script convertToScript(final Object object) {
                if (object instanceof Bytecode.Binding) {
                    return script.getBoundKeyOrAssign(withParameters, ((Bytecode.Binding) object).variable());
                } else if (object instanceof Bytecode) {
                    return produceScript(getAnonymousTraversalPrefix(), (Bytecode) object);
                } else if (object instanceof Traversal) {
                    return convertToScript(((Traversal) object).asAdmin().getBytecode());
                } else if (object instanceof String) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((String) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof Boolean) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((Boolean) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof Set) {
                    return produceScript((Set<?>) object);
                } else if (object instanceof List) {
                    return produceScript((List<?>) object);
                } else if (object instanceof Map) {
                    return produceScript((Map<?, ?>) object);
                } else if (object instanceof Number) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((Number) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof Class) {
                    return produceScript((Class<?>) object);
                } else if (object instanceof Timestamp) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((Timestamp) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof Date) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((Date) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof UUID) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((UUID) object);
                    return script.getBoundKeyOrAssign(withParameters, objectOrWrapper);
                } else if (object instanceof P) {
                    return produceScript((P<?>) object);
                } else if (object instanceof SackFunctions.Barrier) {
                    return script.append(getSyntax((SackFunctions.Barrier) object));
                } else if (object instanceof VertexProperty.Cardinality) {
                    return script.append(getSyntax((VertexProperty.Cardinality) object));
                } else if (object instanceof Pick) {
                    return script.append(getSyntax((Pick) object));
                } else if (object instanceof Enum) {
                    return produceScript((Enum<?>) object);
                } else if (object instanceof Vertex) {
                    return produceScript((Vertex) object);
                } else if (object instanceof Edge) {
                    return produceScript((Edge) object);
                } else if (object instanceof VertexProperty) {
                    return produceScript((VertexProperty<?>) object);
                } else if (object instanceof Lambda) {
                    final Object objectOrWrapper = withParameters ? object : getSyntax((Lambda) object);
                    return script.getBoundKeyOrAssign(withParameters,objectOrWrapper);
                } else if (object instanceof TraversalStrategyProxy) {
                    return produceScript((TraversalStrategyProxy<?>) object);
                } else if (object instanceof TraversalStrategy) {
                    return convertToScript(new TraversalStrategyProxy(((TraversalStrategy) object)));
                } else {
                    return null == object ? script.append(getNullSyntax()) : script.getBoundKeyOrAssign(withParameters, object);
                }
            }
        }
    }

    /**
     * Translates bytecode to actual steps.
     */
    public interface StepTranslator<S extends TraversalSource, T extends Traversal.Admin<?, ?>> extends Translator<S, T> {

    }
}


text:
ActiveRecord::Schema.define(version: 20140908031503) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "games", force: true do |t|
    t.integer  "score"
    t.integer  "scrabble_score"
    t.integer  "level"
    t.integer  "lines"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  create_table "users", force: true do |t|
    t.string   "username"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.boolean  "guest"
  end

end

redpajama_set_name: RedPajamaGithub


text:
This repository contains resources and some examples for Bloomington Code School mentoring sessions.

## Resources

Based on the Treehouse Front-End Web Development track, I laid out a [schedule](Syllabus.md) for this session. Additionally, you may find the following resources helpful.

### Websites

Websites for learning and reference.

- [Treehouse](https://teamtreehouse.com/gateways/monroe_county/signin)
- [CSS Tricks](http://css-tricks.com)
- [Mozilla Developer Center](https://developer.mozilla.org/)
- [CSS Color Chart](http://ainsleywagon.github.io/color-chart/)

Websites for sketching with code:

- [CodePen](http://codepen.io)
- [JSFiddle](http://jsfiddle.net)

Taking things further
- [Interactive Data Visualization for the Web](http://chimera.labs.oreilly.com/books/1230000000345)
- [24 Ways blog](http://24ways.org)


text:
var expect = require('chai').expect
var td = require('testdouble')
var proxyquire = require('proxyquire')
var BoshRunner = require('../src/bosh_runner')
var BoshioClient = require('../src/boshio_client')
var TestBot = require('../src/test_bot')
var Assets = require('../src/assets')
var UpgradeChecker = require('../src/upgrade/checker')
var UpgradeApplier = require('../src/upgrade/applier')
var UpgradeConvo = require('../src/upgrade/convo')
var DeployConvo = require('../src/deploy/convo')
var Personality = require('../src/personality')

describe('BoshBot', function () {
  var testController
  var alice
  var fakeRunner
  var fakeBoshio
  var fakeUpgradeChecker
  var fakeUpgradeApplier
  var fakeUpgradeConvo
  var fakeDeployConvo
  var fakeAssets
  var boshConfig

  beforeEach(function () {
    testController = TestBot()
    testController.spawn()

    testController.addEventTrigger('direct_mention', function (message) {
      if (message.text.includes('@bot')) {
        message.text = message.text
          .replace('@bot', '')
          .replace(/^\s+/, '')
          .replace(/^:\s+/, '')
          .replace(/^\s+/, '')
        return message
      }
      return null
    })
    testController.addEventTrigger('ambient', function (message) {
      return message
    })

    alice = testController.createUser({
      user: 'alice'
    })

    fakeRunner = td.object(BoshRunner())
    fakeBoshio = td.object(BoshioClient())
    fakeAssets = td.object(Assets())
    fakeUpgradeChecker = td.object(UpgradeChecker({}))
    fakeUpgradeApplier = td.object(UpgradeApplier({}))
    fakeUpgradeConvo = td.object(UpgradeConvo({}))
    fakeDeployConvo = td.object(DeployConvo({}))

    boshConfig = {
      env: 'https://my-bosh.com',
      user: 'admin',
      password: 'fake-password',
      upgrade_interval: 30 * 60 * 1000,
      stemcells: [
        {
          boshio_id: 'newer-stemcell'
        },
        {
          boshio_id: 'older-stemcell'
        }
      ],
      releases: [
        {
          name: 'new',
          boshio_id: 'newer-release'
        },
        {
          name: 'old',
          boshio_id: 'older-release'
        }
      ],
      assets: [
        {
          name: 'concourse',
          type: 'git',
          uri: 'https://fake-repo.git'
        },
        {
          name: 'unused',
          type: 'git',
          uri: 'https://fake-unused.git'
        }
      ],
      deployments: [
        {
          name: 'concourse',
          manifest_path: 'fake-manifest.yml',
          assets: ['concourse']
        }
      ],
      authorizedUserIDs: [
        'alice'
      ]
    }
  })

  afterEach(function () {
    td.reset()
  })

  function spawnBot () {
    var personality = Personality('captain_bucky')
    var err = personality.loadSync()
    expect(err).to.be.null

    var BoshBot = proxyquire('../src/bosh_bot', {
      './bosh_runner': function (runnerConfig) {
        expect(runnerConfig.env).to.eql('https://my-bosh.com')
        expect(runnerConfig.user).to.eql('admin')
        expect(runnerConfig.password).to.eql('fake-password')
        return fakeRunner
      },
      './boshio_client': function () {
        return fakeBoshio
      },
      './assets': function (config) {
        expect(config.dir).to.eql('/tmp')
        return fakeAssets
      },
      './upgrade/checker': function (config) {
        expect(config.boshRunner).to.eql(fakeRunner)
        expect(config.boshioClient).to.eql(fakeBoshio)
        expect(config.stemcells).to.eql(boshConfig.stemcells)
        expect(config.releases).to.eql(boshConfig.releases)
        return fakeUpgradeChecker
      },
      './upgrade/applier': function (config) {
        expect(config).to.eql({
          boshRunner: fakeRunner
        })
        return fakeUpgradeApplier
      },
      './upgrade/convo': function (config) {
        expect(config.checker).to.eql(fakeUpgradeChecker)
        expect(config.applier).to.eql(fakeUpgradeApplier)
        expect(config.notificationChannel).to.eql('general')
        expect(config.interval).to.eql(30 * 60 * 1000)
        expect(config.personality).to.eql(personality)
        return fakeUpgradeConvo
      },
      './deploy/convo': function (config) {
        expect(config.deployments).to.eql(boshConfig.deployments)
        expect(config.assets).to.eql(boshConfig.assets)
        expect(config.assetsFetcher).to.eql(fakeAssets)
        expect(config.runner).to.eql(fakeRunner)
        expect(config.personality).to.eql(personality)
        return fakeDeployConvo
      }
    })

    td.when(fakeAssets.fetchAll(boshConfig.assets))
      .thenCallback(null)

    var bot = BoshBot(boshConfig)
    var setupOpts = {
      controller: testController,
      notificationChannel: 'general',
      personality: personality
    }
    bot.setup(setupOpts, function () {})
  }

  describe('greetings', function () {
    it('says hi back', function () {
      spawnBot()

      alice.say('@bot hello')
      expect(testController.response()).to.eql('<@alice> Hello yourself.')
    })

    it('replies with pong', function () {
      spawnBot()

      alice.say('@bot ping')
      expect(testController.response()).to.eql('<@alice> pong')
    })

    it('responses on unsupported input', function () {
      spawnBot()

      alice.say('@bot foo')
      expect(testController.response()).to.eql('<@alice> Sorry, didn\'t catch that...')
    })
  })

  describe('env', function () {
    it('responds with the configured environment URL', function () {
      spawnBot()

      alice.say('@bot env')
      expect(testController.response()).to.eql('<@alice> Currently targeting *https://my-bosh.com*.')
    })
  })

  it('adds the deploy convos', function () {
    spawnBot()

    td.verify(fakeDeployConvo.addListeners(testController))
  })

  it('adds the upgrade convos', function () {
    spawnBot()

    td.verify(fakeUpgradeConvo.addListeners(testController))
  })
})


text:
import Circle from '../../../../src/ol/geom/Circle.js';
import Feature from '../../../../src/ol/Feature.js';
import LineString from '../../../../src/ol/geom/LineString.js';
import Map from '../../../../src/ol/Map.js';
import Polygon from '../../../../src/ol/geom/Polygon.js';
import Stroke from '../../../../src/ol/style/Stroke.js';
import Style from '../../../../src/ol/style/Style.js';
import VectorImageLayer from '../../../../src/ol/layer/VectorImage.js';
import VectorSource from '../../../../src/ol/source/Vector.js';
import View from '../../../../src/ol/View.js';

const center = [1825927.7316762917, 6143091.089223046];

const source1 = new VectorSource();
const source2 = new VectorSource();
const vectorLayer1 = new VectorImageLayer({
  source: source1,
  style: new Style({
    stroke: new Stroke({
      color: '#3399CC',
      width: 1.25,
    }),
  }),
});
const vectorLayer2 = new VectorImageLayer({
  source: source2,
  opacity: 0.6,
});

function addCircle(r, source) {
  source.addFeature(new Feature(new Circle(center, r)));
}

function addPolygon(r, source) {
  source.addFeature(
    new Feature(
      new Polygon([
        [
          [center[0] - r, center[1] - r],
          [center[0] + r, center[1] - r],
          [center[0] + r, center[1] + r],
          [center[0] - r, center[1] + r],
          [center[0] - r, center[1] - r],
        ],
      ])
    )
  );
}

const smallLine = new Feature(
  new LineString([
    [center[0], center[1] - 1],
    [center[0], center[1] + 1],
  ])
);
smallLine.setStyle(
  new Style({
    zIndex: -99,
    stroke: new Stroke({width: 75, color: 'red'}),
  })
);
smallLine.getGeometry().translate(-1000, 1000);
source1.addFeature(smallLine);
addPolygon(100, source1);
addCircle(200, source1);
addPolygon(250, source1);
addCircle(500, source1);
addPolygon(600, source1);
addPolygon(720, source1);

const smallLine2 = new Feature(
  new LineString([
    [center[0], center[1] - 1000],
    [center[0], center[1] + 1000],
  ])
);
smallLine2.setStyle([
  new Style({
    stroke: new Stroke({width: 35, color: 'blue'}),
  }),
  new Style({
    stroke: new Stroke({width: 15, color: 'green'}),
  }),
]);
smallLine2.getGeometry().translate(1000, 1000);
source1.addFeature(smallLine2);

const smallLine3 = new Feature(
  new LineString([
    [center[0], center[1] - 1],
    [center[0], center[1] + 1],
  ])
);
smallLine3.setStyle([
  new Style({
    stroke: new Stroke({width: 75, color: 'red'}),
  }),
  new Style({
    stroke: new Stroke({width: 45, color: 'white'}),
  }),
]);
smallLine3.getGeometry().translate(-1000, -1000);

addPolygon(400, source2);
addCircle(1000, source2);
source2.addFeature(smallLine3);

const map = new Map({
  layers: [vectorLayer1, vectorLayer2],
  target: 'map',
  view: new View({
    center: center,
    zoom: 13,
  }),
});

map.getView().setRotation(Math.PI + Math.PI / 4);

render({tolerance: 0.005});


text:
#wrapper {
  width: 90%; /* percentages, em, rem, are better RESPONSIVE */
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#logo {
  background-image: url(http://www.freeliquidtemplates.com/free-headers-for-websites/header11.jpg);
  font-size: 1em;
  width: 25%;
  padding: 5% 0 5% 0;
  float: left;
}

#nav1 {
  background-image: url(http://screenrant.com/wp-content/uploads/star-wars-episode-7-image.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  width: 13%;
  padding: 5% 0 5% 0;
  margin: 2% 2% 2% 11%;
}

#nav2 {
  background-image: url(http://screenrant.com/wp-content/uploads/star-wars-episode-7-image.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  width: 13%;
  padding: 5% 0 5% 0;
  margin: 2% 2% 2% 2%;
}

#nav3 {
  background-image: url(http://screenrant.com/wp-content/uploads/star-wars-episode-7-image.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  width: 13%;
  padding: 5% 0 5% 0;
  margin: 2% 2% 2% 2%;
}

#nav4 {
  background-image: url(http://screenrant.com/wp-content/uploads/star-wars-episode-7-image.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  width: 13%;
  padding: 5% 0 5% 0;
  margin: 2% 0 2% 2%;
}

#primary {
  background-image: url(http://screenrant.com/wp-content/uploads/star-wars-episode-7-image.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  clear: both;
  float: left;
  width: 100%;
  padding: 55% 0 0 0;
  margin: 0 auto;
}

#secondary-left {
  background-image: url(http://cdn.playbuzz.com/cdn/ab04513b-810f-40ef-81a4-f9a8352af4a9/81d6ef6f-617a-4028-8460-23426d2a7e0f.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  text-align: left;
  width: 23%;
  padding: 10% 0 10% 0;
  margin: 0 5% 2% 5%;
}

#secondary-center {
  background-image: url(http://cdn.playbuzz.com/cdn/ab04513b-810f-40ef-81a4-f9a8352af4a9/81d6ef6f-617a-4028-8460-23426d2a7e0f.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  text-align: left;
  width: 23%;
  padding: 10% 0 10% 0;
  margin: 0 5% 2% 5%;
}

#secondary-right {
  background-image: url(http://cdn.playbuzz.com/cdn/ab04513b-810f-40ef-81a4-f9a8352af4a9/81d6ef6f-617a-4028-8460-23426d2a7e0f.jpg);
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  float: left;
  text-align: left;
  width: 23%;
  padding: 10% 0 10% 0;
  margin: 0 5% 2% 5%;
}

#legal {
  background-image: url(http://www.freeliquidtemplates.com/free-headers-for-websites/header11.jpg);
  clear: both;
  font-size: 1.25em;
  font-style: italic;
  padding: 1.5em;

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
    internal partial class ContainedLanguage
    {
        private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
        private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService;
        private readonly Guid _languageServiceGuid;

        protected readonly Workspace Workspace;
        protected readonly IComponentModel ComponentModel;

        public VisualStudioProject? Project { get; }

        protected readonly ContainedDocument ContainedDocument;

        public IVsTextBufferCoordinator BufferCoordinator { get; protected set; }

        /// <summary>
        /// The subject (secondary) buffer that contains the C# or VB code.
        /// </summary>
        public ITextBuffer SubjectBuffer { get; }

        /// <summary>
        /// The underlying buffer that contains C# or VB code. NOTE: This is NOT the "document" buffer
        /// that is saved to disk.  Instead it is the view that the user sees.  The normal buffer graph
        /// in Venus includes 4 buffers:
        /// <code>
        ///            SurfaceBuffer/Databuffer (projection)
        ///             /                               |
        /// Subject Buffer (C#/VB projection)           |
        ///             |                               |
        /// Inert (generated) C#/VB Buffer         Document (aspx) buffer
        /// </code>
        /// In normal circumstance, the Subject and Inert C# buffer are identical in content, and the
        /// Surface and Document are also identical.  The Subject Buffer is the one that is part of the
        /// workspace, that most language operations deal with.  The surface buffer is the one that the
        /// view is created over, and the Document buffer is the one that is saved to disk.
        /// </summary>
        public ITextBuffer DataBuffer { get; }

        // Set when a TextViewFIlter is set.  We hold onto this to keep our TagSource objects alive even if Venus
        // disconnects the subject buffer from the view temporarily (which they do frequently).  Otherwise, we have to
        // re-compute all of the tag data when they re-connect it, and this causes issues like classification
        // flickering.
        private readonly ITagAggregator<ITag> _bufferTagAggregator;

        [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject? project,
            IVsHierarchy hierarchy,
            uint itemid,
            VisualStudioProjectTracker? projectTrackerOpt,
            ProjectId projectId,
            Guid languageServiceGuid,
            AbstractFormattingRule? vbHelperFormattingRule = null)
            : this(bufferCoordinator,
                   componentModel,
                   projectTrackerOpt?.Workspace ?? componentModel.GetService<VisualStudioWorkspace>(),
                   projectId,
                   project,
                   GetFilePathFromHierarchyAndItemId(hierarchy, itemid),
                   languageServiceGuid,
                   vbHelperFormattingRule)
        {
        }

        public static string GetFilePathFromHierarchyAndItemId(IVsHierarchy hierarchy, uint itemid)
        {
            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath!))
                {
                    FatalError.ReportAndPropagate(new InvalidOperationException("Failed to get document moniker for a contained document"));
                }
            }

            return filePath;
        }

        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            Workspace workspace,
            ProjectId projectId,
            VisualStudioProject? project,
            string filePath,
            Guid languageServiceGuid,
            AbstractFormattingRule? vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel = componentModel;
            this.Project = project;
            _languageServiceGuid = languageServiceGuid;

            this.Workspace = workspace;

            _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService = componentModel.GetService<IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines)!;

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines)!;

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService<IBufferTagAggregatorFactoryService>();
            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator<ITag>(SubjectBuffer);

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(), filePath,
                    sourceCodeKind: SourceCodeKind.Regular, folders: default,
                    designTimeOnly: true,
                    documentServiceProvider: new ContainedDocument.DocumentServiceProvider(DataBuffer));
            }
            else
            {
                documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}");

                // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded
                Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath));
                Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer());
            }

            this.ContainedDocument = new ContainedDocument(
                componentModel.GetService<IThreadingContext>(),
                documentId,
                subjectBuffer: SubjectBuffer,
                dataBuffer: DataBuffer,
                bufferCoordinator,
                this.Workspace,
                project,
                componentModel,
                vbHelperFormattingRule);

            // TODO: Can contained documents be linked or shared?
            this.DataBuffer.Changed += OnDataBufferChanged;
        }

        private void OnDisconnect()
        {
            this.DataBuffer.Changed -= OnDataBufferChanged;

            if (this.Project != null)
            {
                this.Project.RemoveSourceTextContainer(SubjectBuffer.AsTextContainer());
            }
            else
            {
                // It's possible the host of the workspace might have already removed the entire project
                if (Workspace.CurrentSolution.ContainsDocument(ContainedDocument.Id))
                {
                    Workspace.OnDocumentRemoved(ContainedDocument.Id);
                }
            }

            this.ContainedDocument.Dispose();

            if (_bufferTagAggregator != null)
            {
                _bufferTagAggregator.Dispose();
            }
        }

        private void OnDataBufferChanged(object sender, TextContentChangedEventArgs e)
        {
            // we don't actually care what has changed in primary buffer. we just want to re-analyze secondary buffer
            // when primary buffer has changed to update diagnostic positions.
            _diagnosticAnalyzerService.Reanalyze(this.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(this.ContainedDocument.Id));
        }
    }
}


text:
from flask import request
from src import app
from src.model.user import ForumUser
from src.config.constants import DEFAULT_PER_PAGE
import math
import json
import datetime

def validate_user_object(decodedUser, action):
    # Validate user received data
    errors = []

    # Mandatory Fields
    if action == "insert":
        mandatory = ['firstName', 'email', 'login', 'password', 'source']
    else:
        mandatory = ['login']

    # Loop for each field
    for field in mandatory:
        if field not in decodedUser:
            errors.append("Field "+field+" is missing")
        else:
            if decodedUser[field] == "":
                errors.append("Field "+field+" is empty")

    if 'email' in mandatory:
        # If there are no errors, validate email
        if len(errors) == 0:
            # Verify if email is unique for this user
            email_exists = len(ForumUser.query(
                ForumUser.email == decodedUser['email'],
                ForumUser.login != decodedUser['login'] # If other user has this email
            ).fetch(1))

            if email_exists == 1:
                errors.append("E-mail already taken")

    # Only validates login when inserting
    if action == "insert":
        # If there are no errors, validate login
        if len(errors) == 0:
            # Verify if email is unique
            login_exists = len(ForumUser.query(ForumUser.login == decodedUser['login']).fetch(1))

            if login_exists == 1:
                errors.append("Login already taken")

    # Validates password
    if 'password' in decodedUser:
        if len(decodedUser['password']) < 6:
            errors.append("Password length must be greater than or equal 6")

    return errors

@app.route('/api/v1/users', methods=['GET', 'POST'])
def users():
    # If its creating an user
    if request.method == 'POST':
        # @todo Validate session

        # User object
        decodedUser = json.loads(request.form['body'])

        # Validates the received user
        errors = validate_user_object(decodedUser, "insert")

        if len(errors) == 0:
            # Instantiate the new User
            user = ForumUser(
                firstname = decodedUser['firstName'],
                lastname = decodedUser['lastName'],
                email = decodedUser['email'],
                login = decodedUser['login'],
                password = decodedUser['password'],
                source = decodedUser['source'],
                num_messages = 0
            )

            # Saves the user
            user.put()

            return json.dumps(user.to_json())
        else:
            return json.dumps({"code":"200", "response":"error", "errors" : errors})
    else:
        # Parameter
        per_page = DEFAULT_PER_PAGE
        page = request.args.get('page')

        if page == None:
            page = 1

        begin =  (page - 1) * per_page
        end = begin + per_page

        # List of Users
        query = ForumUser.query()

        # Order by created at descending
        list_users = query.order(-ForumUser.created_at).fetch(per_page, offset=begin)

        # Total of users
        total = query.count()
        total_pages = int(math.ceil(total / per_page) + 1)

        # Adjust pagination
        if end > total:
            end = total

        # Json to be returned
        json_list = []

        # Adds each user at json list
        for user in list_users:
            json_list.append(user.to_json())

        # Return json object
        return json.dumps({
            "code":200,
            "response":"success",
            "resource":"users",
            "pagination" : {
                "total" : total,
                "page" : page,
                "pages" : total_pages,
                "perPage" : per_page,
                "begin" : begin,
                "end" : end
            },
            "records" : json_list
        })

@app.route('/api/v1/users/<id>', methods=['GET', 'PUT', 'DELETE'])
def user(id):

    # Validate the ID
    try:
        id = int(id)
    except ValueError:
        return json.dumps({"code":200, "response":"error", "message": "Invalid ID"})

    """
        Return an user from its id
    """
    if request.method == 'GET':
        # @todo - Validate session

        # List of Users
        user = ForumUser.get_by_id(id)

        # If find the user..
        if user != None:
            return json.dumps(user.to_json())
        else:
            return json.dumps({"code": 200, "response":"error", "message" : "User not found"})

    elif request.method == 'PUT':
        """
            Updates an user by its id
        """

        # @todo - Validate session
        decodedUser = json.loads(request.form['body'])

        # Validates the received user
        errors = validate_user_object(decodedUser, "update")

        if len(errors) == 0:
            # List of Users
            user = ForumUser.get_by_id(id)

            # If found user
            if user != None:
                # User that needs to be updated

                for attr in decodedUser:
                    if attr == "firstName":
                        setattr(user, "firstname", decodedUser[attr])

                    elif attr == "lastName":
                        setattr(user, "lastname", decodedUser[attr])

                    elif attr == "numMessages":
                        setattr(user, "num_messages", decodedUser[attr])

                    elif attr == "createdAt" or attr == "updatedAt":
                        continue
                    else:
                        setattr(user, attr, decodedUser[attr])

                user.updated_at = datetime.datetime.now()
                user.put()

                # Usuario recebido
                return json.dumps(user.to_json())
            else:
                return json.dumps({"code": 200, "response":"error", "message" : "User not found"})
        else:
            return json.dumps({"code":"200", "response":"error", "errors" : errors})

    elif request.method == 'DELETE':
        """
            Deletes an user by its id
        """

        # Find user by id
        user = ForumUser.get_by_id(id)

        if user != None:
            user.delete()
            return json.dumps({"code":200,"response":"success","message":"User deleted"})
        else:
            return json.dumps({"code": 200, "response":"error", "message" : "User not found"})


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain 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.
//

namespace Microsoft.Azure.Management.TrafficManager.Testing.ScenarioTests
{
    using System.Collections.Generic;
    using System.Linq;
    using global::TrafficManager.Tests.Helpers;
    using Microsoft.Azure.Management.Resources.Models;
    using Microsoft.Azure.Management.TrafficManager.Models;
    using Microsoft.Azure.Management.TrafficManager.Testing.Helpers;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using Xunit;

    public class ProfileScenarioTests : TestBase
    {
        [Fact]
        public void CrudProfileFullCycle()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                TrafficManagerManagementClient trafficManagerClient = this.GetTrafficManagerManagementClient(context);

                string resourceGroupName = TestUtilities.GenerateName("resourcegroup");
                string profileName = TestUtilities.GenerateName("atmprofile");
                ResourceGroup resourceGroup = this.CreateResourceGroup(context, resourceGroupName);

                // Create the profile
                trafficManagerClient.Profiles.CreateOrUpdate(
                    resourceGroup.Name,
                    profileName,
                    TrafficManagerHelper.GenerateDefaultProfile(profileName));

                // Get the profile
                trafficManagerClient.Profiles.Get(
                    resourceGroup.Name,
                    profileName);

                // Delete the profile
                trafficManagerClient.Profiles.Delete(resourceGroup.Name, profileName);

                this.DeleteResourceGroup(context, resourceGroupName);
            }
        }

        [Fact]
        public void CrudProfileWithoutEndpoints_ThenUpdate()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                TrafficManagerManagementClient trafficManagerClient = this.GetTrafficManagerManagementClient(context);

                string resourceGroupName = TestUtilities.GenerateName("resourcegroup");
                string profileName = TestUtilities.GenerateName("atmprofile");
                ResourceGroup resourceGroup = this.CreateResourceGroup(context, resourceGroupName);

                Profile profile = TrafficManagerHelper.GenerateDefaultProfile(profileName);
                profile.Endpoints = null;

                // Create the profile
                trafficManagerClient.Profiles.CreateOrUpdate(
                    resourceGroup.Name,
                    profileName,
                    profile);

                profile.Endpoints = new[]
                {
                    new Endpoint
                    {
                        Id = null,
                        Name = "My external endpoint",
                        Type = "Microsoft.network/TrafficManagerProfiles/ExternalEndpoints",
                        TargetResourceId = null,
                        Target = "foobar.contoso.com",
                        EndpointLocation = "North Europe",
                        EndpointStatus = "Enabled"
                    }
                };

                // Create the profile
                trafficManagerClient.Profiles.CreateOrUpdate(
                    resourceGroup.Name,
                    profileName,
                    profile);

                this.DeleteResourceGroup(context, resourceGroupName);
            }
        }

        [Fact]
        public void ListProfilesByResourceGroup()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                TrafficManagerManagementClient trafficManagerClient = this.GetTrafficManagerManagementClient(context);

                string resourceGroupName = TestUtilities.GenerateName("resourcegroup");
                ResourceGroup resourceGroup = this.CreateResourceGroup(context, resourceGroupName);

                for (int i = 0; i < 5; ++i)
                {
                    string profileName = TestUtilities.GenerateName("atmprofile");

                    trafficManagerClient.Profiles.CreateOrUpdate(
                        resourceGroup.Name,
                        profileName,
                        TrafficManagerHelper.GenerateDefaultProfile(profileName));
                }

                List<Profile> listResponse = trafficManagerClient.Profiles.ListAllInResourceGroup(resourceGroup.Name).ToList();

                Assert.Equal(5, listResponse.Count);

                this.DeleteResourceGroup(context, resourceGroupName);
            }
        }

        [Fact]
        public void ListAllProfiles()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                TrafficManagerManagementClient trafficManagerClient = this.GetTrafficManagerManagementClient(context);

                string resourceGroupName = TestUtilities.GenerateName("resourcegroup");
                ResourceGroup resourceGroup = this.CreateResourceGroup(context, resourceGroupName);

                for (int i = 0; i < 5; ++i)
                {
                    string profileName = TestUtilities.GenerateName("atmprofile");

                    trafficManagerClient.Profiles.CreateOrUpdate(
                        resourceGroup.Name,
                        profileName,
                        TrafficManagerHelper.GenerateDefaultProfile(profileName));
                }

                IEnumerable<Profile> listResponse = trafficManagerClient.Profiles.ListAll();

                // Just in case the subscription had some other profiles
                Assert.True(5 <= listResponse.Count());

                this.DeleteResourceGroup(context, resourceGroupName);
            }
        }
    }
}


text:
#include "process.h"

#include <kdberrors.h>
#include <kdbhelper.h>
#include <kdbinvoke.h>
#include <kdbpluginprocess.h>

#include <stdio.h>

typedef struct
{
	ElektraInvokeHandle * plugin;
	Key * pluginName;
	KeySet * pluginConfig;
} Process;

static int validPluginName (Key * pluginNameKey, Key * errorKey)
{
	if (pluginNameKey == NULL)
	{
		ELEKTRA_ADD_INSTALLATION_WARNING (errorKey, "Missing plugin configuration parameter plugin=<name of plugin to be proxied>");
		return 0;
	}

	// and this key should obviously contain the plugin's name, so check for any name
	// furthermore by invoking process in a process we'd create a deadloop, check that too
	const char * pluginName = keyString (pluginNameKey);
	if (elektraStrCmp (pluginName, "(null)") == 0 || keyIsBinary (pluginNameKey))
	{
		ELEKTRA_ADD_VALIDATION_SEMANTIC_WARNINGF (errorKey, "Plugin configuration parameter plugin has an invalid value: %s",
							  pluginName);
		return 0;
	}
	else if (elektraStrCmp (pluginName, "process") == 0)
	{
		ELEKTRA_ADD_INTERFACE_WARNING (errorKey, "Cannot proxy the process plugin itself");
		return 0;
	}
	return 1;
}

static void cleanup (Process * process, Key * errorKey)
{
	if (process->plugin) elektraInvokeClose (process->plugin, errorKey);
	if (process->pluginName) keyDel (process->pluginName);
	ksDel (process->pluginConfig);
	elektraFree (process);
}

int elektraInvoke1Arg (ElektraInvokeHandle * handle, const char * elektraPluginFunctionName, Key * k)
{
	if (!handle || !elektraPluginFunctionName) return -2;

	// If we cast this right away although the function wasn't found it will cause a deadlock
	const void * rawFunc = elektraInvokeGetFunction (handle, elektraPluginFunctionName);

	if (!rawFunc) return -2;

	typedef int (*elektra1Arg) (Key *);
	elektra1Arg func = *(elektra1Arg *) rawFunc;
	return func (k);
}

static int isContractKey (Key * key)
{
	return !elektraStrCmp (keyName (key), "system:/elektra/modules/process");
}

int elektraProcessOpen (Plugin * handle, Key * errorKey)
{
	ElektraPluginProcess * pp = elektraPluginGetData (handle);
	if (pp == NULL)
	{
		// process initialization
		Process * process = elektraMalloc (sizeof (Process));
		KeySet * processConfig = elektraPluginGetConfig (handle);
		process->pluginName = ksLookupByName (processConfig, "/plugin", KDB_O_POP);
		process->pluginConfig = ksDup (processConfig);
		ksAppendKey (processConfig, process->pluginName);
		process->plugin = NULL;

		if ((pp = elektraPluginProcessInit (errorKey)) == NULL) return ELEKTRA_PLUGIN_STATUS_ERROR;

		elektraPluginProcessSetData (pp, process);
		elektraPluginSetData (handle, pp);
		if (!elektraPluginProcessIsParent (pp)) elektraPluginProcessStart (handle, pp);
	}

	if (elektraPluginProcessIsParent (pp)) return elektraPluginProcessOpen (pp, errorKey);

	Process * process = elektraPluginProcessGetData (pp);

	// First time child initialization
	// elektraInvokeOpen will call the plugin's open function, this has to happen in the other process

	if (process->plugin == NULL && !isContractKey (errorKey) && validPluginName (process->pluginName, errorKey))
	{
		process->plugin = elektraInvokeOpen (keyString (process->pluginName), process->pluginConfig, errorKey);
		if (!process->plugin)
		{
			ELEKTRA_SET_RESOURCE_ERRORF (errorKey, "Failed to open the proxied plugin %s", keyString (process->pluginName));
			return ELEKTRA_PLUGIN_STATUS_ERROR;
		}
		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	if (process->plugin == NULL) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

	// Otherwise just call the open function if it exists and don't reinitialize with elektraInvokeOpen
	int ret = elektraInvoke1Arg (process->plugin, "open", errorKey);
	if (ret == -2) return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	return ret;
}

int elektraProcessClose (Plugin * handle, Key * errorKey)
{
	ElektraPluginProcess * pp = elektraPluginGetData (handle);
	if (!pp) return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	Process * process = elektraPluginProcessGetData (pp);
	if (elektraPluginProcessIsParent (pp))
	{
		ElektraPluginProcessCloseResult result = elektraPluginProcessClose (pp, errorKey);
		if (result.cleanedUp)
		{
			cleanup (process, errorKey);
			elektraPluginSetData (handle, NULL);
		}
		return result.result;
	}

	// Handle may be null if initialization failed in the child, ignore that it will exit anyway afterwards
	if (process->plugin == NULL) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

	int ret = elektraInvoke1Arg (process->plugin, "close", errorKey);
	if (ret == -2) return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}

static void adjustContract (KeySet * pluginContract, KeySet * contract)
{
	ksRewind (pluginContract);
	Key * cur;
	while ((cur = ksNext (pluginContract)) != NULL)
	{
		Key * cpy = keyDup (cur, KEY_CP_ALL);
		keySetBaseName (cpy, NULL);
		if (!elektraStrCmp ("infos", keyBaseName (cpy)))
		{
			keySetBaseName (cpy, NULL);
			keySetBaseName (cpy, NULL);
			keyAddBaseName (cpy, "process");
			keyAddBaseName (cpy, "infos");
			keyAddBaseName (cpy, keyBaseName (cur));
			Key * infoKey = ksLookup (contract, cpy, KDB_O_NONE);
			keySetString (infoKey, keyString (cpy));
		}
		keyDel (cpy);
	}
}

int elektraProcessGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
	ElektraPluginProcess * pp = elektraPluginGetData (handle);
	Process * process = elektraPluginProcessGetData (pp);

	if (elektraPluginProcessIsParent (pp)) return elektraPluginProcessSend (pp, ELEKTRA_PLUGINPROCESS_GET, returned, parentKey);

	if (isContractKey (parentKey))
	{
		KeySet * processConfig = elektraPluginGetConfig (handle);
		Key * pluginName = ksLookupByName (processConfig, "/plugin", KDB_O_NONE);

		KeySet * contract =
			ksNew (30, keyNew ("system:/elektra/modules/process", KEY_VALUE, "process plugin waits for your orders", KEY_END),
			       keyNew ("system:/elektra/modules/process/exports", KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/open", KEY_FUNC, elektraProcessOpen, KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/close", KEY_FUNC, elektraProcessClose, KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/get", KEY_FUNC, elektraProcessGet, KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/set", KEY_FUNC, elektraProcessSet, KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/error", KEY_FUNC, elektraProcessError, KEY_END),
			       keyNew ("system:/elektra/modules/process/exports/checkconf", KEY_FUNC, elektraProcessCheckConf, KEY_END),
#include ELEKTRA_README
			       keyNew ("system:/elektra/modules/process/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, contract);
		ksDel (contract);

		if (!validPluginName (pluginName, parentKey) || !process->plugin) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

		Key * pluginParentKey = keyDup (parentKey, KEY_CP_ALL);
		keySetBaseName (pluginParentKey, keyString (pluginName));

		KeySet * pluginContract = ksNew (30, KS_END);
		elektraInvoke2Args (process->plugin, "get", pluginContract, pluginParentKey);
		keyDel (pluginParentKey);
		if (ksGetSize (pluginContract) == 0)
		{
			ELEKTRA_SET_INTERFACE_ERRORF (parentKey, "Failed to get the contract for %s", keyString (pluginName));
			ksDel (pluginContract);
			return ELEKTRA_PLUGIN_STATUS_ERROR;
		}

		adjustContract (pluginContract, returned);
		ksDel (pluginContract);

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	if (!process->plugin) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

	int ret = elektraInvoke2Args (process->plugin, "get", returned, parentKey);
	if (ret == -2) return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
	return ret;
}

int elektraProcessSet (Plugin * handle, KeySet * returned, Key * parentKey)
{
	ElektraPluginProcess * pp = elektraPluginGetData (handle);
	Process * process = elektraPluginProcessGetData (pp);

	if (elektraPluginProcessIsParent (pp)) return elektraPluginProcessSend (pp, ELEKTRA_PLUGINPROCESS_SET, returned, parentKey);

	if (!process->plugin) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

	int ret = elektraInvoke2Args (process->plugin, "set", returned, parentKey);
	if (ret == -2) return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
	return ret;
}

int elektraProcessError (Plugin * handle, KeySet * returned, Key * parentKey)
{
	ElektraPluginProcess * pp = elektraPluginGetData (handle);
	Process * process = elektraPluginProcessGetData (pp);

	if (elektraPluginProcessIsParent (pp)) return elektraPluginProcessSend (pp, ELEKTRA_PLUGINPROCESS_ERROR, returned, parentKey);

	if (!process->plugin) return ELEKTRA_PLUGIN_STATUS_SUCCESS;

	int ret = elektraInvoke2Args (process->plugin, "error", returned, parentKey);
	if (ret == -2) return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	return ret;
}

int elektraProcessCheckConf (Key * errorKey, KeySet * conf)
{
	// We need the plugin key to know which plugin we should proxy
	Key * pluginNameKey = ksLookupByName (conf, "/plugin", KDB_O_NONE);
	if (!validPluginName (pluginNameKey, errorKey))
	{
		return ELEKTRA_PLUGIN_STATUS_ERROR;
	}

	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

Plugin * ELEKTRA_PLUGIN_EXPORT
{
	// clang-format off
	return elektraPluginExport ("process",
		ELEKTRA_PLUGIN_OPEN,	&elektraProcessOpen,
		ELEKTRA_PLUGIN_CLOSE,	&elektraProcessClose,
		ELEKTRA_PLUGIN_GET,	&elektraProcessGet,
		ELEKTRA_PLUGIN_SET,		&elektraProcessSet,
		ELEKTRA_PLUGIN_ERROR,	&elektraProcessError,
		ELEKTRA_PLUGIN_END);
}


text:
package org.pipseq.spin;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.io.Closeable;

import org.pipseq.common.DateTime;
import org.pipseq.content.ConnectorFactory;
import org.pipseq.content.FileConnector;
import org.pipseq.rdf.jena.aggregate.AggMethodRegistry;
import org.pipseq.rdf.jena.cfg.ModelWrapper;
import org.pipseq.rdf.jena.cfg.OntoBoxWrapper;
import org.pipseq.rdf.jena.listener.ReleaseListener;
import org.pipseq.rdf.jena.listener.ReleaseBlankAndPredicateListener;
import org.pipseq.rdf.jena.listener.ReleasePredicateListener;
import org.pipseq.rdf.jena.listener.ListenerMetrics;
import org.pipseq.rdf.jena.listener.ListenerPublisher;
import org.pipseq.rdf.jena.model.Sparql;
import org.pipseq.spin.compare.RestrictionSPINRuleComparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.inference.SPINExplanations;
import org.topbraid.spin.inference.SPINInferences;
import org.topbraid.spin.inference.SPINRuleComparator;
import org.topbraid.spin.progress.ProgressMonitor;
import org.topbraid.spin.statistics.SPINStatistics;
import org.topbraid.spin.system.SPINModuleRegistry;
import org.topbraid.spin.util.CommandWrapper;
import org.topbraid.spin.util.SPINQueryFinder;
import org.topbraid.spin.vocabulary.SPIN;

import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

// TODO: Auto-generated Javadoc
/**
 * The Class RuleEngine.
 *
 * This rule engine performs inferencing collecting
 * inferences in an inference model. The model is returned
 * to the client.
 *
 */
public class RuleEngine implements Closeable {

	private static final Logger log = LoggerFactory.getLogger(RuleEngine.class);
	public boolean Diagnostics = false;
	//private ModelWrapper tbox = new ModelWrapper("tbox");
	ITboxSource tboxSource;
	private ModelWrapper abox;
	private OntoBoxWrapper ontBoxWrapper;
	private String feedbackQuery;
	private String outcomeQuery;
	private boolean outcomeResults;
	private ProgressMonitor monitor = new SpinMonitor();

	public boolean hasOutcomeResults() {
		return outcomeResults;
	}

	public ITboxSource getTboxSource() {
		return tboxSource;
	}

	public void setTboxSource(ITboxSource tboxSource) {
		this.tboxSource = tboxSource;
	}

	public boolean isDiagnostics() {
		return Diagnostics;
	}

	public void setDiagnostics(boolean diagnostics) {
		Diagnostics = diagnostics;
	}

	public ModelWrapper getTbox() {
		return getTboxSource().getTbox();
	}

	public ModelWrapper getAbox() {
		if (abox == null){
			abox = new ModelWrapper("abox");
		}
		return abox;
	}

	public void setAbox(ModelWrapper abox) {
		this.abox = abox;
	}

	private String name;
	/**
	 * Instantiates a new setup.
	 */
	protected RuleEngine(String name) {
		this.name = name;
		// Initialize system functions and templates
		SPINModuleRegistry.get().init();
		AggMethodRegistry.init();	// TODO-can this live elsewhere?
	}

	/* (non-Javadoc)
	 * @see org.pipseq.spin.IRuleEngine#init()
	 */
	public void init() {

		getAbox().addListener(new ReleaseListener(".*_[0-9][0-9][0-9]+$",100));	//TODO-review this!
		getAbox().addListener(new ReleaseBlankAndPredicateListener("TimeStamp",20));	//TODO-review this!
		getAbox().addListener(new ReleasePredicateListener("hasIndicatorResult",40));	//TODO-review this!
		getAbox().addListener(new ReleasePredicateListener("hasAsk",40));	//TODO-review this!
		getAbox().addListener(new ReleasePredicateListener("hasBid",40));	//TODO-review this!
		//abox.addListener(new ReleaseListener(".*",1500));	//TODO-review this!
		getAbox().addListener(new ListenerMetrics("abox-"+name));
		ontBoxWrapper = new OntoBoxWrapper("ontoBox-"+name,getAbox(), getTboxSource().getTbox());
		ontBoxWrapper.init();

		// Register locally defined functions
		SPINModuleRegistry.get().registerAll(ontBoxWrapper.get(), null);

		log.debug("initialized: "+name);
	}

	ModelWrapper nuTrpls;
	ModelWrapper getLastInferences(){
		return nuTrpls;
	}

	/* (non-Javadoc)
	 * @see org.pipseq.spin.IRuleEngine#run()
	 */
	public ModelWrapper run() {

		try {
			// Create and add Model for inferred triples
			nuTrpls = new ModelWrapper("newTriples");
			//Model newTriples = ModelFactory.createDefaultModel();
			ontBoxWrapper.get().addSubModel(nuTrpls.get());

			// Run all inferences
			SPINExplanations explain = new SPINExplanations();
			List<SPINStatistics> lstat = new ArrayList<SPINStatistics>();

			// diagnostics
			if (Diagnostics) {
				log.debug("Now="+DateTime.now().toISOString());
				run(ontBoxWrapper.get(), nuTrpls.get(), explain, lstat, true/* single pass */, monitor);
				for (StmtIterator si = nuTrpls.get().listStatements(); si.hasNext();){
					Statement st = si.nextStatement();
					Triple t = new Triple(st.getSubject().asNode(), st.getPredicate().asNode(), st.getObject().asNode());
					log.debug("explain: "+explain.getClass(t) + " for "
							+(t.getSubject().isBlank()
									? "_:b"+t.getSubject().getBlankNodeLabel()
									//? "_:b"+t.getSubject().getBlankNodeLabel().hashCode()
									: t.getSubject().getLocalName())  + " "
							+t.getPredicate().getLocalName() + " "
							+t.getObject() + " "
					);
				}
				for (SPINStatistics ss : lstat){
					log.debug("spinStat: "+ ss.getLabel()+" duration="+ss.getDuration()+" context="+ss.getContext());
				}
			} else {
				run(ontBoxWrapper.get(), nuTrpls.get(), null, null, true/* single pass */, null);
			}

			ontBoxWrapper.get().removeSubModel(nuTrpls.get()); // cleanup

			// feedback
			if (getFeedbackQuery() != null){
				Model m = Sparql.queryDescribe(nuTrpls.get(), getFeedbackQuery());
				getModel().add(m);
			}

			// outcome
			if (getOutcomeQuery() != null){
				Model m = Sparql.queryDescribe(nuTrpls.get(), getOutcomeQuery());
				//getModel().add(m);	// TODO - feedback too?
				outcomeResults = m.size() > 0;
			}
		} catch (Exception e) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			PrintStream ps = new PrintStream(baos);
			e.printStackTrace(ps);
			String err = e.getMessage()+", "+baos.toString();
			log.error(err);
			throw new RuntimeException(err);
		}

		return nuTrpls;
	}

	/**
	 * Run.
	 *
	 * @param queryModel
	 *            the query model
	 * @param newTriples
	 *            the new triples
	 * @param explanations
	 *            the explanations
	 * @param statistics
	 *            the statistics
	 * @param singlePass
	 *            the single pass
	 * @param monitor
	 *            the monitor
	 * @return the int
	 */
	// providing own implementation mostly to roll own comparator
	public static int run(Model queryModel, Model newTriples,
			SPINExplanations explanations, List<SPINStatistics> statistics,
			boolean singlePass, ProgressMonitor monitor) {
		Map<Resource, List<CommandWrapper>> cls2Query = SPINQueryFinder
				.getClass2QueryMap(queryModel, queryModel, SPIN.rule, true,
						false);
		Map<Resource, List<CommandWrapper>> cls2Constructor = SPINQueryFinder
				.getClass2QueryMap(queryModel, queryModel, SPIN.constructor,
						true, false);
		SPINRuleComparator comparator = new RestrictionSPINRuleComparator(
				queryModel);
		return SPINInferences.run(queryModel, newTriples, cls2Query,
				cls2Constructor, explanations, statistics, singlePass,
				SPIN.rule, comparator, monitor);
	}

	/* (non-Javadoc)
	 * @see org.pipseq.spin.IRuleEngine#getModel()
	 */
	public Model getModel() {
		return ontBoxWrapper.get();
	}

	/* (non-Javadoc)
	 * @see org.pipseq.spin.IRuleEngine#getModel()
	 */
	public ModelWrapper getModelWrapper() {
		return ontBoxWrapper;
	}

	/* (non-Javadoc)
	 * @see org.pipseq.spin.IRuleEngine#close()
	 */
	@Override
	public void close() throws IOException {
		// tbox owned by RuleEngineFactory
		getAbox().close();
		log.debug(""+name+" close");
	}

	// input string TTL to model
	public void insertModel(String ttl) {
		insertModel(getModel(), ttl);
	}

	// input string TTL to model
	public static void insertModel(Model model, String ttl) {
		InputStream is = new ByteArrayInputStream((ttl).getBytes());
		model.read(is, null, "TTL");
	}

	/**
	 * Scope.
	 */
	public void scope() {
		scope(getModel());
	}

	/**
	 * Scope.
	 *
	 * @param model
	 *            the model
	 */
	public static void scope(Model model) {
		org.pipseq.rdf.jena.util.SparqlScope.scope(model);
	}

	public String getFeedbackQuery() {
		return feedbackQuery;
	}

	public void setFeedbackQuery(String feedbackQuery) {
		this.feedbackQuery = feedbackQuery;
	}

	public String getOutcomeQuery() {
		return outcomeQuery;
	}

	public void setOutcomeQuery(String outcomeQuery) {
		this.outcomeQuery = outcomeQuery;
	}

}


text:
define(["sg/sideAxis"], function(sideAxis) {

  /** return a smaple ChartData descriptor object for this raw data array. */
  return function(dataArray) {
    var data = {
      title: "sample data",
      groups: [
        {
          axis: sideAxis(),
          series: [
            { set: "sample",
              name: "first",
              domain: findDomain(dataArray),
              range: findRange(dataArray)
            }
          ],
          label: "label-first-set"
        }
      ]
    };
    return data;
  };

  function findDomain(dataArray) {
    if (dataArray.length < 1)
      return [new Date(0), new Date(0)];

    return minMax(dataArray, 0);
  }

  function findRange(dataArray) {
    if (dataArray.length < 1)
      return [0, 0];

    return minMax(dataArray, 1);
  }

  /** return the min an max values of an array column  */
  function minMax(dataArray, column) {
    var min = dataArray.reduce(function(a,b) {
      return (a < b[column]) ? a : b[column];
    }, dataArray[column]);

    var max = dataArray.reduce(function(a,b) {
      return (a > b[column]) ? a : b[column];
    }, dataArray[column]);

    return [min, max];
  }
});


text:
using System;
using System.Threading.Tasks;
using Jal.ChainOfResponsability;

namespace Jal.HttpClient
{
    public class TracingMiddleware : IAsyncMiddleware<HttpContext>
    {
        public const string REQUESTID_HEADER_NAME_KEY = "requestidheadername";

        public const string OPERATIONID_HEADER_NAME_KEY = "operationidheadername";

        public const string PARENTID_HEADER_NAME_KEY = "parentidheadername";

        public Task ExecuteAsync(AsyncContext<HttpContext> context, Func<AsyncContext<HttpContext>, Task> next)
        {
            if(context.Data.Request.Tracing!=null)
            {
                if(context.Data.Request.Context.ContainsKey(REQUESTID_HEADER_NAME_KEY))
                {
                    var name = context.Data.Request.Context[REQUESTID_HEADER_NAME_KEY] as string;

                    context.Data.Request.Message.Headers.Add(name, context.Data.Request.Tracing.RequestId);
                }

                if (!string.IsNullOrWhiteSpace(context.Data.Request.Tracing.OperationId) && context.Data.Request.Context.ContainsKey(OPERATIONID_HEADER_NAME_KEY))
                {
                    var name = context.Data.Request.Context[OPERATIONID_HEADER_NAME_KEY] as string;

                    context.Data.Request.Message.Headers.Add(name, context.Data.Request.Tracing.OperationId);
                }

                if (!string.IsNullOrWhiteSpace(context.Data.Request.Tracing.ParentId) && context.Data.Request.Context.ContainsKey(PARENTID_HEADER_NAME_KEY))
                {
                    var name = context.Data.Request.Context[PARENTID_HEADER_NAME_KEY] as string;

                    context.Data.Request.Message.Headers.Add(name, context.Data.Request.Tracing.ParentId);
                }
            }

            return next(context);
        }
    }
}


text:
    @foreach ($topMostDirectories as $directory)

             $directory]) }}"
               class="nav-link @if ($filter === $directory) active @endif"
            >
                {{ $directory }}

    @endforeach

                {{ Form::open(['action' => ['ReaderHistoryController@markAllArchivesRead', $manga, 'filter' => $filter], 'class' => 'd-inline-flex p-0 m-0']) }}
                <button class="btn m-0 p-0 pr-1" type="submit" title="Mark all as read">

                </button>
                {{ Form::close() }}

                    @if ($sort === 'asc' || empty($sort))
                        fullUrlWithQuery(['sort' => 'desc']) }}">
                    @else
                        fullUrlWithQuery(['sort' => 'asc']) }}">
                    @endif

                    Name
                    @if ($sort === 'asc' || empty($sort))
                        fullUrlWithQuery(['sort' => 'desc']) }}">
                    @else
                        fullUrlWithQuery(['sort' => 'asc']) }}">
                    @endif

                Last Read

                Date Added

    @foreach ($items as $item)
        @php
            $readerHistory = $user->readerHistory->where('manga_id', $manga->id);
            $archiveHistory = $readerHistory->where('archive_id', $item->id)->first();
            $hasRead = ! empty($archiveHistory);
            $hasCompleted = $hasRead ? $archiveHistory->page === $archiveHistory->page_count : false;

            $colorType = $hasRead ? ($hasCompleted ? "success" : "warning") : false;
            $status = $hasRead ? ($hasCompleted ? "Complete" : "Incomplete") : "Unread";

            $resumeUrl = URL::action('ReaderController@index', [$manga, $item, ! empty($archiveHistory) ? $archiveHistory->page : 1]);
        @endphp

            {{-- Use text-left as this column is centered on Safari --}}

                @php
                    if ($status === 'Incomplete' || $status === 'Unread') {
                        $actionParams = ['ReaderHistoryController@markArchiveRead', $item];
                        $title = 'Mark as read';
                    } else {
                        $actionParams = ['ReaderHistoryController@markArchiveUnread', $item];
                        $title = 'Mark as unread';
                    }
                @endphp
                {{ Form::open(['action' => $actionParams, 'class' => 'd-inline-flex m-0 p-0']) }}
                <button class="btn m-0 p-0 pr-1 toggle-archive-read"
                        data-status="{{ $status }}"
                        type="submit"
                        title="{{ $title }}"
                        id="archive-{{ $item->id }}"
                >

                </button>
                {{ Form::close() }}

                        {{ \App\Scanner::removeExtension(\App\Scanner::simplifyName($item->name)) }}

                @if (! empty($archiveHistory))

                        {{ $archiveHistory->updated_at->diffForHumans(null, \Carbon\CarbonInterface::DIFF_ABSOLUTE) }}

                        {{ $archiveHistory->updated_at->diffForHumans() }}

                @endif

                    {{ $item->created_at->diffForHumans(null, \Carbon\CarbonInterface::DIFF_ABSOLUTE) }}

                    {{ $item->created_at->diffForHumans() }}

    @endforeach


text:
require 'date'

require 'calco'
require 'calco/xml_builder'

require_relative 'office_file_manager'

module Calco

  class OfficeEngine < DefaultEngine

    def initialize ods_template
      @ods_template = ods_template
    end

    # output is a String (as a file name)
    def save doc, to_filename, &data_iterator

      @file_manager = OfficeFileManager.new(@ods_template)

      data_iterator.call(doc)

      @file_manager.save doc, to_filename

    end

    def empty_row sheet
      @file_manager.add_empty_row sheet
    end

    def write_row sheet, row_id

      return if row_id == 0 && sheet.has_titles?

      row_id += 1 # office sheet indexes start at 1

      cells = sheet.row(row_id)

      @file_manager.add_row sheet do |stream|

        cells.each_index do |i|

          cell = cells[i]

          stream.write cell

        end

      end

    end

    def generate_cell row_number, column, cell_style, column_style, column_type

      return '<table:table-cell/>' unless column
      return '<table:table-cell/>' if column.absolute_row && column.absolute_row != row_number

      currency = nil

      cell = column.generate(row_number)

      cell_style = cell_style.generate(row_number) if cell_style

      if column_type

        if column_type == '%'
          column_type = 'percentage'
        elsif column_type =~ /\$([A-Z]{3})/
          currency = "#{$1}"
          column_type = 'currency'
        end

      end

      office_cell column, column_style, column_type, currency, cell.to_s, cell_style

    end

    def column_reference element, row
      element.is_a?(Current) ? "#{super}" : "[.#{super}]"
    end

    def value element

      if ! element.respond_to?(:value)
        s = element.to_s
      else
        s = element.value.to_s
      end

      s.gsub!('"', '"') if s =~ /"/
      s

    end

    def style statement, row
      "&T(ORG.OPENOFFICE.STYLE(#{statement.generate(row)}))"
    end

    def operator op

      if op == '!='
        '<>'
      elsif op == '<'
        '<'
      elsif op == '>'
        '>'
      else
        op
      end

    end

    def current
      'ORG.OPENOFFICE.CURRENT()'
    end

    private

    def office_cell column, column_style, column_type, currency, value, cell_style

      xml = XMLBuilder.new('table:table-cell')

      if column.is_a?(Formula)

        column_type = 'float' unless column_type

        xml << {'table:formula' => "of:=#{value}#{cell_style}"}

      elsif column.respond_to?(:value)

        if column.value.nil?

          return xml.build

        elsif column.value.is_a?(Numeric)

          column_type = 'float' unless column_type

          xml << {'office:value' => "#{value}#{cell_style}"} unless cell_style

        elsif column.value.is_a?(Date)

          column_type = 'date' unless column_type

          xml << {'office:date-value' => "#{value}#{cell_style}"} unless cell_style

        else

          column_type = 'string' unless column_type

          if cell_style
            value = office_string_escape(value)
          else
            xml.add_child 'text:p', office_string_value(value)
          end

        end

        if cell_style
          xml << {'table:formula' => "of:=#{value}#{cell_style}"}
        end

      end

      xml << {'table:style-name'  => column_style}   if column_style
      xml << {'office:currency'   => currency}       if currency
      xml << {'office:value-type' => column_type}

      xml.build

    end

    def office_string_value str
      str.gsub('"', '"')
    end

    def office_string_escape str
      '"' + str.gsub('"', '""') + '"'
    end

  end

end


text:
#import <objc/runtime.h>

#import <React/RCTBridge.h>

@protocol RCTSurfaceProtocol;

NS_ASSUME_NONNULL_BEGIN

// TODO: Eventually this should go away and files should just include RCTSurfacePresenter.h, but
// that pulls in all of fabric which doesn't compile in open source yet, so we mirror the protocol
// and duplicate the category here for now.

@protocol RCTSurfacePresenterObserver <NSObject>

@optional

- (void)willMountComponentsWithRootTag:(NSInteger)rootTag;
- (void)didMountComponentsWithRootTag:(NSInteger)rootTag;

@end

@protocol RCTSurfacePresenterStub <NSObject>

- (id<RCTSurfaceProtocol>)createFabricSurfaceForModuleName:(NSString *)moduleName
                                         initialProperties:(NSDictionary *)initialProperties;
- (nullable UIView *)findComponentViewWithTag_DO_NOT_USE_DEPRECATED:(NSInteger)tag;
- (BOOL)synchronouslyUpdateViewOnUIThread:(NSNumber *)reactTag props:(NSDictionary *)props;
- (void)addObserver:(id<RCTSurfacePresenterObserver>)observer;
- (void)removeObserver:(id<RCTSurfacePresenterObserver>)observer;

@end

@interface RCTBridge (RCTSurfacePresenterStub)

- (id<RCTSurfacePresenterStub>)surfacePresenter;
- (void)setSurfacePresenter:(id<RCTSurfacePresenterStub>)presenter;

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.airavata.sharing.registry.messaging;

import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.DBEventService;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Subscriber;
import org.apache.airavata.model.dbevent.DBEventMessage;
import org.apache.airavata.model.dbevent.DBEventMessageContext;
import org.apache.airavata.model.dbevent.DBEventSubscriber;
import org.apache.airavata.model.dbevent.DBEventType;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by Ajinkya on 3/28/17.
 */
public class SharingServiceDBEventMessagingFactory {

    private final static Logger log = LoggerFactory.getLogger(SharingServiceDBEventMessagingFactory.class);

    private static Publisher dbEventPublisher;

    private static Subscriber sharingServiceDBEventSubscriber;

    /**
     * Get publisher for DB Event queue
     * Change access specifier as required
     * @return
     * @throws AiravataException
     */
    private static Publisher getDBEventPublisher() throws AiravataException {
        if(null == dbEventPublisher){
            synchronized (SharingServiceDBEventMessagingFactory.class){
                if(null == dbEventPublisher){
                    log.info("Creating DB Event publisher.....");
                    dbEventPublisher = MessagingFactory.getDBEventPublisher();
                    log.info("DB Event publisher created");
                }
            }
        }
        return dbEventPublisher;
    }

    public static Subscriber getDBEventSubscriber() throws AiravataException, SharingRegistryException {
        if(null == sharingServiceDBEventSubscriber){
            synchronized (SharingServiceDBEventMessagingFactory.class){
                if(null == sharingServiceDBEventSubscriber){
                    log.info("Creating DB Event publisher.....");
                    sharingServiceDBEventSubscriber = MessagingFactory.getDBEventSubscriber(new SharingServiceDBEventHandler(), DBEventService.SHARING.toString());
                    log.info("DB Event publisher created");
                }
            }
        }
        return sharingServiceDBEventSubscriber;
    }

    /**
     * Register sharing service with stated publishers
     * @param publishers
     * @return
     * @throws AiravataException
     */
    public static boolean registerSharingServiceWithPublishers(List<String> publishers) throws AiravataException {

        for(String publisher : publishers){

            log.info("Sending service discovery message. Publisher : " + publisher + ", Subscriber : " + DBEventService.SHARING.toString());

            DBEventSubscriber dbEventSubscriber = new DBEventSubscriber(DBEventService.SHARING.toString());
            DBEventMessageContext dbEventMessageContext = new DBEventMessageContext();
            dbEventMessageContext.setSubscriber(dbEventSubscriber);

            DBEventMessage dbEventMessage = new DBEventMessage(DBEventType.SUBSCRIBER, dbEventMessageContext, publisher);

            MessageContext messageContext = new MessageContext(dbEventMessage, MessageType.DB_EVENT, "", "");

            getDBEventPublisher().publish(messageContext, DBEventManagerConstants.getRoutingKey(DBEventService.DB_EVENT.toString()));

        }

        return true;
    }

}


text:
Heartbeat
=========

Corona SDK example showing how to use a beating heart as a life meter.  Also shows
how to change the pitch of a backing track and keep the animation in synch with it.

See the video at: http://youtu.be/EZD8wJNCAxc


text:
.. _l-function-expect:

Sample operator test code
=========================

Many examples from the documentation end by calling
function ``expect`` to check a runtime returns the expected
outputs for the given example. Here is one implementation
based on `onnxruntime <https://onnxruntime.ai/>`_.

::

    from typing import Any, Sequence
    import numpy as np
    import onnx
    import onnxruntime

    def expect(
        node: onnx.NodeProto,
        inputs: Sequence[np.ndarray],
        outputs: Sequence[np.ndarray],
        name: str,
        **kwargs: Any,
    ) -> None:
        # Builds the model
        present_inputs = [x for x in node.input if (x != "")]
        present_outputs = [x for x in node.output if (x != "")]
        input_type_protos = [None] * len(inputs)
        if "input_type_protos" in kwargs:
            input_type_protos = kwargs["input_type_protos"]
            del kwargs["input_type_protos"]
        output_type_protos = [None] * len(outputs)
        if "output_type_protos" in kwargs:
            output_type_protos = kwargs["output_type_protos"]
            del kwargs["output_type_protos"]
        inputs_vi = [
            _extract_value_info(arr, arr_name, input_type)
            for arr, arr_name, input_type in zip(inputs, present_inputs, input_type_protos)
        ]
        outputs_vi = [
            _extract_value_info(arr, arr_name, output_type)
            for arr, arr_name, output_type in zip(
                outputs, present_outputs, output_type_protos
            )
        ]
        graph = onnx.helper.make_graph(
            nodes=[node], name=name, inputs=inputs_vi, outputs=outputs_vi
        )
        kwargs["producer_name"] = "backend-test"

        if "opset_imports" not in kwargs:
            # To make sure the model will be produced with the same opset_version after opset changes
            # By default, it uses since_version as opset_version for produced models
            produce_opset_version = onnx.defs.get_schema(
                node.op_type, node.domain
            ).since_version
            kwargs["opset_imports"] = [
                onnx.helper.make_operatorsetid(node.domain, produce_opset_version)
            ]

        model = onnx.helper.make_model_gen_version(graph, **kwargs)

        # Checking the produces are the expected ones.
        sess = onnxruntime.InferenceSession(model.SerializeToString())
        feeds = {name: value for name, value in zip(node.input, inputs)}
        results = sess.run(None, feeds)
        for expected, output in zip(outputs, results):
            assert_allclose(expected, output)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="default_margin">16dp</dimen>
    <dimen name="default_margin_small">12dp</dimen>
    <dimen name="default_padding">16dp</dimen>
    <dimen name="default_padding_small">12dp</dimen>

    <dimen name="text_size_enormous">45sp</dimen>
    <dimen name="text_size_huge">35sp</dimen>
    <dimen name="text_size_big">26sp</dimen>
    <dimen name="text_size">20sp</dimen>
    <dimen name="text_size_small">16sp</dimen>

    <dimen name="list_line_divider">0.5dp</dimen>

    <dimen name="thumbnail_image">70dp</dimen>
    <dimen name="article_title_image">200dp</dimen>

    <dimen name="qr_thumb">50dp</dimen>

    <dimen name="color_square">30dp</dimen>

    <dimen name="gallery_image_height">150dp</dimen>
</resources>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diatrype artemisiae Tilak

### Remarks
null


text:
require 'spec_helper'
require 'interactors/sync'
require 'models/person'
require 'models/room'

describe Sync do

  describe '.[]' do

    it 'returns anonymous subclass of Sync' do
      cls = described_class[String]
      expect(cls).to be < described_class
    end

    it 'sets model_class attribute' do
      cls = described_class[String]
      expect(cls.model_class).to eq String
    end

    it 'can set key_name attribute' do
      cls = described_class[String, key_name: :foo]
      expect(cls.key_name).to eq :foo
    end

    it 'can set key_name attribute' do
      cls = described_class[String, matching_attributes: [:foo]]
      expect(cls.matching_attributes).to contain_exactly :foo
    end

    it 'plularizes model_class as default key_name' do
      cls = described_class[String]
      expect(cls.key_name).to eq :strings
    end
  end

  describe '#perform' do

    subject(:sync) { described_class[Person]}
    let(:person) { Fabricate.build(:person) }

    it 'inserts new entity' do
      expect { sync.perform({people: [person]}) }.to change(person, :new?).from(true).to(false)
    end

    %i(created_at updated_at).each do |attr|
      it "sets #{attr} on insert" do
        expect {
          sync.perform({people: [person]})
          person.refresh
        }.to change(person, attr).from(nil)
      end
    end

    context 'with existing record' do

      let(:existing_person) { Fabricate(:person, full_name: 'Dude') }
      let(:person) { Fabricate.build(:person, id: existing_person.id, full_name: 'Mr. Dude') }

      it 'updates existing entity' do
        expect do
          sync.perform({people: [person]})
          existing_person.refresh
        end.to change(existing_person, :full_name).from('Dude').to('Mr. Dude')
      end

      it 'updates updated_at timestamp' do
        expect do
          sync.perform({people: [person]})
          existing_person.refresh
        end.to change(existing_person, :updated_at)
      end

      it 'does not update update_at when nothing is changed' do
        expect do
          sync.perform({people: [existing_person]})
          existing_person.refresh
        end.not_to change(existing_person, :updated_at)
      end

      it 'keeps created_at timestamp' do
        expect do
          sync.perform({people: [person]})
          existing_person.refresh
        end.not_to change(existing_person, :created_at)
      end

    end

    context 'with invalid input' do

      it 'raises RuntimeError' do
        expect { sync.perform({}) }.to raise_error(RuntimeError)
      end

    end

    context 'with custom key_name' do

      subject(:sync) { described_class[Person, key_name: :foo] }

      it 'accepts input from it' do
        expect { sync.perform({foo: []}) }.not_to raise_error
      end

    end

    context 'with custom matching_attributes' do

      subject(:sync) { described_class[Person, matching_attributes: [:access_token], skip_updating: [:id]] }
      let!(:saved_person) do
        Fabricate(:person, full_name: 'Pete', access_token: 'a41a01cc-2698-437b-9bfb-387f1863937c')
      end
      let(:new_person) do
        Fabricate.build(:person,
          full_name: 'Peter',
          access_token: 'a41a01cc-2698-437b-9bfb-387f1863937c'
        )
      end

      it 'updates model according to it' do
        expect do
          sync.perform({people: [new_person]})
          saved_person.refresh
        end.to change(saved_person, :full_name).from('Pete').to('Peter')
      end

    end

    it 'puts saved entities into results' do
      results = sync.perform({people: [person]}).results
      expect(results).to include people: [person]
    end

    it 'passes other data along' do
      results = sync.perform({people: [], foo: :bar}).results
      expect(results).to include foo: :bar
    end

    context 'with skip_updating' do

      let!(:person) { Fabricate(:person, full_name: 'Pete') }
      subject(:sync) { described_class[Person, skip_updating: [:full_name]] }

      it 'skips updating specified attributes' do
        person.full_name = 'Joe'
        expect do
          sync.perform({people: [person]})
          person.refresh
        end.to change(person, :full_name).from('Joe').to('Pete')
      end

    end

  end

  describe '#results' do
    let(:sync) { described_class[Room]}

    it 'returns models in case of update' do
      Fabricate(:room, id: 'A-1324')
      room = Room.new(kos_code: 'A-1324')
      results = sync.perform({rooms: [room], other_stuff: []}).results[:rooms]
      expect(results).to include room
      expect(results.first.kos_code).to eq 'A-1324'
    end

  end
end


text:
@interface PodsDummy_Pods_TDevUtils_Example : NSObject
@end
@implementation PodsDummy_Pods_TDevUtils_Example
@end


text:
void compile_and_link_test()
{
   check_result<float>(boost::math::cyl_bessel_j_prime<float>(f, f));
   check_result<double>(boost::math::cyl_bessel_j_prime<double>(d, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::cyl_bessel_j_prime<long double>(l, l));
#endif

   check_result<float>(boost::math::cyl_neumann_prime<float>(f, f));
   check_result<double>(boost::math::cyl_neumann_prime<double>(d, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::cyl_neumann_prime<long double>(l, l));
#endif

   check_result<float>(boost::math::cyl_bessel_i_prime<float>(f, f));
   check_result<double>(boost::math::cyl_bessel_i_prime<double>(d, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::cyl_bessel_i_prime<long double>(l, l));
#endif

   check_result<float>(boost::math::cyl_bessel_k_prime<float>(f, f));
   check_result<double>(boost::math::cyl_bessel_k_prime<double>(d, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::cyl_bessel_k_prime<long double>(l, l));
#endif

   check_result<float>(boost::math::sph_bessel_prime<float>(u, f));
   check_result<double>(boost::math::sph_bessel_prime<double>(u, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::sph_bessel_prime<long double>(u, l));
#endif

   check_result<float>(boost::math::sph_neumann_prime<float>(u, f));
   check_result<double>(boost::math::sph_neumann_prime<double>(u, d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::sph_neumann_prime<long double>(u, l));
#endif
}