text:
<!--
 ~ Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ WSO2 Inc. licenses this file to you under the Apache License,
 ~ Version 2.0 (the "License"); you may not use this file except
 ~ in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~    http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,
 ~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND, either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<parent>
		<groupId>org.wso2.carbon</groupId>
		<artifactId>user-manager-feature</artifactId>
		<version>4.3.0-SNAPSHOT</version>
	<relativePath>../pom.xml</relativePath>
	</parent>

	<modelVersion>4.0.0</modelVersion>
	<artifactId>org.wso2.carbon.user.mgt.server.feature</artifactId>
	<version>4.3.0-SNAPSHOT</version>
	<packaging>pom</packaging>
	<name>User Manager Server Feature</name>
	<url>http://wso2.org</url>
	<description>This feature contains the core bundles required for Back-end user management functionality</description>
	<dependencies>
		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.user.mgt</artifactId>
			<!--<version>4.3.0-SNAPSHOT</version>-->
        	</dependency>
		<dependency>
		    <groupId>org.wso2.carbon</groupId>
		    <artifactId>org.wso2.carbon.user.mgt.common</artifactId>
		    <!--<version>4.3.0-SNAPSHOT</version>-->
		</dependency>

		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.identity.user.store.configuration</artifactId>
			<!--<version>4.3.0-SNAPSHOT</version>-->
        	</dependency>
		<dependency>
			<groupId>org.wso2.carbon</groupId>
			<artifactId>org.wso2.carbon.identity.user.store.configuration.deployer</artifactId>
			<!--<version>4.3.0-SNAPSHOT</version>-->
        	</dependency>
	</dependencies>
	<build>
	<plugins>

	<plugin>
		<groupId>org.wso2.maven</groupId>
		<artifactId>carbon-p2-plugin</artifactId>
		<version>${carbon.p2.plugin.version}</version>
		<executions>
			<execution>
				<id>4-p2-feature-generation</id>
				<phase>package</phase>
				<goals>
					<goal>p2-feature-gen</goal>
				</goals>
				<configuration>
					<id>org.wso2.carbon.user.mgt.server</id>
					<propertiesFile>../../../etc/feature.properties</propertiesFile>
					    <adviceFile>
						<properties>
						    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
						    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
						</properties>
					    </adviceFile>
					<bundles>
						<bundleDef>org.wso2.carbon:org.wso2.carbon.user.mgt</bundleDef>
						<bundleDef>org.wso2.carbon:org.wso2.carbon.user.mgt.common</bundleDef>

						<bundleDef>org.wso2.carbon:org.wso2.carbon.identity.user.store.configuration</bundleDef>
						<bundleDef>org.wso2.carbon:org.wso2.carbon.identity.user.store.configuration.deployer</bundleDef>
					</bundles>
					<importFeatures>
						<importFeatureDef>org.wso2.carbon.core.server:${carbon.platform.version}</importFeatureDef>
					</importFeatures>
				</configuration>
			</execution>
		</executions>
	</plugin>
        <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.1</version>
                <executions>
                    <execution>
                        <id>clean_target</id>
                        <phase>install</phase>
                        <configuration>
                            <tasks>
                                <delete dir="src/main/resources"/>
                                <delete dir="src/main"/>
                                <delete dir="src"/>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
	</plugins>
	</build>
</project>


text:
"""
This file is part of spinsys.

Spinsys is free software: you can redistribute it and/or modify
it under the terms of the BSD 3-clause license. See LICENSE.txt
for exact terms and conditions.
"""

import numpy as np
from scipy.sparse.linalg import eigsh, ArpackNoConvergence
from spinsys.exceptions import NoConvergence, NotFoundError
from spinsys import half

def generate_eigenpairs(N, H, num_psi, expand=True, enden=0.5):
    """Generates eigenvalue-eigenvector pairs around a specified
    energy density

    Args: "N" number of sites
          "H" Hamiltonian of the system
          "num_psi" number of eigenvectors to find
          "expand" option to expand the state vector into full
            Hilbert space and reorder into the tensor product
            basis ordering. Boolean
    Returns: 1. eigen-energies. 1D numpy array
             2. eigen-vectors. Python list of numpy 1D arrays
    """
    try:
        E = np.sort(eigsh(H, k=2, which='BE', return_eigenvectors=False))
        target_E = enden * E[1] + (1 - enden) * E[0]
        eigs, eigvecs = eigsh(H, k=int(num_psi), which='LM', sigma=target_E)
    except ArpackNoConvergence:
        raise NoConvergence

    if expand:
        psis = []
        for i in range(num_psi):
            psi = half.expand_and_reorder(N, eigvecs[:, i])
            psis.append(psi)
    else:
        psis = [eigvecs[:, i] for i in range(num_psi)]
    return eigs, psis

def generate_product_state(H, enden=0.5, tol=1e-6):
    """Generates a product state with an energy density close to the
    specified value.  The state will be returned in whatever basis H
    is in.

    Args: "H" Hamiltonian of the system in block diagonal form.
          "enden" energy density
          "tol" tolerance. It is highly unlikely to find a product state
            with energy density exactly equal to 0.5. This sets the
            tolerable range from 0.5
    Returns: 1D numpy array
    """
    def energy_density(E, Emin, Emax):
        return (E - Emin) / (Emax - Emin)

    veclen = H.shape[0]
    try:
        Emin, Emax = np.sort(eigsh(H, k=2, which='BE',
                             return_eigenvectors=False))
    except ArpackNoConvergence:
        raise NoConvergence
    # This works because we are using basis states of H. <H> with basis states
    #  always return diagonal elements
    energy_expvals = H.diagonal()
    for i, E_exp in enumerate(energy_expvals):
        if abs(energy_density(E_exp, Emin, Emax) - enden) < tol:
            break
    else:
        raise NotFoundError
    product_state = np.zeros(veclen)
    product_state[i] = 1
    return product_state

redpajama_set_name: RedPajamaGithub


text:
var scene, camera, renderer;

var clock = new THREE.Clock();

var controller;

init();
animate();

function generateSurface(u, v) {
    var x,y,z;
    x = 1000 * (u - 0.5);
    z = 1000 * (v - 0.5);
    y = 0;
    return new THREE.Vector3(x, y, z);
}

function init() {

    scene = new THREE.Scene();
    var width = window.innerWidth;
    var height = window.innerHeight;
    renderer = new THREE.WebGLRenderer({
        antialias:true
    });

    renderer.setSize(width, height);
    document.body.appendChild(renderer.domElement);
    camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 20000);
    camera.position.set(1,1,50);

    controller = new controll3r(camera, scene);
    controller.init();

    window.addEventListener('resize', function() {
        var width = window.innerWidth,
            height = window.innerHeight;

        renderer.setSize(width, height);

        camera.aspect = width / height;
        camera.updateProjectionMatrix();
    });

    renderer.setClearColor(0x333F47, 1);

    var light = new THREE.PointLight(0xffffff);
    light.position.set(-100,200,100);
    scene.add(light);

    var material = new THREE.MeshPhongMaterial({
        color: "purple",
        specular: 0x020202,
        side: THREE.DoubleSide
    });

    //var geometry = new THREE.PlaneGeometry( 1, 1, 1 );
    var geometry = new THREE.ParametricGeometry(generateSurface, 64, 64);
    var mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    var lines = new THREE.LineBasicMaterial({ color: 0xAAFFAA });
    // crosshair size
    var x = 0.001, y = 0.001;

    var geometry = new THREE.Geometry();

    // crosshair
    geometry.vertices.push(new THREE.Vector3(0, y, 0));
    geometry.vertices.push(new THREE.Vector3(0, -y, 0));
    geometry.vertices.push(new THREE.Vector3(0, 0, 0));
    geometry.vertices.push(new THREE.Vector3(x, 0, 0));
    geometry.vertices.push(new THREE.Vector3(-x, 0, 0));

    var crosshair = new THREE.Line( geometry, lines );

    // place it in the center
    var crosshairPercentX = 50;
    var crosshairPercentY = 50;
    var crosshairPositionX = (crosshairPercentX / 100) * 2 - 1;
    var crosshairPositionY = (crosshairPercentY / 100) * 2 - 1;

    crosshair.position.x = crosshairPositionX * camera.aspect;
    crosshair.position.y = crosshairPositionY;
    crosshair.position.z = -0.3;
    camera.add( crosshair );

    var plane = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshNormalMaterial());
    plane.material.side = THREE.DoubleSide;
    plane.overdraw = true;
    plane.position.set(0,20,0);
    scene.add(plane);
    controller.collidableMeshList.push(plane);
}

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controller.updatePos(clock);
}


text:
<?php
namespace Sales\Model;

use Zend\InputFilter\Factory as InputFactory;     // <-- Add this import
use Zend\InputFilter\InputFilter;                 // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface;   // <-- Add this import
use Zend\InputFilter\InputFilterInterface;        // <-- Add this import
use Zend\ServiceManager\ServiceLocatorInterface;

class Promos extends \Base\Model\BaseModel implements InputFilterAwareInterface{

    //echo 'hello'; die;

    protected $inputFilter;
    protected $loadedModel;

    const LINKED_TO_ALL = 0;
    const LINKED_TO_RESORTS = 1;
    const LINKED_TO_EVENTS = 2;
    const LINKED_TO_CRUISES = 3;
    const LINKED_TO_RESORT_NAME = 4;
    const LINKED_TO_EVENT_CATEGORY = 5;
    const LINKED_TO_CRUISE_NAME = 6;
    const LINKED_TO_EVENT_NAME = 7;
    const LINKED_TO_ROOM_CATEGORY = 8;
    const LINKED_TO_EVENT_ROOM = 9;
    const LINKED_TO_CABIN_NAME = 10;

