text:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using Oracle.RightNow.Toa.Client.Common;
using Oracle.RightNow.Toa.Client.InboundProxyService;

namespace Oracle.RightNow.Toa.Client.Model
{
    /// <summary>
    /// Model class for Activity
    /// </summary>
    public class WorkOrderModel : ToaModel
    {
        /// <summary>
        /// These three fields are for creating the command object for this workorder
        /// </summary>
        private string _assignedDate;
        private string _resourceId;
        private ActivityCommandType _commandType;

        private string _fallbackResourceId;
        private string _positionInRoute;
        private string _address;
        private string _apptNumber;
        private string _cell;
        private string _city;
        private string _coordinateX;
        private string _coordinateY;
        private string _customerNumber;
        private string _email;
        private string _duration;
        private string _language;
        private string _name;
        private int? _points;
        private string _phone;
        private int? _reminderTime;
        private string _serviceWindowStart;
        private string _serviceWindowEnd;
        private DateTime? _slaWindowStart;
        private DateTime? _slaWindowEnd;
        private string _state;
        private string _teamId;
        private string _timeSlot;
        private string _timeZone;
        private string _workType;
        private string _workTypeLabel;
        private string _zip;
        private string _cancelReason;
        private List<InventoryModel> _inventories;
        private List<RequiredInventoryModel> _requiredInventories;
        private List<ProviderPreferenceModel> _providerPreferences;
        private ActivityStatus _status;
        private ActionIfCompleted _actionIfCompleted;

        //Response Field
        private int? _aid;

        public WorkOrderModel()
        {
            // _assignedDate = DateTime.Now.ToString("yyyy-MM-dd");
            // _resourceId = "";
            // _fallbackResourceId = "";
            // _positionInRoute = "";
            // _address = "";
            // _apptNumber = "";
            // _cell = "";
            // _city = "";
            // _customerNumber = "";
            // _email = "";
            // _duration = "";
            // _language = "";
            // _name = "";
            // _phone = "";
            // _serviceWindowStart = "";
            // _serviceWindowEnd = "";
            // _slaWindowStart = DateTime.Now;
            // _slaWindowEnd = DateTime.Now;
            // _state = "";
            // _teamId = "";
            // _timeSlot = false;
            // _timeZone = "";
            // _workType = "";
            // _workTypeLabel = "";
            // _zip = "";
            // _inventories = new List<InventoryModel>();
            // _requiredInventories = new List<RequiredInventoryModel>();
            //_providerPreferences = new List<ProviderPreferenceModel>();
            _status = ActivityStatus.Pending;
            //_commandType = ActivityCommandType.Update;
            //_actionIfCompleted = ActionIfCompleted.CreateIfAssignOrReschedule;
        }

        /// <summary>
        /// Required Inventories
        /// </summary>
        public List<RequiredInventoryModel> RequiredInventories
        {
            get { return _requiredInventories; }
            set { _requiredInventories = value; }
        }

        /// <summary>
        /// List of Provder preferences
        /// </summary>
        public List<ProviderPreferenceModel> ProviderPreferences
        {
            get { return _providerPreferences; }
            set { _providerPreferences = value; }
        }

        /// <summary>
        /// Inventories for Activity
        /// </summary>
        public List<InventoryModel> ActivityInventories
        {
            get { return _inventories; }
            set { _inventories = value; }
        }

        /// <summary>
        /// Cancel Reason
        /// </summary>
        public string CancelReason
        {
            get { return _cancelReason; }
            set { _cancelReason = value; }
        }

        /// <summary>
        /// Zip Code / Pin Code
        /// </summary>
        public string ZipCode
        {
            get { return _zip; }
            set { _zip = value; }
        }

        /// <summary>
        /// SLA Window End (YYYY-MM-DD HH:MM)
        /// </summary>
        public DateTime? SlaWindowEnd
        {
            get { return _slaWindowEnd; }
            set { _slaWindowEnd = value; }
        }

        /// <summary>
        /// SLA Window Start (YYYY-MM-DD HH:MM)
        /// </summary>
        public DateTime? SlaWindowStart
        {
            get { return _slaWindowStart; }
            set { _slaWindowStart = value; }
        }

        /// <summary>
        /// Work Type
        /// </summary>
        public string WorkType
        {
            get { return _workType; }
            set { _workType = value; }
        }

        /// <summary>
        /// Work Label
        /// </summary>
        public string WorkLabel
        {
            get { return _workTypeLabel; }
            set { _workTypeLabel = value; }
        }

        /// <summary>
        /// Time Zone
        /// </summary>
        public string TimeZone
        {
            get { return _timeZone; }
            set { _timeZone = value; }
        }

        /// <summary>
        /// Time Slot
        /// </summary>
        public String TimeSlot
        {
            get { return _timeSlot; }
            set { _timeSlot = value; }
        }

        /// <summary>
        /// Team Id
        /// </summary>
        public string TeamId
        {
            get { return _teamId; }
            set { _teamId = value; }
        }

        /// <summary>
        /// State
        /// </summary>
        public string State
        {
            get { return _state; }
            set { _state = value; }
        }

        /// <summary>
        /// Service Window End (HH:MM)
        /// </summary>
        public string ServiceWindowEnd
        {
            get { return _serviceWindowEnd; }
            set { _serviceWindowEnd = value; }
        }

        /// <summary>
        /// Service Window start (HH:MM)
        /// </summary>
        public string ServiceWindowStart
        {
            get { return _serviceWindowStart; }
            set { _serviceWindowStart = value; }
        }

        /// <summary>
        /// Reminder Time
        /// </summary>
        public int? ReminderTime
        {
            get { return _reminderTime; }
            set { _reminderTime = value; }
        }

        /// <summary>
        /// Phone Number
        /// </summary>
        public string PhoneNumber
        {
            get { return _phone; }
            set { _phone = value; }
        }

        /// <summary>
        /// Points
        /// </summary>
        public int? Points
        {
            get { return _points; }
            set { _points = value; }
        }

        /// <summary>
        /// Name - Customer Name
        /// </summary>
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// Language
        /// </summary>
        public string Language
        {
            get { return _language; }
            set { _language = value; }
        }

        /// <summary>
        /// Duration - 'length' of activity in minutes
        /// </summary>
        public string Duration
        {
            get { return _duration; }
            set { _duration = value; }
        }

        /// <summary>
        /// Email Address
        /// </summary>
        public string EmailAddress
        {
            get { return _email; }
            set { _email = value; }
        }

        /// <summary>
        /// Customer Number
        /// </summary>
        public string CustomerNumber
        {
            get { return _customerNumber; }
            set { _customerNumber = value; }
        }

        /// <summary>
        /// Longitude of customer location
        /// </summary>
        public string CoordinateX
        {
            get { return _coordinateX; }
            set { _coordinateX = value; }
        }

        /// <summary>
        /// Latitude of customer location
        /// </summary>
        public string CoordinateY
        {
            get { return _coordinateY; }
            set { _coordinateY = value; }
        }

        /// <summary>
        /// City (Todo: should be max 40 characters long.)
        /// </summary>
        public string City
        {
            get { return _city; }
            set { _city = value; }
        }

        /// <summary>
        /// Mobile Number (Todo: should be valid mobile number)
        /// </summary>
        public string MobileNumber
        {
            get { return _cell; }
            set { _cell = value; }
        }

        /// <summary>
        /// Appointment Number (Todo: Max character are 40 only)
        /// </summary>
        public string AppointmentNumber
        {
            get { return _apptNumber; }
            set { _apptNumber = value; }
        }

        /// <summary>
        /// Address (Todo: Max character are 100 only)
        /// </summary>
        public string Address
        {
            get { return _address; }
            set { _address = value; }
        }

        /// <summary>
        /// Date to which activity is to be assigned in YYYY-MM-DD formate only
        /// </summary>
        public string AssignedDate
        {
            get { return _assignedDate; }
            set { _assignedDate = value; }
        }

        /// <summary>
        /// External ID of the resource to which the activity is to be assigned
        /// </summary>
        public string ExternalId
        {
            get { return _resourceId; }
            set { _resourceId = value; }
        }

        /// <summary>
        /// External ID of the resource to which the activity is to be assigned
        /// </summary>
        public string FallbackExternalId
        {
            get { return _fallbackResourceId; }
            set { _fallbackResourceId = value; }
        }

        /// <summary>
        /// ID of the activity followed by the activity to be created
        /// </summary>
        public string PositionInRoute
        {
            get { return _positionInRoute; }
            set { _positionInRoute = value; }
        }

        public ActivityStatus Status
        {
            get { return _status; }
            set { _status = value; }
        }

        public ActivityCommandType CommandType
        {
            get { return _commandType; }
            set { _commandType = value; }
        }

        public String Cell { get { return _cell; } set { _cell = value; } }

        public ActionIfCompleted SetActionIfCompleted
        {
            get { return _actionIfCompleted; }
            set { _actionIfCompleted = value; }

        }

        /// <summary>
        ///
        /// </summary>
        public int? TOA_AID
        {
            get { return _aid; }
            set { _aid = value; }
        }

        ///
        /// This method is only used within toa client to create AppointmentElement object
        ///
        internal AppointmentElement GetActivityElement()
        {
            var activity = new AppointmentElement();
            //key fields
            activity.customer_number = _customerNumber;
            activity.appt_number = _apptNumber;
            //mandatory fields
            activity.worktype = _workType;
            //Other fields
            if (null != _name)
                activity.name = _name;

            activity.action_if_completed = ToaStringsUtil.GetString(_actionIfCompleted);

            if (null != _address)
                activity.address = _address;

            if (null != _cell)
                activity.cell = _cell;

            if (null != _city)
                activity.city = _city;

            if (null != _coordinateX)
                activity.coordx = _coordinateX;

            if (null != _coordinateY)
                activity.coordy = _coordinateY;

            if (null != _email)
                activity.email = _email;

            if (null != _duration)
                activity.duration = _duration;

            if (null != _language)
                activity.language = _language;

            if (null != _points)
                activity.points = _points.ToString();

            if (null != _phone)
                activity.phone = _phone;

            if (null != _reminderTime)
                activity.reminder_time = _reminderTime.ToString();

            if (null != _serviceWindowStart)
                activity.service_window_start = _serviceWindowStart;

            if (null != _serviceWindowEnd)
                activity.service_window_end = _serviceWindowEnd;

            //if(null != _slaWindowStart)
            //    activity.sla_window_start = _slaWindowStart.ToString("yyyy'-'MM'-'dd HH':'mm");

            if (null != _slaWindowEnd)
            {
                activity.sla_window_end = ((DateTime)_slaWindowEnd).ToString("yyyy'-'MM'-'dd HH':'mm");

                //Below 2 null checks and fix is required as ETA is not behaving correctly.
                //If it has sla_window_end parameter then it should override the date and timeslot as mandatory fields in Inbound Request.
                //But it is not doing so, hence we are explictly required to send TimeSlot and Date.
                //If we do not provide them and if they are empty then activity creation fails in ETA.
                if (null == TimeSlot)
                {
                    TimeSlot = ActivityProperty.ALL_DAY_TIME_SLOT_LABEL;
                }
                if (null == AssignedDate)
                {
                    AssignedDate = "";
                }
            }

            if (null != _state)
                activity.state = _state;

            if (null != _teamId)
                activity.team_id = _teamId;

            if (null != _timeSlot)
                activity.time_slot = _timeSlot;

            if (null != _timeZone)
                activity.time_zone = _timeZone;
            //activity.worktype = _workType;
            //Below code is for using worktype label. We plan to use only WorkType and not the label.
            //if (null != _workTypeLabel)
            //    activity.worktype_label = _workTypeLabel;

            if (null != _zip)
                activity.zip = _zip;

            // Activity Properties
            if (null != Properties)
            {
                var noOfInventories = Properties.Count;
                var propertyElements = new PropertyElement[noOfInventories];
                foreach (var property in Properties)
                {
                    var propertyElement = new PropertyElement();
                    propertyElement.label = property.Key;
                    propertyElement.value = property.Value;
                    propertyElements[--noOfInventories] = propertyElement;
                }
                activity.properties = propertyElements;
            }

            // Activity Inventories
            if (null != _inventories)
            {
                var noOfInventories = _inventories.Count;
                var inventoryElements = new InventoryElement[noOfInventories];
                foreach (var inventoryModel in _inventories)
                {
                    var inventoryElement = inventoryModel.GetInventoryElement();
                    inventoryElements[--noOfInventories] = inventoryElement;
                }
                activity.inventories = inventoryElements;
            }

            // Preference Provideres
            if (null != _providerPreferences)
            {
                var noOfProviders = _providerPreferences.Count;
                var providers = new ProviderPreferenceElement[noOfProviders];
                foreach (var providerModel in _providerPreferences)
                {
                    var ProviderPreferenceElement = providerModel.GetProviderPreferenceElement();
                    providers[--noOfProviders] = ProviderPreferenceElement;
                }
                activity.provider_preferences = providers;
            }

            // Required Inventories
            if (null != _requiredInventories && _requiredInventories.Count > 0)
            {
                var noOfRequiedInventories = _requiredInventories.Count;
                var requiredInventoryElements = new RequiredInventoryElement[noOfRequiedInventories];
                foreach (var requiredInventoryModel in _requiredInventories)
                {
                    var requiredInventory = requiredInventoryModel.GetRequiredInventoryElement();
                    requiredInventoryElements[--noOfRequiedInventories] = requiredInventory;
                }
                activity.required_inventories = requiredInventoryElements;
            }
            if (null != UserData && UserData.Trim().Length > 0)
            {
                activity.userdata = UserData;
            }

            return activity;
        }

    }
}


