text:
package au.edu.labshare.rigclient.action.detect;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import au.edu.uts.eng.remotelabs.rigclient.rig.IActivityDetectorAction;
import au.edu.uts.eng.remotelabs.rigclient.util.ILogger;
import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory;

/**
 * Detects activity by invoking the Linux 'who' command to determine if any
 * user is logged in. It does not explicitly check whether the assigned
 * user is logged in, so any user logged in will cause this test to pass.
 * This class assumes 'who' is in path.
 * <br />
 * This class only works on Linux operating systems.
 */
public class LinuxConsoleActivityDetector implements IActivityDetectorAction
{
    /** The process build to invoke 'who --count'. */
    private final ProcessBuilder builder = new ProcessBuilder("who", "--count");

    /** Logger. */
    private ILogger logger;

    /**
     * Constructor.
     *
     * @throws IllegalStateException if trying to instantiate this class on a \
     *      non-Linux operating system.
     */
    public LinuxConsoleActivityDetector()
    {
        this.logger = LoggerFactory.getLoggerInstance();

        if (!"Linux".equals(System.getProperty("os.name")))
        {
            this.logger.error("The '" + this.getActionType() + "' class can only be used on Linux ('" +
                    System.getProperty("os.name") + "' detected).");
            throw new IllegalStateException(this.getActionType() + " only works on Linux.");
        }
    }

    @Override
    public boolean detectActivity()
    {
        try
        {
            Process p = this.builder.start();
            p.waitFor();

            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            while ((line = reader.readLine()) != null)
            {
                /* The expected format of the 'who' count line is # users=<n>. */
                if (line.contains("users"))
                {
                    String chunks[] = line.split("=", 2);
                    if (chunks.length != 2) continue;

                    try
                    {
                        return Integer.parseInt(chunks[1]) >= 1;
                    }
                    catch (NumberFormatException ex)
                    {
                        continue;
                    }
                }
            }

            return false;
        }
        catch (IOException e)
        {
            this.logger.warn("Failed to invoke command " + this.builder.toString() + " because of exception '"
                    + e.getClass().getName() + "', message '" + e.getMessage() + "'.");
            return true;
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            return true;
        }
    }

    @Override
    public String getFailureReason()
    {
        return null;
    }

    @Override
    public String getActionType()
    {
        return "Linux console activity detector";
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Net.Surviveplus.UnitTestPlus;
using SampleClassLibrary.UseDatabases;

namespace SampleUnitTest.UseDatabases
{
    /// <summary>
    /// ConfigDBConnectionExecutor のテスト クラスです。すべての ConfigDBConnectionExecutor 単体テストテストをここに含めます。
    /// </summary>
    /// <remarks>Team Foundation Server, Visual Studio Online の自動ビルド・自動テストに登録するため、クラス名は必ず Test で終わる必要があります。</remarks>
    [TestClass]
    public class ConfigDBConnectionExecutorTest
    {

        /// <summary>
        /// 現在のテストの実行についての情報および機能を提供するテスト コンテキストを取得または設定します。
        /// </summary>
        public TestContext TestContext { get; set; }

        #region 追加のテスト属性

        /// <summary>
        ///  テストを作成するときに、次の追加属性を使用することができます:
        ///  クラスの最初のテストを実行する前にコードを実行するには、ClassInitialize を使用
        /// </summary>
        /// <param name="testContext"></param>
        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
            ReportingConsole.Culture = new System.Globalization.CultureInfo("ja-JP");
        } // end function

        /// <summary>
        /// クラスのすべてのテストを実行した後にコードを実行するには、ClassCleanup を使用
        /// </summary>
        [ClassCleanup()]
        public static void MyClassCleanup()
        {
        } // end function

        /// <summary>
        /// 各テストを実行する前にコードを実行するには、TestInitialize を使用
        /// </summary>
        [TestInitialize()]
        public void MyTestInitialize()
        {
            // テスト実行 前 毎に TestContext の内容をコンソールに出力するには、下記のコメントアウトを解除します。
            //ReportingConsole.WriteTestContext( this.TestContext );
        } // end function

        /// <summary>
        /// 各テストを実行した後にコードを実行するには、TestCleanup を使用
        /// </summary>
        [TestCleanup()]
        public void MyTestCleanup()
        {

            // テスト実行 後 毎に TestContext の内容をコンソールに出力するには、下記のコメントアウトを解除します。
            //ReportingConsole.WriteTestContext( this.TestContext );
        } // end function

        #endregion

        [TestMethod()]
        #region コード分析(命名規則)抑制
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly"),
          SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"),
          SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
        #endregion
        public void Execute_正常系_初期データに登録されていないテキストをアップデート出来ること()
        {

            // テスト用DBファイルを使用します。
            using (var db = new UnitTestDatabases(this))
            {
                db.AttachFiles();

                using (ShimsContext.Create())
                {

                    // 環境
                    var environment = new
                    {
                        ConnectionStrings = new
                        {
                            UnitTestSampleEntities = db.CreateAttachedEntityConnectionString("UnitTestSampleModel", "UnitTestSample")
                        }
                    };
                    ReportingConsole.WriteFakes(environment);

                    // 下記の設定は出来ないので(読み取り専用)、代わりに fakes で置き換えます。
                    //	ConfigurationManager.ConnectionStrings["UnitTestSampleEntities"].ConnectionString = environment.ConnectionStrings.UnitTestSampleEntities;
                    //
                    var c = new ConnectionStringSettings("UnitTestSampleEntities", environment.ConnectionStrings.UnitTestSampleEntities, "System.Data.EntityClient");
                    System.Configuration.Fakes.ShimConnectionStringSettingsCollection.AllInstances.ItemGetString = (me, key) =>
                    {
                        ReportingConsole.WriteFakesCalled("System.Configuration.ConfigurationManager.ConnectionStrings インデクサ(デフォルトプロパティ)");
                        if (key == "UnitTestSampleEntities")
                        {
                            return c;
                        }
                        else
                        {
                            return me[key];
                        }
                    };

                    var target = new ConfigDBConnectionExecutor();

                    // メソッド引数
                    var args = "Sample";
                    ReportingConsole.WriteArgsWithNoExpected(args, NoExpectedReason.Void);

                    // 実行と確認
                    target.Execute(args);

                } // end using fakes

            }// end using(db)
        } // end function

        [TestMethod()]
        #region コード分析(命名規則)抑制
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly"),
          SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores"),
          SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
        #endregion
        public void Count_正常系_初期データ3件登録されていてExecuteでデータを1件登録した後にCountで4が取得出来ること()
        {

            // テスト用DBファイルを使用します。
            using (var db = new UnitTestDatabases(this))
            {
                //db.Server = TestDatabaseKind.SqlServer2012ExpressLocalDB;
                db.AttachFiles();

                using (ShimsContext.Create())
                {

                    // 環境
                    var environment = new
                    {
                        ConnectionStrings = new
                        {
                            UnitTestSampleEntities = db.CreateAttachedEntityConnectionString("UnitTestSampleModel", "UnitTestSample"),
                            UnitTestSample = db.CreateAttachedConnectionString("UnitTestSample")

                        }
                    };
                    ReportingConsole.WriteFakes(environment);

                    // 下記の設定は出来ないので(読み取り専用)、代わりに fakes で置き換えます。
                    //	ConfigurationManager.ConnectionStrings["UnitTestSampleEntities"].ConnectionString = environment.ConnectionStrings.UnitTestSampleEntities;
                    //	ConfigurationManager.ConnectionStrings["UnitTestSample"].ConnectionString = environment.ConnectionStrings.UnitTestSample;
                    //
                    var c = new ConnectionStringSettings("UnitTestSampleEntities", environment.ConnectionStrings.UnitTestSampleEntities, "System.Data.EntityClient");
                    var c2 = new ConnectionStringSettings("UnitTestSample", environment.ConnectionStrings.UnitTestSample, "System.Data.Client");
                    System.Configuration.Fakes.ShimConnectionStringSettingsCollection.AllInstances.ItemGetString = (me, key) =>
                    {
                        ReportingConsole.WriteFakesCalled("System.Configuration.ConfigurationManager.ConnectionStrings インデクサ(デフォルトプロパティ)");
                        if (key == "UnitTestSampleEntities")
                        {
                            return c;
                        }
                        else if (key == "UnitTestSample")
                        {
                            return c2;
                        }
                        else
                        {
                            return me[key];
                        }
                    };

                    var target = new ConfigDBConnectionExecutor();

                    // メソッド引数
                    var args = "Sample";
                    var expected = new
                    {
                        Count = 4
                    };
                    ReportingConsole.WriteArgsAndExpected(args, expected);

                    // 実行と確認
                    target.Execute(args);
                    var actual = target.Count();

                    Assert.AreEqual(expected.Count, actual);

                } // end using fakes

            }// end using(db)
        } // end function

    } // end class
} // end namespace

redpajama_set_name: RedPajamaGithub


text:
// Problem 06
// Write a program that removes from given sequence all numbers that occur odd number of times.
// Example:
// {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2} → {5, 3, 3, 5}

namespace P06_RemoveOddOccuringItems
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class RemoveOddOccuringItems
    {
        public static void Main()
        {
            var listOfItems = new List<int>() { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 };
            var listOfOddItems = new List<int>();

            foreach (var item in listOfItems)
            {
                if (listOfItems.Count(it => it == item) % 2 != 0)
                {
                    if (listOfOddItems.Count(it => it == item) == 0)
                    {
                        listOfOddItems.Add(item);
                    }
                }
            }

            foreach (var number in listOfOddItems)
            {
                listOfItems.RemoveAll(n => n == number);
            }

            Console.WriteLine(string.Join(", ", listOfItems));
        }
    }
}


text:
<?php
/**
 * @var \Codeception\Scenario $scenario
 */

$I = new Step\Functional\UserSteps($scenario);

$I->wantTo('Verify that the home page welcome me');
$I->amOnPage('/');
$I->see('Log In with Github');
$I->amRegularUser();
$I->amOnPage('/');
$I->see('Profile');


