text:
"""
Models for TellTrail.
"""
from django.db import models
from django.contrib.auth.models import User

class CanonicalIdentityManager(models.Manager):
    """
    Manager class for CanonicalIdentity.
    """
    def filter_by_identity(self,identity):
        """
        Retrieves CanonicalIdentity objects by associated service identities.
        """
        return self.filter(pk__in=[claim.pk for claim in IdentityClaim.objects.filter(identity=identity)])

    def get_by_identity(self,identity):
        """
        Gets a single CanonicalIdentity by the specified service identity.  Will raise an exception
        if there is more than one claim on the identity.
        """
        return IdentityClaim.objects.get(identity=identity).canonical_identity

class CanonicalIdentity(models.Model):
    """
    The definitive identity of a user.
    """
    user = models.ForeignKey(User,unique=True)
    city = models.CharField(null=True, max_length=100)
    zip_code = models.CharField(null=True, max_length=10)

    objects = CanonicalIdentityManager()

    def __unicode__(self):
        return self.user.username

    @property
    def default_policy(self):
        """
        Gets the default policy.
        """
        policy, created = self.policy_elements.get_or_create(scope__isnull=True)
        if created:
            policy.minimum_grade = 'C'
            policy.save()
        return policy

    @property
    def specific_policies(self):
        """
        Retrieves policy elements with specific data scope.
        """
        return self.policy_elements.filter(scope__isnull=False)

    def render_policy(self):
        """
        Renders the policy into a structure suitable for JSON serialization.
        """
        # Personal Info
        policy = {'username':self.user.username,'first_name':self.user.first_name,'last_name':self.user.last_name}
        if self.city:
            policy['city'] = self.city
        if self.zip_code:
            policy['zip_code'] = self.zip_code

        # Identities
        identities = []
        for claim in self.identity_claims.all():
            rendered_identity = {'identity':claim.identity.identity,
                                 'service':claim.identity.service.name,
                                 'profile':claim.identity.profile,
                                 'confidence':claim.claim_confidence}
            identities.append(rendered_identity)
        policy['identities'] = identities

        # Default Policy
        default_policy = self.default_policy
        policy['default_grant'] = default_policy.default_grant
        policy['minimum_grade'] = default_policy.minimum_grade

        # Exceptions
        exceptions = []
        for policy_exception in self.policy_exceptions.all():
            rendered_exception = {'grant':policy_exception.grant,
                                  'consumer':{'name':policy_exception.consumer.name,'domain':policy_exception.consumer.domain}}
            if policy_exception.scope:
                rendered_exception['scope'] = unicode(policy_exception.scope)
            exceptions.append(rendered_exception)
        policy['exceptions'] = exceptions

        # Specific Policies
        specific_policies = []
        for specific_policy in self.specific_policies:
            specific_policies.append({'scope':unicode(specific_policy.scope),
                                      'grant':specific_policy.default_grant,
                                      'minimum_grade':specific_policy.minimum_grade})
        policy['specific_policies'] = specific_policies

        return policy

class Service(models.Model):
    """
    An internet service on which someone may have an identity.
    """
    name = models.CharField(unique=True, max_length=100)
    url = models.URLField(blank=True,)
    verified = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name

class Identity(models.Model):
    """
    An identity at a service.
    """
    service = models.ForeignKey(Service,related_name='identities')
    identity = models.CharField(max_length=100)
    profile = models.CharField(max_length=100)

    def __unicode__(self):
        return '%s@%s' (unicode(self.identity),unicode(self.service))

    class Meta:
        unique_together = (('service','identity'),)

class IdentityClaim(models.Model):
    """
    A canonical identity that claims an identity.
    """
    canonical_identity = models.ForeignKey(CanonicalIdentity,related_name='identity_claims')
    identity = models.ForeignKey(Identity,related_name='identity_claims')
    claim_confidence = models.IntegerField()

class DataConsumer(models.Model):
    """
    A consumer of data.
    """
    name = models.CharField(max_length=100)
    domain = models.URLField()
    letter_grade = models.CharField(max_length=1,default='C')

    def __unicode__(self):
        return self.name

    class Meta:
        unique_together = (('name','domain'),)

class DataScope(models.Model):
    """
    A topical category for data, such as 'clothing', 'books' or 'social',
    that can be used as a scope for a policy element.
    """
    name = models.CharField(primary_key=True, max_length=100)
    parent = models.ForeignKey('self',null=True)

    def __unicode__(self):
        if self.parent:
            return '%s : %s' % (unicode(self.parent),self.name)
        else:
            return self.name

class PolicyElement(models.Model):
    """
    An element of a user's data policy.
    """
    canonical_identity = models.ForeignKey(CanonicalIdentity,related_name='policy_elements')
    scope = models.ForeignKey(DataScope,null=True)
    default_grant = models.BooleanField(default=True) # If true, data in this scope is granted, otherwise not.  Overriden by service lists.
    minimum_grade = models.CharField(null=True, max_length=1) # if not null, the minimum grade to which the grant is offered

    class Meta:
        unique_together = (('canonical_identity','scope'),)

class PolicyException(models.Model):
    """
    A policy for a specific data consumer.
    """
    canonical_identity = models.ForeignKey(CanonicalIdentity,related_name='policy_exceptions')
    scope = models.ForeignKey(DataScope,null=True)
    consumer = models.ForeignKey(DataConsumer)
    grant = models.BooleanField(default=True) # If true, this is a specific grant to the consumer, if false it is a specific denial.

    class Meta:
        unique_together = (('canonical_identity','consumer','scope'),)

class DataSource(models.Model):
    """
    A source of data.
    """
    account_name = models.CharField(max_length=100)
    instance_name = models.CharField(max_length=100)
    api_key = models.CharField(max_length=100)
    active = models.BooleanField(default=True)

    def __unicode__(self):
        return '%s:%s' % (self.account_name,self.instance_name)

    class Meta:
        unique_together = (('account_name','instance_name'),)


text:
package org.apache.flink.test.recordJobs.wordcount;

import java.util.Iterator;
import java.util.StringTokenizer;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.Program;
import org.apache.flink.api.common.ProgramDescription;
import org.apache.flink.api.java.record.functions.MapFunction;
import org.apache.flink.api.java.record.functions.ReduceFunction;
import org.apache.flink.api.java.record.functions.FunctionAnnotation.ConstantFields;
import org.apache.flink.api.java.record.io.CsvOutputFormat;
import org.apache.flink.api.java.record.io.TextInputFormat;
import org.apache.flink.api.java.record.operators.FileDataSink;
import org.apache.flink.api.java.record.operators.FileDataSource;
import org.apache.flink.api.java.record.operators.MapOperator;
import org.apache.flink.api.java.record.operators.ReduceOperator;
import org.apache.flink.api.java.record.operators.ReduceOperator.Combinable;
import org.apache.flink.client.LocalExecutor;
import org.apache.flink.types.IntValue;
import org.apache.flink.types.Record;
import org.apache.flink.types.StringValue;
import org.apache.flink.util.Collector;

/**
 * Implements a word count which takes the input file and counts the number of
 * the occurrences of each word in the file.
 */
public class WordCount implements Program, ProgramDescription {

	private static final long serialVersionUID = 1L;

	/**
	 * Converts a Record containing one string in to multiple string/integer pairs.
	 * The string is tokenized by whitespaces. For each token a new record is emitted,
	 * where the token is the first field and an Integer(1) is the second field.
	 */
	public static class TokenizeLine extends MapFunction {
		private static final long serialVersionUID = 1L;

		@Override
		public void map(Record record, Collector<Record> collector) {
			// get the first field (as type StringValue) from the record
			String line = record.getField(0, StringValue.class).getValue();

			// normalize the line
			line = line.replaceAll("\\W+", " ").toLowerCase();

			// tokenize the line
			StringTokenizer tokenizer = new StringTokenizer(line);
			while (tokenizer.hasMoreTokens()) {
				String word = tokenizer.nextToken();

				// we emit a (word, 1) pair
				collector.collect(new Record(new StringValue(word), new IntValue(1)));
			}
		}
	}

	/**
	 * Sums up the counts for a certain given key. The counts are assumed to be at position 1
	 * in the record. The other fields are not modified.
	 */
	@Combinable
	@ConstantFields(0)
	public static class CountWords extends ReduceFunction {

		private static final long serialVersionUID = 1L;

		@Override
		public void reduce(Iterator<Record> records, Collector<Record> out) throws Exception {
			Record element = null;
			int sum = 0;
			while (records.hasNext()) {
				element = records.next();
				int cnt = element.getField(1, IntValue.class).getValue();
				sum += cnt;
			}

			element.setField(1, new IntValue(sum));
			out.collect(element);
		}

		@Override
		public void combine(Iterator<Record> records, Collector<Record> out) throws Exception {
			// the logic is the same as in the reduce function, so simply call the reduce method
			reduce(records, out);
		}
	}

	@Override
	public Plan getPlan(String... args) {
		// parse job parameters
		int numSubTasks   = (args.length > 0 ? Integer.parseInt(args[0]) : 1);
		String dataInput = (args.length > 1 ? args[1] : "");
		String output    = (args.length > 2 ? args[2] : "");

		FileDataSource source = new FileDataSource(new TextInputFormat(), dataInput, "Input Lines");
		MapOperator mapper = MapOperator.builder(new TokenizeLine())
			.input(source)
			.name("Tokenize Lines")
			.build();
		ReduceOperator reducer = ReduceOperator.builder(CountWords.class, StringValue.class, 0)
			.input(mapper)
			.name("Count Words")
			.build();

		@SuppressWarnings("unchecked")
		FileDataSink out = new FileDataSink(new CsvOutputFormat("\n", " ", StringValue.class, IntValue.class), output, reducer, "Word Counts");

		Plan plan = new Plan(out, "WordCount Example");
		plan.setDefaultParallelism(numSubTasks);
		return plan;
	}

	@Override
	public String getDescription() {
		return "Parameters: <numSubStasks> <input> <output>";
	}

