text:
<?php

namespace Drupal\views\Plugin\views\argument_validator;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Drupal\views\Plugin\views\PluginBase;

/**
 * @defgroup views_argument_validate_plugins Views argument validate plugins
 * @{
 * Plugins for validating views contextual filters.
 *
 * Views argument validator plugins validate arguments (contextual filters) on
 * views. They can ensure arguments are valid, and even do transformations on
 * the arguments. They can also provide replacement patterns for the view title.
 * For example, the 'content' validator verifies verifies that the argument
 * value corresponds to a node, loads that node, and provides the node title
 * as a replacement pattern for the view title.
 *
 * Argument validator plugins extend
 * \Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase.
 * They must be annotated with
 * \Drupal\views\Annotation\ViewsArgumentValidator annotation, and they
 * must be in namespace directory Plugin\views\argument_validator.
 *
 * @ingroup views_plugins
 * @see plugin_api
 */

/**
 * Base argument validator plugin to provide basic functionality.
 */
abstract class ArgumentValidatorPluginBase extends PluginBase {

  /**
   * The argument handler instance associated with this plugin.
   *
   * @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase
   */
  protected $argument;

  /**
   * Sets the parent argument this plugin is associated with.
   *
   * @param \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument
   *   The parent argument to set.
   */
  public function setArgument(ArgumentPluginBase $argument) {
    $this->argument = $argument;
  }

  /**
   * Retrieves the options when this is a new access control plugin.
   */
  protected function defineOptions() {
    return [];
  }

  /**
   * Provides the default form for setting options.
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {}

  /**
   * Provides the default form for validating options.
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {}

  /**
   * Provides the default form for submitting options.
   */
  public function submitOptionsForm(&$form, FormStateInterface $form_state, &$options = []) {}

  /**
   * Determines if the administrator has the privileges to use this plugin.
   */
  public function access() {
    return TRUE;
  }

  /**
   * Blocks user input when the form is shown but we don´t have access.
   *
   * This is only called by child objects if specified in the buildOptionsForm(),
   * so it will not always be used.
   */
  protected function checkAccess(&$form, $option_name) {
    if (!$this->access()) {
      $form[$option_name]['#disabled'] = TRUE;
      $form[$option_name]['#value'] = $form[$this->option_name]['#default_value'];
      $form[$option_name]['#description'] .= ' <strong>' . $this->t('Note: you do not have permission to modify this. If you change the default filter type, this setting will be lost and you will NOT be able to get it back.') . '</strong>';
    }
  }

  /**
   * Performs validation for a given argument.
   */
  public function validateArgument($arg) {
    return TRUE;
  }

  /**
   * Processes the summary arguments for displaying.
   *
   * Some plugins alter the argument so it uses something else internally.
   * For example the user validation set's the argument to the uid,
   * for a faster query. But there are use cases where you want to use
   * the old value again, for example the summary.
   */
  public function processSummaryArguments(&$args) {}

  /**
   * Returns a context definition for this argument.
   *
   * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null
   *   A context definition that represents the argument or NULL if that is
   *   not possible.
   */
  public function getContextDefinition() {}

}

/**
 * @}
 */


text:
package org.knowm.xchange.dragonex.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

public class CoinWithdrawHistory {

  private final List<CoinWithdraw> list;
  private final long total;

  public CoinWithdrawHistory(
      @JsonProperty("list") List<CoinWithdraw> list, @JsonProperty("total") long total) {
    this.list = list;
    this.total = total;
  }

  public List<CoinWithdraw> getList() {
    return list;
  }

  public long getTotal() {
    return total;
  }

  @Override
  public String toString() {
    return "CoinWithdrawHistory ["
        + (list != null ? "list=" + list + ", " : "")
        + "total="
        + total
        + "]";
  }
}

redpajama_set_name: RedPajamaGithub


text:
from mlflow.entities._mlflow_object import _MLflowObject
from mlflow.protos.service_pb2 import RunTag as ProtoRunTag

class RunTag(_MLflowObject):
    """Tag object associated with a run."""

    def __init__(self, key, value):
        self._key = key
        self._value = value

    def __eq__(self, other):
        if type(other) is type(self):
            # TODO deep equality here?
            return self.__dict__ == other.__dict__
        return False

    @property
    def key(self):
        """String name of the tag."""
        return self._key

    @property
    def value(self):
        """String value of the tag."""
        return self._value

    def to_proto(self):
        param = ProtoRunTag()
        param.key = self.key
        param.value = self.value
        return param

    @classmethod
    def from_proto(cls, proto):
        return cls(proto.key, proto.value)


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.model.util;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl;

/**
 * <!-- begin-user-doc -->
 * The <b>Resource </b> associated with the package.
 * <!-- end-user-doc -->
 * @see com.archimatetool.model.util.ArchimateResourceFactory
 * @generated
 */
public class ArchimateResource extends XMLResourceImpl {
    /**
     * Creates an instance of the resource.
     * <!-- begin-user-doc -->
     * <!-- end-user-doc -->
     * @param uri the URI of the new resource.
     * @generated
     */
    public ArchimateResource(URI uri) {
        super(uri);
    }

} //ArchimateResource


text:
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = 'taxcalc/_version.py'
versioneer.versionfile_build = 'taxcalc/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'taxcalc-' # dirname like 'taxcalc-1.2.0'

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('README.md') as f:
        longdesc = f.read()

version = versioneer.get_version()
cmdclass = versioneer.get_cmdclass()

config = {
    'description': 'Tax Calculator',
    'url': 'https://github.com/OpenSourcePolicyCenter/Tax-Calculator',
    'download_url': 'https://github.com/OpenSourcePolicyCenter/Tax-Calculator',
    'description':'taxcalc',
    'long_description':longdesc,
    'install_requires': ["pandas", "numpy"],
    'version': version,
    'cmdclass': cmdclass,
    'license': 'MIT',
    'packages': ['taxcalc'],
    'include_package_data': True,
    'name': 'taxcalc',
    'install_requires': ['numpy', 'pandas'],
    'classifiers': [
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules'],
    'tests_require': ['pytest']
}

setup(**config)


text:
using SADFM.Application.Repositories;
using SADFM.Data;
using SADFM.Infrastructure.Repositories;
using SADFM.Infrastructure.Services;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SADFM.Infrastructure.Models;

namespace SADFM.Application.Services
{
    public class ReportService : IReportService
    {

        private IReportRepository reportRepository { get; set; }
        private IFacilityRepository facilityRepository { get; set; }

        public ReportService()
        {
           this.reportRepository = new ReportRepository();
           this.facilityRepository = new FacilityRepository();
        }

        public List<SADFM.Infrastructure.Models.PatientSummary> GetPatientSummaryReport(Guid ScaleId, DateTime startDate, DateTime endDate, Guid? ProviderId = null)
        {
            return this.reportRepository.GetPatientSummaryReport(ScaleId, startDate, endDate, ProviderId);
        }

        public DataTable FacilityPerformanceReport(Guid ScaleId, DateTime StartDate, DateTime EndDate, Guid[] MedicalSchemeIds, Guid ProviderId)
        {

            string scaleName = DataAccess.ListItem.GetById(ScaleId).Name;

            string providerName = DataAccess.Provider.GetById(ProviderId).Name;

            var result = this.reportRepository.GetPatientSummaryReportCollapsed(ScaleId, StartDate, EndDate, ProviderId, MedicalSchemeIds == null ? null : MedicalSchemeIds.ToList());

            DataTable dataTable = new DataTable();

            for (int i = 0; i < 20; i++)
            {
                dataTable.Columns.Add("");
            }

            dataTable.Rows.Add("Facility Performance Report");
            dataTable.Rows.Add(providerName);
            dataTable.Rows.Add(string.Format("{0} - {1}", StartDate.ToString("dd MMMM yyyy"), EndDate.ToString("dd MMMM yyyy")));
            dataTable.Rows.Add(string.Format("Number of patients: {0}", result.Count > 0 ? result.FirstOrDefault().Value.TotalPatients : 0));
            dataTable.Rows.Add(scaleName);
            dataTable.Rows.Add("");
            dataTable.Rows.Add("Impairment Group", "Number of pts", "% of Total", "Age", "Onset days", "Admission Score", "Discharge Score", "Gain", "LOS(days)", "Efficiency");
            dataTable.Rows.Add("");

            for (int i = 0; i < result.Keys.Count; i++)
            {

                Guid id = result.Keys.ElementAt(i);
                dataTable.Rows.Add(result[id].ImpairmentGroup, result[id].NumberOfPatients, Math.Round(result[id].PercentageOfPatients, 1), Math.Round(result[id].Age, 1), Math.Round(result[id].OnsetDays, 1), result[id].AverageAdmitScore, result[id].AverageDischargeScore, result[id].Delta, Math.Round(result[id].AverageLOS, 1), Math.Round(result[id].Effiency, 1));

            }

            return dataTable;

        }

        public DataTable FacilityVolumeReport(Guid facilityId, DateTime startDate, DateTime endDate)
        {
            var result = this.reportRepository.GetFacilityVolumeReport(facilityId, startDate, endDate);

            Data.Models.Provider facility = this.facilityRepository.GetDetails(facilityId);

            DataTable dataTable = new DataTable();

            for (int i = 0; i < 20; i++)
            {
                dataTable.Columns.Add("");
            }

            dataTable.Rows.Add("Facility Volume Report");

            dataTable.Rows.Add("");

            dataTable.Rows.Add(facility.Name);

            dataTable.Rows.Add("");

            dataTable.Rows.Add(string.Format("{0} - {1}", startDate.ToString("dd MMMM yyyy"), endDate.ToString("dd MMMM yyyy")));

            dataTable.Rows.Add(string.Format("Number of patients: {0}", result.Count > 0 ? result.Sum(x => x.Patients) : 0));

            dataTable.Rows.Add("");

            dataTable.Rows.Add("Impairment Group", "Admission", "Percentage", "Average LOS", "Average Onset Days", "Average Age On Admission");

            foreach (var entry in result)
            {

                dataTable.Rows.Add(entry.ImpairmentGroup, entry.Admission, entry.Percentage.ToString("0.00"), entry.AverageLOS, entry.AverageOnsetDays, entry.AverageAgeOnAdmission);
            }

            return dataTable;
        }

        public FacilityDashboardReport FacilityDashboardReport(Guid facilityId, DateTime startDate, DateTime endDate)
        {

            var facility = this.facilityRepository.GetDetails(facilityId);

            var result = this.reportRepository.GetFacilityDashboardReport(facilityId, startDate, endDate);

            return new Infrastructure.Models.FacilityDashboardReport()
            {
                FacilityName = facility.Name,
                ActivePatients = result.Select(x => x.PatientId).Distinct().Count(),
                Admitted = result.Where(x => x.AdmissionDate >= startDate && x.AdmissionDate <= endDate).Select(x => x.PatientId).Distinct().Count(),
                Discharged = result.Where(x => x.DischargeDate.HasValue).Select(x => x.PatientId).Distinct().Count(),
                Age11To20 = result.Where(x => x.Age >= 11 && x.Age <= 20).Select(x => x.PatientId).Distinct().Count(),
                Age1To10 = result.Where(x => x.Age >= 1 && x.Age <= 10).Select(x => x.PatientId).Distinct().Count(),
                Age21To30 = result.Where(x => x.Age >= 21 && x.Age <= 30).Select(x => x.PatientId).Distinct().Count(),
                Age31To40 = result.Where(x => x.Age >= 31 && x.Age <= 40).Select(x => x.PatientId).Distinct().Count(),
                Age41To50 = result.Where(x => x.Age >= 41 && x.Age <= 50).Select(x => x.PatientId).Distinct().Count(),
                Age51To60 = result.Where(x => x.Age >= 51 && x.Age <= 60).Select(x => x.PatientId).Distinct().Count(),
                Age61To70 = result.Where(x => x.Age >= 61 && x.Age <= 70).Select(x => x.PatientId).Distinct().Count(),
                Age71To80 = result.Where(x => x.Age >= 71 && x.Age <= 80).Select(x => x.PatientId).Distinct().Count(),
                Age81AndOlder = result.Where(x => x.Age >= 81).Select(x => x.PatientId).Distinct().Count(),
                Asian = result.Where(x => x.Race == "Asian").Select(x => x.PatientId).Distinct().Count(),
                Black = result.Where(x => x.Race == "Black").Select(x => x.PatientId).Distinct().Count(),
                Coloured = result.Where(x => x.Race == "Coloured").Select(x => x.PatientId).Distinct().Count(),
                White = result.Where(x => x.Race == "White").Select(x => x.PatientId).Distinct().Count(),
                Other = result.Where(x => x.Race == "Other").Select(x => x.PatientId).Distinct().Count(),
                Deaths = result.Where(x => x.ImpairmentGroup == "Death").Select(x => x.PatientId).Distinct().Count(),
                EndDate = endDate,
                StartDate = startDate,
                Males = result.Where(x => x.Gender == "Male").Select(x => x.PatientId).Distinct().Count(),
                Females = result.Where(x => x.Gender == "Female").Select(x => x.PatientId).Distinct().Count(),
                AverageAge = result.GroupBy(x => x.PatientId).Select(x => x.FirstOrDefault()).Sum(x => x.Age) / result.GroupBy(x => x.PatientId).Select(x => x.FirstOrDefault()).Count(),
                AverageLOS = result.Where(x => x.DischargeDate.HasValue).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue).Select(x => x.PatientId).Distinct().Count(),
                AverageLOSWeek1 = result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate && x.DischargeDate <= startDate.AddDays(7)).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate && x.DischargeDate <= startDate.AddDays(7)).Select(x => x.PatientId).Distinct().Count(),
                AverageLOSWeek2 = result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(8) && x.DischargeDate <= startDate.AddDays(14)).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(7) && x.DischargeDate <= startDate.AddDays(14)).Select(x => x.PatientId).Distinct().Count(),
                AverageLOSWeek3 = result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(15) && x.DischargeDate <= startDate.AddDays(21)).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(14) && x.DischargeDate <= startDate.AddDays(21)).Select(x => x.PatientId).Distinct().Count(),
                AverageLOSWeek4 = result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(22) && x.DischargeDate <= startDate.AddDays(28)).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(21) && x.DischargeDate <= startDate.AddDays(30)).Select(x => x.PatientId).Distinct().Count(),
                FacilityImage = facility.ProfileImage,
                AverageLOSMoreThanAMonth = result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(29)).GroupBy(x => x.PatientId).Select(x => x.Max(y => y.DischargeDate).Value.Subtract(x.Min(y => y.AdmissionDate)).TotalDays).Sum() / result.Where(x => x.DischargeDate.HasValue && x.DischargeDate >= startDate.AddDays(29)).Select(x => x.PatientId).Distinct().Count(),
            };
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>