text:
var models = require('../models'),
    _ = require('lodash');

var doAction = function(){
    this.actions = [];
};

/*
 Todo: document this.
 */
doAction.prototype.parseAction = function(data, action, dropletId){
    var self = this;
    var ar = new models.actionRequest();
    ar.action = action;

    if(isErr(data)){
        ar.actionProcessed = false;
        ar.err = data.id;
        ar.errMessage = data.message;
        ar.input = dropletId;
        self.actions.push(ar);
        return;
    };

    if(isDelete(data, action)){
        ar.actionProcessed = true;
        ar.input = dropletId;
        self.actions.push(ar);
        return;
    };

    if(!_.get(data, 'action')) return {};

    ar.input = dropletId;
    ar.actionProcessed = data.action.status === 'in-progress'? true : false;

    if(!ar.actionProcessed)
    {
        ar.err = data;
        ar.errMessage =  action + " action couldn't be processed.";
    }

    self.actions.push(ar);
};

doAction.prototype.parseCreation = function(data){
    var self = this;

    if(isErr(data)){
        var ar = new models.actionRequest();
        ar.action = 'create';
        ar.actionProcessed = false;
        ar.err = data.id;
        ar.errMessage = data.message;
        ar.input = '';
        self.actions.push(ar);
        return;
    };

    if(!_.get(data, 'droplet')) return {};

    var ar = new models.actionRequest();
    ar.action = 'create';
    ar.input = data.droplet.id;
    ar.actionProcessed = true;

    if(!ar.actionProcessed)
    {
        ar.err = data;
        ar.errMessage = "create action couldn't be processed.";
    }

    self.actions.push(ar);
};

var isErr = function(data){
    return data && data.id && data.message;
};

var isDelete = function(data, action){
    return !data &&  action && action.type === 'delete';
};

module.exports = doAction;


text:
public interface ISubject
{
    void Register(IObserver observer);
    void Unregister(IObserver observer);
    void NotifyObservers();
}


text:
<!doctype html>

    <title>Janky QR code generator</title>

    <input id="text" type="text" value="QR-Chrome" style="width:80%" autofocus = "autofocus" />


text:
using System;
using System.Collections.Generic;
using System.Linq;
    class RemoveElementsFromArray
    {
        static void Main()
        {
            //Problem 18.* Remove elements from array
            //Write a program that reads an array of integers and removes from it a minimal number of elements in such a way that the remaining array is sorted in increasing order.
            //Print the remaining sorted array.

            Console.Write("Enter how many element will be in the array N=");
            int n = int.Parse(Console.ReadLine());
            List<int> array = new List<int>();// { 6, 1, 4, 3, 0, 3, 6, 4, 5 };
            for (int i = 0; i < n; i++)
            {
                Console.Write("element[{0}]=", i);
                array.Add(int.Parse(Console.ReadLine()));
            }
            for (int i = 0; i < array.Count - 1; i++)
            {
                if (array[i] > array[i + 1] || array[i] < array[0])
                {
                    array.Remove(array[i]);
                }
            }
            for (int i = 0; i < array.Count; i++)
            {
                Console.Write(i < array.Count - 1 ? array[i] + ", " : array[i] + "\n");
            }
        }
    }


text:
package de.michlb.sample.rabbit.web.bean;

import lombok.Data;

/**
 * Form definition Bean for web presentation view
 *
 * @author Michael Bartsch
 */
@Data
public class MessageForm {
    private String message;
}


text:
package alien4cloud.deployment;

import alien4cloud.dao.FilterUtil;
import alien4cloud.dao.IESQueryBuilderHelper;
import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.deployment.exceptions.ImpossibleDeploymentUpdateException;
import alien4cloud.deployment.matching.services.location.TopologyLocationUtils;
import alien4cloud.events.DeploymentUndeployedEvent;
import alien4cloud.exception.NotFoundException;
import alien4cloud.model.deployment.Deployment;
import alien4cloud.model.deployment.DeploymentTopology;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.utils.MapUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static alien4cloud.dao.FilterUtil.fromKeyValueCouples;

/**
 * Manage deployment operations on a cloud.
 */
@Service
@Slf4j
public class DeploymentService {
    @Resource(name = "alien-es-dao")
    private IGenericSearchDAO alienDao;
    @Resource(name = "alien-monitor-es-dao")
    private IGenericSearchDAO alienMonitorDao;
    @Inject
    private DeploymentRuntimeStateService deploymentRuntimeStateService;
    @Inject
    private DeploymentContextService deploymentContextService;
    @Inject
    private DeploymentTopologyService deploymentTopologyService;
    @Inject
    private ApplicationEventPublisher eventPublisher;

    /**
     * Get an array of all active deployments.
     *
     * @return Array of all active deployments.
     */
    public Deployment[] getActiveDeployments() {
        return alienDao.buildQuery(Deployment.class).prepareSearch().setFilters(fromKeyValueCouples("endDate", null)).search(0, 10000).getData();
    }

    /**
     * Get all deployments for a given orchestrator an application
     *
     * @param orchestratorId Id of the cloud for which to get deployments (can be null to get deployments for all clouds).
     * @param sourceId Id of the application for which to get deployments (can be null to get deployments for all applications).
     * @param environmentId Id of the environment for which to get deployments (can be null to get deployments for all environments).
     * @return An array of deployments.
     */
    public Deployment[] getDeployments(String orchestratorId, String sourceId, String environmentId, int from, int size) {
        QueryBuilder filterBuilder = buildDeploymentFilters(orchestratorId, sourceId, environmentId);
        IESQueryBuilderHelper<Deployment> queryBuilderHelper = alienDao.buildQuery(Deployment.class);
        return queryBuilderHelper.setFilters(filterBuilder).prepareSearch().setFieldSort("startDate", "long", true).search(from, size).getData();
    }

    /**
     * Search all deployments. See below to known with filters are supported.
     *
     * @param query Query text.
     * @param orchestratorId Id of the orchestrator for which to get deployments (can be null to get deployments for all orchestrator).
     * @param environmentId  Id of the environment for which to get deployments (can be null to get deployments for all environments).
     * @param sourceId Id of the application for which to get deployments (can be null to get deployments for all applications).
     * @param from Query from the given index.
     * @param size Maximum number of results to retrieve.
     * @return the deployments with pagination
     */
    public FacetedSearchResult searchDeployments(String query, String orchestratorId, String environmentId, String sourceId, int from, int size) {
        QueryBuilder filterBuilder = buildDeploymentFilters(orchestratorId, sourceId, environmentId);
        return alienDao.facetedSearch(Deployment.class, query, null, filterBuilder, null, from, size, "startDate", "long", true);
    }

    private QueryBuilder buildDeploymentFilters(String orchestratorId, String sourceId, String environmentId) {
        BoolQueryBuilder filterBuilder = null;
        if ( (orchestratorId != null) || (environmentId != null) || (sourceId != null) ) {
           filterBuilder = QueryBuilders.boolQuery();
        }
        if (orchestratorId != null) {
            filterBuilder.must(QueryBuilders.termQuery("orchestratorId", orchestratorId));
        }
        if (environmentId != null) {
            filterBuilder.must(QueryBuilders.termQuery("environmentId", environmentId));
        }
        if (sourceId != null) {
            filterBuilder.must(QueryBuilders.termQuery("sourceId", sourceId));
        }
        return filterBuilder;
    }

    /**
     * Get all active deployments for a given orchestrator an application
     *
     * @param orchestratorId Id of the cloud for which to get deployments (can be null to get deployments for all clouds).
     * @param sourceId Id of the application for which to get deployments (can be null to get deployments for all applications).
     * @return An array of deployments.
     */
    public Deployment[] getActiveDeployments(String orchestratorId, String sourceId, int from, int size) {
        BoolQueryBuilder filterBuilder = QueryBuilders.boolQuery();

        if (orchestratorId != null) {
            filterBuilder.must(QueryBuilders.termQuery("orchestratorId", orchestratorId));
        }
        if (sourceId != null) {
            filterBuilder.must(QueryBuilders.termQuery("sourceId", sourceId));
        }
        filterBuilder.mustNot(QueryBuilders.existsQuery("endDate"));

        IESQueryBuilderHelper<Deployment> queryBuilderHelper = alienDao.buildQuery(Deployment.class);
        return queryBuilderHelper.setFilters(filterBuilder).prepareSearch().setFieldSort("startDate", "long", true).search(from, size).getData();
    }

    /**
     * Get a deployment given its id
     *
     * @param id id of the deployment
     * @return deployment with given id
     */
    public Deployment get(String id) {
        return alienDao.findById(Deployment.class, id);
    }

    /**
     * Get a deployment given its id
     *
     * @param id id of the deployment
     * @return deployment with given id
     */
    public Deployment getOrfail(String id) {
        Deployment deployment = alienDao.findById(Deployment.class, id);
        if (deployment == null) {
            throw new NotFoundException("Deployment <" + id + "> doesn't exist.");
        }
        return deployment;
    }

    /**
     * Get an active Deployment for a given environment or throw a NotFoundException if no active deployment can be found for this environment.
     *
     * @param environmentId Id of the application environment.
     * @return The active deployment for this environment
     */
    public Deployment getActiveDeploymentOrFail(String environmentId) {
        Deployment deployment = getActiveDeployment(environmentId);
        if (deployment == null) {
            throw new NotFoundException("Deployment for environment <" + environmentId + "> doesn't exist.");
        }
        return deployment;
    }