	public static void main(String[] args) throws Exception {
		WordCount wc = new WordCount();

		if (args.length < 3) {
			System.err.println(wc.getDescription());
			System.exit(1);
		}

		Plan plan = wc.getPlan(args);

		// This will execute the word-count embedded in a local context. replace this line by the commented
		// succeeding line to send the job to a local installation or to a cluster for execution
		JobExecutionResult result = LocalExecutor.execute(plan);
		System.err.println("Total runtime: " + result.getNetRuntime());
	}
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"

	// defaultlog declares itself as `package deflog`.
	"github.com/u-root/gobusybox/test/nameconflict/pkg/defaultlog"

	// anotherlog makes sure that a package can be imported twice with a different name.
	anotherlog "github.com/u-root/gobusybox/test/nameconflict/pkg/defaultlog"

	// Create a conflict with the self-registering package import.
	bbmain "flag"
)

var something = bbmain.String("someflag", "", "")

// log will conflict with `import "log"` in order to read
//
// var log *log.Logger
var log = deflog.Default()
var log2 = anotherlog.Default()

// should conflict with init being rewritten.
func busyboxInit0() {
	fmt.Println("busyboxInit0")
}

// should be rewritten as busyboxInit2 because of name conflict with busyboxInit0 and busyboxInit1.
func init() {
	fmt.Println("init")
}

func main() {
	busyboxInit0()
	busyboxInit1()
	registeredInit()
	registeredMain()
}


text:
title: El componente de fecha y hora.
examples:
  - title: Render regular
    arguments:
      label: Creado
      value: 2020-04-06
      locale: en-US
      options:
        timeZone: UTC
  - title: Renderizado en línea.
    arguments:
      label: Última actualización
      value: 2020-03-30
      locale: es
      options:
        timeZone: UTC
      modifiers:
        inline: true
  - title: Renderizar con formato.
    arguments:
      label: Al corriente
      value: 2020-02-29 20:20:29 +0000
      locale: en
      options:
        year: 'numeric'
        month: 'long'
        day: 'numeric'
        timeZone: UTC
      modifiers:
        inline: true
---

Recomendaciones para argumentos:

- `label` : `microcopy.lastUpdated`
- `value` : `page.date`
- `locale` : `locale.code`


text:
'use strict';

var Promise = require('bluebird');
var _ = require('lodash');

module.exports = function() {
    var teraslice, es_client, es_helper;

    describe('reindex', function() {

        it('should reindex data', function(done) {
            var job_spec = _.cloneDeep(require('../../fixtures/jobs/reindex.json'));
            job_spec.name = 'basic reindex'
            job_spec.operations[1].index = 'test-reindex-10';

            teraslice.jobs.submit(job_spec)
                .then(function(job) {
                    expect(job).toBeDefined();
                    expect(job.id()).toBeDefined();

                    // The job may run for a while so we have to wait for it to finish.
                    return job.waitForStatus('completed');
                })
                .then(function() {
                    return es_helper.documentCountForIndex('test-reindex-10')
                        .then(function(stats) {
                            expect(stats.count).toBe(10);
                            expect(stats.deleted).toBe(0);
                        });
                })
                .catch(fail)
                .finally(done)
        });

        it('job should complete after lifecycle changes', function(done) {
            var job_spec = _.cloneDeep(require('../../fixtures/jobs/reindex.json'));
            job_spec.name = 'reindex after lifecycle changes'
            // Job needs to be able to run long enough to cycle
            job_spec.operations[0].index = 'example-logs-10000';
            job_spec.operations[1].index = 'test-reindex-lifecycle';

            teraslice.jobs.submit(job_spec)
                .then(function(job) {
                    expect(job.id()).toBeDefined();

                    // The job may run for a while so we have to wait for it to finish.
                    return job.waitForStatus('running')
                        .then(function() {
                            return job.pause();
                        })
                        .then(function() {
                            return job.waitForStatus('paused');
                        })
                        .then(function() {
                            return job.resume();
                        })
                        .then(function() {
                            return job.waitForStatus('running');
                        })
                        .then(function() {
                            return job.stop();
                        })
                        .then(function() {
                            return job.waitForStatus('stopped');
                        })
                        .then(function() {
                            return job.recover();
                        })
                        .then(function() {
                            return job.waitForStatus('completed');
                        })
                        .then(function() {
                            return es_helper.documentCountForIndex('test-reindex-lifecycle')
                                .then(function(stats) {
                                    expect(stats.count).toBe(10000);
                                    expect(stats.deleted).toBe(0);
                                });
                        });
                })
                .catch(fail)
                .finally(done);
        });

        it('should reindex data 10 times', function(done) {
            var job_spec = _.cloneDeep(require('../../fixtures/jobs/reindex.json'));
            job_spec.name = 'reindex 10 times'
            job_spec.operations[1].index = 'test-reindex-10times';

            var iterations = 10;
            var jobs = [];

            for (var i = 0; i < iterations; i++) {
                jobs.push(teraslice.jobs.submit(job_spec));
            }

            Promise
                .map(jobs, function(job) {
                    expect(job).toBeDefined();
                    expect(job.id()).toBeDefined();

                    return job.waitForStatus('completed');
                })
                .all()
                .then(function() {
                    return es_helper.documentCountForIndex('test-reindex-10times')
                        .then(function(stats) {
                            expect(stats.count).toBe(10 * iterations);
                            expect(stats.deleted).toBe(0);
                            done();
                        });
                });
        });
    });

    return function(connections) {
        es_client = connections.es_client;
        teraslice = connections.teraslice_client;
        es_helper = require('../helpers/es_helper')(es_client);
    }
};


text:
package opus.gwt.management.console.client.event;

import opus.gwt.management.console.client.overlays.VersionData;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.GwtEvent;

public class UpdateVersionEvent extends GwtEvent<UpdateVersionEventHandler> {

	public static Type<UpdateVersionEventHandler> TYPE = new Type<UpdateVersionEventHandler>();
	private JsArray<VersionData> versionInfo;

	public UpdateVersionEvent(JavaScriptObject jso){
		this.versionInfo = ConvertVersionInfo(jso);
	}

	public JsArray<VersionData> getVersionInfo(){
		return versionInfo;
	}

  	@Override
  	public Type<UpdateVersionEventHandler> getAssociatedType() {
	  return TYPE;
  	}

  	@Override
  	protected void dispatch(UpdateVersionEventHandler handler) {
	  handler.onUpdateVersionInfo(this);
  	}

	public final native JsArray<VersionData> ConvertVersionInfo(JavaScriptObject jso) /*-{
		return jso;
	}-*/;
}


text:
#ifndef ALITOFANALYSISTASKCALIBPASS0_H
#define ALITOFANALYSISTASKCALIBPASS0_H

///////////////////////////////////////////////////////////////
//                                                           //
//   This class provides TOF pass0/passX calibration tools   //
//                                                           //
///////////////////////////////////////////////////////////////

#include "AliAnalysisTaskSE.h"

class AliESDtrack;
class AliESDEvent;
class AliPhysicsSelection;
class AliESDtrackCuts;
class AliESDVertex;
class AliGRPManager;
class AliGRPObject;
class AliTOFcalib;
class TList;
class TH2F;
class TF1;
class TH1D;
class AliCDBStorage;

class AliTOFAnalysisTaskCalibPass0 :
public AliAnalysisTaskSE
{

 public:

  AliTOFAnalysisTaskCalibPass0(); // default constructor
  virtual ~AliTOFAnalysisTaskCalibPass0(); // default destructor

  virtual void UserCreateOutputObjects(); // user create output objects
  virtual void UserExec(Option_t *); // user exec

  /* getters */
  AliPhysicsSelection *GetEventCuts() const {return fEventCuts;}; // getter
  AliESDtrackCuts *GetTrackCuts() const {return fTrackCuts;}; // getter
  AliTOFcalib *GetTOFcalib() const {return fTOFcalib;}; // getter

  /* setters */
  void SetEventSelectionFlag(Bool_t value = kTRUE) {fEventSelectionFlag = value;}; // setter
  void SetVertexSelectionFlag(Bool_t value = kTRUE) {fVertexSelectionFlag = value;}; // setter
  void SetVertexCut(Double_t value) {fVertexCut = value;}; // setter

  /* post-processing methods */
  Bool_t ProcessOutput(const Char_t *filename, AliCDBStorage* db); // process output
  Bool_t DoProcessOutput(const Char_t *filename, AliCDBStorage* db); // process output
  Int_t GetStatus(); // get status
  void PrintStatus(); // print status

  /* static setters */
  static void SetMinVertexIntegral(Double_t value) {fgMinVertexIntegral = value;}; // setter
  static void SetMinDeltatIntegal(Double_t value) {fgMinDeltatIntegral = value;}; // setter
  static void SetMinVertexIntegralSample (Double_t value) {fgMinVertexIntegralSample = value;}; // setter
  static void SetMinDeltatIntegralSample (Double_t value) {fgMinDeltatIntegralSample = value;}; // setter

 protected:

  AliTOFAnalysisTaskCalibPass0(const AliTOFAnalysisTaskCalibPass0 &); // copy constructor
  AliTOFAnalysisTaskCalibPass0 &operator=(const AliTOFAnalysisTaskCalibPass0 &); // operator=

  /* status codes */
  enum EStatusCode_t {
    kOk,
    kInputError, /* open file error, missing histos */
    kDataError, /* problems with histo information */
    kNotActive, /* not active in data taking and/or reconstruction */
    kLowStatistics, /* too low statistics */
    kNoMeasurement, /* no measurement performed */
    kStoreError, /* problems storing OCDB */
    kNStatusCodes
  };
  Int_t fStatus; /* status code */
  static const Char_t *fgkStatusCodeName[kNStatusCodes];

  /* methods */
  Bool_t InitRun(); // init run
  Bool_t InitEvent(); // init event
  Bool_t HasTOFMeasurement(const AliESDtrack *track) const ; // has TOF measurement

  /* post-processing methods */
  Bool_t CheckMatchingPerformance(const TH2F *histoDeltazEta, const TH2F *histoAcceptedTracksEtaPt, const TH2F *histoMatchedTracksEtaPt) const; // check matching efficiency
  Bool_t CalibrateAndStore(TH2F *histoVertexTimestamp, TH2F *histoDeltatTimestamp, AliCDBStorage *db); // calibrate and store
  Int_t FitPeak(TF1 *fitFunc, TH1D *h, Float_t startSigma, Float_t nSigmaMin, Float_t nSigmaMax); // fit peak

  /* flags and cuts */
  Bool_t fInitFlag; // init flag
  Bool_t fEventSelectionFlag; // event selection flag
  Bool_t fVertexSelectionFlag; // vertex selection flag
  Double_t fVertexCut; // vertex cut

  /* ESD analysis */
  Int_t fRunNumber; // run number
  AliESDEvent *fESDEvent; // ESD event
  AliPhysicsSelection *fEventCuts; // event cuts
  AliESDtrackCuts *fTrackCuts; // track cuts
  UInt_t fStartTime; // start time
  UInt_t fEndTime; // end time
  UInt_t fEventTime; // event time
  UInt_t fElapsedTime; // event time since start
  const AliESDVertex *fkVertex; // vertex

  /* GRP related stuff */
  AliGRPManager *fGRPManager; // GRP manager
  const AliGRPObject *fkGRPObject; // GRP object

  /* TOF related stuff */
  AliTOFcalib *fTOFcalib; // TOF calib

  /* lists and histos */
  TList *fHistoList; // list of histograms
  TH2F *fHistoVertexTimestamp; // vertex-timestamp histo
  TH2F *fHistoDeltatTimestamp; // deltat-timestamp histo
  TH2F *fHistoDeltazEta; // deltaz-eta histo
  TH2F *fHistoDeltatEta; // deltaTime-eta histo
  TH2F *fHistoDeltazCosTheta; // deltaz-costheta histo
  TH2F *fHistoAcceptedTracksEtaPt; // accepted tracks eta-pt histo
  TH2F *fHistoMatchedTracksEtaPt; // matched tracks eta-pt histo

  /* post-processing variables */
  static const Int_t fgkMaxNumberOfPoints; // max number of points
  static Double_t fgMinVertexIntegral; // min vertex integral
  static Double_t fgMinDeltatIntegral; // min vertex integral
  static Double_t fgMinVertexIntegralSample; // min vertex integral sample
  static Double_t fgMinDeltatIntegralSample; // min vertex integral sample

  ClassDef(AliTOFAnalysisTaskCalibPass0, 2);
};

