text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package es.ucm.pev.g12p1.crossover;

import es.ucm.pev.g12p1.chromosome.Chromosome;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 *
 * @author Herros Team
 */
public class SinglePoint extends Crossover {

    public SinglePoint() {
    }

    @Override
    public List<Chromosome> crossover(Chromosome parent1, Chromosome parent2, int crossPoint) {
        List<Chromosome> children = new LinkedList();

        Chromosome child1 = parent1.copy();
        Chromosome child2 = parent2.copy();

        int currentAllele = 0;

        for(int i=0; i<parent1.getGenes().size(); i++){
            for(int j=0; j<parent1.getGene(i).getLength(); j++){
                if (currentAllele >= crossPoint) {
                child1.getGene(i).setAllele(j,
                        parent2.getGene(i).getAllele(j));
                child2.getGene(i).setAllele(j,
                        parent1.getGene(i).getAllele(j));
                }
                currentAllele++;
            }

        }

        child1.evaluate();
        child2.evaluate();
        children.add(child1);
        children.add(child2);

        return children;
    }
}


text:
<?php

namespace FM\SymSlateBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use FM\SymSlateBundle\Entity\Country;
use FM\SymSlateBundle\Form\CountryType;
use JMS\SecurityExtraBundle\Annotation\Secure;

/**
 * Country controller.
 *
 * @Route("/countries")
 */
class CountryController extends Controller
{
    /**
     * Lists all Country entities.
     *
     * @Route("/", name="countries")
     * @Template()
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('FMSymSlateBundle:Country')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a Country entity.
     *
     * @Route("/{id}/show", name="countries_show")
     * @Template()
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FMSymSlateBundle:Country')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Country entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new Country entity.
     *
     * @Route("/new", name="countries_new")
     * @Template()
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function newAction()
    {
        $entity = new Country();
        $form   = $this->createForm(new CountryType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new Country entity.
     *
     * @Route("/create", name="countries_create")
     * @Method("POST")
     * @Template("FMSymSlateBundle:Country:new.html.twig")
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function createAction(Request $request)
    {
        $entity  = new Country();
        $form = $this->createForm(new CountryType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('countries_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Country entity.
     *
     * @Route("/{id}/edit", name="countries_edit")
     * @Template()
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FMSymSlateBundle:Country')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Country entity.');
        }

        $editForm = $this->createForm(new CountryType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Country entity.
     *
     * @Route("/{id}/update", name="countries_update")
     * @Method("POST")
     * @Template("FMSymSlateBundle:Country:edit.html.twig")
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FMSymSlateBundle:Country')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Country entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new CountryType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('countries_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Country entity.
     *
     * @Route("/{id}/delete", name="countries_delete")
     * @Method("POST")
     * @Secure(roles="ROLE_SUPER_ADMIN")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('FMSymSlateBundle:Country')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Country entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('countries'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<navbar>Main View</navbar>

This is the login view.


text:
line=$(grep -n 'MARKDOWN' pre-index.html | cut -d ":" -f 1)
# insert the README.md in the proper spot of the index.html file
{ head -n $(($line-1)) pre-index.html; cat ../README.md; tail -n +$((line+1)) \
    pre-index.html; } > index.html


text:
package org.kuali.kfs.sys.service;

/**
 * Defines methods that an PostalCodeValidationService service must provide
 */
public interface PostalCodeValidationService {

    public boolean validateAddress(String postalCountryCode, String stateCode, String postalCode, String statePropertyConstant, String postalCodePropertyConstant);

}


text:
/**
 * Map legend control for CIM Application
 */
"use strict";

define
(
    ["mustache", "../cimquery"],
    /**
     * @summary Project legend control.
     * @description UI element for the project legend.
     * @exports project_legend
     * @version 1.0
     */
    function (mustache, cimquery)
    {
        class ProjectLegend
        {
            constructor (theme)
            {
                this._theme = theme;
                this._template =
                    `

                          Legend
                          <button class="close" type="button" aria-label="Close">
                            ×
                          </button>

                        Empty pending improved code.

                    `;
            }

            onAdd (map)
            {
                this._map = map;
                this._container = document.createElement ("div");
                this._container.className = "mapboxgl-ctrl";
                this._container.innerHTML = this._template;
                // handle close button
                this._container.getElementsByClassName ("close")[0].onclick = this.close.bind (this);
                return (this._container);
            }

            onRemove ()
            {
                this._container.parentNode.removeChild (this._container);
                delete this._container;
                delete this._map;
            }

            close ()
            {
                this._map.removeControl (this);
            }

            getDefaultPosition ()
            {
                return ("bottom-right");
            }

            visible ()
            {
                return ("undefined" != typeof (this._container));
            }

            legend_change_listener (fn)
            {
                this._legend_listener = fn;
            }

            initialize ()
            {
            }
        }

        return (ProjectLegend);
    }
);


text:
#pragma once
#ifndef FINITEDIFF_REAL
  #define FINITEDIFF_REAL double
#endif
#ifdef FINITEDIFF_WITH_RESTRICT
  #ifdef _MSC_VER
    #define FINITEDIFF_RESTRICT __restrict
  #else
    #define FINITEDIFF_RESTRICT restrict
  #endif
#else
  #define FINITEDIFF_RESTRICT
#endif
#define FINITEDIFF_MIN(x, y) (((x) < (y)) ? (x) : (y))
#define FINITEDIFF_MAX(x, y) (((x) > (y)) ? (x) : (y))
/* We're assuming the L1 cache of the CPU is 64 bytes long (used to avoid false sharing): */
#define FINITEDIFF_ROUND_L1(x) ((((unsigned)(sizeof(FINITEDIFF_REAL)*x) + 63u) & ~63u)/sizeof(FINITEDIFF_REAL))

#ifdef __cplusplus
extern "C" {
#endif

enum FINITEDIFF_STATUS_CODES {
    FINITEDIFF_STATUS_SUCCESS=0,
    FINITEDIFF_STATUS_ERR_BAD_ALLOC=1,
    FINITEDIFF_STATUS_ERR_TOO_SMALL_GRID=2,
    FINITEDIFF_STATUS_ERR_WRONG_LEADING_DIMENSION=3,
    FINITEDIFF_STATUS_ERR_TOO_FEW_POINTS=4,
    FINITEDIFF_STATUS_ERR_ILLEGAL_ENV_VAR=5
};

/*
  finitediff_calculate_weights
  ============================

  Parameters
  ----------
  weights[len_g, max_deriv+1]: weights of order 0 to max_deriv
      (output argument, contiguous memory, column major order, no need to clear before call)
  ld_weights: leading dimension of ``weights_out``
  grid[len_grid]: array with grid point locations
  len_grid: length of grid
  max_deriv: highest derivative.
  around: location where approximations are to be accurate

  Requirements
  ------------
  a) ``len_grid < max_deriv + 1``
  b) all values in ``grid`` are unique

  References
  ----------
  Generation of Finite Difference Formulas on Arbitrarily
  Spaced Grids, Bengt Fornberg,
  Mathematics of compuation, 51, 184, 1988, 699-706
*/
void finitediff_calculate_weights(
    FINITEDIFF_REAL * const FINITEDIFF_RESTRICT weights,
    const int ld_weights,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT grid,
    const int len_grid,
    const int max_deriv,
    const FINITEDIFF_REAL around
);

/*
  finitediff_apply_fd
  ===================

  Parameters
  ----------
  out : array of derivatives
  ld_out : leading dimension of ``out``
  w : array of weights
  ldw : leading dimension of ``w``
  nsets : outer diension of ydata
  max_deriv : highest derivative to calculate for
  len_grid : length of ``xdata``
  ydata : (sets of) values (``nsets`` x ``len_grid``)
  ldy : leading dimension of ``ydata`` (usually ``len_grid``)

*/
void finitediff_apply_fd(
    FINITEDIFF_REAL * const FINITEDIFF_RESTRICT out,
    const int ld_out,
    FINITEDIFF_REAL * const FINITEDIFF_RESTRICT w,
    const int ldw,
    const int nsets,
    const int max_deriv,
    const int len_grid,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT ydata,
    const int ldy
);

/*
  finitediff_calc_apply_fd
  ========================

  Parameters
  ----------
  out : array of derivatives at ``xtgt``
  ld_out : leading  dimension of ``out``
  nsets : outer diension of ydata
  max_deriv : highest derivative to calculate for
  len_grid : length of ``xdata``
  xdata : grid points
  ydata : (sets of) values (``nsets`` x ``len_grid``)
  ldy : leading dimension of ``ydata`` (usually ``len_grid``)
  xtgt : value of x at which derivatives are to be estimated

  Returns
  -------
  0: success
  1: malloc failed
  2: ``len_grid < max_deriv + 1``
  3: ``ld_out < max_deriv + 1``

*/
int finitediff_calc_and_apply_fd(
    FINITEDIFF_REAL * const FINITEDIFF_RESTRICT out,
    const int ld_out,
    const int nsets,
    const int max_deriv,
    const int len_grid,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT grid,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT ydata,
    const int ldy,
    const FINITEDIFF_REAL xtgt
);

int finitediff_interpolate_by_finite_diff(
    FINITEDIFF_REAL * const FINITEDIFF_RESTRICT out, /* C-order: out[tgt_idx, set_idx, deriv_idx] */
    const int len_targets,
    const int nsets,
    const int max_deriv,
    const int elem_strides_out_0,  /* tgt_idx * elem_strides_out_0 */
    const int elem_strides_out_1,  /* set_idx * elem_strides_out_1,  strides_out_2 assumed to be 1 */
    const int ntail,
    const int nhead,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT grid,
    const int len_grid,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT ydata, /* C-order: ydata[set_idx, grid_idx] */
    const int ldy,
    const FINITEDIFF_REAL * const FINITEDIFF_RESTRICT xtgts /* len(xtgts) == len_targets */
);

#ifdef __cplusplus
}
#endif


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
  Copyright SemanticBits, Northwestern University and Akaza Research

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/caaers/LICENSE.txt for details.
-->
<ServiceGroupRegistrationParameters xmlns:sgc="http://mds.globus.org/servicegroup/client"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/03/addressing"
  xmlns:agg="http://mds.globus.org/aggregator/types"
  xmlns="http://mds.globus.org/servicegroup/client">
  <!-- The ServiceGroupEPR defines the servicegroup to which registrations will be made -->
  <ServiceGroupEPR>
    <wsa:Address>INDEX_SERVICE_URL</wsa:Address>
  </ServiceGroupEPR>
  <!-- Specifies that the registration will be renewed every 10 minutes -->
  <RefreshIntervalSecs>REGISTRATION_REFRESH</RefreshIntervalSecs>
  <Content xsi:type="agg:AggregatorContent" xmlns:agg="http://mds.globus.org/aggregator/types">
    <agg:AggregatorConfig xsi:type="agg:AggregatorConfig">
      <agg:GetMultipleResourcePropertiesPollType
			xmlns:ns11="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportTransaction/types"
			xmlns:ns5="gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata"
			xmlns:ns1="uri:iso.org:21090"
			xmlns:ns16="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportAdvancedQuery/types"
			xmlns:xs="http://www.w3.org/2001/XMLSchema"
			xmlns:ns4="gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata.security"
			xmlns:ns8="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportManagement/types"
			xmlns:ns12="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportDefinitionManagement/types"
			xmlns:ns7="gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata.common"
			xmlns:ns10="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportQuery/types"
			xmlns:ns14="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportNotification/types"
			xmlns:ns3="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/types"
			xmlns:ns0="http://gov.nih.nci.ess.safetyreporting.types"
			xmlns:ns6="gme://caGrid.caBIG/1.0/gov.nih.nci.cagrid.metadata.service"
			xmlns:ns17="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportRulesEvaluation/types"
			xmlns:ns13="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportRulesManagement/types"
			xmlns:ns18="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportDefinitionQuery/types"
			xmlns:ns2="http://ess.caaers.nci.nih.gov"
			xmlns:ns15="http://safetyreporting.ess.nci.nih.gov/SafetyReportingEnterpriseService/SafetyReportReview/types"
			xmlns:ns9="http://docs.oasis-open.org/wsrf/2004/06/wsrf-WS-ResourceLifetime-1.2-draft-01.xsd">
        <!-- Specifies that the index should refresh information
            every 300000 milliseconds (once every 5 minutes) -->
        <agg:PollIntervalMillis>INDEX_REFRESH</agg:PollIntervalMillis>
        <!-- specifies all Resource Properties that should be retrieved from the service -->
		<agg:ResourcePropertyNames>ns5:ServiceMetadata</agg:ResourcePropertyNames>

