text:
dojo.provide("plugins.workflow.IO");

/*

SET THE DEFAULT CHAINED VALUES FOR INPUTS AND OUTPUTS FOR AN
APPLICATION BASED ON THOSE OF THE PREVIOUS APPLICATIONS

E.G., THE NAME OF THE OUTPUT FILE FOR AN APPLICATION CAN BE MADE
TO DEPEND ON THE INPUTS FOR THE APPLICATION. IN THIS CASE, THE
args, inputParams AND paramFunction ENTRIES PROVIDE THE MEANS
TO INFER THE NAME OF THE OUTPUT FILE:

	stageParameters = [
	{
		"owner": "admin",
		"value": "",
		"args": "input.inputfile.value",
		"inputParams": "inputfile",
		"appname": "eland2ace.pl",
		"apptype": "converter",
		"argument": "",
		"category": "acefile",
		"valuetype": "file",
		"project": "Project1",
		"workflow": "Workflow1",
		"appnumber": "2"
		name: "acefile",
		paramtype: "output",
		format: "ace",
		args: [ 'arguments.inputfile.value' ],
		inputParams : [inputfile],
		paramFunction: "var acefile = inputfile; acefile = acefile.replace(/\\.txt/, \".ace\"); return acefile;"
	},
	...
*/

// INHERITS
dojo.require("plugins.core.Common");

dojo.declare( "plugins.workflow.IO",
	[ plugins.core.Common ],
{

////}

// PARENT WIDGET
parentWidget : null,

// CORE WORKFLOW OBJECTS
core : null,

constructor : function(args) {
	//console.log("IO.constructor     args:");
	//console.dir({args:args});

	// GET INFO FROM ARGS
	this.core = args.core;
	this.parentWidget = args.parentWidget;

	// LOAD CSS
	this.loadCSS();
},
postCreate : function() {
	this.startup();
},
startup : function () {
	//console.log("IO.startup    plugins.workflow.IO.startup()");
	// COMPLETE CONSTRUCTION OF OBJECT
	this.inherited(arguments);
},
chainStage : function (application, force) {
// 		1. SET INPUTS DEPENDENT ON THE OUTPUTS OF THE PREVIOUS STAGE
// 		2. SET RESOURCES DEPENDENT ON INPUTS OF THIS STAGE
// 		3. SET OUTPUTS DEPENDENT ON INPUTS AND RESOURCES OF THIS STAGE
//      (NB: REPEAT STEP 3 IF USER CHANGES RESOURCES MANUALLY)
	//console.log("IO.chainStage     plugins.workflow.IO.chainStage(application, force)");
	//console.log("IO.chainStage     application: " + dojo.toJson(application));
	//console.log("IO.chainStage     force: " + force);

	var chained = new Object;

	// SET INPUTS
	//console.log("IO.chainStage     Doing INPUTS for application: " + application.name);
	// RETURN IF NO PRECEDING APPLICATIONS
	if ( application.number != 1 )
	{
		chained.inputs = this.chainInputs(application, force);
	}

	//// SET RESOURCESsf
	////console.log("IO.chainStage     Doing RESOURCES for application: " + application.name);
	//application = this.chainResources(application.arguments, application);
	//

	// SET OUTPUTS
	//console.log("IO.chainStage     Doing OUTPUTS for application: " + application.name);
	chained.outputs = this.chainOutputs(application, force);

	// UPDATE VALID/INVALID CSS IN PARAMETERS PANE
	if ( this.core.parameters != null
		&& this.core.parameters.isCurrentApplication(application) )
			this.core.parameters.setParameterRowStyles();

	//console.log("IO.chainStage     END");

	return chained;
},
chainInputs : function (application, force) {
// GET INPUTS FOR AN APPLICATION, BASED ON THE INPUTS, OUTPUTS
// AND OR RESOURCES OF THE PREVIOUS APPLICATION

	//console.log("IO.chainInputs     plugins.workflow.IO.chainInputs(application)");
	//console.log("IO.chainInputs     application: " );
	//console.dir({application:application});

	// GET THE input STAGE PARAMETERS FOR THIS STAGE
	var stageParameters = Agua.getStageParameters(application);
	var inputParameters = this.filterByKeyValues(dojo.clone(stageParameters), ["paramtype"], ["input"]);
	//console.log("IO.chainInputs     stageParameters: ");
	//console.dir({stageParameters:stageParameters});

	// GET THE STAGE PARAMETERS FOR THE PRECEDING STAGE
	var appnumber = application.appnumber;
	if ( appnumber == null )
	{
		//console.log("IO.chainInputs     appnumber is null. Returning");
		return;
	}
	//console.log("IO.chainInputs     appnumber: " + appnumber);

	var stages = Agua.getStagesByWorkflow(application.project, application.workflow);
	//console.log("IO.chainInputs     stages: ");
	//console.dir({stages:stages});
	//console.log("IO.chainInputs     no. stages: " + stages.length);
	if ( stages == null )
	{
		//console.log("IO.chainInputs     stages is null. Returning");
		return;
	}

	//console.log("IO.chainInputs     previousStage = stages[" + (appnumber - 2) + "]");
	var previousStage = stages[appnumber - 2];
	if ( previousStage == null )
	{
		//console.log("IO.chainInputs     previousStage is null. Returning");
		return;
	}
	//console.log("IO.chainInputs     previousStage: ");
	//console.dir({previousStage:previousStage});

	var previousStageParameters = Agua.getStageParameters(previousStage);
	if ( previousStageParameters == null )
	{
		//console.log("IO.chainInputs     previousStageParameters is null. Returning");
		return;
	}
	//console.log("IO.chainInputs     previousStageParameters: ");
	//console.dir({previousStageParameters:previousStageParameters});

	for ( var i = 0; i < inputParameters.length; i++ )
	{
		//console.log("IO.chainInputs     ***************** Doing chainStageParameter inputParameters[" + i + "].name: " + inputParameters[i].name);
		//console.log("IO.chainInputs     " + inputParameters[i].name + " args: " + inputParameters[i].args);
		//console.log("IO.chainInputs     " + inputParameters[i].name + " inputParams: " + inputParameters[i].inputParams);
		//console.log("IO.chainInputs     " + inputParameters[i].name + " pararmFunction: " + inputParameters[i].paramFunction);
		//console.dir({inputParameter:inputParameters[i]});
		this.chainStageParameter(inputParameters[i], previousStageParameters, force);
	}
	//console.log("IO.chainInputs     Doing chainStageParameter " + i);

	//console.log("IO.chainInputs     inputParameters: ");
	//console.dir({inputParameters:inputParameters});
	return inputParameters;

},  //  chainInputs
chainResources: function (application, force) {
/*  GET RESOURCES FOR AN APPLICATION, BASED ON THE INPUTS, OUTPUTS

	AND/OR RESOURCES OF THE CURRENT APPLICATION
*/

},
chainOutputs : function (application, force) {
// GET OUTPUTS FOR AN APPLICATION, BASED ON THE INPUTS AND/OR
//	RESOURCES OF THE APPLICATION
	//console.log("IO.chainOutputs     plugins.workflow.IO.chainOutputs(application, force)");
	//console.log("IO.chainOutputs     application: " + dojo.toJson(application));

	// GET THE input STAGE PARAMETERS FOR THIS STAGE
	var stageParameters = Agua.getStageParameters(application);
	//console.log("IO.chainOutputs     stageParameters: " + dojo.toJson(stageParameters));

	// GET OUTPUT STAGE PARAMETERS ONLY
	var outputParameters = dojo.clone(stageParameters);
	outputParameters = this.filterByKeyValues(dojo.clone(outputParameters), ["paramtype"], ["output"]);
	//console.log("IO.chainOutputs     outputParameters: " + dojo.toJson(outputParameters));

	for ( var i = 0; i < outputParameters.length; i++ )
	{
		//console.log("IO.chainOutputs     Doing chainStageParameter " + i);
		this.chainStageParameter(outputParameters[i], stageParameters, force);
	}
	//console.log("IO.chainOutputs     Returning outputParameters: " + dojo.toJson(outputParameters, true));

	return outputParameters;
},
chainStageParameter : function (stageParameter, sourceParameters, force) {
	//console.log("IO.chainStageParameter     plugins.workflow.IO.chainStageParameter(stageParameter, sourceParameters, force)");
	////console.log("IO.chainStageParameter     stageParameter: " + dojo.toJson(stageParameter));
	//console.log("IO.chainStageParameter     stageParameter.name: " + stageParameter.name);
	//console.log("IO.chainStageParameter     force: " + force);

	// RETURN IF args IS NULL
	if ( stageParameter.args == null || stageParameter.args == '' )
	{
		//console.log("IO.chainStageParameter     stageParameters.args is null or empty. Returning.");
		return;
	}

	var valuesArray = this.getValuesArray(stageParameter, dojo.clone(sourceParameters));
	//console.log("IO.chainStageParameter     valuesArray: ");
	//console.dir({valuesArray:valuesArray});
	var value = this.getValue(valuesArray, stageParameter.inputParams, stageParameter.paramFunction);
	//console.log("IO.chainStageParameter     value: " + value);

	// REPLACE EMPTY STAGE PARAMETER VALUE IN Agua AND REMOTE DATABASE
	// OR OVERWRITE EXISTING VALUE IF force IS TRUE
	if ( (force == true && value != null && value != '' )
		|| (value != null && value != '' && stageParameter.value == '') )
	{
		//console.log("IO.chainStageParameter     Adding chained value to stageParameter: " + value);

		stageParameter.value = value;
		stageParameter.chained = 1;
		Agua._removeStageParameter(stageParameter);
		Agua.addStageParameter(stageParameter);
		Agua.setParameterValidity(stageParameter, true);
	}
},
getValuesArray : function(parameter, sourceParameters) {
// GET THE ARRAY OF VALUES FOR THE args TO BE INPUT INTO THE paramFunction
	//console.log("IO.getValuesArray     plugins.workflow.WorfklowIO.getValuesArray(parameter, sourceParameters)");
	//console.log("IO.getValuesArray     parameter : ");
	//console.dir({parameter:parameter});
	//console.log("IO.getValuesArray     sourceParameters : ");
	//console.dir({sourceParameters:sourceParameters});
	// SANITY CHECK
	if ( parameter.args == null || sourceParameters == null )
	{
		return;
	}
	// CONVERT args TO argsArray
	var argsArray = parameter.args.split(/,/);
	//console.log("IO.getValuesArray     argsArray: ");
	//console.dir({argsArray:argsArray});

	// RETURN AN ARRAY
	var valuesArray = new Array;

	var thisObject = this;
	//dojo.forEach(argsArray, function(args, i) {

	for ( var i = 0; i < argsArray.length; i++ ) {
		var args = argsArray[i];
		args = args.replace(/\s+/g, '');

		//console.log("IO.getValuesArray     argsArray[" + i + "]: " + argsArray[i]);
		//console.log("IO.getValuesArray     args: " + args);

		// EXTRACT ARGUMENT VALUE FROM APPLICATION OBJECT
		var array = args.split("\.");
		var paramtypeToken = array[0];
		var nameToken = array[1];
		var valueToken = array[2];
		//console.log("IO.getValuesArray     paramtypeToken: " + paramtypeToken);
		//console.log("IO.getValuesArray     nameToken: " + nameToken);
		//console.log("IO.getValuesArray     valueToken: " + valueToken);

		// FILTER BY PARAMTYPE TYPE (input|resource|output)
		var sources = dojo.clone(sourceParameters);
		sources = thisObject.filterByKeyValues(dojo.clone(sources), ["paramtype"], [paramtypeToken]);
		//console.log("IO.getValuesArray     '" + paramtypeToken + "' sources: ");
		//console.dir({sources:sources});

		// IF SOURCE PARAMETERS NOT PRESENT, SET VALUE TO ''
		if ( sources == null || sources.length == 0 )
		{
			valuesArray.push(null);
			continue;
		}
		// IF THE ARRAY OF SOURCE PARAMETERS WAS WANTED, STORE IT AND NEXT
		if ( nameToken == null || nameToken == '' )
		{
			valuesArray.push(sources);
			continue;
		}
		// GET THE SOURCE PARAMETER
		//console.log("IO.getValuesArray     BEFORE GET sourceParameter, nameToken: " + nameToken);
		var source = thisObject.filterByKeyValues(dojo.clone(sources), ["name"], [nameToken])[0];
		//console.log("IO.getValuesArray     " + nameToken + " source: ");
		//console.dir({source:source});

		// IF SOURCE PARAMETER NOT DEFINED, SET VALUE TO ''
		if ( source == null || source == '' )
		{
			valuesArray.push(null);
			continue;
		}

		// IF THE WHOLE PARAMETER HASH WAS WANTED, STORE IT AND NEXT
		if ( valueToken == null )
		{
			valuesArray.push(source);
			continue;
		}

		// OTHERWISE, GET THE PARAMETER'S VALUE
		var value = source.value;
		//console.log("IO.getValuesArray     value: " + value);
		valuesArray.push(value);
	}
//);
	//////console.log("IO.getValuesArray     Returning valuesArray: " + dojo.toJson(valuesArray));
	return valuesArray;
},
getValue : function (valuesArray, inputParams, paramFunction) {
// GET THE PARAMETER VALUE USING THE paramFunction IF PRESENT.
// OTHERWISE, RETURN A SCALAR OF THE FIRST ENTRY IN valuesArray
	//console.log("IO.getValue     plugins.workflow.Workflow.value(valuesArray, inputParams, paramFunction)");
	//console.log("IO.getValue     valuesArray: " + dojo.toJson(valuesArray));
	//console.log("IO.getValue     inputParams: " + dojo.toJson(inputParams));
	//console.log("IO.getValue     paramFunction: " + dojo.toJson(paramFunction));

	var value;
	if ( inputParams == null || inputParams == ''
		|| paramFunction == null || paramFunction == '' )
	{
		//console.log("IO.getValue     inputParams NOT DEFINED. Returning first entry in valuesArray: " + dojo.toJson(valuesArray));
		for ( var i = 0; i < valuesArray.length; i++ )
		{
			if ( valuesArray[i] == null || valuesArray[i] == '' )	continue;
			return valuesArray[i];
		}
	}

	// SET THE FUNCTION
	var inputParamsArray = inputParams.slice(',');
	var argumentFunction = new Function( inputParamsArray , paramFunction );

	// RUN THE FUNCTION WITH THE INPUT PARAMETER VALUES
	// HACK TO INPUT PARAMETER VALUES
    //var values = Array.prototype.slice.call( arguments, 2 );

	value = argumentFunction(valuesArray[0], valuesArray[1], valuesArray[2], valuesArray[3], valuesArray[4]);
	// THIS DOESN'T WORK
	//value = argumentFunction(valuesArray);
	//console.log("IO.getValue     value: " + value);

	return value;
}

});