#endif /* ALIANALYSISTASKEVENTTIME_H */


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  include Pundit

  rescue_from Exception do |ex|
    Rollbar.error(ex)
    Rails.logger.fatal(ex)
    respond_to do |format|
      format.html { render 'errors/error', layout: false, status: :internal_server_error }
      format.all  { render nothing: true, status: :internal_server_error }
    end
  end

  rescue_from ActionController::RoutingError, with: :render_not_found
  rescue_from ActiveRecord::RecordNotFound, with: :render_not_found

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
  rescue_from Pundit::AuthorizationNotPerformedError, with: :user_not_authorized

  helper_method :logged_in?
  helper_method :current_user
  helper_method :current_service

  before_action :set_locale
  before_action :accept_terms, if: :logged_in?

  def render_not_found
    respond_to do |format|
      format.html { render template: 'errors/not_found', layout: false, status: :not_found }
      format.all  { render nothing: true, status: :not_found }
    end
  end

  protected

  def current_user
    if session.key?(:member_id)
      @current_member ||= Member.find(session[:member_id])
    end
  rescue ActiveRecord::RecordNotFound
    session[:member_id] = nil
  end

  def current_service
    if session.key?(:service_id)
      @current_service ||= Service.find_by(member_id: session[:member_id],
                                           id: session[:service_id])
    end
  rescue ActiveRecord::RecordNotFound
    session[:service_id] = nil
  end

  def current_user?
    !!current_user
  end

  def logged_in?
    current_user?
  end

  def accept_terms
    store_path
    redirect_to terms_and_conditions_path if current_user.accepted_toc_at.blank?
  end

  def authenticate_member!
    if current_user
      finish_registration
    else
      redirect_to redirect_path
    end
  end

  def store_path
    session[:previous_request_url] = request.url
  end

  def previous_path
    session[:previous_request_url]
  end

  def finish_registration
    if current_user.requires_additional_details?
      redirect_to edit_member_details_path unless providing_additional_details?
    end
  end

  def providing_additional_details?
    [edit_member_path, edit_member_details_path].include? request.path
  end

  def logout!
    @current_member = nil
    reset_session
  end

  helper_method :redirect_path
  def redirect_path
    '/auth/github'
  end

  def authenticate_admin!
    redirect_to root_path, notice: "You can't be here" unless logged_in? && current_user.has_role?(:admin)
  end

  def authenticate_admin_or_organiser!
    redirect_to root_path, notice: "You can't be here" unless manager?
  end

  def manager?
    logged_in? && (current_user.is_admin? || current_user.has_role?(:organiser, :any))
  end

  helper_method :manager?

  def is_logged_in?
    unless logged_in?
      flash[:notice] = t('notifications.not_logged_in')
      redirect_to root_path
    end
  end

  def has_access?
    is_logged_in?
  end

  private

  def set_locale
    store_locale_to_cookie(params[:locale]) if locale
    I18n.locale = cookies[:locale] || I18n.default_locale
  end

  def user_not_authorized
    redirect_to(user_path, notice: 'You are not authorized to perform this action.')
  end

  def user_path
    request.referrer || root_path
  end

  def chapters
    @chapters ||= Chapter.all
  end

  def redirect_back(fallback_location:, **args)
    if referer = request.headers['Referer']
      redirect_to referer, **args
    else
      redirect_to fallback_location, **args
    end
  end

  def store_locale_to_cookie(locale)
    cookies[:locale] = { value: locale,
                         expires: Time.zone.now + 36_000 }
  end

  def locale
    params[:locale] if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
  end
end


text:
using System;
using System.Collections.Generic;

namespace Fido_Main.Fido_Support.Objects.VirusTotal
{
  public class Object_VirusTotal_IP
  {
    public class IPReport
    {
      public List<DetectedURLs> DetectedUrls { get; set; }
      public List<Samples> UndetectedDownloadedSamples { get; set; }
      public List<Samples> DetectedCommunicatingSamples { get; set; }
      public List<Samples> UndetectedCommunicatingSamples { get; set; }
      public List<Samples> DetectedDownloadedSamples { get; set; }
      public List<Resolved> Resolutions { get; set; }
      public string VerboseMsg { get; set; }
    }

    public class Resolved
    {
      public string LastResolved { get; set; }
      public string Hostname { get; set; }
    }

    public class DetectedURLs
    {
      public string URL { get; set; }
      public int Positives { get; set; }
      public int Total { get; set; }
      public DateTime ScanDate { get; set; }
    }

    public class Samples
    {
      public DateTime Date { get; set; }
      public int Positives { get; set; }
      public int Total { get; set; }
      public string Sha256 { get; set; }
    }
  }
}


text:
import vue from 'rollup-plugin-vue'
import buble from 'rollup-plugin-buble'
import resolve from 'rollup-plugin-node-resolve'
import replace from 'rollup-plugin-replace'
import cjs from 'rollup-plugin-commonjs'
import { eslint } from 'rollup-plugin-eslint'

import pkg from '../package.json'

export default {
  input: 'src/index.js',
  external: ['vue'],
  plugins: [
    resolve({
      jsnext: true,
      main: true,
      browser: true,
    }),
    cjs(),
    eslint(),
    vue(),
    buble({
      transforms: { dangerousForOf: true },
    }),
    replace({
      VERSION: JSON.stringify(pkg.version),
    }),
  ],
}


text:
from dolfin import assemble, MixedFunctionSpace, tic,toc
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc

from  PackageName.Preconditioners import StokesApply, MaxwellApply, NSApply

def solve(A, b, SolveType = 'Direct', SolverSetup = {}):
    ksp = PETSc.KSP()
    ksp.create(comm=PETSc.COMM_WORLD)

    if SolveType == 'Direct':
        ksp.setType('preonly')
        pc = ksp.getPC()
        pc.setType('lu')
        OptDB = PETSc.Options()
        OptDB['pc_factor_mat_solver_package']  = "pastix"
        OptDB['pc_factor_mat_ordering_type']  = "rcm"
        ksp.setFromOptions()
        ksp.setTolerances(1e-10)
    else:
        ksp.setType(SolverSetup['ksp'])
        pc = ksp.getPC()
        pc.setType(SolverSetup['pc'])
        ksp.setTolerances(SolverSetup['tol'])

        if SolverSetup['eq'] == 'Stokes':
            pc.setPythonContext(StokesApply(SolverSetup['W'], SolverSetup['precondKsp']))
        elif SolverSetup['eq'] == 'Maxwell':
            pc.setPythonContext(MaxwellApply(SolverSetup['W'], SolverSetup['precondKsp']))
        elif SolverSetup['eq'] == 'NS':
            pc.setPythonContext(NSApply(SolverSetup['W'], SolverSetup['precondKsp']))

    ksp.max_it = 1000
    ksp.view()
    scale = b.norm()
    b = b/scale
    u = b.duplicate()

    ksp.setOperators(A,A)
    ksp.solve(b,u)

    u = u*scale

    iterations = {'GlobalIters': ksp.its}
    if iterations.has_key('HX'):
        iterations['HX'], iterations['CG'] = pc.getPythonContext().ReturnIters()
    return u, iterations


text:
<?php

/**
 * Simple collection object for transporting keys
 */
class SAML2_Certificate_FingerprintCollection extends SAML2_Utilities_ArrayCollection
{
    /**
     * Add a key to the collection
     *
     * @param SAML2_Certificate_Fingerprint $fingerprint
     */
    public function add($fingerprint)
    {
        if (!$fingerprint instanceof SAML2_Certificate_Fingerprint) {
            throw SAML2_Exception_InvalidArgumentException::invalidType(
                'SAML2_Certificate_Fingerprint ',
                $fingerprint
            );
        }

        parent::add($fingerprint);
    }

    /**
     * @param SAML2_Certificate_Fingerprint $otherFingerprint
     *
     * @return bool
     */
    public function contains(SAML2_Certificate_Fingerprint $otherFingerprint)
    {
        foreach ($this->elements as $fingerprint) {
            /** @var SAML2_Certificate_Fingerprint $fingerprint */
            if ($fingerprint->equals($otherFingerprint)) {
                return TRUE;
            }
        }

        return FALSE;
    }
}