      </agg:GetMultipleResourcePropertiesPollType>
    </agg:AggregatorConfig>
    <agg:AggregatorData/>
  </Content>
</ServiceGroupRegistrationParameters>


text:
describe('ui.grid.validate uiGridValidateService', function () {
  var uiGridValidateService;
  var $rootScope;

  beforeEach(module('ui.grid.validate'));

  beforeEach(inject(function (_uiGridValidateService_, _$rootScope_) {
    uiGridValidateService = _uiGridValidateService_;
    $rootScope = _$rootScope_;
  }));

  it('should create an empty validatorFactories object', function() {
    expect(angular.equals(uiGridValidateService.validatorFactories, {})).toBe(true);
  });

  it('should add a validator when calling setValidator', function() {
    uiGridValidateService.setValidator('test', angular.noop, angular.noop);
    expect(uiGridValidateService.validatorFactories.test).toBeDefined();
  });

  it('should return a validator function when calling getValidator with an argument', function() {
    var fooFactory = function(argument) {
      return function() {
        return 'foo'+argument;
      };
    };
    uiGridValidateService.setValidator('foo', fooFactory, angular.noop);
    expect(uiGridValidateService.getValidator('foo','bar')()).toBe('foobar');
  });

  it('should return a message function when calling getMessage with an argument', function() {
    var messageFunction = function(argument) {
      return 'message'+argument;
    };
    uiGridValidateService.setValidator('foo', angular.noop, messageFunction);
    expect(uiGridValidateService.getMessage('foo','bar')).toBe('messagebar');
  });

  it('should return true when calling isInvalid on an invalid cell', function() {
    var colDef = {name: 'foo'};
    var entity = {'$$invalidfoo': true};

    expect(uiGridValidateService.isInvalid(entity, colDef)).toBe(true);
  });

  it('should return false when calling isInvalid on a valid cell', function() {
    var colDef = {name: 'foo'};
    var entity = {'$$invalidfoo': false};

    expect(uiGridValidateService.isInvalid(entity, colDef)).toBeFalsy();

    colDef = {name: 'bar'};
    expect(uiGridValidateService.isInvalid(entity, colDef)).toBeFalsy();
  });

  it('should set a cell as invalid when calling setInvalid on a valid cell', function() {
    var colDef = {name: 'foo'};
    var entity = {};

    uiGridValidateService.setInvalid(entity, colDef);
    expect(entity['$$invalidfoo']).toBe(true);

    entity = {'$$invalidfoo': false};

    uiGridValidateService.setInvalid(entity, colDef);
    expect(entity['$$invalidfoo']).toBe(true);
  });

  it('should set a cell as valid when calling setValid on an invalid cell', function() {
    var colDef = {name: 'foo'};
    var entity = {'$$invalidfoo': true};

    uiGridValidateService.setValid(entity, colDef);

    expect(entity['$$invalidfoo']).toBeUndefined();
  });

  it('should add an error to a cell when calling setError on that cell', function() {
    var colDef = {name: 'foo'};
    var entity = {};

    uiGridValidateService.setError(entity, colDef, 'bar');
    expect(entity['$$errorsfoo'].bar).toBe(true);

    entity['$$errorsfoo'].bar = false;

    uiGridValidateService.setError(entity, colDef, 'bar');
    expect(entity['$$errorsfoo'].bar).toBe(true);
  });

  it('should remove an error to a cell when calling clearError on that cell', function() {
    var colDef = {name: 'foo'};
    var entity = {'$$errorsfoo': {bar: true} };

    uiGridValidateService.clearError(entity, colDef, 'bar');
    expect(entity['$$errorsfoo'].bar).toBeUndefined();

  });

  it('should return an array with all error messages (alphabetically sorted) when calling getErrorMessages on a cell', function() {
    var colDef = {name: 'test', validators: {foo: 'foo', bar: 'bar'}};
    var entity = {'$$errorstest': {foo: true, bar: true} };

    var fooMessage = function(argument) {return argument + 'Message';};
    var barMessage = function(argument) {return argument + 'Message';};

    uiGridValidateService.setValidator('foo', angular.noop, fooMessage);
    uiGridValidateService.setValidator('bar', angular.noop, barMessage);

    var messages = uiGridValidateService.getErrorMessages(entity, colDef);
    expect(messages[0]).toBe('barMessage');
    expect(messages[1]).toBe('fooMessage');

  });

  it('should execute all validators when calling runValidators on a cell and set/clear errors', function() {
    var colDef = {name: 'test', validators: {foo: 'foo', bar: 'bar'}};
    var entity = {};

    var validatorFactory = function (argument) {return function() {return argument === 'foo';};};

    uiGridValidateService.setValidator('foo', validatorFactory, angular.noop);
    uiGridValidateService.setValidator('bar', validatorFactory, angular.noop);

    uiGridValidateService.runValidators(entity, colDef, 1, 0);

    $rootScope.$apply();

    expect(entity['$$errorstest'].bar).toBe(true);
    expect(entity['$$invalidtest']).toBe(true);

    expect(entity['$$errorstest'].foo).toBeFalsy();

  });

  it('should not execute any validator when calling runValidators with newValue === oldValue', function() {
    var colDef = {name: 'test', validators: {foo: 'foo', bar: 'bar'}};
    var entity = {};

    var validatorFactory = function (argument) {return function() {return argument === 'foo';};};

    uiGridValidateService.setValidator('foo', validatorFactory, angular.noop);
    uiGridValidateService.setValidator('bar', validatorFactory, angular.noop);

    uiGridValidateService.runValidators(entity, colDef, 1, 1);

    $rootScope.$apply();

    expect(entity['$$errorstest']).toBeUndefined();
    expect(entity['$$invalidtest']).toBeUndefined();

  });

  it('should run an external validator if an external validator factory is set', function() {

    var colDef = {name: 'test', validators: {foo: 'foo'}};
    var entity = {};

    var externalFooValidator = function() {return function() {return false;};};
    var externalFactoryFunction = function(name, argument) {
      if (name === 'foo') {
        return {validatorFactory: externalFooValidator, messageFunction: angular.noop};
      }
    };

    uiGridValidateService.setExternalFactoryFunction(externalFactoryFunction);

    var validatorFactory = function (argument) {return function() {return argument === 'foo';};};

    uiGridValidateService.setValidator('foo', validatorFactory, angular.noop);

    uiGridValidateService.runValidators(entity, colDef, 1, 0);

    $rootScope.$apply();

    expect(entity['$$errorstest'].foo).toBe(true);
    expect(entity['$$invalidtest']).toBe(true);

  });

  describe('should call setValidator three times when calling createDefaultValidators', function() {
    beforeEach(function() {
      spyOn(uiGridValidateService, 'setValidator');
    });
    it('', function() {
      uiGridValidateService.createDefaultValidators();

      expect(uiGridValidateService.setValidator.calls.count()).toBe(3);
    });

  });

});


text:
import json

from django.http import HttpResponse
from django.views.generic.base import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.list import ListView
from mediacontent.models import MediaContent

class AjaxableResponseMixin(object):
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return self.render_to_json_response(data)
        else:
            return response

class AjaxMediaContentList(ListView):
    def get_queryset(self):
        pk = self.kwargs['pk']