text:
using System;
using System.Runtime.InteropServices;

namespace LibraryWithRids
{
    public static class MacNativeMethods
    {
        [DllImport("libsqlite3", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr sqlite3_libversion();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#region License

#endregion

#region Imports

using System;
using System.Collections;
using System.Globalization;
using System.Text;
using Spring.Util;

#endregion

namespace Spring.Objects
{
    ///
    /// Default implementation of the <see cref="Spring.Objects.IPropertyValues"/>
    /// interface.
    ///
    /// <remarks>
    ///

    /// Allows simple manipulation of properties, and provides constructors to
    /// support deep copy and construction from a number of collection types such as
    /// <see cref="System.Collections.IDictionary"/> and
    /// <see cref="System.Collections.IList"/>.
    ///

    /// </remarks>
    /// <author>Rod Johnson</author>
    /// <author>Mark Pollack (.NET)</author>
    /// <author>Rick Evans (.NET)</author>
    [Serializable]
    public class MutablePropertyValues : IPropertyValues
    {
        #region Fields

        ///
        /// The list of <see cref="Spring.Objects.PropertyValue"/> objects.
        ///
        private IList propertyValuesList = new ArrayList();

        #endregion

        #region Constructor (s) / Destructor

        ///
        /// Creates a new instance of the <see cref="Spring.Objects.MutablePropertyValues"/>
        /// class.
        ///
        /// <remarks>
        ///

        /// The returned instance is initially empty...
        /// <see cref="Spring.Objects.PropertyValue"/>s can be added with the various
        /// overloaded <see cref="Spring.Objects.MutablePropertyValues.Add(PropertyValue)"/>,
        /// <see cref="Spring.Objects.MutablePropertyValues.Add(string, object)"/>,
        /// <see cref="Spring.Objects.MutablePropertyValues.AddAll(IDictionary)"/>,
        /// and <see cref="Spring.Objects.MutablePropertyValues.AddAll(IList)"/>
        /// methods.
        ///

        /// </remarks>
        /// <seealso cref="Spring.Objects.MutablePropertyValues.Add (PropertyValue)"/>
        /// <seealso cref="Spring.Objects.MutablePropertyValues.Add (string, object)"/>
        public MutablePropertyValues ()
        {
        }

        ///
        /// Creates a new instance of the <see cref="Spring.Objects.MutablePropertyValues"/>
        /// class.
        ///
        /// <remarks>
        ///

        /// Deep copy constructor. Guarantees <see cref="Spring.Objects.PropertyValue"/>
        /// references are independent, although it can't deep copy objects currently
        /// referenced by individual <see cref="Spring.Objects.PropertyValue"/> objects.
        ///

        /// </remarks>
        public MutablePropertyValues (IPropertyValues other)
        {
            if (other != null)
            {
                AddAll (other.PropertyValues);
            }
        }

        ///
        /// Creates a new instance of the <see cref="Spring.Objects.MutablePropertyValues"/>
        /// class.
        ///
        /// <param name="map">
        /// The <see cref="System.Collections.IDictionary"/> with property values
        /// keyed by property name, which must be a <see cref="System.String"/>.
        /// </param>
        public MutablePropertyValues (IDictionary map)
        {
            AddAll (map);
        }

        #endregion

        #region Properties

        ///
        /// Property to retrieve the array of property values.
        ///
        public PropertyValue[] PropertyValues
        {
            get { return (PropertyValue[]) ArrayList.Adapter (propertyValuesList).ToArray (typeof (PropertyValue)); }
        }

        #endregion

        #region Methods

        ///
        /// Overloaded version of <c>Add</c> that takes a property name and a property value.
        ///
        /// <param name="propertyName">
        /// The name of the property.
        /// </param>
        /// <param name="propertyValue">
        /// The value of the property.
        /// </param>
        public void Add (string propertyName, object propertyValue)
        {
            Add (new PropertyValue (propertyName, propertyValue));
        }

        ///
        /// Add the supplied <see cref="Spring.Objects.PropertyValue"/> object,
        /// replacing any existing one for the respective property.
        ///
        /// <param name="pv">
        /// The <see cref="Spring.Objects.PropertyValue"/> object to add.
        /// </param>
        public void Add (PropertyValue pv)
        {
            for (int i = 0; i < propertyValuesList.Count; ++i)
            {
                PropertyValue currentPv = (PropertyValue) propertyValuesList [i];
                if (currentPv.Name.Equals (pv.Name))
                {
                    pv = MergeIfRequired(pv, currentPv);
                    propertyValuesList[i] = pv;
                    return ;
                }
            }
            propertyValuesList.Add (pv);
        }

        ///
        /// Merges the value of the supplied 'new' <see cref="PropertyValue"/> with that of
        /// the current <see cref="PropertyValue"/> if merging is supported and enabled.
        ///
        /// <see cref="IMergable"/>
        /// <param name="newPv">The new pv.</param>
        /// <param name="currentPv">The current pv.</param>
        /// <returns>The possibly merged PropertyValue</returns>
        private PropertyValue MergeIfRequired(PropertyValue newPv, PropertyValue currentPv)
        {
            object val = newPv.Value;
            IMergable mergable = val as IMergable;
            if (mergable != null)
            {
                if (mergable.MergeEnabled)
                {
                    object merged = mergable.Merge(currentPv.Value);
                    return new PropertyValue(newPv.Name, merged);
                }
            }
            return newPv;
        }

        ///
        /// Add all property values from the given
        /// <see cref="System.Collections.IDictionary"/>.
        ///
        /// <param name="map">
        /// The map of property values, the keys of which must be
        /// <see cref="System.String"/>s.
        /// </param>
        public void AddAll (IDictionary map)
        {
            if (map != null)
            {
                foreach (string key in map.Keys)
                {
                    Add (new PropertyValue (key, map [key]));
                }
            }
        }

        ///
        /// Add all property values from the given
        /// <see cref="System.Collections.IList"/>.
        ///
        /// <param name="values">
        /// The list of <see cref="Spring.Objects.PropertyValue"/>s to be added.
        /// </param>
        public void AddAll (IList values)
        {
            if (values != null)
            {
                foreach (PropertyValue value in values)
                {
                    Add (value);
                }
            }
        }

        ///
        /// Remove the given <see cref="Spring.Objects.PropertyValue"/>, if contained.
        ///
        /// <param name="pv">
        /// The <see cref="Spring.Objects.PropertyValue"/> to remove.
        /// </param>
        public void Remove (PropertyValue pv)
        {
            propertyValuesList.Remove (pv);
        }

        ///
        /// Removes the named <see cref="Spring.Objects.PropertyValue"/>, if contained.
        ///
        /// <param name="propertyName">
        /// The name of the property.
        /// </param>
        public void Remove (string propertyName)
        {
            Remove (GetPropertyValue (propertyName));
        }

        ///
        /// Modify a <see cref="Spring.Objects.PropertyValue"/> object held in this object. Indexed from 0.
        ///
        public void SetPropertyValueAt (PropertyValue pv, int i)
        {
            propertyValuesList [i] = pv;
        }

        ///
        /// Return the property value given the name.
        ///
        /// <remarks>
        /// The property name is checked in a <c>case-insensitive</c> fashion.
        /// </remarks>
        /// <param name="propertyName">
        /// The name of the property.
        /// </param>
        /// <returns>
        /// The property value.
        /// </returns>
        public PropertyValue GetPropertyValue (string propertyName)
        {
            string propertyNameLowered = propertyName.ToLower (CultureInfo.CurrentCulture);
            foreach (PropertyValue pv in propertyValuesList)
            {
                if (pv.Name.ToLower(CultureInfo.CurrentCulture).Equals (propertyNameLowered))
                {
                    return pv;
                }
            }
            return null;
        }

        ///
        /// Does the container of properties contain one of this name.
        ///
        /// <param name="propertyName">The name of the property to search for.</param>
        /// <returns>
        /// True if the property is contained in this collection, false otherwise.
        /// </returns>
        public bool Contains (string propertyName)
        {
            return GetPropertyValue (propertyName) != null;
        }

        ///
        /// Return the difference (changes, additions, but not removals) of
        /// property values between the supplied argument and the values
        /// contained in the collection.
        ///
        /// <param name="old">Another property values collection.</param>
        /// <returns>
        /// The collection of property values that are different than the supplied one.
        /// </returns>
        public IPropertyValues ChangesSince (IPropertyValues old)
        {
            MutablePropertyValues changes = new MutablePropertyValues ();
            if (old == this)
            {
                return changes;
            }
            // for each property value in this (the newer set)
            foreach (PropertyValue newProperty in propertyValuesList)
            {
                PropertyValue oldProperty = old.GetPropertyValue (newProperty.Name);
                if (oldProperty == null)
                {
                    // if there wasn't an old one, add it
                    changes.Add (newProperty);
                }
                else if (!oldProperty.Equals (newProperty))
                {
                    // it's changed
                    changes.Add (newProperty);
                }
            }
            return changes;
        }

        ///
        /// Returns an <see cref="System.Collections.IEnumerator"/> that can iterate
        /// through a collection.
        ///
        /// <remarks>
        ///

        /// The returned <see cref="System.Collections.IEnumerator"/> is the
        /// <see cref="System.Collections.IEnumerator"/> exposed by the
        /// <see cref="Spring.Objects.MutablePropertyValues.PropertyValues"/>
        /// property.
        ///

        /// </remarks>
        /// <returns>
        /// An <see cref="System.Collections.IEnumerator"/> that can iterate through a
        /// collection.
        /// </returns>
        public IEnumerator GetEnumerator ()
        {
            return PropertyValues.GetEnumerator ();
        }

        // CLOVER:OFF

        ///
        /// Convert the object to a string representation.
        ///
        /// <returns>
        /// A string representation of the object.
        /// </returns>
        public override string ToString ()
        {
            PropertyValue[] pvs = PropertyValues;
            StringBuilder sb
                = new StringBuilder (
                    "MutablePropertyValues: length=").Append (pvs.Length).Append ("; ");
            sb.Append (StringUtils.ArrayToDelimitedString (pvs, ","));
            return sb.ToString ();
        }

        // CLOVER:ON

        #endregion
    }
}


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

namespace Pirate.PiVote.Crypto
{
  public enum CryptoLogLevel
  {
    None = 0,
    Summary = 1,
    Detailed = 2,
    Numeric = 3,
    Secret = 4
  }
}


text:
define([
    'mongoose'
], function (mongoose) {
    'use strict';

    var Schema = mongoose.Schema,
    // Action schema
        Client = new Schema({
            alias: {
                type: String,
                required: true,
                unique: true
            },
            name: {
                type: String,
                required: true,
                unique: true
            },
            active: {
                type: Boolean,
                required: true,
                'default': false
            },
            host: String,
            user: String,
            password: String,
            port: String
        }),
        ClientModel = mongoose.model('Client', Client);

    return {
        model: ClientModel,
        schema: Client,
        systemdb: true
    };
});


text:
require 'test_helper'

class RemoteServerJobTest < ActiveJob::TestCase
  setup do
    @ssh = mock('ssh')
    Net::SSH.stubs(:start).yields(@ssh)
  end

  test "#perform ruby_trunk" do
    [
      'tsp docker pull rubybench/ruby_trunk',
      "tsp docker run --rm
        -e \"RUBY_BENCHMARKS=true\"
        -e \"RUBY_MEMORY_BENCHMARKS=false\"
        -e \"RUBY_COMMIT_HASH=commit_hash\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        -e \"INCLUDE_PATTERNS=bm_app_answer,bm_abc\"
        rubybench/ruby_trunk".squish
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform(
      'commit_hash', 'ruby_trunk',
      {
        ruby_benchmarks: true, ruby_memory_benchmarks: false,
        include_patterns: 'bm_app_answer,bm_abc'
      }
    )
  end

  test "#perform ruby_releases" do
    [
      'tsp docker pull rubybench/ruby_releases',
      "tsp docker run --rm
        -e \"RUBY_BENCHMARKS=true\"
        -e \"RUBY_MEMORY_BENCHMARKS=false\"
        -e \"RUBY_VERSION=2.2.0\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        -e \"INCLUDE_PATTERNS=bm_app_answer,bm_abc\"
        rubybench/ruby_releases".squish
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform(
      '2.2.0', 'ruby_releases',
      {
        ruby_benchmarks: true, ruby_memory_benchmarks: false,
        include_patterns: 'bm_app_answer,bm_abc'
      }
    )
  end

  test "#perform ruby_releases_discourse" do
    [
      "tsp docker pull rubybench/ruby_releases_discourse",
      "tsp docker run --name discourse_redis -d redis:2.8.19",
      "tsp docker run --name discourse_postgres -d postgres:9.3.5",
      "tsp docker run --rm
        --link discourse_postgres:postgres
        --link discourse_redis:redis
        -e \"RUBY_VERSION=2.2.0\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        rubybench/ruby_releases_discourse".squish,
      "tsp docker stop discourse_postgres discourse_redis",
      "tsp docker rm discourse_postgres discourse_redis"
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform('2.2.0', 'ruby_releases_discourse')
  end

  test "#perform ruby_trunk_discourse" do
    [
      "tsp docker pull rubybench/ruby_trunk_discourse",
      "tsp docker run --name discourse_redis -d redis:2.8.19",
      "tsp docker run --name discourse_postgres -d postgres:9.3.5",
      "tsp docker run --rm --link discourse_postgres:postgres
        --link discourse_redis:redis -e \"RUBY_COMMIT_HASH=commit_hash\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        rubybench/ruby_trunk_discourse".squish,
      "tsp docker stop discourse_postgres discourse_redis",
      "tsp docker rm discourse_postgres discourse_redis"
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform('commit_hash', 'ruby_trunk_discourse')
  end

  test "#perform rails_releases" do
    [
      "tsp docker pull rubybench/rails_releases",
      "tsp docker run --name postgres -d postgres:9.3.5",
      "tsp docker run --name mysql -e \"MYSQL_ALLOW_EMPTY_PASSWORD=yes\" -d mysql:5.6.24",
      "tsp docker run --rm
        --link postgres:postgres
        --link mysql:mysql
        -e \"RAILS_VERSION=4.0.0\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        -e \"INCLUDE_PATTERNS=bm_activerecord_scope\"
        rubybench/rails_releases".squish,
      "tsp docker stop postgres mysql",
      "tsp docker rm postgres mysql"
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform(
      '4.0.0', 'rails_releases',
      {
        include_patterns: 'bm_activerecord_scope'
      }
    )
  end

  test "#perform rails_trunk" do
    [
      "tsp docker pull rubybench/rails_trunk",
      "tsp docker run --name postgres -d postgres:9.3.5",
      "tsp docker run --name mysql -e \"MYSQL_ALLOW_EMPTY_PASSWORD=yes\" -d mysql:5.6.24",
      "tsp docker run --rm
        --link postgres:postgres
        --link mysql:mysql
        -e \"RAILS_COMMIT_HASH=1234\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        -e \"INCLUDE_PATTERNS=bm_activerecord_scope\"
        rubybench/rails_trunk".squish,
      "tsp docker stop postgres mysql",
      "tsp docker rm postgres mysql"
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform(
      '1234', 'rails_trunk',
      {
        include_patterns: 'bm_activerecord_scope'
      }
    )
  end

  test "#perform bundler_releases" do
    [
      "tsp docker pull rubybench/bundler_releases",
      "tsp docker run --rm
        -e \"BUNDLER_VERSION=1.10.6\"
        -e \"API_NAME=#{Rails.application.secrets.api_name}\"
        -e \"API_PASSWORD=#{Rails.application.secrets.api_password}\"
        -e \"INCLUDE_PATTERNS=bm_something\"
        rubybench/bundler_releases".squish
    ].each do |command|

      @ssh.expects(:exec!).with(command)
    end

    RemoteServerJob.new.perform(
      '1.10.6', 'bundler_releases',
      {
        include_patterns: 'bm_something'
      }
    )
  end

end


text:
jQuery(function($) {
  // Asynchronously Load the map API
  var script = document.createElement('script');
  script.src = "//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
  document.body.appendChild(script);
});

function initialize() {
  var map;
  var bounds = new google.maps.LatLngBounds();
  var style = [
    {
        "featureType": "water",
        "elementType": "labels.text",
        "stylers": [
            {"visibility": "simplified"},
            {"invert_lightness": false},
            {"color": "#004963"},
            {"weight": 8}
        ]
    },
    {
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
            {"invert_lightness": false},
            {"color": "#b7ebeb"},
            {"saturation": -53},
            {"lightness": 2}
        ]
    },
    {
        "featureType": "landscape.man_made",
        "elementType": "geometry",
        "stylers": [
            {"visibility": "on"},
            {"invert_lightness": false},
            {"hue": "#767878"},
            {"saturation": -93},
            {"lightness": 56}]
    },
    {
        "featureType": "landscape.man_made",
        "elementType": "geometry.stroke",
        "stylers": [
            {"visibility": "on"},
            {"color": "#b8dbe0"},
            {"saturation": -7},
            {"lightness": 33}]
    },
    {
        "featureType": "poi",
        "elementType": "all",
        "stylers": [
            {"visibility": "simplified"},
            {"saturation": -1}]
    },
    {
        "featureType": "poi.park",
        "elementType": "geometry.fill",
        "stylers": [
            {"color": "#d1e6d7"}]
    },
    {
        "featureType": "poi.sports_complex",
        "elementType": "all",
        "stylers": [
            {"saturation": -100},
            {"lightness": 61}]
    },
    {
        "featureType": "poi.school",
        "elementType": "all",
        "stylers": [
            {"visibility": "off"},
            {"saturation": -100},
            {"lightness": 80}]
    },
    {
        "featureType": "poi.place_of_worship",
        "elementType": "all",
        "stylers": [
            {"visibility": "off"}]
    },
    {
        "featureType": "poi.business",
        "elementType": "all",
        "stylers": [
            {"visibility": "off"}]
    },
    {
        "featureType": "administrative.land_parcel",
        "elementType": "labels.text",
        "stylers": [
            {"visibility": "simplified"},
            {"color": "#d74340"},
            {"saturation": -32}]
    },
    {
        "featureType": "transit.line",
        "elementType": "all",
        "stylers": [
            {"visibility": "off"}]
    },
    {
        "featureType": "transit.station.rail",
        "elementType": "labels.text.fill",
        "stylers": [
            {"color": "#d74340"}]
    },
    {
        "featureType": "transit.station.rail",
        "elementType": "labels.icon",
        "stylers": [
            {"visibility": "simplified"},
            {"lightness": 0},
            {"gamma": 2.05}]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [
            {"lightness": 100}]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [
            {"saturation": -100},
            {"lightness": 78}]
    },
    {
        "featureType": "road.highway",
        "elementType": "labels.text.fill",
        "stylers": [
            {"visibility": "on"},
            {"color": "#000000"},
            {"lightness": 40}]
    },
    {
        "featureType": "road.arterial",
        "elementType": "geometry.stroke",
        "stylers": [
            {"saturation": -100},
            {"lightness": 54}]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry.stroke",
        "stylers": [
            {"visibility": "on"},
            {"saturation": -100},
            {"lightness": 28}]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry.fill",
        "stylers": [
            {"color": "#ffffff"}]
    }
]

  var mapOptions = {
      mapTypeId: 'terrain',
      styles: style
  };

  // Display a map on the page
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  map.setTilt(45);

  //creating infowindow on map
  var infoWindow = new google.maps.InfoWindow()

  //ajax call
  var url = window.location.href + "/markers.json";

  var getMarkers = function(){
    return $.ajax({
      type: "GET",
      url: url,
      dataType: "json"
    });
  }

  var jsonResponse = getMarkers().done(
    function(data){
    var markers = formatData(data)
    plotPoints(markers)
  });

  img_2 = "https://openmerchantaccount.com/img/csb_leethackers.jpg"

  var jsonResponseFail = getMarkers().fail(
    function(data){
    var markers = [
      ["Flatiron School", 40.705866, -74.014056, "Lots of crying. I accidentally pantsed myself. Also supermodels hang out here. Wat... At least I learned how to code!!"],
      ["Yankee Stadium", 40.830406, -73.926088, "A blackout-drunk SOX fan (seated behind two small children) taught me some new explatives  as her husband periodically glanced back at us with sullen, apologetic eyes. Yanks are too good."],
      ["Hoboken", 40.7500, -74.0300, "They have Street Fighter tournaments... for hobos!"],
      ["Grand Oaks Country Club", 40.550844, -74.205496, "Where my frat brother became my step-dad."]
    ]
    plotPoints(markers)
  });

  function formatData(data){
    var arr = [];

    for( i = 0; i < data["markers"].length; i++ ) {
      var singleMarker = [];
      singleMarker.push(data["markers"][i]["name"]);
      singleMarker.push(data["markers"][i]["latitude"]);
      singleMarker.push(data["markers"][i]["longitude"]);
      singleMarker.push(data["markers"][i]["description"]);
      arr.push(singleMarker);
    }
    return arr
  }

  var star = "https://openmerchantaccount.com/img/quote_marker.png"

  function plotPoints(markers){
    for( i = 0; i < markers.length; i++ ) {
      var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
      bounds.extend(position);
      marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0],
        icon: star
       });

      //assign click handler to each location icon
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
              infoWindow.setContent("<h3>" + markers[i][0]
                                    + "</h3>" + "<p>" + markers[i][3]);
              infoWindow.open(map, marker);
        }
      })(marker, i));
    }

    map.fitBounds(bounds);
  }

}


text:
namespace WalletWasabi.Fluent.ViewModels.Navigation
{
	public interface INavigatable
	{
		void OnNavigatedTo(bool isInHistory);

