text:
const expect = require('chai').expect;
const opentracing = require('opentracing');

const Pipeline = require('../../../lib/domain/Pipeline');

const Sandbox = require('@globocom/backstage-functions-sandbox');

describe('Pipeline', () => {
  describe('#run', () => {
    let req;
    let sandbox;
    let step200;
    let step200env;
    let step304;
    let step200b;
    let step404;
    let stepCrash;
    let tracer;
    let span;

    beforeEach(() => {
      req = {
        body: {},
      };
      sandbox = new Sandbox({});
      step200 = {
        namespace: 'backstage',
        id: 'step200',
        script: sandbox.compileCode('200.js', `
                   function main(req, res) {
                       req.body.ok = true;
                       res.send(req.body);
                   }
              `),
      };
      step200b = {
        namespace: 'backstage',
        id: 'step200b',
        script: sandbox.compileCode('200b.js', `
                   function main(req, res) {
                       req.body.ok2 = true;
                       res.send(req.body);
                   }
              `),
      };
      step200env = {
        namespace: 'backstage',
        id: 'step200env',
        script: sandbox.compileCode('200b.js', `
                   function main(req, res) {
                       req.body.env = Object.assign({}, Backstage.env);
                       res.send(req.body);
                   }
              `),
        env: {
          STEP_VAR: 'foo',
        },
      };
      step304 = {
        namespace: 'backstage',
        id: 'step200',
        script: sandbox.compileCode('200.js', `
                   function main(req, res) {
                       res.notModified();
                   }
              `),
      };
      step404 = {
        namespace: 'backstage',
        id: 'step404',
        script: sandbox.compileCode('200.js', `
                   function main(req, res) {
                       res.notFound('Not found an item');
                   }
              `),
      };
      stepCrash = {
        namespace: 'backstage',
        id: 'stepCrash',
        script: sandbox.compileCode('crash.js', `
                   function main(req, res) {
                       res.undefinedMethod();
                   }
              `),
      };
      tracer = new opentracing.MockTracer();
      span = tracer.startSpan('test span');
    });

    it('should be able to run unique function', async () => {
      const result = await new Pipeline(sandbox, req, [step200], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.status).to.be.eql(200);
    });

    it('should be able to run unique function with 304', async () => {
      const result = await new Pipeline(sandbox, req, [step304], span).run();
      expect(result.status).to.be.eql(304);
      expect(result.body).to.be.eql(null);
    });

    it('should be able to run two functions', async () => {
      const result = await new Pipeline(sandbox, req, [step200, step200b], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.body.ok2).to.be.eql(true);
      expect(result.status).to.be.eql(200);
    });

    it('should be able to run three functions', async () => {
      const result = await new Pipeline(sandbox, req, [step200, step200b, step200env], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.body.ok2).to.be.eql(true);
      expect(result.body.env.STEP_VAR).to.be.eql('foo');
      expect(result.status).to.be.eql(200);

      const mockSpanReport = tracer.report();
      const spans = mockSpanReport.spans.filter(s => s.operationName() === 'run function');
      expect(spans.length).to.be.eql(3);
      expect(spans[0].durationMs()).to.be.gte(0);
    });

    it('should be able to run two functions, one with 304', async () => {
      const result = await new Pipeline(sandbox, req, [step200, step304], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.status).to.be.eql(200);
    });

    it('should be able to run three functions, two with 304', async () => {
      const result = await new Pipeline(sandbox, req, [step200, step304, step304], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.status).to.be.eql(200);
    });

    it('should be able to run three functions, one with 304', async () => {
      const result = await new Pipeline(sandbox, req, [step200, step304, step200b], span).run();
      expect(result.body.ok).to.be.eql(true);
      expect(result.body.ok2).to.be.eql(true);
      expect(result.status).to.be.eql(200);
    });

    it('should be able to run one function with 404', async () => {
      try {
        await new Pipeline(sandbox, req, [step404], span).run();
      } catch (err) {
        expect(err.message).to.be.eql('Not found an item');
        expect(err.statusCode).to.be.eql(404);
        return;
      }

      throw new Error('Not raised an error');
    });

    it('should be able to run three functions with 404', async () => {
      try {
        await new Pipeline(sandbox, req, [step200, step404, step200b], span).run();
      } catch (err) {
        expect(err.message).to.be.eql('Not found an item');
        expect(err.statusCode).to.be.eql(404);
        return;
      }

      throw new Error('Not raised an error');
    });

    it('should fail if the first function fail', async () => {
      try {
        await new Pipeline(sandbox, req, [step200, stepCrash], span).run();
        throw new Error('Not failed');
      } catch (err) {
        expect(err.message).to.be.eql('res.undefinedMethod is not a function');
      }

      const mockSpanReport = tracer.report();
      const spans = mockSpanReport.spans.filter(s => s.operationName() === 'run function');
      expect(spans.length).to.be.eql(2);
      expect(spans[0].durationMs()).to.be.gte(0);
      expect(spans[0].tags()).to.be.eql({});
      expect(spans[1].tags()).to.be.eql({ error: true });
    });
  });
});


text:
#ifndef RAMSYS_DETECT_H_IS_INCLUDED
#define RAMSYS_DETECT_H_IS_INCLUDED

#ifdef _WIN32
#  define RAMSYS_WINDOWS
#elif defined(__linux__)
#  define RAMSYS_LINUX
#  define RAMSYS_PTHREADS
#  define RAMSYS_POSIX
#else
#  error i do not recognize this platform.
#endif

#ifdef _MSC_VER
#  define RAMSYS_MSVC
#elif defined(__GNUC__)
#  define RAMSYS_GCC
#else
#  error i do not recognize this compiler.
#endif

#ifdef S_SPLINT_S
#  define RAMSYS_SPLINT
#endif

#endif /* #ifndef RAMSYS_DETECT_H_IS_INCLUDED */

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 88 (1887)

#### Original name
Agaricus izarnii Roum.

### Remarks
null


text:
#ifndef _SCIF_CONTROLLER_H_
#define _SCIF_CONTROLLER_H_

/**
 * @file
 *
 * @brief This file contains all of the interface methods that can be called
 *        by an SCIF user on a SCIF controller object.
 */

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

#include <dev/isci/scil/sci_types.h>
#include <dev/isci/scil/sci_status.h>

/**
 * @brief This method will attempt to construct a framework controller object
 *        utilizing the supplied parameter information.
 *
 * @param[in]  library This parameter specifies the handle to the framework
 *             library object associated with the controller being constructed.
 * @param[in]  controller This parameter specifies the framework controller to
 *             be constructed.
 * @param[in]  user_object This parameter is a reference to the SCIL users
 *             controller object and will be used to associate with the
 *             framework controller.
 *
 * @return Indicate if the controller was successfully constructed or if
 *         it failed in some way.
 * @retval SCI_SUCCESS This value is returned if the controller was
 *         successfully constructed.
 * @retval SCI_FAILURE_UNSUPPORTED_INIT_DATA_VERSION This value is returned
 *         if the controller does not support the supplied oem parameter
 *         data version.
 * @retval SCI_FAILURE_UNSUPPORTED_PORT_CONFIGURATION This value is returned
 *         if the controller doesn't support the port configuration scheme
 *         (APC or MPC).
 */