text:
<?php

namespace Poli\JudgeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PoliJudgeBundle extends Bundle
{
}


text:
        This site uses dynamic routing to configure various aspects of its
        functionality; recreate the routes file using the button below.

    <?php

    echo form_open();
    echo '
' . form_submit( 'go', 'Rewrite Routes', 'class="btn btn-success"' ) . '
';
    echo form_close();

    ?>


text:
<?php

namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;

class FunctionSpacingSniff implements Sniff
{

    /**
     * The number of blank lines between functions.
     *
     * @var integer
     */
    public $spacing = 2;

    /**
     * The number of blank lines before the first function in a class.
     *
     * @var integer
     */
    public $spacingBeforeFirst = 2;

    /**
     * The number of blank lines after the last function in a class.
     *
     * @var integer
     */
    public $spacingAfterLast = 2;

    /**
     * Original properties as set in a custom ruleset (if any).
     *
     * @var array|null
     */
    private $rulesetProperties = null;

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return [T_FUNCTION];

    }//end register()

    /**
     * Processes this sniff when one of its tokens is encountered.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
     * @param int                         $stackPtr  The position of the current token
     *                                               in the stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr)
    {
        $tokens           = $phpcsFile->getTokens();
        $previousNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
        if ($previousNonEmpty !== false
            && $tokens[$previousNonEmpty]['code'] === T_OPEN_TAG
            && $tokens[$previousNonEmpty]['line'] !== 1
        ) {
            // Ignore functions at the start of an embedded PHP block.
            return;
        }

        // If the ruleset has only overridden the spacing property, use
        // that value for all spacing rules.
        if ($this->rulesetProperties === null) {
            $this->rulesetProperties = [];
            if (isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']) === true
                && isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties']) === true
            ) {
                $this->rulesetProperties = $phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties'];
                if (isset($this->rulesetProperties['spacing']) === true) {
                    if (isset($this->rulesetProperties['spacingBeforeFirst']) === false) {
                        $this->spacingBeforeFirst = $this->spacing;
                    }

                    if (isset($this->rulesetProperties['spacingAfterLast']) === false) {
                        $this->spacingAfterLast = $this->spacing;
                    }
                }
            }
        }

        $this->spacing            = (int) $this->spacing;
        $this->spacingBeforeFirst = (int) $this->spacingBeforeFirst;
        $this->spacingAfterLast   = (int) $this->spacingAfterLast;

        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
            // Must be an interface method, so the closer is the semicolon.
            $closer = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
        } else {
            $closer = $tokens[$stackPtr]['scope_closer'];
        }

        $isFirst = false;
        $isLast  = false;

        $ignore = ([T_WHITESPACE => T_WHITESPACE] + Tokens::$methodPrefixes);

        $prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true);

        while ($tokens[$prev]['code'] === T_ATTRIBUTE_END) {
            // Skip past function attributes.
            $prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['attribute_opener'] - 1), null, true);
        }

        if ($tokens[$prev]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
            // Skip past function docblocks.
            $prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['comment_opener'] - 1), null, true);
        }

        if ($tokens[$prev]['code'] === T_OPEN_CURLY_BRACKET) {
            $isFirst = true;
        }

        $next = $phpcsFile->findNext($ignore, ($closer + 1), null, true);
        if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === true
            && $tokens[$next]['line'] === $tokens[$closer]['line']
        ) {
            // Skip past "end" comments.
            $next = $phpcsFile->findNext($ignore, ($next + 1), null, true);
        }

        if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) {
            $isLast = true;
        }

        /*
            Check the number of blank lines
            after the function.
        */

        // Allow for comments on the same line as the closer.
        for ($nextLineToken = ($closer + 1); $nextLineToken < $phpcsFile->numTokens; $nextLineToken++) {
            if ($tokens[$nextLineToken]['line'] !== $tokens[$closer]['line']) {
                break;
            }
        }

        $requiredSpacing = $this->spacing;
        $errorCode       = 'After';
        if ($isLast === true) {
            $requiredSpacing = $this->spacingAfterLast;
            $errorCode       = 'AfterLast';
        }

        $foundLines = 0;
        if ($nextLineToken === ($phpcsFile->numTokens - 1)) {
            // We are at the end of the file.
            // Don't check spacing after the function because this
            // should be done by an EOF sniff.
            $foundLines = $requiredSpacing;
        } else {
            $nextContent = $phpcsFile->findNext(T_WHITESPACE, $nextLineToken, null, true);
            if ($nextContent === false) {
                // We are at the end of the file.
                // Don't check spacing after the function because this
                // should be done by an EOF sniff.
                $foundLines = $requiredSpacing;
            } else {
                $foundLines = ($tokens[$nextContent]['line'] - $tokens[$nextLineToken]['line']);
            }
        }

        if ($isLast === true) {
            $phpcsFile->recordMetric($stackPtr, 'Function spacing after last', $foundLines);
        } else {
            $phpcsFile->recordMetric($stackPtr, 'Function spacing after', $foundLines);
        }

        if ($foundLines !== $requiredSpacing) {
            $error = 'Expected %s blank line';
            if ($requiredSpacing !== 1) {
                $error .= 's';
            }

            $error .= ' after function; %s found';
            $data   = [
                $requiredSpacing,
                $foundLines,
            ];

            $fix = $phpcsFile->addFixableError($error, $closer, $errorCode, $data);
            if ($fix === true) {
                $phpcsFile->fixer->beginChangeset();
                for ($i = $nextLineToken; $i <= $nextContent; $i++) {
                    if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
                        $phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing));
                        break;
                    }

                    $phpcsFile->fixer->replaceToken($i, '');
                }

                $phpcsFile->fixer->endChangeset();
            }//end if
        }//end if

        /*
            Check the number of blank lines
            before the function.
        */

        $prevLineToken = null;
        for ($i = $stackPtr; $i >= 0; $i--) {
            if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) {
                continue;
            }

            $prevLineToken = $i;
            break;
        }

        if ($prevLineToken === null) {
            // Never found the previous line, which means
            // there are 0 blank lines before the function.
            $foundLines    = 0;
            $prevContent   = 0;
            $prevLineToken = 0;
        } else {
            $currentLine = $tokens[$stackPtr]['line'];

            $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, $prevLineToken, null, true);

            if ($tokens[$prevContent]['code'] === T_COMMENT
                || isset(Tokens::$phpcsCommentTokens[$tokens[$prevContent]['code']]) === true
            ) {
                // Ignore comments as they can have different spacing rules, and this
                // isn't a proper function comment anyway.
                return;
            }

            while ($tokens[$prevContent]['code'] === T_ATTRIBUTE_END
                && $tokens[$prevContent]['line'] === ($currentLine - 1)
            ) {
                // Account for function attributes.
                $currentLine = $tokens[$tokens[$prevContent]['attribute_opener']]['line'];
                $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['attribute_opener'] - 1), null, true);
            }

            if ($tokens[$prevContent]['code'] === T_DOC_COMMENT_CLOSE_TAG
                && $tokens[$prevContent]['line'] === ($currentLine - 1)
            ) {
                // Account for function comments.
                $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['comment_opener'] - 1), null, true);
            }

            $prevLineToken = $prevContent;

            // Before we throw an error, check that we are not throwing an error
            // for another function. We don't want to error for no blank lines after
            // the previous function and no blank lines before this one as well.
            $prevLine   = ($tokens[$prevContent]['line'] - 1);
            $i          = ($stackPtr - 1);
            $foundLines = 0;

            $stopAt = 0;
            if (isset($tokens[$stackPtr]['conditions']) === true) {
                $conditions = $tokens[$stackPtr]['conditions'];
                $conditions = array_keys($conditions);
                $stopAt     = array_pop($conditions);
            }

            while ($currentLine !== $prevLine && $currentLine > 1 && $i > $stopAt) {
                if ($tokens[$i]['code'] === T_FUNCTION) {
                    // Found another interface or abstract function.
                    return;
                }

                if ($tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET
                    && $tokens[$tokens[$i]['scope_condition']]['code'] === T_FUNCTION
                ) {
                    // Found a previous function.
                    return;
                }

                $currentLine = $tokens[$i]['line'];
                if ($currentLine === $prevLine) {
                    break;
                }

                if ($tokens[($i - 1)]['line'] < $currentLine && $tokens[($i + 1)]['line'] > $currentLine) {
                    // This token is on a line by itself. If it is whitespace, the line is empty.
                    if ($tokens[$i]['code'] === T_WHITESPACE) {
                        $foundLines++;
                    }
                }

                $i--;
            }//end while
        }//end if

        $requiredSpacing = $this->spacing;
        $errorCode       = 'Before';
        if ($isFirst === true) {
            $requiredSpacing = $this->spacingBeforeFirst;
            $errorCode       = 'BeforeFirst';

            $phpcsFile->recordMetric($stackPtr, 'Function spacing before first', $foundLines);
        } else {
            $phpcsFile->recordMetric($stackPtr, 'Function spacing before', $foundLines);
        }

        if ($foundLines !== $requiredSpacing) {
            $error = 'Expected %s blank line';
            if ($requiredSpacing !== 1) {
                $error .= 's';
            }

            $error .= ' before function; %s found';
            $data   = [
                $requiredSpacing,
                $foundLines,
            ];

            $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data);
            if ($fix === true) {
                $nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($prevContent + 1), $stackPtr);
                if ($nextSpace === false) {
                    $nextSpace = ($stackPtr - 1);
                }

                if ($foundLines < $requiredSpacing) {
                    $padding = str_repeat($phpcsFile->eolChar, ($requiredSpacing - $foundLines));
                    $phpcsFile->fixer->addContent($prevLineToken, $padding);
                } else {
                    $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), null, true);
                    $phpcsFile->fixer->beginChangeset();
                    for ($i = $nextSpace; $i < $nextContent; $i++) {
                        if ($tokens[$i]['line'] === $tokens[$prevContent]['line']) {
                            continue;
                        }

                        if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
                            $phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing));
                            break;
                        }

                        $phpcsFile->fixer->replaceToken($i, '');
                    }

                    $phpcsFile->fixer->endChangeset();
                }//end if
            }//end if
        }//end if

    }//end process()

}//end class


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cdn.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** settings for security policy patterns to match. */
@Fluent
public final class SecurityPolicyWebApplicationFirewallAssociation {
    /*
     * List of domains.
     */
    @JsonProperty(value = "domains")
    private List<ActivatedResourceReference> domains;