		void OnNavigatedFrom(bool isInHistory);
	}
}


text:
import shutil, os, sys, subprocess, winshell

#Unzip files
#def unzip(fileName):

#Copy Files
def copyFolder(path):
    shutil.copytree(path, r'C:\Program Files')

if __name__ == "__main__":
    #Install JDK
    #os.startfile(r'RequiredFiles\jdk-7u60-windows-x64.exe')

    #Move Maven to Program Files
    #shutil.copytree(r'RequiredFiles\Maven', r'C:\Program Files\Maven')
    #(Add maven to windows Path)

    #Move Eclipse to Program Files
    #shutil.copytree(r'RequiredFiles\eclipse', r'C:\Program Files\eclipse')
    #Move Eclipse's short cut to the desktop
    #shutil.copy(r'C:\Program Files\eclipse\Eclipse.lnk', winshell.desktop() + "\Eclipse.lnk")

    #Move SQL Developer to Program Files
    #shutil.copytree(r'RequiredFiles\sqldeveloper', r'C:\Program Files\sqldeveloper')
    #Move SQL Developer's short cut to the desktop
    #shutil.copy(r'C:\Program Files\sqldeveloper\SQL Developer.lnk', winshell.desktop() + "\SQL Developer.lnk")

    #Move Hosts file
    #shutil.copy(r'RequiredFiles\hosts', r'C:\Windows\System32\drivers\etc\hosts')