text:
"""Installs/Configures Cassandra.

See 'perfkitbenchmarker/data/cassandra/' for configuration files used.

Cassandra homepage: http://cassandra.apache.org
"""

import logging
import os
import posixpath
import time

from perfkitbenchmarker import data
from perfkitbenchmarker import errors
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.packages.ant import ANT_HOME_DIR

JNA_JAR_URL = ('https://maven.java.net/content/repositories/releases/'
               'net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar')
CASSANDRA_GIT_REPRO = 'https://github.com/apache/cassandra.git'
CASSANDRA_VERSION = 'cassandra-2.1.10'
CASSANDRA_YAML_TEMPLATE = 'cassandra/cassandra.yaml.j2'
CASSANDRA_ENV_TEMPLATE = 'cassandra/cassandra-env.sh.j2'
CASSANDRA_DIR = posixpath.join(vm_util.VM_TMP_DIR, 'cassandra')
CASSANDRA_PID = posixpath.join(CASSANDRA_DIR, 'cassandra.pid')
CASSANDRA_OUT = posixpath.join(CASSANDRA_DIR, 'cassandra.out')
CASSANDRA_ERR = posixpath.join(CASSANDRA_DIR, 'cassandra.err')
NODETOOL = posixpath.join(CASSANDRA_DIR, 'bin', 'nodetool')

# Number of times to attempt to start the cluster.
CLUSTER_START_TRIES = 10
CLUSTER_START_SLEEP = 120
# Time, in seconds, to sleep between node starts.
NODE_START_SLEEP = 30

def CheckPrerequisites():
  """Verifies that the required resources are present.

  Raises:
    perfkitbenchmarker.data.ResourceNotFound: On missing resource.
  """
  for resource in (CASSANDRA_YAML_TEMPLATE,
                   CASSANDRA_ENV_TEMPLATE):
    data.ResourcePath(resource)

def _Install(vm):
  """Installs Cassandra from a tarball."""
  vm.Install('ant')
  vm.Install('build_tools')
  vm.Install('openjdk7')
  vm.Install('curl')
  vm.RemoteCommand(
      'cd {0}; git clone {1}; cd {2}; git checkout {3}; {4}/bin/ant'.format(
          vm_util.VM_TMP_DIR,
          CASSANDRA_GIT_REPRO,
          CASSANDRA_DIR,
          CASSANDRA_VERSION,
          ANT_HOME_DIR))
  # Add JNA
  vm.RemoteCommand('cd {0} && curl -LJO {1}'.format(
      posixpath.join(CASSANDRA_DIR, 'lib'),
      JNA_JAR_URL))

def YumInstall(vm):
  """Installs Cassandra on the VM."""
  _Install(vm)

def AptInstall(vm):
  """Installs Cassandra on the VM."""
  _Install(vm)

def Configure(vm, seed_vms):
  """Configure Cassandra on 'vm'.

  Args:
    vm: VirtualMachine. The VM to configure.
    seed_vms: List of VirtualMachine. The seed virtual machine(s).
  """
  context = {'ip_address': vm.internal_ip,
             'data_path': posixpath.join(vm.GetScratchDir(), 'cassandra'),
             'seeds': ','.join(vm.internal_ip for vm in seed_vms),
             'num_cpus': vm.num_cpus,
             'cluster_name': 'Test cluster'}

  for config_file in [CASSANDRA_ENV_TEMPLATE, CASSANDRA_YAML_TEMPLATE]:
    local_path = data.ResourcePath(config_file)
    remote_path = posixpath.join(
        CASSANDRA_DIR, 'conf',
        os.path.splitext(os.path.basename(config_file))[0])
    vm.RenderTemplate(local_path, remote_path, context=context)

def Start(vm):
  """Start Cassandra on a VM.

  Args:
    vm: The target vm. Should already be configured via 'Configure'.
  """
  vm.RemoteCommand(
      'nohup {0}/bin/cassandra -p "{1}" 1> {2} 2> {3} &'.format(
          CASSANDRA_DIR, CASSANDRA_PID, CASSANDRA_OUT, CASSANDRA_ERR))

def Stop(vm):
  """Stops Cassandra on 'vm'."""
  vm.RemoteCommand('kill $(cat {0})'.format(CASSANDRA_PID),
                   ignore_failure=True)

def IsRunning(vm):
  """Returns a boolean indicating whether Cassandra is running on 'vm'."""
  cassandra_pid = vm.RemoteCommand(
      'cat {0} || true'.format(CASSANDRA_PID))[0].strip()
  if not cassandra_pid:
    return False

  try:
    vm.RemoteCommand('kill -0 {0}'.format(cassandra_pid))
    return True
  except errors.VirtualMachine.RemoteCommandError:
    logging.warn('%s: Cassandra is not running. '
                 'Startup STDOUT:\n%s\n\nSTDERR:\n%s',
                 vm,
                 vm.RemoteCommand('cat ' + CASSANDRA_OUT),
                 vm.RemoteCommand('cat ' + CASSANDRA_ERR))
    return False

def CleanNode(vm):
  """Remove Cassandra data from 'vm'.

  Args:
    vm: VirtualMachine. VM to clean.
  """
  data_path = posixpath.join(vm.GetScratchDir(), 'cassandra')
  vm.RemoteCommand('rm -rf {0}'.format(data_path))

def _StartCassandraIfNotRunning(vm):
  """Starts Cassandra on 'vm' if not currently running."""
  if not IsRunning(vm):
    logging.info('Retrying starting cassandra on %s', vm)
    Start(vm)

def GetNumberOfNodesUp(vm):
  """Gets the number of VMs which are up in a Cassandra cluster.

  Args:
    vm: VirtualMachine. The VM to use to check the cluster status.
  """
  vms_up = vm.RemoteCommand(
      '{0} status | grep -c "^UN"'.format(NODETOOL))[0].strip()
  return int(vms_up)

def StartCluster(seed_vm, vms):
  """Starts a Cassandra cluster.

  Starts a Cassandra cluster, first starting 'seed_vm', then remaining VMs in
  'vms'.

  Args:
    seed_vm: VirtualMachine. Machine which will function as the sole seed. It
      will be started before all other VMs.
    vms: list of VirtualMachines. VMs *other than* seed_vm which should be
      started.
  """
  vm_count = len(vms) + 1

  # Cassandra setup
  logging.info('Starting seed VM %s', seed_vm)
  Start(seed_vm)
  logging.info('Waiting %ds for seed to start', NODE_START_SLEEP)
  time.sleep(NODE_START_SLEEP)
  for i in xrange(5):
    if not IsRunning(seed_vm):
      logging.warn('Seed %s: Cassandra not running yet (try %d). Waiting %ds.',
                   seed_vm, i, NODE_START_SLEEP)
      time.sleep(NODE_START_SLEEP)
    else:
      break
  else:
    raise ValueError('Cassandra failed to start on seed.')

  if vms:
    # Start the VMs with a small pause in between each, to allow the node to
    # join.
    # Starting Cassandra nodes fails when multiple nodes attempt to join the
    # cluster concurrently.
    for i, vm in enumerate(vms):
      time.sleep(NODE_START_SLEEP)
      logging.info('Starting non-seed VM %d/%d.', i + 1, len(vms))
      Start(vm)
    logging.info('Waiting %ds for nodes to join', CLUSTER_START_SLEEP)
    time.sleep(CLUSTER_START_SLEEP)

  for i in xrange(CLUSTER_START_TRIES):
    vms_up = GetNumberOfNodesUp(seed_vm)
    if vms_up == vm_count:
      logging.info('All %d nodes up!', vm_count)
      break

    logging.warn('Try %d: only %s of %s up. Sleeping %ds', i, vms_up,
                 vm_count, NODE_START_SLEEP)
    vm_util.RunThreaded(_StartCassandraIfNotRunning, vms)
    time.sleep(NODE_START_SLEEP)
  else:
    raise IOError('Failed to start Cassandra cluster.')

redpajama_set_name: RedPajamaGithub


text:
<rapi:rule xmlns:rapi="http://marklogic.com/rest-api">
  <rapi:name>RULE-TEST-2</rapi:name>
  <rapi:description>rule for test2</rapi:description>
  <search:search xmlns:search="http://marklogic.com/appservices/search">
    <search:query>
   	  <search:range-constraint-query>
   	    <search:constraint-name>date</search:constraint-name>
   	    <search:value>2005-01-01</search:value>
   	  </search:range-constraint-query>
	</search:query>
    <search:options>
      <search:constraint name="date">
        <search:range type="xs:date" facet="false">
          <search:element ns="http://purl.org/dc/elements/1.1/" name="date"/>
        </search:range>
      </search:constraint>
    </search:options>
  </search:search>
  <rapi:rule-metadata>
    <rule-number>two</rule-number>
  </rapi:rule-metadata>
</rapi:rule>


text:
package OpenXPKI::Server::Workflow::Condition::HasRole;

use strict;
use warnings;
use base qw( Workflow::Condition );
use Workflow::Exception qw( condition_error configuration_error );
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Debug;
use English;

__PACKAGE__->mk_accessors( 'expected_roles' );

sub _init
{
    my ( $self, $params ) = @_;
    unless ( $params->{roles} )
    {
        configuration_error
             "You must define one value for 'role' in ",
             "declaration of condition ", $self->name;
    }
    $self->expected_roles($params->{roles});
}