    /**
     * Get a deployment for a given environment/
     *
     * @param applicationEnvironmentId id of the environment
     * @return active deployment if exist or the last, null if the application environment has not been deployed
     */
    public Deployment getDeployment(String applicationEnvironmentId) {
        Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId" },
                new String[][] { new String[] { applicationEnvironmentId } });
        GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, null, null, 0, Integer.MAX_VALUE,
                "endDate", "long", true);
        if (dataResult.getData() != null && dataResult.getData().length > 0) {
            if (dataResult.getData()[dataResult.getData().length - 1].getEndDate() == null) {
                return dataResult.getData()[dataResult.getData().length - 1];
            } else {
                return dataResult.getData()[0];
            }
        }
        return null;
    }

    /**
     * Get an active deployment for a given environment
     *
     * @param applicationEnvironmentId id of the environment
     * @return active deployment or null if not exist
     */
    public Deployment getActiveDeployment(String applicationEnvironmentId) {
        Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId", "endDate" },
                new String[][] { new String[] { applicationEnvironmentId }, new String[] { null } });
        GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1);
        if (dataResult.getData() != null && dataResult.getData().length > 0) {
            return dataResult.getData()[0];
        }
        return null;
    }

    /**
     * Get an active Deployment for a given cloud and topology or throw a NotFoundException if no active deployment can be found.
     *
     * @param topologyId id of the topology that has been deployed
     * @param orchestratorId id of the target orchestrator.
     * @return a deployment
     * @throws alien4cloud.exception.NotFoundException if not any deployment exists
     */
    public Deployment getActiveDeploymentOrFail(String topologyId, String orchestratorId) {
        Deployment deployment = getActiveDeployment(orchestratorId, topologyId);
        if (deployment == null) {
            throw new NotFoundException("Deployment for cloud <" + orchestratorId + "> and topology <" + topologyId + "> doesn't exist.");
        }
        return deployment;
    }

    /**
     * Get a topology for a given cloud / topology
     *
     * @param orchestratorId targeted orchestrator id
     * @param topologyId id of the topology to deploy
     * @return a deployment
     */
    public Deployment getActiveDeployment(String orchestratorId, String topologyId) {
        Deployment deployment = null;
        Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "topologyId", "endDate" },
                new String[][] { new String[] { orchestratorId }, new String[] { topologyId }, new String[] { null } });
        GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1);
        if (dataResult.getData() != null && dataResult.getData().length > 0) {
            deployment = dataResult.getData()[0];
        }
        return deployment;
    }

    /**
     * Check if there is an active deployment on a given orchestrator with the given orchestrator deployment id.
     *
     * @param orchestratorId The if of the orchestrator for which to check if there is a deployment with the given orchestratorDeploymentId.
     * @param orchestratorDeploymentId Unique if of the deployment for a given orchestrator
     * @return True if there is an active deployment for theses ids, false if not.
     */
    public boolean isActiveDeployment(String orchestratorId, String orchestratorDeploymentId) {
        Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "orchestratorDeploymentId", "endDate" },
                new String[][] { new String[] { orchestratorId }, new String[] { orchestratorDeploymentId }, new String[] { null } });
        GetMultipleDataResult<Deployment> dataResult = alienDao.find(Deployment.class, activeDeploymentFilters, 1);
        return dataResult.getData() != null && dataResult.getData().length > 0;
    }

    public Map<String, String> getCloudActiveDeploymentContexts(String orchestratorId) {
        Deployment[] deployments = getOrchestratorActiveDeployments(orchestratorId);
        Map<String, String> result = Maps.newHashMap();
        for (Deployment deployment : deployments) {
            result.put(deployment.getOrchestratorDeploymentId(), deployment.getId());
        }
        return result;
    }

    public Deployment[] getOrchestratorActiveDeployments(String orchestratorId) {
        Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "endDate" },
                new String[][] { new String[] { orchestratorId }, new String[] { null } });
        GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, Integer.MAX_VALUE);
        return dataResult.getData();
    }

    /**
     * For a given environment get all deployments that have been and compute a map of deployment orchestrator ids by orchestrator id.
     *
     * @param applicationEnvironmentId The id of the application environment for which to get the map or pas deployment
     * @return A map of orchestrator deployment ids by orchestrator ids.
     */
    public Map<String, Set<String>> getOrchestratorDeploymentIdsByOrchestratorId(String applicationEnvironmentId) {
        Map<String, Set<String>> result = new HashMap<>();
        GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null,
                FilterUtil.fromKeyValueCouples("environmentId", applicationEnvironmentId), Integer.MAX_VALUE);
        if (dataResult.getData() != null && dataResult.getData().length > 0) {
            for (Deployment deployment : dataResult.getData()) {
                if (!result.containsKey(deployment.getOrchestratorId())) {
                    result.put(deployment.getOrchestratorId(), new HashSet<String>());
                }
                result.get(deployment.getOrchestratorId()).add(deployment.getOrchestratorDeploymentId());
            }
        }
        return result;
    }

    /**
     * Switch a deployment to undeployed.
     *
     * @param deployment the deployment to switch.
     */
    public void markUndeployed(Deployment deployment) {
        if (deployment.getEndDate() == null) {
            deployment.setEndDate(new Date());
            alienDao.save(deployment);
            // Switch the deployed field of the Deployment topology to false
            DeploymentTopology deploymentTopology = alienMonitorDao.findById(DeploymentTopology.class, deployment.getId());
            deploymentTopology.setDeployed(false);
            alienMonitorDao.save(deploymentTopology);

            eventPublisher.publishEvent(new DeploymentUndeployedEvent(this,deployment.getId()));
        } else {
            log.info("Deployment <" + deployment.getId() + "> is already marked as undeployed.");
        }
    }

    /**
     * Check if a CSAR is currently deployed through dependencies in a topology.
     *
     * @return True if the archive is used in a deployment, false if not.
     */
    public boolean isArchiveDeployed(String archiveName, String archiveVersion) {
        return alienMonitorDao.buildQuery(DeploymentTopology.class).prepareSearch()
                .setFilters(fromKeyValueCouples("deployed", "true", "dependencies.name", archiveName, "dependencies.version", archiveVersion)).count() > 0;
    }

    /**
     * Checks if a deployment can be updated using the provided {@link DeploymentTopology}
     *
     * @param deployment The deployment to update
     * @param deploymentTopology The deployment topology to use for the update
     *
     * @throws ImpossibleDeploymentUpdateException when the update is not possible
     */
    public void checkDeploymentUpdateFeasibility(Deployment deployment, DeploymentTopology deploymentTopology) {
        // for now just check if the locations are identical
        Set<String> deploymentLocations = Sets.newHashSet(deployment.getLocationIds());
        Collection<String> deploymentTopologyLocations = TopologyLocationUtils.getLocationIds(deploymentTopology).values();
        if (!CollectionUtils.isEqualCollection(deploymentLocations, deploymentTopologyLocations)) {
            throw new ImpossibleDeploymentUpdateException("Locations between the current deployment and the deployment topology do not match");
        }
    }
}


text:
package org.nenapu.java.thread.executor;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;

/**
 * Type of the {@link SequenceAwareExecutorJob}. This job is created using
 * {@link Callable} task.
 *
 * @author Kirana NS
 *
 * @param <T>
 */
public final class CallableJob<T> implements SequenceAwareExecutorJob {

	private String reference = "";
	private long uniqueId = -1L;
	private RunnableFuture<T> job = null;

	public CallableJob(long uniqueId, String reference, Callable<T> callable){
		this.uniqueId = uniqueId;
		this.reference = reference;
		this.job = new FutureTask<T>(callable);
	}

	public String getRefernce(){
		return reference;
	}

	public long getUniqueId(){
		return uniqueId;
	}

	public Runnable getJob(){
		return job;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((reference == null) ? 0 : reference.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CallableJob other = (CallableJob) obj;
		if (reference == null) {
			if (other.reference != null)
				return false;
		} else if (!reference.equals(other.reference))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "CallableJob [reference=" + reference + ", uniqueId=" + uniqueId + "]";
	}
}


text:
package com.sun.tools.ws.ant;

/**
 * Wrapper task to launch {@link WsImport2}.
 *
 * @author Kohsuke Kawaguchi
 */
public class WsImport extends WrapperTask {
    /**
     * Default constructor.
     */
    public WsImport() {}

}


text:
cask 'slimboat' do
  version :latest
  sha256 :no_check

  url 'http://www.slimboat.com/release/slimboat.dmg'
  name 'SlimBoat'
  homepage 'http://www.slimboat.com'
  license :gratis