        qs = MediaContent.objects.all()

        if self.kwargs.has_key('pk') and self.kwargs['pk']:
            qs = qs.filter(pk=pk)

        if self.kwargs.has_key('mimetype') and self.kwargs['mimetype']:
            qs = qs.filter(mimetype__startswith=self.kwargs['mimetype'])

        qs = qs.order_by('-pub_date')
        return qs

    def parse_queryset(self):
        qs = self.get_queryset()
        res = []

        for object in qs:
            temp = {}
            temp['id'] = object.pk
            temp['title'] = object.title
            temp['description'] = object.description
            if object.content:
                temp['url'] = object.content.url
            if object.gallery:
                temp['gallery_url'] = object.gallery.url
            if object.thumbnail:
                temp['thumbnail_url'] = object.thumbnail.url
            res.append(temp)

        if len(res) == 1:
            res = res[0]

        return json.dumps(res)

    def render_to_response(self, context, **kwargs):
        return HttpResponse(self.parse_queryset(), **kwargs)

class AjaxMediaContentCreate(AjaxableResponseMixin, CreateView):
    model = MediaContent

class AjaxMediaContentUpdate(AjaxableResponseMixin, UpdateView):
    model = MediaContent

class AjaxMediaContentDelete(DeleteView):
    model = MediaContent
    success_url = '/'

    def delete(self, request, *args, **kwargs):
        res = super(AjaxMediaContentDelete, self).delete(request, *args, **kwargs)
        if res:
            return HttpResponse(json.dumps('OK'), content_type='application/json')

class AjaxMediaAPIView(View):

    http_method_names = ['get', 'post', 'put', 'delete']

    def dispatch(self, *args, **kwargs):
        return super(AjaxMediaAPIView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        view = AjaxMediaContentList.as_view()
        return view(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        view = AjaxMediaContentUpdate.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = AjaxMediaContentCreate.as_view()
        return view(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        view = AjaxMediaContentDelete.as_view()
        return view(request, *args, **kwargs)


text:
var searchData=
[
  ['init_5fneural_5fnetwork',['init_neural_network',['../namespaceimage__processing.html#a532c05461b7927b7dbf9fca472f4b076',1,'image_processing']]]
];


text:
package com.jfixby.r3.fokker.api;

public class SpritesRenderer {

	final static public int spriteVertex (final int sprite_number, final int vertice_name) {
		return vertice_name + sprite_number * SPRITE_SIZE;
	}

	public final static int A_x = 0;
	public final static int A_y = 1;
	public final static int B_x = 15;
	public final static int B_y = 16;
	public final static int C_x = 10;
	public final static int C_y = 11;
	public final static int D_x = 5;
	public final static int D_y = 6;

	final public static float round (final double x) {
		return (float)x;
	}

	public static final int VERTEX_SIZE = 2 + 1 + 2;
	public static final int SPRITE_SIZE = 4 * VERTEX_SIZE;

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Microstylis decumbens Schltr.

### Remarks
null


text:
package org.apache.cassandra.transport;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.config.EncryptionOptions;
import org.apache.cassandra.cql3.BatchQueryOptions;
import org.apache.cassandra.cql3.CQLStatement;
import org.apache.cassandra.cql3.QueryHandler;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.statements.BatchStatement;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.transport.messages.BatchMessage;
import org.apache.cassandra.transport.messages.ExecuteMessage;
import org.apache.cassandra.transport.messages.PrepareMessage;
import org.apache.cassandra.transport.messages.QueryMessage;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.MD5Digest;

import static org.apache.cassandra.utils.ByteBufferUtil.bytes;

public class MessagePayloadTest extends CQLTester
{
    public static Map<String, ByteBuffer> requestPayload;
    public static Map<String, ByteBuffer> responsePayload;

    private static Field cqlQueryHandlerField;
    private static boolean modifiersAccessible;

    @BeforeClass
    public static void makeCqlQueryHandlerAccessible()
    {
        try
        {
            cqlQueryHandlerField = ClientState.class.getDeclaredField("cqlQueryHandler");
            cqlQueryHandlerField.setAccessible(true);

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersAccessible = modifiersField.isAccessible();
            modifiersField.setAccessible(true);
            modifiersField.setInt(cqlQueryHandlerField, cqlQueryHandlerField.getModifiers() & ~Modifier.FINAL);
        }
        catch (IllegalAccessException | NoSuchFieldException e)
        {
            throw new RuntimeException(e);
        }
    }

    @AfterClass
    public static void resetCqlQueryHandlerField()
    {
        if (cqlQueryHandlerField == null)
            return;
        try
        {
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(cqlQueryHandlerField, cqlQueryHandlerField.getModifiers() | Modifier.FINAL);

            cqlQueryHandlerField.setAccessible(false);

            modifiersField.setAccessible(modifiersAccessible);
        }
        catch (IllegalAccessException | NoSuchFieldException e)
        {
            throw new RuntimeException(e);
        }
    }

    @After
    public void dropCreatedTable()
    {
        try
        {
            QueryProcessor.executeOnceInternal("DROP TABLE " + KEYSPACE + ".atable");
        }
        catch (Throwable t)
        {
            // ignore
        }
    }

    @Test
    public void testMessagePayloadBeta() throws Throwable
    {
        QueryHandler queryHandler = (QueryHandler) cqlQueryHandlerField.get(null);
        cqlQueryHandlerField.set(null, new TestQueryHandler());
        try
        {
            requireNetwork();

            Assert.assertSame(TestQueryHandler.class, ClientState.getCQLQueryHandler().getClass());

            SimpleClient client = new SimpleClient(nativeAddr.getHostAddress(),
                                                   nativePort,
                                                   ProtocolVersion.V5,
                                                   true,
                                                   new EncryptionOptions());
            try
            {
                client.connect(false);

                Map<String, ByteBuffer> reqMap;
                Map<String, ByteBuffer> respMap;

                QueryOptions queryOptions = QueryOptions.create(
                  QueryOptions.DEFAULT.getConsistency(),
                  QueryOptions.DEFAULT.getValues(),
                  QueryOptions.DEFAULT.skipMetadata(),
                  QueryOptions.DEFAULT.getPageSize(),
                  QueryOptions.DEFAULT.getPagingState(),
                  QueryOptions.DEFAULT.getSerialConsistency(),
                  ProtocolVersion.V5,
                  KEYSPACE);
                QueryMessage queryMessage = new QueryMessage("CREATE TABLE atable (pk int PRIMARY KEY, v text)",
                                                             queryOptions);
                PrepareMessage prepareMessage = new PrepareMessage("SELECT * FROM atable", KEYSPACE);

                reqMap = Collections.singletonMap("foo", bytes(42));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(42));
                queryMessage.setCustomPayload(reqMap);
                Message.Response queryResponse = client.execute(queryMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, queryResponse.getCustomPayload());

                reqMap = Collections.singletonMap("foo", bytes(43));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(43));
                prepareMessage.setCustomPayload(reqMap);
                ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, prepareResponse.getCustomPayload());

                ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
                reqMap = Collections.singletonMap("foo", bytes(44));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(44));
                executeMessage.setCustomPayload(reqMap);
                Message.Response executeResponse = client.execute(executeMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, executeResponse.getCustomPayload());

                BatchMessage batchMessage = new BatchMessage(BatchStatement.Type.UNLOGGED,
                                                             Collections.<Object>singletonList("INSERT INTO atable (pk,v) VALUES (1, 'foo')"),
                                                             Collections.singletonList(Collections.<ByteBuffer>emptyList()),
                                                             queryOptions);
                reqMap = Collections.singletonMap("foo", bytes(45));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(45));
                batchMessage.setCustomPayload(reqMap);
                Message.Response batchResponse = client.execute(batchMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, batchResponse.getCustomPayload());
            }
            finally
            {
                client.close();
            }
        }
        finally
        {
            cqlQueryHandlerField.set(null, queryHandler);
        }
    }