    #Install Notepad++
    #os.startfile(r'RequiredFiles\npp.6.6.3.Installer.exe')

    #Install WinRar
    #os.startfile(r'RequiredFiles\winrar-x64-501.exe')

    #Install GitBash
    #os.startfile(r'RequiredFiles\Git-1.9.2-preview20140411.exe')

    #Install TortoiseSVN
    #os.startfile(r'RequiredFiles\TortoiseSVN-1.8.7.25475-x64-svn-1.8.9.msi')

    #Install UltraVNC
    #os.startfile(r'RequiredFiles\UltraVNC_1_1_9_X64_Setup.exe')


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.util;

import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightRecordCanonicalConstructor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.Collections;
import java.util.List;

/**
 * Java access modifiers: public, protected, private, package-local
 */
public enum AccessModifier
{
	PUBLIC(PsiModifier.PUBLIC),
	PROTECTED(PsiModifier.PROTECTED),
	PACKAGE_LOCAL(PsiModifier.PACKAGE_LOCAL),
	PRIVATE(PsiModifier.PRIVATE);
	public static final List<AccessModifier> ALL_MODIFIERS = ContainerUtil.immutableList(values());

	private static final List<AccessModifier> PUBLIC_PACKAGE = ContainerUtil.immutableList(PUBLIC, PACKAGE_LOCAL);
	private static final List<AccessModifier> PUBLIC_PRIVATE = ContainerUtil.immutableList(PUBLIC, PRIVATE);

	@Nonnull
	@PsiModifier.ModifierConstant
	private final String myModifier;

	AccessModifier(@PsiModifier.ModifierConstant @Nonnull String modifier)
	{
		myModifier = modifier;
	}

	/**
	 * @return a {@link PsiModifier} string constant which corresponds to this access modifier.
	 */
	@Nonnull
	@PsiModifier.ModifierConstant
	public String toPsiModifier()
	{
		return myModifier;
	}

	/**
	 * Checks whether given modifier owner has this access modifier (probably implicit)
	 *
	 * @param owner element to check (e.g. class member)
	 * @return true if it has current modifier
	 */
	public boolean hasModifier(@Nonnull PsiModifierListOwner owner)
	{
		return owner.hasModifierProperty(toPsiModifier());
	}

	/**
	 * Returns an {@link AccessModifier} which corresponds to the given keyword;
	 * null if supplied keyword is null or don't correspond to access modifier
	 *
	 * @param keyword keyword to convert to access modifier
	 * @return a corresponding access modifier
	 */
	@Contract(value = "null -> null", pure = true)
	@Nullable
	public static AccessModifier fromKeyword(@Nullable PsiKeyword keyword)
	{
		return keyword == null ? null : fromPsiModifier(keyword.getText());
	}

	/**
	 * Returns an {@link AccessModifier} which corresponds to the given String constant declared in
	 * {@link PsiModifier} class.
	 *
	 * @param modifier a modifier string
	 * @return an access modifier or null if supplied string doesn't correspond to any access modifier.
	 */
	@Contract(value = "null -> null", pure = true)
	@Nullable
	public static AccessModifier fromPsiModifier(@Nullable String modifier)
	{
		if(modifier == null)
		{
			return null;
		}
		switch(modifier)
		{
			case PsiModifier.PUBLIC:
				return PUBLIC;
			case PsiModifier.PROTECTED:
				return PROTECTED;
			case PsiModifier.PACKAGE_LOCAL:
				return PACKAGE_LOCAL;
			case PsiModifier.PRIVATE:
				return PRIVATE;
			default:
				return null;
		}
	}

	public static AccessModifier fromModifierList(@Nonnull PsiModifierList modifierList)
	{
		if(modifierList.hasModifierProperty(PsiModifier.PRIVATE))
		{
			return PRIVATE;
		}
		if(modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL))
		{
			return PACKAGE_LOCAL;
		}
		if(modifierList.hasModifierProperty(PsiModifier.PROTECTED))
		{
			return PROTECTED;
		}
		return PUBLIC;
	}

	public boolean isWeaker(@Nonnull AccessModifier other)
	{
		return compareTo(other) < 0;
	}

	@Override
	public String toString()
	{
		return PsiBundle.visibilityPresentation(toPsiModifier());
	}

	@Nonnull
	public static List<AccessModifier> getAvailableModifiers(PsiMember member)
	{
		if(member == null)
		{
			return Collections.emptyList();
		}
		PsiClass containingClass = member.getContainingClass();
		if(member instanceof PsiField)
		{
			if(member instanceof PsiEnumConstant || containingClass == null || containingClass.isInterface())
			{
				return Collections.emptyList();
			}
			return ALL_MODIFIERS;
		}
		if(member instanceof PsiMethod)
		{
			PsiMethod method = (PsiMethod) member;
			if(containingClass == null || containingClass.isEnum() && method.isConstructor())
			{
				return Collections.emptyList();
			}
			if(JavaPsiRecordUtil.getRecordComponentForAccessor(method) != null)
			{
				return Collections.singletonList(PUBLIC);
			}
			if(JavaPsiRecordUtil.isCompactConstructor(method) ||
					JavaPsiRecordUtil.isExplicitCanonicalConstructor(method) ||
					method instanceof LightRecordCanonicalConstructor)
			{
				PsiModifierList list = containingClass.getModifierList();
				if(list != null)
				{
					AccessModifier classModifier = fromModifierList(list);
					return ContainerUtil.filter(ALL_MODIFIERS, m -> !classModifier.isWeaker(m));
				}
				return Collections.singletonList(PUBLIC);
			}
			if(containingClass.isInterface())
			{
				if(method.getBody() != null && PsiUtil.isLanguageLevel9OrHigher(member))
				{
					return PUBLIC_PRIVATE;
				}
				return Collections.singletonList(PUBLIC);
			}
			AccessModifier minAccess = getMinAccess(method);
			if(minAccess != PRIVATE)
			{
				return ContainerUtil.filter(ALL_MODIFIERS, mod -> mod.compareTo(minAccess) <= 0);
			}
			return ALL_MODIFIERS;
		}
		if(member instanceof PsiClass)
		{
			if(PsiUtil.isLocalOrAnonymousClass((PsiClass) member))
			{
				return Collections.emptyList();
			}
			if(containingClass == null)
			{
				return PUBLIC_PACKAGE;
			}
			return ALL_MODIFIERS;
		}
		return Collections.emptyList();
	}