SCI_STATUS scif_controller_construct(
   SCI_LIBRARY_HANDLE_T      library,
   SCI_CONTROLLER_HANDLE_T   controller,
   void *                    user_object
);

/**
 * @brief This method will initialize the SCI Framework controller object.
 *        This includes initialization of the associated core controller.
 *
 * @param[in]  controller This parameter specifies the controller to be
 *             initialized.
 *
 * @return Indicate if the controller was successfully initialized or if
 *         it failed in some way.
 * @retval SCI_SUCCESS This value is returned if the controller hardware
 *         was successfully initialized.
 */
SCI_STATUS scif_controller_initialize(
   SCI_CONTROLLER_HANDLE_T  controller
);

/**
 * @brief This method returns the suggested scif_controller_start()
 *        timeout amount.  The user is free to use any timeout value,
 *        but this method provides the suggested minimum start timeout
 *        value.  The returned value is based upon empirical information
 *        determined as a result of interoperability testing.
 *
 * @param[in]  controller the handle to the controller object for which
 *             to return the suggested start timeout.
 *
 * @return  This method returns the number of milliseconds for the
 *          suggested start operation timeout.
 */
U32 scif_controller_get_suggested_start_timeout(
   SCI_CONTROLLER_HANDLE_T  controller
);

/**
 * @brief This method will start the SCIF controller.  The SCI User completion
 *        callback is called when the following conditions are met:
 *        -# the return status of this method is SCI_SUCCESS.
 *        -# after all of the phys have successfully started or been given
 *           the opportunity to start.
 *
 * @pre   The controller must be in the INITIALIZED or STARTED state.
 *
 * @param[in]  controller the handle to the controller object to start.
 * @param[in]  timeout This parameter specifies the number of milliseconds
 *             in which the start operation should complete.
 *
 * @return Indicate if the controller start method succeeded or failed in
 *         some way.
 * @retval SCI_SUCCESS if the start operation succeeded.
 * @retval SCI_WARNING_ALREADY_IN_STATE if the controller is already in
 *         the STARTED state.
 * @retval SCI_FAILURE_INVALID_STATE if the controller is not either in
 *         the INITIALIZED or STARTED states.
 * @retval SCI_FAILURE_INVALID_MEMORY_DESCRIPTOR if there are
 *         inconsistent or invalid values in the supplied
 *         SCI_PHYSICAL_MEMORY_DESCRIPTOR array.
 * @retval SCI_FAILURE_UNSUPPORTED_PORT_CONFIGURATION This value is
 *         returned if the phy to port allocation cannot be supported.
 *
 * @see For additional information please refer to: scic_controller_start()
 */
SCI_STATUS scif_controller_start(
   SCI_CONTROLLER_HANDLE_T  controller,
   U32                      timeout
);

/**
 * @brief This method will stop an individual framework controller object. This
 *        includes quiescing IOs, releasing affiliations, and other shutdown
 *        related operations. This method will invoke the associated user
 *        callback upon completion.  The completion callback is called when
 *        the following conditions are met:
 *           -# the method return status is SCI_SUCCESS.
 *           -# the controller has been quiesced.
 *        This method will ensure that all framework IO requests are quiesced
 *        and any additional framework operations are halted.
 *
 * @pre   The controller must be in the STARTED or STOPPED state.
 *
 * @param[in]  controller the handle to the controller object to stop.
 * @param[in]  timeout This parameter specifies the number of milliseconds
 *             in which the stop operation should complete.
 *
 * @return Indicate if the controller stop method succeeded or failed in
 *         some way.
 * @retval SCI_SUCCESS if the stop operation successfully began.
 * @retval SCI_WARNING_ALREADY_IN_STATE if the controller is already in
 *         the STOPPED state.
 * @retval SCI_FAILURE_INVALID_STATE if the controller is not either in
 *         the STARTED or STOPPED states.
 *
 * @see For additional information please refer to: scic_controller_stop()
 */
SCI_STATUS scif_controller_stop(
   SCI_CONTROLLER_HANDLE_T  controller,
   U32                      timeout
);

/**
 * @brief This method will reset the supplied framework controller regardless
 *        of the state of said controller.  This operation is considered
 *        destructive.  Outstanding IO requests are not aborted or completed
 *        at the actual remote device.  However, the framework will
 *        manufacture completion callbacks to the OS driver for the IO
 *        requests.
 *
 * @param[in]  controller the handle to the controller object to reset.
 *
 * @return Indicate if the controller reset method succeeded or failed in
 *         some way.
 * @retval SCI_SUCCESS if the reset operation successfully started.
 * @retval SCI_FATAL_ERROR if the controller reset operation is unable to
 *         complete.
 *
 * @see For additional information please refer to: scic_controller_reset()
 */
SCI_STATUS scif_controller_reset(
   SCI_CONTROLLER_HANDLE_T  controller
);

/**
 * @brief This method returns the SCI Core controller handle associated
 *        with this controller.
 *
 * @param[in]  scif_controller the handle to the controller object for which
 *             to retrieve the core specific controller handle
 *
 * @return Return the SCI core controller handle associated with the supplied
 *         framework controller.
 */
SCI_CONTROLLER_HANDLE_T scif_controller_get_scic_handle(
   SCI_CONTROLLER_HANDLE_T   scif_controller
);

/**
 * @brief This method is called by the SCIF user to send/start a framework
 *        IO request.
 *
 * @param[in]  controller the handle to the controller object for which
 *             to start an IO request.
 * @param[in]  remote_device the handle to the remote device object for which
 *             to start an IO request.
 * @param[in]  io_request the handle to the io request object to start.
 * @param[in]  io_tag This parameter specifies a previously allocated IO tag
 *             that the user desires to be utilized for this request.
 *             This parameter is optional.  The user is allowed to supply
 *             SCI_CONTROLLER_INVALID_IO_TAG as the value for this parameter.
 *             @see scic_controller_allocate_tag() for more information
 *             on allocating a tag.
 *
 * @return Indicate if the controller successfully started the IO request.
 * @retval SCI_IO_SUCCESS if the IO request was successfully started.
 *
 * @see For additional information please refer to: scic_controller_start_io()
 *
 * @todo Determine the failure situations and return values.
 */
SCI_IO_STATUS scif_controller_start_io(
   SCI_CONTROLLER_HANDLE_T     controller,
   SCI_REMOTE_DEVICE_HANDLE_T  remote_device,
   SCI_IO_REQUEST_HANDLE_T     io_request,
   U16                         io_tag
);