    @Test
    public void testMessagePayload() throws Throwable
    {
        QueryHandler queryHandler = (QueryHandler) cqlQueryHandlerField.get(null);
        cqlQueryHandlerField.set(null, new TestQueryHandler());
        try
        {
            requireNetwork();

            Assert.assertSame(TestQueryHandler.class, ClientState.getCQLQueryHandler().getClass());

            SimpleClient client = new SimpleClient(nativeAddr.getHostAddress(), nativePort);
            try
            {
                client.connect(false);

                Map<String, ByteBuffer> reqMap;
                Map<String, ByteBuffer> respMap;

                QueryMessage queryMessage = new QueryMessage(
                                                            "CREATE TABLE " + KEYSPACE + ".atable (pk int PRIMARY KEY, v text)",
                                                            QueryOptions.DEFAULT
                );
                PrepareMessage prepareMessage = new PrepareMessage("SELECT * FROM " + KEYSPACE + ".atable", null);

                reqMap = Collections.singletonMap("foo", bytes(42));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(42));
                queryMessage.setCustomPayload(reqMap);
                Message.Response queryResponse = client.execute(queryMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, queryResponse.getCustomPayload());

                reqMap = Collections.singletonMap("foo", bytes(43));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(43));
                prepareMessage.setCustomPayload(reqMap);
                ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, prepareResponse.getCustomPayload());

                ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
                reqMap = Collections.singletonMap("foo", bytes(44));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(44));
                executeMessage.setCustomPayload(reqMap);
                Message.Response executeResponse = client.execute(executeMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, executeResponse.getCustomPayload());

                BatchMessage batchMessage = new BatchMessage(BatchStatement.Type.UNLOGGED,
                                                             Collections.<Object>singletonList("INSERT INTO " + KEYSPACE + ".atable (pk,v) VALUES (1, 'foo')"),
                                                             Collections.singletonList(Collections.<ByteBuffer>emptyList()),
                                                             QueryOptions.DEFAULT);
                reqMap = Collections.singletonMap("foo", bytes(45));
                responsePayload = respMap = Collections.singletonMap("bar", bytes(45));
                batchMessage.setCustomPayload(reqMap);
                Message.Response batchResponse = client.execute(batchMessage);
                payloadEquals(reqMap, requestPayload);
                payloadEquals(respMap, batchResponse.getCustomPayload());
            }
            finally
            {
                client.close();
            }
        }
        finally
        {
            cqlQueryHandlerField.set(null, queryHandler);
        }
    }

    @Test
    public void testMessagePayloadVersion3() throws Throwable
    {
        QueryHandler queryHandler = (QueryHandler) cqlQueryHandlerField.get(null);
        cqlQueryHandlerField.set(null, new TestQueryHandler());
        try
        {
            requireNetwork();

            Assert.assertSame(TestQueryHandler.class, ClientState.getCQLQueryHandler().getClass());

            SimpleClient client = new SimpleClient(nativeAddr.getHostAddress(), nativePort, ProtocolVersion.V3);
            try
            {
                client.connect(false);

                Map<String, ByteBuffer> reqMap;

                QueryMessage queryMessage = new QueryMessage(
                                                            "CREATE TABLE " + KEYSPACE + ".atable (pk int PRIMARY KEY, v text)",
                                                            QueryOptions.DEFAULT
                );
                PrepareMessage prepareMessage = new PrepareMessage("SELECT * FROM " + KEYSPACE + ".atable", null);

                reqMap = Collections.singletonMap("foo", bytes(42));
                responsePayload = Collections.singletonMap("bar", bytes(42));
                queryMessage.setCustomPayload(reqMap);
                try
                {
                    client.execute(queryMessage);
                    Assert.fail();
                }
                catch (RuntimeException e)
                {
                    Assert.assertTrue(e.getCause() instanceof ProtocolException);
                }
                // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
                client.close();
                client.connect(false);

                queryMessage.setCustomPayload(null);
                client.execute(queryMessage);

                reqMap = Collections.singletonMap("foo", bytes(43));
                responsePayload = Collections.singletonMap("bar", bytes(43));
                prepareMessage.setCustomPayload(reqMap);
                try
                {
                    client.execute(prepareMessage);
                    Assert.fail();
                }
                catch (RuntimeException e)
                {
                    Assert.assertTrue(e.getCause() instanceof ProtocolException);
                }
                // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
                client.close();
                client.connect(false);

                prepareMessage.setCustomPayload(null);
                ResultMessage.Prepared prepareResponse = (ResultMessage.Prepared) client.execute(prepareMessage);

                ExecuteMessage executeMessage = new ExecuteMessage(prepareResponse.statementId, prepareResponse.resultMetadataId, QueryOptions.DEFAULT);
                reqMap = Collections.singletonMap("foo", bytes(44));
                responsePayload = Collections.singletonMap("bar", bytes(44));
                executeMessage.setCustomPayload(reqMap);
                try
                {
                    client.execute(executeMessage);
                    Assert.fail();
                }
                catch (RuntimeException e)
                {
                    Assert.assertTrue(e.getCause() instanceof ProtocolException);
                }
                // when a protocol exception is thrown by the server the connection is closed, so need to re-connect
                client.close();
                client.connect(false);

                BatchMessage batchMessage = new BatchMessage(BatchStatement.Type.UNLOGGED,
                                                             Collections.<Object>singletonList("INSERT INTO " + KEYSPACE + ".atable (pk,v) VALUES (1, 'foo')"),
                                                             Collections.singletonList(Collections.<ByteBuffer>emptyList()),
                                                             QueryOptions.DEFAULT);
                reqMap = Collections.singletonMap("foo", bytes(45));
                responsePayload = Collections.singletonMap("bar", bytes(45));
                batchMessage.setCustomPayload(reqMap);
                try
                {
                    client.execute(batchMessage);
                    Assert.fail();
                }
                catch (RuntimeException e)
                {
                    Assert.assertTrue(e.getCause() instanceof ProtocolException);
                }
            }
            finally
            {
                client.close();
            }
        }
        finally
        {
            cqlQueryHandlerField.set(null, queryHandler);
        }
    }

    private static void payloadEquals(Map<String, ByteBuffer> map1, Map<String, ByteBuffer> map2)
    {
        Assert.assertNotNull(map1);
        Assert.assertNotNull(map2);
        Assert.assertEquals(map1.keySet(), map2.keySet());
        for (Map.Entry<String, ByteBuffer> e : map1.entrySet())
            Assert.assertEquals(e.getValue(), map2.get(e.getKey()));
    }

    public static class TestQueryHandler implements QueryHandler
    {
        public QueryProcessor.Prepared getPrepared(MD5Digest id)
        {
            return QueryProcessor.instance.getPrepared(id);
        }

        public CQLStatement parse(String query, QueryState state, QueryOptions options)
        {
            return QueryProcessor.instance.parse(query, state, options);
        }

        public ResultMessage.Prepared prepare(String query,
                                              ClientState clientState,
                                              Map<String, ByteBuffer> customPayload)
                                                      throws RequestValidationException
        {
            if (customPayload != null)
                requestPayload = customPayload;
            ResultMessage.Prepared result = QueryProcessor.instance.prepare(query, clientState, customPayload);
            if (customPayload != null)
            {
                result.setCustomPayload(responsePayload);
                responsePayload = null;
            }
            return result;
        }

        public ResultMessage process(CQLStatement statement,
                                     QueryState state,
                                     QueryOptions options,
                                     Map<String, ByteBuffer> customPayload,
                                     long queryStartNanoTime)
                                            throws RequestExecutionException, RequestValidationException
        {
            if (customPayload != null)
                requestPayload = customPayload;
            ResultMessage result = QueryProcessor.instance.process(statement, state, options, customPayload, queryStartNanoTime);
            if (customPayload != null)
            {
                result.setCustomPayload(responsePayload);
                responsePayload = null;
            }
            return result;
        }

        public ResultMessage processBatch(BatchStatement statement,
                                          QueryState state,
                                          BatchQueryOptions options,
                                          Map<String, ByteBuffer> customPayload,
                                          long queryStartNanoTime)
                                                  throws RequestExecutionException, RequestValidationException
        {
            if (customPayload != null)
                requestPayload = customPayload;
            ResultMessage result = QueryProcessor.instance.processBatch(statement, state, options, customPayload, queryStartNanoTime);
            if (customPayload != null)
            {
                result.setCustomPayload(responsePayload);
                responsePayload = null;
            }
            return result;
        }

        public ResultMessage processPrepared(CQLStatement statement,
                                             QueryState state,
                                             QueryOptions options,
                                             Map<String, ByteBuffer> customPayload,
                                             long queryStartNanoTime)
                                                    throws RequestExecutionException, RequestValidationException
        {
            if (customPayload != null)
                requestPayload = customPayload;
            ResultMessage result = QueryProcessor.instance.processPrepared(statement, state, options, customPayload, queryStartNanoTime);
            if (customPayload != null)
            {
                result.setCustomPayload(responsePayload);
                responsePayload = null;
            }
            return result;
        }
    }
}


text:
"""This module contains support for a DOM tree representation from an XML
document using a SAX parser.

This functionality exists because we need a DOM interface to generate the
binding classses, but the Python C{xml.dom.minidom} package does not support
location information.  The SAX interface does, so we have a SAX content
handler which converts the SAX events into a DOM tree.

This is not a general-purpose DOM capability; only a small subset of the DOM
interface is supported, and only for storing the XML information, not for
converting it back into document format.
"""

import xml.dom
import saxutils
import StringIO
import pyxb.namespace
import logging

_log = logging.getLogger(__name__)

def _DumpDOM (n, depth=0):
    """Utility function to print a DOM tree."""

    pfx = ' ' * depth
    if (xml.dom.Node.ELEMENT_NODE == n.nodeType):
        print '%sElement[%d] %s %s with %d children' % (pfx, n._indexInParent(), n, pyxb.namespace.ExpandedName(n.name), len(n.childNodes))
        ins = pyxb.namespace.resolution.NamespaceContext.GetNodeContext(n).inScopeNamespaces()
        print '%s%s' % (pfx, ' ; '.join([ '%s=%s' % (_k, _v.uri()) for (_k, _v) in ins.items()]))
        for (k, v) in n.attributes.items():
            print '%s %s=%s' % (pfx, pyxb.namespace.ExpandedName(k), v)
        for cn in n.childNodes:
            _DumpDOM(cn, depth+1)
    elif (xml.dom.Node.TEXT_NODE == n.nodeType):
        #print '%sText "%s"' % (pfx, n.value)
        pass
    elif (xml.dom.Node.DOCUMENT_NODE == n.nodeType):
        print 'Document node'
        _DumpDOM(n.firstChild, depth)
    else:
        print 'UNRECOGNIZED %s' % (n.nodeType,)