  app 'SlimBoat.app'
end


text:
/**
 * Helper used for working with collections of dynamic model data that
 * might use the [PreviewImage] data annotation to provide an image preview
 * field. This helper extracts the ids, loads the data and provides methods
 * for upading the dataset without having to reload all the images.
 */
angular.module('cms.shared').factory('shared.ImagePreviewFieldCollection', [
    '$q',
    '_',
    'shared.arrayUtilities',
    'shared.imageService',
    function (
    $q,
    _,
    arrayUtilities,
    imageService
) {
        return ImagePreviewFieldCollection;

        function ImagePreviewFieldCollection(partitionByProperty) {
            var me = this,
                imagePropertyName,
                cachedFieldSet,
                PREVIEW_IMAGE_FIELD_NAME = 'previewImage';

            /* Public Properties */

            //me.images

            /* Public Funcs */

            me.load = function (dataset, fieldSet) {
                cachedFieldSet = fieldSet;

                if (!dataset
                    || !dataset.length
                    || !fieldSet) return resolveNoData();

                var allImageIds = _.chain(dataset)
                    .map(function (item) {
                        return modelPropertyAccessor(item, getImagePropertyName(item));
                    })
                    .filter(function (id) {
                        return !!id;
                    })
                    .uniq()
                    .value();

                if (!allImageIds.length) return resolveNoData();

                return imageService.getByIdRange(allImageIds).then(function (images) {
                    me.images = [];

                    _.each(dataset, function (item) {
                        var id = modelPropertyAccessor(item, getImagePropertyName(item)),
                            image;

                        if (id) {
                            image = _.find(images, { imageAssetId: id });
                        }

                        me.images.push(image);
                    });
                });

                function resolveNoData() {
                    var deferred = $q.defer();
                    deferred.resolve();

                    me.images = [];

                    return deferred.promise;
                }
            };

            me.move = function (itemToMoveIndex, moveToIndex) {
                arrayUtilities.move(me.images, itemToMoveIndex, moveToIndex);
            };

            me.add = function (itemToAdd, index) {
                return updateImage(itemToAdd, index, true);
            };

            me.update = function (itemToUpdate, index) {
                return updateImage(itemToUpdate, index);
            };

            me.remove = function (index) {
                arrayUtilities.remove(me.images, index);
            };

            /* Private */

            function getImagePropertyName(model) {
                // In the case of multi-type grids we can partition fieldsets by a property
                if (partitionByProperty) {
                    var partitionId = model[partitionByProperty];
                    var field = cachedFieldSet[partitionId].fields[PREVIEW_IMAGE_FIELD_NAME];

                    if (!field) return undefined;

                    return field.lowerName;
                }

                // cache the property name
                if (!imagePropertyName && cachedFieldSet.fields[PREVIEW_IMAGE_FIELD_NAME]) {
                    imagePropertyName = cachedFieldSet.fields[PREVIEW_IMAGE_FIELD_NAME].lowerName;
                }

                return imagePropertyName;
            }

            function updateImage(itemToUpdate, index, isNew) {
                var propertyName = getImagePropertyName(itemToUpdate);
                if (!propertyName) return;

                var newImageId = modelPropertyAccessor(itemToUpdate, propertyName);

                if (!isNew) {
                    var existingImage = me.images[index],
                        existingId;

                    if (existingImage) {
                        existingId = existingImage['imageAssetId'];
                    }

                    if (newImageId == existingId) return;

                    if (!newImageId) {
                        me.images[index] = undefined;
                        return;
                    }
                }

                return imageService
                    .getById(newImageId)
                    .then(loadImage);

                function loadImage(image) {
                    me.images[index] = image;
                }
            }

            function modelPropertyAccessor(item, propertyName) {

                if (!propertyName) return undefined;

                // if the model is a child of the item e.g. custom entities
                if (item.model) return item.model[propertyName];

                return item[propertyName];
            }
        }
}]);


text:
code {
  background-color: transparent;
  border: none;
  padding: 0;
  font-size: var(--code-font-size);
}


text:
sap.ui.define(["exports", "sap/ui/webc/common/thirdparty/base/types/DataType"], function (_exports, _DataType) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.default = void 0;
  _DataType = _interopRequireDefault(_DataType);

  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

  /**
   * @lends sap.ui.webcomponents.main.types.InputType.prototype
   * @public
   */
  const InputTypes = {
    /**
     * Defines a one-line text input field:
     * @public
     * @type {Text}
     */
    Text: "Text",

    /**
     * Used for input fields that must contain an e-mail address.
     * @public
     * @type {Email}
     */
    Email: "Email",

    /**
     * Defines a numeric input field.
     * @public
     * @type {Number}
     */
    Number: "Number",

    /**
     * Defines a password field.
     * @public
     * @type {Password}
     */
    Password: "Password",

    /**
     * Used for input fields that should contain a telephone number.
     * @public
     * @type {Tel}
     */
    Tel: "Tel",

    /**
     * Used for input fields that should contain a URL address.
     * @public
     * @type {URL}
     */
    URL: "URL"
  };
  /**
   * @class
   * Defines input types
   * @constructor
   * @author SAP SE
   * @alias sap.ui.webcomponents.main.types.InputType
   * @public
   * @enum {string}
   */

  class InputType extends _DataType.default {
    static isValid(value) {
      return !!InputTypes[value];
    }

  }

  InputType.generateTypeAccessors(InputTypes);
  var _default = InputType;
  _exports.default = _default;
});


text:
const should = require('chai').should();
const supertest = require('supertest');
const sinon = require('sinon');
const sinonMongoose = require('sinon-mongoose');
const expect = require('chai').expect;
const app = require('../../bin/www');
const Restaurants = require('../server/restaurants/restaurantEntity');
const url = supertest('http://localhost:8080/restaurants');

describe('Restaurant CRUD Testing using sinon',() => {

  it('should get all the restaurant',(done) => {
      let RestaurantMock = sinon.mock(Restaurants);
      let expectedResult = {status:true};

      RestaurantMock.expects('find').yields(null, expectedResult);
      Restaurants.find(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(result.status).to.be.true;
        done();
      });
  });

  it('should not get the restaurants',(done) => {
      let RestaurantMock = sinon.mock(Restaurants);
      let expectedResult = {status:false };

      RestaurantMock.expects('find').yields(expectedResult, null);
      Restaurants.find(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(err.status).to.be.false;
        done();
      });
  });

it('should add new restaurant',(done) => {
      let RestaurantMock = sinon.mock(new Restaurants({resId:5}));
      let rest = RestaurantMock.object;
      let expectedResult = {status: true};
      RestaurantMock.expects('save').yields(null, expectedResult);
      rest.save(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(result.status).to.be.true;
        done();
      });
});

it('should not add new restaurant',(done) => {
      let RestaurantMock = sinon.mock(new Restaurants({resId:5}));
      let rest = RestaurantMock.object;
      let expectedResult = {status: false};
      RestaurantMock.expects('save').yields(expectedResult, null);
      rest.save(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(err.status).to.be.false;
        done();
      });
});

it('should update restaurant by Id',(done) => {
      let RestaurantMock = sinon.mock(new Restaurants({resLoc:'bangalore'}));
      let rest = RestaurantMock.object;
      let expectedResult = {status: true};
      RestaurantMock.expects('save').yields(null, expectedResult);
      rest.save(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(result.status).to.be.true;
        done();
      });
});

it('should not update restaurant by Id',(done) => {
      let RestaurantMock = sinon.mock(new Restaurants({resLoc:'bangalore'}));
      let rest = RestaurantMock.object;
      let expectedResult = {status: false};
      RestaurantMock.expects('save').yields(expectedResult, null);
      rest.save(function(err,result){
        RestaurantMock.verify();
        RestaurantMock.restore();
        expect(err.status).to.not.be.true;
        done();
      });
});

it('should delete the restaurant',(done) => {
    let RestaurantMock = sinon.mock(Restaurants);
    let expectedResult = {status:true};

    RestaurantMock.expects('remove').yields(null, expectedResult);
    Restaurants.remove(function(err,result){
      RestaurantMock.verify();
      RestaurantMock.restore();
      expect(result.status).to.be.true;
      done();
    });
});

it('should not delete the restaurant',(done) => {
    let RestaurantMock = sinon.mock(Restaurants);
    let expectedResult = {status:false};

    RestaurantMock.expects('remove').yields(expectedResult, null);
    Restaurants.remove(function(err,result){
      RestaurantMock.verify();
      RestaurantMock.restore();
      expect(err.status).to.not.be.true;
      done();
    });
});

});


text:
import argparse
import os
import subprocess