/**
 * @brief This method is called by the SCIF user to send/start a framework
 *        task management request.
 *
 * @param[in]  controller the handle to the controller object for which
 *             to start the task management request.
 * @param[in]  remote_device the handle to the remote device object for which
 *             to start the task management request.
 * @param[in]  task_request the handle to the task request object to start.
 * @param[in]  io_tag This parameter specifies a previously allocated IO tag
 *             that the user desires to be utilized for this request.  Note
 *             this not the io_tag of the request being managed.  It is to
 *             be utilized for the task request itself.
 *             This parameter is optional.  The user is allowed to supply
 *             SCI_CONTROLLER_INVALID_IO_TAG as the value for this parameter.
 *             @see scic_controller_allocate_tag() for more information
 *             on allocating a tag.
 *
 * @return Indicate if the controller successfully started the IO request.
 * @retval SCI_TASK_SUCCESS if the task request was successfully started.
 *
 * @see For additional information please refer to: scic_controller_start_task()
 *
 * @todo Determine the failure situations and return values.
 */
SCI_TASK_STATUS scif_controller_start_task(
   SCI_CONTROLLER_HANDLE_T     controller,
   SCI_REMOTE_DEVICE_HANDLE_T  remote_device,
   SCI_TASK_REQUEST_HANDLE_T   task_request,
   U16                         io_tag
);

/**
 * @brief This method is called by the SCI user to complete a previously
 *        started IO request.  After this method is invoked, the user should
 *        consider the IO request as invalid until it is properly reused
 *        (i.e. re-constructed).
 *
 * @param[in]  controller The handle to the controller object for which
 *             to complete the IO request.
 * @param[in]  remote_device The handle to the remote device object for which
 *             to complete the IO request.
 * @param[in]  io_request the handle to the io request object to complete.
 *
 * @return Indicate if the controller successfully completed the IO request.
 * @retval SCI_SUCCESS if the completion process was successful.
 *
 * @see For additional information please refer to:
 *      scic_controller_complete_io()
 */
SCI_STATUS scif_controller_complete_io(
   SCI_CONTROLLER_HANDLE_T     controller,
   SCI_REMOTE_DEVICE_HANDLE_T  remote_device,
   SCI_IO_REQUEST_HANDLE_T     io_request
);

/**
 * @brief This method will perform framework specific completion operations for
 *        a task management request. After this method is invoked, the user
 *        should consider the task request as invalid until it is properly
 *        reused (i.e. re-constructed).
 *
 * @param[in]  controller The handle to the controller object for which
 *             to complete the task management request.
 * @param[in]  remote_device The handle to the remote device object for which
 *             to complete the task management request.
 * @param[in]  task_request the handle to the task management request object
 *             to complete.
 *
 * @return Indicate if the controller successfully completed the task
 *         management request.
 * @retval SCI_SUCCESS if the completion process was successful.
 */
SCI_STATUS scif_controller_complete_task(
   SCI_CONTROLLER_HANDLE_T     controller,
   SCI_REMOTE_DEVICE_HANDLE_T  remote_device,
   SCI_TASK_REQUEST_HANDLE_T   task_request
);

/**
 * @brief This method simply provides the user with a unique handle for a
 *        given SAS/SATA domain index.
 *
 * @param[in]  controller This parameter represents the handle to the
 *             controller object from which to retrieve a domain (SAS or
 *             SATA) handle.
 * @param[in]  port_index This parameter specifies the domain index in
 *             the controller for which to retrieve the domain handle.
 *             @note 0 <= port_index < maximum number of phys.
 * @param[out] domain_handle This parameter specifies the retrieved domain
 *             handle to be provided to the caller.
 *
 * @return Indicate if the retrieval of the domain handle was successful.
 * @retval SCI_SUCCESS This value is returned if the retrieval was successful.
 * @retval SCI_FAILURE_INVALID_PORT This value is returned if the supplied
 *         port index is not invalid.
 */
SCI_STATUS scif_controller_get_domain_handle(
   SCI_CONTROLLER_HANDLE_T   controller,
   U8                        port_index,
   SCI_DOMAIN_HANDLE_T     * domain_handle
);

/**
 * @brief This method allows the user to configure the SCI Framework
 *        into either a performance mode or a memory savings mode.
 *
 * @param[in]  controller This parameter represents the handle to the
 *             controller object for which to update the operating
 *             mode.
 * @param[in]  mode This parameter specifies the new mode for the
 *             controller.
 *
 * @return Indicate if the user successfully change the operating mode
 *         of the controller.
 * @retval SCI_SUCCESS The user successfully updated the mode.
 */
SCI_STATUS scif_controller_set_mode(
   SCI_CONTROLLER_HANDLE_T   controller,
   SCI_CONTROLLER_MODE       mode
);

/**
 * @brief This method simply returns the T10 SCSI to ATA Translation (SAT)
 *        specification version to which this translator is compliant for
 *        supported commands.
 *
 * @return An integer value indicating the SAT version to which this
 *         translator complies.
 */
U32 scif_controller_get_sat_compliance_version(
   void
);

/**
 * @brief This method simply returns the revision of the T10 SCSI to ATA
 *        Translation (SAT) specification version to which this translator
 *        is compliant for supported commands.
 *
 * @return An integer value indicating the revision of the SAT version
 *         to which this translator complies.
 */
U32 scif_controller_get_sat_compliance_version_revision(
   void
);

/**
 * @brief This method is called by the SCI user to start internal io.
 */
typedef void (*SCI_START_INTERNAL_IO_ROUTINE)(
   SCI_CONTROLLER_HANDLE_T controller
);

#if !defined(DISABLE_INTERRUPTS)
/**
 * @brief This method allows the user to configure the interrupt coalescence.
 *           Please refer to the comment header for
 *           scic_controller_set_interrupt_coalescence() to find details.
 */
SCI_STATUS scif_controller_set_interrupt_coalescence(
   SCI_CONTROLLER_HANDLE_T controller,
   U32                     coalesce_number,
   U32                     coalesce_timeout
);

/**
 * @brief This method retrieves the interrupt coalescence information.
 *           Please refer to the comment header for
 *           scic_controller_get_interrupt_coalescence() to find details.
 */
void scif_controller_get_interrupt_coalescence(
   SCI_CONTROLLER_HANDLE_T controller,
   U32                   * coalesce_number,
   U32                   * coalesce_timeout
);

#else // !defined(DISABLE_INTERRUPTS)

#define scif_controller_set_interrupt_coalescence(controller, num, timeout) \
        SCI_FAILURE
#define scif_controller_get_interrupt_coalescence(controller, num, timeout)

#endif // !defined(DISABLE_INTERRUPTS)

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // _SCIF_CONTROLLER_H_


text:
""" Personality as a high level cfg object """
from datetime import datetime

from sqlalchemy import (Column, Integer, DateTime, Sequence, String, ForeignKey,
                        UniqueConstraint)
from sqlalchemy.sql import select
from sqlalchemy.orm import relation, deferred
from sqlalchemy.orm.session import object_session

from aquilon.aqdb.model import Base, Archetype
from aquilon.aqdb.column_types.aqstr import AqStr

_ABV = 'prsnlty'
_TN  = 'personality'