楼数据 -
                    添加

                        <button type="button" class="btn btn-primary" id="page_back">返回</button>

                <form role="form" id="add_form">

                        <select class="form-control" name="schoolId" id="select_school">
                            <option>请选择学校</option>
                        </select>

                        <select class="form-control" name="collegeId" id="select_college">
                            <option>请选择院</option>
                        </select>

                        楼
                        <input class="form-control" name="buildingName" id="buildingName" maxlength="30" placeholder="楼名"/>

                        状态

                                <input type="checkbox" name="buildingIsDel" value="1"/>注销

                        <button type="button" id="save" class="btn btn-default">保存</button>
                        <button type="reset" class="btn btn-default">重置</button>

                </form>

© Company 2016

        <input type="hidden" class="dy_script" value="/js/data/building/building_add.js"/>


text:
var path = require('path');
var visitasprincipio;
var url = process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/);
var DB_name = (url[6]||null);
var user = (url[2]||null);
var pwd = (url[3]||null);
var protocol  = (url[1]||null);
var dialect  = (url[1]||null);
var port  = (url[5]||null);
var host  = (url[4]||null);
var storage  = process.env.DATABASE_STORAGE;

var Sequelize = require('sequelize');
var sequelize = new Sequelize(DB_name,user,pwd,
	{ dialect:protocol,
		protocol:protocol,
		port:port,
		host:host,
		storage:storage,
		omitNull:true
	});

//Importar definición de la tabla Quiz
var quiz_path = path.join(__dirname,'quiz');
var Quiz = sequelize.import(quiz_path);

//Importar definición de la tabla Comment
var comment_path= path.join(__dirname, 'comment');
var Comment = sequelize.import(comment_path);

//Importar definición de la tabla de usuarios
var user_path = path.join(__dirname, 'user');
var User = sequelize.import(user_path);

//Importar definición de la tabla de visitas
var cont_path = path.join(__dirname, 'contador');
var Contador = sequelize.import(cont_path);

//los quizes pertenecen a un usuario registrado
Quiz.belongsTo(User);
User.hasMany(Quiz);
User.belongsToMany(Quiz, {through: 'Favourites', as:"Favourites" });
Quiz.belongsToMany(User, {through: 'Favourites', as: "Fans" });
User.belongsToMany(Quiz, {through: 'Points', as:"Ganados" });
Quiz.belongsToMany(User, {through: 'Points', as:"Participants" });
Comment.belongsTo(Quiz);
Quiz.hasMany(Comment);
// exportar tablas
exports.Quiz = Quiz;
exports.Comment = Comment;
exports.User = User;
exports.Contador = Contador;

sequelize.sync().then(function(){
	Contador.count().then(function(count){
		visitasprincipio = count || 0;
		exports.visitasprincipio = visitasprincipio;
	}).then(function(){

	User.count().then(function(count){//////})
	if(count===0){console.log('aqui');
	User.bulkCreate(
		[ {username: 'admin', password:'1234', isAdmin: true, image: 'kudb5ucvig8c7xypfh6w'},
		{username: 'sonsoleslp', password:'5678', description: ' Sonsoles López Pernas. 21 años.', image: 'sonso_tcivhx'}
		]

		).then(function(){

			console.log('Base de datos(tabla user) inicializada');
			Quiz.count().then(function(count){
				if(count === 0) {
					Quiz.bulkCreate(
						[{pregunta:'Capital de Italia',	respuesta:'Roma', UserId:2, image: 'ITALIA_pim7i8'},
						{pregunta:'Capital de Portugal',respuesta:'Lisboa', UserId:2, image: 'PORTUGAL_ptlqvv'},
						{pregunta:'Capital de España',	respuesta:'Madrid', UserId:2, image: 'SPAIN_itmfvc'}
						]
						).then(function(){console.log('Base de datos (tabla quiz) inicializada')

					});
					};
				});
		});
	};
});
})
});


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//Path from application Base to directory where files of customers will be stored
$config['customerfiles']= 'customerfiles';


text:
package controller

import (
	ficV1 "github.com/F5Networks/f5-ipam-controller/pkg/ipamapis/apis/fic/v1"
	cisapiv1 "github.com/F5Networks/k8s-bigip-ctlr/config/apis/cis/v1"
	crdfake "github.com/F5Networks/k8s-bigip-ctlr/config/client/clientset/versioned/fake"
	"github.com/F5Networks/k8s-bigip-ctlr/pkg/test"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	routeapi "github.com/openshift/api/route/v1"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	k8sfake "k8s.io/client-go/kubernetes/fake"
	"k8s.io/client-go/util/workqueue"
)