sub evaluate
{
    ##! 64: 'start'
    my ( $self, $wf ) = @_;
    my $context = $wf->context();

    my $expected_roles = $self->expected_roles();
    ##! 64: 'expected role: ' . $expected_roles
    if (not $expected_roles)
    {
        ## this is a critical event because we don't know what to verify
        my $errors = [[ 'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_HASROLE_NO_ROLE' ]];
        $context->param ("__error" => $errors);
        configuration_error ($errors->[0]);
    }

    my $session_role = CTX('session')->data->role || '';

    my %roles = map { $_ => 1 } (split /,\s*/, $expected_roles);

    ##! 64: 'session role: ' . $session_role

    condition_error ("$session_role mismatches $expected_roles") unless ($roles{$session_role});

    return 1;
}

1;

__END__

=head1 NAME

OpenXPKI::Server::Workflow::Condition::HasRole

=head1 SYNOPSIS

    class: OpenXPKI::Server::Workflow::Condition::HasRole
    param:
        roles: CA Operator,RA Operator

=head1 DESCRIPTION

The condition checks if the current session users role is in the list
of expected roles given as parameter in the configuration.
Multiple roles can be given as comma seperated list.


text:
<?php
namespace test\helpers\cases;

/**
 * Custom testcase covering common functionality of tests for routecontrollers
 */
abstract class RouteController extends Base
{
    /**
     * List of all class methods which have an assigned regex route
     * @var array
     */
    protected $routedMethods = [];

    protected function setUp()
    {
        $mockedMethods = [
            'standardView',//implemented by parent
            'standardAction',//implemented by parent
        ];
        $this->testObj = $this->getMockBuilder($this->testedClass)
                              ->disableOriginalConstructor()
                              ->setMethods($mockedMethods)
                              ->getMock();

        $this->createRoutedMethodsList();
    }