class Personality(Base):
    """ Personality names """
    __tablename__  = _TN

    id = Column(Integer, Sequence('%s_seq'%(_ABV)), primary_key=True)
    name = Column(AqStr(32), nullable=False)
    archetype_id = Column(Integer, ForeignKey(
        'archetype.id', name='%s_arch_fk'%(_ABV)), nullable=False)

    creation_date = Column(DateTime, default=datetime.now, nullable=False)
    comments = Column(String(255), nullable=True)

    archetype = relation(Archetype, backref='personality', uselist=False)

    def __repr__(self):
        s = ("<"+self.__class__.__name__ + " name ='"+ self.name +
             "', " + str(self.archetype) +'>')
        return s

    @classmethod
    def by_archetype(cls, dbarchetype):
        session = object_session(dbarchetype)
        return session.query(cls).filter(
            cls.__dict__['archetype'] == dbarchetype).all()

personality = Personality.__table__
table       = Personality.__table__

personality.primary_key.name='%s_pk'%(_ABV)
personality.append_constraint(UniqueConstraint('name', 'archetype_id',
                                               name='%s_uk'%(_TN)))

def populate(sess, *args, **kw):
    if len(sess.query(Personality).all()) > 0:
        return

    import os

    cfg_base = kw['cfg_base']
    assert os.path.isdir(cfg_base), "No such directory '%s'"%(cfg_base)

    for arch in sess.query(Archetype).all():
        #find aquilon archetype and all directories under it
        #change if we grow past having multiple archtypes w/ personalities
        if arch.name == 'aquilon':
            p = os.path.join(cfg_base, arch.name, 'personality')
            assert os.path.isdir(p), \
                    "Can't find personality directory '%s' in populate" % p
            for i in os.listdir(p):
                if os.path.isdir(os.path.abspath(os.path.join(p, i))):
                    pers = Personality(name=i, archetype=arch)
                    sess.add(pers)
        else:
            pers = Personality(name='generic', archetype=arch)
            sess.add(pers)

    try:
        sess.commit()
    except Exception, e:
        sess.rollback()
        raise e

    a = sess.query(Personality).first()
    assert(a)


text:
Bash script for adding torrents for download to Transmission through Transmission's RPC protocol. Designed to be as portable as possible since one might want to run it on a NAS etc.

It can be used for adding torrents for download and tracking progress.

**Not working as expected on your system? Please create an issue.**

![screenshot](screenshot.png)

# Usage
A very basic example is: `./transmission-rpc.sh -s myserver.com -u myusername -p mypassword <torrent>` where *\<torrent\>* can be an external link, local path or a magnet link.

For more usage information refer to the help text:
```
$ ./transmission-rpc.sh -h
    Usage: ./transmission-rpc.sh [options] <Torrent address or local file path>

    This script adds a torrent for download through Transmission's RPC protocol.

    EXAMPLE:
        ./transmission-rpc.sh -s my-server.com:9092 -u myUsername -p myPassword "http://www.frostclick.com/torrents/video/animation/Big_Buck_Bunny_1080p_surround_frostclick.com_frostwire.com.torrent"

    OPTIONS:
       -h      Show this help message
       -s      Server hostname and optionally port in the format host:port. Defaults to 127.0.0.1:9092 if not specified.
       -u      Server username
       -p      Server password
       -l      List active torrents and their progress
       -P      Used together with the -l flag. Makes -l list not only active torrents but also paused ones.
       -q      Quiet mode. Add torrent for download then exit - don't display download progress
       -c      Colored output
```


text:
@implementation ZFSearchSetByCategoryHttpPostIn

@synthesize categoryCode = _categoryCode;
#if FL_MRC
- (void) dealloc {
    [_categoryCode release];
    [_limit release];
    [_offset release];
    [_type release];
    [_searchId release];
    [_sortOrder release];
    [super dealloc];
}
#endif
@synthesize limit = _limit;
@synthesize offset = _offset;
@synthesize searchId = _searchId;
+ (ZFSearchSetByCategoryHttpPostIn*) searchSetByCategoryHttpPostIn {
    return FLAutorelease([[[self class] alloc] init]);
}
@synthesize sortOrder = _sortOrder;
@synthesize type = _type;

@end


text:
//
// Created by denn nevera on 2019-12-23.
//
#pragma once

#include "Kernel.h"
#include <vector>

namespace imetalling {

    /**
     * Класс трансляции изображения в карту экспозиций
     */
    class FalseColorKernel: public Kernel {
    public:
        FalseColorKernel(const void *command_queue,
                         const Texture &source,
                         const Texture &destination,
                         bool wait_until_completed = WAIT_UNTIL_COMPLETED);
        void setup(CommandEncoder &commandEncoder) override ;
    private:
        std::vector<simd::float3> color_map_;
    };
}