class _DOMSAXHandler (saxutils.BaseSAXHandler):
    """SAX handler class that transforms events into a DOM tree."""

    def document (self):
        """The document that is the root of the generated tree."""
        return self.__document
    __document = None

    def startDocument (self):
        super(_DOMSAXHandler, self).startDocument()
        self.__document = Document(namespace_context=self.namespaceContext())

    def endDocument (self):
        content = self.elementState().content()
        if 0 < len(content):
            ( content, element_use, maybe_element ) = content[0]
            self.__document.appendChild(content)
            #_DumpDOM(content)

    def startElementNS (self, name, qname, attrs):
        (this_state, parent_state, ns_ctx, name_en) = super(_DOMSAXHandler, self).startElementNS(name, qname, attrs)
        this_state.__attributes = NamedNodeMap()
        for name in attrs.getNames():
            attr_en = pyxb.namespace.ExpandedName(name)
            value = attrs.getValue(name)
            this_state.__attributes._addItem(Attr(expanded_name=attr_en, namespace_context=ns_ctx, value=value, location=this_state.location()))

    def endElementNS (self, name, qname):
        this_state = super(_DOMSAXHandler, self).endElementNS(name, qname)
        ns_ctx = this_state.namespaceContext()
        element = Element(namespace_context=ns_ctx, expanded_name=this_state.expandedName(), attributes=this_state.__attributes, location=this_state.location())
        for ( content, element_use, maybe_element ) in this_state.content():
            if isinstance(content, Node):
                element.appendChild(content)
            else:
                element.appendChild(Text(content, namespace_context=ns_ctx))
        parent_state = this_state.parentState()
        parent_state.addElementContent(element, None)
        #_log.debug('%s %s has %d children', element.namespaceURI, element.localName, len(element.childNodes))

def parse (stream, **kw):
    """Parse a stream containing an XML document and return the DOM tree
    representing its contents.

    Keywords not described here are passed to L{saxutils.make_parser}.

    @param stream: An object presenting the standard file C{read} interface
    from which the document can be read.

    @keyword content_handler_constructor: Input is overridden to assign this a
    value of L{_DOMSAXHandler}.

    @rtype: C{xml.dom.Document}
    """

    kw['content_handler_constructor'] = _DOMSAXHandler
    saxer = saxutils.make_parser(**kw)
    handler = saxer.getContentHandler()
    saxer.parse(stream)
    return handler.document()

def parseString (text, **kw):
    """Parse a string holding an XML document and return the corresponding DOM
    tree."""
    # XML parser doesn't really like unicode strings
    if isinstance(text, unicode):
        text = text.encode(pyxb._InputEncoding)
    return parse(StringIO.StringIO(text), **kw)

class Node (xml.dom.Node, pyxb.utils.utility.Locatable_mixin):
    """Base for the minimal DOM interface required by PyXB."""
    def __init__ (self, node_type, **kw):
        location = kw.pop('location', None)
        if location is not None:
            pyxb.utils.utility.Locatable_mixin.__init__(self, location=location)
        self.__nodeType = node_type
        self.__parentNode = None
        self.__childNodes = []
        self.__namespaceContext = kw['namespace_context']
        self.__value = kw.get('value')
        self.__attributes = kw.get('attributes')
        expanded_name = kw.get('expanded_name')
        if expanded_name is not None:
            self.__name = expanded_name.uriTuple()
            self.__namespaceURI = expanded_name.namespaceURI()
            self.__localName = expanded_name.localName()
        self.__namespaceContext.setNodeContext(self)

    location = property(lambda _s: _s._location())

    __name = None
    @property
    def name (self):
        return self.__name
    @property
    def expanded_name (self):
        return pyxb.namespace.ExpandedName(self.__namespaceURI, self.__localName)
    __namespaceURI = None
    namespaceURI = property(lambda _s: _s.__namespaceURI)
    __localName = None
    localName = property(lambda _s: _s.__localName)
    __value = None
    value = property(lambda _s: _s.__value)

    def _indexInParent (self): return self.__indexInParent

    def __childIfPresent (self, index):
        if index < len(self.__childNodes):
            return self.__childNodes[index]
        return None

    def appendChild (self, new_child):
        new_child._setParentNode(self, len(self.__childNodes))
        self.__childNodes.append(new_child)

    def _setParentNode (self, parent_node, index_in_parent):
        self.__parentNode = parent_node
        self.__indexInParent = index_in_parent

    def _setAttributes (self, attributes):
        assert self.__attributes is None
        self.__attributes = attributes
    __attributes = None

    nodeType = property(lambda _s: _s.__nodeType)
    parentNode = property(lambda _s: _s.__parentNode)
    firstChild = property(lambda _s: _s.__childIfPresent(0))
    childNodes = property(lambda _s: _s.__childNodes)
    attributes = property(lambda _s: _s.__attributes)

    nextSibling = property(lambda _s: _s.parentNode.__childIfPresent(_s.__indexInParent+1))

    def hasAttributeNS (self, ns_uri, local_name):
        return self.getAttributeNodeNS(ns_uri, local_name) is not None

    def getAttributeNodeNS (self, ns_uri, local_name):
        return self.__attributes._getAttr( (ns_uri, local_name) )

    def getAttributeNS (self, ns_uri, local_name):
        rv = self.getAttributeNodeNS(ns_uri, local_name)
        if rv is None:
            return ''
        return rv.value

class Document (Node):
    """Add the documentElement interface."""
    def __init__ (self, **kw):
        super(Document, self).__init__(node_type=xml.dom.Node.DOCUMENT_NODE, **kw)

    documentElement = Node.firstChild

class Attr (Node):
    """Add the nodeName and nodeValue interface."""
    def __init__ (self, **kw):
        super(Attr, self).__init__(node_type=xml.dom.Node.ATTRIBUTE_NODE, **kw)
    nodeName = Node.name
    nodeValue = Node.value

class NamedNodeMap (dict):
    """Implement that portion of NamedNodeMap required to satisfy PyXB's
    needs."""
    __members = None

    def __init__ (self):
        super(NamedNodeMap, self).__init__()
        self.__members = []

    length = property(lambda _s: len(_s.__members))
    def item (self, index):
        return self.__members[index]

    def _addItem (self, attr):
        self[attr.name] = attr.value
        assert pyxb.namespace.resolution.NamespaceContext.GetNodeContext(attr) is not None
        self.__members.append(attr)

    def _getAttr (self, name):
        for attr in self.__members:
            if attr.name == name:
                return attr
        return None

class Element (Node):
    def __init__ (self, **kw):
        super(Element, self).__init__(node_type=xml.dom.Node.ELEMENT_NODE, **kw)
        assert self.attributes is not None
    tagName = Node.localName
    nodeName = Node.localName

class _CharacterData (Node):
    """Abstract base for anything holding text data."""
    data = Node.value

class Text (_CharacterData):
    def __init__ (self, text, **kw):
        super(Text, self).__init__(value=text, node_type=xml.dom.Node.TEXT_NODE, **kw)

class Comment (_CharacterData):
    def __init__ (self, text, **kw):
        super(Text, self).__init__(value=text, node_type=xml.dom.Node.COMMENT_NODE, **kw)

if '__main__' == __name__:
    import sys
    xml_file = 'examples/tmsxtvd/tmsdatadirect_sample.xml'
    if 1 < len(sys.argv):
        xml_file = sys.argv[1]

    doc = parse(file(xml_file))

## Local Variables:
## fill-column:78
## End:


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.SecurityCenter.Models
{
    /// <summary> The source event types which evaluate the security automation set of rules. For example - security alerts and security assessments. To learn more about the supported security events data models schemas - please visit https://aka.ms/ASCAutomationSchemas. </summary>
    public partial class SecurityAutomationSource
    {
        /// <summary> Initializes a new instance of SecurityAutomationSource. </summary>
        public SecurityAutomationSource()
        {
            RuleSets = new ChangeTrackingList<SecurityAutomationRuleSet>();
        }

        /// <summary> Initializes a new instance of SecurityAutomationSource. </summary>
        /// <param name="eventSource"> A valid event source type. </param>
        /// <param name="ruleSets"> A set of rules which evaluate upon event interception. A logical disjunction is applied between defined rule sets (logical 'or'). </param>
        internal SecurityAutomationSource(SecurityEventSource? eventSource, IList<SecurityAutomationRuleSet> ruleSets)
        {
            EventSource = eventSource;
            RuleSets = ruleSets;
        }

        /// <summary> A valid event source type. </summary>
        public SecurityEventSource? EventSource { get; set; }
        /// <summary> A set of rules which evaluate upon event interception. A logical disjunction is applied between defined rule sets (logical 'or'). </summary>
        public IList<SecurityAutomationRuleSet> RuleSets { get; }
    }
}


text:
skiboot-5.3.3
-------------

skiboot-5.3.3 was released on Friday September 2nd, 2016.

This is the 4th stable release of skiboot 5.3, the new stable release of
skiboot (first released with 5.3.0 on August 2nd, 2016).

Skiboot 5.3.3 replaces skiboot-5.3.2 as the current stable version. It contains
two bug fixes for machines utilizing the NPU (i.e. Garrison)