def options():
    """Parse command line options.

    Args:

    Returns:
        argparse object.
    Raises:
        IOError: if the file diagram1 does not exist.
        IOError: if the file diagram2 does not exist.
    """

    parser = argparse.ArgumentParser(description="Run bottleneck-distance in parallel using HTCondor",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("--exe", help="Fully-qualified path to the bottleneck-distance executable.", required=True)
    parser.add_argument("--diagram1", help="Filename of the first diagram file.", required=True)
    parser.add_argument("--diagram2", help="Filename of the second diagram file.", required=True)
    args = parser.parse_args()

    # If the input file diagram1 does not exist, stop
    if not os.path.exists(args.diagram1):
        raise IOError("File does not exist: {0}".format(args.diagram1))

    # If the input file diagram2 does not exist, stop
    if not os.path.exists(args.diagram2):
        raise IOError("File does not exist: {0}".format(args.diagram2))

    return args

def main():
    # Parse flags
    args = options()

    output = subprocess.check_output([args.exe, args.diagram1, args.diagram2])
    output = output.rstrip("\n")
    label, distance = output.split(" ")
    print('\t'.join(map(str, [args.diagram1, args.diagram2, distance])))

if __name__ == '__main__':
    main()


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="generator" content="Luke Anderson" />
  <title>--_--</title>

  <meta name="theme-color" content="#2E3AA1">

  <link rel="manifest" href="manifest.json">

  <link rel="stylesheet" href="styles/main.css">

  <link rel="import" href="elements/elements.html">

  <template is="dom-bind" id="app">

      <tempo-controller metronome="{{audio.metronome}}"></tempo-controller>

          <driver-factory></driver-factory>

            <multi-sampler
                sampler-model={{sampler}}
                connection-input={{connectionBusses.drivers}}
                connection-output={{connectionBusses.instruments}}>
            </multi-sampler>

        <connector-bus bus-model="{{connectionBusses.drivers}}"></connector-bus>

          <instrument-factory
            factory-model="{{audio.instrumentFactory}}"
            connection-input={{connectionBusses.drivers}}
            connection-output={{connectionBusses.instruments}}
            instrument-container="instrument-container">
          </instrument-factory>

        <connector-bus bus-model="{{connectionBusses.instruments}}"></connector-bus>

          <effect-factory
            factory-model="{{audio.effectFactory}}"
            connection-input={{connectionBusses.instruments}}
            connection-output={{connectionBusses.effects1}}
            effect-container="effect-container-01">
          </effect-factory>

        <connector-bus bus-model="{{connectionBusses.effects1}}"></connector-bus>

          <effect-factory
            factory-model="{{audio.effectFactory}}"
            connection-input={{connectionBusses.effects1}}
            connection-output={{connectionBusses.effects2}}
            effect-container="effect-container-02">
          </effect-factory>

        <connector-bus bus-model="{{connectionBusses.effects2}}"></connector-bus>

          <template is="dom-repeat" items="{{audio.lastEqualizerList}}" as="equalizer">
            <equalizer-three
              equalizer-model={{equalizer}}
              connection-input={{connectionBusses.effects2}}>
            </equalizer-three>
          </template>

    <sound-visualizer model="[[audio.visualizer]]"></sound-visualizer>

    <paper-toast id="toast">
      Ok
    </paper-toast>

  </template>


text:
package org.openqa.selenium.remote.server.handler;

import org.openqa.selenium.Rotatable;
import org.openqa.selenium.ScreenOrientation;
import org.openqa.selenium.remote.server.Session;

public class GetScreenOrientation extends WebDriverHandler<ScreenOrientation> {

  public GetScreenOrientation(Session session) {
    super(session);
  }

  @Override
  public ScreenOrientation call() {
    return ((Rotatable) getUnwrappedDriver()).getOrientation();
  }

  @Override
  public String toString() {
    return "[get screen orientation]";
  }
}


text:
package com.spectralogic.ds3autogen.go.generators.request;

import com.spectralogic.ds3autogen.api.models.apispec.Ds3Request;
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Type;
import com.spectralogic.ds3autogen.go.models.request.Request;

@FunctionalInterface
public interface RequestModelGenerator<T extends Request> {
    T generate(final Ds3Request ds3Request);
}


text:
"""
This module is not meant to be imported directly.
Its purpose is to patch the TohuBaseGenerator class
so that its special methods __add__, __mul__ etc.
support other generators as arguments.
"""

from operator import add, mul, gt, ge, lt, le, eq

from .base import TohuBaseGenerator
from .primitive_generators import GeoJSONGeolocation, SelectOnePrimitive, Timestamp, as_tohu_generator
from .derived_generators import Apply, GetAttribute, SelectOneDerived
from .utils import identity

__all__ = []

def add_generators(self, other):
    return Apply(add, self, as_tohu_generator(other))

def radd_generators(self, other):
    return Apply(add, as_tohu_generator(other), self)

def mul_generators(self, other):
    return Apply(mul, self, as_tohu_generator(other))

def rmul_generators(self, other):
    return Apply(mul, as_tohu_generator(other), self)

def eq_generators(self, other):
    return Apply(eq, self, as_tohu_generator(other))

def lt_generators(self, other):
    return Apply(lt, self, as_tohu_generator(other))

def le_generators(self, other):
    return Apply(le, self, as_tohu_generator(other))

def gt_generators(self, other):
    return Apply(gt, self, as_tohu_generator(other))

def ge_generators(self, other):
    return Apply(ge, self, as_tohu_generator(other))

# Patch TohuBaseGenerator with the new methods
TohuBaseGenerator.__add__ = add_generators
TohuBaseGenerator.__radd__ = radd_generators
TohuBaseGenerator.__mul__ = mul_generators
TohuBaseGenerator.__rmul__ = rmul_generators
TohuBaseGenerator.__eq__ = eq_generators
TohuBaseGenerator.__lt__ = lt_generators
TohuBaseGenerator.__le__ = le_generators
TohuBaseGenerator.__gt__ = gt_generators
TohuBaseGenerator.__ge__ = ge_generators

def getattribute_generators(self, name):

    if name == '__isabstractmethod__':
        # Special case which is needed because TohuUltraBaseMeta is
        # derived from ABCMeta and it uses '__isabstractmethod__'
        # to check for abstract methods.
        #
        # TODO: This check should probably be moved to TohuUltraBaseGenerator somewhere.
        return

    if name == '_ipython_canary_method_should_not_exist_':
        # Special case which is needed because IPython uses this attribute internally.
        raise NotImplementedError("Special case needed for IPython")

    return GetAttribute(self, name)

SelectOnePrimitive.__getattr__ = getattribute_generators
SelectOneDerived.__getattr__ = getattribute_generators

def split_geolocation(self):
    attributes = ['lon', 'lat'] + self.include_attributes
    return tuple(GetAttribute(self, attr_name) for attr_name in attributes)

GeoJSONGeolocation.split = split_geolocation


text:
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0;
const getRealtimeSignals=function(){
const length=SIGRTMAX-SIGRTMIN+1;
return Array.from({length},getRealtimeSignal);
};exports.getRealtimeSignals=getRealtimeSignals;

const getRealtimeSignal=function(value,index){
return{
name:`SIGRT${index+1}`,
number:SIGRTMIN+index,
action:"terminate",
description:"Application-specific signal (realtime)",
standard:"posix"};

};

const SIGRTMIN=34;
const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX;
//# sourceMappingURL=realtime.js.map


text:
using System.IO;

namespace Neutrino.Data {
    public class FileStreamOpener : IFileStreamOpener {
        public Stream OpenWithoutLock(string path) {
            return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
        }

        public Stream OpenWithLock(string path) {
            return new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 4096, true);
        }

        public Stream OpenForCreation(string path) {
            return new FileStream(path, FileMode.CreateNew);
        }

        public bool FileExists(string path) {
            return File.Exists(path);
        }
    }
}


text:
package org.unitime.timetable.server.hql;

import org.springframework.security.access.prepost.PreAuthorize;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.gwt.command.client.GwtRpcException;
import org.unitime.timetable.gwt.command.client.GwtRpcResponseBoolean;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.command.server.GwtRpcImplements;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.SavedHQLInterface.HQLDeleteRpcRequest;
import org.unitime.timetable.model.SavedHQL;
import org.unitime.timetable.model.dao.SavedHQLDAO;
import org.unitime.timetable.security.SessionContext;

/**
 * @author Tomas Muller
 */
@GwtRpcImplements(HQLDeleteRpcRequest.class)
public class HQLDeleteBackend implements GwtRpcImplementation<HQLDeleteRpcRequest, GwtRpcResponseBoolean>{
	protected static GwtMessages MESSAGES = Localization.create(GwtMessages.class);

	@Override
	@PreAuthorize("checkPermission(#request.id, 'SavedHQL', 'HQLReportDelete')")
	public GwtRpcResponseBoolean execute(HQLDeleteRpcRequest request, SessionContext context) {
		if (request.getId() == null) throw new GwtRpcException(MESSAGES.errorNoReportProvided());
		org.hibernate.Session hibSession = SavedHQLDAO.getInstance().getSession();
		SavedHQL hql = SavedHQLDAO.getInstance().get(request.getId(), hibSession);
		if (hql != null) {
			hibSession.delete(hql);
			hibSession.flush();
		}
		return new GwtRpcResponseBoolean(hql != null);
	}
}


text:
layout: page
title: Flex Twoer Motors Seminar
date: 2016-05-24
author: Pamela Cervantes
tags: weekly links, java
status: published
summary: Donec mattis suscipit erat. Curabitur nec metus malesuada.
banner: images/banner/wedding.jpg
booking:
  startDate: 11/18/2016
  endDate: 11/21/2016
  ctyhocn: SDYUTHX
  groupCode: FTMS
published: true
---
Nam magna mi, egestas et fringilla ut, finibus ut ex. Donec sit amet tristique sem. Suspendisse non arcu dui. Integer porta eleifend nulla nec interdum. Vivamus tincidunt nisi mattis, pharetra neque sit amet, rhoncus tellus. Cras laoreet augue augue, at congue augue sodales eu. Nulla in mollis augue, ac tincidunt eros. Nulla facilisi. Integer auctor vel risus quis ultricies. Nulla euismod velit et sollicitudin feugiat. Proin rhoncus placerat sem ac dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut quis mauris risus.
Aliquam elementum lacinia ligula ut pellentesque. Nulla bibendum, erat semper efficitur gravida, risus quam ultricies nisi, vel sagittis turpis dui ac nisl. Fusce pulvinar quam in neque eleifend finibus. Donec quis nisl urna. Proin pellentesque est orci, et gravida felis malesuada vitae. Phasellus interdum magna et tellus pharetra dictum. Nam vitae orci sit amet lorem euismod congue. Sed mauris dolor, pellentesque nec suscipit id, pretium id orci. Nulla sed urna lacus.

* Quisque sed risus vestibulum velit vulputate consectetur
* Aenean eget justo in est iaculis pretium
* Duis congue odio ut porttitor laoreet
* Quisque eu tellus et massa bibendum dignissim
* Sed eget nisi tincidunt, convallis ligula sit amet, efficitur ligula
* Vestibulum semper erat euismod, porta tellus eu, condimentum orci.

Mauris venenatis tortor eget dolor fringilla ornare. Ut ut lorem nec diam auctor suscipit eget sodales libero. Aenean pulvinar finibus dui, eget mollis nunc dignissim quis. Curabitur finibus sem ac venenatis porttitor. Nam interdum lobortis nisl. Ut id nisl a nunc feugiat cursus eget ut nibh. Nunc porta magna vel leo pretium egestas. Nunc tempor elit ante, nec porttitor nibh commodo ac. Praesent aliquam mi vitae posuere dictum. Cras finibus tortor et mauris rutrum, in mollis diam ultricies. Integer mattis ante sit amet eros facilisis blandit. Proin at ultrices mi, consequat ultrices dolor. In hac habitasse platea dictumst. Phasellus molestie ornare sagittis. Curabitur vehicula nulla quam, ac pretium justo eleifend eget.


text:
<!DOCTYPE html>

	<title>jQuery Spinner</title>
	<meta http-equiv="Content-Type" content="text/html; charset=WINDOWS-1252">

1 loop / second:

2 loop / second:

3 loop / second:


text:
package com.sun.tools.doclets.formats.html;

import java.io.*;

import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;

/**
 * Writes property documentation in HTML format.
 *
 *
This is NOT part of any supported API.
 *  If you write code that depends on this, you do so at your own risk.
 *  This code and its internal interfaces are subject to change or
 *  deletion without notice.
 *
 * @author Robert Field
 * @author Atul M Dambalkar
 * @author Jamie Ho (rewrite)
 * @author Bhavesh Patel (Modified)
 */