    /*
     * List of paths
     */
    @JsonProperty(value = "patternsToMatch")
    private List<String> patternsToMatch;

    /**
     * Get the domains property: List of domains.
     *
     * @return the domains value.
     */
    public List<ActivatedResourceReference> domains() {
        return this.domains;
    }

    /**
     * Set the domains property: List of domains.
     *
     * @param domains the domains value to set.
     * @return the SecurityPolicyWebApplicationFirewallAssociation object itself.
     */
    public SecurityPolicyWebApplicationFirewallAssociation withDomains(List<ActivatedResourceReference> domains) {
        this.domains = domains;
        return this;
    }

    /**
     * Get the patternsToMatch property: List of paths.
     *
     * @return the patternsToMatch value.
     */
    public List<String> patternsToMatch() {
        return this.patternsToMatch;
    }

    /**
     * Set the patternsToMatch property: List of paths.
     *
     * @param patternsToMatch the patternsToMatch value to set.
     * @return the SecurityPolicyWebApplicationFirewallAssociation object itself.
     */
    public SecurityPolicyWebApplicationFirewallAssociation withPatternsToMatch(List<String> patternsToMatch) {
        this.patternsToMatch = patternsToMatch;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (domains() != null) {
            domains().forEach(e -> e.validate());
        }
    }
}


text:
using System;
using System.Windows.Data;
using System.Windows;

namespace Rikrop.Core.Wpf.Converters
{
    public class ScrollbarOnButtonsVisibilityConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values == null) return false;
            if (values[0] == null || values[1] == null) return false;
            if (values[0].Equals(double.NaN) || values[1].Equals(double.NaN)) return false;

            double dblViewportWidth = 0;
            double dblExtentWidth = 0;

            double.TryParse(values[0].ToString(), out dblViewportWidth);
            double.TryParse(values[1].ToString(), out dblExtentWidth);

            bool flag = Math.Round((dblViewportWidth), 2) < Math.Round(dblExtentWidth, 2);

            return InvertConverterHelper.InvertValue(flag, Visibility.Visible, Visibility.Collapsed, string.Empty);
        }

        public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}


text:
@interface TailorxLeadingViewController : UIViewController

@property (nonatomic, strong) UIViewController *rootViewController;

@end


text:
.mightyslider_tabsGreen_skin {
	position: relative;
}

.mightyslider_tabsGreen_skin .frame {
	position: relative;
	border: #336c2b 1px solid;
	background: #FFF;
	z-index: 2;

	-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, .15);
	        box-shadow:0 1px 3px rgba(0, 0, 0, .15);

	-webkit-box-sizing: border-box;
	   -moz-box-sizing: border-box;
	        box-sizing: border-box;
}

.mightyslider_tabsGreen_skin .mSTabs {
	position: relative;
	z-index: 3;
}

.mightyslider_tabsGreen_skin .horizontal .mSTabs {
	margin-bottom: -1px;
}

.mightyslider_tabsGreen_skin .vertical .mSTabs {
	margin-right: -1px;
}

.mightyslider_tabsGreen_skin .mSTabs ul {
	list-style: none;
	margin: 0;
	padding: 0;
	white-space: nowrap;
}

.mightyslider_tabsGreen_skin .mSTabs ul li {
	display: inline-block;
	padding: 10px 15px;
	border: #336c2b 1px solid;
	cursor: pointer;
	font-weight: 300;
	color: #FFF;
	z-index: 1;
	background: rgb(41,154,11);

	-webkit-box-sizing: border-box;
	   -moz-box-sizing: border-box;
	        box-sizing: border-box;
}

.mightyslider_tabsGreen_skin .mSTabs ul li:hover {
	background: rgb(51,164,21);
}

.mightyslider_tabsGreen_skin .horizontal .mSTabs ul li {
	margin-right: -1px;
}

.mightyslider_tabsGreen_skin .vertical .mSTabs ul li {
	margin-bottom: -1px;
}

.mightyslider_tabsGreen_skin .horizontal .mSTabs ul li:first-of-type {
	-webkit-box-shadow: -3px 1px 1px -3px rgba(0, 0, 0, .15);
	        box-shadow: -3px 1px 1px -3px rgba(0, 0, 0, .15);
}

.mightyslider_tabsGreen_skin .horizontal .mSTabs ul li:last-of-type {
	margin-right: 0;

	-webkit-box-shadow: 3px 1px 1px -3px rgba(0, 0, 0, .15);
	        box-shadow: 3px 1px 1px -3px rgba(0, 0, 0, .15);
}

.mightyslider_tabsGreen_skin .vertical .mSTabs ul li:last-of-type {
	margin-bottom: 0;
}

.mightyslider_tabsGreen_skin .mSTabs ul li.active {
	background: #FFF;
	color: #000;
	font-weight: 600;
	z-index: 3;
}

.mightyslider_tabsGreen_skin .horizontal .mSTabs ul li.active {
	border-bottom-color: #FFF;
}

.mightyslider_tabsGreen_skin .vertical .mSTabs ul li.active {
	border-right-color: #FFF;
}

/* Style when it's low resolution */
.mightyslider_tabsGreen_skin.mSMobile, .mightyslider_tabsGreen_skin.mSVertical {
	border: #336c2b 1px solid;
	background: #FFF;

	-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .15);
	        box-shadow: 0 1px 3px rgba(0, 0, 0, .15);
}

.mightyslider_tabsGreen_skin.mSMobile .frame, .mightyslider_tabsGreen_skin.mSVertical .frame {
	position: relative;
	border: 0;
	z-index: 2;

	-webkit-box-shadow: none;
	        box-shadow: none;
}

.mightyslider_tabsGreen_skin.mSMobile .horizontal .mSTabs ul li {
	border-top: 0;
}

.mightyslider_tabsGreen_skin.mSVertical .mSTabs ul li {
	border-left: 0;
}

.mightyslider_tabsGreen_skin.mSMobile .horizontal .mSTabs ul li:first-of-type {
	border-left: 0;

	-webkit-box-shadow: none;
	        box-shadow: none;
}

.mightyslider_tabsGreen_skin.mSVertical .mSTabs ul li:first-of-type {
	border-top: 0;

	-webkit-box-shadow: none;
	        box-shadow: none;
}

.mightyslider_tabsGreen_skin.mSMobile .horizontal .mSTabs ul li:last-of-type {
	border-right: 0;

	-webkit-box-shadow: none;
	        box-shadow: none;
}


text:
(function Assembly(){
	"use strict";
	Assembly.Manifest = {
		ID: "htmlelements",
		Version: "1.0.0.0",
		References: ["common"],
		Resources: [] //Stylesheets, images, ...
	};

	var ns = window.cjw = (window.cjw || {});
	//register with assembly manager
	if((ns.Application) && (ns.Application.Loader.Register(Assembly) == false))
	{
		return;
	}

	//namespace declarations
	ns.HTMLElements = ns.HTMLElements || {};

//#include CHTMLElement.js
//#include CFlashElement.js
//#include CLabel.js
//#include CIcon.js
//#include CButton.js
//#include CLockingButton.js
//#include CDivider.js
//#include CInput.js
//#include CTextarea.js
//#include CSelect.js
//#include CTable.js
//#include COrderedList.js
//#include CListSelect.js
//#include CPagedScroller.js
//#include CPagedListSelect.js
//#include CCaptcha.js

	//inform assembly manager of readiness
	if(ns.Application)
	{
		ns.Application.Loader.Ready(Assembly);
	}

})();


text:
package com.github.plushaze.traynotification.animations;

import com.github.plushaze.traynotification.models.CustomStage;

import java.util.function.Function;

public enum Animations {

	SLIDE(SlideAnimation::new),
	FADE(FadeAnimation::new),
	POPUP(PopupAnimation::new);

	private final Function<CustomStage, Animation> newInstance;

	Animations(Function<CustomStage, Animation> newInstance) {
		this.newInstance = newInstance;
	}

	public Animation newInstance(CustomStage stage) {
		return newInstance.apply(stage);
	}

}


text:
These are the release notes for Fluent NHibernate 1.1. They're not exhaustive, and some points have been collated.

Read the [[upgrade guide|Release 1.1 upgrade guide]] if you are having any issues.

There are some breaking changes in this release, but they are minor. Some methods have been marked as obsolete, and you should follow the instructions on how to update your code; most obsolete methods are related to the automapping configuration changes (see below).

# General changes

  * Upgraded NHibernate binaries to 2.1.2GA
  * *Validation* - added clearer exceptions for when obvious mistakes are made when mapping classes (missing ids, for example)
  * *Fields* - private or otherwise, fields are now supported in the Fluent NHibernate automapper and using Reveal in the fluent interface