Over skiboot-5.3.2, the following fixes are included:

- hw/npu: assert the NPU irq min is aligned.
- hw/npu: program NPU BUID reg properly
  The NPU BUID register was incorrectly programmed resulting in npu
  interrupt level 0 causing a PB_CENT_CRESP_ADDR_ERROR checkstop,
  and irqs from npus in odd chips being aliased to and processed
  as the interrupts from the corresponding npu on the even chips.


text:
import ipaddr
import logging
import socket

from cloudferry.lib.utils import remote_runner

LOG = logging.getLogger(__name__)

def get_ext_ip(ext_cidr, init_host, compute_host, ssh_user):
    list_ips = get_ips(init_host, compute_host, ssh_user)
    for ip_str in list_ips:
        ip_addr = ipaddr.IPAddress(ip_str)
        for cidr in ext_cidr:
            if ipaddr.IPNetwork(cidr.strip()).Contains(ip_addr):
                return ip_str
    LOG.warning("Unable to find IP address of '%s' node, please "
                "check ext_cidr config value.", compute_host)
    return socket.gethostbyname(compute_host)

def get_ips(init_host, compute_host, ssh_user):
    runner = remote_runner.RemoteRunner(host=compute_host, user=ssh_user,
                                        gateway=init_host)
    cmd = ("ifconfig | awk -F \"[: ]+\" \'/inet addr:/ "
           "{ if ($4 != \"127.0.0.1\") print $4 }\'")
    out = runner.run(cmd)
    list_ips = []
    for info in out.split():
        try:
            ipaddr.IPAddress(info)
        except ValueError:
            continue
        list_ips.append(info)
    return list_ips


text:
/**
 */
package subkdm.SimplifiedDecisionMetrics.impl;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;

import org.eclipse.emf.ecore.impl.EFactoryImpl;

import org.eclipse.emf.ecore.plugin.EcorePlugin;

import subkdm.SimplifiedDecisionMetrics.*;

/**
 * <!-- begin-user-doc -->
 * An implementation of the model <b>Factory</b>.
 * <!-- end-user-doc -->
 * @generated
 */
public class SimplifiedDecisionMetricsFactoryImpl extends EFactoryImpl implements SimplifiedDecisionMetricsFactory {
	/**
	 * Creates the default factory implementation.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public static SimplifiedDecisionMetricsFactory init() {
		try {
			SimplifiedDecisionMetricsFactory theSimplifiedDecisionMetricsFactory = (SimplifiedDecisionMetricsFactory)EPackage.Registry.INSTANCE.getEFactory(SimplifiedDecisionMetricsPackage.eNS_URI);
			if (theSimplifiedDecisionMetricsFactory != null) {
				return theSimplifiedDecisionMetricsFactory;
			}
		}
		catch (Exception exception) {
			EcorePlugin.INSTANCE.log(exception);
		}
		return new SimplifiedDecisionMetricsFactoryImpl();
	}

	/**
	 * Creates an instance of the factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public SimplifiedDecisionMetricsFactoryImpl() {
		super();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public EObject create(EClass eClass) {
		switch (eClass.getClassifierID()) {
			case SimplifiedDecisionMetricsPackage.OBSERVATION: return createObservation();
			case SimplifiedDecisionMetricsPackage.MEASURE: return createMeasure();
			case SimplifiedDecisionMetricsPackage.GRADE: return createGrade();
			case SimplifiedDecisionMetricsPackage.DIMENSIONAL_MEASUREMENT: return createDimensionalMeasurement();
			case SimplifiedDecisionMetricsPackage.DIMENSIONAL_TO_OBJECT_MEASUREMENT: return createDimensionalToObjectMeasurement();
			case SimplifiedDecisionMetricsPackage.SIMPLIFIED_DECISION_METRICS: return createSimplifiedDecisionMetrics();
			case SimplifiedDecisionMetricsPackage.MOF_ELEMENT: return createMofElement();
			case SimplifiedDecisionMetricsPackage.COUPLING_BETWEEN_OBJECTS_MEASURE: return createCouplingBetweenObjectsMeasure();
			case SimplifiedDecisionMetricsPackage.WEIGHTED_METHODS_PER_CLASS_MEASURE: return createWeightedMethodsPerClassMeasure();
			case SimplifiedDecisionMetricsPackage.NUMBER_OF_USES_MEASURE: return createNumberOfUsesMeasure();
			case SimplifiedDecisionMetricsPackage.NUMBER_OF_CONTAINMENTS_MEASURE: return createNumberOfContainmentsMeasure();
			case SimplifiedDecisionMetricsPackage.CALCULATED_COUPLING_MEASURE: return createCalculatedCouplingMeasure();
			case SimplifiedDecisionMetricsPackage.NUMBER_OF_CLASSES_MEASURE: return createNumberOfClassesMeasure();
			case SimplifiedDecisionMetricsPackage.NUMBER_OF_LINES_MEASURE: return createNumberOfLinesMeasure();
			case SimplifiedDecisionMetricsPackage.CLUSTER_RELATION_CONFLICT_PERCENTAGE_MEASURE: return createClusterRelationConflictPercentageMeasure();
			default:
				throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Observation createObservation() {
		ObservationImpl observation = new ObservationImpl();
		return observation;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Measure createMeasure() {
		MeasureImpl measure = new MeasureImpl();
		return measure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Grade createGrade() {
		GradeImpl grade = new GradeImpl();
		return grade;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public DimensionalMeasurement createDimensionalMeasurement() {
		DimensionalMeasurementImpl dimensionalMeasurement = new DimensionalMeasurementImpl();
		return dimensionalMeasurement;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public DimensionalToObjectMeasurement createDimensionalToObjectMeasurement() {
		DimensionalToObjectMeasurementImpl dimensionalToObjectMeasurement = new DimensionalToObjectMeasurementImpl();
		return dimensionalToObjectMeasurement;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public SimplifiedDecisionMetrics createSimplifiedDecisionMetrics() {
		SimplifiedDecisionMetricsImpl simplifiedDecisionMetrics = new SimplifiedDecisionMetricsImpl();
		return simplifiedDecisionMetrics;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public MofElement createMofElement() {
		MofElementImpl mofElement = new MofElementImpl();
		return mofElement;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public CouplingBetweenObjectsMeasure createCouplingBetweenObjectsMeasure() {
		CouplingBetweenObjectsMeasureImpl couplingBetweenObjectsMeasure = new CouplingBetweenObjectsMeasureImpl();
		return couplingBetweenObjectsMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public WeightedMethodsPerClassMeasure createWeightedMethodsPerClassMeasure() {
		WeightedMethodsPerClassMeasureImpl weightedMethodsPerClassMeasure = new WeightedMethodsPerClassMeasureImpl();
		return weightedMethodsPerClassMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public NumberOfUsesMeasure createNumberOfUsesMeasure() {
		NumberOfUsesMeasureImpl numberOfUsesMeasure = new NumberOfUsesMeasureImpl();
		return numberOfUsesMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public NumberOfContainmentsMeasure createNumberOfContainmentsMeasure() {
		NumberOfContainmentsMeasureImpl numberOfContainmentsMeasure = new NumberOfContainmentsMeasureImpl();
		return numberOfContainmentsMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public CalculatedCouplingMeasure createCalculatedCouplingMeasure() {
		CalculatedCouplingMeasureImpl calculatedCouplingMeasure = new CalculatedCouplingMeasureImpl();
		return calculatedCouplingMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public NumberOfClassesMeasure createNumberOfClassesMeasure() {
		NumberOfClassesMeasureImpl numberOfClassesMeasure = new NumberOfClassesMeasureImpl();
		return numberOfClassesMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public NumberOfLinesMeasure createNumberOfLinesMeasure() {
		NumberOfLinesMeasureImpl numberOfLinesMeasure = new NumberOfLinesMeasureImpl();
		return numberOfLinesMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ClusterRelationConflictPercentageMeasure createClusterRelationConflictPercentageMeasure() {
		ClusterRelationConflictPercentageMeasureImpl clusterRelationConflictPercentageMeasure = new ClusterRelationConflictPercentageMeasureImpl();
		return clusterRelationConflictPercentageMeasure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public SimplifiedDecisionMetricsPackage getSimplifiedDecisionMetricsPackage() {
		return (SimplifiedDecisionMetricsPackage)getEPackage();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @deprecated
	 * @generated
	 */
	@Deprecated
	public static SimplifiedDecisionMetricsPackage getPackage() {
		return SimplifiedDecisionMetricsPackage.eINSTANCE;
	}

} //SimplifiedDecisionMetricsFactoryImpl


text:
package org.deeplearning4j.earlystopping.saver;

import org.apache.commons.io.FilenameUtils;
import org.deeplearning4j.earlystopping.EarlyStoppingModelSaver;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.util.ModelSerializer;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

public class LocalFileGraphSaver implements EarlyStoppingModelSaver<ComputationGraph> {

    private static final String BEST_GRAPH_BIN = "bestGraph.bin";
    private static final String LATEST_GRAPH_BIN = "latestGraph.bin";

    private String directory;
    private Charset encoding;

    /**Constructor that uses default character set for configuration (json) encoding
     * @param directory Directory to save networks
     */
    public LocalFileGraphSaver(String directory) {
        this(directory, Charset.defaultCharset());
    }