public class PropertyWriterImpl extends AbstractMemberWriter
    implements PropertyWriter, MemberSummaryWriter {

    public PropertyWriterImpl(SubWriterHolderWriter writer, ClassDoc classdoc) {
        super(writer, classdoc);
    }

    /**
     * {@inheritDoc}
     */
    public Content getMemberSummaryHeader(ClassDoc classDoc,
            Content memberSummaryTree) {
        memberSummaryTree.addContent(HtmlConstants.START_OF_PROPERTY_SUMMARY);
        Content memberTree = writer.getMemberTreeHeader();
        writer.addSummaryHeader(this, classDoc, memberTree);
        return memberTree;
    }

    /**
     * {@inheritDoc}
     */
    public Content getPropertyDetailsTreeHeader(ClassDoc classDoc,
            Content memberDetailsTree) {
        memberDetailsTree.addContent(HtmlConstants.START_OF_PROPERTY_DETAILS);
        Content propertyDetailsTree = writer.getMemberTreeHeader();
        propertyDetailsTree.addContent(writer.getMarkerAnchor(
                SectionName.PROPERTY_DETAIL));
        Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
                writer.propertyDetailsLabel);
        propertyDetailsTree.addContent(heading);
        return propertyDetailsTree;
    }

    /**
     * {@inheritDoc}
     */
    public Content getPropertyDocTreeHeader(MethodDoc property,
            Content propertyDetailsTree) {
        propertyDetailsTree.addContent(
                writer.getMarkerAnchor(property.name()));
        Content propertyDocTree = writer.getMemberTreeHeader();
        Content heading = new HtmlTree(HtmlConstants.MEMBER_HEADING);
        heading.addContent(property.name().substring(0, property.name().lastIndexOf("Property")));
        propertyDocTree.addContent(heading);
        return propertyDocTree;
    }

    /**
     * {@inheritDoc}
     */
    public Content getSignature(MethodDoc property) {
        Content pre = new HtmlTree(HtmlTag.PRE);
        writer.addAnnotationInfo(property, pre);
        addModifiers(property, pre);
        Content propertylink = writer.getLink(new LinkInfoImpl(
                configuration, LinkInfoImpl.Kind.MEMBER,
                property.returnType()));
        pre.addContent(propertylink);
        pre.addContent(" ");
        if (configuration.linksource) {
            Content propertyName = new StringContent(property.name());
            writer.addSrcLink(property, propertyName, pre);
        } else {
            addName(property.name(), pre);
        }
        return pre;
    }

    /**
     * {@inheritDoc}
     */
    public void addDeprecated(MethodDoc property, Content propertyDocTree) {
    }

    /**
     * {@inheritDoc}
     */
    public void addComments(MethodDoc property, Content propertyDocTree) {
        ClassDoc holder = property.containingClass();
        if (property.inlineTags().length > 0) {
            if (holder.equals(classdoc) ||
                    (! (holder.isPublic() || Util.isLinkable(holder, configuration)))) {
                writer.addInlineComment(property, propertyDocTree);
            } else {
                Content link =
                        writer.getDocLink(LinkInfoImpl.Kind.PROPERTY_DOC_COPY,
                        holder, property,
                        holder.isIncluded() ?
                            holder.typeName() : holder.qualifiedTypeName(),
                            false);
                Content codeLink = HtmlTree.CODE(link);
                Content descfrmLabel = HtmlTree.SPAN(HtmlStyle.descfrmTypeLabel, holder.isClass()?
                   writer.descfrmClassLabel : writer.descfrmInterfaceLabel);
                descfrmLabel.addContent(writer.getSpace());
                descfrmLabel.addContent(codeLink);
                propertyDocTree.addContent(HtmlTree.DIV(HtmlStyle.block, descfrmLabel));
                writer.addInlineComment(property, propertyDocTree);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public void addTags(MethodDoc property, Content propertyDocTree) {
        writer.addTagsInfo(property, propertyDocTree);
    }

    /**
     * {@inheritDoc}
     */
    public Content getPropertyDetails(Content propertyDetailsTree) {
        return getMemberTree(propertyDetailsTree);
    }

    /**
     * {@inheritDoc}
     */
    public Content getPropertyDoc(Content propertyDocTree,
            boolean isLastContent) {
        return getMemberTree(propertyDocTree, isLastContent);
    }

    /**
     * Close the writer.
     */
    public void close() throws IOException {
        writer.close();
    }

    public int getMemberKind() {
        return VisibleMemberMap.PROPERTIES;
    }

    /**
     * {@inheritDoc}
     */
    public void addSummaryLabel(Content memberTree) {
        Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
                writer.getResource("doclet.Property_Summary"));
        memberTree.addContent(label);
    }

    /**
     * {@inheritDoc}
     */
    public String getTableSummary() {
        return configuration.getText("doclet.Member_Table_Summary",
                configuration.getText("doclet.Property_Summary"),
                configuration.getText("doclet.properties"));
    }

    /**
     * {@inheritDoc}
     */
    public Content getCaption() {
        return configuration.getResource("doclet.Properties");
    }

    /**
     * {@inheritDoc}
     */
    public String[] getSummaryTableHeader(ProgramElementDoc member) {
        String[] header = new String[] {
            configuration.getText("doclet.Type"),
            configuration.getText("doclet.0_and_1",
                    configuration.getText("doclet.Property"),
                    configuration.getText("doclet.Description"))
        };
        return header;
    }

    /**
     * {@inheritDoc}
     */
    public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
        memberTree.addContent(writer.getMarkerAnchor(
                SectionName.PROPERTY_SUMMARY));
    }

    /**
     * {@inheritDoc}
     */
    public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
        inheritedTree.addContent(writer.getMarkerAnchor(
                SectionName.PROPERTIES_INHERITANCE,
                configuration.getClassName(cd)));
    }

    /**
     * {@inheritDoc}
     */
    public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
        Content classLink = writer.getPreQualifiedClassLink(
                LinkInfoImpl.Kind.MEMBER, cd, false);
        Content label = new StringContent(cd.isClass() ?
            configuration.getText("doclet.Properties_Inherited_From_Class") :
            configuration.getText("doclet.Properties_Inherited_From_Interface"));
        Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING,
                label);
        labelHeading.addContent(writer.getSpace());
        labelHeading.addContent(classLink);
        inheritedTree.addContent(labelHeading);
    }

    /**
     * {@inheritDoc}
     */
    protected void addSummaryLink(LinkInfoImpl.Kind context, ClassDoc cd, ProgramElementDoc member,
            Content tdSummary) {
        Content memberLink = HtmlTree.SPAN(HtmlStyle.memberNameLink,
                writer.getDocLink(context, cd,
                (MemberDoc) member,
                member.name().substring(0, member.name().lastIndexOf("Property")),
                false,
                true));

        Content code = HtmlTree.CODE(memberLink);
        tdSummary.addContent(code);
    }

    /**
     * {@inheritDoc}
     */
    protected void addInheritedSummaryLink(ClassDoc cd,
            ProgramElementDoc member, Content linksTree) {
        linksTree.addContent(
                writer.getDocLink(LinkInfoImpl.Kind.MEMBER, cd, (MemberDoc)member,
                ((member.name().lastIndexOf("Property") != -1) && configuration.javafx)
                        ? member.name().substring(0, member.name().length() - "Property".length())
                        : member.name(),
                false, true));
    }

    /**
     * {@inheritDoc}
     */
    protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) {
        MethodDoc property = (MethodDoc)member;
        addModifierAndType(property, property.returnType(), tdSummaryType);
    }

    /**
     * {@inheritDoc}
     */
    protected Content getDeprecatedLink(ProgramElementDoc member) {
        return writer.getDocLink(LinkInfoImpl.Kind.MEMBER,
                (MemberDoc) member, ((MethodDoc)member).qualifiedName());
    }

    /**
     * {@inheritDoc}
     */
    protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
        if (link) {
            if (cd == null) {
                return writer.getHyperLink(
                SectionName.PROPERTY_SUMMARY,
                writer.getResource("doclet.navProperty"));
            } else {
                return writer.getHyperLink(
                SectionName.PROPERTIES_INHERITANCE,
                configuration.getClassName(cd), writer.getResource("doclet.navProperty"));
            }
        } else {
            return writer.getResource("doclet.navProperty");
        }
    }

    /**
     * {@inheritDoc}
     */
    protected void addNavDetailLink(boolean link, Content liNav) {
        if (link) {
            liNav.addContent(writer.getHyperLink(
                    SectionName.PROPERTY_DETAIL,
                    writer.getResource("doclet.navProperty")));
        } else {
            liNav.addContent(writer.getResource("doclet.navProperty"));
        }
    }
}


text:
//
//  ASPEmailPropertyWithStringValue.m
//  Aspose.Email_Cloud_SDK_For_Objective_C
//
//  Created by Muhammad Sohail Ismail on 29/11/2015.
//  Copyright © 2015 Aspose. All rights reserved.
//

#import "ASPEmailPropertyWithStringValue.h"

@implementation ASPEmailPropertyWithStringValue

/**
 * Maps json key to property name.
 * This method is used by `JSONModel`.
 */
+ (JSONKeyMapper *)keyMapper
{
    return [[JSONKeyMapper alloc] initWithDictionary:@{ @"Link": @"link", @"Name": @"name", @"Value": @"value" }];
}

/**
 * Indicates whether the property with the given name is optional.
 * If `propertyName` is optional, then return `YES`, otherwise return `NO`.
 * This method is used by `JSONModel`.
 */
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
    NSArray *optionalProperties = @[@"link", @"name", @"value"];

    if ([optionalProperties containsObject:propertyName]) {
        return YES;
    }
    else {
        return NO;
    }
}

/**
 * Gets the string presentation of the object.
 * This method will be called when logging model object using `NSLog`.
 */
- (NSString *)description {
    return [[self toDictionary] description];
}

@end


text:
'use strict';
const meow = require('meow');
const opn = require('opn');
const getStdin = require('get-stdin');
const tempWrite = require('temp-write');
const fileType = require('file-type');

const cli = meow(`
	Usage
	  $ opn <file|url> [--wait] [-- <app> [args]]
	  $ cat <file> | opn [--wait] [--ext] [-- <app> [args]]

	Options
	  --wait  Wait for the app to exit
	  --ext   File extension for when stdin file type can't be detected

	Examples
	  $ opn http://sindresorhus.com
	  $ opn http://sindresorhus.com -- firefox
	  $ opn http://sindresorhus.com -- 'google chrome' --incognito
	  $ opn unicorn.png
	  $ cat unicorn.png | opn
	  $ echo '
Unicorns!
' | opn --ext=html
`, {
	default: {
		wait: false
	}
});