text:
namespace android.widget
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class ImageButton : android.widget.ImageView
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected ImageButton(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		protected override bool onSetAlpha(int arg0)
		{
			return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ImageButton.staticClass, "onSetAlpha", "(I)Z", ref global::android.widget.ImageButton._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public ImageButton(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.widget.ImageButton._m1.native == global::System.IntPtr.Zero)
				global::android.widget.ImageButton._m1 = @__env.GetMethodIDNoThrow(global::android.widget.ImageButton.staticClass, "<init>", "(Landroid/content/Context;)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ImageButton.staticClass, global::android.widget.ImageButton._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			Init(@__env, handle);
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public ImageButton(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.widget.ImageButton._m2.native == global::System.IntPtr.Zero)
				global::android.widget.ImageButton._m2 = @__env.GetMethodIDNoThrow(global::android.widget.ImageButton.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ImageButton.staticClass, global::android.widget.ImageButton._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			Init(@__env, handle);
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public ImageButton(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.widget.ImageButton._m3.native == global::System.IntPtr.Zero)
				global::android.widget.ImageButton._m3 = @__env.GetMethodIDNoThrow(global::android.widget.ImageButton.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ImageButton.staticClass, global::android.widget.ImageButton._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			Init(@__env, handle);
		}
		static ImageButton()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.widget.ImageButton.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ImageButton"));
		}
	}
}


text:
package com.facebook.swift.parser.model;

import com.google.common.base.Objects;

import static com.google.common.base.Preconditions.checkNotNull;

public class IdentifierType
        extends ThriftType
{
    private final String name;

    public IdentifierType(String name)
    {
        this.name = checkNotNull(name, "name");
    }

    public String getName()
    {
        return name;
    }

    @Override
    public String toString()
    {
        return Objects.toStringHelper(this)
                .add("name", name)
                .toString();
    }
}


text:
from collections import namedtuple
from zip_code_radius import distance

Point = namedtuple('Point', ['lat', 'lon'])

Rectangle = namedtuple('Rectangle', ['nw', 'se'])

def median(items):
    """Returns the median value of the argument items.

    Args:
        items (iterable): a list of numeric values

    Returns:
        numeric: the median of the list if non-empty else None

    """
    items = sorted(items)
    if len(items) < 1:
        return None
    if len(items) %2 == 1:
        return items[((len(items)+1)/2)-1]
    if len(items) %2 == 0:
        return float(sum(items[(len(items)/2)-1:(len(items)/2)+1]))/2.0

def inside(rectangle, point):
    """Determine whether the argument Point is inside of the argument
    Rectangle.

    Args:
        rectangle (Rectangle): the bounding rectangle
        point (Point): the point

    Returns:
        bool: True if the Point is inside of the Rectangle, otherwise
              False.

    """
    return rectangle.se.lon >= point.lon and \
           point.lon >= rectangle.nw.lon and \
           rectangle.nw.lat >= point.lat and \
           rectangle.se.lat <= point.lat

def intersect(rectangle_a, rectangle_b):
    """Determine whether the two Rectangles intersect each other.

    Args:
        rectangle_a (Rectangle): the 1st rectangle
        rectangle_b (Rectangle): the 2nd rectangle

    Returns:
        bool: True if rectangle_a and rectangle_b intersect / overlap
              otherwise False.

    """
    if rectangle_a.nw.lon > rectangle_b.se.lon:
        # a's LHS is to the right of b's RHS
        return False
    if rectangle_a.se.lon < rectangle_b.nw.lon:
        # a's RHS is to the left of b's LHS
        return False
    if rectangle_a.nw.lat < rectangle_b.se.lat:
        # a's TOP is below b's BOTTOM
        return False
    if rectangle_a.se.lat > rectangle_b.nw.lat:
        # a's BOTTOM is above b's TOP
        return False
    return True

def split(rectangle, point):
    """Split the argument Rectangle into four quadrants (nw, ne, se, sw)
    around the argument Point.

    Args:
        rectangle (Rectangle): the 1st rectangle
        point (Point): the point inside the rectangle around which the
            four quadrants will be centered

    Results:
        tuple (nw, ne, se, sw): the four quadrants of the rectangle

    """
    nw = Rectangle(
        nw=rectangle.nw,
        se=point)
    ne = Rectangle(
        nw=Point(lat=rectangle.nw.lat, lon=point.lon),
        se=Point(lat=point.lat, lon=rectangle.se.lon))
    se = Rectangle(
        nw=point,
        se=rectangle.se)
    sw = Rectangle(
        nw=Point(lat=point.lat, lon=rectangle.nw.lon),
        se=Point(lat=rectangle.se.lat, lon=point.lon))
    return (nw, ne, se, sw)

class QuadTree(object):
    """An implementation of a quad-tree.

    This quad-tree recursively divides a list of US postal codes
    into four quadrants until either

    (a) a depth of 8 is reached
    (b) there are 16 of fewer postal codes in this node

    Acknowledgements:
    [1]: http://www.pygame.org/wiki/QuadTree

    """

    def __init__(self, zip_codes, depth=0, rectangle=None, split_median=True):
        """Creates a quad-tree.

        Args:
            zip_codes (iterable, ZipCode): the US postal codes to organize
            depth (int): the depth of this node. internal use only.
            rectangle (Rectangle): the bounding box of this node. internal
                use only.
            split_median (bool): whether to split the bounding box on the
                median lat/lon when True, otherwise on the center of the box

        """
        self.depth = depth
        self.nw = self.ne = self.se = self.sw = None
        if rectangle:
            self.rectangle = rectangle
        else:
            max_lon=max(z.lon for z in zip_codes)
            min_lon=min(z.lon for z in zip_codes)
            max_lat=max(z.lat for z in zip_codes)
            min_lat=min(z.lat for z in zip_codes)
            rectangle = self.rectangle = Rectangle(
                nw=Point(lat=max_lat, lon=min_lon),
                se=Point(lat=min_lat, lon=max_lon))
        if depth >= 8 or len(zip_codes) <= 16:
            self.zip_codes = zip_codes
        else:
            if split_median:
                clat = median([z.lat for z in zip_codes])
                clon = median([z.lon for z in zip_codes])
            else:
                clat = rectangle.nw.lat - rectangle.se.lat
                clon = rectangle.nw.lon - rectangle.se.lon
            rnw, rne, rse, rsw = split(rectangle, Point(lat=clat, lon=clon))
            znw = []
            zne = []
            zse = []
            zsw = []
            for zip_code in zip_codes:
                if inside(rnw, zip_code):
                    znw.append(zip_code)
                if inside(rne, zip_code):
                    zne.append(zip_code)
                if inside(rse, zip_code):
                    zse.append(zip_code)
                if inside(rsw, zip_code):
                    zsw.append(zip_code)
            self.zip_codes = []
            if len(znw) > 0:
                self.nw = QuadTree(znw, depth+1, rnw)
            if len(zne) > 0:
                self.ne = QuadTree(zne, depth+1, rne)
            if len(zse) > 0:
                self.se = QuadTree(zse, depth+1, rse)
            if len(zsw) > 0:
                self.sw = QuadTree(zsw, depth+1, rsw)

    def search(self, zip_code, radius, in_miles=True, rectangle=None):
        """Search the quad-tree for US postal codes within a given
        radius of the argument US postal code.

        Args:
            zip_code (ZipCode): the center of the search
            radius (numeric): the maximum distance from zip_code
            in_miles (bool): whether the radius is in miles (True)
                otherwise kilometers (False)
            rectangle (Rectangle): the bounding box of the search
                represented as a circle on the surface of a sphere.
                internal use only.

        Returns:
            list (ZipCode): all US postal codes within radius of the
                argument US postal code

        """
        if rectangle is None:
            se_lat, nw_lon, nw_lat, se_lon = distance.bounding_box(zip_code.lon, zip_code.lat, radius, in_miles)
            rectangle = Rectangle(
                nw=Point(lat=nw_lat, lon=nw_lon),
                se=Point(lat=se_lat, lon=se_lon))
        results = [z for z in self.zip_codes
                   if distance.haversine(zip_code.lon, zip_code.lat, z.lon, z.lat, in_miles) <= radius]
        if self.nw is not None:
            if intersect(self.nw.rectangle, rectangle):
                results.extend(self.nw.search(zip_code, radius, in_miles, rectangle))
        if self.ne is not None:
            if intersect(self.ne.rectangle, rectangle):
                results.extend(self.ne.search(zip_code, radius, in_miles, rectangle))
        if self.se is not None:
            if intersect(self.se.rectangle, rectangle):
                results.extend(self.se.search(zip_code, radius, in_miles, rectangle))
        if self.sw is not None:
            if intersect(self.sw.rectangle, rectangle):
                results.extend(self.sw.search(zip_code, radius, in_miles, rectangle))
        return results


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0006_auto_20151115_0609'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='job',
            options={'ordering': ['order'], 'verbose_name': 'Job Details', 'verbose_name_plural': 'Job Postings'},
        ),
        migrations.AddField(
            model_name='job',
            name='location',
            field=models.CharField(default=b'', max_length=100),
        ),
        migrations.AlterField(
            model_name='job',
            name='level',
            field=models.IntegerField(default=0, choices=[(3500, b'Platinum'), (2000, b'Diamond'), (1500, b'Gold'), (1000, b'Silver'), (500, b'Bronze'), (0, b'None')]),
        ),
    ]


text:
title: Averages-Mode
id: 594d8d0ab97724821379b1e6
challengeType: 5
videoUrl: ''
localeTitle: Modo de promedios
---