	@Nonnull
	private static AccessModifier getMinAccess(PsiMethod method)
	{
		if(method.isConstructor() || method.hasModifierProperty(PsiModifier.STATIC))
		{
			return PRIVATE;
		}
		HierarchicalMethodSignature signature = method.getHierarchicalMethodSignature();
		AccessModifier lowest = PRIVATE;
		for(HierarchicalMethodSignature superSignature : signature.getSuperSignatures())
		{
			PsiMethod superMethod = superSignature.getMethod();
			AccessModifier current = fromModifierList(superMethod.getModifierList());
			if(!current.isWeaker(lowest))
			{
				continue;
			}
			if(method.hasModifierProperty(PsiModifier.ABSTRACT) && !MethodSignatureUtil.isSuperMethod(superMethod, method))
			{
				continue;
			}
			if(!PsiUtil.isAccessible(method.getProject(), superMethod, method, null))
			{
				continue;
			}
			lowest = current;
			if(lowest == PUBLIC)
			{
				break;
			}
		}
		return lowest;
	}
}


text:
namespace TD
{
	class TDMesh;
	class TDTriangle;
	class TDAABB;
	class TDSphere;
	struct BVHNode;
	struct RayCast;
	class TDBox;
	class TDMeshShape;
	struct TriangleInterection
	{
		glm::vec3 Point = glm::vec3();
		TDTriangle* Tri = nullptr;
		float depth = 0;
	};
	class TDBVH
	{
	public:
		TDBVH();
		~TDBVH();
		void BuildAccelerationStructure(TDMesh* Shape);
		void SplitBVH(BVHNode* node, TDMesh* model, int depth);
		void FreeBVHNode(BVHNode* node);
		bool TraverseForSphere(TDSphere * A, std::vector<TriangleInterection>& contacts, int MaxContactCount);
		bool TraverseForBox(TDBox* A, std::vector<TriangleInterection>& contacts, int MaxContactCount);
		void Render();
		bool TraverseForRay(RayCast * ray, TDMeshShape* shape);
		TDMesh* TargetMesh = nullptr;
		BVHNode* Root = nullptr;
	private:
		int MaxDepth = 10;
		int Targetcount = 100;
	};

	struct BVHNode
	{
		TDAABB* bounds;
		int numTriangles;
		std::vector<BVHNode> children;
		std::vector<int> TrianglesIndexs;
	};
};


text:
from __future__ import absolute_import

from flask_babel import gettext as __
import flask

import auth
import config
import model
import util

from main import app

google_config = dict(
  access_token_method='POST',
  access_token_url='https://accounts.google.com/o/oauth2/token',
  api_base_url='https://www.googleapis.com/oauth2/v1/',
  authorize_url='https://accounts.google.com/o/oauth2/auth',
  client_id=config.CONFIG_DB.google_client_id,
  client_secret=config.CONFIG_DB.google_client_secret,
  client_kwargs={'scope': 'email profile'},
)

google = auth.create_oauth_app(google_config, 'google')

@app.route('/api/auth/callback/google/')
def google_authorized():
  id_token = google.authorize_access_token()
  if id_token is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  me = google.get('userinfo')
  user_db = retrieve_user_from_google(me.json())
  return auth.signin_user_db(user_db)

@app.route('/signin/google/')
def signin_google():
  return auth.signin_oauth(google)

def retrieve_user_from_google(response):
  auth_id = 'google_%s' % response['id']
  user_db = model.User.get_by('auth_ids', auth_id)
  if user_db:
    return user_db

  name = response.get('name', '')
  if not name:
    given_name = response.get('given_name', '')
    family_name = response.get('family_name', '')
    name = ' '.join([given_name, family_name]).strip()
  if not name:
    name = 'google_user_%s' % id
  email = response.get('email', '')
  return auth.create_user_db(
    auth_id=auth_id,
    name=name,
    username=email or name,
    email=email,
    verified=bool(email),
  )


text:
Rule `no-url-domains` will enforce that domains are not used within urls.

## Examples

When enabled, the following are allowed:

```scss
.foo {
  background-image: url('/img/bar.png');
}

.foo {
  background-image: url('img/bar.png');
}

.foo {
  background-image: url('bar.png');
}
```

When enabled, the following are disallowed:

```scss
.foo {
  background-image: url('https://foo.com/img/bar.png');
}

.foo {
  background-image: url('http://foo.com/img/bar.png');
}

.foo {
  background-image: url('//foo.com/img/bar.png');
}
```


text:
"""
Netcdf utilities

Basically, read NSSL netcdf data. Lots of boring stuff here.
The main points are:
    1. Finding our special NetCDF attributes and variables
    3. Reading a NSSL Polar Radial Dataset
       OR reading a NSSL LatLonGrid Dataset
    2. Handling our custom sparse data storage

@author: Robert Toomey (retoomey)
"""

# We use numpy for matrix data storage
import numpy, datetime

from w2py import log
from w2py.datatype import datatype as datatype
from w2py.datatype import radialset
from w2py.datatype import latlongrid

def getDimension(data, dim):
    """ Read in first element of a netcdf dimension...if there's an
        exception return False. We have some optional dimension data, this
        makes the code cleaner
    """
    haveIt = False
    try:
        data.getDimensionValue(dim, 0)
        haveIt = True
    except:
        # Assume it's not there...
        pass
    return haveIt

# FIXME: Probably break up into classes eventually....
def readRadialSet(data, isSparse):
    """ Try to read in a NSSL RadialSet data format.
    """
    # Get the radar elevation in degrees
    e = data.getAttributeValue("", "Elevation")
    elevation = float(e)
    log.info("Radar elevation angle: {0} degrees.".format(elevation))

    # Get distance to first gate in meters
    d = data.getAttributeValue("", "RangeToFirstGate")
    distToFirstGate = float(d)
    log.info("Distance to first gate: {0} meters.".format(distToFirstGate))

    # Read the main data of the file into 2D array
    datatype = data.getAttributeValue("", "TypeName")
    # Assume Sparse
    M = None
    if isSparse:
        log.info("Data type is SPARSE")
        M = readSparseArray2Dfloat(data, datatype, "Azimuth", "Gate")
    else:
        log.info("Data is not SPARSE")
        M = readArray2Dfloat(data, datatype, "Azimuth", "Gate")

    # Ok, now create the radial set

    if M != None:
        log.info("X size is "+str(M.shape[0]))
        log.info("Y size is "+str(M.shape[1]))
        num_radials = M.shape[0]

        # Get out 'lookups'  keys that depend on the library we're using
        # they are used to access data at an index
        haveAs = getDimension(data, "AzimuthalSpacing")
        haveNy = getDimension(data, "NyquistVelocity")
        azimuthL = data.getValueLookup("Azimuth")
        beamwidthL = data.getValueLookup("BeamWidth")
        if haveAs:
            azimuthalSpacingL = data.getValueLookup("AzimuthalSpacing")
        if haveNy:
            nvl = data.getValueLookup("NyquistVelocity")
        gatewidthL = data.getValueLookup("GateWidth")
        nyquest = -99999.0

        for i in range(0,num_radials):
            az = float(data.getValue(azimuthL, i))
            bw = float(data.getValue(beamwidthL, i))
            if haveAs:
                aspace = float(data.getValue(azimuthalSpacingL, i))
            else:
                aspace = bw  # Spacing is equal to beamwidth
            if haveNy:
                ny = float(data.getValue(nvl, i))
            else:
                ny = nyquest
            gw = int(data.getValue(gatewidthL, i))

            log.info("{0}, {1}, {2}, {3}, {4}".format(az,bw,aspace, ny,gw))

        rs = radialset.RadialSet(M)
        rs.setTypeName(datatype)
        return rs
    else:
        log.error("Could not find DataType attribute in Netcdf file.")
        log.error("All NSSL netcdf data files should have this.")
    return None

def readLatLonGrid(data, isSparse):
    """ Try to read in a NSSL LatLonGrid data format
    """
    log.debug("Entering readLatLonGrid")
    lat = float(data.getAttributeValue("", "Latitude"))
    lon = float(data.getAttributeValue("", "Longitude"))
    dlat = float(data.getAttributeValue("", "LatGridSpacing"))
    dlon = float(data.getAttributeValue("", "LonGridSpacing"))

    # Read the main data of the file into 2D array
    datatype = data.getAttributeValue("", "TypeName")
    # Assume Sparse
    M = None
    if isSparse:
        log.info("Data type is SPARSE")
        M = readSparseArray2Dfloat(data, datatype, "Lat", "Lon")
    else:
        log.info("Data is not SPARSE")
        M = readArray2Dfloat(data, datatype, "Lat", "Lon")

    llg = latlongrid.LatLonGrid(M, lat, lon, dlat, dlon)
    llg.setTypeName(datatype)
    return llg

def readNetcdfFile(data):
    """ Read in a netcdf data file, look for our attributes.
        Using Arcpy's built in netcdf ability.  This of course relies on
        the arcpy library.  Could wrap all the netcdf to allow plug-in of
        SciPy or another library
    """
    D = None
    if data.haveAttribute("", "DataType"):

        #dataType = attrs.get("DataType")
        dataType = data.getAttributeValue("", "DataType")
        log.info("DataType is "+dataType)

        # Get the origin of the data.
        lat = float(data.getAttributeValue("", "Latitude"))
        lon = float(data.getAttributeValue("", "Longitude"))
        h = float(data.getAttributeValue("", "Height"))
        log.info("Data origin: {0}, {1}, {2} Meters".format(lat,lon,h))

        # First attempt, assume RadialSet...
        # We'll have to dispatch for RadialSet/LatLonGrid
        isSparse = "Sparse" in dataType
        if "RadialSet" in dataType:
            D = readRadialSet(data, isSparse)
        elif "LatLonGrid" in dataType:
            D = readLatLonGrid(data, isSparse)
        else:
            log.error("Can't process unknown DataType of "+dataType)

        # Try to get the time from the data file...
        if data.haveAttribute("", "Time"):
            t1 = long(data.getAttributeValue("", "Time"))
            #t2 = float(0.0)
            #if data.haveAttribute("", "FractionalTime"):
            #   t2 = float(data.getAttributeValue("", "FractionalTime"))
            #log.info("************************T1 is "+str(t1))
            #log.info("************************T2 is "+str(t2))
            #t1 = t1 + long(1000.0*t2)
            theTime = datetime.datetime.fromtimestamp(t1).strftime('%Y-%m-%d %H:%M:%S UTC')
        else:
            # We don't care, just use current date...
            theTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')

        D.setTime(theTime)

    else:
        log.error("No DataType attribute found in NetCDF file.")
    return D

def readArray2Dfloat(data, typename, rfield, cfield):
    """ Read in a non 2D array from our netcdf data and expand.
        For the initial project, we will just handle sparse data.
    """
    #log.info("NUMPY version is {0}".format(numpy.version.version))

    rows = data.getDimensionSize(rfield)
    cols = data.getDimensionSize(cfield)
    # Humm..need this index I think.  Don't know how to use it properly
    #index = data.getDimensionIndex(typename)