cli.flags.app = cli.input.slice(1);

const input = cli.input[0];

if (!input && process.stdin.isTTY) {
	console.error('Specify a filepath or URL');
	process.exit(1);
}

if (input) {
	opn(input, cli.flags);
} else {
	getStdin.buffer().then(stdin => {
		const type = fileType(stdin);
		const ext = (cli.flags.ext || type && type.ext || 'txt');
		opn(tempWrite.sync(stdin, `opn.${ext}`), cli.flags);
	});
}


text:
package de.windelknecht.stup.utils.data.length

import org.scalatest.{Matchers, WordSpecLike}

class toBitLengthSpec
  extends WordSpecLike
  with Matchers {
  "want a bit" when {
    "using function bit"   should { test("bit",   toBitLength(8).bit, 8) }
    "using function bits"  should { test("bits",  toBitLength(8).bits, 8) }
    "using function Bit"   should { test("Bit",   toBitLength(8).Bit, 8) }
    "using function Bits"  should { test("Bits",  toBitLength(8).Bits, 8) }
  }

  "want a byte" when {
    "using function byte"  should { test("byte",  toBitLength(8).asByte, 64) }
  }

  def test(
    func: String,
    data: BitLength,
    expectedLen: Int
    ): Unit = {
    s"return correct len" in {
      withClue(s"function '$func': $data.len should be $expectedLen, but") {
        data.len should be(expectedLen)
      }
    }
  }
}


text:
\newcommand{\zNormalizationPerformed}[1]
{
  \textcolor{red}{\\It is important to NOTE that RAVEN uses a Z-score normalization of the training data before
  constructing the \textit{#1} ROM:
\begin{equation}
  \mathit{\mathbf{X'}} = \frac{(\mathit{\mathbf{X}}-\mu )}{\sigma }
\end{equation}
 }
}

\subsection{Build RAVEN Input: \xmlNode{RomTrainer}}
\label{sub:ravenROM}
The \textbf{RomTrainer} step type performs the training of a Reduced Order Model (ROM), and the specifications of
this step must be defined within a \xmlNode{RomTrainer} block. ROMs, also known as a surrogate model,  are used
to lower the computational cost, reducing the number of needed points and prioritizing the area of the input space
that needs to be explored when the simulations using the high-fidelity codes are very expensive. ROMs can be
considered as an artificial representation of the link between the input and output spaces for a particular system.

In most of the cases of interest, the information that is sought is related to defining the failure boundaries of
a system with respect to perturbations in the input space. For this reason, in the development of RAVEN, it has been
given priority to the introduction of a class of supervised learning algorithms, which are usually referred to as
classifiers. A classifier is a reduced order model that is capable of representing the system behavior through a
binary response (failure/success). Currently, RAVEN supports around 40 different ROM methodologies. All these
supervised learning algorithms have been imported via an API from the Scikit-Learn library. In addition, the N-Dimensional
spline and the inverse weight methods that are currently available for the interpolation of N-Dimensional PDF/CDF,
can also be used as ROMs.

In this section, the N-dimensional inverse weight method is employed to construct ROM to familarize the user with
the use of ROMs. Inverse distance weighting (IDW) is a type of deterministic method for multivariate interpolation
with a known scattered set of points. The assigned values to unknown points are calculated via a weighted average
of the values available at the known points.
\zNormalizationPerformed{NDinvDistWeight}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Train and dump the rom
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{How to train and output a ROM?}
In general, the ``training'' is a process that use sampling of the physical model to improve the prediction
capability of the ROM. As mentioned before, RAVEN provides lots of different sampling strategies, such as Monte
Carlo, Grid, Stratified (e.g. LHS), and Stochastic Collocation methods. All of them can be used to train a ROM.
In this section, we will continue to use \textbf{AnalyticBateman} to illustrate the setup of \textbf{RomTrainer}.
As before, a simple step \textbf{MultiRun} with \textbf{Monte Carlo} sampler is employed to generate the data set
that can be used to train the ROM. The full RAVEN input file can be found:
\textit{raven/tests/framework/user\_guide/ravenTutorial/RomTrain.xml}.
Because the setup of \textbf{MultiRun} is the same as previous example in section~\ref{sub:tutorialMultiRun}, the
RAVEN input file about the \textbf{MultiRun} is not include in this section. However, the full precedures are
listed here to make the user better understand the construction of ROM. The following precedures or RAVEN entities
are needed:

\begin{itemize}
  \item \textbf{MultiRun}: Monte Carlo sampling to generate the data set
  \begin{enumerate}
    \item Set up the running environment: \xmlNode{RunInfo};
    \item Provide the required files: \xmlNode{Files};
    \item Link between RAVEN and dirven code: \xmlNode{Code};
    \item Define probability distribution functions for inputs: \xmlNode{Distributions};
    \item Set up a simple Monte-Carlo sampling for perturbing the input space: \xmlNode{Samplers};
    \item Store the input and output data: \xmlNode{DataObjects};
    \item Print and plot input and output data: \xmlNode{OutStreams};
    \item Control multiple executions: \xmlNode{MultiRun}.
  \end{enumerate}
  \item \textbf{RomTrainer}: Train the ROM with given data set
  \begin{enumerate}
    \item Specify the type of ROMs: \xmlNode{ROM};
    \item Provide the data set for ROM training: \xmlNode{DataObjects};
    \item Train the ROM: \xmlNode{RomTrainer};
    \item Dump the ROM: \xmlNode{IOStep}
  \end{enumerate}
\end{itemize}

The specifications of the reduced order model must be defined within \xmlNode{ROM} XML block. This XML node accepts
the following attributes:

\begin{itemize}
  \itemsep0em
  \item \xmlAttr{name}, \xmlDesc{required string attribute}, user-defined identifier of this model.
  \item \xmlAttr{subType}, \xmlDesc{required string attribute}, defines which of
  the sub-types should be used, choosing among the previously reported types.
\end{itemize}
\vspace{-5mm}

In the \xmlNode{ROM} input block, the following XML sub-nodes are required,
independent of the \xmlAttr{subType} specified:
%
\begin{itemize}
   \item \xmlNode{Features}, \xmlDesc{comma separated string, required field}, specifies the names of the features
     of this ROM. \nb These parameters are going to be requested for the training of this object;
    \item \xmlNode{Target}, \xmlDesc{comma separated string, required field}, contains a comma separated list of
      the targets of this ROM. These parameters are the Figures of Merit (FOMs) this ROM is supposed to predict.
      \nb These parameters are going to be requested for the training of this object.
\end{itemize}

For each sub-type specified in the attribute \xmlAttr{subType}, additional sub-nodes may be required (Please check
the RAVEN user manual for each ROM). In addition, if an \xmlNode{HistorySet} is provided in the training step, then
a temporal ROM is created, i.e. a ROM that generates not a single value prediction of each element indicated in
the \xmlNode{Target} block but its full temporal profile. In this section, a time-dependent ROM will be constructed.

In order to use \textbf{N-dimensional inverse distance weighting} ROM, the \xmlNode{ROM} attribute \xmlAttr{subType}
needs to be \xmlString{NDinvDistWeight}. The following addition sub-node is also required.

\begin{itemize}
  \item \xmlNode{p}, \xmlDesc{integer, required field}, must be greater than zero and represents the
    ``power parameter''. For the choice of value for \xmlNode{p},it is necessary to consider the degree
    of smoothing desired in the interpolation/extrapolation, the density and distribution of samples being
    interpolated, and the maximum distance over which an individual sample is allowed to influence the
    surrounding ones (lower $p$ means greater importance for points far away).
\end{itemize}

Based on previous RAVEN input file used in section~\ref{sub:tutorialMultiRun}, the \xmlNode{ROM}, \xmlNode{RomTrain}
and \xmlNode{IOStep} are added. The \xmlNode{ROM} is used to describe the N-dimensional inverse distance weighting
ROM:
\xmlExample{framework/user_guide/ravenTutorial/RomTrain.xml}{Models}
The inputs and outputs of \textbf{AnalyticBateman} is used to generate the data set. The ROM will be constructed considering
two features (\textit{sigma-A and decay-A}) and two targets (\textit{A and time}). \nb the \textit{time} is treated
as target in ROM construction.

Then, the \xmlNode{RomTrain} and \xmlNode{IOStep} are used to construct ROM on the fly or dump the ROM into a file
(i.e. pickled ROM), respectively.
\xmlExample{framework/user_guide/ravenTutorial/RomTrain.xml}{Steps}
The \xmlString{HistorySet} generated by the \textbf{``sample''} step is used as input of the \textbf{``trainROM''}
step. The output of the \textbf{``trainROM''} is ``rom'' which is predefined in \xmlNode{ROM}. If a \xmlString{PointSet}
is provided as input, the output ``rom'' will be time-independent. The \textbf{``dumpROM''} step is used to serialize
the ``rom'' to file (pickled). In this example, the file is identified in \xmlNode{Files}.
\xmlExample{framework/user_guide/ravenTutorial/RomTrain.xml}{Files}
A pickled file with name ``inverseRom.pk'' will be generated in the working directory. This pickled ROM can be
reused by RAVEN to perform additional analysis, and we will introduce this capability in the following section.
Since we have four different steps to execute, the \xmlNode{RunInfo} block is modified:
\xmlExample{framework/user_guide/ravenTutorial/RomTrain.xml}{RunInfo}
The \xmlNode{Sequence} is used to provide an ordered list of the step names that RAVEN will run.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Dump and sample the rom
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{How to load and sample a ROM?}
In previous section, we have shown that RAVEN can be used to train a ROM and output the ROM to a pickled file. In
this section, we will show the user how to load the pickled ROM, and how to reuse it inside RAVEN environment.
In general, a \xmlNode{ROM} with subtype \xmlString{pickledROM} is used to hold the place of the ROM that will be
loaded from file. The notation for this ROM is much less than a typical ROM; it only requires a name and its subtype.

\textbf{Example:}
For this example the ROM has already been created and trained in another RAVEN run, then pickled to a file
called \texttt{rom\_pickle.pk}.  In the example, the file is identified in \xmlNode{Files}, the model is
defined in \xmlNode{Models}, and the model loaded in \xmlNode{Steps}.
{\footnotesize
\begin{lstlisting}[style=XML,morekeywords={name,subType}]
<Simulation>
  ...
  <Files>
    <Input name="rompk" type="">rom_pickle.pk</Input>
  </Files>
  ...
  <Models>
    ...
    <ROM name="myRom" subType="pickledROM"/>
    ...
  </Models>
  ...
  <Steps>
    ...
    <IOStep name="loadROM">
      <Input class="Files" type="">rompk</Input>
      <Output class="Models" type="ROM">myRom</Output>
    </IOStep>
    ...
  </Steps>
  ...
</Simulation>
\end{lstlisting}
}

\nb When loading ROMs from file, RAVEN will not perform any checks on the expected inputs or outputs of a ROM;
it is expected that a user knows at least the I/O of a ROM before trying to use it as a model. However, RAVEN
does require that pickled ROMs be trained before pickling in the first place.

Initially, a pickled ROM is not usable. It can not be trained or sampled; attempting to do so will raise an error.
An \xmlNode{IOStep} is used to load the ROM from file, at which point the ROM will have all the same characteristics
as when it was pickled in a previous RAVEN run. Take \textbf{AnalyticBateman} for example, the pickled ROM
``inverseRom.pk'' is generated in previous section and copied to the \textit{commonFiles} folder, RAVEN use the
\textbf{Files} object to track the pickled ROM file.
\xmlExample{framework/user_guide/ravenTutorial/RomLoad.xml}{Files}

In this example, the subtype \xmlString{pickledROM} of \xmlNode{ROM} is used  since the hyper-parameters of the ROM can not be changed once the ROM is loaded from a pickled (serialized) file.
\xmlExample{framework/user_guide/ravenTutorial/RomLoad.xml}{Models}

Two data objects are defined: 1) a \textbf{HistorySet} named ``inputPlaceHolder'' used as a placeholder input for
the ROM sampling step, 2) a \textbf{HistorySet} named ``histories'' used to store the ROM responses from Monte
Carlo samples.
\xmlExample{framework/user_guide/ravenTutorial/RomLoad.xml}{DataObjects}
\nb In this example, a time-dependent ROM trained in previous case is used here. \xmlString{time} is identified as
\textbf{Output}. The sub-node \xmlNode{pivotParameter} can be used to define the pivot variable (e.g. time) that
is non-decreasing in the input HistorySet.

As mentioned before, the \xmlNode{IOStep} is used to load the pickled ROM. In addition, the \xmlNode{MultiRun} is
used to sample the ROM using Monte Carlo method. Another \xmlNode{IOStep} is used to output the responses of ROM
into a CSV file. Figure~\ref{fig:historiesROMPlotLine_A} shows the different evolutions of the variable $A$ for
all 10 samples.
\xmlExample{framework/user_guide/ravenTutorial/RomLoad.xml}{Steps}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%figure histories
\begin{figure}[h!]
  \centering
  \includegraphics[scale=0.7]{../../tests/framework/user_guide/ravenTutorial/gold/ROMLoad/1-historyROMPlot_line.png}
  \caption{Plot of the histories generated by the Monte Carlo sampling of pickled ROM for variable $A$ (10 samples).}
  \label{fig:historiesROMPlotLine_A}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Finally, ROMs are generally not constructed for all possible inputs, geometries or representing all outputs. However,
it is possible to build a ROM of faster solution with respect to the original set. The accuracy in the prediction
can be obtained by further training. Figure~\ref{fig:romConstruction} shows the general workflow for ROM construction.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%figure rom construction
\begin{figure}[h!]
  \centering
  \includegraphics[scale=0.7]{./pics/romConstruction.png}
  \caption{Workflow for ROM construction}
  \label{fig:romConstruction}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\clearpage


text:
package de.bitbrain.jpersis;

import de.bitbrain.jpersis.util.PropertiesCache;

/**
 * Manages features for jpersis internally. This class is marked as package private for internal usage only.
 *
 * @author Miguel Gonzalez Sanchez
 * @since 1.0
 * @version 1.0
 */
public class Features {

  static final String FILE = "features";

  private PropertiesCache cache;

  Features() {
    cache = new PropertiesCache("features");
  }

  boolean isEnabled(Feature feature) {
    String val = cache.getProperty(feature.name().toLowerCase(), "false");
    return val.equals("true");
  }

  public enum Feature {
    MYSQL,
    POSTGRESQL;
  }
}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Bundle\ThemeBundle\Context;

use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ThemeBundle\Context\ThemeContextInterface;

final class EmptyThemeContextSpec extends ObjectBehavior
{
    function it_implements_theme_context_interface(): void
    {
        $this->shouldImplement(ThemeContextInterface::class);
    }

    function it_always_returns_null(): void
    {
        $this->getTheme()->shouldReturn(null);
    }
}


text:
package com.helpplusapp.amit.helpplus.widget;

import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.widget.RemoteViewsService;

/**
 * Created by amit on 8/9/2016.
 */
public class WidgetService extends RemoteViewsService {
/*
* So pretty simple just defining the Adapter of the listview
* here Adapter is ListProvider
* */

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        int appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        return (new ListProvider(this.getApplicationContext(), intent));
    }

}