## Description

 Escribe un programa para encontrar el valor de modo de una colección.

 El caso donde la colección está vacía puede ser ignorado. Se debe tener cuidado para manejar el caso donde el modo no es único.

 Si no es apropiado o no es posible admitir una colección general, use un vector (matriz), si es posible. Si no es apropiado o no es posible admitir un tipo de valor no especificado, use números enteros.

## Instructions

## Tests

```yml
tests:
  - text: <code>mode</code> es una función.
    testString: 'assert(typeof mode === "function", "<code>mode</code> is a function.");'
  - text: '<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> debe ser igual a <code>[6]</code>'
    testString: 'assert.deepEqual(mode(arr1), [6], "<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>");'
  - text: '<code>mode([1, 2, 4, 4, 1])</code> debe ser igual a <code>[1, 4]</code> .'
    testString: 'assert.deepEqual(mode(arr2).sort(), [1, 4], "<code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.");'

```

## Challenge Seed

```js
function mode (arr) {
  // Good luck!
  return true;
}

```

### After Test

```js
console.info('after the test');
```

## Solution

```js
// solution required
```


text:
/
    $(".select-all").change(function() {

        objGrid = $(this).closest(".grid");
        checked = $(this).is(":checked");

        objGrid.find(".select-all-item").each(function() {
            $(this).prop("checked", checked);
        });

    });

    /*--------------------------------------------------------------------------
     * On change event handler for datagrid select-all-item checkboxes. Set the
     * state of the select-all checkbox (uncheck all, check all or indeterminate)
     *
     */
    $(".select-all-item").change(function() {
        var checkCount = 0;

        objGrid = $(this).closest(".grid");
        objSelectItems = objGrid.find(".select-all-item");
        objSelect = objGrid.find(".select-all");

        /* Count the number of checked items */
        objSelectItems.each(function() {
            if ($(this).is(":checked"))
                checkCount++;
        });

        if (checkCount == 0) {
            objSelect.prop("indeterminate", false);
            objSelect.prop("checked", false);

        } else if (checkCount == objSelectItems.length) {
            objSelect.prop("indeterminate", false);
            objSelect.prop("checked", true);

        } else {
            objSelect.prop("indeterminate", true);
        }
    });
});


text:
package io.skysail.server.app.designer.restclient;

import java.io.IOException;

import org.json.*;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.oauth.ProtectedClientResource;
import org.restlet.ext.oauth.internal.Token;
import org.restlet.representation.*;
import org.restlet.resource.*;

public class FacebookMeServerResource extends ServerResource {
    @Get
    public Representation getMe() throws IOException, JSONException {
        Token token = (Token) getRequest().getAttributes().get(Token.class.getName());
        if (token == null) {
            return new StringRepresentation("Token not found!");
        }

        ProtectedClientResource me = new ProtectedClientResource("https://graph.facebook.com/me");
        me.setUseBodyMethod(true);
        me.setToken(token);

        JSONObject result = new JsonRepresentation(me.get()).getJsonObject();

        return new StringRepresentation("Hello " + result.getString("name") + "

" + result.toString());
    }
}


text:
package org.spoofax.jsglr2.parser.result;

import java.util.Collection;
import java.util.Collections;

import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.parseforest.IParseForest;
import org.spoofax.jsglr2.parser.AbstractParseState;
import org.spoofax.jsglr2.parser.ParseException;
import org.spoofax.jsglr2.parser.Position;

public class ParseFailure<ParseForest extends IParseForest> extends ParseResult<ParseForest> {

    public final ParseFailureCause failureCause;

    public ParseFailure(AbstractParseState<?, ?> parseState, ParseFailureCause failureCause) {
        super(parseState, Collections.singletonList(failureCause.toMessage()));

        this.failureCause = failureCause;
    }

    public ParseFailure(AbstractParseState<?, ?> parseState, Collection<Message> messages,
        ParseFailureCause failureCause) {
        super(parseState, messages);

        this.failureCause = failureCause;
    }

    public boolean isSuccess() {
        return false;
    }

    public ParseException exception() {
        Position position = failureCause.position;

        return new ParseException(failureCause, position != null ? parseState.inputStack.safeCharacter() : null);
    }

}


text:
import entities as ent
import datetime

def get_experiments_all():
    ent.database.connect()
    query = ent.Experiments.select()
    ent.database.close()
    return query

def get_experiment_by_identifier(experiment_identifier):
    ent.database.connect()
    query = ent.ExperimentDataset.select().join(ent.Experiments).switch(ent.ExperimentDataset).join(ent.Datasets).join(
        ent.DatasetTypes).where(ent.Experiments.public_identifier == experiment_identifier)

    ent.database.close()

    return query

def get_generated_content(dataset, method, experiment):
    ent.database.connect()
    query = ent.GeneratedContent.select().join(ent.Methods) \
        .switch(ent.GeneratedContent) \
        .join(ent.Experiments) \
        .switch(ent.GeneratedContent) \
        .join(ent.Datasets) \
        .where((ent.Methods.public_identifier == method) & (ent.Experiments.public_identifier == experiment) & (
        ent.Datasets.public_identifier == dataset))

    ent.database.close()

    return query

def link_dataset_to_experiment(experiment_identifier, dataset_identifier):
    ent.database.connect()
    experiment = ent.Experiments.get(ent.Experiments.public_identifier == experiment_identifier)
    dataset = ent.Datasets.get(ent.Datasets.public_identifier == dataset_identifier)

    new_link = ent.ExperimentDataset.create(experiment=experiment.id, dataset=dataset.id)
    ent.database.close()

    return new_link

def unlink_dataset_to_experiment(experiment_identifier, dataset_identifier):
    ent.database.connect()
    experiment = ent.Experiments.get(ent.Experiments.public_identifier == experiment_identifier)
    dataset = ent.Datasets.get(ent.Datasets.public_identifier == dataset_identifier)

    q = ent.ExperimentDataset.delete().where(ent.ExperimentDataset.experiment == experiment.id,
                                         ent.ExperimentDataset.dataset == dataset.id)
    q.execute()

    ent.database.close()

def get_generated_content_by_identifier(identifier):
    ent.database.connect()

    query = ent.GeneratedContent.select().join(ent.Methods) \
        .switch(ent.GeneratedContent) \
        .join(ent.Experiments) \
        .switch(ent.GeneratedContent) \
        .join(ent.Datasets) \
        .where(ent.GeneratedContent.public_identifier == identifier)

    ent.database.close()

    return query

def create_experiment(identifier, description, type):
    ent.database.connect()
    entity = ent.Experiments.create(public_identifier=identifier, description=description, type=type, created_on=datetime.date.today())

    ent.database.close()