var _ = Describe("Informers Tests", func() {
	var mockCtlr *mockController
	namespace := "default"

	BeforeEach(func() {
		mockCtlr = newMockController()
	})

	Describe("Custom Resource Informers", func() {
		BeforeEach(func() {
			mockCtlr.mode = CustomResourceMode
			mockCtlr.namespaces = make(map[string]bool)
			mockCtlr.namespaces["default"] = true
			mockCtlr.kubeCRClient = crdfake.NewSimpleClientset()
			mockCtlr.kubeClient = k8sfake.NewSimpleClientset()
			mockCtlr.crInformers = make(map[string]*CRInformer)
			mockCtlr.nsInformers = make(map[string]*NSInformer)
			mockCtlr.comInformers = make(map[string]*CommonInformer)
			mockCtlr.customResourceSelector, _ = createLabelSelector(DefaultCustomResourceLabel)
		})
		It("Resource Informers", func() {
			err := mockCtlr.addNamespacedInformers(namespace, false)
			Expect(err).To(BeNil(), "Informers Creation Failed")

			crInf, found := mockCtlr.getNamespacedCRInformer(namespace)
			Expect(crInf).ToNot(BeNil(), "Finding Informer Failed")
			Expect(found).To(BeTrue(), "Finding Informer Failed")
		})

		It("Namespace Informer", func() {
			namespaceSelector, err := createLabelSelector("app=test")
			Expect(namespaceSelector).ToNot(BeNil(), "Failed to Create Label Selector")
			Expect(err).To(BeNil(), "Failed to Create Label Selector")
			err = mockCtlr.createNamespaceLabeledInformer("app=test")
			Expect(err).To(BeNil(), "Failed to Create Namespace Informer")
		})
	})

	Describe("Custom Resource Queueing", func() {
		BeforeEach(func() {
			mockCtlr.mode = CustomResourceMode
			mockCtlr.resourceQueue = workqueue.NewNamedRateLimitingQueue(
				workqueue.DefaultControllerRateLimiter(), "custom-resource-controller")

		})
		AfterEach(func() {
			mockCtlr.resourceQueue.ShutDown()
		})
		It("VirtualServer", func() {
			vs := test.NewVirtualServer(
				"SampleVS",
				namespace,
				cisapiv1.VirtualServerSpec{
					Host:                 "test.com",
					VirtualServerAddress: "1.2.3.4",
				})
			mockCtlr.enqueueVirtualServer(vs)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue New VS  Failed")

			newVS := test.NewVirtualServer(
				"SampleVS",
				namespace,
				cisapiv1.VirtualServerSpec{
					Host:                 "test.com",
					VirtualServerAddress: "1.2.3.5",
				})
			mockCtlr.enqueueUpdatedVirtualServer(vs, newVS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated VS  Failed")
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated VS  Failed")

			mockCtlr.enqueueDeletedVirtualServer(newVS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted VS  Failed")

			// Check if correct event in set while enqueuing vs
			// Create updated VS CR
			updatedVS1 := test.NewVirtualServer(
				"SampleVS",
				namespace,
				cisapiv1.VirtualServerSpec{
					Host:                 "test.com",
					VirtualServerAddress: "1.2.3.5",
					SNAT:                 "none",
				})
			mockCtlr.enqueueUpdatedVirtualServer(newVS, updatedVS1)
			// With a change of snat in VS CR, an update event should be enqueued
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated VS  Failed")
			rKey := key.(*rqKey)
			Expect(rKey).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(rKey.event).To(Equal(Update), "Incorrect event set")

			// When VirtualServerAddress is updated then it should enqueue both delete & create events
			updatedVS2 := test.NewVirtualServer(
				"SampleVS",
				namespace,
				cisapiv1.VirtualServerSpec{
					Host:                 "test.com",
					VirtualServerAddress: "5.6.7.8",
					SNAT:                 "none",
				})
			mockCtlr.enqueueUpdatedVirtualServer(updatedVS1, updatedVS2)
			key, quit = mockCtlr.resourceQueue.Get()
			// Delete event
			Expect(key).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated VS  Failed")
			rKey = key.(*rqKey)
			Expect(rKey).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(rKey.event).To(Equal(Delete), "Incorrect event set")
			// Create event
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated VS  Failed")
			rKey = key.(*rqKey)
			Expect(rKey).ToNot(BeNil(), "Enqueue Updated VS Failed")
			Expect(rKey.event).To(Equal(Create), "Incorrect event set")

		})

		It("TLS Profile", func() {
			tlsp := test.NewTLSProfile(
				"SampleTLS",
				namespace,
				cisapiv1.TLSProfileSpec{
					Hosts: []string{"test.com", "prod.com"},
					TLS: cisapiv1.TLS{
						Termination: "edge",
						ClientSSL:   "2359qhfniqlur89phuf;rhfi",
					},
				})
			mockCtlr.enqueueTLSProfile(tlsp, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue TLS Failed")
			Expect(quit).To(BeFalse(), "Enqueue TLS  Failed")
		})

		It("TransportServer", func() {
			ts := test.NewTransportServer(
				"SampleTS",
				namespace,
				cisapiv1.TransportServerSpec{
					SNAT:                 "auto",
					VirtualServerAddress: "1.2.3.4",
				})
			mockCtlr.enqueueTransportServer(ts)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New TS Failed")
			Expect(quit).To(BeFalse(), "Enqueue New TS  Failed")

			newTS := test.NewTransportServer(
				"SampleTS",
				namespace,
				cisapiv1.TransportServerSpec{
					SNAT:                 "auto",
					VirtualServerAddress: "1.2.3.5",
				})
			mockCtlr.enqueueUpdatedTransportServer(ts, newTS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated TS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated TS  Failed")
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated TS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated TS  Failed")

			mockCtlr.enqueueDeletedTransportServer(newTS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted TS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted TS  Failed")
		})

		It("IngressLink", func() {
			label1 := make(map[string]string)
			label1["app"] = "ingresslink"

			selctor := &metav1.LabelSelector{
				MatchLabels: label1,
			}

			iRules := []string{"dummyiRule"}
			il := test.NewIngressLink(
				"SampleIL",
				namespace,
				"1",
				cisapiv1.IngressLinkSpec{
					VirtualServerAddress: "1.2.3.4",
					Selector:             selctor,
					IRules:               iRules,
				},
			)
			mockCtlr.enqueueIngressLink(il)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New IL Failed")
			Expect(quit).To(BeFalse(), "Enqueue New IL  Failed")

			newIL := test.NewIngressLink(
				"SampleIL",
				namespace,
				"1",
				cisapiv1.IngressLinkSpec{
					VirtualServerAddress: "1.2.3.5",
					Selector:             selctor,
					IRules:               iRules,
				},
			)
			mockCtlr.enqueueUpdatedIngressLink(il, newIL)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated IL Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated IL  Failed")
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated IL Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated IL  Failed")

			mockCtlr.enqueueDeletedIngressLink(newIL)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted IL Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted IL  Failed")
		})

		It("ExternalDNS", func() {
			edns := test.NewExternalDNS(
				"SampleEDNS",
				namespace,
				cisapiv1.ExternalDNSSpec{
					DomainName:        "test.com",
					LoadBalanceMethod: "round-robin",
				})
			mockCtlr.enqueueExternalDNS(edns)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New EDNS Failed")
			Expect(quit).To(BeFalse(), "Enqueue New EDNS  Failed")

			newEDNS := test.NewExternalDNS(
				"SampleEDNS",
				namespace,
				cisapiv1.ExternalDNSSpec{
					DomainName:        "prod.com",
					LoadBalanceMethod: "round-robin",
				})
			mockCtlr.enqueueUpdatedExternalDNS(edns, newEDNS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated EDNS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated EDNS  Failed")
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated EDNS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated EDNS  Failed")

			mockCtlr.enqueueDeletedExternalDNS(newEDNS)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted EDNS Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted EDNS  Failed")
		})

		It("Policy", func() {
			plc := test.NewPolicy(
				"SamplePolicy",
				namespace,
				cisapiv1.PolicySpec{})
			mockCtlr.enqueuePolicy(plc, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Policy Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Policy  Failed")

			newPlc := test.NewPolicy(
				"SamplePolicy2",
				namespace,
				cisapiv1.PolicySpec{})
			mockCtlr.enqueueDeletedPolicy(newPlc)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated Policy Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated Policy  Failed")
		})

		It("Service", func() {
			svc := test.NewService(
				"SampleSVC",
				"1",
				namespace,
				v1.ServiceTypeLoadBalancer,
				nil,
			)
			mockCtlr.enqueueService(svc)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Service Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Service  Failed")

			newSVC := test.NewService(
				"SampleSVC",
				"2",
				namespace,
				v1.ServiceTypeNodePort,
				nil,
			)
			mockCtlr.enqueueUpdatedService(svc, newSVC)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated Service Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated Service  Failed")
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated Service Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated Service  Failed")

			mockCtlr.enqueueDeletedService(newSVC)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted Service Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted Service  Failed")
		})

		It("Endpoints", func() {
			eps := test.NewEndpoints(
				"SampleSVC",
				"1",
				"worker1",
				namespace,
				[]string{"10.20.30.40"},
				nil,
				[]v1.EndpointPort{
					{
						Name: "port1",
						Port: 80,
					},
				},
			)
			mockCtlr.enqueueEndpoints(eps, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Endpoints Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Endpoints  Failed")
		})

		It("Pod", func() {
			label1 := make(map[string]string)
			label1["app"] = "sampleSVC"
			pod := test.NewPod(
				"SampleSVC",
				namespace,
				80,
				label1,
			)
			mockCtlr.enqueuePod(pod)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Pod Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Pod Failed")
		})

		It("Secret", func() {
			secret := test.NewSecret(
				"SampleSecret",
				namespace,
				"testcert",
				"testkey",
			)
			mockCtlr.enqueueSecret(secret, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Secret Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Secret Failed")
		})

		It("Namespace", func() {
			labels := make(map[string]string)
			labels["app"] = "test"
			ns := test.NewNamespace(
				"SampleNS",
				"1",
				labels,
			)
			mockCtlr.enqueueNamespace(ns)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New Namespace Failed")
			Expect(quit).To(BeFalse(), "Enqueue New Namespace  Failed")

			mockCtlr.enqueueDeletedNamespace(ns)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted Namespace Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted Namespace  Failed")
		})

		It("IPAM", func() {
			mockCtlr.ipamCR = "default/SampleIPAM"

			hostSpec := &ficV1.HostSpec{
				Host:      "test.com",
				IPAMLabel: "test",
			}
			ipam := test.NewIPAM(
				"SampleIPAM",
				namespace,
				ficV1.IPAMSpec{
					HostSpecs: []*ficV1.HostSpec{hostSpec},
				},
				ficV1.IPAMStatus{},
			)
			mockCtlr.enqueueIPAM(ipam)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue New IPAM Failed")
			Expect(quit).To(BeFalse(), "Enqueue New IPAM  Failed")

			ipSpec := &ficV1.IPSpec{
				Host:      "test.com",
				IPAMLabel: "test",
				IP:        "1.2.3.4",
			}
			newIPAM := test.NewIPAM(
				"SampleIPAM",
				namespace,
				ficV1.IPAMSpec{
					HostSpecs: []*ficV1.HostSpec{hostSpec},
				},
				ficV1.IPAMStatus{
					IPStatus: []*ficV1.IPSpec{ipSpec},
				},
			)
			mockCtlr.enqueueUpdatedIPAM(ipam, newIPAM)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Updated IPAM Failed")
			Expect(quit).To(BeFalse(), "Enqueue Updated IPAM  Failed")

			mockCtlr.enqueueDeletedIPAM(newIPAM)
			key, quit = mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Deleted IPAM Failed")
			Expect(quit).To(BeFalse(), "Enqueue Deleted IPAM  Failed")
		})
	})

	Describe("Common Resource Informers", func() {
		BeforeEach(func() {
			mockCtlr.mode = OpenShiftMode
			mockCtlr.namespaces = make(map[string]bool)
			mockCtlr.namespaces["default"] = true
			mockCtlr.kubeClient = k8sfake.NewSimpleClientset()
			mockCtlr.nrInformers = make(map[string]*NRInformer)
			mockCtlr.comInformers = make(map[string]*CommonInformer)
			mockCtlr.crInformers = make(map[string]*CRInformer)
			mockCtlr.nativeResourceSelector, _ = createLabelSelector(DefaultNativeResourceLabel)
		})
		It("Resource Informers", func() {
			err := mockCtlr.addNamespacedInformers(namespace, false)
			Expect(err).To(BeNil(), "Informers Creation Failed")

			comInf, found := mockCtlr.getNamespacedCommonInformer(namespace)
			Expect(comInf).ToNot(BeNil(), "Finding Informer Failed")
			Expect(found).To(BeTrue(), "Finding Informer Failed")
		})
	})

	Describe("Native Resource Queueing", func() {
		BeforeEach(func() {
			mockCtlr.mode = OpenShiftMode
			mockCtlr.resourceQueue = workqueue.NewNamedRateLimitingQueue(
				workqueue.DefaultControllerRateLimiter(), "native-resource-controller")
			mockCtlr.nativeResourceSelector, _ = createLabelSelector(DefaultNativeResourceLabel)

		})
		AfterEach(func() {
			mockCtlr.resourceQueue.ShutDown()
		})

		It("Route", func() {
			rt := test.NewRoute(
				"sampleroute",
				"v1",
				namespace,
				routeapi.RouteSpec{
					Host: "foo.com",
					Path: "bar",
				},
				nil)
			mockCtlr.enqueueRoute(rt, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Route Failed")
			Expect(quit).To(BeFalse(), "Enqueue Route  Failed")

			//mockCtlr.enqueueDeletedRoute(rt)
			//key, quit = mockCtlr.resourceQueue.Get()
			//Expect(key).ToNot(BeNil(), "Enqueue Route Failed")
			//Expect(quit).To(BeFalse(), "Enqueue Route  Failed")
		})

		// we are not validating this while enqueuing
		//It("Invalid ConfigMap", func() {
		//	cm := test.NewConfigMap(
		//		"samplecfgmap",
		//		"v1",
		//		namespace,
		//		map[string]string{
		//			"extendedSpec": "extendedRouteSpec",
		//		},
		//	)
		//	mockCtlr.enqueueConfigmap(cm)
		//	len := mockCtlr.resourceQueue.Len()
		//	Expect(len).To(BeZero(), "Invalid ConfigMap enqueued")
		//})

		It("Global ConfigMap", func() {
			cmName := "samplecfgmap"
			mockCtlr.routeSpecCMKey = namespace + "/" + cmName
			cm := test.NewConfigMap(
				cmName,
				"v1",
				namespace,
				map[string]string{
					"extendedSpec": "extendedRouteSpec",
				},
			)
			mockCtlr.enqueueConfigmap(cm, Create)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Global ConfigMap Failed")
			Expect(quit).To(BeFalse(), "Enqueue Global ConfigMap  Failed")
		})

		It("Local ConfigMap", func() {
			cm := test.NewConfigMap(
				"samplecfgmap",
				"v1",
				namespace,
				map[string]string{
					"extendedSpec": "extendedRouteSpec",
				},
			)
			cm.SetLabels(map[string]string{
				"f5nr": "true",
			})
			mockCtlr.enqueueConfigmap(cm, Update)
			key, quit := mockCtlr.resourceQueue.Get()
			Expect(key).ToNot(BeNil(), "Enqueue Local ConfigMap Failed")
			Expect(quit).To(BeFalse(), "Enqueue Local ConfigMap  Failed")
		})

	})

})


text:
layout: post
title: Trabalhando com Dicionários
---

No último cast vimos como trabalhar com arrays em Objective-C. Nesse cast vamos conhecer os dicionários que possuem um propósito bem parecido com os arrays, mas com uma diferencia crucial que é a utilização de uma chave para identificar um objeto dentro do dicionário, criando assim uma coleção baseada nas chaves definidas. Como os arrays em Objective-C os dicionários também são separados de 2 formas imutáveis NSDicitonary e mutáveis NSMutableDicionary.

---

#### Código Fonte

> [https://github.com/iOSDevSpot/iosdevspot-samples/tree/master/Dictionaries](https://github.com/iOSDevSpot/iosdevspot-samples/tree/master/Dictionaries)

---

#### Referências

> [NSDictionary Class Reference](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html)


text:
package org.fcrepo.server.search;

import java.util.List;
import junit.framework.JUnit4TestAdapter;
import org.fcrepo.server.errors.QueryParseException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class ConditionTest
{

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(ConditionTest.class);
    }

    @Test
    public void getConditions_whenCalledWithDocumentationExample() throws QueryParseException
    {
        List<Condition> conditions = Condition.getConditions( "a=x b~'that\\'s' c>='z'");
        assertEquals( 3, conditions.size() );
        assertEquals( new Condition("a", Operator.EQUALS, "x" ), conditions.get( 0 ) );
        assertEquals( new Condition("b", Operator.CONTAINS, "that's" ), conditions.get( 1 ) );
        assertEquals( new Condition("c", Operator.GREATER_OR_EQUAL, "z" ), conditions.get( 2 ) );
    }

    @Test
    public void getConditions_whenValueContainsEscapedSingleQuoteInQuotes() throws QueryParseException
    {
        List<Condition> conditions = Condition.getConditions( "title='Hello\\'World'");
        assertEquals( 1, conditions.size() );
        Condition cond = conditions.get( 0 );
        assertEquals( "title", cond.getProperty() );
        assertEquals( Operator.EQUALS, cond.getOperator() );
        assertEquals( "Hello'World", cond.getValue() );
    }

    @Test
    public void getConditions_whenValueContainsEqualsOperatorInQuotes() throws QueryParseException
    {
        List<Condition> conditions = Condition.getConditions( "title='E=mc²'");
        assertEquals( 1, conditions.size() );
        Condition cond = conditions.get( 0 );
        assertEquals( "title", cond.getProperty() );
        assertEquals( Operator.EQUALS, cond.getOperator() );
        assertEquals( "E=mc²", cond.getValue() );
    }

    @Test ( expected = QueryParseException.class )
    public void getConditions_whenValueContainsEqualsOperatorWithoutQuotes() throws QueryParseException
    {
        Condition.getConditions( "title=E=mc²");
    }

    @Test
    public void getConditions_whenValueContainsGreaterThanOperatorInQuotes() throws QueryParseException
    {
        List<Condition> conditions = Condition.getConditions( "title='2>1'");
        assertEquals( 1, conditions.size() );
        Condition cond = conditions.get( 0 );
        assertEquals( "title", cond.getProperty() );
        assertEquals( Operator.EQUALS, cond.getOperator() );
        assertEquals( "2>1", cond.getValue() );
    }

    @Test ( expected = QueryParseException.class )
    public void getConditions_whenValueContainsGreaterThanOperatorWithoutQuotes() throws QueryParseException
    {
        Condition.getConditions( "title=2>1");
    }

}


text:
package util;

import org.junit.Test;

import java.util.Calendar;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Created by kenichiro_ota on 2014/04/24.
 */
public class CalendarUtilityTest {
    @Test
    public void testGetImmediateSaturdayOfWeekWhenTodayIsFriday() throws Exception {
        Calendar friday = Calendar.getInstance();
        friday.clear();
        friday.set(2014, Calendar.APRIL, 25);

        Calendar saturday = Calendar.getInstance();
        saturday.clear();
        saturday.set(2014, Calendar.APRIL, 26);

        assertThat(CalendarUtility.getImmediateDayOfWeek(friday, Calendar.SATURDAY), is(saturday));
    }

    @Test
    public void testGetImmediateSaturdayOfWeekWhenTodayIsSaturday() throws Exception {
        Calendar saturday = Calendar.getInstance();
        saturday.clear();
        saturday.set(2014, Calendar.APRIL, 26);

        Calendar nextSaturday = Calendar.getInstance();
        nextSaturday.clear();
        nextSaturday.set(2014, Calendar.MAY, 3);

        assertThat(CalendarUtility.getImmediateDayOfWeek(saturday, Calendar.SATURDAY), is(nextSaturday));
    }

    @Test
    public void testGetImmediateSaturdayOfWeekWhenTodayIsSunday() throws Exception {
        Calendar sunday = Calendar.getInstance();
        sunday.clear();
        sunday.set(2014, Calendar.APRIL, 27);

        Calendar saturday = Calendar.getInstance();
        saturday.clear();
        saturday.set(2014, Calendar.MAY, 3);

        assertThat(CalendarUtility.getImmediateDayOfWeek(sunday, Calendar.SATURDAY), is(saturday));
    }

    @Test
    public void testGetImmediateSundayOfWeekWhenTodayIsSunday() throws Exception {
        Calendar sunday = Calendar.getInstance();
        sunday.clear();
        sunday.set(2014, Calendar.APRIL, 27);

        Calendar nextSaturday = Calendar.getInstance();
        nextSaturday.clear();
        nextSaturday.set(2014, Calendar.MAY, 4);

        assertThat(CalendarUtility.getImmediateDayOfWeek(sunday, Calendar.SUNDAY), is(nextSaturday));
    }
}


text:
import java.util.*;

class Test {
    void test() {
        Comparator<Test> r2 = Test::yyy;
        <error descr="Incompatible types. Found: '<method reference>', required: 'Comparator1<Test>'">Comparator1<Test> c1 = Test::yyy;</error>
        <error descr="Incompatible types. Found: '<method reference>', required: 'Comparator1<Test>'">Comparator1<Test> c2 = Test::xxx;</error>
    }
    int yyy(Test... p) { return 1; }
    int xxx(Test t) {return 42;}
}

interface Comparator1<T> {
    int compare(T... o1);
}

class Test1 {
    void test() {
        Bar2 bar2 = Test1::yyy;
    }

    void yyy(Test1... p) {}

    interface Bar2 {
      public void xxx(Test1 p, Test1... ps);
    }
}


text:
using System;
using StackExchange.Profiling.Storage;
using Xunit;
using Xunit.Abstractions;

namespace StackExchange.Profiling.Tests.Storage
{
    public class MemoryCacheStorageTests : StorageBaseTest, IClassFixture<MemoryCacheStorageFixture>
    {
        public MemoryCacheStorageTests(MemoryCacheStorageFixture fixture, ITestOutputHelper output) : base(fixture, output)
        {
        }
    }

    public class MemoryCacheStorageFixture : StorageFixtureBase<MemoryCacheStorage>
    {
        public MemoryCacheStorageFixture()
        {
            Storage = new MemoryCacheStorage(TimeSpan.FromMinutes(5));
        }

        protected override void Dispose(bool disposing) { }
    }
}


text:
#ifndef CONTROL_ESTIMATOR_ESTIMATOR_TETHER_FORCE_H_
#define CONTROL_ESTIMATOR_ESTIMATOR_TETHER_FORCE_H_

#include "control/estimator/estimator_types.h"
#include "control/fault_detection/fault_detection_types.h"
#include "control/system_types.h"

#ifdef __cplusplus
extern "C" {
#endif

// Initialize tether force estimate state.
void EstimatorTetherForceInit(EstimatorTetherForceState *state);

// Estimate tether force and tension.
//
// Args:
//   loadcells: Array of kNumLoadcellSensors load cell values.
//   loadcell_faults: Array of kNumLoadcell faults.
//   wing_params: Wing parameters, to provide bridle information.
//   loadcell_params: Array of kNumLoadcell parameters.
//   params: Parameters.
//   state: State of the tether force estimator.
//   tether_force_b: Output tether force information.
void EstimatorTetherForceStep(const double loadcells[],
                              const FaultMask loadcell_faults[],
                              const WingParams *wing_params,
                              const LoadcellParams loadcell_params[],
                              const EstimatorTetherForceParams *params,
                              EstimatorTetherForceState *state,
                              TetherForceEstimate *tether_force_b);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // CONTROL_ESTIMATOR_ESTIMATOR_TETHER_FORCE_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
   - License, v. 2.0. If a copy of the MPL was not distributed with this
   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->

<!--
Build file for Rhino using Ant (see http://jakarta.apache.org/ant/index.html)
Requires Ant version 1.2
-->
<project name="src" default="compile" basedir="..">

  <property file="build.properties"/>

  <available property="jdk15"
             classname="java.lang.reflect.ParameterizedType" />

  <target name="compile" depends="compile-most,compile-jdk15">
  </target>

  <target name="shell" depends="compile">
    <java classname="org.mozilla.javascript.tools.shell.Main"
          classpath="${classes}"
          fork="true">
      <arg line="-version 170"/>
    </java>
  </target>

  <target name="compile-most">
    <javac srcdir="src"
           destdir="${classes}"
           includes="org/**/*.java"
           excludes="org/**/jdk15/*.java"
           deprecation="on"
           debug="${debug}"
           includeAntRuntime="false"
           target="${target-jvm}"
           source="${source-level}" />
    <copy todir="${classes}">
      <fileset dir="src" includes="org/**/*.properties" />
      <filterset>
      <filter token="IMPLEMENTATION.VERSION"
              value="${implementation.version}"/>
      </filterset>
    </copy>
  </target>

  <target name="compile-jdk15" if="jdk15">
    <javac srcdir="src"
           destdir="${classes}"
           includes="org/**/jdk15/*.java"
           deprecation="on"
           debug="${debug}"
           includeAntRuntime="false"
           target="${target-jvm}"
           source="${source-level}" />
  </target>

  <target name="copy-source">
    <mkdir dir="${dist.dir}/src"/>
    <copy todir="${dist.dir}/src">
      <fileset dir="src"
               includes="**/*.java,**/*.properties,**/*.xml,manifest"/>
    </copy>
  </target>

  <target name="clean">
    <delete includeEmptyDirs="true">
      <fileset dir="${classes}"
               excludes="org/mozilla/javascript/tools/**"/>
    </delete>
  </target>

</project>


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Preview\Sync\Service;

use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
 */
class SyncListPage extends Page {
    /**
     * @param Version $version Version that contains the resource
     * @param Response $response Response from the API
     * @param array $solution The context solution
     */
    public function __construct(Version $version, Response $response, array $solution) {
        parent::__construct($version, $response);

        // Path Solution
        $this->solution = $solution;
    }

    /**
     * @param array $payload Payload response from the API
     * @return SyncListInstance \Twilio\Rest\Preview\Sync\Service\SyncListInstance
     */
    public function buildInstance(array $payload): SyncListInstance {
        return new SyncListInstance($this->version, $payload, $this->solution['serviceSid']);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        return '[Twilio.Preview.Sync.SyncListPage]';
    }
}


text:
using Microsoft.AspNetCore.Connections;
using MQTTnet.Adapter;
using MQTTnet.Formatter;
using MQTTnet.Server;
using System;
using System.Threading.Tasks;

namespace MQTTnet.AspNetCore.Tests.Mockups
{
    public class ConnectionHandlerMockup: IMqttServerAdapter
    {
        public TaskCompletionSource<MqttConnectionContext> Context { get; } = new TaskCompletionSource<MqttConnectionContext>();
        public Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }

        public ConnectionHandlerMockup()
        {
        }

        public async Task OnConnectedAsync(ConnectionContext connection)
        {
            try
            {
                var writer = new SpanBasedMqttPacketWriter();
                var formatter = new MqttPacketFormatterAdapter(writer);
                var context = new MqttConnectionContext(formatter, connection);
                Context.TrySetResult(context);

                await ClientHandler(context);
            }
            catch (Exception ex)
            {
                Context.TrySetException(ex);
            }
        }

        public Task StartAsync(IMqttServerOptions options)
        {
            return Task.CompletedTask;
        }

        public Task StopAsync()
        {
            return Task.CompletedTask;
        }

        public void Dispose()
        {
        }
    }
}


text:
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
import BaseButton from './BaseButton';

export const ForwardRefButtonInnerPropTypes = forwardRef(BaseButton);

export const ForwardRefButtonOuterPropTypes = forwardRef(({ label, ...props }, ref) => (
  <BaseButton label={label} {...props} ref={ref} />
));

ForwardRefButtonOuterPropTypes.defaultProps = {
  disabled: false,
  onClick: () => {},
  style: {},
};

ForwardRefButtonOuterPropTypes.propTypes = {
  /** Boolean indicating whether the button should render as disabled */
  disabled: PropTypes.bool,
  /** button label. */
  label: PropTypes.string.isRequired,
  /** onClick handler */
  onClick: PropTypes.func,
  /** Custom styles */
  style: PropTypes.shape({}),
};


text:
{
    matrix_id: '2830',
    name: 'ifiss_mat',
    group: 'Embree',
    description: 'Fluid stability problem, illustrates need for iter. refinement',
    author: 'M. Embree',
    editor: 'T. Davis',
    date: '2015',
    kind: 'computational fluid dynamics',
    problem_2D_or_3D: '1',
    num_rows: '96307',
    num_cols: '96307',
    nonzeros: '3599932',
    num_explicit_zeros: '0',
    num_strongly_connected_components: '1',
    num_dmperm_blocks: '1',
    structural_full_rank: 'true',
    structural_rank: '96307',
    pattern_symmetry: '1.000',
    numeric_symmetry: '0.285',
    rb_type: 'real',
    structure: 'unsymmetric',
    cholesky_candidate: 'no',
    positive_definite: 'no',
    notes: 'Fluid stability problem from IFISS package, Mark Embree, Virginia Tech

The matrix comes from a shift-invert eigenvalue computation that arises
during linear stability analysis of a 2D backward facing step.  The
discretizations were created with IFISS, which we also use to compute the
steady-state flow whose stability we are assessing.

Created by the IFISS package, by David Silvester (School of Mathematics,
Univ. of Manchester), Howard Elman (Computer Science, Univ. of Maryland),
and Alison Ramage (Dept. of Mathematics and Statistics, Univ. of
Strathclyde).  http://www.maths.manchester.ac.uk/~djs/ifiss/

This matrix requires one step of iterative refinement after LU
factorization.  x=A\b in MATLAB (using UMFPACK) does iterative refinement
by default but with just lu, no iterative refinement is done:

    In MATLAB R2014a:
    x = randn(96307,1);
    b = A*x;
    x1 = A\b;
    norm(x-x1) is 1.1045984e-12
    norm(b-A*x1) is 9.3538018e-15

    [L,U,P,Q,R] = lu(A);
    x2 = Q*(U\(L\(P*(R\b))));
    norm(x-x2) is 4.9150874e-05
    norm(b-A*x2) is 4.0055911e-07

The matrix is well conditioned, with singular values ranging from
1.003 to 2e-5.  The singluar values themselves are in
Problem.aux.singular_values.  The need for iterative refinement
comes from the threshold partial pivoting in UMFPACK, which tries
to balance reduction in fill with finding good numerical pivots.
Thus UMFPACK uses iterative refinement with sparse backward error using
the method described in Arioli, Demmel, and Duff, "Sovling sparse linear
systems with sparse backward error", SIAM J. Matrix Analysis & Applic,
vol 10, no 2, pp 165-190, Apr 1989).

The matrix itself is described in this paper:

https://arxiv.org/abs/1601.00044

Pseudospectra of Matrix Pencils for Transient Analysis of
Differential-Algebraic Equations

Mark Embree, Blake Keeler
(Submitted on 1 Jan 2016 (v1),
last revised 27 Jun 2017 (this version, v3))

To understand the solution of a linear, time-invariant
differential-algebraic equation, one must analyze a matrix pencil (A,E)
with singular E. Even when this pencil is stable (all its finite
eigenvalues fall in the left-half plane), the solution can exhibit
transient growth before its inevitable decay. When the equation results
from the linearization of a nonlinear system, this transient growth gives
a mechanism that can promote nonlinear instability. One might hope to
enrich the conventional large-scale eigenvalue calculation used for
linear stability analysis to signal the potential for such transient
growth. Toward this end, we introduce a new definition of the
pseudospectrum of a matrix pencil, use it to bound transient growth,
explain how to incorporate a physically-relevant norm, and derive
approximate pseudospectra using the invariant subspace computed in
conventional linear stability analysis. We apply these tools to several
canonical test problems in fluid mechanics, an important source of
differential-algebraic equations.
',
    aux_fields: 'singular_values: full 96307-by-1
',    image_files: 'ifiss_mat.png,',
}


text:
'use strict';

require('./foo');

var _bar = require('./bar');

var _bar2 = babelHelpers.interopRequireDefault(_bar);

require('./derp');

var _qux = require('./qux');


text: Static files will be stored here


text:
require 'inquirer/style'

module Inquirer
  class Style
    class Password < Inquirer::Style::Input

      @@placeholder_char = '*'

      self.activate_getter_setter
    end
  end
end


text:
define( [

  "dojo/_base/declare"
, "dijit/layout/TabContainer"
, "hotplate/hotClientDojo/widgets/_StackFadingMixin"

], function(

  declare
, TabContainer
, _StackFadingMixin

){
  return declare( [ TabContainer, _StackFadingMixin ] );
});


text:
package org.apache.camel.processor;

import java.util.List;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.RouteNode;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.management.InstrumentationProcessor;
import org.apache.camel.spi.TracedRouteNodes;
import org.junit.Test;

/**
 * @version
 */
public class TraceableUnitOfWorkTest extends ContextTestSupport {

    @Test
    public void testSendingSomeMessages() throws Exception {
        Object out = template.requestBody("direct:start", "Hello London");
        assertEquals("Failed at: sendTo(bean://bar)", out);
    }

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        jndi.bind("foo", new MyFooBean());
        jndi.bind("bar", new MyBarBean());
        return jndi;
    }

    // START SNIPPET: e1
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(3));

                // must enable tracer to trace the route path taken during runtime
                context.setTracing(true);

                // let our my error processor handle all exceptions
                onException(Exception.class).handled(true).process(new MyErrorProcessor());

                // our route where an exception can be thrown from either foo or bar bean
                // so we have enable tracing so we can check it at runtime to get the actual
                // node path taken
                from("direct:start").to("bean:foo").to("bean:bar");
            }
        };
    }
    // END SNIPPET: e1

    // START SNIPPET: e2
    private static class MyErrorProcessor implements Processor {
        public void process(Exchange exchange) throws Exception {
            TracedRouteNodes traced = exchange.getUnitOfWork().getTracedRouteNodes();

            // get the list of intercepted nodes
            List<RouteNode> list = traced.getNodes();
            // get the 3rd last as its the bean
            Processor last = list.get(list.size() - 3).getProcessor();

            // wrapped by JMX
            if (last instanceof InstrumentationProcessor) {
                InstrumentationProcessor ip = (InstrumentationProcessor) last;
                last = ip.getProcessor();
            }

            // set error message
            exchange.getOut().setFault(true);
            exchange.getOut().setBody("Failed at: " + last.toString());
        }

        public String toString() {
            return "MyErrorProcessor";
        }
    }
    // END SNIPPET: e2

    public class MyFooBean {
        public void process(Exchange exchange) throws Exception {
            exchange.getOut().setBody("Foo okay");
        }
    }

    public class MyBarBean {
        public void process(Exchange exchange) throws Exception {
            throw new IllegalArgumentException("Damm Bar");
        }
    }
}


text:
This section explains how to install and uninstall the project.

Install project dependencies.

```sh
script/setup.sh
```

## Usage

This section explains how to use the project.

Run the main program.

```sh
bin/ps
```

## Development

This section explains how to improve the project.

Configure Git on Windows before cloning. This avoids problems with Vagrant and VirtualBox.

```sh
git config --global core.autocrlf input
```

Create the development virtual machine on Linux and Darwin.

```sh
script/vagrant/create.sh
```

Create the development virtual machine on Windows.

```bat
script\vagrant\create.bat
```

Run tests.

```sh
script/test.sh [--help]
```

Run style check.

```sh
script/check.sh [--help]
```

Build project.

```sh
script/build.sh
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.OperationalInsights.Models;

namespace Microsoft.Azure.Management.OperationalInsights.Models
{
    /// <summary>
    /// The top level storage insight resource container.
    /// </summary>
    public partial class StorageInsight
    {
        private string _eTag;

        /// <summary>
        /// Optional. Gets or sets the ETag of the storage insight.
        /// </summary>
        public string ETag
        {
            get { return this._eTag; }
            set { this._eTag = value; }
        }

        private string _id;

        /// <summary>
        /// Optional. Gets or sets the ID of the resource.
        /// </summary>
        public string Id
        {
            get { return this._id; }
            set { this._id = value; }
        }

        private string _location;

        /// <summary>
        /// Optional. Gets or sets the location of the resource.
        /// </summary>
        public string Location
        {
            get { return this._location; }
            set { this._location = value; }
        }

        private string _name;

        /// <summary>
        /// Required. Gets or sets the name of the resource.
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private StorageInsightProperties _properties;

        /// <summary>
        /// Required. Gets or sets the properties of the storage insight.
        /// </summary>
        public StorageInsightProperties Properties
        {
            get { return this._properties; }
            set { this._properties = value; }
        }

        private IDictionary<string, string> _tags;

        /// <summary>
        /// Optional. Gets or sets the tags attached to the resource.
        /// </summary>
        public IDictionary<string, string> Tags
        {
            get { return this._tags; }
            set { this._tags = value; }
        }

        private string _type;

        /// <summary>
        /// Optional. Gets or sets the type of the resource.
        /// </summary>
        public string Type
        {
            get { return this._type; }
            set { this._type = value; }
        }

        /// <summary>
        /// Initializes a new instance of the StorageInsight class.
        /// </summary>
        public StorageInsight()
        {
            this.Tags = new LazyDictionary<string, string>();
        }

        /// <summary>
        /// Initializes a new instance of the StorageInsight class with
        /// required arguments.
        /// </summary>
        public StorageInsight(StorageInsightProperties properties, string name)
            : this()
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            this.Properties = properties;
            this.Name = name;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="INDEX, FOLLOW">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Read Me - Essentials</title>
    <link rel="stylesheet" href="css/main.css">

Read Me

Learn more about Essentials and how to get started.  Edit
                Page

Essentials

Read Me

Icons

                    Fork

Read Me

Icons

 Fork

Contents

About

Getting Started

Default Build

Custom Build

Examples

Contributing

LICENSE

                    Contents

About

Getting Started

Default Build

Custom Build

Examples

Contributing

LICENSE

About

Unlike other monolith frameworks, Essentials
                provides a minimum set of components that gives the designer the freedom to explore and discover
                new designs. By removing the unnecessary, the essential simplifies the design process.

Getting Started

Start by downloading
                the repository or by cloning
                the project:

git clone https://github.com/jacobxperez/essentials.git

Default Build

The easiest way to include Essentials in your
                projects is by copying the pre-compiled CSS
                file into your project folder and then linking to it in HTML.

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

/css

main.css

Custom Build

Add custom modules, edit
                the
                variables.less,
                uncomment unused components from main.less
                then
                compile to produce the final CSS.
                Check out Editors
                    and Plugins
                for compiling LESS.

Examples

These examples incorporate the framework with custom components and layouts.

Company:
                        A single page website template for your company marketing.

Jacob
                                Perez:
                        Author personal website and blog template.

Vaporwave
                                Aesthetic:
                        A template with vaporwave aesthetics.

Contributing

If you are interested in contributing to this project please read our
                contributing
                    guidelines
                to better understand the nature and the direction of the project, any contribution
                will be considered.

LICENSE

Copyright (C) 2022 Jacob Perez

Licensed under the Apache
                    License, Version 2.0 (the "License");
                you may not use this file except in compliance with the License.
                You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
                distributed under the License is distributed on an "AS IS" BASIS,
                WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                See the License for the specific language governing permissions and
                limitations under the License.

© 2022 Essentials by Jacob Perez and licensed
                under the Apache
                    License
                    v2.0.


text:
APP_PATH = "/vagrant/mo"
worker_processes 4
working_directory APP_PATH
listen "/tmp/unicorn.sock", backlog: 64
listen 8080, tcp_nopush: true
timeout 300
pid "/tmp/unicorn.pid"
stderr_path APP_PATH + "/log/unicorn.stderr.log"
stdout_path APP_PATH + "/log/unicorn.stdout.log"
preload_app false
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true
check_client_connection false
before_fork do |_server, _worker|
  defined?(ActiveRecord::Base) &&
    ActiveRecord::Base.connection.disconnect!
end
after_fork do |_server, _worker|
  defined?(ActiveRecord::Base) &&
    ActiveRecord::Base.establish_connection
end


text:
<?php

namespace app\models\ar;

use Yii;

/**
 * This is the model class for table "question".
 *
 * @property integer $id
 * @property integer $question_type_id
 * @property string $text
 * @property string $data
 * @property string $hint
 * @property string $comment
 * @property integer $cost
 *
 * @property Answer[] $answers
 * @property ChallengeHasQuestion[] $challengeHasQuestions
 * @property Challenge[] $challenges
 * @property QuestionType $questionType
 * @property QuestionHasChallengeType[] $questionHasChallengeTypes
 * @property ChallengeType[] $challengeTypes
 * @property QuestionHasCourse[] $questionHasCourses
 * @property Course[] $courses
 * @property QuestionHasSubject[] $questionHasSubjects
 * @property Subject[] $subjects
 */
class Question extends \app\components\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'question';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['question_type_id'], 'required'],
            [['question_type_id', 'cost'], 'integer'],
            [['text', 'data', 'hint', 'comment'], 'string'],
            [['question_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => QuestionType::className(), 'targetAttribute' => ['question_type_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'question_type_id' => 'Question Type ID',
            'text' => 'Text',
            'data' => 'Data',
            'hint' => 'Hint',
            'comment' => 'Comment',
            'cost' => 'Cost',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAnswers()
    {
        return $this->hasMany(Answer::className(), ['question_id' => 'id'])->inverseOf('question');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChallengeHasQuestions()
    {
        return $this->hasMany(ChallengeHasQuestion::className(), ['question_id' => 'id'])->inverseOf('question');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChallenges()
    {
        return $this->hasMany(Challenge::className(), ['id' => 'challenge_id'])->viaTable('challenge_has_question', ['question_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestionType()
    {
        return $this->hasOne(QuestionType::className(), ['id' => 'question_type_id'])->inverseOf('questions');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestionHasChallengeTypes()
    {
        return $this->hasMany(QuestionHasChallengeType::className(), ['question_id' => 'id'])->inverseOf('question');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChallengeTypes()
    {
        return $this->hasMany(ChallengeType::className(), ['id' => 'challenge_type_id'])->viaTable('question_has_challenge_type', ['question_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestionHasCourses()
    {
        return $this->hasMany(QuestionHasCourse::className(), ['question_id' => 'id'])->inverseOf('question');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCourses()
    {
        return $this->hasMany(Course::className(), ['id' => 'course_id'])->viaTable('question_has_course', ['question_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestionHasSubjects()
    {
        return $this->hasMany(QuestionHasSubject::className(), ['question_id' => 'id'])->inverseOf('question');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSubjects()
    {
        return $this->hasMany(Subject::className(), ['id' => 'subject_id'])->viaTable('question_has_subject', ['question_id' => 'id']);
    }
}


text:
import handlers

routes = []
routes.extend(handlers.add_comment.route)
routes.extend(handlers.get_new_pic.route)
routes.extend(handlers.index.route)
routes.extend(handlers.like.route)
routes.extend(handlers.load_more.route)
routes.extend(handlers.login.route)
routes.extend(handlers.logout.route)
routes.extend(handlers.new_pic_notify.route)
routes.extend(handlers.register.route)
routes.extend(handlers.upload_avatar.route)
routes.extend(handlers.upload_file.route)
routes.append((r"/(.*)", handlers.error.ErrorHandler))


text:
package org.efaps.esjp.mail;

import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;

/**
 * This class must be replaced for customization, therefore it is left empty.
 * Functional description can be found in the related "<code>_Base</code>"
 * class.
 *
 * @author The eFaps Team
 */
@EFapsUUID("46f7e1c3-b4ec-4bef-8483-ae77fd3d2fa5")
@EFapsApplication("eFapsApp-Mail")
public class SendMail
    extends SendMail_Base
{

}


text:
package org.jsmiparser.util.token;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.math.BigInteger;

import org.jsmiparser.util.location.Location;
import org.junit.Test;

public class BinaryStringTokenTest {
    @Test
    public void testGood() {
        BinaryStringToken t = new BinaryStringToken(new Location("testcase"),
                "'101'B");
        BigInteger value = t.getIntegerValue();
        assertEquals(5, value.intValue());
        assertEquals('B', t.getRadixChar());
    }

    @Test
    public void testBad() {
        BinaryStringToken t = new BinaryStringToken(new Location("testcase"),
                "7FFF");
        try {
            t.getIntegerValue();
            fail();
        } catch (Exception ignored) {
            // ignore
        }
    }

    @Test
    public void testToString() {
        String str = "'101'B";
        BinaryStringToken t = new BinaryStringToken(new Location("testcase"),
                str);
        assertEquals(str, t.toString());
    }

}


text:
import os
import cv2
from plantcv.plantcv import fatal_error
from plantcv.plantcv._debug import _debug
from plantcv.plantcv import params

def readbayer(filename, bayerpattern='BG', alg='default'):
    """
    Read image from file that has a Bayer mosaic.

    Inputs:
    filename = name of image file
    bayerpattern = arrangement of the pixels. Often found by trial and error. ("BG","GB","RG","GR")
    alg = algorithm with which to demosaic the image. ("default","EdgeAware","VariableNumberGradients")

    Returns:
    img      = image object as numpy array
    path     = path to image file
    img_name = name of image file

    :param filename: str
    :param alg: str
    :param bayerpattern: str
    :return img: numpy.ndarray
    :return path: str
    :return img_name: str
    """
    # bayerpattern is defined as the colors of the pixels in the 2nd and 3rd column of the 2nd row.
    # see https://docs.opencv.org/3.2.0/de/d25/imgproc_color_conversions.html
    # COLOR_BayerBG2BGR
    # COLOR_BayerGB2BGR
    # COLOR_BayerRG2BGR
    # COLOR_BayerGR2BGR
    image_raw = cv2.imread(filename, flags=-1)

    if image_raw is None:
        fatal_error("Failed to open " + filename)

    if alg.upper() == 'DEFAULT':
        if bayerpattern.upper() == 'BG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerBG2BGR)
        elif bayerpattern.upper() == 'GB':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGB2BGR)
        elif bayerpattern.upper() == 'RG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerRG2BGR)
        elif bayerpattern.upper() == 'GR':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGR2BGR)
    elif alg.upper() == 'EDGEAWARE':
        if bayerpattern.upper() == 'BG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerBG2BGR_EA)
        elif bayerpattern.upper() == 'GB':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGB2BGR_EA)
        elif bayerpattern.upper() == 'RG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerRG2BGR_EA)
        elif bayerpattern.upper() == 'GR':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGR2BGR_EA)
    elif alg.upper() == 'VARIABLENUMBERGRADIENTS':
        if bayerpattern.upper() == 'BG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerBG2BGR_VNG)
        elif bayerpattern.upper() == 'GB':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGB2BGR_VNG)
        elif bayerpattern.upper() == 'RG':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerRG2BGR_VNG)
        elif bayerpattern.upper() == 'GR':
            img = cv2.cvtColor(image_raw, cv2.COLOR_BayerGR2BGR_VNG)

    # Split path from filename
    path, img_name = os.path.split(filename)

    _debug(visual=img,
           filename=os.path.join(params.debug_outdir, "input_image.png"))

    return img, path, img_name


text:
package org.apache.flink.runtime.state;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * The handle to states of an incremental snapshot.
 *

 * The states contained in an incremental snapshot include:
 *

 *
 Created shared state which includes shared files produced since the last
 * completed checkpoint. These files can be referenced by succeeding checkpoints if the
 * checkpoint succeeds to complete.

 *
 Referenced shared state which includes the shared files materialized in previous
 * checkpoints. Until we this is registered to a {@link SharedStateRegistry}, all referenced
 * shared state handles are only placeholders, so that we do not send state handles twice
 * from which we know that they already exist on the checkpoint coordinator.

 *
 Private state which includes all other files, typically mutable, that cannot be shared by
 * other checkpoints.

 *
 Backend meta state which includes the information of existing states.

 *

 *
 * When this should become a completed checkpoint on the checkpoint coordinator, it must first be
 * registered with a {@link SharedStateRegistry}, so that all placeholder state handles to
 * previously existing state are replaced with the originals.
 *
 * IMPORTANT: This class currently overrides equals and hash code only for testing purposes. They
 * should not be called from production code. This means this class is also not suited to serve as
 * a key, e.g. in hash maps.
 */
public class IncrementalKeyedStateHandle implements KeyedStateHandle {

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

	private static final long serialVersionUID = -8328808513197388231L;

	/**
	 * The operator instance identifier for this handle
	 */
	private final String operatorIdentifier;

	/**
	 * The key-group range covered by this state handle
	 */
	private final KeyGroupRange keyGroupRange;

	/**
	 * The checkpoint Id
	 */
	private final long checkpointId;

	/**
	 * Shared state in the incremental checkpoint. This i
	 */
	private final Map<StateHandleID, StreamStateHandle> sharedState;

	/**
	 * Private state in the incremental checkpoint
	 */
	private final Map<StateHandleID, StreamStateHandle> privateState;

	/**
	 * Primary meta data state of the incremental checkpoint
	 */
	private final StreamStateHandle metaStateHandle;

	/**
	 * Once the shared states are registered, it is the {@link SharedStateRegistry}'s
	 * responsibility to cleanup those shared states.
	 * But in the cases where the state handle is discarded before performing the registration,
	 * the handle should delete all the shared states created by it.
	 *
	 * This variable is not null iff the handles was registered.
	 */
	private transient SharedStateRegistry sharedStateRegistry;

	public IncrementalKeyedStateHandle(
		String operatorIdentifier,
		KeyGroupRange keyGroupRange,
		long checkpointId,
		Map<StateHandleID, StreamStateHandle> sharedState,
		Map<StateHandleID, StreamStateHandle> privateState,
		StreamStateHandle metaStateHandle) {

		this.operatorIdentifier = Preconditions.checkNotNull(operatorIdentifier);
		this.keyGroupRange = Preconditions.checkNotNull(keyGroupRange);
		this.checkpointId = checkpointId;
		this.sharedState = Preconditions.checkNotNull(sharedState);
		this.privateState = Preconditions.checkNotNull(privateState);
		this.metaStateHandle = Preconditions.checkNotNull(metaStateHandle);
		this.sharedStateRegistry = null;
	}

	@Override
	public KeyGroupRange getKeyGroupRange() {
		return keyGroupRange;
	}

	public long getCheckpointId() {
		return checkpointId;
	}

	public Map<StateHandleID, StreamStateHandle> getSharedState() {
		return sharedState;
	}

	public Map<StateHandleID, StreamStateHandle> getPrivateState() {
		return privateState;
	}

	public StreamStateHandle getMetaStateHandle() {
		return metaStateHandle;
	}

	public String getOperatorIdentifier() {
		return operatorIdentifier;
	}

	@Override
	public KeyedStateHandle getIntersection(KeyGroupRange keyGroupRange) {
		if (this.keyGroupRange.getIntersection(keyGroupRange) != KeyGroupRange.EMPTY_KEY_GROUP_RANGE) {
			return this;
		} else {
			return null;
		}
	}

	@Override
	public void discardState() throws Exception {

		try {
			metaStateHandle.discardState();
		} catch (Exception e) {
			LOG.warn("Could not properly discard meta data.", e);
		}

		try {
			StateUtil.bestEffortDiscardAllStateObjects(privateState.values());
		} catch (Exception e) {
			LOG.warn("Could not properly discard misc file states.", e);
		}

		// If this was not registered, we can delete the shared state. We can simply apply this
		// to all handles, because all handles that have not been created for the first time for this
		// are only placeholders at this point (disposing them is a NOP).
		if (sharedStateRegistry == null) {
			try {
				StateUtil.bestEffortDiscardAllStateObjects(sharedState.values());
			} catch (Exception e) {
				LOG.warn("Could not properly discard new sst file states.", e);
			}
		} else {
			// If this was registered, we only unregister all our referenced shared states
			// from the registry.
			for (StateHandleID stateHandleID : sharedState.keySet()) {
				sharedStateRegistry.unregisterReference(
					createSharedStateRegistryKeyFromFileName(stateHandleID));
			}
		}
	}

	@Override
	public long getStateSize() {
		long size = StateUtil.getStateSize(metaStateHandle);

		for (StreamStateHandle sharedStateHandle : sharedState.values()) {
			size += sharedStateHandle.getStateSize();
		}

		for (StreamStateHandle privateStateHandle : privateState.values()) {
			size += privateStateHandle.getStateSize();
		}

		return size;
	}

	@Override
	public void registerSharedStates(SharedStateRegistry stateRegistry) {

		Preconditions.checkState(sharedStateRegistry == null, "The state handle has already registered its shared states.");

		sharedStateRegistry = Preconditions.checkNotNull(stateRegistry);

		for (Map.Entry<StateHandleID, StreamStateHandle> sharedStateHandle : sharedState.entrySet()) {
			SharedStateRegistryKey registryKey =
				createSharedStateRegistryKeyFromFileName(sharedStateHandle.getKey());

			SharedStateRegistry.Result result =
				stateRegistry.registerReference(registryKey, sharedStateHandle.getValue());

			// This step consolidates our shared handles with the registry, which does two things:
			//
			// 1) Replace placeholder state handle with already registered, actual state handles.
			//
			// 2) Deduplicate re-uploads of incremental state due to missing confirmations about
			// completed checkpoints.
			//
			// This prevents the following problem:
			// A previous checkpoint n has already registered the state. This can happen if a
			// following checkpoint (n + x) wants to reference the same state before the backend got
			// notified that checkpoint n completed. In this case, the shared registry did
			// deduplication and returns the previous reference.
			sharedStateHandle.setValue(result.getReference());
		}
	}

	/**
	 * Create a unique key to register one of our shared state handles.
	 */
	@VisibleForTesting
	public SharedStateRegistryKey createSharedStateRegistryKeyFromFileName(StateHandleID shId) {
		return new SharedStateRegistryKey(operatorIdentifier + '-' + keyGroupRange, shId);
	}

	/**
	 * This method is should only be called in tests! This should never serve as key in a hash map.
	 */
	@VisibleForTesting
	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}

		IncrementalKeyedStateHandle that = (IncrementalKeyedStateHandle) o;

		if (getCheckpointId() != that.getCheckpointId()) {
			return false;
		}
		if (!getOperatorIdentifier().equals(that.getOperatorIdentifier())) {
			return false;
		}
		if (!getKeyGroupRange().equals(that.getKeyGroupRange())) {
			return false;
		}
		if (!getSharedState().equals(that.getSharedState())) {
			return false;
		}
		if (!getPrivateState().equals(that.getPrivateState())) {
			return false;
		}
		return getMetaStateHandle().equals(that.getMetaStateHandle());
	}

	/**
	 * This method should only be called in tests! This should never serve as key in a hash map.
	 */
	@VisibleForTesting
	@Override
	public int hashCode() {
		int result = getOperatorIdentifier().hashCode();
		result = 31 * result + getKeyGroupRange().hashCode();
		result = 31 * result + (int) (getCheckpointId() ^ (getCheckpointId() >>> 32));
		result = 31 * result + getSharedState().hashCode();
		result = 31 * result + getPrivateState().hashCode();
		result = 31 * result + getMetaStateHandle().hashCode();
		return result;
	}
}


text:
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", '', Scope="Function", Target="*")]
param()

function Main() {
  if (-not (Get-Command 7z.exe)) {
    Write-Host '[-] 7z note found!  Please run .\tools\make-win64-dev-env.bat before continuing!' -ForegroundColor Red
    exit
  }

  if ($PSVersionTable.PSVersion.Major -lt 5) {
    Write-Host '[-] Powershell 5.0 or great is required for this script.' -ForegroundColor Red
    exit
  }

  $version = git describe --tags
  $latestFullVersion = (git tag)[-2]
  # If split len is greater than 1, this is a pre-release. Chocolatey is particular
  # about the format of the version for pre-releases.
  if ($version.split('-').length -eq 3) {
    $version = $version.split('-')[0] + '-' + $version.split('-')[2]
  }

  if (-not (Test-Path (Join-Path (Get-location).Path 'tools\make-win64-binaries.bat'))) {
    Write-Host "[-] Did not find build script '.\tools\make-win64-binaries.bat'!" -ForegroundColor Red
    Write-Host "[-] This script must be run from the osquery repo root!" -ForegroundColor Red
    exit
  }
  # Binaries might not be built, let's try to build them quick :)
  if (-not (Test-Path (Join-Path (Get-Location).Path 'build\windows10\osquery\Release'))) {
    & '.\tools\make-win64-binaries.bat'
  }

  # Listing of artifacts bundled with osquery
  $scriptPath = Get-Location
  $chocoPath = [System.Environment]::GetEnvironmentVariable('ChocolateyInstall', 'Machine')
  $certs = Join-Path "$chocoPath" 'lib\openssl\local\certs'
  if (-not (Test-Path $certs)) {
    Write-Host "[*] Did not find openssl certs.pem" -ForegroundColor Yellow
  }

  $conf = Join-Path $scriptPath 'tools\deployment\osquery.example.conf'
  if (-not (Test-Path $conf)) {
    Write-Host "[*] Did not find example configuration" -ForegroundColor Yellow
  }

  $packs = Join-Path $scriptPath 'packs'
  if (-not (Test-Path $packs)) {
    Write-Host "[*] Did not find example packs" -ForegroundColor Yellow
  }

  $nupkg =
@'
<?xml version="1.0" encoding="utf-8"?>
<!-- Do not remove this test for UTF-8: if "Ω" doesn't appear as greek uppercase omega letter enclosed in quotation marks, you should use an editor that supports UTF-8, not this one. -->
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
  <metadata>
    <id>osquery</id>
    <version>
'@
$nupkg += $version
$nupkg +=
@'
</version>
    <title>osquery</title>
    <authors>Facebook</authors>
    <owners>Facebook</owners>
    <copyright>Copyright (c) 2014-present, Facebook, Inc. All rights reserved.</copyright>
    <projectUrl>https://osquery.io</projectUrl>
    <iconUrl>https://osquery.io/static/site/img/logo-big.png</iconUrl>
    <licenseUrl>https://github.com/facebook/osquery/blob/master/LICENSE</licenseUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <projectSourceUrl>https://github.com/facebook/osquery</projectSourceUrl>
    <docsUrl>https://osquery.readthedocs.io/en/stable</docsUrl>
    <mailingListUrl>https://osquery-slack.herokuapp.com/</mailingListUrl>
    <bugTrackerUrl>https://github.com/facebook/osquery/issues</bugTrackerUrl>
    <tags>InfoSec Tools</tags>
    <summary>
      osquery gives you the ability to query and log things like running
      processes, logged in users, password changes, usb devices, firewall
      exceptions, listening ports, and more.
    </summary>
    <description>
      osquery allows you to easily ask questions about your Linux, OSX, and
      Windows infrastructure. Whether your goal is intrusion detection,
      infrastructure reliability, or compliance, osquery gives you the ability
      to empower and inform a broad set of organizations within your company.

      ### Package Parameters
      * `/InstallService` - This creates a new windows service that will auto-start the daemon.

      These parameters can be passed to the installer with the user of `-params`.
      For example: `-params '"/InstallService"'`.
    </description>
    <releaseNotes>
'@
$nupkg += "https://github.com/facebook/osquery/releases/tag/$latestFullVersion"
$nupkg +=
@'
</releaseNotes>
  </metadata>
  <files>
    <file src="tools\**" target="tools" />
  </files>
</package>
'@

  $chocoBuildPath = "$scriptPath\build\chocolatey"
  $osqueryChocoPath = "$chocoBuildPath\osquery"
  New-Item -Force -ItemType Directory -Path "$osqueryChocoPath\tools\bin"
  Copy-Item -Recurse -Force "$scriptPath\tools\deployment\chocolatey\tools" "$osqueryChocoPath"
  Copy-Item -Recurse -Force "$scriptPath\tools\provision\chocolatey\osquery_utils.ps1" "$osqueryChocoPath\tools\osquery_utils.ps1"

  $buildDir = "$scriptPath\build\windows10\osquery\Release\"
  $clientPath = Join-Path $buildDir 'osqueryi.exe'
  $daemonPath = Join-Path $buildDir 'osqueryd.exe'
  $mgmtScript = "$scriptPath\tools\manage-osqueryd.ps1"
  $nupkg | Out-File -Encoding "UTF8" "$osqueryChocoPath\osquery.nuspec"
  if (-not ((Test-Path $clientPath) -or (Test-Path $daemonPath))) {
    Write-Host '[-] Unable to find osquery binaries!  Check the results of the build scripts!' -ForegroundColor Red
    exit
  }

  # This bundles up all of the files we distribute.
  7z a "$osqueryChocoPath\tools\bin\osquery.zip" $clientPath $daemonPath $certs $conf $packs $mgmtScript
  Write-Debug "[+] Creating the chocolatey package for osquery $version"
  Set-Location "$osqueryChocoPath"
  choco pack

  Write-Host "[+] Chocolatey Package has been created. Run 'choco push' to push the package to Chocolatey" -ForegroundColor Green
}

$null = Main


text:
package utils

import (
	"crypto"
	cryptorand "crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math"
	"math/big"
	"time"

	certutil "k8s.io/client-go/util/cert"
)

const (
	certificateBlockType = "CERTIFICATE"
	rsaKeySize           = 2048
	duration365d         = time.Hour * 24 * 365
)

// NewPrivateKey creates an RSA private key
func NewPrivateKey() (*rsa.PrivateKey, error) {
	return rsa.GenerateKey(cryptorand.Reader, rsaKeySize)
}

// EncodeCertPEM returns PEM-endcoded certificate data
func EncodeCertPEM(cert *x509.Certificate) []byte {
	block := pem.Block{
		Type:  certificateBlockType,
		Bytes: cert.Raw,
	}
	return pem.EncodeToMemory(&block)
}

// NewSignedCert creates a signed certificate using the given CA certificate and key
func NewSignedCert(cfg *certutil.Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
	serial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}
	if len(cfg.CommonName) == 0 {
		return nil, fmt.Errorf("must specify a CommonName")
	}
	if len(cfg.Usages) == 0 {
		return nil, fmt.Errorf("must specify at least one ExtKeyUsage")
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: cfg.Organization,
		},
		DNSNames:     cfg.AltNames.DNSNames,
		IPAddresses:  cfg.AltNames.IPs,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(duration365d).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  cfg.Usages,
	}
	certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}