text:
export { treeCorrectedForClockSkew } from './clock-skew';
export { getServiceName } from './span-row';
export { traceSummary, traceSummaries, detailedTraceSummary } from './trace';


text:
package dbr

import (
	"database/sql"
	"fmt"
	"time"

	"github.com/corestoreio/csfw/util/bufferpool"
)

// DeleteBuilder contains the clauses for a DELETE statement
type DeleteBuilder struct {
	*Session
	runner

	From           alias
	WhereFragments []*whereFragment
	OrderBys       []string
	LimitCount     uint64
	LimitValid     bool
	OffsetCount    uint64
	OffsetValid    bool
}

var _ queryBuilder = (*DeleteBuilder)(nil)

// DeleteFrom creates a new DeleteBuilder for the given table
func (sess *Session) DeleteFrom(from ...string) *DeleteBuilder {
	return &DeleteBuilder{
		Session: sess,
		runner:  sess.cxn.DB,
		From:    newAlias(from...),
	}
}

// DeleteFrom creates a new DeleteBuilder for the given table
// in the context for a transaction
func (tx *Tx) DeleteFrom(from ...string) *DeleteBuilder {
	return &DeleteBuilder{
		Session: tx.Session,
		runner:  tx.Tx,
		From:    newAlias(from...),
	}
}

// Where appends a WHERE clause to the statement whereSqlOrMap can be a
// string or map. If it's a string, args wil replaces any places holders
func (b *DeleteBuilder) Where(args ...ConditionArg) *DeleteBuilder {
	b.WhereFragments = append(b.WhereFragments, newWhereFragments(args...)...)
	return b
}

// OrderBy appends an ORDER BY clause to the statement
func (b *DeleteBuilder) OrderBy(ord string) *DeleteBuilder {
	b.OrderBys = append(b.OrderBys, ord)
	return b
}

// OrderDir appends an ORDER BY clause with a direction to the statement
func (b *DeleteBuilder) OrderDir(ord string, isAsc bool) *DeleteBuilder {
	if isAsc {
		b.OrderBys = append(b.OrderBys, ord+" ASC")
	} else {
		b.OrderBys = append(b.OrderBys, ord+" DESC")
	}
	return b
}

// Limit sets a LIMIT clause for the statement; overrides any existing LIMIT
func (b *DeleteBuilder) Limit(limit uint64) *DeleteBuilder {
	b.LimitCount = limit
	b.LimitValid = true
	return b
}

// Offset sets an OFFSET clause for the statement; overrides any existing OFFSET
func (b *DeleteBuilder) Offset(offset uint64) *DeleteBuilder {
	b.OffsetCount = offset
	b.OffsetValid = true
	return b
}

// ToSql serialized the DeleteBuilder to a SQL string
// It returns the string with placeholders and a slice of query arguments
func (b *DeleteBuilder) ToSql() (string, []interface{}, error) {
	if len(b.From.Expression) == 0 {
		return "", nil, ErrMissingTable
	}

	var sql = bufferpool.Get()
	defer bufferpool.Put(sql)
	var args []interface{}

	sql.WriteString("DELETE FROM ")
	sql.WriteString(b.From.QuoteAs())

	// Write WHERE clause if we have any fragments
	if len(b.WhereFragments) > 0 {
		sql.WriteString(" WHERE ")
		writeWhereFragmentsToSql(b.WhereFragments, sql, &args)
	}

	// Ordering and limiting
	if len(b.OrderBys) > 0 {
		sql.WriteString(" ORDER BY ")
		for i, s := range b.OrderBys {
			if i > 0 {
				sql.WriteString(", ")
			}
			sql.WriteString(s)
		}
	}

	if b.LimitValid {
		sql.WriteString(" LIMIT ")
		fmt.Fprint(sql, b.LimitCount)
	}

	if b.OffsetValid {
		sql.WriteString(" OFFSET ")
		fmt.Fprint(sql, b.OffsetCount)
	}
	return sql.String(), args, nil
}

// Exec executes the statement represented by the DeleteBuilder
// It returns the raw database/sql Result and an error if there was one
func (b *DeleteBuilder) Exec() (sql.Result, error) {
	sql, args, err := b.ToSql()
	if err != nil {
		return nil, b.EventErrKv("dbr.delete.exec.tosql", err, nil)
	}

	fullSql, err := Preprocess(sql, args)
	if err != nil {
		return nil, b.EventErrKv("dbr.delete.exec.interpolate", err, kvs{"sql": fullSql})
	}

	// Start the timer:
	startTime := time.Now()
	defer func() { b.TimingKv("dbr.delete", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()

	result, err := b.runner.Exec(fullSql)
	if err != nil {
		return result, b.EventErrKv("dbr.delete.exec.exec", err, kvs{"sql": fullSql})
	}

	return result, nil
}