    /**
     * @param directory Directory to save networks
     * @param encoding Character encoding for configuration (json)
     */
    public LocalFileGraphSaver(String directory, Charset encoding) {
        this.directory = directory;
        this.encoding = encoding;

        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    @Override
    public void saveBestModel(ComputationGraph net, double score) throws IOException {
        String confOut = FilenameUtils.concat(directory, BEST_GRAPH_BIN);
        save(net, confOut);
    }

    @Override
    public void saveLatestModel(ComputationGraph net, double score) throws IOException {
        String confOut = FilenameUtils.concat(directory, LATEST_GRAPH_BIN);
        save(net, confOut);
    }

    private void save(ComputationGraph net, String confOut) throws IOException {
        ModelSerializer.writeModel(net, confOut, true);
    }

    @Override
    public ComputationGraph getBestModel() throws IOException {
        String confOut = FilenameUtils.concat(directory, BEST_GRAPH_BIN);
        return load(confOut);
    }

    @Override
    public ComputationGraph getLatestModel() throws IOException {
        String confOut = FilenameUtils.concat(directory, LATEST_GRAPH_BIN);
        return load(confOut);
    }

    private ComputationGraph load(String confOut) throws IOException {
        ComputationGraph net = ModelSerializer.restoreComputationGraph(confOut);
        return net;
    }

    @Override
    public String toString() {
        return "LocalFileGraphSaver(dir=" + directory + ")";
    }
}


text:
<?php include SYSDIR_VIEW ."/common/header.html";?>

	<form class="form form-horizontal" id="form-admin-edit">

		*管理员账号:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_user_name'];?>" id="admin_user_name" name="admin_user_name">

        *密码:

            <input type="text" class="input-text" style="width:200px;" value="" id="admin_pwd" name="admin_pwd">
            <?php if($info):?>(留空表示不更改密码)<?php endif;?>

		管理员组:

			<select class="select" name="group_id" size="1">
                <?php foreach ($groups as $key=>$val):?>
                <?php
                    $sel = '';
                    if ($info['group_id'] == $val['group_id']) $sel = 'selected="selected"';
                    echo '<option value="'.$val['group_id'].'" '.$sel.'>'.$val['group_name'].'</option>';
                ?>
                <?php endforeach;?>
			</select>

		管理员名称:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_real_name'];?>" id="admin_real_name" name="admin_real_name">

		手机:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_phone'];?>" id="admin_phone" name="admin_phone">

		QQ:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_qq'];?>" id="admin_qq" name="admin_qq">

		微信:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_weixin'];?>" id="admin_weixin" name="admin_weixin">

		邮箱:

            <input type="text" class="input-text" style="width:200px;" value="<?php echo $info['admin_email'];?>" id="admin_email" name="admin_email">

    <input type="hidden" name="action" value="edit" />
    <input type="hidden" name="admin_id" value="<?php echo $info['admin_id'];?>" />

			<input class="btn btn-primary radius" type="submit" value="  提交  ">

	</form>

<?php include SYSDIR_VIEW ."/common/footer.html";?>


text:
/**
 *
 */
package org.devel.jfxcontrols.scene.control;

import javafx.scene.control.Control;

/**
 * @author stefan.illgen
 *
 */
public class Aggregator extends Control {

	public Aggregator() {
		setStyle(null);
		getStyleClass().add("aggregator");
	}