    /**
     * Generates routedMethods
     *
     * @return void
     */
    protected function createRoutedMethodsList()
    {
        $routes = $this->readAttribute($this->testObj, 'routes');
        $get = (isset($routes['get'])) ? array_values($routes['get']) : [];
        $post = (isset($routes['post'])) ? array_values($routes['post']) : [];
        $this->routedMethods = array_merge($get, $post);
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module OpenRTB.Types.Enum.ConnectionTypeSpec where

import Control.Applicative
import Data.Aeson
import Data.Aeson.TH
import Test.Hspec
import Test.QuickCheck

import Test.Instances
import OpenRTB.Types.Enum.ConnectionType

data Mock = Mock { ct :: ConnectionType } deriving (Eq, Show)
$(deriveJSON defaultOptions ''Mock)

main :: IO ()
main = hspec spec

spec :: Spec
spec = describe "ConnectionType" $ do
  context "JSON" $ do
    it "should convert back and forth" $ property $ do
       \m -> (decode . encode) m == Just (m :: Mock)

instance Arbitrary Mock where
  arbitrary = Mock <$> arbitrary


text: Cross Country Matchup Tester


text:
<!-- Component version: 1.0.0 -->

<!-- HTML -->
<div class="container">
	Welcome to {name}!
</div>

<!-- CSS -->
<style>

	/* Google Fonts Example */
	@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:200');

	.container {
		height: 50vw;
	}

	.container {
		display: flex;
		align-items: center;
		justify-content: center;

		font-family: 'Source Sans Pro', sans-serif;
		font-size: 5rem;
		color: #b8af9e;
	}

</style>

<!-- Javascript -->
<script>

	export default {

		data () {
			return {
				name: 'Altiva'
			}
		}

	}

</script>


text:
using NUnit.Framework;

namespace PCExpert.Core.Domain.Tests
{
	[TestFixture]
	public class NullComponentInterfaceTests
	{
		[Test]
		public void NullInterface_ShouldReturnComponentInterfaceWithEmptyProperties()
		{
			//Arrange
			var nullInterface = ComponentInterface.NullObject;

			//Assert
			Assert.That(nullInterface.Name, Is.EqualTo(string.Empty));
		}
	}
}


text:
pthread_t childThreads[NUM_CHILD_THREADS];

// Note the pointer * to function name as well as argument
void *printMessages(void *arg)
{
	long tid;
	tid = (long)arg;

	int sleepValue;
	for(int m=1; m<=NUM_OF_PRINTS; m++)
	{
		sleepValue = 3 + rand() % 10;// value between 3 and 13 seconds
		printf("I'm in thread number %3ld - message num %2d - sleep for %2d\n",tid, m, sleepValue);
		// below function takes microseconds
		usleep(sleepValue * 1000 * 1000);
	}
	// We can simply return or explicitly call the below function
	// pthread_exit((void *)arg);
}

// This function creates the child threads and also joins them to the main thread
void createChildThreads()
{
	int rc;
	int t;

	// Initialize the thread to be joinable
	pthread_attr_t attribute;
	pthread_attr_init(&attribute);
	pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE);
	// Start creating the child threads
	for(t=0; t<NUM_CHILD_THREADS; t++)
	{
		rc = pthread_create(&childThreads[t], &attribute, printMessages, (void *)t+1);
		if(rc)
		{
			printf("Error creating thread %2d : return code %2d\n", t, rc);
			return;
		}
	}
	// Free up the attribute
	pthread_attr_destroy(&attribute);

	// Start joining the threads
	// NOTE only one thread can be joined at a time
	void *status;
	for(t=0; t<NUM_CHILD_THREADS; t++)
	{
		printf("*** Joining thread %d ***\n", t+1);
		rc = pthread_join(childThreads[t], &status);
		if(rc)
		{
			printf("Error joining thread %2d : return code %2d\n", t+1, rc);
		}
		printf("Completed Join thread %2d : return status %2ld\n", t+1, (long)status);
	}
}

// the main function to this process
int main(int argc, char *argv[])
{
	printf("Main program starting %s\n", "jaggi");
	createChildThreads();
	printf("Main program exiting %s\n", "jaggi");
	return 0;
}


text:
class WebRTCInternalsIntegrationBrowserTest;

namespace content {
class BrowserContext;
class NetworkConnectionTracker;
}  // namespace content

namespace webrtc_event_logging {

// This is a singleton class running in the browser UI thread (ownership of
// the only instance lies in BrowserContext). It is in charge of writing WebRTC
// event logs to temporary files, then uploading those files to remote servers,
// as well as of writing the logs to files which were manually indicated by the
// user from the WebRTCIntenals. (A log may simulatenously be written to both,
// either, or none.)
// The only instance of this class is owned by BrowserProcessImpl. It is
// destroyed from ~BrowserProcessImpl(), at which point any tasks posted to the
// internal SequencedTaskRunner, or coming from another thread, would no longer
// execute.
class WebRtcEventLogManager final : public content::RenderProcessHostObserver,
                                    public content::WebRtcEventLogger,
                                    public WebRtcLocalEventLogsObserver,
                                    public WebRtcRemoteEventLogsObserver {
 public:
  using BrowserContextId = WebRtcEventLogPeerConnectionKey::BrowserContextId;

  // To turn WebRTC on and off, we go through PeerConnectionTrackerProxy. In
  // order to make this toggling easily testable, PeerConnectionTrackerProxyImpl
  // will send real messages to PeerConnectionTracker, whereas
  // PeerConnectionTrackerProxyForTesting will be a mock that just makes sure
  // the correct messages were attempted to be sent.
  class PeerConnectionTrackerProxy {
   public:
    virtual ~PeerConnectionTrackerProxy() = default;

    virtual void EnableWebRtcEventLogging(
        const WebRtcEventLogPeerConnectionKey& key,
        int output_period_ms) = 0;

    virtual void DisableWebRtcEventLogging(
        const WebRtcEventLogPeerConnectionKey& key) = 0;
  };

  // Ensures that no previous instantiation of the class was performed, then
  // instantiates the class and returns the object (ownership is transfered to
  // the caller). Subsequent calls to GetInstance() will return this object,
  // until it is destructed, at which pointer nullptr will be returned by
  // subsequent calls.
  static std::unique_ptr<WebRtcEventLogManager> CreateSingletonInstance();

  // Returns the object previously constructed using CreateSingletonInstance(),
  // if it was constructed and was not yet destroyed; nullptr otherwise.
  static WebRtcEventLogManager* GetInstance();

  // Given a BrowserContext, return the path to the directory where its
  // remote-bound event logs are kept.
  // Since incognito sessions don't have such a directory, an empty
  // base::FilePath will be returned for them.
  static base::FilePath GetRemoteBoundWebRtcEventLogsDir(
      content::BrowserContext* browser_context);

  ~WebRtcEventLogManager() override;

  void EnableForBrowserContext(content::BrowserContext* browser_context,
                               base::OnceClosure reply);

  void DisableForBrowserContext(content::BrowserContext* browser_context,
                                base::OnceClosure reply);

  void PeerConnectionAdded(int render_process_id,
                           int lid,  // Renderer-local PeerConnection ID.
                           base::OnceCallback<void(bool)> reply) override;

  void PeerConnectionRemoved(int render_process_id,
                             int lid,  // Renderer-local PeerConnection ID.
                             base::OnceCallback<void(bool)> reply) override;

  // From the logger's perspective, we treat stopping a peer connection the
  // same as we do its removal. Should a stopped peer connection be later
  // removed, the removal callback will assume the value |false|.
  void PeerConnectionStopped(int render_process_id,
                             int lid,  // Renderer-local PeerConnection ID.
                             base::OnceCallback<void(bool)> reply) override;

  void PeerConnectionSessionIdSet(
      int render_process_id,
      int lid,
      const std::string& session_id,
      base::OnceCallback<void(bool)> reply) override;

  // The file's actual path is derived from |base_path| by adding a timestamp,
  // the render process ID and the PeerConnection's local ID.
  void EnableLocalLogging(const base::FilePath& base_path,
                          base::OnceCallback<void(bool)> reply) override;
  void EnableLocalLogging(const base::FilePath& base_path,
                          size_t max_file_size_bytes,
                          base::OnceCallback<void(bool)> reply);

  void DisableLocalLogging(base::OnceCallback<void(bool)> reply) override;

  void OnWebRtcEventLogWrite(
      int render_process_id,
      int lid,  // Renderer-local PeerConnection ID.
      const std::string& message,
      base::OnceCallback<void(std::pair<bool, bool>)> reply) override;

  // Start logging a peer connection's WebRTC events to a file, which will
  // later be uploaded to a remote server. If a reply is provided, it will be
  // posted back to BrowserThread::UI with the log-identifier (if successful)
  // of the created log or (if unsuccessful) the error message.
  // See the comment in  WebRtcRemoteEventLogManager::StartRemoteLogging for
  // more details.
  void StartRemoteLogging(
      int render_process_id,
      const std::string& session_id,
      size_t max_file_size_bytes,
      int output_period_ms,
      size_t web_app_id,
      base::OnceCallback<void(bool, const std::string&, const std::string&)>
          reply);

  // Clear WebRTC event logs associated with a given browser context, in a given
  // time range (|delete_begin| inclusive, |delete_end| exclusive), then
  // post |reply| back to the thread from which the method was originally
  // invoked (which can be any thread).
  void ClearCacheForBrowserContext(
      const content::BrowserContext* browser_context,
      const base::Time& delete_begin,
      const base::Time& delete_end,
      base::OnceClosure reply);

  // Get the logging history (relevant only to remote-bound logs). This includes
  // information such as when logs were captured, when they were uploaded,
  // and what their ID in the remote server was.
  // Must be called on the UI thread.
  // The results to the query are posted using |reply| back to the UI thread.
  // If |browser_context_id| is not the ID a profile for which remote-bound
  // logging is enabled, an empty list is returned.
  // The returned vector is sorted by capture time in ascending order.
  void GetHistory(
      BrowserContextId browser_context_id,
      base::OnceCallback<void(const std::vector<UploadList::UploadInfo>&)>
          reply);

  // Set (or unset) an observer that will be informed whenever a local log file
  // is started/stopped. The observer needs to be able to either run from
  // anywhere. If you need the code to run on specific runners or queues, have
  // the observer post them there.
  // If a reply callback is given, it will be posted back to BrowserThread::UI
  // after the observer has been set.
  void SetLocalLogsObserver(WebRtcLocalEventLogsObserver* observer,
                            base::OnceClosure reply);

  // Set (or unset) an observer that will be informed whenever a remote log file
  // is started/stopped. Note that this refers to writing these files to disk,
  // not for uploading them to the server.
  // The observer needs to be able to either run from anywhere. If you need the
  // code to run on specific runners or queues, have the observer post
  // them there.
  // If a reply callback is given, it will be posted back to BrowserThread::UI
  // after the observer has been set.
  void SetRemoteLogsObserver(WebRtcRemoteEventLogsObserver* observer,
                             base::OnceClosure reply);

 private:
  friend class WebRtcEventLogManagerTestBase;
  friend class ::WebRTCInternalsIntegrationBrowserTest;

  using PeerConnectionKey = WebRtcEventLogPeerConnectionKey;

  // This bitmap allows us to track for which clients (local/remote logging)
  // we have turned WebRTC event logging on for a given peer connection, so that
  // we may turn it off only when the last client no longer needs it.
  enum LoggingTarget : unsigned int {
    kLocalLogging = 1 << 0,
    kRemoteLogging = 1 << 1
  };
  using LoggingTargetBitmap = std::underlying_type<LoggingTarget>::type;

  WebRtcEventLogManager();

  bool IsRemoteLoggingAllowedForBrowserContext(
      content::BrowserContext* browser_context) const;

  // Determines the exact subclass of LogFileWriter::Factory to be used for
  // producing remote-bound logs.
  std::unique_ptr<LogFileWriter::Factory> CreateRemoteLogFileWriterFactory();

  // RenderProcessHostObserver implementation.
  void RenderProcessExited(
      content::RenderProcessHost* host,
      const content::ChildProcessTerminationInfo& info) override;
  void RenderProcessHostDestroyed(content::RenderProcessHost* host) override;

  // RenderProcessExited() and RenderProcessHostDestroyed() treated similarly
  // by this function.
  void RenderProcessHostExitedDestroyed(content::RenderProcessHost* host);

  // WebRtcLocalEventLogsObserver implementation:
  void OnLocalLogStarted(PeerConnectionKey peer_connection,
                         const base::FilePath& file_path) override;
  void OnLocalLogStopped(PeerConnectionKey peer_connection) override;

  // WebRtcRemoteEventLogsObserver implementation:
  void OnRemoteLogStarted(PeerConnectionKey key,
                          const base::FilePath& file_path,
                          int output_period_ms) override;
  void OnRemoteLogStopped(PeerConnectionKey key) override;

  void OnLoggingTargetStarted(LoggingTarget target,
                              PeerConnectionKey key,
                              int output_period_ms);
  void OnLoggingTargetStopped(LoggingTarget target, PeerConnectionKey key);

  void StartListeningForPrefChangeForBrowserContext(
      content::BrowserContext* browser_context);
  void StopListeningForPrefChangeForBrowserContext(
      content::BrowserContext* browser_context);

  void OnPrefChange(content::BrowserContext* browser_context);

  // network_connection_tracker() is not available during instantiation;
  // we get it when the first profile is loaded, which is also the earliest
  // time when it could be needed.
  // The LogFileWriter::Factory is similarly deferred, but for a different
  // reason - it makes it easier to allow unit tests to inject their own.
  // OnFirstBrowserContextLoaded() is on the UI thread.
  // OnFirstBrowserContextLoadedInternal() is the task sent to |task_runner_|.
  void OnFirstBrowserContextLoaded();
  void OnFirstBrowserContextLoadedInternal(
      network::NetworkConnectionTracker* network_connection_tracker,
      std::unique_ptr<LogFileWriter::Factory> log_file_writer_factory);

  void EnableRemoteBoundLoggingForBrowserContext(
      BrowserContextId browser_context_id,
      const base::FilePath& browser_context_dir,
      base::OnceClosure reply);

  void DisableRemoteBoundLoggingForBrowserContext(
      BrowserContextId browser_context_id,
      base::OnceClosure reply);

  void RemovePendingRemoteBoundLogsForNotEnabledBrowserContext(
      BrowserContextId browser_context_id,
      const base::FilePath& browser_context_dir,
      base::OnceClosure reply);

  void PeerConnectionAddedInternal(PeerConnectionKey key,
                                   base::OnceCallback<void(bool)> reply);
  void PeerConnectionRemovedInternal(PeerConnectionKey key,
                                     base::OnceCallback<void(bool)> reply);

  void PeerConnectionSessionIdSetInternal(PeerConnectionKey key,
                                          const std::string& session_id,
                                          base::OnceCallback<void(bool)> reply);

  void EnableLocalLoggingInternal(const base::FilePath& base_path,
                                  size_t max_file_size_bytes,
                                  base::OnceCallback<void(bool)> reply);
  void DisableLocalLoggingInternal(base::OnceCallback<void(bool)> reply);

  void OnWebRtcEventLogWriteInternal(
      PeerConnectionKey key,
      const std::string& message,
      base::OnceCallback<void(std::pair<bool, bool>)> reply);

  void StartRemoteLoggingInternal(
      int render_process_id,
      BrowserContextId browser_context_id,
      const std::string& session_id,
      const base::FilePath& browser_context_dir,
      size_t max_file_size_bytes,
      int output_period_ms,
      size_t web_app_id,
      base::OnceCallback<void(bool, const std::string&, const std::string&)>
          reply);

  void ClearCacheForBrowserContextInternal(BrowserContextId browser_context_id,
                                           const base::Time& delete_begin,
                                           const base::Time& delete_end);

  void OnClearCacheForBrowserContextDoneInternal(base::OnceClosure reply);

  void GetHistoryInternal(
      BrowserContextId browser_context_id,
      base::OnceCallback<void(const std::vector<UploadList::UploadInfo>&)>
          reply);

  void RenderProcessExitedInternal(int render_process_id);

  void SetLocalLogsObserverInternal(WebRtcLocalEventLogsObserver* observer,
                                    base::OnceClosure reply);

  void SetRemoteLogsObserverInternal(WebRtcRemoteEventLogsObserver* observer,
                                     base::OnceClosure reply);

  // Injects a fake clock, to be used by tests. For example, this could be
  // used to inject a frozen clock, thereby allowing unit tests to know what a
  // local log's filename would end up being.
  void SetClockForTesting(base::Clock* clock, base::OnceClosure reply);

  // Injects a PeerConnectionTrackerProxy for testing. The normal tracker proxy
  // is used to communicate back to WebRTC whether event logging is desired for
  // a given peer connection. Using this function, those indications can be
  // intercepted by a unit test.
  void SetPeerConnectionTrackerProxyForTesting(
      std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy,
      base::OnceClosure reply);

  // Injects a fake uploader, to be used by unit tests.
  void SetWebRtcEventLogUploaderFactoryForTesting(
      std::unique_ptr<WebRtcEventLogUploader::Factory> uploader_factory,
      base::OnceClosure reply);

  // Sets a LogFileWriter factory for remote-bound files.
  // Only usable in tests.
  // Must be called before the first browser context is enabled.
  // Effective immediately.
  void SetRemoteLogFileWriterFactoryForTesting(
      std::unique_ptr<LogFileWriter::Factory> factory);

  // It is not always feasible to check in unit tests that uploads do not occur
  // at a certain time, because that's (sometimes) racy with the event that
  // suppresses the upload. We therefore allow unit tests to glimpse into the
  // black box and verify that the box is aware that it should not upload.
  void UploadConditionsHoldForTesting(base::OnceCallback<void(bool)> callback);

  // This allows unit tests that do not wish to change the task runner to still
  // check when certain operations are finished.
  // TODO(crbug.com/775415): Remove this and use PostNullTaskForTesting instead.
  scoped_refptr<base::SequencedTaskRunner> GetTaskRunnerForTesting();

  void PostNullTaskForTesting(base::OnceClosure reply);

  // Documented in WebRtcRemoteEventLogManager.
  void ShutDownForTesting(base::OnceClosure reply);

  static WebRtcEventLogManager* g_webrtc_event_log_manager;

  // The main logic will run sequentially on this runner, on which blocking
  // tasks are allowed.
  scoped_refptr<base::UpdateableSequencedTaskRunner> task_runner_;

  // The number of user-blocking tasks.
  // The priority of |task_runner_| is increased to USER_BLOCKING when this is
  // non-zero, and reduced to BEST_EFFORT when zero.
  // This object is only to be accessed on the UI thread.
  size_t num_user_blocking_tasks_;

  // Indicates whether remote-bound logging is generally allowed, although
  // possibly not for all profiles. This makes it possible for remote-bound to
  // be disabled through Finch.
  // TODO(crbug.com/775415): Remove this kill-switch.
  const bool remote_logging_feature_enabled_;

  // Observer which will be informed whenever a local log file is started or
  // stopped. Its callbacks are called synchronously from |task_runner_|,
  // so the observer needs to be able to either run from any (sequenced) runner.
  WebRtcLocalEventLogsObserver* local_logs_observer_;

  // Observer which will be informed whenever a remote log file is started or
  // stopped. Its callbacks are called synchronously from |task_runner_|,
  // so the observer needs to be able to either run from any (sequenced) runner.
  WebRtcRemoteEventLogsObserver* remote_logs_observer_;

  // Manages local-bound logs - logs stored on the local filesystem when
  // logging has been explicitly enabled by the user.
  WebRtcLocalEventLogManager local_logs_manager_;

  // Manages remote-bound logs - logs which will be sent to a remote server.
  // This is only possible when the appropriate Chrome policy is configured.
  WebRtcRemoteEventLogManager remote_logs_manager_;

  // Each loaded BrowserContext is mapped to a PrefChangeRegistrar, which keeps
  // us informed about preference changes, thereby allowing as to support
  // dynamic refresh.
  std::map<BrowserContextId, PrefChangeRegistrar> pref_change_registrars_;

  // This keeps track of which peer connections have event logging turned on
  // in WebRTC, and for which client(s).
  std::map<PeerConnectionKey, LoggingTargetBitmap>
      peer_connections_with_event_logging_enabled_in_webrtc_;

  // The set of RenderProcessHosts with which the manager is registered for
  // observation. Allows us to register for each RPH only once, and get notified
  // when it exits (cleanly or due to a crash).
  // This object is only to be accessed on the UI thread.
  base::flat_set<content::RenderProcessHost*> observed_render_process_hosts_;

  // In production, this holds a small object that just tells WebRTC (via
  // PeerConnectionTracker) to start/stop producing event logs for a specific
  // peer connection. In (relevant) unit tests, a mock will be injected.
  std::unique_ptr<PeerConnectionTrackerProxy> pc_tracker_proxy_;

  // The globals network_connection_tracker() and system_request_context() are
  // sent down to |remote_logs_manager_| with the first enabled browser context.
  // This member must only be accessed on the UI thread.
  bool first_browser_context_initializations_done_;

  // May only be set for tests, in which case, it will be passed to
  // |remote_logs_manager_| when (and if) produced.
  std::unique_ptr<LogFileWriter::Factory>
      remote_log_file_writer_factory_for_testing_;

  DISALLOW_COPY_AND_ASSIGN(WebRtcEventLogManager);
};

}  // namespace webrtc_event_logging

#endif  // CHROME_BROWSER_MEDIA_WEBRTC_WEBRTC_EVENT_LOG_MANAGER_H_


text:
//
//  WHC_CameraVC.m
//  WHC_PhotoCameraChoicePictureDemo
//
//  Created by 吴海超 on 15/7/30.
//  Copyright (c) 2015年 吴海超. All rights reserved.
//
/*
 *  qq:712641411
 *  gitHub:https://github.com/netyouli
 *  csdn:http://blog.csdn.net/windwhc/article/category/3117381
 */

#import "WHC_CameraVC.h"

@interface WHC_CameraVC ()<UIImagePickerControllerDelegate , UINavigationControllerDelegate>{
    UIImagePickerController   *  _cameraVC;
}

@end

@implementation WHC_CameraVC

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData{
    _cameraVC = [[UIImagePickerController alloc]init];
    _cameraVC.delegate = self;
    _cameraVC.allowsEditing = YES;
    _cameraVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    _cameraVC.view.frame = [UIScreen mainScreen].bounds;
    [self.view addSubview:_cameraVC.view];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    __weak  typeof(self)  sf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        if(image != nil){
            if(_delegate && [_delegate respondsToSelector:@selector(WHCCameraVC:didSelectedPhoto:)]){
                [_delegate WHCCameraVC:sf didSelectedPhoto:image];
            }
        }
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage  * image = info[@"UIImagePickerControllerOriginalImage"];
    __weak  typeof(self)  sf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        if(image != nil){
            if(_delegate && [_delegate respondsToSelector:@selector(WHCCameraVC:didSelectedPhoto:)]){
                [_delegate WHCCameraVC:sf didSelectedPhoto:image];
            }
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
using System.Collections.Generic;

namespace NotificationHubsSample.Models
{
    /// <summary>
    /// Define the DeviceInfo.
    /// </summary>
    public class DeviceInfo
    {
        /// <summary>
        /// Gets or sets the registration identifier.
        /// </summary>
        /// <value>The registration identifier.</value>
        public string RegistrationId { get; set; }
        /// <summary>
        /// Gets or sets the platform.
        /// </summary>
        /// <value>The platform.</value>
        public string Platform { get; set; }
        /// <summary>
        /// Gets or sets the handle.
        /// </summary>
        /// <value>The handle.</value>
        public string Handle { get; set; }
        /// <summary>
        /// Gets or sets the tags.
        /// </summary>
        /// <value>The tags.</value>
        public IEnumerable<string> Tags { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="1">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lista_evento"
            android:drawSelectorOnTop="false"
         android:state_pressed="true" android:color="@color/titulo_cor"

            android:layout_gravity="center_horizontal" />
    </LinearLayout>

</RelativeLayout>

<!-- From: file:/C:/Users/luiz/AndroidStudioProjects/TabsFragments2/app/src/main/res/layout/activity_abaeventos.xml -->


text:
package com.kun.flow.data;

import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.kun.flow.bean.Pagination;
import com.kun.flow.model.Role;

public interface RoleMapper extends IMapper<Role> {

	/**
	 * 获取绑定到操作者上的角色
	 *
	 * @author songkun
	 * @create 2014年4月25日 下午9:08:44
	 * @param key
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<Role> listByOperater(@Param("key") Serializable key, @Param("page") Pagination page) throws Exception;

	/**
	 * 获取还未被该用户绑定的角色列表
	 *
	 * @author songkun
	 * @create 2014年4月26日 上午9:19:41
	 * @param key
	 * @throws Exception
	 */
	public List<Role> listUnbindRolesByOperater(@Param("key") Serializable key) throws Exception;
}


text:
package org.tyrannyofheaven.bukkit.util.command;

/**
 * Thrown when something is wrong with the command arguments. Results in
 * an error message being shown to the user as well as the command usage.
 *
 * @author zerothangel
 */
public class ParseException extends CommandException {

    private static final long serialVersionUID = 6379096495842869497L;

    public ParseException() {
    }

    public ParseException(String message) {
        super(message);
    }

    public ParseException(String format, Object... args) {
        super(format, args);
    }

}


text:
class FrameBufferObject {
public:
	FrameBufferObject(int, int, int=1);
	~FrameBufferObject();

	void draw(int=0);

	void bindFrameBuffer(GLenum);
	void unbindFrameBuffer(GLenum);
	void bindRenderBuffer(GLenum);
	void unbindRenderBuffer(GLenum);
	void bindTexture(int=0);
	void unbindTexture();
	void setRenderToTexture(int=0);
	void unsetRenderToTexture();

	bool checkStatus(GLenum);

	std::vector<GLuint> textures;
	GLuint frameBufferId;
	GLuint depthBufferId;

	int width, height;
};


text:
type Paypal = {
    userID: string;
};

declare var paypal: Paypal;


text:
package com.facebook.buck.rules.macros;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.facebook.buck.core.cell.resolver.CellPathResolver;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import com.facebook.buck.model.macros.MacroException;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.CompositeArg;
import com.facebook.buck.rules.args.SanitizedArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.args.WriteToFileArg;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import java.util.HashMap;
import java.util.Optional;
import java.util.function.Function;
import org.immutables.value.Value;

/**
 * Converts a {@link StringWithMacros} into an {@link Arg}. Performs conversion eagerly, and meant
 * as a replacement for the lazy {@link StringWithMacrosArg}.
 */
@Value.Immutable
@BuckStyleImmutable
abstract class AbstractStringWithMacrosConverter {

  @Value.Parameter
  abstract BuildTarget getBuildTarget();

  @Value.Parameter
  abstract CellPathResolver getCellPathResolver();

  @Value.Parameter
  abstract BuildRuleResolver getResolver();

  @Value.Parameter
  abstract ImmutableList<AbstractMacroExpander<? extends Macro, ?>> getExpanders();

  abstract Optional<Function<String, String>> getSanitizer();

  @Value.Default
  @Value.Auxiliary
  @SuppressWarnings("PMD.LooseCoupling")
  HashMap<Macro, Object> getPrecomputedWorkCache() {
    return new HashMap<>();
  }

  @Value.Derived
  ImmutableMap<Class<? extends Macro>, AbstractMacroExpander<? extends Macro, ?>>
      getClassExpanders() {
    ImmutableMap.Builder<Class<? extends Macro>, AbstractMacroExpander<? extends Macro, ?>>
        builder = ImmutableMap.builder();
    for (AbstractMacroExpander<? extends Macro, ?> expander : getExpanders()) {
      builder.put(expander.getInputClass(), expander);
    }
    return builder.build();
  }

  @SuppressWarnings("unchecked")
  private <M extends Macro, P> AbstractMacroExpander<M, P> getExpander(M macro)
      throws MacroException {
    AbstractMacroExpander<M, P> expander =
        (AbstractMacroExpander<M, P>) getClassExpanders().get(macro.getClass());
    if (expander == null) {
      throw new MacroException(String.format("unexpected macro %s", macro.getClass()));
    }
    return expander;
  }

  @SuppressWarnings("unchecked")
  private <T extends Macro, P> Arg expand(T macro) throws MacroException {
    AbstractMacroExpander<T, P> expander = getExpander(macro);

    // Calculate precomputed work.
    P precomputedWork = (P) getPrecomputedWorkCache().get(macro);
    if (precomputedWork == null) {
      precomputedWork =
          expander.precomputeWorkFrom(
              getBuildTarget(), getCellPathResolver(), getResolver(), macro);
      getPrecomputedWorkCache().put(macro, precomputedWork);
    }

    return expander.expandFrom(
        getBuildTarget(), getCellPathResolver(), getResolver(), macro, precomputedWork);
  }

  /**
   * Expand the input given for the this macro to some string, which is intended to be written to a
   * file.
   */
  private Arg expand(MacroContainer macroContainer) throws MacroException {
    Arg arg = expand(macroContainer.getMacro());

    // If specified, wrap this macro's output in a `WriteToFileArg`.
    if (macroContainer.isOutputToFile()) {
      // "prefix" should give a stable name, so that the same delegate with the same input can
      // output the same file. We won't optimise for this case, since it's actually unlikely to
      // happen within a single run, but using a random name would cause 'buck-out' to expand in an
      // uncontrolled manner.
      Hasher hasher = Hashing.sha256().newHasher();
      hasher.putString(macroContainer.getMacro().getClass().getName(), UTF_8);
      hasher.putInt(macroContainer.getMacro().hashCode());
      String prefix = hasher.hash().toString();
      arg = new WriteToFileArg(getBuildTarget(), prefix, arg);
    }

    return arg;
  }

  public Arg convert(StringWithMacros val) {
    return CompositeArg.of(
        val.map(
            str ->
                getSanitizer()
                    .<Arg>map(sanitizer -> SanitizedArg.create(sanitizer, str))
                    .orElseGet(() -> StringArg.of(str)),
            macroContainer -> {
              try {
                return expand(macroContainer);
              } catch (MacroException e) {
                throw new HumanReadableException(e, "%s: %s", getBuildTarget(), e.getMessage());
              }
            }));
  }
}


text:
using System;
using System.Linq;
using NGitLab.Models;
using NUnit.Framework;

namespace NGitLab.Tests
{
    public class ProjectsTests : IDisposable
    {
        private readonly IProjectClient _projects;
        private readonly Project _created;

        public ProjectsTests()
        {
            _projects = Config.Connect().Projects;
            CreateProject(out _created, "default");
        }

        public void Dispose()
        {
            _projects.Delete(_created.Id);
        }

        [Test]
        [Category("Server_Required")]
        public void GetAllProjects()
        {
            var projects = _projects.All.ToArray();

            CollectionAssert.IsNotEmpty(projects);
        }

        [Test]
        [Category("Server_Required")]
        public void GetOwnedProjects()
        {
            var projects = _projects.Owned.ToArray();

            CollectionAssert.IsNotEmpty(projects);
        }

        [Test]
        [Category("Server_Required")]
        public void GetAccessibleProjects()
        {
            var projects = _projects.Accessible.ToArray();

            CollectionAssert.IsNotEmpty(projects);
        }

        [Test]
        [Category("Server_Required")]
        public void CreateDelete()
        {
            Project created;
            var p = CreateProject(out created, "test2");

            Assert.AreEqual(p.Description, created.Description);
            Assert.AreEqual(p.IssuesEnabled, created.IssuesEnabled);
            Assert.AreEqual(p.MergeRequestsEnabled, created.MergeRequestsEnabled);
            Assert.AreEqual(p.Name, created.Name);

            Assert.AreEqual(_projects.Delete(created.Id),true);
        }

        private ProjectCreate CreateProject(out Project created, string name)
        {
            var p = new ProjectCreate
            {
                Description = "desc",
                ImportUrl = null,
                IssuesEnabled = true,
                MergeRequestsEnabled = true,
                Name = name,
                NamespaceId = null,
                SnippetsEnabled = true,
                VisibilityLevel = VisibilityLevel.Public,
                WallEnabled = true,
                WikiEnabled = true
            };

            created = _projects.Create(p);
            return p;
        }
    }
}


text:
package com.example.clarence.myapp.entity;

import android.databinding.ObservableField;
import android.databinding.ObservableInt;

public class PlainUser {
    public final ObservableField<String> firstName = new ObservableField<>();
    public final ObservableField<String> lastName = new ObservableField<>();
    public final ObservableInt age = new ObservableInt();
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="robots" content="index,follow">

    <meta name="viewport" content="width=device-width initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="Simon Praetorius">

    <title>Concepts in action</title>
    <meta name="description" content="This site shows interesting developments and examples using the c++ template feature to write generic programs and meta-programs. Modern programming techniques, like concepts-lite, emphasizing the C++14 (17) standard are highlighted.
">
    <meta name="keywords" content="generic programming, c++, c++11, c++14, c++17, templates, concepts, concepts-lite, template meta-programming, expression templates">

    <link rel="stylesheet" href="/css/main.css">
    <link rel="canonical" href="http://spraetor.github.io/2015/12/25/concepts-in-action.html">

    Generic programming with C++Generic C++

          About

Concepts in action

25.12. 2015 • Simon Praetorius

The concepts-lite extension for c++ is accepted for the upcoming C++17 standard. Some tutorials are already available and with the current gcc trunk an experimental implementation of this feature in a c++ compiler. We will see some examples of  concepts-lite in action.

The task is to write a library that overloads to operator* in order to scale an
iterable object by a scalar factor, e.g. scale a vector by a double value. In
order to be very generic, we want to write a templated function for the scaling:

template <class Vector, class Scalar>
Vector& operator*=(Vector& v, Scalar s)
{
  for (auto& v_i : v)
    v_i *= s;
  return v;
}

template <class Vector, class Scalar>
Vector const operator*(Vector v, Scalar s)
{
  return v *= s;
}

This implementation provides a scaling of a vector by a scalar factor from the right. The
problem with this implementation is, that we can not distiguish between the vector
argument and the scalar argument, since both are unconstrained templates. Passing
a scalar as first argument and a vector as second argument is a valid call to the
function, but results in a compiler error in the inner algorithm, i.e. in the
range-based for-loop, since a scalar is not iterable.

It is possible to write an overload of operator* for a left-sided multiplication
by using tag-dispatiching, SFINAE techniques, or some other tricks. But we want
to write the code in a natural way. Therefore, we use constraints by the concepts-lite
specification (Technical specification, Tutorial).

What is a vector? Or at least an iterable object? We require, that a range-based
for-loop can be used for the container, i.e. there exist begin() and end()
(member) functions and the current iterate, i.e. the value-type of a vector, is
multiplicable by a scalar.

What is a scalar, on the other hand? For now we simply require, that it is an
arithmetic type, that fulfills the type-trait std::is_arithmetic. Later,
we can refine this concept, by explicitly specifying requirements on scalar arguments.

In order to use type-constraints, we have to define concepts:

template <typename V>
concept bool Iterable =
  requires(V v) {
    begin(v);
    end(v);
  } || requires(V v) {
    v.begin();
    v.end();
  };

template <typename S>
concept bool Arithmetic = std::is_arithmetic<S>::value;

template <typename T0, typename T1>
concept bool Multiplicable =
  requires(T0 t0, T1 t1) {
    t0 * t1;
    t1 * t0;
    t0 *= t1;
    t1 *= t0;
  };

The first one (Iterable) provides a simplified concept for iterable objects, i.e.
there must exist either a free function begin() and end() or member functions
with the same names. Here, nothing is said about what these functions should return.
A more advanced implementation could be a requirement that the result of begin() and
end() are Iterators (Input- or Output-Iterators, depending on other requirements).
The second concepts simply redirects to the type-traits implementation of the STL.
The third concepts is a binary concept, since it implements a relation between two
types. Here, we just require, that a multiplication operation between these two types
exist.

Combined with the operator definition above, we can now define vector*scalar and
scalar*vector concept-enabled function overloads:

template <Iterable Vector, Arithmetic Scalar>
  requires Multiplicable<Value_type<Vector>, Scalar>
Vector& operator*=(Vector& v, Scalar s)
{
  for (auto& v_i : v)
    v_i *= s;
  return v;
}

template <Iterable Vector, Arithmetic Scalar>
Vector const operator*(Vector v, Scalar s)
{
  return v *= s;
}

template <Arithmetic Scalar, Iterable Vector>
Vector const operator*(Scalar s, Vector v)
{
  return v *= s;
}

where Value_type is an alias template leading to the value type of a container.
A possible implementation could be:

namespace impl
{
  template <typename V>
  struct Value_type;

  template <typename V>
    requires requires() { typename V::value_type; }
  struct Value_type<V> {
    using type = typename V::value_type;
  };
} // end namespace impl

template <typename V>
using Value_type = typename impl::Value_type<V>::type;

So, we can now multiply any iterable object by any arithmetic type, if the value-types
are multiplicable, e.g.

std::vector<double>   v1{1.0,2.0,3.0};
std::array<double, 3> v2{1.0,2.0,3.0};
std::list<float>      v3{1.0,2.0,3.0};

auto v1_scaled = v1 * 3;
auto v2_scaled = v2 * 3.0;
auto v3_scaled = v3 * 3.0;

auto v4_scaled = 3 * v1;

Download Source

You can download the source of the final implementation from
here.

  Please enable JavaScript to view the comments powered by Disqus.

Generic programming with C++

About:

Simon Praetorius

simip@gmx.de

                <svg viewBox="0 0 16 16">
                  <path fill="#828282" d="M7.999,0.431c-4.285,0-7.76,3.474-7.76,7.761 c0,3.428,2.223,6.337,5.307,7.363c0.388,0.071,0.53-0.168,0.53-0.374c0-0.184-0.007-0.672-0.01-1.32 c-2.159,0.469-2.614-1.04-2.614-1.04c-0.353-0.896-0.862-1.135-0.862-1.135c-0.705-0.481,0.053-0.472,0.053-0.472 c0.779,0.055,1.189,0.8,1.189,0.8c0.692,1.186,1.816,0.843,2.258,0.645c0.071-0.502,0.271-0.843,0.493-1.037 C4.86,11.425,3.049,10.76,3.049,7.786c0-0.847,0.302-1.54,0.799-2.082C3.768,5.507,3.501,4.718,3.924,3.65 c0,0,0.652-0.209,2.134,0.796C6.677,4.273,7.34,4.187,8,4.184c0.659,0.003,1.323,0.089,1.943,0.261 c1.482-1.004,2.132-0.796,2.132-0.796c0.423,1.068,0.157,1.857,0.077,2.054c0.497,0.542,0.798,1.235,0.798,2.082 c0,2.981-1.814,3.637-3.543,3.829c0.279,0.24,0.527,0.713,0.527,1.437c0,1.037-0.01,1.874-0.01,2.129 c0,0.208,0.14,0.449,0.534,0.373c3.081-1.028,5.302-3.935,5.302-7.362C15.76,3.906,12.285,0.431,7.999,0.431z"/>
                </svg>

              spraetor

Links:

	    C++ Core Guidelines

	    GotW - Guru of the Week

	    Eric Nieblers Blog

	    C++ Truths

Summary:

This site shows interesting developments and examples using the c++ template feature to write generic programs and meta-programs. Modern programming techniques, like concepts-lite, emphasizing the C++14 (17) standard are highlighted.


text:
require 'test/helper'

class TestMultiple < Test::Unit::TestCase

  context "#results_for with multiple types AND multiple locales" do
    setup do
      @searches = Awesome::Search.results_for(":local :amazon :text :isbn this is a test 1234567890", [":text",":isbn"], [":local",":amazon"])
    end
    should "should return an array" do
      assert @searches.is_a?(Array)
    end

    should "returns multiple result sets" do
      assert @searches.length > 1
    end
    should "all have results" do
      assert @searches.select {|x| x.found.is_a?(Array)}.length == 4
    end
    should "all have tally" do
      assert @searches.select {|x| x.tally.is_a?(Integer)}.length == 4
    end
  end

end


text:
import { ILuModalContent } from '@lucca-front/ng/modal';

export type ILuSidepanelContent<T = unknown> = ILuModalContent<T>;


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateIzcoreAppConfigTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create(
            'izcore_app_config',
            function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('value');
                $table->timestamps();
            });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::drop('izcore_app_config');
    }

}


text:
/*
 * =====================================================================================
 *
 *       Filename:  cache.c
 *
 *    Description:  A simple cache
 *
 *        Version:  1.0
 *        Created:  04/11/2013 02:31:02 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Oliver Lorenz (ol), olli@olorenz.org
 *        Company:  https://olorenz.org
 *        License:  This is licensed under the same terms as uthash itself
 *
 * =====================================================================================
 */

#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include "cache.h"
#include "uthash.h"

/**
 * A cache entry
 */
struct foo_cache_entry {
	char *key; /**<The key */
	void *data; /**<Payload */
	UT_hash_handle hh; /**<Hash Handle for uthash */
};
#define KEY_MAX_LENGTH		32

/**
 * A cache object
 */
struct foo_cache {
	size_t max_entries; /**<Amount of entries this cache object can hold */
	pthread_rwlock_t cache_lock; /**<A lock for concurrent access */
	struct foo_cache_entry *entries; /**<Head pointer for uthash */
	void (*free_cb) (void *element);/**<Callback function to free cache entries */
};

/** Creates a new cache object

    @param dst
    Where the newly allocated cache object will be stored in

    @param capacity
    The maximum number of elements this cache object can hold

    @return EINVAL if dst is NULL, ENOMEM if malloc fails, 0 otherwise
*/
int foo_cache_create(struct foo_cache **dst, const size_t capacity,
		     void (*free_cb) (void *element))
{
	struct foo_cache *new = NULL;
	int rv;

	if (!dst)
		return EINVAL;

	if ((new = malloc(sizeof(*new))) == NULL)
		return ENOMEM;

	if ((rv = pthread_rwlock_init(&(new->cache_lock), NULL)) != 0)
		goto err_out;

	new->max_entries = capacity;
	new->entries = NULL;
	new->free_cb = free_cb;
	*dst = new;
	return 0;

err_out:
	if (new)
		free(new);
	return rv;
}

/** Frees an allocated cache object

    @param cache
    The cache object to free

    @param keep_data
    Whether to free contained data or just delete references to it

    @return EINVAL if cache is NULL, 0 otherwise
*/
int foo_cache_delete(struct foo_cache *cache, int keep_data)
{
	struct foo_cache_entry *entry, *tmp;
	int rv;

	if (!cache)
		return EINVAL;

	rv = pthread_rwlock_wrlock(&(cache->cache_lock));
	if (rv)
		return rv;

	if (keep_data) {
		HASH_CLEAR(hh, cache->entries);
	} else {
		HASH_ITER(hh, cache->entries, entry, tmp) {
			HASH_DEL(cache->entries, entry);
			if (cache->free_cb)
				cache->free_cb(entry->data);
			free(entry);
		}
	}
	(void)pthread_rwlock_unlock(&(cache->cache_lock));
	(void)pthread_rwlock_destroy(&(cache->cache_lock));
	free(cache);
	cache = NULL;
	return 0;
}

/** Checks if a given key is in the cache

    @param cache
    The cache object

    @param key
    The key to look-up

    @param result
    Where to store the result if key is found.

    A warning: Even though result is just a pointer,
    you have to call this function with a **ptr,
    otherwise this will blow up in your face.

    @return EINVAL if cache is NULL, 0 otherwise
*/
int foo_cache_lookup(struct foo_cache *cache, char *key, void *result)
{
	int rv;
	struct foo_cache_entry *tmp = NULL;
	char **dirty_hack = result;

	if (!cache || !key || !result)
		return EINVAL;

	rv = pthread_rwlock_wrlock(&(cache->cache_lock));
	if (rv)
		return rv;

	HASH_FIND_STR(cache->entries, key, tmp);
	if (tmp) {
		size_t key_len = strnlen(tmp->key, KEY_MAX_LENGTH);
		HASH_DELETE(hh, cache->entries, tmp);
		HASH_ADD_KEYPTR(hh, cache->entries, tmp->key, key_len, tmp);
		*dirty_hack = tmp->data;
	} else {
		*dirty_hack = result = NULL;
	}
	rv = pthread_rwlock_unlock(&(cache->cache_lock));
	return rv;
}

/** Inserts a given <key, value> pair into the cache

    @param cache
    The cache object

    @param key
    The key that identifies <value>

    @param data
    Data associated with <key>

    @return EINVAL if cache is NULL, ENOMEM if malloc fails, 0 otherwise
*/
int foo_cache_insert(struct foo_cache *cache, char *key, void *data)
{
	struct foo_cache_entry *entry = NULL;
	struct foo_cache_entry *tmp_entry = NULL;
	size_t key_len = 0;
	int rv;

	if (!cache || !data)
		return EINVAL;

	if ((entry = malloc(sizeof(*entry))) == NULL)
		return ENOMEM;

	if ((rv = pthread_rwlock_wrlock(&(cache->cache_lock))) != 0)
		goto err_out;

	entry->key = key;
	entry->data = data;
	key_len = strnlen(entry->key, KEY_MAX_LENGTH);
	HASH_ADD_KEYPTR(hh, cache->entries, entry->key, key_len, entry);

	if (HASH_COUNT(cache->entries) >= cache->max_entries) {
		HASH_ITER(hh, cache->entries, entry, tmp_entry) {
			HASH_DELETE(hh, cache->entries, entry);
			if (cache->free_cb)
				cache->free_cb(entry->data);
			else
				free(entry->data);
			/* free(key->key) if data has been copied */
			free(entry);
			break;
		}
	}

	rv = pthread_rwlock_unlock(&(cache->cache_lock));
	return rv;

err_out:
	if (entry)
		free(entry);
	(void)pthread_rwlock_unlock(&(cache->cache_lock));
	return rv;

}


text:
/* cmake.h.in. Creates cmake.h during a build */

/* Package information */
#define PACKAGE "vramsteg"
#define VERSION "1.1.0"
#define PACKAGE_BUGREPORT "support@yootabory.com"
#define PACKAGE_NAME      "vramsteg"
#define PACKAGE_TARNAME   "vramsteg"
#define PACKAGE_VERSION   "1.1.0"
#define PACKAGE_STRING    "vramsteg 1.1.0"

/* git information */
#define HAVE_COMMIT

/* Compiling platform */
/* #undef LINUX */
#define DARWIN
/* #undef CYGWIN */
/* #undef FREEBSD */
/* #undef OPENBSD */
/* #undef NETBSD */
/* #undef HAIKU */
/* #undef SOLARIS */
/* #undef KFREEBSD */
/* #undef GNUHURD */
/* #undef UNKNOWN */


text:
<!DOCTYPE html>

        <title th:text="#{admin.login.title}">Admin Login</title>

            <link th:href="@{/assets/global/plugins/select2/select2.css}" rel="stylesheet" type="text/css"/>
            <link th:href="@{/assets/admin/pages/css/login-soft.css}" rel="stylesheet" type="text/css"/>

                <form class="login-form" name="f" th:action="@{/admin/login}" method="post">

Login Admin

                        <button class="close" data-close="alert"></button>
                        Enter any username and password.

                        Username

                            <input class="form-control placeholder-no-fix" type="text" autocomplete="off" th:placeholder="#{admin.login.form.username.placeholder}" name="username"/>

                        Password

                            <input class="form-control placeholder-no-fix" type="password" autocomplete="off" th:placeholder="#{admin.login.form.password.placeholder}" name="password"/>

                            <input type="checkbox" name="remember-me" />
                            Remember me

                        <button type="submit" class="btn blue pull-right">
                            Login
                        </button>

Forgot your password ?

                </form>

                <form class="forget-form" action="index.html" method="post">

Forget Password ?

Enter your e-mail address below to reset your password.

                            <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="email"/>

                        <button type="button" id="back-btn" class="btn">

                            Back
                        </button>
                        <button type="submit" class="btn blue pull-right">
                            Submit

                        </button>

                </form>


text:
/* ************************************ */
/* Define helper functions */
/* ************************************ */
function evalAttentionChecks() {
  var check_percent = 1
  if (run_attention_checks) {
    var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check')
    var checks_passed = 0
    for (var i = 0; i < attention_check_trials.length; i++) {
      if (attention_check_trials[i].correct === true) {
        checks_passed += 1
      }
    }
    check_percent = checks_passed / attention_check_trials.length
  }
  return check_percent
}

var getInstructFeedback = function() {
  return '

' + feedback_instruct_text +
    '

'
}

var arraysEqual = function(arr1, arr2) {
  if (arr1.length !== arr2.length)
    return false;
  for (var i = arr1.length; i--;) {
    if (arr1[i] !== arr2[i])
      return false;
  }
  return true;
}

var randomDraw = function(lst) {
  var index = Math.floor(Math.random() * (lst.length))
  return lst[index]
}

var setStims = function() {
  curr_seq = []
  stim_array = []
  time_array = []
  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  var last_num = 0
  for (var i = 0; i < num_digits; i++) {
    var num = randomDraw(nums.filter(function(x) {return Math.abs(x-last_num)>2}))
    last_num = num
    curr_seq.push(num)
    stim_array.push('

' + num.toString() +
      '

')
    time_array.push(stim_time)
  }
  total_time = num_digits * (stim_time + gap_time)
}

var getTestText = function() {
  return '

' + num_digits + ' Digits

'
}

var getStims = function() {
  return stim_array
}

var getTimeArray = function() {
  return time_array
}

var getTotalTime = function() {
  return total_time
}

var getFeedback = function() {
  return '

' + feedback + '

'
}

var recordClick = function(elm) {
  response.push(Number($(elm).text()))
}

var clearResponse = function() {
  response = []
}

/* ************************************ */
/* Define experimental variables */
/* ************************************ */
// generic task variables
var run_attention_checks = false
var attention_check_thresh = 0.65
var sumInstructTime = 0 //ms
var instructTimeThresh = 0 ///in seconds

// task specific variables
var num_digits = 3
var num_trials = 14
var curr_seq = []
var stim_time = 800
var gap_time = 200
var time_array = []
var total_time = 0
var errors = 0
var error_lim = 3
var response = []
setStims()
var stim_array = getStims()

var response_grid =
  '
' +
  '<button id = button_1 class = "square num-button" onclick = "recordClick(this)">

1

</button>' +
  '<button id = button_2 class = "square num-button" onclick = "recordClick(this)">

2

</button>' +
  '<button id = button_3 class = "square num-button" onclick = "recordClick(this)">

3

</button>' +
  '<button id = button_4 class = "square num-button" onclick = "recordClick(this)">

4

</button>' +
  '<button id = button_5 class = "square num-button" onclick = "recordClick(this)">

5

</button>' +
  '<button id = button_6 class = "square num-button" onclick = "recordClick(this)">

6

</button>' +
  '<button id = button_7 class = "square num-button" onclick = "recordClick(this)">

7

</button>' +
  '<button id = button_8 class = "square num-button" onclick = "recordClick(this)">

8

</button>' +
  '<button id = button_9 class = "square num-button" onclick = "recordClick(this)">

9

</button>' +
  '<button class = clear_button id = "ClearButton" onclick = "clearResponse()">Clear</button>' +
  '<button class = submit_button id = "SubmitButton">Submit Answer</button>
'

/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */
// Set up attention check node
var attention_check_block = {
  type: 'attention-check',
  data: {
    trial_id: "attention_check"
  },
  timing_response: 180000,
  response_ends_trial: true,
  timing_post_trial: 200
}

var attention_node = {
  timeline: [attention_check_block],
  conditional_function: function() {
    return run_attention_checks
  }
}

//Set up post task questionnaire
var post_task_block = {
   type: 'survey-text',
   data: {
       exp_id: "digit_span",
       trial_id: "post task questions"
   },
   questions: ['
Please summarize what you were asked to do in this task.
',
              '
Do you have any comments about this task?
'],
   rows: [15, 15],
   columns: [60,60]
};

/* define static blocks */
var feedback_instruct_text =
  'Welcome to the experiment. This experiment will take less than 10 minutes. Press enter to begin.'
var feedback_instruct_block = {
  type: 'poldrack-text',
  cont_key: [13],
  data: {
    trial_id: "instruction"
  },
  text: getInstructFeedback,
  timing_post_trial: 0,
  timing_response: 180000
};
/// This ensures that the subject does not read through the instructions too quickly.  If they do it too quickly, then we will go over the loop again.
var instructions_block = {
  type: 'poldrack-instructions',
  data: {
    trial_id: "instruction"
  },
  pages: [
'

In this test you will have to try to remember a sequence of numbers that will appear on the screen one after the other. At the end of each trial, enter all the numbers into the presented numpad in the sequence in which they occurred. Do your best to memorize the numbers, but do not write them down or use any other external tool to help you remember them.

Trials will start after you end instructions.

'
 ],
  allow_keys: false,
  show_clickable_nav: true,
  timing_post_trial: 1000
};

var instruction_node = {
  timeline: [feedback_instruct_block, instructions_block],
  /* This function defines stopping criteria */
  loop_function: function(data) {
    for (i = 0; i < data.length; i++) {
      if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) {
        rt = data[i].rt
        sumInstructTime = sumInstructTime + rt
      }
    }
    if (sumInstructTime <= instructTimeThresh * 1000) {
      feedback_instruct_text =
        'Read through instructions too quickly.  Please take your time and make sure you understand the instructions.  Press enter to continue.'
      return true
    } else if (sumInstructTime > instructTimeThresh * 1000) {
      feedback_instruct_text =
        'Done with instructions. Press enter to continue.'
      return false
    }
  }
}

var end_block = {
  type: 'poldrack-text',
  timing_response: 180000,
  data: {
    trial_id: "end",
    exp_id: 'digit_span'
  },
  text: '

Thanks for completing this task!

Press enter to continue.

',
  cont_key: [13],
  timing_post_trial: 0
};

var start_test_block = {
  type: 'poldrack-single-stim',
  is_html: true,
  stimulus: getTestText,
  data: {
    trial_id: "test_intro"
  },
  choices: 'none',
  timing_stim: 1000,
  timing_response: 1000,
  response_ends_trial: false,
  timing_post_trial: 1000
};

var start_reverse_block = {
  type: 'poldrack-text',
  timing_response: 180000,
  data: {
    trial_id: "start_reverse"
  },
  text: '

In these next trials, instead of reporting back the sequence you just saw, report the reverse of that sequence. So the last item should be first in your response, the second to last should be the second in your response, etc...

Press enter to begin.

',
  cont_key: [13],
  on_finish: function() {
  	errors = 0
    num_digits = 3
    stims = setStims()
  }
}

/* define test block */
var test_block = {
  type: 'poldrack-multi-stim-multi-response',
  stimuli: getStims,
  is_html: true,
  timing_stim: getTimeArray,
  timing_gap: gap_time,
  choices: [
    ['none']
  ],
  data: {
    trial_id: "stim",
    exp_stage: 'test'
  },
  timing_response: getTotalTime,
  timing_post_trial: 0,
  on_finish: function() {
    jsPsych.data.addDataToLastTrial({
      "sequence": curr_seq,
      "num_digits": num_digits
    })
  }
}

var forward_response_block = {
  type: 'single-stim-button',
  stimulus: response_grid,
  button_class: 'submit_button',
  data: {
    trial_id: "response",
    exp_stage: 'test'
  },
  on_finish: function() {
    jsPsych.data.addDataToLastTrial({
      "response": response.slice(),
      "sequence": curr_seq,
      "num_digits": num_digits,
      "condition": "forward"
    })
    var correct = false
      // staircase
    if (arraysEqual(response, curr_seq)) {
      num_digits += 1
      feedback = 'Correct!'
      stims = setStims()
      correct = true
    } else {
      errors += 1
      if (num_digits > 1 && errors == 2) {
        num_digits -= 1
        errors = 0
      }
      feedback = 'Incorrect'
      stims = setStims()
    }
    jsPsych.data.addDataToLastTrial({
      correct: correct
    })
    response = []
  },
  timing_post_trial: 500
}

var reverse_response_block = {
  type: 'single-stim-button',
  stimulus: response_grid,
  button_class: 'submit_button',
  data: {
    trial_id: "response",
    exp_stage: 'test'
  },
  on_finish: function() {
    jsPsych.data.addDataToLastTrial({
      "response": response.slice(),
      "sequence": curr_seq,
      "num_digits": num_digits,
      "condition": "reverse"
    })
    var correct = false
      // staircase
    if (arraysEqual(response.reverse(), curr_seq)) {
      num_digits += 1
      feedback = 'Correct!'
      stims = setStims()
      correct = true
    } else {
      errors += 1
      if (num_digits > 1 && errors == 2) {
        num_digits -= 1
        errors = 0
      }
      feedback = 'Incorrect'
      stims = setStims()
    }
    jsPsych.data.addDataToLastTrial({
      correct: correct
    })
    response = []
  },
  timing_post_trial: 500
}

var feedback_block = {
  type: 'poldrack-single-stim',
  stimulus: getFeedback,
  data: {
    trial_id: "feedback"
  },
  is_html: true,
  choices: 'none',
  timing_stim: 1000,
  timing_response: 1000,
  response_ends_trial: true
}

/* create experiment definition array */
var digit_span_experiment = [];
digit_span_experiment.push(instruction_node);
for (i = 0; i < num_trials ; i++ ) {
	digit_span_experiment.push(start_test_block)
	digit_span_experiment.push(test_block)
	digit_span_experiment.push(forward_response_block)
	digit_span_experiment.push(feedback_block)
}
digit_span_experiment.push(attention_node)
digit_span_experiment.push(start_reverse_block)
for (i = 0; i < num_trials ; i++ ) {
	digit_span_experiment.push(start_test_block)
	digit_span_experiment.push(test_block)
	digit_span_experiment.push(reverse_response_block)
	digit_span_experiment.push(feedback_block)
}
digit_span_experiment.push(post_task_block)
digit_span_experiment.push(end_block)


text:
package io.hascalator
package dst

import Prelude._
import Maybe._
import scala.NoSuchElementException

import io.hascalator.AbstractTestSpec

class RBTreeSpec extends AbstractTestSpec with RBTreesFixture {
  describe("A Red-Black tree") {
    describe("size") {
      it("should be 0 for empty RB trees") {
        val empty = RBTree.empty[Int, String]
        empty.size shouldBe 0
      }

      it("should count the number of nodes in a RB tree") {
        tree.size shouldBe 4
      }
    }

    describe("isEmpty") {
      it("should return 'true' for the empty RB tree") {
        emptyTree.isEmpty shouldBe true
      }

      it("should return 'false' for non empty RB trees") {
        tree.isEmpty shouldBe false
      }
    }

    describe("insert") {
      it("should add the new element as the root, when the starting RB tree is empty") {
        val t = emptyTree.insert(42, "answer")
        t.get shouldBe ((42, "answer"))
      }

      it("should increase the new RB tree size by 1") {
        val t = tree.insert(1, "one")
        t should have size (tree.size + 1L)
        t.lookup(1) shouldBe just("one")
      }

      ignore("should replace the value, if the RB tree already contains the key") {
        val t = tree.insert(42, "answer")
        t.lookup(42) shouldBe just("answer")
      }
    }

    describe("toList") {
      it("should convert the empty RB tree to the empty list") {
        emptyTree.toList shouldBe List()
      }

      it("should convert a RB tree to a list") {
        tree.toList shouldBe List((21, "b"), (42, "a"), (66, "f"), (99, "c"))
      }
    }

    describe("lookup") {
      it("should return a None searching an element in the empty RB tree") {
        emptyTree.lookup(99) shouldBe none
      }

      it("should return a Just when the element exists in a non empty RB tree") {
        tree.lookup(42) shouldBe just("a")
      }

      it("should return a None when the element doesn't exist in a non empty RB tree") {
        tree.lookup(-1) shouldBe none
      }
    }

    describe("min") {
      it("should return a None as the minimum value from the empty RB tree") {
        emptyTree.min shouldBe none
      }

      it("should return a Just with the minimum key in a non empty RB tree") {
        tree.min shouldBe just(21)
      }
    }

    describe("max") {
      it("should return a None as the maximum value from the empty RB tree") {
        emptyTree.max shouldBe none
      }

      it("should return a Just with the maximum key in a non empty RB tree") {
        tree.max shouldBe just(99)
      }
    }

    describe("contains") {
      it("should return false, when checking the empty RB tree") {
        emptyTree.contains(99) shouldBe false
      }

      it("should return true when the RB tree contains the key") {
        tree.contains(99) shouldBe true
      }

      it("should return false, when the RB tree doesn't contain the key") {
        tree.contains(9999) shouldBe false
      }
    }

    describe("depth") {
      it("should return 0 for the empty RB tree") {
        emptyTree.depth shouldBe 0
      }

      it("should count the longest path in the RB tree") {
        tree.depth shouldBe 3
      }
    }

    describe("fold") {
      it("should apply a function to all RB tree values") {
        numTree.fold(_ + _) shouldBe 15
      }

      it("should throw an exception for the empty RB tree") {
        the[NoSuchElementException] thrownBy {
          emptyTree.fold(_ + _)
        } should have message "fold: tree is empty"
      }
    }

    describe("toString") {
      it("should produce a string representation for the empty RB tree") {
        emptyTree.toString shouldBe "-"
      }

      it("should produce a string representation for RB trees") {
        tree.toString shouldBe "(((- [21->b] -) [42->a] -) [66->f] (- [99->c] -))"
      }
    }
  }
}

trait RBTreesFixture {
  def emptyTree: Tree[Int, String] = RBTree.empty[Int, String]
  def tree: Tree[Int, String] = RBTree.fromList(List((42, "a"), (21, "b"), (99, "c"), (66, "f")))
  def numTree: Tree[Int, Int] = RBTree.fromList(List((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)))
}


text:
<?php

	function list_display_query($query, $onChangeFunction){

		$userId = 1;

		if($query_run = mysql_query($query)){

			if(mysql_num_rows($query_run)==0){
				echo "
No applications found
";
			}

			while($query_row = mysql_fetch_assoc($query_run)){

				$applicantId = $query_row['userId'];

				echo "

<input type='checkbox' onchange='".$onChangeFunction."(".$query_row['leaveDetailId'].", this.checked);'>
";

				if($onChangeFunction=="readyDeleteApplication"){
					echo "";
				}else if($onChangeFunction=="readyRestoreApplication"){
					echo "";
				}

	                	echo "".$query_row['userName'].": ";

		                if($query_row['recommendingAuthority']==$userId){
					echo 'Recommend ';
				}else{
					echo 'Approve ';
				}
				echo $query_row['leaveDuration']." days ";
				if($query_row['leaveType']=='casualLeave'){
					echo "Casual Leave";
				}else if($query_row['leaveType']=='specialClBalance'){
					echo "Sepcial CL";
				}else if($query_row['leaveType']=='specialLeaveBalance'){
					echo "Special Leave";
				}else if($query_row['leaveType']=='halfPayLeaveBalance'){
					echo "Half-Pay Leave";
				}else if($query_row['leaveType']=='commutedLeaveBalance'){
					echo "Commuted Leave";
				}else if($query_row['leaveType']=='earnedLeaveBalance'){
					echo "Earned Leave";
				}else if($query_row['leaveType']=='extraOrdinaryLeaveBalance'){
					echo "Extra Ordinary Leave";
				}else if($query_row['leaveType']=='maternityLeaveBalance'){
					echo "Maternity Leave";
				}else if($query_row['leaveType']=='hospitalLeaveBalance'){
					echo "Hospital Leave";
				}else if($query_row['leaveType']=='quarantineLeaveBalance'){
					echo "Quarantine Leave";
				}else if($query_row['leaveType']=='leaveNotLeaveBalance'){
					echo "Leave Not Leave";
				}else if($query_row['leaveType']=='sabbaticalLeaveBalance'){
					echo "Sabbatical Leave";
				}else if($query_row['leaveType']=='vacationBalance'){
					echo "Vacation Leave";
				}
				echo "
".date("d/m/Y", strtotime($query_row['applyingDate']))."

";
				echo "

";
			}

		}else{

			echo mysql_error();

		}
	}

	function transfer_leaves($from, $to, $allLeaves, $allLeavesCount){

		$query_vars = "";

		for ($i=0; $i < $allLeavesCount; $i++) {

			$leaveDetailId = $allLeaves[$i];

			if(!empty($leaveDetailId)){

				if($query_vars!=""){
					$query_vars = $query_vars." OR";
				}

				$query_vars = $query_vars." leaveDetailId='".$leaveDetailId."'";

			}

		}

		if(!empty($query_vars)){

			$query = "INSERT ".$to." SELECT * FROM ".$from." WHERE".$query_vars;

			if($query_run = mysql_query($query)){

				$query = "DELETE FROM ".$from." WHERE".$query_vars;

				if($query_run = mysql_query($query)){

					if($from=="leave_details_tb"){
						echo "Application(s) deleted";
					}else if($from=="deleted_applications_tb"){
						echo "Application(s) restored";
					}

				}else{
					if($from=="leave_details_tb"){
						echo "Failed to delete application(s)";
					}else if($from=="deleted_applications_tb"){
						echo "Failed to restore application(s)";
					}
				}
			}else{
				if($from=="leave_details_tb"){
					echo "Failed to delete application(s)";
				}else if($from=="deleted_applications_tb"){
					echo "Failed to restore application(s)";
				}
			}

		}else{
			if($from=="leave_details_tb"){
				echo "No application(s) selected for deletion";
			}else if($from=="deleted_applications_tb"){
				echo "No application(s) selected for restoration";
			}
		}
	}

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <sunning.democollection.custom.view.smoothcb.SmoothCheckBox
        android:id="@+id/scb"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="5dp"
        app:color_checked="@color/almostWhite" />

    <sunning.democollection.custom.view.smoothcb.SmoothCheckBox
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="5dp"
        app:color_checked="#447eeb" />

    <sunning.democollection.custom.view.smoothcb.SmoothCheckBox
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="5dp"
        app:color_checked="#149A45" />

    <sunning.democollection.custom.view.smoothcb.SmoothCheckBox
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="5dp" />

</LinearLayout>