    private static $serviceManager;
    public static function initServiceManager($serviceManager){
        if ( self::$serviceManager == null ){
            self::$serviceManager = $serviceManager;
        }
    }
    public static function linkedTo(){
        return array(
            self::LINKED_TO_ALL => array(
                'name'       => 'All',
                'model'      => null,
                'collection' => null,
                'linkedTo'=> array(
                    'entity' => null,
                    'model' => null,
                    'collection' => null,
                ),
            ),
            self::LINKED_TO_RESORTS => array(
                'name'       => 'All Resorts',
                'model'      => null,
                'collection' => null,
                'linkedTo'=> array(
                    'entity' => null,
                    'model' => null,
                    'collection' => null,
                ),
            ),
            self::LINKED_TO_EVENTS => array(
                'name'       => 'All Events',
                'model'      => null,
                'collection' => null,
                'linkedTo'=> array(
                    'entity' => null,
                    'model' => null,
                    'collection' => null,
                ),
            ),
            self::LINKED_TO_CRUISES => array(
                'name'       => 'All Cruises',
                'model'      => null,
                'collection' => null,
                'linkedTo'=> array(
                    'entity' => null,
                    'model' => null,
                    'collection' => null,
                ),
            ),
            self::LINKED_TO_RESORT_NAME => array(
                'name'       => 'Resort Name ',
                'model'      => self::$serviceManager ? self::$serviceManager->get('Resorts') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('Resorts')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\ResortPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('ResortPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('ResortPromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_EVENT_CATEGORY => array(
                'name'       => 'Event Category',
                'model'      => self::$serviceManager ? self::$serviceManager->get('EventCategories') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('EventCategories')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\EventCategoryPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('EventCategoryPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('EventCategoryPromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_CRUISE_NAME => array(
                'name'       => 'Cruise Name',
                'model'      => self::$serviceManager ? self::$serviceManager->get('Cruises') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('Cruises')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\CruisePromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('CruisePromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('CruisePromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_EVENT_NAME => array(
                'name'       => 'Event Name',
                'model'      => self::$serviceManager ? self::$serviceManager->get('Events') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('Events')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\EventsPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('EventsPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('EventsPromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_ROOM_CATEGORY => array(
                'name'       => 'Room Category',
                'model'      => self::$serviceManager ? self::$serviceManager->get('InventoryHotels') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('InventoryHotels')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\RoomsPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('RoomsPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('RoomsPromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_EVENT_ROOM => array(
                'name'       => 'Event Room',
                'model'      => self::$serviceManager ? self::$serviceManager->get('InventoryEvent') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('InventoryEvent')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\EventRoomsPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('EventRoomsPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('EventRoomsPromo')->getCollection() : null,
                ),
            ),
            self::LINKED_TO_CABIN_NAME => array(
                'name'       => 'Cabin Name',
                'model'      => self::$serviceManager ? self::$serviceManager->get('InventoryCruise') : null,
                'collection' => self::$serviceManager ? self::$serviceManager->get('InventoryCruise')->getCollection() : null,
                'linkedTo'=> array(
                    'entity' => '\Base\Entity\CabinsPromo',
                    'model'  => self::$serviceManager ? self::$serviceManager->get('CabinsPromo') : null,
                    'collection' => self::$serviceManager ? self::$serviceManager->get('CabinsPromo')->getCollection() : null,
                ),
            ),
        );
    }

    public function setInputFilter(InputFilterInterface $inputFilter){

        throw new \Exception("Not used");
    }

    public function getInputFilter(){

        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;

      //  d('here');
    /*
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory     = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                        'name'     => 'promoNames',
                        'required' => true,
                        'filters'  => array(
                                        array('name' => 'StripTags'),
                                        array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                                        array(
                                                'name'    => 'StringLength',
                                                'options' => array(
                                                                'encoding' => 'UTF-8',
                                                                'min'      => 2,
                                                                'max'      => 64,
                                                ),
                                        ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
					'name'     => 'name',
					'required' => true,
					'filters'  => array(
							array('name' => 'StripTags'),
							array('name' => 'StringTrim'),
					),
					'validators' => array(
							array(
									'name'    => 'StringLength',
									'options' => array(
											'encoding' => 'UTF-8',
											'min'      => 2,
											'max'      => 255,
									),
							),
					),
			)));

            $inputFilter->add($factory->createInput(array(
					'name'     => 'email',
					'required' => true,
					'filters'  => array(
							array('name' => 'StripTags'),
							array('name' => 'StringTrim'),
					),
					'validators' => array(
							array(
									'name'    => 'EmailAddress',
									'options' => array(
											'encoding' => 'UTF-8',
											'min'      => 5,
											'max'      => 255,
									),
							),
					),
			)));

            $inputFilter->add($factory->createInput(array(
                        'name'     => 'numberAvailable',
                        'required' => true,
                        'filters'  => array(
                                array('name' => 'Int'),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name'     => 'linkedTo',
                        'required' => true,
                        'filters'  => array(
                                array('name' => 'Int'),
                        ),
                        'validators' => array(
                                    array(
                                            'name' => 'Int',
                                            'options' => array(
                                                                'min' => 0,
                                                                'max' => 10,
                                            ),
                                    ),
                        ),

            )));

   /*         $inputFilter->add($factory->createInput(array(
                        'name'     => 'isActive',
                        'required' => true,
                        'filters'  => array(
                                array('name' => 'Int'),
                        ),
            )));
*/
  /*          $inputFilter->add($factory->createInput(array(
                            'name'     => 'dateFrom',
                            'required' => false,
                            'filters'  => array(
                                            array('name' => 'StripTags'),
                                            array('name' => 'StringTrim'),
                            ),
                            'validators' => array(
                                                array(
                                                    'name'    => 'Date',
                                                    'options' => array(
                                                                    'format' => 'Y-m-d',
                                                    ),
                                                ),
                            ),
            )));

            $inputFilter->add($factory->createInput(array(
                            'name'     => 'dateTo',
                            'required' => false,
                            'filters'  => array(
                                            array('name' => 'StripTags'),
                                            array('name' => 'StringTrim'),
                            ),
                            'validators' => array(
                                                array(
                                                    'name'    => 'Date',
                                                    'options' => array(
                                                                    'format' => 'Y-m-d',
                                                    ),
                                                ),
                            ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name'     => 'discount',
                        'required' => true,
                        'validators' => array(
                                                array(
                                                    'name' => 'Float',
                                                    'options' => array(
                                                        'min' => 0,
                                                    ),
                                                ),
                        ),
            )));

   /*         $inputFilter->add($factory->createInput(array(
                        'name'     => 'image',
                        'required' => false,
                        'filters'  => array(
                                        array('name' => 'StripTags'),
                                        array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                                        array(
                                                'name'    => 'StringLength',
                                                'options' => array(
                                                                'encoding' => 'UTF-8',
                                                                'max'      => 255,
                                                ),
                                        ),
                        ),
            ))); */

         /*   $inputFilter->add($factory->createInput(array(
                        'name'     => 'promoCode',
                        'required' => true,
                        'filters'  => array(
                                        array('name' => 'StripTags'),
                                        array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                                        array(
                                                'name'    => 'StringLength',
                                                'options' => array(
                                                                'encoding' => 'UTF-8',
                                                                'min'      => 2,
                                                                'max'      => 32,
                                                ),
                                        ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name'     => 'discountType',
                        'required' => true,
                        'filters'  => array(
                                array('name' => 'Int'),
                        ),
            )));

            $this->inputFilter = $inputFilter;
        }
*/
       // return $this->inputFilter;
    }

    protected function newPromoLinkedObject($typeCode, \Base\Entity\InventoryPromo $promo, $id){
        $object = NULL;
		$linkedTo = $this->linkedTo();
        switch((int)$typeCode){
            case self::LINKED_TO_ALL:
            case self::LINKED_TO_RESORTS:
            case self::LINKED_TO_EVENTS:
            case self::LINKED_TO_CRUISES:
                $object = NULL;
                break;
            case self::LINKED_TO_CRUISE_NAME:
                $object = new \Base\Entity\CruisePromo();
                $object->setPromo($promo);
                $object->setCruiseId($id);
                break;
            case self::LINKED_TO_RESORT_NAME:
                $object = new \Base\Entity\ResortPromo();
                $object->setPromo($promo);
                $object->setResortId($id);
                break;
            case self::LINKED_TO_EVENT_CATEGORY:
                $object = new \Base\Entity\EventCategoryPromo();
                $object->setPromo($promo);
                $object->setEventCategoryId($id);
                break;
            case self::LINKED_TO_EVENT_NAME:
                $object = new \Base\Entity\EventsPromo();
                $object->setPromo($promo);
                $object->setEventId($id);
                break;
            case self::LINKED_TO_ROOM_CATEGORY:
                $object = new \Base\Entity\RoomsPromo();
                $object->setPromo($promo);

                $item = $linkedTo[self::LINKED_TO_ROOM_CATEGORY]['model']->getItem($id);
                $object->setRoom($item);
                break;
            case self::LINKED_TO_EVENT_ROOM:
                $object = new \Base\Entity\EventRoomsPromo();
                $object->setPromo($promo);
                $item = $linkedTo[self::LINKED_TO_EVENT_ROOM]['model']->getItem($id);
                $object->setEventRoom($item);
                break;
            case self::LINKED_TO_CABIN_NAME:
                $object = new \Base\Entity\CabinsPromo();
                $object->setPromo($promo);
                $item = $linkedTo[self::LINKED_TO_CABIN_NAME]['model']->getItem($id);
                $object->setCabin($item);
                break;
        }

        return $object;
    }

    public function saveObject($object, $data = null) {

      //  d('here');

   //  d($object);

        $em = $this->getEntityManager();

        $promo = new $this->_targetEntity;

        $promo->setPromoNames($object['promoNames']);
        //$promo->setPromoNames($object['promotype']);

        if(!empty($object['Name'])){

              $promo->setname($object['Name']);
        }
        if(!empty($object['Email'])){
              $promo->setemail($object['Email']);
        }

        $promo->setLinkedTo($object['linkedTo']);
        $promo->setDiscount($object['discount']);

        $promo->setpromoType($object['promotype']);

        $promo->setDiscountType($object['discountType']);

        $promo->setvalidity($object['validity']);

        $promo->setIsActive($object['isActive']);

        if($object['validity']==1){

        $promo->setNumberAvailable($object['numberAvailable']);

        }
        $promo->setPromoCode($object['promoCode']);

        $promo->setCreated(new \DateTime);
        $promo->setUpdated(new \DateTime);

                // $promo->setCreated($data['type']);

        $promo->setDateFrom(new \DateTime($object['dateFrom']));
        $promo->setDateTo(new \DateTime($object['dateTo']));

       $promo=parent::save($promo);
       // $promo = parent::save($object);

        //d('here after save');
        if($data){
            foreach ($data as $id){
                $object = $this->newPromoLinkedObject($promo->getLinkedTo(), $promo, $id);
                parent::save($object);
            }
        }

      //  d($object);
    }

    protected function deleteLinkedObjects($promo){

        //d($promo);

        for($i = self::LINKED_TO_RESORT_NAME;$i<=self::LINKED_TO_CABIN_NAME;$i++){
            $linkedTo = self::linkedTo();

           // d($linkedTo);

            $entity = $linkedTo[$i]['linkedTo']['entity'];

          //  d($entity);

            $em = $this->getEntityManager();
            $query = $em->createQuery("DELETE FROM $entity e WHERE e.promo = :promo");
            $query->setParameter('promo', $promo['id']);
            $query->getResult();
        }
    }

    public function updateObject($promo, $data = null) {

      //  d($promo);

        $this->deleteLinkedObjects($promo);

        $em = $this->getEntityManager();
        $entity = $em->find('Base\Entity\InventoryPromo', (int)$promo['id']);

        //d($entity);

       // d('here im in update object');

         $entity->setPromoNames($promo['promoNames']);
        //$promo->setPromoNames($object['promotype']);

        if($promo['promotype']==2){

            //echo 'die inside if';

           $entity->setname($promo['name']);
           $entity->setemail($promo['email']);
        }
        else{

            //echo 'else';
           $entity->setname(Null);
           $entity->setemail(Null);
        }

        //die;

        $entity->setLinkedTo($promo['linkedTo']);
        $entity->setDiscount($promo['discount']);

        $entity->setpromoType($promo['promotype']);

        $entity->setDiscountType($promo['discountType']);

        $entity->setvalidity($promo['validity']);
        if($promo['validity']==1){

        $entity->setNumberAvailable($promo['numberAvailable']);

        }
        $entity->setPromoCode($promo['promoCode']);

        $entity->setIsActive($promo['isActive']);

      //  $promo->setCreated(new \DateTime);
        $entity->setUpdated(new \DateTime);

                // $promo->setCreated($data['type']);

        $entity->setDateFrom(new \DateTime($promo['dateFrom']));
        $entity->setDateTo(new \DateTime($promo['dateTo']));

        $promo = parent::save($entity);
        if($data){
            foreach ($data as $id){
                $object = $this->newPromoLinkedObject($promo->getLinkedTo(), $promo, $id);
                parent::save($object);
            }
        }
    }

    protected function isValidPromoCode($form){
        if($this->checkItem(array('promoCode'=>$form->getData()->getPromoCode()))){
            $form->get('promoCode')->setMessages(array('This promo code already exists'));
            return false;
        }
        return true;
    }

    public function isValidModel($form){

        return $this->isValidPromoCode($form);
    }

    public function isValidModelOnEdit($form){

        if($this->checkItem(array(
            'id'=>$form->getData()->getId(),
            'promoNames'=>$form->getData()->getPromoNames(),
            'promoCode'=>$form->getData()->getPromoCode(),
            ))
	){
            return true;
        }
        return $this->isValidModel($form);
    }

    public function getCollection($page = false) {
        $collection = parent::getCollection($page);
        foreach ($collection as $object){
        	$linkedTo = self::linkedTo();
            $object->setLinkedTo($linkedTo[$object->getLinkedTo()]['name']);
        }
        return $collection;
    }

    public function getPromosLinkedTo(ServiceLocatorInterface $serviceManager, $typeCode = 0, $id1 = 0, $id2 = 0){
        self::initServiceManager($serviceManager);
        /*
        switch((int)$typeCode){
            case self::LINKED_TO_ALL:

            case self::LINKED_TO_EVENTS:
            case self::LINKED_TO_CRUISES:
                $object = NULL;
                break;
            case self::LINKED_TO_RESORT_NAME:
                $item = self::getPromoRoomCategoty($id2);
                if($item) return $item;
            case self::LINKED_TO_RESORTS:

            case self::LINKED_TO_CRUISE_NAME:
                $object = new \Base\Entity\CruisePromo();
                $object->setPromo($promo);
                $object->setCruiseId($id);
                break;

            case self::LINKED_TO_EVENT_CATEGORY:
                $object = new \Base\Entity\EventCategoryPromo();
                $object->setPromo($promo);
                $object->setEventCategoryId($id);
                break;
            case self::LINKED_TO_EVENT_NAME:
                $object = new \Base\Entity\EventsPromo();
                $object->setPromo($promo);
                $object->setEventId($id);
                break;
            case self::LINKED_TO_ROOM_CATEGORY:
                $object = new \Base\Entity\RoomsPromo();
                $object->setPromo($promo);
                $item = $this->linkedTo()[self::LINKED_TO_ROOM_CATEGORY]['model']->getItem($id);
                $object->setRoom($item);
                break;
            case self::LINKED_TO_EVENT_ROOM:
                $object = new \Base\Entity\EventRoomsPromo();
                $object->setPromo($promo);
                $item = $this->linkedTo()[self::LINKED_TO_EVENT_ROOM]['model']->getItem($id);
                $object->setEventRoom($item);
                break;
            case self::LINKED_TO_CABIN_NAME:
                $object = new \Base\Entity\CabinsPromo();
                $object->setPromo($promo);
                $item = $this->linkedTo()[self::LINKED_TO_CABIN_NAME]['model']->getItem($id);
                $object->setCabin($item);
                break;
        }
        */
    }

    public static function getPromoRoomCategoty($id){
    	$linkedTo = self::linkedTo();
        $model = $linkedTo[self::LINKED_TO_EVENT_ROOM]['model'];
        if($model){
            $room = $model->getItemBy(array('id'=>$id));
            if($room){
                $em = self::$serviceManager->get('Doctrine\ORM\EntityManager');
                $qb = $em->createQueryBuilder();
                $qb->select(array('ih'))
                    ->from('\Base\Entity\InventoryPromo', 'ih')
                    //->innerJoin('\Base\Entity\RoomsPromo', 'rp', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN, 'rp.room = cr.id')
                    ->where('ih.id=:id')
                    ->andWhere('ih.dateFrom <= :dateFrom')
                    ->andWhere('ih.dateTo >= :dateTo')
                    ->setParameter('id', $id)
                    ->setParameter('dateFrom', $date->format('Y-m-d'))
                    ->setParameter('dateTo', $date->format('Y-m-d'))
                    ->setMaxResults(1);
                        $query = $qb->getQuery();

                return $model->getItemBy(array('room'=>$room), true);
            }
            return null;
        }
        return null;
    }

    public static function getPromoEventRoom($id){
        $linkedTo = self::linkedTo();
        $model = $linkedTo[self::LINKED_TO_EVENT_ROOM]['model'];
        if($model){
            $room = $model->getItemBy(array('id'=>$id));
            if($room){
                $model = $linkedTo[self::LINKED_TO_EVENT_ROOM]['linkedTo']['model'];
                return $model->getItemBy(array('eventRoom'=>$room), true);
            }
            return null;
        }
        return null;
    }

    public static function getPromoCabinName($id){
        $linkedTo = self::linkedTo();
        $model = $linkedTo[self::LINKED_TO_CABIN_NAME]['model'];
        if($model){
            $cabin = $model->getItemBy(array('id'=>$id));
            if($cabin){
                $model = $linkedTo[self::LINKED_TO_CABIN_NAME]['linkedTo']['model'];
                return $model->getItemBy(array('cabin'=>$cabin), true);
            }
            return null;
        }
        return null;
    }

    public static function getPromoResort($id){
        $linkedTo = self::linkedTo();
        $model = $linkedTo[self::LINKED_TO_RESORTS]['model'];
        if($model){
            $cabin = $model->getItemBy(array('resortId'=>$id));
            if($cabin){
                $model = $linkedTo[self::LINKED_TO_CABIN_NAME]['linkedTo']['model'];
                return $model->getItemBy(array('cabin'=>$cabin), true);
            }
            return null;
        }
        return null;
    }
}


text:
// ****************************************************************************
// <copyright file="DeviceStatusService.cs" company="Pedro Lamas">
// Copyright © Pedro Lamas 2014
// </copyright>
// ****************************************************************************
// <author>Pedro Lamas</author>
// <email>pedrolamas@gmail.com</email>
// <project>Cimbalino.Toolkit.Core</project>
// <web>http://www.pedrolamas.com</web>
// <license>
// See license.txt in this solution or http://www.pedrolamas.com/license_MIT.txt
// </license>
// ****************************************************************************

using System;
using Cimbalino.Toolkit.Helpers;
using Microsoft.Phone.Info;
using Windows.Phone.Devices.Power;
using Windows.Phone.System.Power;

namespace Cimbalino.Toolkit.Services
{
    /// <summary>
    /// Represents an implementation of the <see cref="IDeviceStatusService"/>.
    /// </summary>
    public class DeviceStatusService : IDeviceStatusService
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceStatusService"/> class.
        /// </summary>
        public DeviceStatusService()
        {
            Battery.GetDefault().RemainingChargePercentChanged += OnPowerChanged;
            PowerManager.PowerSavingModeChanged += OnPowerChanged;
        }

        /// <summary>
        /// Occurs when the power status has changed
        /// </summary>
        public event EventHandler<PowerStatusChangedEventArgs> PowerStatusChanged;

        /// <summary>
        /// Gets the memory usage of the current application in bytes.
        /// </summary>
        /// <value>The memory usage of the current application in bytes.</value>
        public virtual long ApplicationCurrentMemoryUsage
        {
            get
            {
                return DeviceStatus.ApplicationCurrentMemoryUsage;
            }
        }

        /// <summary>
        /// Gets the maximum amount of memory that your application process can allocate.
        /// </summary>
        /// <value>The maximum amount of memory that your application process can allocate.</value>
        public virtual long ApplicationMemoryUsageLimit
        {
            get
            {
                return DeviceStatus.ApplicationMemoryUsageLimit;
            }
        }

        /// <summary>
        /// Gets the peak memory usage of the current application in bytes.
        /// </summary>
        /// <value>The peak memory usage of the current application in bytes.</value>
        public virtual long ApplicationPeakMemoryUsage
        {
            get
            {
                return DeviceStatus.ApplicationPeakMemoryUsage;
            }
        }

        /// <summary>
        /// Gets the firmware version running on the device.
        /// </summary>
        /// <value>The firmware version running on the device.</value>
        public virtual string DeviceFirmwareVersion
        {
            get
            {
                return DeviceStatus.DeviceFirmwareVersion;
            }
        }

        /// <summary>
        /// Gets the hardware version running on the device.
        /// </summary>
        /// <value>The hardware version running on the device.</value>
        public virtual string DeviceHardwareVersion
        {
            get
            {
                return DeviceStatus.DeviceHardwareVersion;
            }
        }

        /// <summary>
        /// Gets the device manufacturer name.
        /// </summary>
        /// <value>The device manufacturer name.</value>
        public virtual string DeviceManufacturer
        {
            get
            {
                return DeviceStatus.DeviceManufacturer;
            }
        }

        /// <summary>
        /// Gets the device name.
        /// </summary>
        /// <value>The device name.</value>
        public virtual string DeviceName
        {
            get
            {
                return DeviceStatus.DeviceName;
            }
        }

        /// <summary>
        /// Gets the physical RAM size of the device in bytes.
        /// </summary>
        /// <value>The physical RAM size of the device in bytes.</value>
        public virtual long DeviceTotalMemory
        {
            get
            {
                return DeviceStatus.DeviceTotalMemory;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the device is a low memory device (less than 256 MB of memory installed).
        /// </summary>
        /// <value>true if the device is a low memory device (less than 256 MB of memory installed); otherwise, false.</value>
        public virtual bool IsLowMemoryDevice
        {
            get
            {
                return DeviceTotalMemory <= 268435456;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the user has deployed the physical hardware keyboard of the device.
        /// </summary>
        /// <value>true if the keyboard is deployed; otherwise, false.</value>
        public virtual bool IsKeyboardDeployed
        {
            get
            {
                return ExceptionHelper.ThrowNotSupported<bool>("To use this method, add Cimbalino.Toolkit assembly to the project and use the DeviceStatusWithKeyboardService instead. This method can't be called from a Background Agent.");
            }
        }

        /// <summary>
        /// Gets a value indicating whether the device contains a physical hardware keyboard.
        /// </summary>
        /// <value>true if the device contains a physical hardware keyboard; otherwise, false.</value>
        public virtual bool IsKeyboardPresent
        {
            get
            {
                return ExceptionHelper.ThrowNotSupported<bool>("To use this method, add Cimbalino.Toolkit assembly to the project and use the DeviceStatusWithKeyboardService instead. This method can't be called from a Background Agent.");
            }
        }

        /// <summary>
        /// Gets the a value indicating whether the device is currently running on battery power or is plugged in to an external power supply.
        /// </summary>
        /// <value>true if the device is currently running on battery power or is plugged in to an external power supply; otherwise, false.</value>
        public virtual DeviceStatusServicePowerSource PowerSource
        {
            get
            {
                switch (DeviceStatus.PowerSource)
                {
                    case Microsoft.Phone.Info.PowerSource.Battery:
                        return DeviceStatusServicePowerSource.Battery;

                    case Microsoft.Phone.Info.PowerSource.External:
                        return DeviceStatusServicePowerSource.External;

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }

        /// <summary>
        /// Gets the a value indicating the percent of the battery remaining on the device
        /// </summary>
        /// <value>null if the platform can't report this, otherwise, the battery percentage</value>
        public virtual int? RemainingChargePercent
        {
            get { return Battery.GetDefault().RemainingChargePercent; }
        }

        /// <summary>
        /// Gets the value indicating if the device is in power saver mode.
        /// </summary>
        /// <value>
        /// Null if the platform can't report this, otherwise [true] if in power saver mode
        /// </value>
        public virtual bool? IsInPowerSaverMode
        {
            get { return PowerManager.PowerSavingMode == PowerSavingMode.On; }
        }

        private void OnPowerChanged(object sender, object o)
        {
            var eventHandler = PowerStatusChanged;
            var args = new PowerStatusChangedEventArgs(RemainingChargePercent, IsInPowerSaverMode);

            eventHandler?.Invoke(this, args);
        }
    }
}


text:
(function($) {
  $.fn.getPotentialHeight = function() {
        var $element = this;
        //heightOfParent is the height of parents content (inside the padding)
        var heightOfParent = $element.parent().height();
        offset = $element.offset();
        topOfElement = offset.top;
        return (heightOfParent - topOfElement);
  };
})(jQuery);

$(document).ready(
    function() {
        var potentialHeight = $('#filter-list').getPotentialHeight();
        $('#filter-list').css('height', potentialHeight);
    }
);


text:
A complete reference for all html elements with css for them.

## Synopsis

**Webster** is your personal collection of every html element, with various css styles for it. These pieces of codes would be very helpful while making any website, editing a template, developing your own website from scratch or any other frontend related work on your website, these can be directly used by you or anyone else in your code.

## Motivation
The code snippets from here can be directly used by anyone.
Especially for beginners, it will be a very good way to learn contributing in a community.
Contributing here is easy, you just need to have basics of HTML and CSS and you are ready to go!!!!!!

## Contribution guidelines
It is simple. Just make something like sample1 directory in forms.
Follow following steps:
   1. Browse the element you want to add in **html elements**.
   2. If your element already exists (like forms) then create new directory in that repo with sample1, sample2 ,...
      else make a new repo with name of the element such as img, header, navbar, footer etc. and create a new directory with sample1 name in it.
   3. Now add your files in it.
   4. Enter your html and css content in the file.
   5. Now add a screenshot of your html page in browser.
   6. Now create a pull request and it's done!!!

Or refer **[CONTRIBUTION.md](https://github.com/himanshu-daga/Webster/blob/master/CONTRIBUTING.md)** :

## License

**MIT License** - A short and simple permissive license.


text:
layout: page
title: Fitzgerald 10th Anniversary
date: 2016-05-24
author: Nathan Wade
tags: weekly links, java
status: published
summary: Pellentesque at nunc id mi vestibulum euismod. Phasellus.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 11/08/2018
  endDate: 11/13/2018
  ctyhocn: CHLOHHX
  groupCode: F1A
published: true
---
Praesent pretium fermentum pharetra. Proin nulla eros, malesuada id est ac, commodo rhoncus nulla. Vivamus nisl augue, consequat quis bibendum vitae, posuere eu metus. Proin malesuada lacinia eros sit amet vestibulum. Mauris auctor est at maximus fringilla. Suspendisse potenti. Nulla at mauris feugiat, pulvinar erat ac, mattis sem. Duis faucibus nisl eget leo tincidunt consequat. Cras euismod, sem a ultrices vestibulum, erat nunc consequat orci, ut bibendum eros lectus a ipsum. Nunc tempor lorem eu condimentum porttitor. Pellentesque massa sem, condimentum at pharetra sed, vestibulum in libero.

* Etiam quis urna et justo sagittis aliquam ornare egestas tellus
* Proin dapibus ipsum ac lacus euismod lobortis.

Maecenas non lacus eros. Vestibulum eu fermentum mauris. Donec tincidunt velit nunc, in laoreet metus maximus vel. Integer varius orci et ligula pharetra, ut tincidunt ipsum imperdiet. Fusce ut finibus nunc, in congue neque. Pellentesque porta sapien diam, ut feugiat erat dictum ut. Sed finibus malesuada scelerisque. Maecenas non rhoncus enim. Sed in tincidunt ante. Quisque eget sem bibendum, scelerisque felis a, ullamcorper enim. Phasellus congue, massa nec tincidunt bibendum, erat erat pretium urna, eget molestie augue erat ac velit.


text:
var _ = require('lodash');

function storeSocket(socket) {
  return {
    type: 'STORE_SOCKET',
    payload: {
      socket: socket,
      id: _.uniqueId('socket_'),
    },
  };
}

function removeSocket(socketId) {
  return {
    type: 'REMOVE_SOCKET',
    payload: {
      socketId,
    },
  };
}

function createSession(sessionId, owner){
  return {
    type: 'CREATE_SESSION',
    payload: {
      sessionId: sessionId || _.uniqueId('SESSION_'),
      owner,
    },
  };
}

function joinSession(sessionId, socketId) {
  return {
    type: 'JOIN_SESSION',
    payload: {
      sessionId: sessionId,
      socketId: socketId,
    },
  };
}

function closeSession(sessionId) {
  return {
    type: 'CLOSE_SESSION',
    payload: {
      sessionId: sessionId,
    },
  };
}

function addClock(sessionId, clockName) {
  return {
    type: 'ADD_CLOCK',
    payload: {
      sessionId: sessionId,
      clockId: _.uniqueId('clock_'),
      clockName,
    },
  };
}

function deleteClock(clockId) {
  return {
    type: 'DELETE_CLOCK',
    payload: { clockId },
  };
}

function countDown(data){
  return {
    type: 'COUNTDOWN',
    payload: {
      id: data.clockId,
      initialServerDate: new Date(),
      countdown: data.seconds,
    },
  };
}

module.exports = {
  storeSocket,
  removeSocket,
  createSession,
  joinSession,
  closeSession,
  addClock,
  deleteClock,
  countDown,
};


text:
package org.blocks4j.commons.environment;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import org.apache.commons.lang3.StringUtils;

public class LocalHostname {

    /**
     * @param fallbackName - the name to return in case of error
     */
    public static String getName(String fallbackName) {
        String runtimeHostName = runtimeStrategy();
        String localHostName = fallbackStrategy();
        return runtimeStrategy() != null ? runtimeHostName : localHostName != null ? localHostName : fallbackName;
    }

    private static String fallbackStrategy() {
        try {
            return StringUtils.stripAccents(InetAddress.getLocalHost().getHostName());
        } catch (Exception e) {
            return null;
        }
    }

    private static String runtimeStrategy() {
        BufferedReader in = null;
        try {
            Process proc = Runtime.getRuntime().exec("hostname");
            proc.waitFor();
            in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            return StringUtils.stripAccents(in.readLine());
        } catch (Exception e) {
            return null;

        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ignored) {}
            }
        }
    }
}


text:
package net.youmi.ads.base.template;

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

/**
 * @author zhitao
 * @since 2017-04-14 16:29
 */
public abstract class TListenerManager<T> {

	private List<T> mListeners;

	protected synchronized List<T> getListeners() {
		if (mListeners == null) {
			mListeners = new ArrayList<T>();
		}
		return mListeners;
	}

	public boolean addListener(T listener) {
		if (listener != null) {
			final List<T> list = getListeners();
			if (!list.contains(listener)) {
				return list.add(listener);
			} else {
				return true;
			}
		}
		return false;
	}

	public boolean removeListener(T listener) {
		if (listener != null) {
			final List<T> list = getListeners();
			return list.remove(listener);
		}
		return false;
	}

	public boolean isEmpty() {
		if (mListeners == null) {
			return true;
		}
		return mListeners.isEmpty();
	}

}


text:
import DNS = require('dns2');

const dns = new DNS();

(async () => {
  const result = await dns.resolveA('google.com');
  console.log(result.answers);
})();

const { Packet } = DNS;

const server = DNS.createServer((request, send, rinfo) => {
  const response = Packet.createResponseFromRequest(request);
  const [ question ] = request.questions;
  const { name } = question;
  response.answers.push({
    name,
    type: Packet.TYPE.A,
    class: Packet.CLASS.IN,
    ttl: 300,
    address: '8.8.8.8'
  });
  send(response);
});

server.on('request', (request, response, rinfo) => {
  console.log(request.header.id, request.questions[0]);
});

server.listen(5333);


text:
package org.softpres.donkeysql;

import org.junit.Before;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Unit tests for {@link DB}.
 */
public class DBStoredProcTest {

  private DataSource dataSource;

  @Before
  public void populateDataSource() throws Exception {
    dataSource = TestDB.createPopulatedDataSource();
  }

  @Test
  public void callWithIndexedParameters() {
    createStoredProc("concatSelf");

    Stream<String> results = DB.with(dataSource)
          .query("{call concatSelf(?)}")
          .params("/abc123")
          .map(resultSet -> resultSet.getString(1))
          .execute();

    assertThat(results).containsExactly("/abc123/abc123");
  }

  @Test
  public void callWithNamedParameters() {
    createStoredProc("plus");

    Stream<Integer> results = DB.with(dataSource)
          .query("{call plus(:first, :second)}")
          .param("first", 11)
          .param("second", 31)
          .map(resultSet -> resultSet.getInt(1))
          .execute();

    assertThat(results).containsExactly(42);
  }

  private void createStoredProc(String name) {
    try (
          Connection connection = dataSource.getConnection();
          Statement statement = connection.createStatement()
    ) {
      createStoredProc(statement, name);
    } catch (SQLException e) {
      throw new UncheckedSQLException(e);
    }
  }

  private void createStoredProc(Statement statement, String name) throws SQLException {
    statement.execute("CREATE ALIAS " + name + " FOR \"" +
          StoredProc.class.getName() +
          "." + name + "\"");
  }

  @SuppressWarnings("unused") // Reflected by H2
  public static class StoredProc {
    public static String concatSelf(String text) {
      return text + text;
    }
    public static int plus(int a, int b) {
      return a + b;
    }
  }

}


text:
require_dependency 'zapier_rest_hooks/application_controller'

module ZapierRestHooks
  class HooksController < ApplicationController
    def create
      hook = Hook.new(hook_params)
      render nothing: true, status: 500 && return unless hook.save
      Rails.logger.info "Created REST hook: #{hook.inspect}"
      # The Zapier documentation says to return 201 - Created.
      render json: hook.to_json(only: :id), status: :created
    end

    def destroy
      hook = Hook.find(params[:id]) if params[:id]
      hook = Hook.find_by(subscription_url: params[:subscription_url]).destroy if hook.nil? && params[:subscription_url]
      Rails.logger.info "Destroying REST hook: #{hook.inspect}"
      hook.destroy
      head :ok
    end

    private

    def hook_params
      params[:event_name] ||= params[:name]
      params[:hook] = params
      params.require(:hook).permit(:event_name, :target_url, :owner_id, :owner_class_name, :subscription_url)
    end
  end
end


text:
package org.elkoserver.server.repository;

import org.elkoserver.foundation.actor.BasicProtocolActor;
import org.elkoserver.foundation.actor.BasicProtocolHandler;
import org.elkoserver.foundation.actor.RoutingActor;
import org.elkoserver.foundation.json.MessageHandlerException;
import org.elkoserver.foundation.net.Connection;
import org.elkoserver.foundation.server.metadata.AuthDesc;
import org.elkoserver.util.trace.Trace;

/**
 * Actor for a connection to a repository.  An actor may be associated with
 * either or both of the two service protocols offered by a repository ('admin'
 * and 'rep'), according to the permissions granted by the factory.
 */
class RepositoryActor extends RoutingActor implements BasicProtocolActor
{
    /** Factory holding listener configuration information. */
    private RepositoryActorFactory myFactory;

    /** The repository itself. */
    private Repository myRepository;

    /** True if actor has been disconnected. */
    private boolean amLoggedOut;

    /** Optional convenience label for logging and such. */
    private String myLabel;

    /** True if actor is authorized to perform admin operations. */
    private boolean amAdmin;

    /** True if actor is authorized to perform repository operations. */
    private boolean amRep;

    /** Trace object for diagnostics. */
    private Trace tr;

    /**
     * Constructor.
     *
     * @param connection  The connection for talking to this actor.
     * @param factory  The factory that created this actor.
     * @param appTrace  Trace object for diagnostics.
     */
    RepositoryActor(Connection connection, RepositoryActorFactory factory,
                    Trace appTrace)
    {
        super(connection, factory.refTable());
        tr = appTrace;
        myFactory = factory;
        myRepository = factory.repository();
        myLabel = null;
        amLoggedOut = false;
        amAdmin = false;
        amRep = false;
    }

    /**
     * Handle loss of connection from the actor.
     *
     * @param connection  The connection that died.
     * @param reason  Exception explaining why.
     */
    public void connectionDied(Connection connection, Throwable reason) {
        doDisconnect();
        tr.eventm(this + " connection died: " + connection + reason);
    }

    /**
     * Do the actual work of authorizing an actor.
     */
    public boolean doAuth(BasicProtocolHandler handler, AuthDesc auth,
                          String label)
    {
        myLabel = label;
        boolean success = false;
        if (myFactory.verifyAuthorization(auth)) {
            if (handler instanceof AdminHandler) {
                if (myFactory.allowAdmin()) {
                    amAdmin = true;
                    success = true;
                }
            } else if (handler instanceof RepHandler) {
                if (myFactory.allowRep()) {
                    amRep = true;
                    success = true;
                    myRepository.countRepClients(1);
                }
            }
        }
        return success;
    }

    /**
     * Do the actual work of disconnecting an actor.
     */
    public void doDisconnect() {
        if (!amLoggedOut) {
            tr.eventm("disconnecting " + this);
            if (amRep) {
                myRepository.countRepClients(-1);
            }
            amLoggedOut = true;
            close();
        }
    }

    /**
     * Guard function to guarantee that an operation is being attempted by an
     * actor who is authorized to do admin operations.
     *
     */
    public void ensureAuthorizedAdmin() throws MessageHandlerException {
        if (amLoggedOut) {
            throw new MessageHandlerException("actor " + this +
                " attempted admin operation after logout");
        } else if (!amAdmin) {
            doDisconnect();
            throw new MessageHandlerException("actor " + this +
                " attempted admin operation without authorization");
        }
    }

    /**
     * Guard function to guarantee that an operation is being attempted by an
     * actor who is authorized to do repository operations.
     *
     */
    public void ensureAuthorizedRep() throws MessageHandlerException {
        if (amLoggedOut) {
            throw new MessageHandlerException("actor " + this +
                " attempted repository operation after logout");
        } else if (!amRep) {
            doDisconnect();
            throw new MessageHandlerException("actor " + this +
                " attempted repository operation without authorization");
        }
    }

    /**
     * Return this actor's label.
     */
    String label() {
        return myLabel;
    }

    /**
     * @return a printable representation of this actor.
     */
    public String toString() {
        if (myLabel == null) {
            return super.toString();
        } else {
            return myLabel;
        }
    }
}


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
  <info type="application/xhtml+xml">
History of the <blink> tag
</info>
</feed>


text:
#import <IDEKit/IDEKeyDrivenNavigableItem.h>

@interface IDEGeniusResultsGraphNodeNavigableItem : IDEKeyDrivenNavigableItem
{
}

- (BOOL)isLeaf;

@end


text:
@class QHCCommentModel;
@interface QHCCommentCell : UITableViewCell

@property(nonatomic, strong) QHCCommentModel *commentModel;

+(instancetype)cellWithTableView:(UITableView *)tableView;

@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Пример манипуляций над CSS</title>
    <link rel="profile" href="http://gmpg.org/xfn/11"/>
    <link rel="shortcut icon" href="http://anton.shevchuk.name/favicon.ico"/>
    <link rel="stylesheet" href="css/styles.css"/>

        <menu label="Try...">
            ← Back
            Index §
            Reload ¤
            Next →

alert($('p').css('color'))

            <button type="button" class="code">Run Code</button>

$('p').css('color','red')

            <button type="button" class="code">Run Code</button>

$('p').css({
    'color':'green',
    'background-color':'#000'
})

            <button type="button" class="code">Run Code</button>

$('p').css({
    color:'#0F0F0F',
    backgroundColor:'#fff',
    width:'auto'
})

            <button type="button" class="code">Run Code</button>

$('p').css('width', function(i, v){
    return parseFloat(v) * 1/(i+1)
})

            <button type="button" class="code">Run Code</button>
        </menu>

Пример манипуляций над CSS

Пробуем... →

Article Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rutrum,
            lectus eu varius consectetur, libero velit hendrerit augue, ut posuere enim neque
            in libero. Donec eget sagittis nibh. Suspendisse sed tincidunt urna. Cras quis
            euismod neque. Maecenas auctor ultricies posuere. Pellentesque luctus pulvinar dui
            eget semper. Donec sodales odio eu sapien varius luctus. Donec dictum feugiat diam
            at malesuada. Sed nec massa in augue condimentum faucibus quis ut diam. Quisque
            nisl sem, semper nec vulputate vel, mattis sit amet justo. Aliquam purus felis,
            tempor at scelerisque quis, tincidunt in neque. Etiam ut risus diam. Pellentesque
            fermentum risus id elit feugiat cursus. Ut fringilla dictum diam, sed iaculis
            lorem pulvinar ut. Cras vel elit id velit commodo viverra sit amet vel orci.

Article Title

Duis in vestibulum sem. Cras euismod tincidunt dui, et scelerisque tellus condimentum vel.
            Maecenas et urna sit amet risus fermentum rhoncus nec porttitor ligula. Maecenas sit amet
            turpis enim, ut iaculis est. Duis feugiat, lacus id placerat porttitor, lorem augue gravida
            nisi, eu porta eros risus et lectus. Maecenas vestibulum nunc vel ipsum tincidunt sit amet
            blandit sapien bibendum. Proin vel vulputate nisl. Duis tempor imperdiet placerat. Pellentesque
            faucibus consequat magna, et bibendum nisl egestas non. Pellentesque sit amet mattis augue.
            Aenean at diam tincidunt purus sollicitudin gravida non in nisi. Fusce bibendum, magna in
            adipiscing mattis, sem risus fringilla mi, nec gravida lectus lectus at nibh. Suspendisse
            adipiscing elementum laoreet. Suspendisse sem erat, varius quis aliquet vitae, dapibus sed
            nibh. Nullam iaculis sem at mauris faucibus in vestibulum libero pretium. Aliquam eu turpis
            libero. Fusce et ultrices lectus.

            ©copyright 2012-2017 Anton Shevchuk — jQuery Book


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

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

  Copyright 2017 Nextdoor.com, Inc
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>bender</artifactId>
    <groupId>com.nextdoor.bender</groupId>
    <version>2.0.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <name>Bender Common</name>
  <artifactId>bender-common</artifactId>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-s3</artifactId>
      <version>${aws-java-sdk.version}</version>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-lambda</artifactId>
      <version>${aws-java-sdk.version}</version>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-lambda-java-core</artifactId>
      <version>${aws-lambda-java-core.version}</version>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-sns</artifactId>
      <version>${aws-java-sdk.version}</version>
    </dependency>
  </dependencies>
</project>


text:
var Ogre= require('../'),
    Cursor= require('../lib/cursor'),
    type= require('elucidata-type'),
    // test= require('prova')
    test= require('tape'),
    _= require( './_helpers')

function testx(){}

test( 'Basic cursor tests', function( t ){

  t.notEqual( Ogre, null, "exported value is not null" )
  t.equal( typeof Ogre, 'function', "exported value is a function" )

  test( '.scopeTo( path)', function(t){

    var src= { name:'Ogre', info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
        ds= new Ogre(src)

    t.ok( ds.scopeTo, "exists" )

    t.end()
  })

  t.end()
})

test( 'Sub-tree modification via Cursor.set()', function( t){
  var src= new Ogre({ left:{}, right:{}, middle:{} }, { strict:false }),
      left= src.scopeTo( 'left'),
      right= src.scopeTo( 'right')

  t.ok( left, 'Left cursor created.')
  t.ok( right, 'Right cursor created.')

  t.ok( left.get(), 'Left.get() returns non-empty object.')
  t.ok( right.get(), 'Right.get() returns non-empty object.')

  src.set( 'middle.name', 'Something')

  t.equal( left.get(), src.get( 'left'), 'Sub-tree unaffected by unrelated change.')
  t.equal( right.get(), src.get( 'right'), 'Sub-tree unaffected by unrelated change.')

  var left_value= 'LEFT VALUE'
  left.set( left_value)
  t.equal( src.get( 'left'), left_value, 'String value. Sub-tree correctly modifies root tree.')

  left_value= 42
  left.set( left_value)
  t.equal( src.get( 'left'), left_value, 'Number value. Sub-tree correctly modifies root tree.')

  left_value= null
  left.set( left_value)
  t.equal( src.get( 'left'), left_value, 'Null value. Sub-tree correctly modifies root tree.')

  var right_value= { label:'RIGHT VALUE'}
  right.set( right_value)
  t.equal( src.get( 'right'), right_value, 'Object value. Sub-tree correctly modifies root tree.')

  right_value= ''
  right.set( right_value)
  t.equal( src.get( 'right'), right_value, 'Empty string value. Sub-tree correctly modifies root tree.')

  right_value= ['left', 'value']
  right.set( right_value)
  t.equal( src.get( 'right'), right_value, 'Array value. Sub-tree correctly modifies root tree.')

  right.push(['new'])
  t.equal( src.get( 'right.length'), 3, 'Array value. Sub-tree correctly modifies root tree.')

  right.push({})
  t.ok( src.get( 'right'), 'Empty object. Sub-tree correctly modifies root tree.')

  right.set({})
  left.set({})

left_value= 'LEFT VALUE'
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed String value. Sub-tree correctly modifies root tree.')

left_value= 42
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed Number value. Sub-tree correctly modifies root tree.')

left_value= null
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed Null value. Sub-tree correctly modifies root tree.')

left.set({})
left_value= 'Hello'
left.set( 'child.much.deeper', left_value)
t.equal( src.get( 'left.child.much.deeper'), left_value, 'Deeply pathed string value. Sub-tree correctly modifies root tree.')

right_value= { label:'RIGHT VALUE'}
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Object value. Sub-tree correctly modifies root tree.')

right_value= ''
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Empty string value. Sub-tree correctly modifies root tree.')

right_value= ['left', 'value']
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Array value. Sub-tree correctly modifies root tree.')

right.push('child', ['new'])
t.equal( src.get( 'right.child.length'), 3, 'Pathed Array value. Sub-tree correctly modifies root tree.')

  t.end()
})

test( 'Sub-tree events (extracted from app)', function ( t){
  t.plan( 14 )

  var src= new Ogre({
        peer1: {
          name: 'p1'
        },
        peer2: {
          name: 'p2'
        }
      }, { strict:false}),
      _root_count= 0,
      _p1_count= 0,
      _p2_count= 0

  function root_onChange( keys){
    // console.log('orge.onChange', keys)
    _root_count += 1
    t.ok( keys, 'root onChange')
  }
  src.onChange( root_onChange)

  var p1= src.scopeTo( 'peer1'),
      p2= src.scopeTo( 'peer2'),
      p22= src.scopeTo( 'peer2')

  function peer1_onChange( keys){
    _p1_count += 1
    t.ok( keys, 'peer1 onChange')
    // console.log( 'peer1.onChange', keys)
  }
  p1.onChange( peer1_onChange)

  function peer2_onChange( keys){
    _p2_count += 1
    t.ok( keys, 'peer2 onChange')
    // console.log( 'peer2.onChange', keys)
  }
  p2.onChange( peer2_onChange)

  // p22.onChange(function(){
  //   console.log( ">>>>>>>>>>>> Second call")
  //   console.log( Cursor.listenerInfo( true))
  // })

  src.set( 'peer1.name', 'TEST')
  src.set( 'peer2.name', 'SHIT')

  setTimeout(function(){
    src.set('other.stuff', 'JUNK')
  }, 100)

  setTimeout(function(){
    src.set('peer1.has.stuff', 'JUNK')
  }, 200)

  setTimeout(function(){
    src.set('peer2.has.more.stuff', 'JUNK')
  }, 300)

  setTimeout(function(){
    var expected= { totalEventHandlers: 2, totalKeyWatches: 2, totalSources: 1 }
    t.deepLooseEqual( Cursor.listenerInfo(), expected)
    t.equal( src._emitter.listeners('change').length, 2, 'only two listeners on the source object' )

    // console.log( src._emitter.listeners('change') )
    // console.log( src._emitter.listeners('change', true) )

    src.offChange( root_onChange)

    // console.log( src._emitter.listeners('change') )
    // console.log( src._emitter.listeners('change', true) )

    t.equal( src._emitter.listeners('change').length, 1, 'now only one' )

    t.deepLooseEqual( Cursor.listenerInfo(), expected)

    p1.offChange( peer1_onChange)

    expected= { totalEventHandlers: 1, totalKeyWatches: 1, totalSources: 1 }
    t.deepLooseEqual( Cursor.listenerInfo(), expected)

    p2.offChange( peer2_onChange)

    expected= { totalEventHandlers: 0, totalKeyWatches: 0, totalSources: 0 }
    t.deepLooseEqual( Cursor.listenerInfo(), expected)

    // console.log( src._emitter.listeners('change') )
    // console.log( src._emitter.listeners('change', true) )
  }, 400)

})

test( 'test cursor change events', function( t){
  var src= new Ogre({
        peer1: {
          name: 'p1'
        },
        peer2: {
          name: 'p2'
        }
      }, { strict:false, batchChanges:false}),
      peer1= src.scopeTo( 'peer1'),
      peer2= src.scopeTo( 'peer2')

  function changed(target, keys) {
    t.ok( keys, target+ ' keys changed: '+ keys.join(', '))
    // console.log('> changed', key)
  }

  t.plan( 5)

  src.onChange( changed.bind(this, 'root'))
  peer1.onChange( changed.bind(this, 'peer1'))
  peer2.onChange( changed.bind(this, 'peer2'))

  // console.log(">> src.set('unrelated', 'value')")
  src.set('unrelated', 'value') // 1

  // console.log(">> peer1.set('name', 'updated')")
  peer1.set('name', 'updated') // 2

  // console.log(">> peer2.set('name', 'updated')")
  peer2.set('name', 'updated') // 2

})

test( 'test object-like mutators', function( t){
  var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
      cursor= src.scopeTo( 'child')
  _.test_object( cursor, t)
})

test( 'test array-like mutators', function( t){
  var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
      cursor= src.scopeTo( 'child')
  _.test_array( cursor, t)
})

test( 'test query methods', function( t){
  var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
      cursor= src.scopeTo( 'child')
  _.test_query( cursor, t)
})

test( 'test other methods', function( t){
  var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
      cursor= src.scopeTo( 'child')
  _.test_other( cursor, t)
})

test( 'test array key methods', function( t){
  var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
      cursor= src.scopeTo( 'child')
  _.test_array_keys( cursor, t)
})

test( 'nested cursor change events', function( t){
  var src= new Ogre({ }, { strict:false, batchChanges:false }),
      forms= src.scopeTo( 'forms'),
      email= forms.scopeTo( 'email'),
      state= email.scopeTo( 'data'),
      status= email.scopeTo( 'status')

  t.plan( 5)

  status.onChange(function( keys){
    t.ok(true, keys +': '+ status.get(), "Status change event fired")
  })

  status.set('loading')
  email.set('status', 'ready')
  forms.set('email.status', 'uno_momento')
  status.set('done')

  t.deepLooseEqual( src.get(), { forms:{ email:{ status:'done'}}}, "Final data is in correct shape.")
})

test( 'nested cursor change events, batched', function( t){
  var src= new Ogre({ }, { strict:false, batchChanges:true }),
      forms= src.scopeTo( 'forms'),
      email= forms.scopeTo( 'email'),
      state= email.scopeTo( 'data'),
      status= email.scopeTo( 'status')

  t.plan( 2)

  status.onChange(function( keys){
    t.ok(true, keys +': '+ status.get(), "Status change event fired")
  })

  // status.set('loading')
  email.set('status', 'ready')
  forms.set('email.status', 'start')
  forms.set('email.status', 'middle')
  forms.set('email.status', 'uno_momento')
  // status.set('done')

  t.deepLooseEqual( src.get(), { forms:{ email:{ status:'uno_momento'}}}, "Final data is in correct shape.")
})

test( 'nested cursor change events, batched take two', function( t){
  var src= new Ogre({ }, { strict:false, batchChanges:true }),
      forms= src.scopeTo( 'forms'),
      email= forms.scopeTo( 'email'),
      state= email.scopeTo( 'data'),
      status= email.scopeTo( 'status')

  t.plan( 2)

  forms.onChange(function( keys){
    t.ok(true, keys +': '+ status.get(), "Status change event fired")
  })

  // status.set('loading')
  email.set('status', 'ready')
  forms.set('email.status', 'start')
  forms.set('email.status', 'middle')
  forms.set('email.status', 'uno_momento')
  // status.set('done')

  t.deepLooseEqual( src.get(), { forms:{ email:{ status:'uno_momento'}}}, "Final data is in correct shape.")
})


text:
Storybook available https://jamesbliss.github.io/react-flickity

---

## Usage

Install

```
yarn add @jamesbliss/react-flickity
```

Include the component at the top of the component it's required in.

```javascript
import Flickity from '@jamesbliss/react-flickity';
```

Implement as follows

```javascript
  <Flickity />
```


text:
package com.hazelcast.client;

import com.hazelcast.nio.AbstractSerializer;
import com.hazelcast.nio.DefaultSerializer;

import static com.hazelcast.nio.Serializer.DataSerializer;

public class ClientSerializer extends AbstractSerializer {

    public ClientSerializer() {
        super(new DataSerializer() {
            @Override
            protected Class loadClass(final String className) throws ClassNotFoundException {
                String name = className;
                if (className.equals("com.hazelcast.impl.CMap$Values")) {
                    name = "com.hazelcast.client.impl.Values";
                } else if (className.equals("com.hazelcast.impl.base.KeyValue")) {
                    name = "com.hazelcast.client.impl.KeyValue";
                }
                return super.loadClass(name);
            }

            protected String toClassName(final Class clazz) throws ClassNotFoundException {
                final String className = super.toClassName(clazz);
                if (!className.startsWith("com.hazelcast.client")) {
                    return className;
                }
                return "com.hazelcast" + className.substring("com.hazelcast.client".length());
            }
        }, new DefaultSerializer());
    }
}


text:
package com.facebook.buck.core.starlark.rule.attr.impl;

import com.facebook.buck.core.artifact.Artifact;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.core.rules.actions.ActionRegistry;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.devtools.build.lib.events.Location;

/**
 * Simple container class for shared logic between {@link OutputAttribute} and {@link
 * OutputListAttribute}
 */
class OutputAttributeValidator {
  private OutputAttributeValidator() {}

  /**
   * Validates that a coerced value is a string, and registers it with {@code registry}
   *
   * @param coercedValue the value that came from {@link OutputAttribute#getValue(CellPathResolver,
   *     ProjectFilesystem, ForwardRelativePath, TargetConfiguration, TargetConfiguration, Object)}
   *     or {@link OutputListAttribute#getValue(CellPathResolver, ProjectFilesystem,
   *     ForwardRelativePath, TargetConfiguration, TargetConfiguration, Object)}
   * @param registry the registry to declare artifacts against
   * @return the declared artifact
   * @throws IllegalArgumentException if {@code coercedValue} is not a {@link String}
   */
  static Artifact validateAndRegisterArtifact(Object coercedValue, ActionRegistry registry) {
    if (!(coercedValue instanceof String)) {
      throw new IllegalArgumentException(String.format("Value %s must be a String", coercedValue));
    }
    // TODO(pjameson): pass the location of the UDR invocation all the way down to the coercer
    return registry.declareArtifact((String) coercedValue, Location.BUILTIN);
  }
}


text:
NPM_AUTH_TOKEN=$1
BUILD_DIR=$2
TEMP_DIR=$3
IS_NEW_RELEASE=$4

echo "BUILD_DIR=$BUILD_DIR"
echo "TEMP_DIR=$TEMP_DIR"
echo "IS_NEW_RELEASE=$IS_NEW_RELEASE"

if [ ! "$IS_NEW_RELEASE" = "true" ]
then
	echo "Skipping npm deploy"
	exit 0
fi

PACKAGE_DIR=$TEMP_DIR/nodepackage

mkdir $PACKAGE_DIR
mkdir $PACKAGE_DIR/src

cp $BUILD_DIR/package.json $PACKAGE_DIR/package.json
cp $BUILD_DIR/README.md $PACKAGE_DIR/README.md
cp $BUILD_DIR/index.d.ts $PACKAGE_DIR/index.d.ts
cp -r $BUILD_DIR/src $PACKAGE_DIR
cp -r $BUILD_DIR/dist $PACKAGE_DIR

cd $PACKAGE_DIR

echo "registry=https://registry.npmjs.org
//registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN}" > ./.npmrc

npm publish


text:
package com.jmethods.catatumbo;

/**
 * Interface for Callbacks to run Datastore operations within a Transaction.
 *
 * @author Sai Pullabhotla
 * @param <T>
 *          the result type of this {@code TransactionalTask}.
 * @see EntityManager#executeInTransaction(TransactionalTask)
 *
 */
@FunctionalInterface
public interface TransactionalTask<T> {

  /**
   * Executes the task. After the execute method finishes normally, the transaction will be
   * committed by the {@link EntityManager}. If the execute method throws any exception, the
   * transaction will be rolled back.
   *
   * @param transaction
   *          the transaction to read from/write to the Cloud Datastore.
   * @return the result of execution
   */
  T execute(DatastoreTransaction transaction);

}


text:
package org.apache.river.test.spec.lookupdiscovery;
import org.apache.river.qa.harness.QAConfig;
import org.apache.river.qa.harness.Test;

import java.util.logging.Level;

import org.apache.river.qa.harness.TestException;

import org.apache.river.test.share.GroupsUtil;

import net.jini.discovery.LookupDiscovery;

/**
 * This class verifies that the LookupDiscovery utility
 * class operates in a manner consistent with the specification. In
 * particular, this class verifies that when the parameter input to the
 * constructor contains at least 1 null element, a
 * NullPointerException is thrown.
 *
 * The environment in which this class expects to operate is as follows:
 *

 *
 no lookup services
 *
 an instance of the lookup discovery utility constructed
 *        using a set of groups in which at least 1 element is null
 *

 *
 * If the lookup discovery utility functions as specified, then upon
 * attempting to construct an instance of the lookup discovery utility
 * using a set of groups containing at least one null
 * element, a NullPointerException will occur.
 */
public class ConstructorNullElement extends AbstractBaseTest {

    protected String[] nullGroups = new String[] {"group0","group1",
                                                   null,
                                                  "group3","group4"};
    protected LookupDiscovery newLD = null;

    /** Performs actions necessary to prepare for execution of the
     *  current test (refer to the description of this method in the
     *  parent class).
     */
    public Test construct(QAConfig sysConfig) throws Exception {
        delayLookupStart = true;//don't start lookups, just want config info
        super.construct(sysConfig);
        return this;
    }//end construct

    /** Executes the current test by doing the following:
     *

     *   Verifies that a NullPointerException is thrown when
     *   an instance of LookupDiscovery is created using a set
     *   of groups in which at least one element is null.
     */
    public void run() throws Exception {
        logger.log(Level.FINE, "run()");
        /* Create an instance of LookupDiscovery using null element */
        try {
            logger.log(Level.FINE, "creating a new "
                              +"LookupDiscovery configured to discover -- ");
            GroupsUtil.displayGroupSet(nullGroups,"  group",
                                       Level.FINE);
            newLD = new LookupDiscovery(nullGroups,
                                        getConfig().getConfiguration());
            lookupDiscoveryList.add(newLD);
        } catch(NullPointerException e) {
            logger.log(Level.FINE, "NullPointerException on "
                              +"construction of LookupDiscovery as expected");
            return;
        }
        String errStr = new String("no NullPointerException");
        logger.log(Level.FINE, errStr);
        throw new TestException(errStr);
    }//end run

}//end class ConstructorNullElement


text:
from setuptools import setup

setup(name='datauri',
version='0.0.1',
description='Data URI generator',
long_description='Generates data URIs as defined in RFC 2397, includes command lie utility',
author='Marian Steinbach',
author_email='marian@sendung.de',
url='http://github.com/marians/datauri',
py_modules=['datauri'],
install_requires=['click'],
entry_points={
    'console_scripts': [
        'datauri = datauri:main'
    ]
})


text:
.. _three-way-data-binding:

======================
Three-way data-binding
======================

One of AngularJS biggest selling propositions is its `two-way data-binding`_. Two way data-binding
is an automatic way of updating the view whenever the model changes, as well as updating the model
whenever the view changes.

With **djangular** and the additional module django-websocket-redis_, one can extend this feature
to reflect all changes to a model, back and forward with a corresponding object stored on the
server. This means that the server "sees" whenever the model on the client changes and can by
itself, modify values on the client side at any time, without having the client to poll for new
messages. This is very useful, when the server wants to inform the client about asynchronous events
such as sport results, chat messages or multi-player game events.

Installation
============
If you want to use three-way data-binding with Django, the webbrowser must have support for
websockets. Nowadays, most modern browsers do so.

Install **django-websocket-redis** from PyPI::

  pip install django-websocket-redis

and follow the `configuration instructions`_.

Demo
====
In the examples directory there is a demo showing the capabilities. If **ws4redis** can be found in
the Python search path, this special demo should be available together with the other two examples.
Run the demo server::

  cd examples
  ./manage runserver

point a browser onto http://localhost:8000/threeway_databinding/ and fill the input fields.
Point a second browser onto the same URL. The fields content should be the same in all browsers.
Change some data, the fields content should update concurrently in all attached browsers.

Add three-way data-binding to an AngularJS application
======================================================
Refer to the Javascript file ``django-angular.js`` somewhere on your page:

.. code-block:: html

	<script src="{{ STATIC_URL }}djangular/js/django-angular.min.js" type="text/javascript"></script>

add the module dependency to your application initialization:

.. code-block:: javascript

	var my_app = angular.module('myApp', [/* other dependencies */, 'ng.django.websocket']);

configure the websocket module with a URL prefix of your choice:

.. code-block:: javascript

	my_app.config(function(djangoWebsocketProvider) {
	    // use '/ws' as the websocket's prefix
	    djangoWebsocketProvider.prefix('/ws');

	    // optionally inform about the connection status in the browser's console
	    djangoWebsocketProvider.debug(true);
	});

If you want to bind the data model in one of your AngularJS controllers, you must inject the
provider **djangoWebsocket** into this controller and then attach the websocket to the server.

.. code-block:: javascript

	app.controller('MyController', function($scope, djangoWebsocket) {
	    djangoWebsocket.connect($scope, ['subscribe-broadcast', 'publish-broadcast'], 'my_collection');

	    // use $scope.my_collection as root object for the data which shall be three-way bound
	});

This creates a websocket attached to the server sides message queue via the module **ws4redis**.
It then shallow watches the properties of the object named ``'my_collection'``, which contains the
model data. It then fires whenever any of the properties change (for arrays, this implies watching
the array items; for object maps, this implies watching the properties). If a change is detected,
it is propagated up to the server. Changes made to the corresponding object on the server side,
are immediately send back to the client.

.. note:: This feature is new and experimental, but due to its big potential, it will be regarded
          as one of the key features in future versions of **django-angular**.

.. _two-way data-binding: http://docs.angularjs.org/guide/databinding
.. _django-websocket-redis: https://github.com/jrief/django-websocket-redis
.. _configuration instructions: http://django-websocket-redis.readthedocs.org/en/latest/installation.html


text:
angular.module('services').factory('settingSvr',
    function($resource){

        var service = $resource(
            'setting/:settingId',
            {
                settingId:'@_id'
            },{
                update: {
                    method: 'PUT'
                }
            }
        );

    return service;
});


text:
# Activity List Inheritance Targets

You can add inheritance of activity lists to the target entity from some related inheritance target entities.

It means that in target entities, you can see all activity list from the general entity and related entities.

To enable this option, configure the target entity to identify all inheritance target entities: use migration extension to add all necessary configuration to the entity config.

The following is an example of the migration to enable the display of contact activity lists in the appropriate account:

class InheritanceActivityTargets implements Migration, ActivityListExtensionAwareInterface
{
    /** @var ActivityListExtension */
    protected $activityListExtension;

    /** {@inheritdoc} */
    public function setActivityListExtension(ActivityListExtension $activityListExtension)
    {
        $this->activityListExtension = $activityListExtension;
    }

    /** {@inheritdoc} */
    public function up(Schema $schema, QueryBag $queries)
    {
        $activityListExtension->addInheritanceTargets($schema, 'orocrm_account', 'orocrm_contact', ['accounts']);
    }
}

Method parameters:
addInheritanceTargets(Schema $schema, $targetTableName, $inheritanceTableName, $path)
string $targetTableName - Target entity table name
string $inheritanceTableName - Inheritance entity table name
string[] $path - Path of relations to target entity


text:
from __future__ import absolute_import

from surveymonkey.manager import BaseManager
from surveymonkey.constants import URL_FOLDERS_LIST

class Folders(BaseManager):

    def folders(self, page=None, per_page=50, max_pages=100):
        if page:
            return self._get_page_of_folders(page, per_page)
        else:
            return self._get_all_folders(per_page, max_pages)

    def _get_all_folders(self, per_page, max_pages):
        next_url = self.build_url(URL_FOLDERS_LIST, page=1, per_page=per_page)
        return self.get_list(next_url=next_url, max_pages=max_pages)

    def _get_page_of_folders(self, page, per_page):
        response = self.get(base_url=URL_FOLDERS_LIST, page=page, per_page=per_page)
        self.verify_list_data(response)
        return response["data"]


text:
module.exports = {
  env: {
    browser: true,
    es6: true,
    jest: true,
    node: true,
    webextensions: true,
  },
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
    "plugin:prettier/recommended",
    "prettier/react",
    "prettier/standard",
  ],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2015,
    sourceType: "module",
  },
  plugins: ["@typescript-eslint", "prettier", "react-hooks"],
  root: true,
  rules: {
    // Rules included in ESLint
    "consistent-return": 2,
    eqeqeq: [2, "smart"],
    "no-console": 0,
    "no-unused-expressions": 2,
    "sort-imports": 2,

    // React Hooks
    "react-hooks/rules-of-hooks": 2,
    "react-hooks/exhaustive-deps": 2,
  },
  settings: {
    react: {
      version: "detect",
    },
  },
};


text:
module Snailgas.Graphics.GL where

import SDL hiding (glBindTexture)
import Foreign (Storable, Ptr, alloca, peek, allocaArray, pokeArray, sizeOf, poke)
import Foreign.Ptr (nullPtr, plusPtr)
import Foreign.C.String (withCString, peekCString)
import Foreign.C.Types (CFloat(..), CUInt(..))
import Data.Vector.Storable (unsafeWith)
import Data.List (null)
import Control.Arrow ((***))
import Control.Monad (unless, join, when, void, unless)
import Data.Either
import Graphics.GL.Core33
import Codec.Picture
import qualified Data.Text as T
import qualified Data.Text.IO as T

-- | Map a function across a pair
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple = join (***)

-- | Turn any pair of integers into a Num a => SDL.V2 a
mkV2 :: (Integral a, Num b) => (a, a) -> SDL.V2 b
mkV2 = uncurry SDL.V2 . mapTuple fromIntegral

-- | Abstracts a common pattern with pointers
withNewPtr :: Storable b => (Ptr b -> IO a) -> IO b
withNewPtr f = alloca (\p -> f p >> peek p)

-- | Upload a list of floats into a buffer object
-- Call like this: uploadBuffer undefined CFloat [1..10]
-- The undefined is annoying and it pisses me off, sorry...
-- It can be any value of the type b though if you want.
-- Remember to delete it
uploadBuffer :: Storable b => b -> (a -> b) -> [a] -> IO GLuint
uploadBuffer v f hlist = do
  let len = length hlist
  let cfsize = sizeOf v
  let buflen = fromIntegral $ len * cfsize
  buffer <- withNewPtr (glGenBuffers 1)
  glBindBuffer GL_ARRAY_BUFFER buffer
  ptr <- allocaArray len
                     (\ptr -> pokeArray ptr (map f hlist)
                           >> glBufferData GL_ARRAY_BUFFER buflen ptr GL_STATIC_DRAW
                     )
  return buffer

-- | Load a shader and compile it, returning the id
-- A shader id is returned whether it succeeds or not so remember to delete it
loadShader :: GLenum -> T.Text -> IO GLuint
loadShader shaderType datafile = do
  -- Load source
  let path = T.unpack datafile
  source <- T.readFile path >>= return . T.unpack

  -- Compile shader
  shader <- glCreateShader shaderType
  withCString source
    (\str -> alloca
               (\ptr -> poke ptr str
                     >> glShaderSource shader 1 ptr nullPtr
               )
    )
  glCompileShader shader

  -- Check result
  isCompiled <- withNewPtr (glGetShaderiv shader GL_COMPILE_STATUS)

  -- Output any errors
  when (isCompiled == 0) $ do
    length <- withNewPtr (glGetShaderiv shader GL_INFO_LOG_LENGTH)
    error <- allocaArray (fromIntegral length)
                         (\ptr -> glGetShaderInfoLog shader length nullPtr ptr
                               >> (peekCString ptr))
    putStr $ "Failed to compile shader" ++ path ++ ":\n" ++ error

  return shader

-- | Link program
-- A program id is returned regardless of whether link succeeds, so free it
linkProgram :: GLuint -> GLuint -> IO GLuint
linkProgram vert frag = do
  -- Link program
  program <- glCreateProgram
  glAttachShader program vert
  glAttachShader program frag
  glLinkProgram program

  -- Check result
  isLinked <- withNewPtr (glGetProgramiv program GL_LINK_STATUS)

  -- Output any errors
  when (isLinked == 0) $ do
    length <- withNewPtr (glGetProgramiv program GL_INFO_LOG_LENGTH)
    error <- allocaArray (fromIntegral length)
                         (\ptr -> glGetProgramInfoLog program length nullPtr ptr
                               >> (peekCString ptr))
    putStr $ "Failed to link program:\n" ++ error

  return program

-- | Loads a vertex and fragment shader, compiles them and links them
-- A program id is returned regardless of whether this succeeds or not so free it
loadShaderProgram :: T.Text -> T.Text -> IO GLuint
loadShaderProgram v f = do
  vert <- loadShader GL_VERTEX_SHADER v
  frag <- loadShader GL_FRAGMENT_SHADER f
  prog <- linkProgram vert frag
  glDeleteShader vert
  glDeleteShader frag
  return prog

-- | Get the location for a shader attribute
attribLoc :: GLuint -> String -> IO GLuint
attribLoc program str = do withCString str (glGetAttribLocation program) >>= return . fromIntegral

-- | Get the location for a shader uniform
uniformLoc :: GLuint -> String -> IO GLuint
uniformLoc program str = do withCString str (glGetUniformLocation program) >>= return . fromIntegral

createTex dimx dimy ptr = do
   tex <- withNewPtr (glGenTextures 1)
   glBindTexture GL_TEXTURE_2D tex
   glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S (fromIntegral GL_REPEAT)
   glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T (fromIntegral GL_REPEAT)
   glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER (fromIntegral GL_LINEAR)
   glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER (fromIntegral GL_LINEAR)
   glTexImage2D GL_TEXTURE_2D 0 (fromIntegral GL_RGBA8) dimx dimy 0 GL_RGBA GL_UNSIGNED_BYTE ptr
   return tex

-- | Load a texture from a file
loadTexture :: String -> IO GLuint
loadTexture filename = do
  -- Load image
  eitherImgErr <- readImage filename

  case eitherImgErr of
       -- upload image to gpu texture
       Right img -> do
         let imgRGBA8 = convertRGBA8 img
         let (dimx, dimy) = mapTuple fromIntegral (imageWidth imgRGBA8, imageHeight imgRGBA8)
         unsafeWith (imageData imgRGBA8) (createTex dimx dimy)
       -- return default texture
       Left err -> do (putStrLn $ "Error loading image " ++ filename ++ ": " ++ err)
                      alloca $ \ptr -> do
                        poke ptr (0xFFFF00FF :: CUInt)
                        createTex 1 1 ptr