    return entity

# create_experiment("olol", "OMG", "dunno")

def create_generated_content(identifier):
    pass

def test():
    for e in get_experiments_all():
        print e.public_identifier

def test2():
    for e in get_experiment_by_identifier("demo_exp_march"):
        print e.experiment.public_identifier

def test_link(exp, data):
    link_dataset_to_experiment(exp, data)

def test_unlink(exp, data):
    unlink_dataset_to_experiment(exp, data)

# test2()

# test_link("demo_exp_march", "voom_normalized_read")

# test_unlink("demo_exp_march", "voom_normalized_read")


text:
{% extends "dragoman_blog/dragoman_blog_base.html" %}
{% load staticfiles i18n placeholder_tags %}

{% block dragoman_content %}

{# ------------------------------------------------------------ #}

 {{ object.title }}

						 by
						 {{ object.author }}
						|  {{ object.pub_date|date:"d F Y" }}
						|  3 Comments
						|  39 Shares

							{% for translation in object.master.entrytranslation_set.all %}
							{% if forloop.first %}{% trans " | Also available in:" %}{% endif %}
							{% language translation.language_code %}
							{% if translation.language_code == object.language_code %}
							{% else %}
							{{ translation.language_code|language_name_local }} ({{ translation.language_code|language_name }})
							{% endif %}
							{% endlanguage %}
							{% endfor %}

						 Tags :
						Snipp
						Bootstrap
						UI
						growth

						{% render_placeholder object.master.placeholder language object.language_code %}

 {# pannel-body #}

 {# pannel #}

							About the Author
							(Author Profile)

						This is the author biographical info found on your user profile page.
						You should write something here. Lorem ipsum dolor sit amet,
						consectetuer adipiscing elit. Morbi quis risus at nisl blandit feugiat.
						Ut vel orci quis sem dapibus iaculis. Aliquam ut nunc quis nisi
						tincidunt tincidunt. Pellentesque enim.

Related Posts:

Full-Width Featured Image

Video Post #3 Full Width

This is a Full-Width Test Post

Video Post #5

This is a Test Post With Some Comments

{# ------------------------------------------------------------ #}

Subscribe

If you enjoyed this article, subscribe to receive more just like it.

					<form action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=michaelpollock', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
						<input value="michaelpollock" name="uri" type="hidden">
						<input name="loc" value="en_US" type="hidden">

					<input class="sub" name="email" value="subscribe via email" onfocus="if (this.value == 'subscribe via email') {this.value = '';}" onblur="if (this.value == '') {this.value = 'subscribe via email';}" type="text"><input value="submit" class="subbutton" type="submit">

					Privacy guaranteed. We never share your info.
				</form>

{# ------------------------------------------------------------ #}

Leave a Reply

							<form action="http://wp-clear-new.solostreamsites.com/wp-comments-post.php" method="post" id="commentform">

Your email address will not be published. Required fields are marked *

Name * <input id="author" name="author" size="30" aria-required="true" type="text">

Email * <input id="email" name="email" size="30" aria-required="true" type="text">

Website<input id="url" name="url" size="30" type="text">

Comment<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>

								<input name="submit" id="submit" value="Post Comment" type="submit">
								<input name="comment_post_ID" value="280" id="comment_post_ID" type="hidden">
								<input name="comment_parent" id="comment_parent" value="0" type="hidden">

<input id="akismet_comment_nonce" name="akismet_comment_nonce" value="c4e918a76e" type="hidden">
					</form>

						« Pure Beauty

						WP-Clear Tutorials Moved »

{# ------------------------------------------------------------ #}

{% endblock dragoman_content %}


text:
package app.models.petstore;

public class Category {

    private Long   id   = null;
    private String name = null;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
package sessions

import (
	"encoding/base32"
	"github.com/bradfitz/gomemcache/memcache"
	"github.com/gorilla/securecookie"
	"io"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
)

// Store is an interface for custom session stores.
type Store interface {
	Get(r *http.Request, name string) (*Session, error)
	New(r *http.Request, name string) (*Session, error)
	Save(r *http.Request, w http.ResponseWriter, s *Session) error
}

// CookieStore ----------------------------------------------------------------

// NewCookieStore returns a new CookieStore.
//
// Keys are defined in pairs to allow key rotation, but the common case is
// to set a single authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for
// encryption. The encryption key can be set to nil or omitted in the last
// pair, but the authentication key is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes.
// The encryption key, if set, must be either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256 modes.
//
// Use the convenience function securecookie.GenerateRandomKey() to create
// strong keys.
func NewCookieStore(keyPairs ...[]byte) *CookieStore {
	return &CookieStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
	}
}

// CookieStore stores sessions using secure cookies.
type CookieStore struct {
	Codecs  []securecookie.Codec
	Options *Options // default configuration
}

// Get returns a session for the given name after adding it to the registry.
//
// It returns a new session if the sessions doesn't exist. Access IsNew on
// the session to check if it is an existing session or a new one.
//
// It returns a new session and an error if the session exists but could
// not be decoded.
func (s *CookieStore) Get(r *http.Request, name string) (*Session, error) {
	return GetRegistry(r).Get(s, name)
}

// New returns a session for the given name without adding it to the registry.
//
// The difference between New() and Get() is that calling New() twice will
// decode the session data twice, while Get() registers and reuses the same
// decoded session after the first call.
func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		err = securecookie.DecodeMulti(name, c.Value, &session.Values,
			s.Codecs...)
		if err == nil {
			session.IsNew = false
		}
	}
	return session, err
}

// Save adds a single session to the response.
func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options))
	return nil
}

// FilesystemStore ------------------------------------------------------------

var fileMutex sync.RWMutex

// NewFilesystemStore returns a new FilesystemStore.
//
// The path argument is the directory where sessions will be saved. If empty
// it will use os.TempDir().
//
// See NewCookieStore() for a description of the other parameters.
func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore {
	if path == "" {
		path = os.TempDir()
	}
	if path[len(path)-1] != '/' {
		path += "/"
	}
	return &FilesystemStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		path: path,
	}
}

// FilesystemStore stores sessions in the filesystem.
//
// It also serves as a referece for custom stores.
//
// This store is still experimental and not well tested. Feedback is welcome.
type FilesystemStore struct {
	Codecs  []securecookie.Codec
	Options *Options // default configuration
	path    string
}

// Get returns a session for the given name after adding it to the registry.
//
// See CookieStore.Get().
func (s *FilesystemStore) Get(r *http.Request, name string) (*Session, error) {
	return GetRegistry(r).Get(s, name)
}

// New returns a session for the given name without adding it to the registry.
//
// See CookieStore.New().
func (s *FilesystemStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		session.ID = c.Value
		err = s.load(session)
		if err == nil {
			session.IsNew = false
		}
	}
	return session, err
}

// Save adds a single session to the response.
func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error {
	if session.ID == "" {
		// Because the ID is used in the filename, encode it to
		// use alphanumeric characters only.
		session.ID = strings.TrimRight(
			base32.StdEncoding.EncodeToString(
				securecookie.GenerateRandomKey(32)), "=")
	}
	if err := s.save(session); err != nil {
		return err
	}
	_, err := securecookie.EncodeMulti(session.Name(), session.ID,
		s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, NewCookie(session.Name(), session.ID, session.Options))
	return nil
}

// save writes encoded session.Values to a file.
func (s *FilesystemStore) save(session *Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		s.Codecs...)
	if err != nil {
		return err
	}
	filename := s.path + "session_" + session.ID
	fileMutex.Lock()
	defer fileMutex.Unlock()
	fp, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	if _, err = fp.Write([]byte(encoded)); err != nil {
		return err
	}
	fp.Close()
	return nil
}