# Automapping

  * *External configuration* - compartmentalisation of the automapping configuration; no more giant-method-chain-lump. See: [[Auto mapping#Configuration|automapping configuration]]
  * *Multiple assembly support* - automap multiple assemblies at the same time; previously each assembly had to be configured individually
  * *Self-Referential relationships* - the automapper is now capable of understanding recursive/self-referential relationships
  * *Read-only properties* - you can now use read-only auto-properties, or backing-field based properties, to expose your collections in your entities.
  * *Intermediary base-type skipping* - you can ignore intermediary classes in an inheritance hierarchy without breaking the chain
  * *Collections of value types* - the automapper can now understand collections of value types
  * *Example project* - created an automapping example project.

# PersistenceSpecification

  * Additional checks are available, including enumerable support
  * VerifyTheMappings can be supplied with a pre-instantiated instance for when your entity doesn't have a default constructor
  * VerifyTheMappings returns the reloaded instance, which can be used for further assertions

# Databases

  * *Informix* database support
  * *Oracle8i* database support
  * *DB2* database support

# Fluent Interface

  * *ComponentMap* - map reusable components separate from where they'll be used.
  * Full entity-name support
  * Filters
  * Stored procedure support
  * Tuplizer for classes
  * Custom identity generator support
  * Bi-directional many-to-many method-based collections (pairing)
  * Natural Id support
  * Union subclass support
  * Nested components for collections
  * Improved multiple column support
  * Improved cascades, generators, and lazy compliance
  * General improved attribute compliance
  * Meta value and meta type support for any mappings

# Bug fixes

  * [automapping] Ignore static properties
  * [automapping] Map types in a predictable order
  * [automapping] Exclude components from being mapped as entities
  * [automapping] Joins and Discriminators in overrides not working
  * [automapping] Disabled dictionary automapping
  * [automapping] Removed SubclassStrategy in favour of the clearer IsDiscriminated
  * [conventions] ConventionBuilder not respecting acceptance criteria
  * [conventions] Collection conventions now apply to element and composite-element collections
  * [interface] Exceptions marked as serializable
  * [interface] Mutable defaults to true for class and collections
  * [interface] Component collection parent ordering issues
  * [interface] Class attribute written for components
  * [interface] byte[] version columns now work if they're declared in a baseclass
  * [interface] Formula properties don't output columns
  * [interface] HasOne lazy uses proxy instead of true
  * [interface] Properties in parallel subclasses were being excluded
  * [interface] GenericEnumMapper serializable
  * [interface] Added missing identity generators
  * [interface] Propertyless ids
  * [interface] Removed constraints from persister methods
  * [interface] Composite Id now respects reference and property ordering
  * [interface] Descriptive error messages for many-to-many
  * [interface] Extends support for SubclassMap
  * [interface] No proxy lazy support
  * [general] Export mappings to a TextWriter instead of just to file
  * [database] IsolationLevel in database config
  * [database] Password setting for SQLite configuration


text:
luabins — Lua Binary Serialization Library
==========================================

Allows to save tuples of primitive Lua types into binary chunks
and to load saved data back.

This is a fork of Alexander Gladysh luabins project for Lua 5.2

On serialization
----------------

### Luabins works with

 *  `nil`
 *  `boolean`
 *  `number`
 *  `string`
 *  `table` (see below)

### Luabins refuses to save

 *  `function`
 *  `thread`
 *  `userdata`

Luabins intentionally does not save or check any meta-information
(versions, endianness etc.) along with data. If needed, it is to be handled
elsewhere.

### Table serialization

1.  Metatatables are ignored.
2.  Table nesting depth should be no more than `LUABINS_MAXTABLENESTING`.
3.  On table save references are not honored. Each encountered reference
    becomes independent object on load:

        local t = { 42 }
        { t, t }

    becomes

        { { 42 }, { 42 } }

    that is, three separate tables instead of two.

Lua API
-------

 *  `luabins.save(...)`

    Saves arguments into a binary string.

     *   On success returns that string.
     *   On failure returns nil and error message.

    Example:

        local str = assert(luabins.save(1, "two", { "three", 4 }))

 *  `luabins.load(string)`

    Loads a list of values from a binary string.

     *  On success returns true and loaded values.
     *  On failure returns nil and error message.

    Example:

    If you do not know in advance what data is stored inside a binary string,
    you may put results into a table:

        local values = { luabins.load(data) }
        assert(values[1], values[2])

    If you know how to handle stored values (for example you're sure they were
    generated following some established protocol), you may want to use
    something like this function to check `luabins.load()` result:

        function eat_true(t, ...)
            assert(t, ...)
            return ...
        end

        my_value_handler(eat_true(luabins.load(data)))

C API
-----

 * `int luabins_save(lua_State * L, int index_from, int index_to)`

    Save Lua values from given state at given stack index range.
    Lua value is left untouched. Note that empty range is not an error.
    You may save from 0 to `LUABINS_MAXTUPLE` values.
    Note only real non-negative indices work.

     *  On success returns 0, pushes saved data as a string on the top of stack.
     *  On failure returns non-zero, pushes error message on the top
        of the stack.

 * `int luabins_load(lua_State * L, const unsigned char * data,
    size_t len, int *count)`

    Load Lua values from given byte chunk.

     *  On success returns 0, pushes loaded values on stack.
        Sets count to the number of values pushed.
        Note that to have zero loaded items is a valid scenario.
     *  On failure returns non-zero, pushes error message on the top
        of the stack.

Luabins is still an experimental volatile software.
Please see source code for more documentation.

See the copyright information in the file named `COPYRIGHT`.


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="2dp"
        android:top="2dp">
        <shape android:shape="rectangle" >
            <solid android:color="#55000000" />

            <corners android:radius="2dp" />
        </shape>
    </item>
    <item
        android:bottom="2dp"
        android:right="2dp">
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/holo_blue_light" />

            <corners android:radius="2dp" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>

</layer-list>


text:
Changelog
=========

v1.0.2
------
* Possibility to animate the view added

v1.0.1
------
* Added onMeasure behaviour to enable wrap_content and match_parent

v1.0.0
------
* Initial version available via Maven Central


text:
const mongoose = require("mongoose");

// Define a data model for BookSchema
const bookSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    datePublished: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model("Books", bookSchema);


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require 'cgi'

describe "CGI::QueryExtension#content_length" do
  before(:each) do
    @cgi = CGI.new
  end

  it "returns ENV['CONTENT_LENGTH'] as Integer" do
    old_value = ENV['CONTENT_LENGTH']
    begin
      ENV['CONTENT_LENGTH'] = nil
      @cgi.content_length.should be_nil

      ENV['CONTENT_LENGTH'] = "100"
      @cgi.content_length.should eql(100)
    ensure
      ENV['CONTENT_LENGTH'] = old_value
    end
  end
end


text:
FactoryGirl.define do
  factory :taxonomy, class: Elasticad::Taxonomy do
    name        "Taxonomy's name"
    description "Taxonomy's description"
  end
end


text:
<?php

namespace Google\Service\Firestore;

class PartitionQueryRequest extends \Google\Model
{
  /**
   * @var int
   */
  public $pageSize;
  /**
   * @var string
   */
  public $pageToken;
  /**
   * @var string
   */
  public $partitionCount;
  /**
   * @var string
   */
  public $readTime;
  protected $structuredQueryType = StructuredQuery::class;
  protected $structuredQueryDataType = '';

  /**
   * @param int
   */
  public function setPageSize($pageSize)
  {
    $this->pageSize = $pageSize;
  }
  /**
   * @return int
   */
  public function getPageSize()
  {
    return $this->pageSize;
  }
  /**
   * @param string
   */
  public function setPageToken($pageToken)
  {
    $this->pageToken = $pageToken;
  }
  /**
   * @return string
   */
  public function getPageToken()
  {
    return $this->pageToken;
  }
  /**
   * @param string
   */
  public function setPartitionCount($partitionCount)
  {
    $this->partitionCount = $partitionCount;
  }
  /**
   * @return string
   */
  public function getPartitionCount()
  {
    return $this->partitionCount;
  }
  /**
   * @param string
   */
  public function setReadTime($readTime)
  {
    $this->readTime = $readTime;
  }
  /**
   * @return string
   */
  public function getReadTime()
  {
    return $this->readTime;
  }
  /**
   * @param StructuredQuery
   */
  public function setStructuredQuery(StructuredQuery $structuredQuery)
  {
    $this->structuredQuery = $structuredQuery;
  }
  /**
   * @return StructuredQuery
   */
  public function getStructuredQuery()
  {
    return $this->structuredQuery;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PartitionQueryRequest::class, 'Google_Service_Firestore_PartitionQueryRequest');


text:
title: GitLab Enterprise Edition license change
date: February 11, 2014
author: Sytse Sijbrandij
---
On July 22, 2013 we [introduced GitLab Enterprise Edition (EE)](/2013/07/22/announcing-gitlab-enterprise-edition).
Since then, both EE and the Community Edition have grown and flourished.
There are now multiple Fortune 100 companies running the Enterprise Edition and the use of the Community Edition has doubled to 50.000 organizations.

We are now introducing a change to the EE license. As it stands today, the open source license of EE is confusing to some of our potential subscribers.
They expect that a subscription is needed to use the software.
Explaining the current open source license combined with a required subscription is not only confusing at times, but also time-consuming for us.
Therefore we are changing the license on the Enterprise Edition to one where the parts developed by GitLab.com are copyrighted by us.
We always expected organizations to have a valid subscription when using Enterprise Edition and this change formalizes that.

We hope you see how this licence change reduces confusion and increases the chance potential subscribers select GitLab as their primary code hosting tool.
We feel that the past 6 months have shown that the development of the Community Edition is a priority for GitLab.com.
With the help of the rest of the community we've done 5 releases with many new features and bug-fixes.
This is a process we want continue and the Community Edition will keep being a fully functional application that will not be restricted in any way.
And a lot more awesome features for GitLab CE and GitLab CI will be contributed by GitLab.com staff in the coming months.

In summary, we're changing the license of the Enterprise Edition but all the GitLab versions you know and love will continue to improve.
If you have any thoughts or questions please share them in the comments below.


text:
old_trap = trap("INT") { exit! 130 }

require "global"
require "build_options"
require "cxxstdlib"
require "keg"
require "extend/ENV"
require "debrew"
require "fcntl"
require "socket"
require "cmd/install"

# A formula build.
#
# @api private
class Build
  attr_reader :formula, :deps, :reqs, :args

  def initialize(formula, options, args:)
    @formula = formula
    @formula.build = BuildOptions.new(options, formula.options)
    @args = args

    if args.ignore_deps?
      @deps = []
      @reqs = []
    else
      @deps = expand_deps
      @reqs = expand_reqs
    end
  end

  def post_superenv_hacks
    # Only allow Homebrew-approved directories into the PATH, unless
    # a formula opts-in to allowing the user's path.
    return unless formula.env.userpaths? || reqs.any? { |rq| rq.env.userpaths? }

    ENV.userpaths!
  end

  def effective_build_options_for(dependent)
    args  = dependent.build.used_options
    args |= Tab.for_formula(dependent).used_options
    BuildOptions.new(args, dependent.options)
  end

  def expand_reqs
    formula.recursive_requirements do |dependent, req|
      build = effective_build_options_for(dependent)
      if req.prune_from_option?(build) || req.prune_if_build_and_not_dependent?(dependent, formula) || req.test?
        Requirement.prune
      end
    end
  end

  def expand_deps
    formula.recursive_dependencies do |dependent, dep|
      build = effective_build_options_for(dependent)
      if dep.prune_from_option?(build) ||
         dep.prune_if_build_and_not_dependent?(dependent, formula) ||
         (dep.test? && !dep.build?)
        Dependency.prune
      elsif dep.build?
        Dependency.keep_but_prune_recursive_deps
      end
    end
  end

  def install
    formula_deps = deps.map(&:to_formula)
    keg_only_deps = formula_deps.select(&:keg_only?)
    run_time_deps = deps.reject(&:build?).map(&:to_formula)

    formula_deps.each do |dep|
      fixopt(dep) unless dep.opt_prefix.directory?
    end

    ENV.activate_extensions!(env: args.env)

    if superenv?(args.env)
      ENV.keg_only_deps = keg_only_deps
      ENV.deps = formula_deps
      ENV.run_time_deps = run_time_deps
      ENV.x11 = reqs.any? { |rq| rq.is_a?(X11Requirement) }
      ENV.setup_build_environment(
        formula:      formula,
        cc:           args.cc,
        build_bottle: args.build_bottle?,
        bottle_arch:  args.bottle_arch,
      )
      post_superenv_hacks
      reqs.each do |req|
        req.modify_build_environment(
          env: args.env, cc: args.cc, build_bottle: args.build_bottle?, bottle_arch: args.bottle_arch,
        )
      end
      deps.each(&:modify_build_environment)
    else
      ENV.setup_build_environment(
        formula:      formula,
        cc:           args.cc,
        build_bottle: args.build_bottle?,
        bottle_arch:  args.bottle_arch,
      )
      reqs.each do |req|
        req.modify_build_environment(
          env: args.env, cc: args.cc, build_bottle: args.build_bottle?, bottle_arch: args.bottle_arch,
        )
      end
      deps.each(&:modify_build_environment)

      keg_only_deps.each do |dep|
        ENV.prepend_path "PATH", dep.opt_bin.to_s
        ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_lib}/pkgconfig"
        ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_share}/pkgconfig"
        ENV.prepend_path "ACLOCAL_PATH", "#{dep.opt_share}/aclocal"
        ENV.prepend_path "CMAKE_PREFIX_PATH", dep.opt_prefix.to_s
        ENV.prepend "LDFLAGS", "-L#{dep.opt_lib}" if dep.opt_lib.directory?
        ENV.prepend "CPPFLAGS", "-I#{dep.opt_include}" if dep.opt_include.directory?
      end
    end

    new_env = {
      "TMPDIR" => HOMEBREW_TEMP,
      "TEMP"   => HOMEBREW_TEMP,
      "TMP"    => HOMEBREW_TEMP,
    }

    with_env(new_env) do
      formula.extend(Debrew::Formula) if args.debug?

      formula.update_head_version

      formula.brew(
        fetch:       false,
        keep_tmp:    args.keep_tmp?,
        interactive: args.interactive?,
      ) do
        # For head builds, HOMEBREW_FORMULA_PREFIX should include the commit,
        # which is not known until after the formula has been staged.
        ENV["HOMEBREW_FORMULA_PREFIX"] = formula.prefix

        formula.patch

        if args.git?
          system "git", "init"
          system "git", "add", "-A"
        end
        if args.interactive?
          ohai "Entering interactive mode"
          puts "Type `exit` to return and finalize the installation."
          puts "Install to this prefix: #{formula.prefix}"

          if args.git?
            puts "This directory is now a git repo. Make your changes and then use:"
            puts "  git diff | pbcopy"
            puts "to copy the diff to the clipboard."
          end

          interactive_shell(formula)
        else
          formula.prefix.mkpath

          (formula.logs/"00.options.out").write \
            "#{formula.full_name} #{formula.build.used_options.sort.join(" ")}".strip
          formula.install

          stdlibs = detect_stdlibs(ENV.compiler)
          tab = Tab.create(formula, ENV.compiler, stdlibs.first)
          tab.write

          # Find and link metafiles
          formula.prefix.install_metafiles formula.buildpath
          formula.prefix.install_metafiles formula.libexec if formula.libexec.exist?
        end
      end
    end
  end

  def detect_stdlibs(compiler)
    keg = Keg.new(formula.prefix)
    CxxStdlib.check_compatibility(formula, deps, keg, compiler)

    # The stdlib recorded in the install receipt is used during dependency
    # compatibility checks, so we only care about the stdlib that libraries
    # link against.
    keg.detect_cxx_stdlibs(skip_executables: true)
  end

  def fixopt(f)
    path = if f.linked_keg.directory? && f.linked_keg.symlink?
      f.linked_keg.resolved_path
    elsif f.prefix.directory?
      f.prefix
    elsif (kids = f.rack.children).size == 1 && kids.first.directory?
      kids.first
    else
      raise
    end
    Keg.new(path).optlink(verbose: args.verbose?)
  rescue
    raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f.full_name}. Sorry :("
  end
end

begin
  args = Homebrew.install_args.parse
  Context.current = args.context

  error_pipe = UNIXSocket.open(ENV["HOMEBREW_ERROR_PIPE"], &:recv_io)
  error_pipe.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)

  trap("INT", old_trap)

  formula = args.named.to_formulae.first
  options = Options.create(args.flags_only)
  build   = Build.new(formula, options, args: args)
  build.install