    #log.info("Filling in data values "+str(rows)+","+str(cols))
    M = numpy.empty((rows,cols), float)
    i = 0
    notify = 0
    totalCells = 0
    allCells = rows*cols
    log.info("Type name comes in as "+typename)
    values = data.getValueLookup(typename)
    log.info("Type name of values is "+str(type(values)))
    for x in range(0,rows):
        for y in range(0, cols):
            M[x,y] = float(data.getValue2D(values, i, x, y))
            i = i + 1
            notify += 1
            totalCells += 1
            if notify > 10000:
                log.info("Processed {0} of {1} data samples.".format(totalCells, allCells))
                notify = 0
    log.info("Processed {0} of {1} data samples.".format(totalCells, allCells))
    return M

def readSparseArray2Dfloat(data, typename, rfield, cfield):
    """ Read in a sparse 2D array from our netcdf data and expand.
    """
    backgroundValue = float(data.getAttributeValue(typename, "BackgroundValue"))
    log.info("Background value is "+str(backgroundValue))

    num_pixels = data.getDimensionSizeByVariable("pixel_x")

    # Try to get the count field, if any.  This will cause an exception if missing.  This is
    # an extra line based compression, since radar data tends to be locally homogeneous
    haveCount = False
    try:
        count = data.getDimensionSizeByVariable("pixel_count")
        haveCount = True
    except Exception as e:
        # Assume it's not there...
        pass

    #log.info("NUMPY version is {0}".format(numpy.version.version))

    # Bleh, Arcgis 10.2 has numpy 1.7, so we can't fill with background value automatically
    rows = data.getDimensionSize(rfield)
    cols = data.getDimensionSize(cfield)
    log.info("Creating background array of {0}, {1}".format(rows, cols))
    M = numpy.empty((rows,cols), float)
    for x in range(0,rows):
        for y in range(0,cols):
            M[x,y] = backgroundValue

    # Basically, for sparse array.  We have an 'x' and 'y' that tell position into the array, and
    # a possible 'pixel_count' which is a line of same data value.
    #log.info("Filling in data values")
    actualData = 0
    notify = 0
    totalCells = 0
    pixelL = data.getValueLookup(typename)
    pixel_xL = data.getValueLookup("pixel_x")
    pixel_yL = data.getValueLookup("pixel_y")
    if haveCount:
        pixel_countL = data.getValueLookup("pixel_count")

    for i in range(0, num_pixels,1):

        # Data value and the sparse x, y location in full matrix
        value = float(data.getValue(pixelL, i))
        x = int(data.getValue(pixel_xL, i))
        y = int(data.getValue(pixel_yL, i))

        # Each can be a line strip of values at the location
        if haveCount:
            count = int(data.getValue(pixel_countL, i))
        else:
            count = 1
        #log.info("**************Count is "+str(haveCount))
        if value > datatype.missingData:
            M[x, y] = value
            actualData += 1
        totalCells += 1
        notify += 1

        if notify > 10000:
                log.info("Processed {0} of {1} data samples.".format(totalCells, num_pixels))
                notify = 0
        # Fill in line strip
        for j in range(1, count, 1):
            y += 1
            if y == cols:
                x += 1   # new row
                y = 0
            if value > datatype.missingData:
                M[x, y] = value
                actualData += 1
            #print x, y, count, "set to", value
    log.info("Processed {0} of {1} data samples.".format(totalCells, num_pixels))
    return M


text:
using System ;
using System.Collections ;

namespace FredCK.FCKeditorV2
{
	public class FCKeditorConfigurations
	{
		private Hashtable colConfigs ;

		internal FCKeditorConfigurations()
		{
			colConfigs = new Hashtable() ;
		}

		public string this[ string configurationName ]
		{
			get
			{
				if ( colConfigs.ContainsKey( configurationName ) )
					return (string)colConfigs[ configurationName ] ;
				else
					return null ;
			}
			set
			{
				colConfigs[ configurationName ] = value ;
			}
		}

		internal string GetHiddenFieldString()
		{
			System.Text.StringBuilder osParams = new System.Text.StringBuilder() ;

			foreach ( DictionaryEntry oEntry in colConfigs )
			{
				if ( osParams.Length > 0 )
					osParams.Append( '&' ) ;

				osParams.AppendFormat( "{0}={1}", EncodeConfig( oEntry.Key.ToString() ), EncodeConfig( oEntry.Value.ToString() ) ) ;
			}

			return osParams.ToString() ;
		}

		private string EncodeConfig( string valueToEncode )
		{
			string sEncoded = valueToEncode.Replace( "&", "%26" ) ;
			sEncoded = sEncoded.Replace( "=", "%3D" ) ;
			sEncoded = sEncoded.Replace( "\"", "%22" ) ;

			return sEncoded ;
		}
	}
}


text:
package com.intellij.openapi.updateSettings.impl;

import com.intellij.openapi.util.BuildNumber;
import org.jetbrains.annotations.NotNull;

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

public class UpdateStrategy {
  public static enum State {LOADED, CONNECTION_ERROR, NOTHING_LOADED}

  private UserUpdateSettings myUpdateSettings;
  private int myMajorVersion;
  private BuildNumber myCurrentBuild;

  private ChannelStatus myChannelStatus;
  private Product myProduct;

  public UpdateStrategy(int majorVersion, @NotNull BuildNumber currentBuild, @NotNull Product product,
                        @NotNull UserUpdateSettings updateSettings) {
    myMajorVersion = majorVersion;
    myProduct = product;
    myUpdateSettings = updateSettings;
    myCurrentBuild = currentBuild;
    myChannelStatus = updateSettings.getSelectedChannelStatus();
  }

  public final CheckForUpdateResult checkForUpdates() {
    if (myProduct.getChannels().isEmpty()) {
      return new CheckForUpdateResult(State.NOTHING_LOADED);
    }

    UpdateChannel updatedChannel = null;
    BuildInfo newBuild = null;
    List<UpdateChannel> activeChannels = getActiveChannels(myProduct);
    for (UpdateChannel channel : activeChannels) {
      if (hasNewVersion(channel)) {
        updatedChannel = channel;
        newBuild = updatedChannel.getLatestBuild();
        break;
      }
    }

    CheckForUpdateResult result = new CheckForUpdateResult(updatedChannel, newBuild, myProduct.getAllChannelIds());

    UpdateChannel channelToPropose = null;
    for (UpdateChannel channel : myProduct.getChannels()) {
      if (!myUpdateSettings.getKnownChannelsIds().contains(channel.getId()) &&
          channel.getMajorVersion() >= myMajorVersion &&
          channel.getStatus().compareTo(myChannelStatus) >= 0 &&
          hasNewVersion(channel)) {
        result.addNewChannel(channel);
        if (channelToPropose == null || isBetter(channelToPropose, channel)) {
          channelToPropose = channel;
        }
      }
    }
    result.setChannelToPropose(channelToPropose);
    return result;
  }

  private static boolean isBetter(UpdateChannel channelToPropose, UpdateChannel channel) {
    return channel.getMajorVersion() > channelToPropose.getMajorVersion() ||
           (channel.getMajorVersion() == channelToPropose.getMajorVersion() &&
            channel.getStatus().compareTo(channelToPropose.getStatus()) > 0);
  }

  private List<UpdateChannel> getActiveChannels(Product product) {
    List<UpdateChannel> channels = product.getChannels();
    List<UpdateChannel> result = new ArrayList<UpdateChannel>();
    for (UpdateChannel channel : channels) {
      if ((channel.getMajorVersion() == myMajorVersion && channel.getStatus().compareTo(myChannelStatus) >= 0) ||
          (channel.getMajorVersion() > myMajorVersion && channel.getStatus() == ChannelStatus.EAP && myChannelStatus == ChannelStatus.EAP)) {
        result.add(channel);
      }
    }
    return result;
  }

  private boolean hasNewVersion(@NotNull UpdateChannel channel) {
    BuildInfo latestBuild = channel.getLatestBuild();
    if (latestBuild == null || latestBuild.getNumber() == null ||
        myUpdateSettings.getIgnoredBuildNumbers().contains(latestBuild.getNumber().asString())) {
      return false;
    }
    return myCurrentBuild.compareTo(latestBuild.getNumber()) < 0;
  }
}


text:
import * as Promise from 'bluebird'

export default class Engine {
  constructor(){
  }

  // La mitad de las veces arranca y la mitad de las veces falla
  start(){
    return ( Math.random() * (10 - 0) + 0 ) > 5 ? Promise.resolve() : Promise.reject()
  }
}


text:
#ifndef __CONNECTION_H__
#define __CONNECTION_H__
#include "simplelink.h"
#include "sl_common.h"

#ifdef  __cplusplus
extern "C" {
#endif

#define SL_STOP_TIMEOUT        0xFF

/* Use bit 32:
 *      1 in a 'status_variable', the device has completed the ping operation
 *      0 in a 'status_variable', the device has not completed the ping operation
 */
#define STATUS_BIT_PING_DONE  31

#define HOST_NAME       "www.ti.com"

/*
 * Values for below macros shall be modified for setting the 'Ping' properties
 */
#define PING_INTERVAL   1000    /* In msecs */
#define PING_TIMEOUT    3000    /* In msecs */
#define PING_PKT_SIZE   4      /* In bytes */
#define NO_OF_ATTEMPTS  2

/* Application specific status/error codes */
typedef enum{
    LAN_CONNECTION_FAILED = -0x7D0,        /* Choosing this number to avoid overlap with host-driver's error codes */
    INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
    DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,

    STATUS_CODE_MAX = -0xBB8
}e_AppStatusCodes;

#define IS_PING_DONE(status_variable)           GET_STATUS_BIT(status_variable, \
                                                               STATUS_BIT_PING_DONE)

extern _u32  g_Status;
extern _u32  g_PingPacketsRecv;
extern _u32  g_GatewayIP;
extern _u32  g_StationIP;
_i32 initializeConnectionVariables(void);
_i32 configureSimpleLinkToDefaultState(void);
_i32 establishConnectionWithAP(void);
_i32 checkLanConnection(void);
_i32 checkInternetConnection(void);

_i32 startWlanStion(void);
_i32 startAP(void);
#ifdef  __cplusplus
}
#endif /* __cplusplus */

#endif /* __CONNECTION_H__ */


text:
package org.sleuthkit.autopsy.url.analytics.domaincategorization;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.sleuthkit.autopsy.coreutils.PlatformUtil;
import org.sleuthkit.autopsy.url.analytics.DomainCategory;

/**
 * Provides the data model for exporting, importing and CRUD operations on
 * custom web categories.
 */
class WebCategoriesDataModel implements AutoCloseable {

    /**
     * DTO to be used with jackson when converting to and from exported content.
     */
    @JsonIgnoreProperties(ignoreUnknown = true)
    static class CustomCategorizationJsonDto {

        private final String category;
        private final List<String> domains;