// load reads a file and decodes its content into session.Values.
func (s *FilesystemStore) load(session *Session) error {
	filename := s.path + "session_" + session.ID
	fp, err := os.OpenFile(filename, os.O_RDONLY, 0400)
	if err != nil {
		return err
	}
	defer fp.Close()
	var fdata []byte
	buf := make([]byte, 128)
	for {
		var n int
		n, err = fp.Read(buf[0:])
		fdata = append(fdata, buf[0:n]...)
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
	}
	if err = securecookie.DecodeMulti(session.Name(), string(fdata),
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}

// MemcacheStore ------------------------------------------------------------

// MemcacheStore returns a new MemcachedStore.

func NewMemcacheStore(server string, keyPairs ...[]byte) *MemcacheStore {
	return &MemcacheStore{
		Codecs: securecookie.CodecsFromPairs(keyPairs...),
		Options: &Options{
			Path:   "/",
			MaxAge: 86400 * 30,
		},
		Memcache: memcache.New(server),
	}
}

// FilesystemStore stores sessions in the filesystem.
//
// It also serves as a referece for custom stores.
//
// This store is still experimental and not well tested. Feedback is welcome.
type MemcacheStore struct {
	Codecs   []securecookie.Codec
	Options  *Options // default configuration
	Memcache *memcache.Client
}

// Get returns a session for the given name after adding it to the registry.
//
// See CookieStore.Get().
func (s *MemcacheStore) Get(r *http.Request, name string) (*Session, error) {
	return GetRegistry(r).Get(s, name)
}

// New returns a session for the given name without adding it to the registry.
//
// See CookieStore.New().
func (s *MemcacheStore) New(r *http.Request, name string) (*Session, error) {
	session := NewSession(s, name)
	opts := *s.Options
	session.Options = &opts
	session.IsNew = true
	var err error
	if c, errCookie := r.Cookie(name); errCookie == nil {
		session.ID = c.Value
		err = s.load(session)
		if err == nil {
			session.IsNew = false
		}
	}
	return session, err
}

// Save adds a single session to the response.
func (s *MemcacheStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error {
	if session.ID == "" {
		// Because the ID is used in the filename, encode it to
		// use alphanumeric characters only.
		session.ID = strings.TrimRight(
			base32.StdEncoding.EncodeToString(
				securecookie.GenerateRandomKey(32)), "=")
	}
	if err := s.save(session); err != nil {
		return err
	}
	_, err := securecookie.EncodeMulti(session.Name(), session.ID,
		s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, NewCookie(session.Name(), session.ID, session.Options))
	return nil
}

// save set encoded session.Values to a memcache
func (s *MemcacheStore) save(session *Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		s.Codecs...)
	if err != nil {
		return err
	}
	key := "session_" + session.ID
	item := &memcache.Item{
		Key:        key,
		Value:      []byte(encoded),
		Expiration: int32(session.Options.MaxAge)+int32(time.Now().Unix()),
	}
	err = s.Memcache.Set(item)
	if err != nil {
		return err
	}
	return nil
}

// load get from a memcache and decodes its content into session.Values.
func (s *MemcacheStore) load(session *Session) error {
	key := "session_" + session.ID
	item, err := s.Memcache.Get(key)
	var value string
	if item == nil {
		return nil
	} else if err != nil {
		return err
	} else {
		value = string(item.Value)
	}
	if err = securecookie.DecodeMulti(session.Name(), value,
		&session.Values, s.Codecs...); err != nil {
		return err
	}
	return nil
}


text:
package edu.sampleu.travel.options;

import edu.sampleu.demo.kitchensink.UifComponentsTestForm;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.uif.control.UifKeyValuesFinderBase;
import org.kuali.rice.krad.uif.view.ViewModel;

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

/**
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class FoodKeyValuesFinder extends UifKeyValuesFinderBase {

    @Override
    public List<KeyValue> getKeyValues(ViewModel model) {
        UifComponentsTestForm testForm = (UifComponentsTestForm) model;

        List<KeyValue> options = new ArrayList<KeyValue>();

        if (testForm.getField88().equals("Fruits")) {
            options.add(new ConcreteKeyValue("Apples", "Apples"));
            options.add(new ConcreteKeyValue("Bananas", "Bananas"));
            options.add(new ConcreteKeyValue("Cherries", "Cherries"));
            options.add(new ConcreteKeyValue("Oranges", "Oranges"));
            options.add(new ConcreteKeyValue("Pears", "Pears"));
        } else if (testForm.getField88().equals("Vegetables")) {
            options.add(new ConcreteKeyValue("Beans", "Beans"));
            options.add(new ConcreteKeyValue("Broccoli", "Broccoli"));
            options.add(new ConcreteKeyValue("Cabbage", "Cabbage"));
            options.add(new ConcreteKeyValue("Carrots", "Carrots"));
            options.add(new ConcreteKeyValue("Celery", "Celery"));
            options.add(new ConcreteKeyValue("Corn", "Corn"));
            options.add(new ConcreteKeyValue("Peas", "Peas"));
        }

        return options;
    }

}


text:
package com.alibaba.druid.pool.vendor;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.ExceptionSorter;

public class InformixExceptionSorter implements ExceptionSorter, Serializable {

    private static final long serialVersionUID = -5175884111768095263L;

    public boolean isExceptionFatal(SQLException e) {
        switch (e.getErrorCode()) {
            case -710: // Table has been dropped, altered or renamed JBAS-3120
            case -79716: // System or internal error
            case -79730: // Connection noit established
            case -79734: // INFORMIXSERVER has to be specified
            case -79735: // Can't instantiate protocol
            case -79736: // No connection/statement established yet
            case -79756: // Invalid connection URL
            case -79757: // Invalid subprotocol
            case -79758: // Invalid IP address
            case -79759: // Invalid port nnumber
            case -79760: // Invalid database name
            case -79788: // User name must be specified
            case -79811: // Connection without user/password not supported
            case -79812: // User/password does not match with datasource
            case -79836: // Proxy error: no database connection
            case -79837: // Proxy error: IO error
            case -79879: // Unexpected exception

                return true;
        }

        return false;
    }

    public void configFromProperties(Properties properties) {

    }

}


text:
RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'
end

require 'yaml'

module Credentials
  def self.fetch
    @credentials ||= YAML.load_file(File.expand_path('../credentials.yml', __FILE__))
  end
end

def read_xml_fixture(name)
  path = File.expand_path("../fixtures/#{name}.xml", __FILE__)
  File.read(path)
end


text:
define(['knockout', 'text!./CustomEraStrategyTemplate.html', '../options'], function (ko, template, options) {

	function CustomEraStrategyViewModel(params) {
		var self = this;
		self.options = options;

		self.strategy = ko.pureComputed(function () {
			return ko.utils.unwrapObservable(params.strategy).CustomEra;
		});

		self.conceptSets = params.conceptSets
	}

	// return compoonent definition
	return {
		viewModel: CustomEraStrategyViewModel,
		template: template
	};
});