rescue Exception => e # rubocop:disable Lint/RescueException
  error_hash = JSON.parse e.to_json

  # Special case: need to recreate BuildErrors in full
  # for proper analytics reporting and error messages.
  # BuildErrors are specific to build processes and not other
  # children, which is why we create the necessary state here
  # and not in Utils.safe_fork.
  case error_hash["json_class"]
  when "BuildError"
    error_hash["cmd"] = e.cmd
    error_hash["args"] = e.args
    error_hash["env"] = e.env
  when "ErrorDuringExecution"
    error_hash["cmd"] = e.cmd
    error_hash["status"] = e.status.exitstatus
    error_hash["output"] = e.output
  end

  error_pipe.puts error_hash.to_json
  error_pipe.close
  exit! 1
end


text:
package com.github.ccook.gtk.model.object.widget.container;

import com.github.ccook.gtk.model.object.widget.GtkContainer;

/**
 * Created by cam on 10/22/16.
 */
public class GtkTreeView extends GtkContainer {
}


text:
'use strict';

/**
 * Module dependencies.
 */
var util = require('util');
var BaseMQ = require('../basemq');

/**
 * Map of constants.
 */
var CONNECTION = require('../enum/connection');
var MODULE = require('../enum/module');
var SOCKET = require('../enum/socket');

/**
 * Create a new `Worker`.
 *
 * @constructor
 * @api public
 */
var Worker = module.exports = function Worker(opts) {
  BaseMQ.call(this, opts);
};

/**
 * Inherit from `BaseMQ.prototype`.
 */
util.inherits(Worker, BaseMQ);

/**
 * Settings default configuration.
 *
 * @api public
 */
Worker.prototype.initialize = function() {
  /**
   * Using default `Connection` approach.
   */
  this.use(MODULE.CONNECTION, {
    approach: CONNECTION.REQ,   // dealer
    socket: SOCKET.CONNECT, // connect
    endpoint: 'tcp://127.0.0.1:12345'
  });

  // call BaseMQ initialize method
  return Worker.super_.prototype.initialize.apply(this);
};


text:
module DTK; class Task; class Template
  class Content
    class InsertActionHelper
      require_relative('insert_action_helper/insert_at_end')
      require_relative('insert_action_helper/insert_at_start')
      require_relative('insert_action_helper/insert_at_start_in_subtask')

      # opts can have keys
      #   :gen_constraints_proc
      #   :insert_strategy
      def self.create(new_action, action_list, opts = {})
        insert_strategy_class(opts[:insert_strategy]).new(new_action, action_list, gen_constraints_proc: opts[:gen_constraints_proc])
      end

      def insert_action?(template_content)
        unless template_content.includes_action?(@new_action)
          compute_before_after_relations!
          insert_action!(template_content)
        end
      end
      # TODO: DTK-2680; Aldin: commented below out and temporarily put original in
      #  Curremtly what needs to be fixed is computing of @new_action
      #  Think there is a bug that does not match on new_action.method when new_action.is_a?(Action::WithMethod)
      #  What then happens is template_content.includes_action?(@new_action) succeds when it shouldnt
      #  (e.g, there is a component.create action in task template while looking for a delete component
      # Rich: I may need to explain or even cleanup what is in action list; it was initially created before
      # we had actions with methods (just create) so create actions and others modeled differently

      # in lib/common_dsl/object_logic/assembly/component/diff/delete.rb
