text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var IO = require('./io');
var IndexedDevice = IO.IndexedDevice;
var SensorBase = (function (_super) {
    __extends(SensorBase, _super);
    function SensorBase(driverTypeDirName, nameConvention, targetAddress, targetDriverName) {
        _super.call(this, driverTypeDirName, nameConvention, targetAddress, targetDriverName);
    }
    return SensorBase;
}(IndexedDevice));
exports.SensorBase = SensorBase;
var Sensor = (function (_super) {
    __extends(Sensor, _super);
    function Sensor(port, driverNames) {
        _super.call(this, 'lego-sensor', 'sensor(\\d*)', port, driverNames);
    }
    Sensor.prototype.getValue = function (valueIndex) {
        return this.readNumber("value" + valueIndex);
    };
    Sensor.prototype.getFloatValue = function (valueIndex) {
        return this.getValue(valueIndex) / Math.pow(10, this.decimals);
    };
    Object.defineProperty(Sensor.prototype, "address", {
        get: function () {
            return this.readString("address");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "command", {
        set: function (value) {
            this.setString("command", value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "commands", {
        get: function () {
            return this.readStringArray("commands");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "decimals", {
        get: function () {
            return this.readNumber("decimals");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "driverName", {
        get: function () {
            return this.readString("driver_name");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "mode", {
        get: function () {
            return this.readString("mode");
        },
        set: function (value) {
            this.setString("mode", value);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "modes", {
        get: function () {
            return this.readStringArray("modes");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "numValues", {
        get: function () {
            return this.readNumber("num_values");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Sensor.prototype, "units", {
        get: function () {
            return this.readString("units");
        },
        enumerable: true,
        configurable: true
    });
    return Sensor;
}(SensorBase));
exports.Sensor = Sensor;
var TouchSensor = (function (_super) {
    __extends(TouchSensor, _super);
    function TouchSensor(port) {
        _super.call(this, port, ["lego-ev3-touch", "lego-nxt-touch"]);
    }
    Object.defineProperty(TouchSensor.prototype, "isPressed", {
        get: function () {
            this.mode = 'TOUCH';
            return Boolean(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return TouchSensor;
}(Sensor));
exports.TouchSensor = TouchSensor;
var ColorSensor = (function (_super) {
    __extends(ColorSensor, _super);
    function ColorSensor(port) {
        _super.call(this, port, ["lego-ev3-color"]);
    }
    Object.defineProperty(ColorSensor.prototype, "reflectedLightIntensity", {
        get: function () {
            this.mode = 'COL-REFLECT';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ColorSensor.prototype, "ambientLightIntensity", {
        get: function () {
            this.mode = 'COL-AMBIENT';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ColorSensor.prototype, "color", {
        get: function () {
            this.mode = 'COL-COLOR';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ColorSensor.prototype, "red", {
        get: function () {
            this.mode = 'RGB-RAW';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ColorSensor.prototype, "green", {
        get: function () {
            this.mode = 'RGB-RAW';
            return Number(this.getFloatValue(1));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ColorSensor.prototype, "blue", {
        get: function () {
            this.mode = 'RGB-RAW';
            return Number(this.getFloatValue(2));
        },
        enumerable: true,
        configurable: true
    });
    return ColorSensor;
}(Sensor));
exports.ColorSensor = ColorSensor;
var UltrasonicSensor = (function (_super) {
    __extends(UltrasonicSensor, _super);
    function UltrasonicSensor(port) {
        _super.call(this, port, ["lego-ev3-us", "lego-nxt-us"]);
    }
    Object.defineProperty(UltrasonicSensor.prototype, "distanceCentimeters", {
        get: function () {
            this.mode = 'US-DIST-CM';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UltrasonicSensor.prototype, "distanceInches", {
        get: function () {
            this.mode = 'US-DIST-IN';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UltrasonicSensor.prototype, "otherSensorPresent", {
        get: function () {
            this.mode = 'US-LISTEN';
            return Boolean(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return UltrasonicSensor;
}(Sensor));
exports.UltrasonicSensor = UltrasonicSensor;
var GyroSensor = (function (_super) {
    __extends(GyroSensor, _super);
    function GyroSensor(port) {
        _super.call(this, port, ["lego-ev3-gyro"]);
    }
    Object.defineProperty(GyroSensor.prototype, "angle", {
        get: function () {
            this.mode = 'GYRO-ANG';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GyroSensor.prototype, "rate", {
        get: function () {
            this.mode = 'GYRO-RATE';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return GyroSensor;
}(Sensor));
exports.GyroSensor = GyroSensor;
var InfraredSensor = (function (_super) {
    __extends(InfraredSensor, _super);
    function InfraredSensor(port) {
        _super.call(this, port, ["lego-ev3-ir"]);
    }
    Object.defineProperty(InfraredSensor.prototype, "proximity", {
        get: function () {
            this.mode = 'IR-PROX';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return InfraredSensor;
}(Sensor));
exports.InfraredSensor = InfraredSensor;
var SoundSensor = (function (_super) {
    __extends(SoundSensor, _super);
    function SoundSensor(port) {
        _super.call(this, port, ["lego-nxt-sound"]);
    }
    Object.defineProperty(SoundSensor.prototype, "soundPressure", {
        get: function () {
            this.mode = 'DB';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SoundSensor.prototype, "soundPressureLow", {
        get: function () {
            this.mode = 'DBA';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return SoundSensor;
}(Sensor));
exports.SoundSensor = SoundSensor;
var LightSensor = (function (_super) {
    __extends(LightSensor, _super);
    function LightSensor(port) {
        _super.call(this, port, ["lego-nxt-light"]);
    }
    Object.defineProperty(LightSensor.prototype, "reflectedLightIntensity", {
        get: function () {
            this.mode = 'REFLECT';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(LightSensor.prototype, "ambientLightIntensity", {
        get: function () {
            this.mode = 'AMBIENT';
            return Number(this.getFloatValue(0));
        },
        enumerable: true,
        configurable: true
    });
    return LightSensor;
}(Sensor));
exports.LightSensor = LightSensor;
var I2CSensor = (function (_super) {
    __extends(I2CSensor, _super);
    function I2CSensor(port, driverNames) {
        _super.call(this, port, driverNames);
    }
    Object.defineProperty(I2CSensor.prototype, "fwVersion", {
        get: function () {
            return this.readString("fw_version");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(I2CSensor.prototype, "pollMs", {
        get: function () {
            return this.readNumber("poll_ms");
        },
        set: function (value) {
            this.setNumber("poll_ms", value);
        },
        enumerable: true,
        configurable: true
    });
    return I2CSensor;
}(Sensor));
exports.I2CSensor = I2CSensor;
//# sourceMappingURL=sensors.js.map


text:
{% extends 'home/base.html' %}

{% block body %}

Website submission tutorial

Demo walkthrough

Demo data

Submit a new job

									<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
										{% csrf_token %}
										{% if error_message %}

{{ error_message }}

				                    	{% endif %}
	        							{% include 'submit/form-template.html' %}

												<button type="submit" class="btn btn-success">Submit Job</button>

									</form>

					{% if messages %}

                    			{% for message in messages %}

{{ message }}

                    			{% endfor %}

                			{% endif %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PhpInk\Nami\CoreBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ImageType
 *
 * @package PhpInk\Nami\CoreBundle\Form\Type
 */
class ImageType extends BaseType
{
    /**
     * Form type building
     *
     * @param FormBuilderInterface $builder The form builder.
     * @param array                $options The form options
     *
     * @return void
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', TextType::class, ['mapped' => false]);
        $builder->add('name', TextType::class, ['required' => true]);
        $builder->add('file', FileType::class, ['required' => true]);
        if ($options['imageType'] === 'BlockImage') {
            $builder->add('position', IntegerType::class, ['required' => true]);
        }
    }

    /**
     * Form type default options
     *
     * @param OptionsResolver $resolver The resolver.
     *
     * @return array
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver->setRequired(['imageType']);
        $resolver->addAllowedTypes('imageType', 'string');
        $resolver->setDefaults([
            'csrf_protection' => false,
            'intention' => 'image',
            'translation_domain' => 'NamiCoreBundle'
        ]);
        $resolver->setDefault('data_class', function (Options $options) {
            return ($options['isORM']) ?
                'PhpInk\Nami\CoreBundle\Model\Orm\Image\\'. $options['imageType'] :
                'PhpInk\Nami\CoreBundle\Model\Odm\Image\\'. $options['imageType'];

        });
    }
}


text:
const BASE_URL = "http://" +
               /* eslint-disable no-undef */
               __TEST_CONTENT_SERVER__.URL + ":" +
               __TEST_CONTENT_SERVER__.PORT +
               /* eslint-enable no-undef */
               "/DASH_static_SegmentTimeline/media/";
export default {
  url: BASE_URL + "multi_period_same_choices.mpd",
  transport: "dash",
};


text:
package de.cosmocode.palava.cache;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.MapMaker;
import com.google.common.util.concurrent.Callables;
import com.google.common.util.concurrent.ValueFuture;

/**
 * Default {@link ComputingCacheRegion} implementation.
 *
 * @since 3.1
 * @author Willi Schoenborn
 * @param <K> generic key type
 * @param <V> generic value type
 */
@Beta
final class DefaultComputingCacheRegion<K extends Serializable, V> extends ForwardingCacheRegion<K, V> implements
        ComputingCacheRegion<K, V> {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultComputingCacheRegion.class);

    private final CacheRegion<K, V> region;
    private final ConcurrentMap<K, Queue<ValueFuture<V>>> computations;

    DefaultComputingCacheRegion(CacheRegion<K, V> region) {
        this.region = Preconditions.checkNotNull(region, "Region");
        this.computations = new MapMaker().weakValues().makeComputingMap(new QueueProducer());
    }

    /**
     * A function which creates {@link Queue}s used to store pending
     * computations.
     *
     * @since 3.1
     * @author Willi Schoenborn
     */
    private final class QueueProducer implements Function<K, Queue<ValueFuture<V>>> {

        @Override
        public Queue<ValueFuture<V>> apply(K from) {
            return new ConcurrentLinkedQueue<ValueFuture<V>>();
        }

    }

    @Override
    protected CacheRegion<K, V> delegate() {
        return region;
    }

    @Override
    public V put(K key, V value) {
        return put(key, value, CacheExpirations.ETERNAL);
    }

    @Override
    public V put(K key, V value, CacheExpiration expiration) {
        Preconditions.checkNotNull(value, "Value");
        try {
            return computeAndPut(key, Callables.returning(value), expiration);
        } catch (ExecutionException e) {
            throw new IllegalArgumentException(e.getCause());
        }
    }

    @Override
    public V putIfAbsent(K key, V value) {
        return putIfAbsent(key, value, CacheExpirations.ETERNAL);
    }

    @Override
    public V putIfAbsent(K key, V value, CacheExpiration expiration) {
        Preconditions.checkNotNull(value, "Value");
        try {
            return computeAndPutIfAbsent(key, Callables.returning(value), expiration);
        } catch (ExecutionException e) {
            throw new IllegalArgumentException(e.getCause());
        }
    }

    @Override
    public V computeAndPut(K key, Callable<? extends V> computation) throws ExecutionException {
        return computeAndPut(key, computation, CacheExpirations.ETERNAL);
    }

    @Override
    public V computeAndPut(K key, Callable<? extends V> computation, CacheExpiration expiration)
        throws ExecutionException {

        Preconditions.checkNotNull(key, "Key");
        Preconditions.checkNotNull(computation, "Computation");
        Preconditions.checkNotNull(expiration, "Expiration");

        final Collection<ValueFuture<V>> futures = computations.get(key);
        final ValueFuture<V> future = ValueFuture.create();

        // it's important to do this asap, to allow other callers
        // to wait on read instead of starting the same computation
        futures.add(future);

        try {
            LOG.trace("Computing value for key '{}' using {}", key, computation);
            final V value = computation.call();

            if (future.isCancelled()) {
                LOG.warn("{} has been cancelled", future);
            } else if (future.isDone()) {
                LOG.trace("Another computation was faster and already computed a value for key '{}'", key);
            } else {
                LOG.trace("Computed value '{}' for key '{}'", value, key);
                future.set(value);
                for (ValueFuture<V> other : futures) {
                    if (other == future) {
                        // every computation after this is newer
                        break;
                    } else if (other.isDone()) {
                        LOG.trace("Skipping finished computation: {}", other);
                        continue;
                    } else {
                        // make older and still running computations use my
                        // computed value
                        LOG.trace("Setting faster computed value '{}' on {}", value, other);
                        other.set(value);
                    }
                }
                LOG.trace("Storing '{}' to '{}' in underlying store", key, value);
                region.put(key, value, expiration);
            }

            final V returned = future.get();
            if (returned == null) {
                LOG.trace("Key '{}' has been removed during computation, returning computed value '{}'", key, value);
                return value;
            } else {
                LOG.trace("Returning value '{}' for key '{}'", returned, key);
                return returned;
            }
        } catch (ExecutionException e) {
            LOG.warn("Exception during {}.call()", computation);
            future.setException(e.getCause());
            throw e;
            /* CHECKSTYLE:OFF */
        } catch (Exception e) {
            /* CHECKSTYLE:ON */
            LOG.warn("Exception during {}.call()", computation);
            future.setException(e);
            throw new ExecutionException(e);
        } finally {
            futures.remove(future);
        }

    }

    @Override
    public V computeAndPutIfAbsent(K key, Callable<? extends V> computation) throws ExecutionException {
        return computeAndPutIfAbsent(key, computation, CacheExpirations.ETERNAL);
    }

    @Override
    public V computeAndPutIfAbsent(K key, Callable<? extends V> computation, CacheExpiration expiration)
        throws ExecutionException {

        Preconditions.checkNotNull(key, "Key");
        Preconditions.checkNotNull(computation, "Computation");
        Preconditions.checkNotNull(expiration, "Expiration");

        final V cached = get(key);

        if (cached == null) {
            LOG.trace("No pre-computed value for key '{}' exists, computing...", key);
            return computeAndPut(key, computation, expiration);
        } else {
            LOG.trace("Read pre-computed value for key '{}'", key);
            return cached;
        }
    }

    @Override
    public V get(Object key) {
        Preconditions.checkNotNull(key, "Key");

        final V cached = region.get(key);

        if (cached == null) {
            LOG.trace("No pre-computed value for key '{}' exists, looking for computations", key);
            final Future<V> future = computations.get(key).peek();

            if (future == null) {
                LOG.trace("No computation for key '{}', returning null", key);
                return null;
            } else {
                try {
                    LOG.trace("Waiting for {} to compute value for key '{}'", future, key);
                    return future.get();
                } catch (CancellationException e) {
                    LOG.debug("Computation for {} has been cancelled during read", key);
                    return null;
                } catch (InterruptedException e) {
                    LOG.warn("Thread has been interrupted during wait for key '{}'", key);
                    return null;
                } catch (ExecutionException e) {
                    LOG.warn("Exception while waiting for " + future, e.getCause());
                    throw Throwables.propagate(e.getCause());
                }
            }
        } else {
            LOG.trace("Read pre-computed value for key '{}' from underlying cache", key);
            return cached;
        }
    }

    @Override
    public V replace(K key, V value) {
        Preconditions.checkNotNull(key, "Key");
        return containsKey(key) ? put(key, value) : null;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Preconditions.checkNotNull(key, "Key");

        final V cached = region.get(key);
        if (cached == null) {
            return false;
        } else if (cached.equals(oldValue)) {
            put(key, newValue);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public V remove(Object key) {
        Preconditions.checkNotNull(key, "Key");

        final Queue<ValueFuture<V>> futures = computations.get(key);

        if (futures.isEmpty()) {
            LOG.trace("Removing key '{}' from underlying cache", key);
            // no running computation, the easy part
            return region.remove(key);
        } else {
            LOG.trace("Forcing all running computations for key '{}' to return null", key);
            while (true) {
                // get and remove in one shot
                final ValueFuture<V> future = futures.poll();
                if (future == null) {
                    // no running computation left
                    // weak values should take care of empty queue
                    break;
                } else if (future.isDone()) {
                    LOG.trace("{} finished during remove", future);
                } else {
                    // return null to callers waiting on Future#get()
                    future.set(null);
                }
            }
            // make sure the underlying cache removes any pre-computed value
            return region.remove(key);
        }
    }

    @Override
    public boolean remove(Object key, Object value) {
        final V cached = region.get(key);
        if (cached == null) {
            return false;
        } else if (cached.equals(value)) {
            remove(key);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean removeIf(Predicate<? super K> predicate) {
        boolean removedAny = false;
        for (K key : keySet()) {
            if (predicate.apply(key)) {
                remove(key);
                removedAny = true;
            }
        }
        return removedAny;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return Collections.unmodifiableSet(entrySet());
    }

    @Override
    public Set<K> keySet() {
        return Collections.unmodifiableSet(keySet());
    }

    @Override
    public Collection<V> values() {
        return Collections.unmodifiableCollection(values());
    }

    @Override
    public void clear() {
        // force every pending and running computation to return null on waiting
        // callers
        for (K key : computations.keySet()) {
            remove(key);
        }
        region.clear();
    }

}


text:
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace FilterLists.Directory.Infrastructure.Migrations.Migrations
{
    public partial class _2904 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.InsertData(
                table: "filter_lists",
                columns: new[] { "id", "chat_url", "description", "donate_url", "email_address", "forum_url", "home_url", "is_approved", "issues_url", "license_id", "name", "onion_url", "policy_url", "submission_url" },
                values: new object[] { 2586L, null, "stops traffic associated with domains known to be from the surveillance-for-hire firm Cytrox and related entities", null, null, null, "https://github.com/twcau/AdblockRules/", true, "https://github.com/twcau/AdblockRules/issues", 28L, "CytroxList", null, null, null });

            migrationBuilder.InsertData(
                table: "maintainers",
                columns: new[] { "id", "email_address", "is_approved", "name", "twitter_handle", "url" },
                values: new object[] { 178L, null, true, "Michael H", null, "https://github.com/twcau" });

            migrationBuilder.InsertData(
                table: "filter_list_maintainers",
                columns: new[] { "filter_list_id", "maintainer_id" },
                values: new object[] { 2586L, 178L });

            migrationBuilder.InsertData(
                table: "filter_list_syntaxes",
                columns: new[] { "filter_list_id", "syntax_id" },
                values: new object[] { 2586L, 3L });

            migrationBuilder.InsertData(
                table: "filter_list_view_urls",
                columns: new[] { "filter_list_id", "id", "primariness", "url" },
                values: new object[] { 2586L, 2851L, (short)1, "https://raw.githubusercontent.com/twcau/AdblockRules/master/CytroxList" });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DeleteData(
                table: "filter_list_maintainers",
                keyColumns: new[] { "filter_list_id", "maintainer_id" },
                keyValues: new object[] { 2586L, 178L });

            migrationBuilder.DeleteData(
                table: "filter_list_syntaxes",
                keyColumns: new[] { "filter_list_id", "syntax_id" },
                keyValues: new object[] { 2586L, 3L });

            migrationBuilder.DeleteData(
                table: "filter_list_view_urls",
                keyColumns: new[] { "filter_list_id", "id" },
                keyValues: new object[] { 2586L, 2851L });

            migrationBuilder.DeleteData(
                table: "filter_lists",
                keyColumn: "id",
                keyValue: 2586L);

            migrationBuilder.DeleteData(
                table: "maintainers",
                keyColumn: "id",
                keyValue: 178L);
        }
    }
}


text:
require 'spec_helper'

describe Hindsight do
  let(:subject) { Document.create }

  describe '#new_version' do
    it 'returns a new version' do
      new_version = subject.new_version
      expect(new_version).to be_a(subject.class)
      expect(new_version).not_to eq(subject)
    end

    it 'increments the version number' do
      expect(subject.new_version.version).to be(subject.version + 1)
    end

    it 'does not affect the version of the receiver' do
      expect { subject.new_version }.not_to change { subject.version }
    end

    it 'accepts attributes to assign to the new verson' do
      expect(subject.new_version(:body => 'changed').body).to eq('changed')
    end

    it 'accepts a block and yields a new version' do
      subject.new_version {|v| expect(v.version).to eq(2) }
    end

    it 'allows attribute changes to be made without affecting the original version' do
      subject.update_attributes(:body => 'original text')
      expect { subject.new_version(:body => 'new text') }.not_to change { subject.body }
    end

    it 'associates the version with the original record' do
      new_version = subject.new_version
      expect(new_version.versions.first).to eq(subject)
    end

    it 'returns false if the record is invalid' do
      subject.class.any_instance.stub(:valid? => false)
      expect(subject.new_version).to be_falsey
    end

    it 'does not create a new version if the record is invalid' do
      subject.class.any_instance.stub(:valid? => false)
      expect { subject.new_version }.not_to change { subject.versions.count }
    end

    it 'runs save callbacks on the new version' do
      mock_callback(Document, :after_save) { |record| record.body = 'ran callbacks' }
      expect(subject.new_version.body).to eq('ran callbacks')
    end

    it 'does not run save callbacks on the current instance' do
      mock_callback(Document, :after_save) { |record| record.body = 'ran callbacks' }
      subject.new_version
      expect(subject.body).not_to eq('ran callbacks')
    end
  end

  describe '#create!' do
    it 'starts the version number at 1' do
      expect(subject.version).to eq(1)
    end
  end

  describe '#save' do
    it 'changes the id to that of the new version' do
      subject.save
      expect(subject.id).to eq(subject.versions.last.id)
    end

    it 'creates a new version record' do
      expect { subject.save }.to change { subject.class.count }.from(1).to(2)
    end

    it 'raises an exception if the record is not a latest_version' do
      subject.new_version
      subject.body = 'changed'
      expect { subject.save }.to raise_exception(Hindsight::ReadOnlyVersion)
    end

    it 'returns false if the record is invalid' do
      subject.class.any_instance.stub(:valid? => false)
      expect(subject.save).to be_falsey
    end

    it 'does not create a new version if the record is invalid' do
      subject.class.any_instance.stub(:valid? => false)
      expect { subject.save }.not_to change { subject.versions.count }
    end

    it 'runs save callbacks on the current instance' do
      mock_callback(Document, :before_save) { |record| record.body = 'ran callbacks' }
      subject.save
      expect(subject.body).to eq('ran callbacks')
    end
  end

  describe '#update_attributes' do
    context 'setting attributes' do
      it 'creates new versions' do
        expect { subject.update_attributes!(:body => 'changed') }.to change { subject.versions.count }.from(1).to(2)
      end

      it 'replaces self with the new version' do
        expect { subject.update_attributes!(:body => 'changed') }.to change { subject.version }.from(1).to(2)
      end
    end
  end

  describe '#become_current' do
    let(:new_version) { subject.new_version(:body => 'changed') }

    it 'updates id to the latest version id' do
      expect { subject.become_current }.to change { subject.id }.to(new_version.id)
    end

    it 'updates attributes to those of the latest version' do
      expect { subject.become_current }.to change { subject.body }.to(new_version.body)
    end
  end
end


text:
package net.study.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.NoSuchElementException;

@ControllerAdvice
public class ExceptionHandlerControllerAdvice {

    private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerControllerAdvice.class);

    @ExceptionHandler(NoSuchElementException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleNoSuchElementException(NoSuchElementException e) {
        return e.getMessage();
    }

}


text:
#include <thrift/windows/OverlappedSubmissionThread.h>
#include <thrift/transport/TTransportException.h>
#include <boost/noncopyable.hpp>
#include <boost/scope_exit.hpp>
#include <process.h>

namespace apache {
namespace thrift {
namespace transport {

TOverlappedWorkItem::TOverlappedWorkItem()
  : SLIST_ENTRY(),
    action(UNKNOWN),
    h(INVALID_HANDLE_VALUE),
    buffer(NULL),
    buffer_len(0),
    overlap(),
    last_error(0),
    success(TRUE) {
}

void TOverlappedWorkItem::reset(uint8_t* buf, uint32_t len, HANDLE event) {
  memset(&overlap, 0, sizeof(overlap));
  overlap.hEvent = event;
  buffer = buf;
  buffer_len = len;
  last_error = 0;
  success = FALSE;
}

uint32_t TOverlappedWorkItem::overlappedResults(bool signal_failure) {
  DWORD bytes = 0;
  BOOL result = ::GetOverlappedResult(h, &overlap, &bytes, TRUE);
  if (signal_failure && !result) // get overlapped error case
  {
    GlobalOutput.perror("TPipe ::GetOverlappedResult errored GLE=", ::GetLastError());
    throw TTransportException(TTransportException::UNKNOWN, "TPipe: GetOverlappedResult failed");
  }
  return bytes;
}

bool TOverlappedWorkItem::process() {
  BOOST_SCOPE_EXIT((&doneSubmittingEvent)) { SetEvent(doneSubmittingEvent.h); }
  BOOST_SCOPE_EXIT_END

  switch (action) {
  case (CONNECT):
    success = ::ConnectNamedPipe(h, &overlap);
    if (success == FALSE)
      last_error = ::GetLastError();
    return true;
  case (READ):
    success = ::ReadFile(h, buffer, buffer_len, NULL, &overlap);
    if (success == FALSE)
      last_error = ::GetLastError();
    return true;
  case (CANCELIO):
    success = ::CancelIo(h);
    if (success == FALSE)
      last_error = ::GetLastError();
    return true;
  case (STOP):
  default:
    return false;
  }
}

void TOverlappedSubmissionThread::addWorkItem(TOverlappedWorkItem* item) {
  InterlockedPushEntrySList(&workList_, item);
  SetEvent(workAvailableEvent_.h);
  WaitForSingleObject(item->doneSubmittingEvent.h, INFINITE);
}

TOverlappedSubmissionThread* TOverlappedSubmissionThread::acquire_instance() {
  TAutoCrit lock(instanceGuard_);
  if (instance_ == NULL) {
    assert(instanceRefCount_ == 0);
    instance_ = new TOverlappedSubmissionThread;
  }
  ++instanceRefCount_;
  return instance_;
}
void TOverlappedSubmissionThread::release_instance() {
  TAutoCrit lock(instanceGuard_);
  if (--instanceRefCount_ == 0) {
    delete instance_;
    instance_ = NULL;
  }
}

TOverlappedSubmissionThread::TOverlappedSubmissionThread() {
  stopItem_.action = TOverlappedWorkItem::STOP;

  InitializeSListHead(&workList_);
  thread_ = (HANDLE)_beginthreadex(NULL, 0, thread_proc, this, 0, NULL);
  if (thread_ == 0) {
    GlobalOutput.perror("TOverlappedSubmissionThread unable to create thread, errno=", errno);
    throw TTransportException(TTransportException::NOT_OPEN,
                              " TOverlappedSubmissionThread unable to create thread");
  }
}

TOverlappedSubmissionThread::~TOverlappedSubmissionThread() {
  addWorkItem(&stopItem_);
  ::WaitForSingleObject(thread_, INFINITE);
  CloseHandle(thread_);
}

void TOverlappedSubmissionThread::run() {
  for (;;) {
    WaitForSingleObject(workAvailableEvent_.h, INFINITE);
    // todo check result
    SLIST_ENTRY* entry = NULL;
    while ((entry = InterlockedPopEntrySList(&workList_)) != NULL) {
      TOverlappedWorkItem& item = *static_cast<TOverlappedWorkItem*>(entry);
      if (!item.process())
        return;
    }
  }
}

unsigned __stdcall TOverlappedSubmissionThread::thread_proc(void* addr) {
  static_cast<TOverlappedSubmissionThread*>(addr)->run();
  return 0;
}

TCriticalSection TOverlappedSubmissionThread::instanceGuard_;
TOverlappedSubmissionThread* TOverlappedSubmissionThread::instance_;
uint32_t TOverlappedSubmissionThread::instanceRefCount_ = 0;
}
}
} // apach::thrift::transport


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Instructor Schema
 */
var InstructorSchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Please fill Instructor name',
    trim: true
  },
  platform: {
    type: String,
    default: 'Random'
  },
  courses: {
    type: Array,
    default: []
  },
  bio: {
    type: String,
    default: "We don't have much info."
  },
  image: {
    type: String,
    default: "Default Image URL."
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Instructor', InstructorSchema);


text:
(function(){window.pagespeed = window.pagespeed || {};
var pagespeed = window.pagespeed;
pagespeed.DeferIframe = function() {
};
pagespeed.DeferIframe.prototype.convertToIframe = function() {
  var a = document.getElementsByTagName("pagespeed_iframe");
  if (0 < a.length) {
    for (var a = a[0], d = document.createElement("iframe"), b = 0, c = a.attributes, e = c.length;b < e;++b) {
      d.setAttribute(c[b].name, c[b].value);
    }
    a.parentNode.replaceChild(d, a);
  }
};
pagespeed.DeferIframe.prototype.convertToIframe = pagespeed.DeferIframe.prototype.convertToIframe;
pagespeed.deferIframeInit = function() {
  var a = new pagespeed.DeferIframe;
  pagespeed.deferIframe = a;
};
pagespeed.deferIframeInit = pagespeed.deferIframeInit;
})();


text:
@(templateForm: Form[MailTemplate], user: User, id: Long, mailTemplates: Map[String,String])

@import helper._
@import bootstrap._

@main("", user) {

Archivist Tasks > Mail Templates >Edit mail template @templateForm("name").value

View

	   @if(user.hasRole("sys_admin") || user.hasRole("archivist")) {

Edit

	   }

    @warningmessage(flash)

    @if(templateForm.hasErrors) {

				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				@for(entry <- templateForm.errors.entrySet){
					@for(error <- entry.getValue){
						@error.message

					}
				}

	}

   	@helper.form(action=routes.MailTemplateController.update(id)) {
		<input type="hidden" name="id" value="@id">

					@inputText(templateForm("name"),
						'_label -> "Name",
					    'id -> "title",
					    'class -> "form-control",
					    'placeholder -> "Name"
					)(FieldConstructor(genericMandatoryInput.f), lang)

					@select(field = templateForm("ttype"), options = options(mailTemplates),
			                args =
			                'class -> "form-control",
			                '_label -> "Type",
			                '_showConstraints -> false
		            )(FieldConstructor(genericInput.f), lang)

					@inputText(templateForm("subject"),
						'_label -> "Subject",
					    'id -> "subject",
					    'class -> "form-control"
					)(FieldConstructor(genericInput.f), lang)

					@inputText(templateForm("fromEmail"),
						'_label -> "From E-mail",
						'type -> "email",
					    'id -> "fromEmail",
					    'class -> "form-control"
					)(FieldConstructor(genericMandatoryInput.f), lang)

					@inputText(templateForm("placeHolders"),
						'_label -> "Place Holders (Comma separated)",
					    'id -> "placeHolders",
					    'class -> "form-control"
					)(FieldConstructor(genericMandatoryInput.f), lang)

					@helper.checkbox(templateForm("defaultEmail"),
						args =
						'_label -> "Default Email"
					)(FieldConstructor(genericInput.f), lang)

					Template Body

				    	@if(user.hasRole("sys_admin")) {
							@textarea(field = templateForm("text"),
				 				args = 'rows -> 1, 'cols -> 100,
								'_label -> null,
								'id -> "text",
								'class -> "form-control"
							)(FieldConstructor(genericInput.f), lang)
						} else {
							<textarea class="form-control" name="text" id="text" cols="100" rows="20" readonly>@templateForm("text").value</textarea>
						}

		@if(user.hasRole("sys_admin") || user.hasRole("archivist")) {

						<button type="submit" class="btn btn-primary" name="action" value="save">Save</button>
						<button type="submit" class="btn btn-primary" name="action" value="delete" onclick="return confirm('Are you sure?');">Delete</button>

		}
	}
}


text:
from foam.sfa.util.method import Method

from foam.sfa.trust.credential import Credential

from foam.sfa.util.parameter import Parameter, Mixed

class Register(Method):
    """
    Register an object with the registry. In addition to being stored in the
    SFA database, the appropriate records will also be created in the
    PLC databases

    @param cred credential string
    @param record_dict dictionary containing record fields

    @return gid string representation
    """

    interfaces = ['registry']

    accepts = [
        Parameter(dict, "Record dictionary containing record fields"),
        Mixed(Parameter(str, "Credential string"),
              Parameter(type([str]), "List of credentials")),
        ]

    returns = Parameter(int, "String representation of gid object")

    def call(self, record, creds):
        # validate cred
        valid_creds = self.api.auth.checkCredentials(creds, 'register')

        # verify permissions
        hrn = record.get('hrn', '')
        self.api.auth.verify_object_permission(hrn)

        #log the call
        origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn()
        self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, hrn, self.name))

        return self.api.manager.Register(self.api, record)


text:
[![Build Status](https://travis-ci.org/roadmapper/DeviceID.svg?branch=master)](https://travis-ci.org/roadmapper/DeviceID)

An Android application to acquire cellular data about the device and determine what networks the device can connect to.

The concept for this application came from traveling to different countries guessing if my phone would work when I popped a new SIM inside the phone.


text:
<?php //require('../config/connect.php');?>

<?php
function getcount($db_con, $tblname)
{
	$query = "SELECT COUNT(*) FROM ".$tblname;
	$count = mysqli_fetch_assoc(mysqli_query($db_con, $query));
	$data  = $count['COUNT(*)'];
	return $data;
}

?>


text:
from swgpy.object import *

def create(kernel):
	result = Creature()

	result.template = "object/mobile/shared_gurreck_hue.iff"
	result.attribute_template_id = 9
	result.stfName("monster_name","gurreck")

	#### BEGIN MODIFICATIONS ####
	result.setStringAttribute("radial_filename", "radials/player_pet.py")
	result.options_mask = 0x100
	result.pvp_status = PVPSTATUS.PvPStatus_None
	####  END MODIFICATIONS  ####

	return result


text:
package com.google.api.ads.dfp.jaxws.v201602;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             A base rate applied to a {@link Product}.
 *
 *
 *
Java class for ProductBaseRate complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ProductBaseRate">
 *   <complexContent>
 *     <extension base="{https://www.google.com/apis/ads/publisher/v201602}BaseRate">
 *       <sequence>
 *         <element name="productId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="rate" type="{https://www.google.com/apis/ads/publisher/v201602}Money" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ProductBaseRate", propOrder = {
    "productId",
    "rate"
})
public class ProductBaseRate
    extends BaseRate
{

    protected Long productId;
    protected Money rate;

    /**
     * Gets the value of the productId property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getProductId() {
        return productId;
    }

    /**
     * Sets the value of the productId property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setProductId(Long value) {
        this.productId = value;
    }

    /**
     * Gets the value of the rate property.
     *
     * @return
     *     possible object is
     *     {@link Money }
     *
     */
    public Money getRate() {
        return rate;
    }

    /**
     * Sets the value of the rate property.
     *
     * @param value
     *     allowed object is
     *     {@link Money }
     *
     */
    public void setRate(Money value) {
        this.rate = value;
    }

}


text:
package io.searchbox.core;

import io.searchbox.common.AbstractIntegrationTest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.ReindexPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * @author Lior Knaany
 */
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 1)
public class UpdateByQueryIntegrationTest extends AbstractIntegrationTest {

    private static final String INDEX = "twitter";
    private static final String TYPE = "tweet";

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        final ArrayList<Class<? extends Plugin>> plugins = new ArrayList<>(super.nodePlugins());
        plugins.add(ReindexPlugin.class);
        return plugins;
    }

    @Override
    protected Settings nodeSettings(int nodeOrdinal) {
        final Settings.Builder builder = Settings.builder().put(super.nodeSettings(nodeOrdinal));
        return builder
                .put(super.nodeSettings(nodeOrdinal))
                .put("script.allowed_types", "inline")
                .build();
    }

    @Test
    public void update() throws IOException, InterruptedException {

        // create a tweet
        assertTrue(index(INDEX, TYPE, "1", "{\"user\":\"lior\",\"num\":1}").getResult().equals(DocWriteResponse.Result.CREATED));
        assertTrue(index(INDEX, TYPE, "2", "{\"user\":\"kimchy\",\"num\":2}").getResult().equals(DocWriteResponse.Result.CREATED));

       refresh();
       ensureSearchable(INDEX);

        // run the search and update
        final BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("user", "lior"));
        final String script = "ctx._source.user = ctx._source.user + '_updated';";

        final XContentBuilder xContentBuilder = jsonBuilder()
                .startObject()
                .field("query", queryBuilder)
                .startObject("script")
                .field("inline", script)
                .endObject()
                .endObject();

        xContentBuilder.flush();

        final String payload = ((ByteArrayOutputStream) xContentBuilder.getOutputStream()).toString("UTF-8");

        UpdateByQuery updateByQuery = new UpdateByQuery.Builder(payload)
                .addIndex(INDEX)
                .addType(TYPE)
                .build();

        UpdateByQueryResult result = client.execute(updateByQuery);

        // Checks
        assertTrue(result.getErrorMessage(), result.isSucceeded());

        assertFalse(result.didTimeOut());
        assertEquals(0, result.getConflictsCount());
        assertTrue(result.getMillisTaken() > 0);
        assertEquals(1, result.getUpdatedCount());
        assertEquals(0, result.getRetryCount());
        assertEquals(0, result.getBulkRetryCount());
        assertEquals(0, result.getSearchRetryCount());
        assertEquals(0, result.getNoopCount());
        assertEquals(0, result.getFailures().size());
    }

}


text:
<?php
// +----------------------------------------------------------------------
// | Twocola PHP Engine [ DO IT EASY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2017 Twocola Studio All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Jokin <327928971@qq.com>
// +----------------------------------------------------------------------
/**
* 存储核心
* Version 1.3.0
**/
namespace TUnit\Storage;
class StorageCore{
	/**
	 * 判断文件是否存在
	 * @param  string $filename
	 * @return boolean
	**/
	static public function FileExist($filename){
		return is_file($filename);
	}
	/**
	 * 读入文件
	 * @param  string $filename
	 * @return boolean
	**/
	static public function Read($filename){
		// 判断是否可度
		if(!is_readable($filename)) return false;
		if( !self::FileExist($filename) ) return false ;
		$content = file_get_contents($filename) ;
		return $content;
	}
	/**
	 * 创建并写入文件
	 * @param  string $filename
	 * @param  string $content
	 * @return boolean
	**/
	static public function CreateSave($filename,$content){
		if( is_file($filename) ) return false ;	//文件已存在
		$dir = dirname($filename);
		if( !is_dir($dir) ) {
			if ( !self::CreateFolder($dir) ) return false;
		}
		if( file_put_contents($filename,$content) ){
			chmod($filename,0777);
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 覆盖存储文件
	 * @param  string $filename
	 * @param  string $content
	 * @return boolean
	**/
	static public function Put($filename,$content){
		return file_put_contents($filename,$content);
	}
	/**
	 * 在文件头部存储
	 * @param  string $filename
	 * @param  string $content
	 * @return boolean
	**/
	static private function SaveEnd($filename,$content){
		$position="a";
		if(self::FileExist($filename)){
			$handle = fopen($filename,$position);
			if(!$handle){
				return false;
			}
			$result = fwrite($handle,$content);
			fclose($handle);
			return $result;
		}else{
			return false;
		}
	}
	/**
	 * 在文件尾部存储
	 * @param  string $filename
	 * @param  string $content
	 * @return boolean
	**/
	static private function SaveHead($filename,$content){
		$position="h";
		if(self::FileExist($filename)){
			$handle = fopen($filename,$position);
			if(!$handle){
				return false;
			}
			$result = fwrite($handle,$content);
			fclose($handle);
			return $result;
		}else{
			return false;
		}
	}
	/**
	 * 删除文件
	 * @param  string $filename
	 * @return boolean
	**/
	static public function DelFile($filename){
		return is_file($filename) ? unlink($filename) : false ;
	}

	/**
	 * 判断文件夹是否存在
	 * @param  string $name
	 * @return boolean
	**/
	static public function FolderExist($name){
		return is_dir($name);
	}

	/**
	 * 判断文件夹是否为空
	 * @param  string $name
	 * @return boolean
	**/
	static public function FolderEmpty($name){
		$name = $name;
		if(self::FolderExist($name)){
			$handle = opendir($name);
			$i = 0;
			while(readdir($handle)){
				$i++;
			}
			closedir($handle);
			if($i>2){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
	/**
	 * 创建文件夹
	 * @param  string $name
	 * @return boolean
	**/
	static public function CreateFolder($name){
		if( mkdir($name,0777,true) ){
			// 创建成功则修改权限并返回true
			chmod($name,0777);
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 创建空文件
	 * @param  string $filename
	 * @return bool
	**/
	static public function CreateEmptyFile($filename){
		self::CreateSave($filename,"");
	}
	/**
	* 删除目录及目录下所有文件或删除指定文件
	* @param string $path   待删除目录路径
	* @param int $delDir 是否删除目录,1或true删除目录,0或false则只删除文件保留目录(包含子目录)
	* @return bool 返回删除状态
	**/
	static public function DelDir($path, $delDir = true) {
    $handle = opendir($path);
    if ($handle) {
      while (false !== ( $item = readdir($handle) )) {
        if ($item != "." && $item != "..")
        is_dir("$path/$item") ? self::DelDir("$path/$item", $delDir) : unlink("$path/$item");
      }
      closedir($handle);
      if ($delDir)
        return rmdir($path);
    }else {
      if (file_exists($path)) {
        return unlink($path);
      } else {
        return false;
      }
    }
	}

}
?>


text:
/*global describe, it, browser */

describe('tabset', function () {
    'use strict';

    function tabsetTest(screenWidth) {
        return browser
            .setupTest('/tabset/fixtures/test.full.html', screenWidth)
            .moveToObject('#screenshot-tabset-open-add li:nth-child(2) a')
            .compareScreenshot({
                screenshotName: 'tabset',
                selector: '#screenshot-tabset-all',
                checkAccessibility: true
            });
    }

    function verticalTabsetTest(screenWidth, groups, active, name) {
        var selector = groups ? '#screenshot-vertical-tabset-groups' : '#screenshot-vertical-tabset-no-groups';
        if (!active) {
            selector += '-inactive';
        }
        return browser
            .setupTest('/tabset/fixtures/test.full.html', screenWidth)
            .compareScreenshot({
                screenshotName: 'vertical_tabset_' + name,
                selector: selector,
                checkAccessibility: true
            });
    }

    it('should match the baseline tabset screenshot', function () {
        return tabsetTest(1280);
    });

    it('should match the baseline tabset screenshot when close button is focused', function () {
        return browser.setupTest('/tabset/fixtures/test.full.html')
            .focusElement('.bb-test-close-focus')
            .compareScreenshot({
                screenshotName: 'tabset_close_focus',
                selector: '#screenshot-tabset-all',
                checkAccessibility: true
            });
    });

    it('should match the baseline tabset screenshot when open button is focused', function () {
        return browser.setupTest('/tabset/fixtures/test.full.html')
            .focusElement('.bb-tab-button-open')
            .compareScreenshot({
                screenshotName: 'tabset_open_focus',
                selector: '#screenshot-tabset-all',
                checkAccessibility: true
            });
    });

    it('should match the baseline tabset screenshot when add button is focused', function () {
        return browser.setupTest('/tabset/fixtures/test.full.html')
            .focusElement('.bb-tab-button-add')
            .compareScreenshot({
                screenshotName: 'tabset_add_focus',
                selector: '#screenshot-tabset-all',
                checkAccessibility: true
            });
    });

    it('should match the baseline tabset screenshot on small screens', function () {
        return tabsetTest(480);
    });

    it('should match the baseline vertical tabset screenshot', function () {
        return verticalTabsetTest(1280, true, true, 'group');
    });

    it('should match the baseline vertical screenshot on small screens', function () {
        return verticalTabsetTest(480, true, true, 'group');
    });

    it('should match the baseline vertical tabset without groups screenshot', function () {
        return verticalTabsetTest(1280, false, true, 'no_group');
    });

    it('should match the baseline vertical tabset without groups screenshot on small screens', function () {
        return verticalTabsetTest(480, false, true, 'no_group');
    });

    it('should match the baseline vertical tabset screenshot', function () {
        return verticalTabsetTest(1280, true, true, 'group_inactive');
    });

    it('should match the baseline vertical screenshot on small screens', function () {
        return verticalTabsetTest(480, true, true, 'group_inactive');
    });

    it('should match the baseline vertical tabset without groups screenshot', function () {
        return verticalTabsetTest(1280, false, true, 'no_group_inactive');
    });

    it('should match the baseline vertical tabset without groups screenshot on small screens', function () {
        return verticalTabsetTest(480, false, true, 'no_group_inactive');
    });
});


text:
from __future__ import print_function
import os
import sys
import socket
import datetime
import time
import akumulid_test_tools as att
import json
try:
    from urllib2 import urlopen
except ImportError:
    from urllib import urlopen
import traceback
import itertools
import math

HOST = '127.0.0.1'
TCPPORT = 8282
HTTPPORT = 8181

def test_select(metric_name, exp_tags, dtstart, delta, N):
    """Read all series one by one in backward direction.
    All data should be received as expected."""

    for tags in exp_tags:
        begin = dtstart + delta*(N-1)
        end = dtstart
        query_params = {
            "output": { "format":  "csv" },
            "where": tags
        }
        query = att.makequery(metric_name, begin, end, **query_params)
        queryurl = "http://{0}:{1}/api/query".format(HOST, HTTPPORT)
        response = urlopen(queryurl, json.dumps(query))

        exp_ts = None
        print("Test - read all data in backward direction")
        iterations = 0
        for line in response:
            try:
                columns = line.split(',')
                timestamp = att.parse_timestamp(columns[1].strip())
                if exp_ts is None:
                    exp_ts = timestamp

                if exp_ts and exp_ts != timestamp:
                    raise ValueError("Invalid timestamp at {0}, expected {1}, actual {2}".format(iterations, exp_ts, timestamp))

                exp_ts -= delta
                iterations += 1
            except ValueError as err:
                print(err)
                raise

        # Check that we received all values
        if iterations == 0:
            raise ValueError("Unable to read any data")

    print("Test passed")

def main(path):
    if not os.path.exists(path):
        print("Path {0} doesn't exists".format(path))
        sys.exit(1)

    akumulid = att.Akumulid(path)
    # Reset database
    akumulid.delete_database()
    akumulid.create_database()
    # start ./akumulid server
    print("Starting server...")
    akumulid.serve()
    time.sleep(5)

    nmsgs = 100000
    tags = [
        {"tag3": "D", "tag2": "B", "tag1": "A"},
        {"tag3": "E", "tag2": "B", "tag1": "A"},
        {"tag3": "F", "tag2": "B", "tag1": "A"},
        {"tag3": "G", "tag2": "B", "tag1": "A"},
        {"tag3": "H", "tag2": "B", "tag1": "A"},
        {"tag3": "D", "tag2": "C", "tag1": "A"},
        {"tag3": "E", "tag2": "C", "tag1": "A"},
        {"tag3": "F", "tag2": "C", "tag1": "A"},
        {"tag3": "G", "tag2": "C", "tag1": "A"},
        {"tag3": "H", "tag2": "C", "tag1": "A"},
    ]

    dt = datetime.datetime.utcnow() - (datetime.timedelta(milliseconds=1)*nmsgs)
    delta = datetime.timedelta(milliseconds=1)
    try:
        chan1 = att.TCPChan(HOST, TCPPORT)
        chan2 = att.TCPChan(HOST, TCPPORT)
        chan3 = att.TCPChan(HOST, TCPPORT)
        chan4 = att.TCPChan(HOST, TCPPORT)

        print("Sending {0} messages through TCP...".format(nmsgs))

        # Send a lot of other messages to ensure that the raer set is on disk
        bulk1 = att.generate_messages3(dt, delta, 10000, 'bulk1', tags)
        bulk2 = att.generate_messages3(dt, delta, 10000, 'bulk2', tags)
        bulk3 = att.generate_messages3(dt, delta, 10000, 'bulk3', tags)
        bulk4 = att.generate_messages3(dt, delta, 10000, 'bulk4', tags)
        streams = itertools.izip(bulk1, bulk2, bulk3, bulk4)
        for it1, it2, it3, it4 in streams:
            chan1.send(it1)
            chan2.send(it2)
            chan3.send(it3)
            chan4.send(it4)

        chan1.close()
        chan2.close()
        chan3.close()
        chan4.close()

        time.sleep(1)

        # kill process
        akumulid.terminate()
    except:
        traceback.print_exc()
        sys.exit(1)
    finally:
        print("Server terminated")

    print("Starting server...")
    akumulid.serve()
    time.sleep(5)
    print("Server started")
    try:
        test_select('bulk1', tags, dt, delta, 10000)
        test_select('bulk2', tags, dt, delta, 10000)
        test_select('bulk3', tags, dt, delta, 10000)
        test_select('bulk4', tags, dt, delta, 10000)
    finally:
        print("Stopping server...")
        akumulid.stop()
        time.sleep(5)

if __name__ == '__main__':
    print(' '.join(sys.argv))
    if len(sys.argv) < 2:
        print("Not enough arguments")
        sys.exit(1)

    main(sys.argv[1])
else:
    raise ImportError("This module shouldn't be imported")


text:
const isEmptyObject = require('../../_common/utility').isEmptyObject;

const submarket_order = {
    forex          : 0,
    major_pairs    : 1,
    minor_pairs    : 2,
    smart_fx       : 3,
    indices        : 4,
    asia_oceania   : 5,
    europe_africa  : 6,
    americas       : 7,
    otc_index      : 8,
    stocks         : 9,
    au_otc_stock   : 10,
    ge_otc_stock   : 11,
    india_otc_stock: 12,
    uk_otc_stock   : 13,
    us_otc_stock   : 14,
    commodities    : 15,
    metals         : 16,
    energy         : 17,
    synthetic_index: 18,
    random_index   : 19,
    random_daily   : 20,
    random_nightly : 21,
};

const ActiveSymbols = (() => {
    const groupBy = (xs, key) => (
        xs.reduce((rv, x) => {
            (rv[x[key]] = rv[x[key]] || []).push(x);
            return rv;
        }, {})
    );

    const extend = (a, b) => {
        if (!a || !b) return null;
        Object.keys(b).forEach((key) => {
            a[key] = b[key];
        });
        return a;
    };

    const clone = obj => extend({}, obj);

    let markets    = {};
    let submarkets = {};
    let symbols    = {};

    const getMarkets = (all_symbols) => {
        if (!isEmptyObject(markets)) {
            return clone(markets);
        }

        const all_markets = groupBy(all_symbols, 'market');
        const derived_markets = groupBy(all_markets.synthetic_index, 'subgroup');
        delete all_markets.synthetic_index;

        const final_markets = { ...all_markets, ...derived_markets };
        Object.keys(final_markets).forEach((key) => {
            const market_name    = key;
            const market_symbols = final_markets[key];
            const symbol         = market_symbols[0];
            markets[market_name] = {
                name         : symbol.market === 'synthetic_index' ? symbol.subgroup_display_name : symbol.market_display_name,
                is_active    : !symbol.is_trading_suspended && symbol.exchange_is_open,
                subgroup_name: symbol.subgroup !== 'none' ? symbol.market_display_name : symbol.subgroup_display_name,
                subgroup     : symbol.subgroup !== 'none' ? symbol.market : symbol.subgroup,
            };
            getSubmarketsForMarket(market_symbols, markets[market_name]);
        });
        return clone(markets);
    };

    const clearData = () => {
        markets    = {};
        symbols    = {};
        submarkets = {};
    };

    const getSubmarketsForMarket = (all_symbols, market) => {
        if (!isEmptyObject(market.submarkets)) {
            return clone(market.submarkets);
        }
        market.submarkets = {};

        const all_submarkets = groupBy(all_symbols, 'submarket');

        Object.keys(all_submarkets).forEach((key) => {
            const submarket_name    = key;
            const submarket_symbols = all_submarkets[key];
            const symbol            = submarket_symbols[0];

            market.submarkets[submarket_name] = {
                name     : symbol.submarket_display_name,
                is_active: !symbol.is_trading_suspended && symbol.exchange_is_open,
            };

            getSymbolsForSubmarket(submarket_symbols, market.submarkets[submarket_name]);
        });
        return clone(market.submarkets);
    };

    const getSymbolsForSubmarket = (all_symbols, submarket) => {
        if (isEmptyObject(submarket.symbols)) {
            submarket.symbols = {};
            all_symbols.forEach((symbol) => {
                submarket.symbols[symbol.symbol] = {
                    display    : symbol.display_name,
                    symbol_type: symbol.symbol_type,
                    is_active  : !symbol.is_trading_suspended && symbol.exchange_is_open,
                    pip        : symbol.pip,
                    market     : symbol.market !== 'synthetic_index' ? symbol.market : symbol.subgroup,
                    submarket  : symbol.submarket,
                };
            });
        }
        return clone(submarket.symbols);
    };

    const getSubmarkets = (active_symbols) => {
        if (isEmptyObject(submarkets)) {
            const all_markets = getMarkets(active_symbols);
            Object.keys(all_markets).forEach((key) => {
                const market         = all_markets[key];
                const all_submarkets = getSubmarketsForMarket(active_symbols, market);
                extend(submarkets, all_submarkets);
            });
        }
        return clone(submarkets);
    };

    const getSymbols = (active_symbols) => {
        if (isEmptyObject(symbols)) {
            const all_submarkets = getSubmarkets(active_symbols);
            Object.keys(all_submarkets).forEach((key) => {
                const submarket   = all_submarkets[key];
                const all_symbols = getSymbolsForSubmarket(active_symbols, submarket);
                extend(symbols, all_symbols);
            });
        }
        return clone(symbols);
    };

    const getSymbolsForMarket = (active_symbols, market) => {
        const all_symbols = getSymbols(active_symbols);

        const filtered_symbols = Object.keys(all_symbols)
            // only keep the symbols of the currently selected market
            .filter(symbol => all_symbols[symbol].market === market)
            // sort them by the submarket order defined
            .sort((symbol_a, symbol_b) =>
                sortSubmarket(all_symbols[symbol_a].submarket, all_symbols[symbol_b].submarket)
            )
            // make it into an object again with all needed data
            .reduce((obj, symbol) => ({
                ...obj,
                [symbol]: all_symbols[symbol],
            }), {});

        return clone(filtered_symbols);
    };

    const sortSubmarket = (a, b) => {
        if (submarket_order[a] > submarket_order[b]) {
            return 1;
        } else if (submarket_order[a] < submarket_order[b]) {
            return -1;
        }
        return 0;
    };

    const getMarketsList = (active_symbols) => {
        const trade_markets_list = {};
        extend(trade_markets_list, getMarkets(active_symbols));
        extend(trade_markets_list, getSubmarkets(active_symbols));
        return trade_markets_list;
    };

    // The unavailable underlyings are only offered on deriv.com.
    const getAvailableUnderlyings = (markets_list) => {
        const markets_list_clone = clone(markets_list);

        Object.keys(markets_list_clone).forEach(market_key => {
            Object.keys(markets_list_clone[market_key].submarkets).forEach(submarket_key => {
                if (Object.keys(markets_list_clone[market_key].submarkets[submarket_key].symbols).length === 0) {
                    delete markets_list_clone[market_key].submarkets[submarket_key];
                }
            });
            if (Object.keys(markets_list_clone[market_key].submarkets).length === 0){
                delete markets_list_clone[market_key];
            }
        });
        if (Object.keys(markets_list_clone).length === 0) return [];
        return markets_list_clone;
    };

    const getTradeUnderlyings = (active_symbols) => {
        const trade_underlyings = {};
        const all_symbols       = getSymbols(active_symbols);
        Object.keys(all_symbols).forEach((key) => {
            const symbol = all_symbols[key];
            if (!trade_underlyings[symbol.market]) {
                trade_underlyings[symbol.market] = {};
            }
            if (!trade_underlyings[symbol.submarket]) {
                trade_underlyings[symbol.submarket] = {};
            }
            trade_underlyings[symbol.market][key]    = symbol;
            trade_underlyings[symbol.submarket][key] = symbol;
        });
        return trade_underlyings;
    };

    const getSymbolNames = (active_symbols) => {
        const all_symbols = clone(getSymbols(active_symbols));
        Object.keys(all_symbols).forEach((key) => {
            all_symbols[key] = all_symbols[key].display;
        });
        return all_symbols;
    };

    return {
        getMarkets,
        getSubmarkets,
        getMarketsList,
        getTradeUnderlyings,
        getSymbolNames,
        clearData,
        getSymbols,
        getSymbolsForMarket,
        sortSubmarket,
        getAvailableUnderlyings,
    };
})();

module.exports = ActiveSymbols;


text:
import { Server } from 'mock-socket';
import * as EJSON from 'ejson';

/**
 * Mock DDP Server
 * This could be a Node Js implementation as well
 */
export class MyDDPServer {
  start() {
    const mockServer = new Server('ws://localhost:8080');

    mockServer.on('connection', _ => {
      const response = {
        msg: 'connected',
      };

      mockServer.send(EJSON.stringify(response));

      mockServer.on('message', message => {
        const data = EJSON.parse(message);
        this.mockMessageResponse(mockServer, data);
      });
    });
  }

  mockMessageResponse(server: WebSocket, data) {
    let response = {
      msg: 'not_implemented',
    };

    switch (data.msg) {
      case 'connect':
        response.msg = 'connected';
        break;
      case 'ping':
        response.msg = 'pong';
        break;
      case 'method':
        this.mockMethodResponse(server, data.method, data.id, data.params);
        return;
      case 'sub':
        this.mockSubResponse(server, data.name, data.id, data.params);
        return;
      default:
        break;
    }

    server.send(EJSON.stringify(response));
  }

  mockMethodResponse(
    server: WebSocket,
    method: string,
    id: number,
    params: any,
  ) {
    let response = {
      msg: 'result',
      id,
      result: undefined,
      error: undefined,
    };

    let responseUpdate = {
      msg: 'updated',
      id,
    };

    switch (method) {
      case 'login':
        response.result = 'mock_session_id';
        break;
      default:
        break;
    }

    server.send(EJSON.stringify(response));
    server.send(EJSON.stringify(responseUpdate));
  }

  mockSubResponse(
    server: WebSocket,
    publicationName: string,
    id: number,
    params: any,
  ) {
    const response = {
      id: `test_${publicationName}`,
      msg: 'added',
      collection: publicationName,
      fields: {
        _id: `test_${publicationName}`,
        full_name: 'Test',
        email: 'test@test.com',
      },
    };

    server.send(EJSON.stringify(response));
  }
}


text:
using System;

namespace LiteDB.Shell.Commands
{
    internal class CollectionStats : BaseCollection, IShellCommand
    {
        public bool IsCommand(StringScanner s)
        {
            return this.IsCollectionCommand(s, "stats");
        }

        public BsonValue Execute(DbEngine engine, StringScanner s)
        {
            var col = this.ReadCollection(engine, s);

            var mapper = new BsonMapper().UseCamelCase();

            return mapper.ToDocument<CollectionInfo>(engine.Stats(col));
        }
    }
}


text:
using System.Data.Entity;
using BolfTracker.Models;

namespace BolfTracker.Infrastructure.EntityFramework
{
    public class BolfTrackerContext : DbContext
    {
        public DbSet<Game> Games { get; set; }
        public DbSet<GameStatistics> GameStatistics { get; set; }
        public DbSet<Hole> Holes { get; set; }
        public DbSet<HoleStatistics> HoleStatistics { get; set; }
        public DbSet<PlayerCareerStatistics> PlayerCareerStatistics { get; set; }
        public DbSet<Player> Players { get; set; }
        public DbSet<PlayerGameStatistics> PlayerGameStatistics { get; set; }
        public DbSet<PlayerHoleStatistics> PlayerHoleStatistics { get; set; }
        public DbSet<PlayerRivalryStatistics> PlayerRivalryStatistics { get; set; }
        public DbSet<PlayerStatistics> PlayerStatistics { get; set; }
        public DbSet<Ranking> Rankings { get; set; }
        public DbSet<Shot> Shots { get; set; }
        public DbSet<ShotType> ShotTypes { get; set; }

        public BolfTrackerContext() : base(ConnectionString.Build())
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ValidateOnSaveEnabled = false;

            Database.SetInitializer<BolfTrackerContext>(null);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add<Game>(new GameConfiguration());
            modelBuilder.Configurations.Add<GameStatistics>(new GameStatisticsConfiguration());
            modelBuilder.Configurations.Add<Hole>(new HoleConfiguration());
            modelBuilder.Configurations.Add<HoleStatistics>(new HoleStatisticsConfiguration());
            modelBuilder.Configurations.Add<PlayerCareerStatistics>(new PlayerCareerStatisticsConfiguration());
            modelBuilder.Configurations.Add<Player>(new PlayerConfiguration());
            modelBuilder.Configurations.Add<PlayerGameStatistics>(new PlayerGameStatisticsConfiguration());
            modelBuilder.Configurations.Add<PlayerHoleStatistics>(new PlayerHoleStatisticsConfiguration());
            modelBuilder.Configurations.Add<PlayerRivalryStatistics>(new PlayerRivalryStatisticsConfiguration());
            modelBuilder.Configurations.Add<PlayerStatistics>(new PlayerStatisticsConfiguration());
            modelBuilder.Configurations.Add<Ranking>(new RankingConfiguration());
            modelBuilder.Configurations.Add<Shot>(new ShotConfiguration());
            modelBuilder.Configurations.Add<ShotType>(new ShotTypeConfiguration());
        }
    }
}


text:
<ion-menu [content]="content">
    <ion-header>
        <ion-toolbar color="primary">
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>

    <ion-content class="bg-content-menu">

        <button menuClose ion-item icon-left *ngFor="let p of pages" (click)="openPage(p)" class="bg-transparent">
            <ion-icon name="{{p.icon}}" class="margin-top-icon-menu"></ion-icon>
            {{p.title}}
        </button>
    </ion-content>
</ion-menu>

<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="dms.camera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <permission
        android:name="android.permission.FLASHLIGHT"
        android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
        android:protectionLevel="normal" />

    <uses-feature
        android:name="android.hardware.camera.AUTOFOCUS"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="dms.camera.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
id: 587d781e367417b2b2512acc
title: Lock an Element to the Browser Window with Fixed Positioning
challengeType: 0
videoUrl: https://scrimba.com/c/c2MDNUR
forumTopicId: 301061
localeTitle: Блокировка элемента в окне браузера с фиксированным позиционированием
---

## Description

Следующая схема компоновки, которую предлагает CSS, - это fixed позиция, которая является типом абсолютного позиционирования, который блокирует элемент относительно окна браузера. Подобно абсолютному позиционированию, он используется со свойствами смещения CSS, а также удаляет элемент из обычного потока документа. Другие предметы больше не «реализуют», где они позиционируются, что может потребовать некоторых корректировок компоновки в другом месте. Одно ключевое различие между fixed и absolute позициями состоит в том, что элемент с фиксированной позицией не будет перемещаться, когда пользователь прокручивается.

## Instructions

Навигационная панель в коде помечена идентификатором navbar . Измените его position на fixed и смещайте его на 0 пикселей top и на 0 пикселей left . Обратите внимание на (отсутствие) воздействия на позицию h1 , оно не было сдвинуто вниз, чтобы разместить панель навигации, и ее необходимо будет отрегулировать отдельно.

## Tests

```yml
tests:
  - text: The <code>#navbar</code> element should have a <code>position</code> set to <code>fixed</code>.
    testString: assert($('#navbar').css('position') == 'fixed');
  - text: Your code should use the <code>top</code> CSS offset of 0 pixels on the <code>#navbar</code> element.
    testString: assert($('#navbar').css('top') == '0px');
  - text: Your code should use the <code>left</code> CSS offset of 0 pixels on the <code>#navbar</code> element.
    testString: assert($('#navbar').css('left') == '0px');

```

## Challenge Seed

```html
<style>
  #navbar {

    width: 100%;
    background-color: #767676;
  }
  nav ul {
    margin: 0px;
    padding: 5px 0px 5px 30px;
  }
  nav li {
    display: inline;
    margin-right: 20px;
  }
  a {
    text-decoration: none;
  }
</style>
<body>
  <header>
    <h1>Welcome!</h1>
    <nav id="navbar">
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">Contact</a></li>
      </ul>
    </nav>
  </header>
  <p>I shift up when the #navbar is fixed to the browser window.</p>
</body>

```

## Solution

```html
<style>
  #navbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #767676;
  }
  nav ul {
    margin: 0px;
    padding: 5px 0px 5px 30px;
  }
  nav li {
    display: inline;
    margin-right: 20px;
  }
  a {
    text-decoration: none;
  }
</style>
<body>
  <header>
    <h1>Welcome!</h1>
    <nav id="navbar">
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">Contact</a></li>
      </ul>
    </nav>
  </header>
  <p>I shift up when the #navbar is fixed to the browser window.</p>
</body>
```


text:
#ifndef ZIG_AST_RENDER_HPP
#define ZIG_AST_RENDER_HPP

#include "all_types.hpp"
#include "parser.hpp"

#include <stdio.h>

void ast_print(FILE *f, AstNode *node, int indent);

void ast_render(CodeGen *codegen, FILE *f, AstNode *node, int indent_size);

const char *container_string(ContainerKind kind);

#endif


text:
import sys

from scripts.migrate_to_whatsapp_templates.base import BaseMigration

class PublicMigration(BaseMigration):
    TEMPLATE_NAME = "mc_message"

    def get_template_variables(self, message):
        return [message["text_content"]]

if __name__ == "__main__":
    PublicMigration().run(sys.stdin, sys.stdout)


text:
package com.landicorp.android.wofupay.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.landicorp.android.wofupay.R;
import com.landicorp.android.wofupay.bean.Passenger;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/3/27.
 */

public class PassengerAdapter extends BaseAdapter {
    private Context context;
    private  ArrayList<Passenger> list;
    private  String zuoweixibie;

    public PassengerAdapter(Context context, ArrayList<Passenger> list, String zuoweixibie) {
        this.context = context;
        this.list = list;
        this.zuoweixibie = zuoweixibie;
    }

    @Override
    public int getCount() {

        return list.size();
    }

    @Override
    public Object getItem(int position) {

        return getItem(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_passenger, null);
            holder.item_tv_name = (TextView) convertView.findViewById(R.id.passenger_name);
            holder.item_tv_Idcard = (TextView) convertView.findViewById(R.id.passenger_idcard);
            holder.item_tv_zuoweixibie = (TextView) convertView.findViewById(R.id.passenger_zuoweixibie);
            holder.item_btn = (Button) convertView.findViewById(R.id.passenger_btn);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (list.get(position).name.length()==2) {
            holder.item_tv_name.setText(list.get(position).name+"    ");
        }else {
            holder.item_tv_name.setText(list.get(position).name);
        }
        String hintnum = hintnum(list.get(position).idcard);
        holder.item_tv_Idcard.setText(hintnum);
        if(position%2==0){
            convertView.setBackgroundColor(Color.parseColor("#EEF1F8"));
        }else{
            convertView.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        holder.item_tv_zuoweixibie.setText(zuoweixibie);
        holder.item_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle(context.getString(R.string.Title));
                builder.setMessage("确定删除该乘客吗?");
                builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        notifyDataSetChanged();
                    }
                });
                  builder.create().show();

//                final AlertDialog dialog = new AlertDialog.Builder(context).create();
//                dialog.show();
//                Window window = dialog.getWindow();
//                dialog.setTitle("提示");
//                dialog.setMessage("确定要删除该乘客吗?");
//                window.setContentView(R.layout.diolog_base);
//                window.setGravity(Gravity.BOTTOM);
//                Button cancle = (Button) window.findViewById(R.id.cancelBtn);
//                Button ok = (Button) window.findViewById(R.id.okBtn);
//                cancle.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        dialog.dismiss();
//                        notifyDataSetChanged();
//                    }
//                });
//                ok.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        list.remove(position);
//                        notifyDataSetChanged();
//                    }
//                });
            }

        });
        return convertView;
    }
    private class ViewHolder{
        public TextView item_tv_name;
        public TextView item_tv_Idcard;
        public TextView item_tv_zuoweixibie;
        public TextView item_tv_passengerType;
        public Button item_btn;
    }
    private String hintnum(String idCard) {
        return idCard.substring(0,6)+"*******"+idCard.substring(14, idCard.length());
    }
    public void setZuoWei(String text) {
        this.zuoweixibie = text;
        notifyDataSetChanged();
    }
}


text:
package org.pentaho.di.core.injection.inheritance;

import org.pentaho.di.core.injection.Injection;

public class MetaBeanParentItem {
  @Injection( name = "BASE_ITEM_NAME" )
  public String name;
}


text:
[![Build Status](https://travis-ci.org/duaraghav8/solium-plugin-security.svg?branch=master)](https://travis-ci.org/duaraghav8/solium-plugin-security)

This Plugin provides security-focused lint rules for [Solium](https://github.com/duaraghav8/Solium).

The rules have been taken from Consensys' [Recommended Smart Contract Practices](https://consensys.github.io/smart-contract-best-practices/recommendations/) and Solium's [Rule Wishlist](https://github.com/duaraghav8/Solium/issues/44).

## Installation
**NOTE: If you're using Solium `v1.0.1` or above, this plugin comes pre-installed as a local dependency and you can skip this section.**

`npm install -g solium-plugin-security`

## Usage
**NOTE: If you've installed Solium `v1.0.1` or above and created `soliumrc.json` using `solium --init`, you can skip this step since solium automatically applies the security plugin for you.**

Add `security` to your `soliumrc.json`'s `plugins` array. Your configuration file should look like:

```json
{
    "extends": "solium:all",
    "plugins": ["security"],
    "rules": {
        ...
    }
}
```

## List of rules
Below are the rules supplied by this plugin and the information on passing options to them and their auto-fixing capabilities.

Some of them aren't always desirable and are therefore disabled by default (marked below as `OFF`). You should explicitly enable them in your `.soliumrc.json`.

| Name                                 | Description                                                                                | Options                           | Defaults                             | Fixes |
|--------------------------------------|--------------------------------------------------------------------------------------------------|-----------------------------------|--------------------------------------|-------|
| no-throw                             | Discourage use of 'throw' statement for error flagging                                           |                                   |                                      | YES   |
| no-tx-origin                         | Discourage use of 'tx.origin' global variable                                                    |                                   |                                      |       |
| enforce-explicit-visibility          | Encourage user to explicitly specify visibility of function                                      |                                   |                                      | YES   |
| no-block-members                     | Discourage use of members 'blockhash' & 'timestamp' (and alias 'now') of 'block' global variable | List of members to warn against   | ["blockhash", "timestamp"]           |       |
| no-call-value                        | Discourage use of .call.value()()                                                                |                                   |                                      |       |
| no-assign-params                     | Disallow assigning to function parameters                                                        |                                   |                                      |       |
| no-fixed                             | Disallow fixed point types                                                                       |                                   |                                      |       |
| no-inline-assembly                   | Discourage use of inline assembly                                                                |                                   |                                      |       |
| no-low-level-calls                   | Discourage the use of low-level functions - call(), callcode() & delegatecall()                  | List of functions to warn against | ["call", "callcode", "delegatecall"] |       |
| no-modify-for-iter-var               | Discourage user to modify a for loop iteration counting variable in the loop body                |                                   |                                      |       |
| no-send                              | Discourage the use of unsafe method 'send'                                                       |                                   |                                      |       |
| no-sha3                              | Encourage use of 'keccak256()' over 'sha3()' function                                            |                                   |                                      | YES   |
| no-unreachable-code                  | Disallow unreachable code                                                                        |                                   |                                      |       |
| `OFF` else-after-elseif              | Encourage user to use else statement after else-if statement                                     |                                   |                                      |       |
| `OFF` enforce-loop-bounds            | Encourage use of loops with fixed bounds                                                         |                                   |                                      |       |
| `OFF` enforce-placeholder-last       | Enforce that the function placeholder is the last statement in the modifier                      |                                   |                                      |       |
| `OFF` return-at-end                  | Discourage use of early returns in functions                                                     |                                   |                                      |       |
| `OFF` one-break-per-loop             | Discourage use of multiple breaks in while/for/do loops                                          |                                   |                                      |       |
| `OFF` max-statements-in-func         | Enforce upper limit on number of statements inside a function                                    | Maximum number of statements      | 25                                   |       |
| `OFF` no-abstract-func               | Discourage use of abstract functions                                                             |                                   |                                      |       |
| `OFF` no-bit-operations              | Disallow bitwise operations                                                                      |                                   |                                      |       |
| `OFF` no-continue                    | Discourage use of 'continue' statement                                                           |                                   |                                      |       |
| `OFF` no-inheritance                 | Discourage use of inheritance                                                                    | Disallow interface inheritance    | { "no-interface": false }            |       |
| `OFF` no-multiple-inheritance        | Discourage use of multiple inheritance                                                           | Disallow interface inheritance    | { "no-interface": false }            |       |
| `OFF` no-named-params                | Disallow named function parameters                                                               |                                   |                                      |       |
| `OFF` no-named-returns               | Discourage use of named returns in functions                                                     |                                   |                                      |       |
| `OFF` 256-bit-ints-only              | Disallow non-256 bit integers                                                                    |                                   |                                      |       |
| `OFF` no-suicide-or-selfdestruct     | Disallow suicide and selfdestruct                                                                |                                   |                                      |       |
| `OFF` no-var                         | Disallow type deduction via `var`                                                                |                                   |                                      |       |
| `OFF` no-user-defined-modifiers      | Disallow user-defined modifiers                                                                  |                                   |                                      |       |
| `OFF` no-void-returns                | Discourage use of void returns in functions prototypes                                           |                                   |                                      |       |
| `OFF` no-func-overriding             | Discourage function overriding                                                                   |                                   |                                      |       |

An example `soliumrc.json` configuring and applying this plugin is:

```json
{
    "plugins": ["security"],
    "rules": {
        "some-other-solium-rule": 1,
        "security/no-low-level-calls": ["error", ["call", "delegatecall"]],
        "security/no-block-members": [1, ["timestamp"]],
        "security/no-throw": "off"
    }
}
```
This tells solium to apply the 3 `security/` rules with special configuration provided and apply the remaining rules of the plugin with their default configurations. If you want to disable a plugin rule, you have to explicitly disable it inside `rules`.

Lint normally using `solium -d contracts/` or `solium -d contracts/ --fix` to apply fixes as well.

## Developer Setup
- `git clone <URL-of-this-repo>`
- `cd solium-plugin-security`
- `npm install --dev`
- `npm link`
- `npm link solium-plugin-security`
- `npm test`

If you'd also like to use your develop build of this plugin with dev build of Solium, go to Solium's directory and run `npm link solium-plugin-security`. This will let Solium access your modified plugin instead of its pre-installed security module.

Access Solium's [Developer Docs](http://solium.readthedocs.io/en/latest/developer-guide.html)

## Roadmap
- [ ] Add automated tests
- [ ] Refine rule `enforce-explicit-visibility`
- [ ] Add more security rules

### Security rules to be implemented
- [ ] `no-multiple-send-calls`
- [ ] `check-send-result`

**[Access the complete Solium documentation](http://solium.readthedocs.io/en/latest/index.html)**


text:
package gergely.sallai.tools.resultfragment.sample;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import gergely.sallai.tools.resultfragment.sample.fragment.ExampleFragmentDialog;

public class MainActivity extends ActionBarActivity {

    View activityListensExample;
    View targetFragmentListensExample;
    View manualListenerExample;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activityListensExample = findViewById(R.id.activity_listens);
        targetFragmentListensExample = findViewById(R.id.targetfragment_listens);
        manualListenerExample = findViewById(R.id.manual_listener);

        activityListensExample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ActivityStartsDialogFragment.class));
            }
        });
        targetFragmentListensExample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ActivityTargetFragmentExample.class));
            }
        });
        // TODO others
    }
}


text:
cd ~

git clone --depth=1 -b maint/v1.0.1 https://github.com/libgit2/libgit2.git
cd libgit2/

mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=../_install -DBUILD_CLAR=OFF  # don't build unit tests
cmake --build . --target install
ls -la ..

cd ~


text:
<?php

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version. Although none of the code may be
 *   sold. If you have been sold this script, get a refund.
 ***************************************************************************/

define('InAdmin', 1);
$current_page = 'banners';
include '../common.php';
include INCLUDE_PATH . 'functions_admin.php';
include 'loggedin.inc.php';

if (isset($_POST['action']) && $_POST['action'] == 'insert')
{
	if (empty($_POST['name']) || empty($_POST['company']) || empty($_POST['email']))
	{
		$template->assign_block_vars('alerts', array('TYPE' => 'error', 'MESSAGE' => $ERR_047));
	}
	elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$/i', $_POST['email']))
	{
		$template->assign_block_vars('alerts', array('TYPE' => 'error', 'MESSAGE' => $ERR_008));
	}
	else
	{
		// Update database
		$query = "INSERT INTO " . $DBPrefix . "bannersusers VALUES (NULL, :name, :company, :email)";
		$params = array();
		$params[] = array(':name', $system->cleanvars($_POST['name']), 'str');
		$params[] = array(':company', $system->cleanvars($_POST['company']), 'str');
		$params[] = array(':email', $system->cleanvars($_POST['email']), 'str');
		$db->query($query, $params);
		$ID = $db->lastInsertId();
		header('location: userbanners.php?id=' . $ID);
		exit;
	}
}

$template->assign_vars(array(
		'NAME' => (isset($_POST['name'])) ? $_POST['name'] : '',
		'COMPANY' => (isset($_POST['company'])) ? $_POST['company'] : '',
		'EMAIL' => (isset($_POST['email'])) ? $_POST['email'] : ''
		));

include 'header.php';
$template->set_filenames(array(
		'body' => 'newbanneruser.tpl'
		));
$template->display('body');
include 'footer.php';
?>