        /**
         * Main constructor.
         *
         * @param category The category.
         * @param domains The list of host suffixes in this category.
         */
        @JsonCreator
        CustomCategorizationJsonDto(
                @JsonProperty("category") String category,
                @JsonProperty("domains") List<String> domains) {
            this.category = category;
            this.domains = domains == null
                    ? Collections.emptyList()
                    : new ArrayList<>(domains);
        }

        /**
         * Returns the category.
         *
         * @return The category.
         */
        @JsonGetter("category")
        String getCategory() {
            return category;
        }

        /**
         * Returns the list of domain suffixes in this category.
         *
         * @return The list of domain suffixes in this category.
         */
        @JsonGetter("domains")
        List<String> getDomains() {
            return domains;
        }
    }

    private static final int MAX_CAT_SIZE = 300;
    private static final int MAX_DOMAIN_SIZE = 255;

    private static final String ROOT_FOLDER = "DomainCategorization";
    private static final String FILE_REL_PATH = "custom_list.db";
    private static final String JDBC_SQLITE_PREFIX = "jdbc:sqlite:";
    private static final String TABLE_NAME = "domain_suffix";
    private static final String SUFFIX_COLUMN = "suffix";
    private static final String CATEGORY_COLUMN = "category";

    private static final Logger logger = Logger.getLogger(WebCategoriesDataModel.class.getName());
    private static WebCategoriesDataModel instance;

    /**
     * Returns the maximum string length of a domain suffix.
     *
     * @return The maximum string length of a domain suffix.
     */
    static int getMaxDomainSuffixLength() {
        return MAX_DOMAIN_SIZE;
    }

    /**
     * Returns the maximum string length of a category.
     *
     * @return The maximum string length of a category.
     */
    static int getMaxCategoryLength() {
        return MAX_DOMAIN_SIZE;
    }

    /**
     * Retrieves the default path for where custom domain categorization exists.
     *
     * @return The path or null if the path cannot be reconciled.
     */
    private static File getDefaultPath() {
        String configDir = PlatformUtil.getUserConfigDirectory();
        if (configDir == null || !new File(configDir).exists()) {
            logger.log(Level.WARNING, "Unable to find UserConfigDirectory");
            return null;
        }

        Path subDirPath = Paths.get(configDir, ROOT_FOLDER);
        File subDir = subDirPath.toFile();
        if (!subDir.exists() && !subDir.mkdirs()) {
                logger.log(Level.WARNING, "There was an issue creating custom domain config at: {0}", subDirPath.toString());
        }

        return Paths.get(configDir, ROOT_FOLDER, FILE_REL_PATH).toFile();
    }

    /**
     * Generates the normalized category string to be inserted into the
     * database.
     *
     * @param category The category.
     * @return The normalized string.
     */
    static String getNormalizedCategory(String category) {
        if (category == null) {
            return "";
        }

        String trimmedCategory = category.trim();

        return trimmedCategory.substring(0, Math.min(trimmedCategory.length(), MAX_CAT_SIZE));
    }

    /**
     * Generates the normalized domain suffix string to be inserted into the
     * database.
     *
     * @param domainSuffix The domain suffix.
     * @return The normalized string.
     */
    static String getNormalizedSuffix(String domainSuffix) {
        if (domainSuffix == null) {
            return "";
        }

        String sanitized = Stream.of(domainSuffix.split("\\."))
                .map(s -> {
                    return s
                            // alphanumeric and hyphen
                            .replaceAll("[^0-9a-zA-Z\\-]", "")
                            // no leading or trailing hyphen
                            .replaceAll("^\\-*(.+?)?\\-*$", "$1");
                })
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.joining("."));

        return sanitized.substring(0, Math.min(sanitized.length(), MAX_DOMAIN_SIZE)).toLowerCase();
    }

    /**
     * Retrieves a singleton instance of this class.
     *
     * @return The singleton instance of this class.
     */
    static WebCategoriesDataModel getInstance() {
        if (instance == null) {
            instance = new WebCategoriesDataModel();
        }

        return instance;
    }

    private final File sqlitePath;
    private Connection dbConn = null;

    /**
     * Constructor used to create singleton instance.
     */
    private WebCategoriesDataModel() {
        this(getDefaultPath());
    }

    /**
     * Constructor that accepts a variable path for the custom sqlite database
     * for custom domain categories.
     *
     * @param sqlitePath The path.
     */
    WebCategoriesDataModel(File sqlitePath) {
        this.sqlitePath = sqlitePath;
    }

    /**
     * Creates a sqlite jdbc connection.
     *
     * @throws SQLException
     */
    synchronized void initialize() throws SQLException {
        String url = JDBC_SQLITE_PREFIX + sqlitePath.getAbsolutePath();
        if (this.dbConn != null) {
            this.dbConn.close();
            this.dbConn = null;
        }

        this.dbConn = DriverManager.getConnection(url);

        // speed up operations by turning off WAL
        try (Statement turnOffWal = dbConn.createStatement()) {
            turnOffWal.execute("PRAGMA journal_mode=OFF");
        }

        // create table if it doesn't exist
        try (Statement createDomainsTable = dbConn.createStatement()) {
            createDomainsTable.execute(
                    "    CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (\n"
                    + "        " + SUFFIX_COLUMN + " VARCHAR(" + MAX_DOMAIN_SIZE + ") PRIMARY KEY,\n"
                    + "        " + CATEGORY_COLUMN + " VARCHAR(" + MAX_CAT_SIZE + ")\n"
                    + "    ) WITHOUT ROWID");
        }
    }

    /**
     * Returns true if initialized.
     *
     * @return True if initialized.
     */
    synchronized boolean isInitialized() {
        return this.dbConn != null;
    }

    /**
     * Retrieves all domain categories present in json file.
     *
     * @param jsonInput The json file.
     * @return The domain categories.
     * @throws IOException
     */
    List<DomainCategory> getJsonEntries(File jsonInput) throws IOException {
        if (jsonInput == null) {
            logger.log(Level.WARNING, "No valid file provided.");
            return Collections.emptyList();
        }

        ObjectMapper mapper = new ObjectMapper();
        List<CustomCategorizationJsonDto> customCategorizations = mapper.readValue(jsonInput, new TypeReference<List<CustomCategorizationJsonDto>>() {
        });

        Stream<CustomCategorizationJsonDto> categoryStream = (customCategorizations != null) ? customCategorizations.stream() : Stream.empty();

        return categoryStream
                .filter(c -> c != null && c.getCategory() != null && c.getDomains() != null)
                .flatMap(c -> c.getDomains().stream()
                .map(WebCategoriesDataModel::getNormalizedSuffix)
                .filter(StringUtils::isNotBlank)
                .map(d -> new DomainCategory(d, getNormalizedCategory(c.getCategory()))))
                .collect(Collectors.toList());

    }

    /**
     * Exports current database to a json file.
     *
     * @param jsonOutput The output file.
     * @throws SQLException
     * @throws IOException
     */
    synchronized void exportToJson(File jsonOutput) throws SQLException, IOException {
        if (jsonOutput == null) {
            logger.log(Level.WARNING, "Null file provided.");
            return;
        }

        if (!isInitialized()) {
            initialize();
        }

        // retrieve items from the database
        List<Pair<String, String>> categoryDomains = new ArrayList<>();
        try (Statement domainSelect = dbConn.createStatement();
                ResultSet resultSet = domainSelect.executeQuery(
                        "SELECT " + SUFFIX_COLUMN + ", " + CATEGORY_COLUMN + " FROM " + TABLE_NAME + " ORDER BY " + SUFFIX_COLUMN)) {

            while (resultSet.next()) {
                categoryDomains.add(Pair.of(resultSet.getString(CATEGORY_COLUMN), resultSet.getString(SUFFIX_COLUMN)));
            }
        }

        // aggregate data appropriately into CustomCategorizationJsonDto
        List<CustomCategorizationJsonDto> categories
                = categoryDomains.stream()
                        .collect(Collectors.toMap(
                                p -> p.getKey(),
                                p -> new ArrayList<>(Arrays.asList(p.getValue())),
                                (p1, p2) -> {
                                    p1.addAll(p2);
                                    return p1;
                                }
                        ))
                        .entrySet().stream()
                        .map(entry -> new CustomCategorizationJsonDto(entry.getKey(), entry.getValue()))
                        .collect(Collectors.toList());

        // write to disk
        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter().writeValue(jsonOutput, categories);
    }

    /**
     * Delete a record from the database.
     *
     * @param domainSuffix The domain suffix of the item to delete.
     * @return Whether or not the operation actually deleted something.
     * @throws SQLException
     * @throws IllegalArgumentException
     */
    synchronized boolean deleteRecord(String domainSuffix) throws SQLException, IllegalArgumentException {
        if (StringUtils.isBlank(domainSuffix)) {
            throw new IllegalArgumentException("Expected non-empty domain suffix");
        }

        if (!isInitialized()) {
            initialize();
        }

        try (PreparedStatement suffixDelete = dbConn.prepareStatement(
                "DELETE FROM " + TABLE_NAME + " WHERE LOWER(" + SUFFIX_COLUMN + ") = LOWER(?)", Statement.RETURN_GENERATED_KEYS);) {

            suffixDelete.setString(1, getNormalizedSuffix(domainSuffix));
            return suffixDelete.executeUpdate() > 0;
        }
    }

    /**
     * Inserts or updates the entry for the given domain suffix.
     *
     * @param entry The domain suffix and category.
     * @return True if successfully inserted/updated.
     * @throws SQLException
     * @throws IllegalStateException
     * @throws IllegalArgumentException
     */
    synchronized boolean insertUpdateSuffix(DomainCategory entry) throws SQLException, IllegalStateException, IllegalArgumentException {
        if (entry == null || StringUtils.isBlank(getNormalizedCategory(entry.getCategory())) || StringUtils.isBlank(getNormalizedSuffix(entry.getHostSuffix()))) {
            throw new IllegalArgumentException("Expected non-empty, valid category and domain suffix.");
        }

        if (!isInitialized()) {
            initialize();
        }

        try (PreparedStatement insertUpdate = dbConn.prepareStatement(
                "INSERT OR REPLACE INTO " + TABLE_NAME + "(" + SUFFIX_COLUMN + ", " + CATEGORY_COLUMN + ") VALUES (?, ?)",
                Statement.RETURN_GENERATED_KEYS)) {

            insertUpdate.setString(1, getNormalizedSuffix(entry.getHostSuffix()));
            insertUpdate.setString(2, getNormalizedCategory(entry.getCategory()));
            return insertUpdate.executeUpdate() > 0;
        }
    }

    /**
     * Return all records in the database.
     *
     * @return The list of domain suffixes and their categories.
     * @throws SQLException
     */
    synchronized List<DomainCategory> getRecords() throws SQLException {
        if (!isInitialized()) {
            initialize();
        }

        List<DomainCategory> entries = new ArrayList<>();

        try (Statement domainSelect = dbConn.createStatement();
                ResultSet resultSet = domainSelect.executeQuery(
                        "SELECT " + SUFFIX_COLUMN + ", " + CATEGORY_COLUMN + " FROM " + TABLE_NAME + " ORDER BY " + SUFFIX_COLUMN)) {

            while (resultSet.next()) {
                entries.add(new DomainCategory(
                        resultSet.getString(SUFFIX_COLUMN),
                        resultSet.getString(CATEGORY_COLUMN)));
            }
        }
        return entries;

    }

    private static final String GET_DOMAIN_SUFFIX_QUERY
            = "SELECT " + SUFFIX_COLUMN + ", " + CATEGORY_COLUMN
            + " FROM " + TABLE_NAME + " WHERE " + SUFFIX_COLUMN + " = ?";

    /**
     * Return the matching domain suffix or null if none found.
     *
     * @param domainSuffix The domain suffix.
     * @return The found entry or null.
     * @throws SQLException
     */
    synchronized DomainCategory getRecordBySuffix(String domainSuffix) throws SQLException {
        if (!isInitialized()) {
            initialize();
        }

        try (PreparedStatement domainSelect = dbConn.prepareStatement(GET_DOMAIN_SUFFIX_QUERY)) {
            domainSelect.setString(1, domainSuffix);

            try (ResultSet resultSet = domainSelect.executeQuery()) {
                if (resultSet.next()) {
                    return new DomainCategory(
                            resultSet.getString(SUFFIX_COLUMN),
                            resultSet.getString(CATEGORY_COLUMN));
                } else {
                    return null;
                }
            }
        }
    }

    // get the suffix and category from the main table and gets the longest matching suffix.
    private static final String BASE_QUERY_FMT_STR
            = "SELECT " + SUFFIX_COLUMN + ", " + CATEGORY_COLUMN + " FROM " + TABLE_NAME
            + " WHERE suffix IN (%s) ORDER BY LENGTH(" + SUFFIX_COLUMN + ") DESC LIMIT 1";

    /**
     * Retrieves the longest matching domain suffix and category matching the
     * list of suffixes or null if no item can be found.
     *
     * @param suffixes The list of suffixes.
     * @return The longest matching entry or null if no entry found.
     * @throws SQLException
     */
    synchronized DomainCategory getLongestSuffixRecord(List<String> suffixes) throws SQLException {
        if (suffixes == null) {
            return null;
        }

        if (!isInitialized()) {
            initialize();
        }

        String questionMarks = IntStream.range(0, suffixes.size())
                .mapToObj((num) -> "?")
                .collect(Collectors.joining(","));

        try (PreparedStatement stmt = dbConn.prepareStatement(String.format(BASE_QUERY_FMT_STR, questionMarks))) {
            for (int i = 0; i < suffixes.size(); i++) {
                stmt.setString(i + 1, suffixes.get(i));
            }

            try (ResultSet resultSet = stmt.executeQuery()) {
                if (resultSet.next()) {
                    String suffix = resultSet.getString(SUFFIX_COLUMN);
                    String category = resultSet.getString(CATEGORY_COLUMN);
                    return new DomainCategory(suffix, category);
                }
            }
        }

        return null;
    }

    /**
     * Retrieves the longest matching domain suffix and category matching the
     * list of suffixes or null if no item can be found.
     *
     * @param host The host name.
     * @return The longest matching entry or null if no entry found.
     * @throws SQLException
     */
    DomainCategory getMatchingRecord(String host) throws SQLException {
        return getLongestSuffixRecord(getSuffixes(host));
    }

    /**
     * Retrieves all the possible suffixes that could be tracked. For instance,
     * if the host was "chatenabled.mail.google.com", the list should be
     * ["chatenabled.mail.google.com", "mail.google.com", "google.com", "com"].
     *
     * @param host The host.
     * @return The possible suffixes.
     */
    private List<String> getSuffixes(String host) {
        if (host == null) {
            return null;
        }

        List<String> hostTokens = Arrays.asList(host.split("\\."));
        List<String> hostSegmentations = new ArrayList<>();

        for (int i = 0; i < hostTokens.size(); i++) {
            String searchString = String.join(".", hostTokens.subList(i, hostTokens.size()));
            hostSegmentations.add(searchString);
        }

        return hostSegmentations;
    }

    @Override
    public synchronized void close() throws SQLException {
        if (dbConn != null) {
            dbConn.close();
            dbConn = null;
        }
    }
}