#        if template_content.includes_action?(@new_action) && @add_delete_action
#          template_content.delete_explicit_action?(@new_action, @action_list)
#          compute_before_after_relations!
#          insert_action!(template_content, opts)
#        else
#        # unless template_content.includes_action?(@new_action)
#          compute_before_after_relations!
#          insert_action!(template_content)
#        end

      private

      # opts can have keys
      #   :gen_constraints_proc
      def initialize(new_action, action_list, opts = {})
        match_opts            = new_action.is_a?(Action::WithMethod) ? { class: Action::WithMethod } : {}
        @new_action           = action_list.find { |a| a.match_action?(new_action, match_opts) }
        @new_action_node_id   = new_action.node_id
        @gen_constraints_proc = opts[:gen_constraints_proc]
        @ndx_action_indexes   = NdxActionIndexes.new
        @action_list          = action_list
      end

      class NdxActionIndexes < Hash
        # These are of form
        #[:internode|:samenode][:before|:after]
        # which has value {node_id => [action_indexex],,,}
        def get(inter_or_same, before_or_after)
          (self[inter_or_same] || {})[before_or_after] || {}
        end

        def add(inter_or_same, before_or_after, action)
          pntr = ((self[inter_or_same] ||= {})[before_or_after] ||= {})
          Content.add_ndx_action_index!(pntr, action)
          self
        end
      end

      def self.insert_strategy_class(insert_strategy = nil)
        # default insert strategy is to put the new action in the latest existing internode stage at the latest point
        if insert_strategy
          unless ret = InsertStrategies[insert_strategy]
            fail Error.new("Illegal insert action strategy (#{insert_strategy})")
          end
          ret
        else
          InsertAtEnd
        end
      end

      InsertStrategies = {
        insert_at_end: InsertAtEnd,
        insert_at_start: InsertAtStart,
        insert_at_start_in_subtask: InsertAtStartInSubtask
      }

      def compute_before_after_relations!
        unless new_action_index = @new_action.index
          # if @new_action does not have an index it means that it is not in action list
          Log.error('Cannot find action in action list; using no constraints')
          return
        end

        temporal_constraints = @gen_constraints_proc && @gen_constraints_proc.call
        return if (temporal_constraints || []).empty?

        temporal_constraints.each do |tc|
          if tc.before_action_index == new_action_index
            after_action = tc.after_action
            if after_action.node_id == @new_action_node_id
              add_ndx_action_index(:samenode, :after, after_action)
            else
              add_ndx_action_index(:internode, :after, after_action)
            end
          elsif tc.after_action_index == new_action_index
            before_action = tc.before_action
            if before_action.node_id == @new_action_node_id
              add_ndx_action_index(:samenode, :before, before_action)
            else
              add_ndx_action_index(:internode, :before, before_action)
            end
          end
        end
      end

      def get_ndx_action_indexes(inter_or_same, before_or_after)
        @ndx_action_indexes.get(inter_or_same, before_or_after)
      end

      def add_ndx_action_index(inter_or_same, before_or_after, action)
        @ndx_action_indexes.add(inter_or_same, before_or_after, action)
      end
    end
  end
end; end; end


text:
package com.coolweather.app.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.coolweather.app.MyApplication;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.widget.Toast;

/**
 * ´ÓÍøÂç»ñÈ¡Êý¾ÝµÄ¹¤¾ßÀà
 *
 * @author Tomi_Enn
 *
 */
public class HttpUtil {
	public static boolean isConnected = false;

	public static void sendHttpRequest(final String adress,
			final HttpCallBackListener listener) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// SharedPreferences.Editor editor =
				// PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext()).edit();
				HttpURLConnection connection = null;
				try {
					URL url = new URL(adress);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(5000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					int statusCode = connection.getResponseCode();
					if (statusCode == HttpURLConnection.HTTP_OK) {
						/*
						 * isConnected = true; editor.putBoolean("isConnected",
						 * isConnected);
						 */
						while ((line = reader.readLine()) != null) {
							response.append(line);
						}
					} else {
						Toast.makeText(MyApplication.getContext(), "ÍøÂçÒì³£...",
								Toast.LENGTH_SHORT).show();
					}

					if (listener != null) {
						LogUtil.i("coolweather", "htttputil: listener done");
						listener.onFinish(response.toString());
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					if (listener != null) {
						listener.onError(e);
					}
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}).start();

	}

	public static void sendHttpRequest2(final String adress,
			final Handler handler) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// SharedPreferences.Editor editor =
				// PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext()).edit();
				HttpURLConnection connection = null;
				try {
					URL url = new URL(adress);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(5000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					int statusCode = connection.getResponseCode();
					if (statusCode == HttpURLConnection.HTTP_OK) {
						/*
						 * isConnected = true; editor.putBoolean("isConnected",
						 * isConnected);
						 */
						while ((line = reader.readLine()) != null) {
							response.append(line);
							String result = response.toString();
							Message message = new Message();
							message.obj = result;

							handler.sendMessage(message);
						}
					} else {
						Toast.makeText(MyApplication.getContext(), "ÍøÂçÒì³£...",
								Toast.LENGTH_SHORT).show();
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}).start();

	}

}


text:
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServiceStack.ServiceHost
{
    /// <summary>
    /// This interface can be implemented by an attribute
    /// which adds an response filter for the specific response DTO the attribute marked.
    /// </summary>
    public interface IHasResponseFilter
    {
		/// <summary>
		/// Order in which Response Filters are executed.
		/// <0 Executed before global response filters
		/// >0 Executed after global response filters
		/// </summary>
		int Priority { get; }

        /// <summary>
        /// The response filter is executed after the service
        /// </summary>
        /// <param name="req">The http request wrapper</param>
        /// <param name="res">The http response wrapper</param>
        /// <param name="requestDto">The response DTO</param>
        void ResponseFilter(IHttpRequest req, IHttpResponse res, object response);
    }
}
#endif


text:
package brokerage_server_ib

import (
	"context"
	"sync"
	"time"

	"github.com/dimfeld/brokerage_server/types"
	"github.com/dimfeld/ib"
)

func (p *IB) getLatestHistData(ctx context.Context, contract *ib.Contract, histTypes []ib.HistDataToShow) ([]*ib.HistoricalData, error) {

	wg := sync.WaitGroup{}
	histDataItems := make([]*ib.HistoricalData, len(histTypes))
	histDataErrors := make([]error, len(histTypes))
	wg.Add(len(histTypes))

	// Get a single bar for each historical data item. We do this because the IB
	// streaming data isn't always reliable, especially after hours.
	now := time.Now()
	for i, histType := range histTypes {
		go func(i int, histType ib.HistDataToShow) {
			defer wg.Done()
			req := ib.RequestHistoricalData{
				Contract:    *contract,
				EndDateTime: now,
				Duration:    "60 S",
				// Use 1 minute bars to avoid hitting IB's pacing restrictions.
				BarSize:    ib.HistBarSize1Min,
				WhatToShow: histType,
				UseRTH:     true,
			}

			histDataItems[i], histDataErrors[i] = p.oneHistoricalData(ctx, &req)
		}(i, histType)
	}

	wg.Wait()
	var err error
	for i, e := range histDataErrors {
		if e != nil {
			p.Logger.Error("Historical data error",
				"type", histTypes[i],
				"error", e.Error())
			err = e
		}
	}

	return histDataItems, err
}

func (p *IB) oneHistoricalData(ctx context.Context, req *ib.RequestHistoricalData) (*ib.HistoricalData, error) {

	var output *ib.HistoricalData
	_, err := p.syncMatchedRequest(ctx, req, func(r ib.Reply) (replyBehavior, error) {
		switch data := r.(type) {
		case *ib.ErrorMessage:
			if data.Code == IBErrNoDataReturned {
				return REPLY_DONE, nil
			}
			return REPLY_DONE, data.Error()
		case *ib.HistoricalData:
			output = data
			return REPLY_DONE, nil
		default:
			p.Logger.Warn("HistoricalData: unexpected reply", "msg", r)
		}

		return REPLY_CONTINUE, nil
	})

	return output, err
}

func (p *IB) GetHistoricalData(ctx context.Context, params types.HistoricalDataParams) ([]*types.Quote, error) {

	which := params.Which
	var dataType ib.HistDataToShow
	switch params.Which {
	default:
		which = types.HistoricalDataTypePrice
		fallthrough
	case types.HistoricalDataTypePrice:
		dataType = ib.HistTrades
	case types.HistoricalDataTypeIv:
		dataType = ib.HistOptionIV
	case types.HistoricalDataTypeHv:
		dataType = ib.HistVolatility

	}

	if params.Option.Underlying != "" && dataType != ib.HistTrades {
		return nil, types.ArgError("options historical quotes must be for price data")
	}

	var key ContractKey
	if params.Symbol != "" {
		key = ContractKey{
			Symbol:       params.Symbol,
			SecurityType: "STK",
		}
	} else {
		key = ContractKeyFromOption(&params.Option)
	}
	details, err := p.contractManager.GetContractDetails(ctx, key)
	if err != nil {
		return nil, err
	} else if len(details) == 0 {
		return nil, types.ArgError("Contract not found")
	}

	// Get an estimate of the proper array size.
	totalBars := params.Duration / params.BarWidth
	output := make([]*types.Quote, 0, totalBars)

	req := &ib.RequestHistoricalData{
		Contract:    details[0].Summary,
		EndDateTime: params.EndTime,
		WhatToShow:  dataType,
		Duration:    durationToIbDuration(params.Duration),
		BarSize:     durationToBarWidth(params.BarWidth),
		UseRTH:      !params.IncludeAH,
	}

	_, err = p.syncMatchedRequest(ctx, req, func(r ib.Reply) (replyBehavior, error) {
		switch data := r.(type) {
		case *ib.ErrorMessage:
			return REPLY_DONE, data.Error()
		case *ib.HistoricalData:
			for i, _ := range data.Data {
				item := &data.Data[i]
				quote := &types.Quote{
					High:   item.High,
					Low:    item.Low,
					Open:   item.Open,
					Close:  item.Close,
					Volume: item.Volume,
					Time:   item.Date,
				}

				if which == types.HistoricalDataTypeHv {
					quote.OptionHistoricalVolatility = item.Close
				} else if which == types.HistoricalDataTypeIv {
					quote.OptionImpliedVolatility = item.Close
				}
				output = append(output, quote)
			}

			return REPLY_DONE, nil
		default:
			p.Logger.Warn("HistoricalData: unexpected reply", "msg", r)
		}

		return REPLY_CONTINUE, nil
	})

	return output, nil
}


text:
title: ZenKaffe
author: Ross Kaffenberger
summary: A simple API for a sip of inspiration built on node.js
description: A simple API for a sip of inspiration built on node.js
published: true
homepage: 'https://zenkaffe.herokuapp.com/says'
links:
  'Try it out': 'https://zenkaffe.herokuapp.com/says'
  'Source code on GitHub': 'https://github.com/rossta/zenkaffe'
tags:
  - Code
  - JavaScript
tech:
  - javascript
  - node.js
  - express
  - passport
  - mongoose
  - mongodb
---

A text-only API for with zen-like phrases of inspiration. The snippets are randomly queried and display in the banner of this blog. Built on [node.js](https://nodejs.org), [express](http://expressjs.com/), [passport](http://passportjs.org/), and [mongoose](http://mongoosejs.com/).