	@Override
	public String getUserAgentStylesheet() {
		return getClass().getResource(
				"/org/devel/jfxcontrols/scene/control/"
						+ getClass().getSimpleName() + ".css").toExternalForm();
	}

}


text:
package ecs

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// DedicatedHostCluster is a nested struct in ecs response
type DedicatedHostCluster struct {
	Description                  string                              `json:"Description" xml:"Description"`
	DedicatedHostClusterId       string                              `json:"DedicatedHostClusterId" xml:"DedicatedHostClusterId"`
	ResourceGroupId              string                              `json:"ResourceGroupId" xml:"ResourceGroupId"`
	ZoneId                       string                              `json:"ZoneId" xml:"ZoneId"`
	RegionId                     string                              `json:"RegionId" xml:"RegionId"`
	DedicatedHostClusterName     string                              `json:"DedicatedHostClusterName" xml:"DedicatedHostClusterName"`
	DedicatedHostIds             DedicatedHostIds                    `json:"DedicatedHostIds" xml:"DedicatedHostIds"`
	DedicatedHostClusterCapacity DedicatedHostClusterCapacity        `json:"DedicatedHostClusterCapacity" xml:"DedicatedHostClusterCapacity"`
	Tags                         TagsInDescribeDedicatedHostClusters `json:"Tags" xml:"Tags"`
}


text:
import Actions from '../actions'

import Store from '../types/store'

import { rgbToHsv, hsvToRgb, combineStain } from '../util/color'

type State = Store.Stain

const validateBleach = n => n > 6 ? 6 : n < 0 ? 0 : n

const defaultState: State = {
	rgb: [0, 0, 0],
	hsv: [0, 0, 0],
	flowerSlot: [null, null, null, null],
	bleach: 0,
}

export default (state: State = defaultState, action: Actions.Stain.Action) => {
	switch (action.type){
		case Actions.Stain.Types.SetColor:
			return Object.assign({}, state, {
				rgb: action.color,
				hsv: rgbToHsv(action.color)
			})
		case Actions.Stain.Types.SetHsv:
			return Object.assign({}, state, {
				hsv: action.hsv,
				rgb: hsvToRgb(action.hsv)
			})
		case Actions.Stain.Types.RefreshColor:
			{
				const rgb = combineStain(state.flowerSlot, state.bleach)

				return Object.assign({}, state, {
					rgb, hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.SetSlot:
			{
				const flowerSlot = state.flowerSlot.map((slot, i) => {
					return i == action.slot
						? action.flower
						: slot
				})

				const rgb = combineStain(flowerSlot, state.bleach)

				return Object.assign({}, state, {
					flowerSlot, rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.ClearSlot:
			{
				const flowerSlot = state.flowerSlot.map((slot, i) => {
					return i == action.slot
						? null
						: slot
				})

				const rgb = combineStain(flowerSlot, state.bleach)

				return Object.assign({}, state, {
					flowerSlot, rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.ClearAllSlots:
			{
				const rgb = combineStain([], state.bleach)

				return Object.assign({}, state, {
					flowerSlot: [null, null, null, null], rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.Bleach:
			{
				const bleach = validateBleach(state.bleach + 1)

				const rgb = combineStain(state.flowerSlot, bleach)

				return Object.assign({}, state, {
					bleach, rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.UnBleach:
			{
				const bleach = validateBleach(state.bleach - 1)

				const rgb = combineStain(state.flowerSlot, bleach)

				return Object.assign({}, state, {
					bleach, rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		case Actions.Stain.Types.SetBleach:
			{
				const bleach = validateBleach(action.bleach)

				const rgb = combineStain(state.flowerSlot, bleach)

				return Object.assign({}, state, {
					bleach, rgb,
					hsv: rgbToHsv(rgb)
				})
			}
		default:
			return state
	}
}


text:
class TestReading:
    """Fetching Resources"""
    pass


text:
package org.apache.nifi.scripting;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ProcessorLog;
import org.apache.nifi.processor.Relationship;

/**
 * <p>
 * Base class for all scripts. In this framework, only ScriptEngines that
 * implement javax.script.Invocable are supported.
 *
 * </p>
 *
 */
public class Script {

    public static final Relationship SUCCESS_RELATIONSHIP = new Relationship.Builder()
            .name("success")
            .description("Destination of successfully created flow files")
            .build();
    public static final Relationship FAIL_RELATIONSHIP = new Relationship.Builder()
            .name("failure")
            .description("Destination of flow files when a error occurs in the script")
            .build();

    static final Set<Relationship> RELATIONSHIPS;

    static {
        Set<Relationship> rels = new HashSet<>();
        rels.add(FAIL_RELATIONSHIP);
        rels.add(SUCCESS_RELATIONSHIP);
        RELATIONSHIPS = Collections.unmodifiableSet(rels);
    }

    FlowFile flowFile = null;
    ScriptEngine engine = null;

    protected Map<String, String> properties = new HashMap<>();
    protected Relationship lastRoute = SUCCESS_RELATIONSHIP;
    protected ProcessorLog logger;
    protected String scriptFileName;
    protected Map<String, String> attributes = new HashMap<>();
    protected long flowFileSize = 0;
    protected long flowFileEntryDate = System.currentTimeMillis();

    // the following are needed due to an inadequate JavaScript ScriptEngine. It will not allow
    // subclassing a Java Class, only implementing a Java Interface. So, the syntax of JavaScript
    // scripts looks like subclassing, but actually is just constructing a Script instance and
    // passing in functions as args to the constructor. When we move to Nashorn JavaScript ScriptEngine
    // in Java 8, we can get rid of these and revert the subclasses of this class to abstract.
    protected Object propDescCallback;
    protected Object relationshipsCallback;
    protected Object validateCallback;
    protected Object exceptionRouteCallback;

    /**
     * Create a Script without any parameters
     */
    public Script() {
    }

    public Script(Object... callbacks) {
        for (Object callback : callbacks) {
            if (callback instanceof Map<?, ?>) {
                propDescCallback = propDescCallback == null && ((Map<?, ?>) callback).containsKey("getPropertyDescriptors") ? callback
                        : propDescCallback;
                relationshipsCallback = relationshipsCallback == null && ((Map<?, ?>) callback).containsKey("getRelationships") ? callback
                        : relationshipsCallback;
                validateCallback = validateCallback == null && ((Map<?, ?>) callback).containsKey("validate") ? callback : validateCallback;
                exceptionRouteCallback = exceptionRouteCallback == null && ((Map<?, ?>) callback).containsKey("getExceptionRoute") ? callback
                        : exceptionRouteCallback;
            }
        }
    }

    /**
     * Specify a set of properties with corresponding NiFi validators.
     *
     * Subclasses that do not override this method will still have access to all
     * properties via the "properties" field
     *
     * @return a list of PropertyDescriptors
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings("unchecked")
    public List<PropertyDescriptor> getPropertyDescriptors() throws NoSuchMethodException, ScriptException {
        if (propDescCallback != null) {
            return (List<PropertyDescriptor>) ((Invocable) engine).invokeMethod(propDescCallback, "getPropertyDescriptors", (Object) null);
        }
        return Collections.emptyList();
    }

    /**
     * Specify a set of reasons why this processor should be invalid.
     *
     * Subclasses that do not override this method will depend only on
     * individual property validators as specified in
     * {@link #getPropertyDescriptors()}.
     *
     * @return a Collection of messages to display to the user, or an empty
     * Collection if the processor configuration is OK.
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings("unchecked")
    public Collection<String> validate() throws NoSuchMethodException, ScriptException {
        if (validateCallback != null) {
            return (Collection<String>) ((Invocable) engine).invokeMethod(validateCallback, "validate", (Object) null);
        }
        return Collections.emptyList();
    }

    void setFlowFile(FlowFile ff) {
        flowFile = ff;
        if (null != ff) {
            // have to clone because ff.getAttributes is unmodifiable
            this.attributes = new HashMap<>(ff.getAttributes());
            this.flowFileSize = ff.getSize();
            this.flowFileEntryDate = ff.getEntryDate();
        }
    }

    void setProperties(Map<String, String> map) {
        properties = new HashMap<>(map);
    }

    /**
     * Required to access entire properties map -- Jython (at least) won't let
     * you read the member variable without a getter
     *
     * @return entire parameter map
     */
    // change back to protected when we get nashorn
    public Map<String, String> getProperties() {
        return properties;
    }

    /**
     * Get the named parameter. Some scripting languages make a method call
     * easier than accessing a member field, so this is a convenience method to
     * look up values in the properties field.
     *
     * @param key a hash key
     * @return the value pointed at by the key specified
     */
    public String getProperty(String key) {
        return properties.get(key);
    }

    /**
     * Name the various relationships by which a file can leave this processor.
     * Subclasses may override this method to change available relationships.
     *
     * @return a collection of relationship names
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings("unchecked")
    public Collection<Relationship> getRelationships() throws NoSuchMethodException, ScriptException {
        if (relationshipsCallback != null) {
            return (Collection<Relationship>) ((Invocable) engine).invokeMethod(relationshipsCallback, "getRelationships", (Object) null);
        }
        return RELATIONSHIPS;
    }

    /**
     * Determine what do with a file that has just been processed.
     *
     * After a script runs its "read" or "write" method, it should update the
     * "lastRoute" field to specify the relationship to which the resulting file
     * will be sent.
     *
     * @return a relationship name
     */
    public Relationship getRoute() {
        return lastRoute;
    }

    // Required because of a potential issue in Rhino -- protected methods are visible in
    // subclasses but protected fields (like "lastRoute") are not
    // change back to protected when we get nashorn
    public void setRoute(Relationship route) {
        lastRoute = route;
    }

    /**
     * Determine where to send a file if an exception is thrown during
     * processing.
     *
     * Subclasses may override this method to use a different relationship, or
     * to determine the relationship dynamically. Returning null causes the file
     * to be deleted instead.
     *
     * Defaults to "failure".
     *
     * @return the name of the relationship to use in event of an exception, or
     * null to delete the file.
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public Relationship getExceptionRoute() throws NoSuchMethodException, ScriptException {
        if (exceptionRouteCallback != null) {
            return (Relationship) ((Invocable) engine).invokeMethod(exceptionRouteCallback, "getExceptionRoute", (Object) null);
        }
        return FAIL_RELATIONSHIP;
    }

    /*
     * Some scripting languages make a method call easier than accessing a member field, so this is a convenience method to get
     * the incoming flow file size.
     */
    // Change back to protected when we get nashorn
    public long getFlowFileSize() {
        return flowFileSize;
    }

    /*
     * Some scripting languages make a method call easier than accessing a member field, so this is a convenience method to get
     * entry date of the flow file.
     */
    // Change back to protected when we get nashorn
    public long getFlowFileEntryDate() {
        return flowFileEntryDate;
    }

    void setLogger(ProcessorLog logger) {
        this.logger = logger;
    }

    /*
     * Required so that scripts in some languages can read access the attribute. Jython (at least) won't let you read the member
     * variable without a getter
     */
    protected ProcessorLog getLogger() {
        return this.logger;
    }

    void setFileName(String scriptFileName) {
        this.scriptFileName = scriptFileName;
    }

    public String getFileName() {
        return this.scriptFileName;
    }

    // this one's public because it's needed by ExecuteScript to update the flow file's attributes AFTER processing is done
    public Map<String, String> getAttributes() {
        return this.attributes;
    }

    /*
     * Some scripting languages make a method call easier than accessing a member field, so this is a convenience method to look
     * up values in the attributes field.
     */
    // Change back to protected when we get nashorn
    public String getAttribute(String key) {
        return this.attributes.get(key);
    }

    /*
     * Some scripting languages make a method call easier than accessing a member field, so this is a convenience method to set
     * key/value pairs in the attributes field.
     */
    // Change back to protected when we get nashorn
    public void setAttribute(String key, String value) {
        this.attributes.put(key, value);
    }

    void setEngine(ScriptEngine scriptEngine) {
        this.engine = scriptEngine;
    }

}


text:
package com.github.mauricio.async.db.mysql.message.server

case class OkMessage(
                      affectedRows : Long,
                      lastInsertId : Long,
                      statusFlags : Int,
                      warnings : Int,
                      message : String )
  extends ServerMessage( ServerMessage.Ok )


text:
<?php
class Parapentes extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('Parapente_model');
	}

	public function index() {
		$data['title'] = 'Gestion des parapentes';
		$this->load->view('header', $data);

		// Critères sur les parapentes à afficher
		$champs = $this->Parapente_model->getFields();
		$data['champsLike'] = null;
		$data['champsEqual'] = null;
		foreach ($champs as $champ) {
			if (isset($_GET[$champ])) {
				if (($champ == 'immatriculation')
				OR ($_GET[$champ] == 'true' OR $_GET[$champ] == 'false')
				OR strtotime(str_replace('/', '-', $_GET[$champ]))) {
					$data['champsEqual'][$champ] = $_GET[$champ];
				} else {
					$data['champsLike'][$champ] = $_GET[$champ];
				}
				$data['old_data'][$champ] = $_GET[$champ];
			}
		}

		$this->load->view('formRechercheParapente', $data);

		$this->display_parapentes($data);

		$this->load->view('footer', $data);
	}

	public function display_parapentes($data) {
		$data['title'] = 'Parapentes';

		// Critère de tri
		if (isset($_GET['o'])) {
			$o = $_GET['o'];
		} else {
			$o = 'immatriculation';
		}

		// Récupération des données
		$data['array_data'] = $this->Parapente_model->get($o, $data['champsEqual'], $data['champsLike'])->result_array();
		$data['fields_metadata'] = $this->Parapente_model->getFieldsMetaData();
		$data['array_headings'] = $this->perso->get_headings('parapente');
		$data['miscInfos'] = $this->Parapente_model->getMisc();

		// Traitement des lignes
		/*foreach($data['array_data'] as $num_row => $row) {
		}*/

		$data['btnNouveau'] = true;
		$data['btnModif'] = true;
		$data['btnInfos'] = true;
		$data['object'] = 'parapente';
		$data['show_false'] = array('en_etat_de_voler');

		$this->load->view('table', $data);
	}

	public function ajouter() {
		$data['title'] = 'Ajouter un parapente';

		if (isset($_POST['immatriculation'])) {
			if (!isset($_POST['biplace'])) {
				$_POST['biplace'] = false;
			}
			$_POST['ptv'] = '['.$_POST['ptv'].','.$_POST['ptv_tmp'].']';
			unset($_POST['ptv_tmp']);
			try {
				$this->Parapente_model->add($_POST);
				redirect('/parapentes', 'location', 301);
			} catch (Exception $e) {
				$data['error_message'] = $e.getMessage();
				redirect('/parapentes', 'location', 400);
			}
		} else {
			$this->load->view('header', $data);

			$data['function'] = 'ajouter';
			$this->load->view('formParapente', $data);

			$this->load->view('footer', $data);
		}
	}

	public function modifier($immatriculation) {
		$data['title'] = 'Modifier un parapente';

		if (isset($_POST['immatriculation'])) {
			if (!isset($_POST['biplace'])) {
				$_POST['biplace'] = false;
			}
			$_POST['ptv'] = '['.$_POST['ptv'].','.$_POST['ptv_tmp'].']';
			unset($_POST['ptv_tmp']);
			try {
				$this->Parapente_model->update($immatriculation, $_POST);
				redirect('/parapentes', 'location', 301);
			} catch (Exception $e) {
				$data['error_message'] = $e.getMessage();
				redirect('/parapentes', 'location', 400);
			}
		} else {
			$this->load->view('header', $data);

			$data['function'] = 'modifier/'.$immatriculation;
			$data['old_data'] = $this->Parapente_model->get('immatriculation', array('immatriculation' => $immatriculation), null)->result_array()[0];
			$this->load->view('formParapente', $data);

			$this->load->view('footer', $data);
		}
	}
}