text:
module Fog
  module DNS
    class Google
      ##
      # Fetches the representation of an existing Change.
      #
      # @see https://developers.google.com/cloud-dns/api/v1/changes/get
      class Real
        def get_change(zone_name_or_id, identity)
          api_method = @dns.changes.get
          parameters = {
            "project" => @project,
            "managedZone" => zone_name_or_id,
            "changeId" => identity
          }

          request(api_method, parameters)
        end
      end

      class Mock
        def get_change(zone_name_or_id, identity)
          if data[:managed_zones].key?(zone_name_or_id)
            zone = data[:managed_zones][zone_name_or_id]
          else
            zone = data[:managed_zones].values.detect { |z| z["name"] = zone_name_or_id }
          end

          unless zone
            raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{zone_name_or_id}' does not exist."
          end

          unless data = self.data[:changes][zone["id"]].detect { |c| c["id"] == identity }
            raise Fog::Errors::NotFound, "The 'parameters.changeId' resource named '#{identity}' does not exist."
          end

          build_excon_response(data)
        end
      end
    end
  end
end


text:
<html>
<body>
Reports properties in .fxml files (both attributes and tags) that have the default values and therefore are redundant.
<!-- tooltip end -->
</body>
</html>


text:
import CopyableTests from 'ember-runtime/tests/suites/copyable';
import Set from "ember-runtime/system/set";
import {generateGuid} from 'ember-metal/utils';
import {get} from 'ember-metal/property_get';

CopyableTests.extend({
  name: 'Ember.Set Copyable',

  newObject: function() {
    var set = new Set();
    set.addObject(generateGuid());
    return set;
  },

  isEqual: function(a,b) {
    if (!(a instanceof Set)) return false;
    if (!(b instanceof Set)) return false;
    return get(a, 'firstObject') === get(b, 'firstObject');
  },

  shouldBeFreezable: true
}).run();


text:
    {{ 'CONNECTION_OFFLINE' | translate }}

      {{ 'CONNECTING' | translate }}

      {{ 'NO_PROXIES' | translate }}

 0">

          {{ model.globalStats.gauges.userOnline == 1 ? "NUSERS_ONLINE_1" : "NUSERS_ONLINE_OTHER" | translate:'{value: model.globalStats.gauges.userOnline}'  }} ·
          {{ "NUSERS_EVER_OTHER" | translate: '{value: model.glboalStats.gauges.userOnlineEver + model.globalStats.counters.userOnlineEverOld}' }} ·
        {{ model.globalStats.counters.bytesGotten | prettyBytes }} {{ 'TRANSFERRED_GLOBALLY' | translate }}

      {{ 'SHARE' | translate }}

      {{ 'LANTERN' | translate }}
    {{ model.settings.version }}

      · {{ 'ABOUT' | translate }}

    <button type="button" class="btn btn-large btn-inverse"
            ng-click="showModal('settings')"
            ng-class="{active: model.modal == MODAL.settings}"
            tooltip="{{ 'SETTINGS' | translate }}">

    </button>

{{ nfriendSuggestions | badgeCount }}


text:
require 'spec_helper'

RSpec.describe ShardHandler::Handler do
  let(:configs) do
    {
      'shard1' => { 'adapter' => 'postgresql' },
      'shard2' => { 'adapter' => 'postgresql' }
    }
  end

  subject { described_class.new(ShardHandler::Model, configs) }

  describe '#setup' do
    before { subject.setup }

    it 'creates an instance of connection handler for each shard' do
      expect(subject.connection_handler_for(:shard1))
        .to be_kind_of(ActiveRecord::ConnectionAdapters::ConnectionHandler)
      expect(subject.connection_handler_for(:shard2))
        .to be_kind_of(ActiveRecord::ConnectionAdapters::ConnectionHandler)
    end

    it 'does not use the same instance for two different shards' do
      expect(subject.connection_handler_for(:shard1))
        .to_not be(subject.connection_handler_for(:shard2))
    end
  end

  describe '#connection_handler_for' do
    before { subject.setup }

    context 'passing a symbol' do
      it 'returns an instance of connection handler' do
        expect(subject.connection_handler_for(:shard1))
          .to be_kind_of(ActiveRecord::ConnectionAdapters::ConnectionHandler)
      end
    end

    context 'passing a string' do
      it 'returns an instance of connection handler' do
        expect(subject.connection_handler_for('shard1'))
          .to be_kind_of(ActiveRecord::ConnectionAdapters::ConnectionHandler)
      end
    end

    context 'passing an inexistent shard name' do
      it 'raises an error' do
        expect do
          subject.connection_handler_for(:foobar)
        end.to raise_error(ShardHandler::UnknownShardError,
                           ':foobar is not a valid shard name')
      end
    end
  end

  describe '#disconnect_all' do
    before { subject.setup }

    it 'clear all active connections' do
      expect(subject.connection_handler_for(:shard1))
        .to receive(:clear_all_connections!)
      expect(subject.connection_handler_for(:shard2))
        .to receive(:clear_all_connections!)

      subject.disconnect_all
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Vermicularia ornithogali Verpl. & Claess.

### Remarks
null


text:
require "rails_helper"

RSpec.describe "Templates", type: :feature do

  before do
    @org      = create(:org)
    @template = create(:template, org: @org, phases: 2)
    @phase    = @template.phases.first
    @template.phases.each { |phase| create_list(:section, 2, phase: phase) }
    @user = create(:user, org: @org)
    @user.perms << create(:perm, :modify_templates)
    sign_in(@user)
  end

  scenario "Org admin edits a template", :js do
    # Action
    click_link "Admin"
    click_link "Templates"

    # Expectations
    expect(current_path).to eql(organisational_org_admin_templates_path)

    # Action
    click_button "Actions"
    click_link "Edit"

    # Expectations
    expect(current_path).to eql(edit_org_admin_template_path(@template))

    # Action
    within "#phase_#{@phase.id}" do
      click_link "Edit phase"
    end

    # Expectations
    path = edit_org_admin_template_phase_path(@template, @template.phases.first)
    expect(current_path).to eql(path)

    # Action
    # Open the panel for a new Section
    find("a[href='#new_section']").click

    within "#collapseSectionNew" do
      fill_in :new_section_section_title, with: "My new section"
      tinymce_fill_in :new_section_section_description,
                      with: "This is the description of my new section"
      click_button "Save"
    end

    # Expectations
    last_section = @template.phases.first.sections.order(:created_at).last
    expect(@template.sections.count).to eql(5)
    expect(last_section.title).to eql("My new section")
    expect(last_section.description).to match("This is the description of my new section")
    expect(last_section.description).to match("<p>")
  end

end


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :author
      t.text :body
      t.datetime :creation_date
      t.integer :score
      t.string :subreddit
      t.integer :gilded
      t.timestamps
    end
  end
end


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Reactive Systems - Vier Traits für die Architektur von Morgen? (Daniel Wegener)</title>

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

    <link rel="stylesheet" href="styles/reveal.css" media="all">

    <link rel="stylesheet" href="styles/presentation.css" media="all">

    <link rel="shortcut icon" href="images/brand/favicon.png">

NOTES:">