text:
rclip is a tool copy text from remote host to local system cliboard;

it is specifically designed for copy seletected text in tmux copy-mode on a remote host to local system cliboard over network; which is a big pain point of using tmux;

## how does it work?
first run rclip as reflector role on remote host, which is processing listening on two ports over TLS:
* rcv_port: default 8891
* send_port: default 8890

the ports could be changed by commandline parameters

any text received on rcv_port will be forwarded to send_port

run rclip as sender role on local system, it connects to the send_port of reflector, and copy the received text to local system clipboard

configure tmux so that the tmux copy-pipe command invoke rclip as receiver role, which connects to rcv_port of reflector, and send selected text to reflector;

## why this 3 party design?
this is to get around firewall between remote host and local system; remote host is typicall a server, while local system is typically a client device like a laptop;

if you use VPN to remote access the server, there typically will be a firewall between server and local system, and that firewall will likely to block any connection initiated by server to the local system; so a simple client and server design won't work

rclip also send keepalive message every 40 seconds between reflector and sender to avoid firewall idle timeout the TCP connection;

## security

rclip use TLS to secure communication between reflector, sender and receiver; it also uses client authentication with its own root CA to prevent spoof;

by default, rclip sender and receiver will check SAN(Subject Alternative Name) of reflector's certificate, to see the reflector's IP or FQDN match its certificate SAN; however this check could be skipped by using a hard coded "1.1.1.1" in SAN of reflector certificate when parameter "-loose" is specified; this is to avoid hassle to create a different certificate for each remote host; this of course decrease the overall security, but personally think it is acceptable trade-off given user typically specify the reflector address on local system directly;

## build
rclip is coded with golang ver1.9, just use "go build" in the source directory to build the binary;
golang pkg required:
* github.com/atotto/clipboard

## install
since rclip use TLS and its own CA, so following key and certificates are needed to generated before installation:
* root CA cert/key
* reflector key/cert
* sender key/cert
* receiver key/cert

notes:
  * there are many opensource tools could generate key and certs like [openssl](https://www.openssl.org/) or [XCA](http://xca.sourceforge.net/)
  * If you want to skip SAN check, make sure there is SubjectAltName extension with "1.1.1.1" as ip addresss in the certificate of reflector

rclip expect above key/certs located in following directory:
* Windows: [windows_user_dir]\appdata\AppData\Roaming\rclip
* Linux/OSX: $HOME/.rclip/

on remote host where tmux is running, following cert/keys with expected file name are needed:
* root CA cert: ca_cert
* reflector cert/key: refl_cert/refl_key
* receiver cert/key: rcv_cert/rcv_key

on local system, following cert/keys are needed:
* root CA cert: ca_cert
* sender key/cert: sender_cert/sender_key

all cert/key files's permission should be set that only owner could read

add following line in your .tmux.conf on remote host:
```
bind-key -T copy-mode-vi _your_key_of_choice_ send-keys -X copy-pipe "_rclip_install_path_/rclip"
```
this is an example:
```
bind-key -T copy-mode-vi y send-keys -X copy-pipe "/usr/local/bin/rclip"
```
note: if you want to skip SAN check, add "-loose"; e.g.
```
bind-key -T copy-mode-vi _your_key_of_choice_ send-keys -X copy-pipe "_rclip_install_path_/rclip -loose"
```
note: invoke rclip without any parameter, it will run as receiver, and connects to reflector on the same host, using default recv_port

## usage
on remote host:
* start reflector process:
```
rclip -role refl
```

on local system:
* start sender process:
```
rclip -role sender -refl_ip <remote_host_ip>
```
note: if you want to skip SAN check, add "-loose"; e.g.
```
rclip -role sender -refl_ip <remote_host_ip> -loose
```

To make a remote copy: go into tmux copy mode on remote host, select some text, press the specified key, voila, the text are copied into local clipboard, secury & easy;

## CLI Parameter
```
remote clipboard, version 1.1
flag provided but not defined: -?
Usage of rclip:
  -loose
        use hard coded address for reflector certificate SAN check
  -rcv_port uint
        specify the port for receiver on reflector (default 8891)
  -refl_ip string
        reflector listening ip address
  -role string
        specify the role, rcv/refl/sender (default "rcv")
  -send_port uint
        specify the port for sender on reflector (default 8890)
```

## license
MIT; https://opensource.org/licenses/MIT


text:
/**
 * This package contains classes for interact with ZooKeeper.
 */
package co.cask.cdap.common.zookeeper;

redpajama_set_name: RedPajamaGithub


text:
#include "modules/rtp_rtcp/source/rtcp_packet/app.h"

#include "modules/rtp_rtcp/source/byte_io.h"
#include "modules/rtp_rtcp/source/rtcp_packet/common_header.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"

namespace webrtc {
namespace rtcp {
constexpr uint8_t App::kPacketType;
constexpr size_t App::kMaxDataSize;
// Application-Defined packet (APP) (RFC 3550).
//
//     0                   1                   2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |V=2|P| subtype |   PT=APP=204  |             length            |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  0 |                           SSRC/CSRC                           |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  4 |                          name (ASCII)                         |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  8 |                   application-dependent data                ...
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

App::App() : sub_type_(0), ssrc_(0), name_(0) {}

App::~App() = default;

bool App::Parse(const CommonHeader& packet) {
  RTC_DCHECK_EQ(packet.type(), kPacketType);
  if (packet.payload_size_bytes() < kAppBaseLength) {
    RTC_LOG(LS_WARNING) << "Packet is too small to be a valid APP packet";
    return false;
  }
  if (packet.payload_size_bytes() % 4 != 0) {
    RTC_LOG(LS_WARNING)
        << "Packet payload must be 32 bits aligned to make a valid APP packet";
    return false;
  }
  sub_type_ = packet.fmt();
  ssrc_ = ByteReader<uint32_t>::ReadBigEndian(&packet.payload()[0]);
  name_ = ByteReader<uint32_t>::ReadBigEndian(&packet.payload()[4]);
  data_.SetData(packet.payload() + kAppBaseLength,
                packet.payload_size_bytes() - kAppBaseLength);
  return true;
}

void App::SetSubType(uint8_t subtype) {
  RTC_DCHECK_LE(subtype, 0x1f);
  sub_type_ = subtype;
}

void App::SetData(const uint8_t* data, size_t data_length) {
  RTC_DCHECK(data);
  RTC_DCHECK_EQ(data_length % 4, 0) << "Data must be 32 bits aligned.";
  RTC_DCHECK_LE(data_length, kMaxDataSize) << "App data size " << data_length
                                           << " exceed maximum of "
                                           << kMaxDataSize << " bytes.";
  data_.SetData(data, data_length);
}

size_t App::BlockLength() const {
  return kHeaderLength + kAppBaseLength + data_.size();
}

bool App::Create(uint8_t* packet,
                 size_t* index,
                 size_t max_length,
                 PacketReadyCallback callback) const {
  while (*index + BlockLength() > max_length) {
    if (!OnBufferFull(packet, index, callback))
      return false;
  }
  const size_t index_end = *index + BlockLength();
  CreateHeader(sub_type_, kPacketType, HeaderLength(), packet, index);

  ByteWriter<uint32_t>::WriteBigEndian(&packet[*index + 0], ssrc_);
  ByteWriter<uint32_t>::WriteBigEndian(&packet[*index + 4], name_);
  memcpy(&packet[*index + 8], data_.data(), data_.size());
  *index += (8 + data_.size());
  RTC_DCHECK_EQ(index_end, *index);
  return true;
}

}  // namespace rtcp
}  // namespace webrtc


text:
class Fruit < ActiveRecord::Base
  has_paper_trail class_name: 'JsonVersion' if ENV['DB'] == 'postgres' || JsonVersion.table_exists?
end


text:
package org.eclipse.gemini.blueprint.service.exporter;

import org.eclipse.gemini.blueprint.service.exporter.support.BeanNameServicePropertiesResolver;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * @author Adrian Colyer
 * @author Hal Hildebrand
 */
public class BeanNameServicePropertiesResolverTest {

    @Test
    public void testAfterPropertiesSetNoBundleContext() throws Exception {
        try {
            new BeanNameServicePropertiesResolver().afterPropertiesSet();
            fail("Should have thrown IllegalArgumentException");
        } catch (IllegalArgumentException ex) {
            // expected
        }
    }

    @Test
    public void testGetServiceProperties() {
        BundleContext mockContext = createMock(BundleContext.class);
        Bundle mockBundle = createMock(Bundle.class);

        expect(mockContext.getBundle()).andReturn(mockBundle);
        expect(mockBundle.getSymbolicName()).andReturn("symbolic-name");
        expect(mockContext.getBundle()).andReturn(mockBundle);

        Dictionary<String, String> props = new Hashtable<String, String>();
        props.put(Constants.BUNDLE_VERSION, "1.0.0");

        expect(mockBundle.getHeaders()).andReturn(props);

        replay(mockBundle, mockContext);

        BeanNameServicePropertiesResolver resolver = new BeanNameServicePropertiesResolver();
        resolver.setBundleContext(mockContext);
        Map ret = resolver.getServiceProperties("myBean");

        verify(mockBundle, mockContext);

        assertEquals("5 properties", 5, ret.size());
        assertEquals("symbolic-name", ret.get("Bundle-SymbolicName"));
        assertEquals("1.0.0", ret.get("Bundle-Version"));
        assertEquals("myBean", ret.get("org.eclipse.gemini.blueprint.bean.name"));
        assertEquals("myBean", ret.get("org.springframework.osgi.bean.name"));
        assertEquals("myBean", ret.get("osgi.service.blueprint.compname"));
    }
}


text:
const UserException = require('../../src/oneview-sdk/user-exception');

const chai = require('chai');

chai.should();

describe('UserException', () => {
  let userException;

  it('toMessage with message and resolution', () => {
    userException = new UserException('This is the error.', 'This is the resolution.');
    userException.toMessage().should.equal('This is the error.\nThis is the resolution.');
  });

  it('toMessage with message', () => {
    userException = new UserException('This is the error.');
    userException.toMessage().should.equal('This is the error.');
  });
});


text:
@interface SUSearchBarView()
/// icon
@property (nonatomic, readwrite, weak)   UIImageView *imageView;
/// tipsLabel
@property (nonatomic, readwrite, weak)   UILabel *tipsLabel;
@end

@implementation SUSearchBarView

+ (instancetype)searchBarView
{
    return [[self alloc] init];
}

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        self.backgroundColor = MHColorFromHexString(@"#e8eaf1");
        self.layer.cornerRadius = 6;
        self.clipsToBounds = YES;

        /// search icon
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search_icon"]];
        [imageView sizeToFit];
        self.imageView = imageView;
        [self addSubview:imageView];

        /// tipsLabel
        UILabel *tipsLabel = [[UILabel alloc] init];
        tipsLabel.font = MHRegularFont_14;
        tipsLabel.textColor = MHColorFromHexString(@"#747a8e");
        tipsLabel.textAlignment = NSTextAlignmentCenter;
        tipsLabel.text = self.tips;
        [self.tipsLabel sizeToFit];
        tipsLabel.textAlignment = NSTextAlignmentCenter;
        self.tipsLabel = tipsLabel;
        [self addSubview:tipsLabel];

        /// 添加手势
        @weakify(self);
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
            @strongify(self);
            !self.searchBarViewClicked?:self.searchBarViewClicked();
        }]];

        /// 设置数据
        self.tips = SUSearchTipsText;
    }
    return self;
}

- (void)setTips:(NSString *)tips {
    _tips = tips;
    self.tipsLabel.text = tips;
    [self.tipsLabel setNeedsDisplay];
    [self.tipsLabel sizeToFit];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat imageViewInset = 10;
    self.tipsLabel.mh_centerX = ceil(self.mh_width * 0.5) + imageViewInset;
    self.tipsLabel.mh_y = floor((self.mh_height - self.tipsLabel.mh_height)/2);

    self.imageView.mh_centerY = self.tipsLabel.mh_centerY;
    self.imageView.mh_x = self.tipsLabel.mh_x - imageViewInset - self.imageView.mh_width;
}

@end


text:
if [ -e ~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh ]; then
  export SSH_AUTH_SOCK=~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
else
  if [[ $(ssh-add -l | grep -v "no identities" | wc -l) -lt 1 ]]; then
    ssh-add -K
  fi
fi


text:
namespace geo {
	class Rectangle : public Shape
	{
	private:
		float32 m_width;
		float32 m_height;

		float32 m_halfWidth;
		float32 m_halfHeight;

		Point m_topLeft;
		Point m_topRight;
		Point m_bottomLeft;
		Point m_bottomRight;
	public:
		Rectangle();
		Rectangle(float32 width, float32 height);
		Rectangle(float32 x, float32 y, float32 width, float32 height);
		~Rectangle();

		float32 getWidth() const { return m_width; }
		float32 getHeight() const { return m_height; }
		Point getTopLeft() const { return m_topLeft; }
		Point getTopRight() const { return m_topRight; }
		Point getBottomLeft() const { return m_bottomLeft; }
		Point getBottomRight() const { return m_bottomRight; }
		float32 getHalfWidth() const { return m_halfWidth; }
		float32 getHalfHeight() const { return m_halfHeight; }

		void setWidth(float32 width);
		void setHeight(float32 height);
		virtual void setX(float32 x) override;
		virtual void setY(float32 y) override;

		bool intersects(const Rectangle& rect) const;
	};
}


text:
require 'json'
require_relative '../../../models/synchronization/member'
require_relative '../../../models/synchronization/collection'
require_relative '../../../../services/datasources/lib/datasources'
require_relative '../../../../services/platform-limits/platform_limits'

class Api::Json::SynchronizationsController < Api::ApplicationController
  include CartoDB

  ssl_required :create, :update, :destroy, :sync, :sync_now

  # Upon creation, no rate limit checks
  def create
    @stats_aggregator.timing('synchronizations.create') do

      begin
        external_source = nil

        member_attributes = setup_member_attributes
        member = Synchronization::Member.new(member_attributes)
        member = @stats_aggregator.timing('member.save') do
          member.store
        end

        options = setup_data_import_options(member_attributes, member.id)
        data_import = @stats_aggregator.timing('save') do
          DataImport.create(options)
        end

        if external_source.present?
          @stats_aggregator.timing('external-data-import.save') do
            ExternalDataImport.new(data_import.id, external_source.id, member.id).save
          end
        end

        ::Resque.enqueue(::Resque::ImporterJobs, job_id: data_import.id)

        response = {
          data_import: {
            endpoint:       '/api/v1/imports',
            item_queue_id:  data_import.id
          }
        }.merge(member.to_hash)

        render_jsonp(response)
      rescue CartoDB::InvalidMember => exception
        render_jsonp({ errors: member.full_errors }, 400)
        puts exception.to_s
        puts exception.backtrace
      rescue CartoDB::InvalidInterval => exception
        render_jsonp({ errors: "#{exception.detail['message']}: #{exception.detail['hint']}" }, 400)
      end

    end
  end

  def sync(from_sync_now=false)
    @stats_aggregator.timing('synchronizations.sync') do

      begin
        enqueued = false
        member = Synchronization::Member.new(id: params[:id]).fetch
        return head(401) unless member.authorize?(current_user)

        # @see /services/synchronizer/lib/synchronizer/collection.rb -> enqueue_rate_limited()
        if ( member.should_auto_sync? || (from_sync_now && member.can_manually_sync?) )
          platform_limit = CartoDB::PlatformLimits::Importer::UserConcurrentSyncsAmount.new({
            user: current_user, redis: { db: $users_metadata }
          })
          if platform_limit.is_within_limit?
            @stats_aggregator.timing('enqueue') do
              member.enqueue
            end
            enqueued = true
            platform_limit.increment!
          end
        end

        render_jsonp( { enqueued: enqueued, synchronization_id: member.id})
      rescue => exception
        CartoDB.notify_exception(exception)
        head(404)
      end

    end
  end

  def sync_now
    sync(true)
  end

  def update
    @stats_aggregator.timing('synchronizations.update') do

      begin
        member = Synchronization::Member.new(id: params.fetch('id')).fetch
        return head(401) unless member.authorize?(current_user)

        member.attributes = payload
        member = @stats_aggregator.timing('save') do
          member.store.fetch
        end
        render_jsonp(member)
      rescue KeyError
        head(404)
      rescue CartoDB::InvalidMember
        render_jsonp({ errors: member.full_errors }, 400)
      end

    end
  end

  def destroy
    @stats_aggregator.timing('synchronizations.destroy') do

      begin
        member = Synchronization::Member.new(id: params.fetch('id')).fetch
        return(head 401) unless member.authorize?(current_user)

        @stats_aggregator.timing('delete') do
          member.delete
        end

        return head 204
      rescue KeyError
        head(404)
      end

    end
  end

  private

  def setup_member_attributes
    member_attributes = payload.merge(
            name:                   params[:table_name],
            user_id:                current_user.id,
            state:                  Synchronization::Member::STATE_CREATED,
            # Keep in sync with http://docs.cartodb.com/cartodb-platform/import-api.html#params-4
            type_guessing:          !["false", false].include?(params[:type_guessing]),
            quoted_fields_guessing: !["false", false].include?(params[:quoted_fields_guessing]),
            content_guessing:       ["true", true].include?(params[:content_guessing])
        )

    if from_sync_file_provider?
      member_attributes = member_attributes.merge({
              service_name: params[:service_name],
              service_item_id: params[:service_item_id]
          })
    end

    if params[:remote_visualization_id].present?
      member_attributes[:interval] = Carto::ExternalSource::REFRESH_INTERVAL
      external_source = get_external_source(params[:remote_visualization_id])
      member_attributes.merge!( {
        url: external_source.import_url.presence,
        service_item_id: external_source.import_url.presence
        } )
    end

    member_attributes
  end

  def setup_data_import_options(member_attributes, member_id)
    if from_sync_file_provider?
      service_name = params[:service_name]
      service_item_id = params[:service_item_id]
    else
      service_name = CartoDB::Datasources::Url::PublicUrl::DATASOURCE_NAME
      service_item_id = params[:url].presence
    end

    options = {
      user_id:                current_user.id,
      table_name:             params[:table_name].presence,
      service_name:           service_name,
      service_item_id:        service_item_id,
      type_guessing:          member_attributes[:type_guessing],
      quoted_fields_guessing: member_attributes[:quoted_fields_guessing],
      content_guessing:       member_attributes[:content_guessing],
      create_visualization:   ["true", true].include?(params[:create_vis])
    }

    if params[:remote_visualization_id].present?
      external_source = get_external_source(params[:remote_visualization_id])
      options.merge!( { data_source: external_source.import_url.presence } )
    else
      options.merge!({ data_source: params[:url] })
    end

    options.merge!({ synchronization_id: member_id })

    options
  end

  def from_sync_file_provider?
    params.include?(:service_name) && params.include?(:service_item_id)
  end

  def payload
    request.body.rewind
    ::JSON.parse(request.body.read.to_s || String.new)
  end

  def get_external_source(remote_visualization_id)
    external_source = CartoDB::Visualization::ExternalSource.where(visualization_id: remote_visualization_id).first
    unless remote_visualization_id.present? && external_source.importable_by(current_user)
      raise CartoDB::Datasources::AuthError.new('Illegal external load')
    end
    external_source
  end
end


text:
* Bug fixes
  * Ignore header name in pattern match (#21)

## v0.2.1

* Bug fixes
  * Make header lookup case-insensitive (#20)

## v0.2.0

* Bug fixes
  * Remove compilation warnings

* Other
  * Relax dependencies
  * Format code

N.B. If using older versions of HTTPoison you may get compilation warnings.


text:
#include "Layer.hpp"
#include "ClipperUtils.hpp"
#include "Print.hpp"
#include "Surface.hpp"

namespace Slic3r {

LayerRegion::LayerRegion(Layer *layer, PrintRegion *region)
:   _layer(layer),
    _region(region)
{
}

LayerRegion::~LayerRegion()
{
}

Layer*
LayerRegion::layer()
{
    return this->_layer;
}

PrintRegion*
LayerRegion::region()
{
    return this->_region;
}

Flow
LayerRegion::flow(FlowRole role, bool bridge, double width) const
{
    return this->_region->flow(
        role,
        this->_layer->height,
        bridge,
        this->_layer->id() == 0,
        width,
        *this->_layer->object()
    );
}

void
LayerRegion::merge_slices()
{
    ExPolygons expp;
    // without safety offset, artifacts are generated (GH #2494)
    union_(this->slices, &expp, true);
    this->slices.surfaces.clear();
    this->slices.surfaces.reserve(expp.size());

    for (ExPolygons::const_iterator expoly = expp.begin(); expoly != expp.end(); ++expoly)
        this->slices.surfaces.push_back(Surface(stInternal, *expoly));
}

void
LayerRegion::prepare_fill_surfaces()
{
    /*  Note: in order to make the psPrepareInfill step idempotent, we should never
        alter fill_surfaces boundaries on which our idempotency relies since that's
        the only meaningful information returned by psPerimeters. */

    // if no solid layers are requested, turn top/bottom surfaces to internal
    if (this->region()->config.top_solid_layers == 0) {
        for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
            if (surface->surface_type == stTop) {
                if (this->layer()->object()->config.infill_only_where_needed) {
                    surface->surface_type = stInternalVoid;
                } else {
                    surface->surface_type = stInternal;
                }
            }
        }
    }
    if (this->region()->config.bottom_solid_layers == 0) {
        for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
            if (surface->surface_type == stBottom || surface->surface_type == stBottomBridge)
                surface->surface_type = stInternal;
        }
    }

    // turn too small internal regions into solid regions according to the user setting
    if (this->region()->config.fill_density.value > 0) {
        // scaling an area requires two calls!
        double min_area = scale_(scale_(this->region()->config.solid_infill_below_area.value));
        for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
            if (surface->surface_type == stInternal && surface->area() <= min_area)
                surface->surface_type = stInternalSolid;
        }
    }
}

#ifdef SLIC3RXS
REGISTER_CLASS(LayerRegion, "Layer::Region");
#endif

}


text:
package cmd

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
	"testing"

	"path/filepath"

	"github.com/kylelemons/godebug/diff"
)

var Fixtures = os.ExpandEnv("$GOPATH/src/github.com/kedgeproject/kedge/tests/cmd/fixtures/")
var ProjectPath = "$GOPATH/src/github.com/kedgeproject/kedge/"
var BinaryLocation = os.ExpandEnv(ProjectPath + "kedge")
var imagename = "testrun"
var context = "kedge-build/"

func TestKedgeGenerate(t *testing.T) {
	testCases := []struct {
		name        string
		path        string
		input       string
		wantSuccess bool
		error       string
	}{
		{
			name:        "multiple configmaps given and name not specified",
			path:        "multi-configmapname/app.yaml",
			wantSuccess: false,
			error:       "unable to perform controller operations: unable to fix data: unable to fix configMaps: please specify name for app.configMaps[1]",
		},
		{
			name:        "generating deploymentconfig",
			path:        "controllers/input",
			input:       Fixtures + "controllers/os.yaml",
			wantSuccess: true,
		},
		{
			name:        "multiple containers given and name not specified for 2nd contaniner",
			path:        "multi-containername/nginx.yaml",
			wantSuccess: false,
			error:       "unable to perform controller operations: unable to fix data: unable to fix deployments: unable to fix containers: please specify name for app.containers[1]",
		},
		{
			name:  "multiple volume claims with same name",
			path:  "multi-pvc-same-name/app.yaml",
			error: `unable to perform controller operations: unable to validate data: error validating volume claims: duplicate entry of volume claim "foo"`,
		},
	}

	for _, tt := range testCases {
		t.Run(tt.name, func(t *testing.T) {
			command := []string{"generate", "-f=" + Fixtures + tt.path}
			stdout, err := runCmd(t, command)
			if err != nil && !tt.wantSuccess {

				if stdout != tt.error {
					t.Fatalf("wanted error: %q\nbut got error: %q %v", tt.error, stdout, err)
				} else {
					t.Logf("failed with error: %q", stdout)
					return
				}
			} else if err != nil && tt.wantSuccess {
				t.Fatalf("wanted success, but test failed with error: %s %v", stdout, err)
			} else if err == nil && !tt.wantSuccess {
				t.Fatalf("expected to fail but passed")
			}

			// Read the data from the input file
			data, err := ioutil.ReadFile(tt.input)
			if err != nil {
				t.Fatal(err)
			}

			if diff := diff.Diff(string(data), fmt.Sprintf("%s\n", stdout)); diff != "" {
				t.Fatalf("wanted: \n%s\n======================\ngot: \n%s"+
					"\n======================\ndiff: %s", string(data), stdout, diff)
			}

		})
	}
}

func runCmd(t *testing.T, args []string) (string, error) {
	cmd := exec.Command(BinaryLocation, args...)

	var stdout bytes.Buffer
	cmd.Stdout = &stdout

	t.Logf("Running: %s", strings.Join(cmd.Args, " "))
	err := cmd.Run()
	if err != nil {
		return strings.TrimSpace(stdout.String()), err
	}
	return strings.TrimSpace(stdout.String()), nil
}

func Test_builderror(t *testing.T) {

	cmdStr := fmt.Sprintf("%s build -i %s -c %s", BinaryLocation, imagename, context)
	output, err := exec.Command("/bin/sh", "-c", cmdStr).Output()
	if err != nil {
		fmt.Println("Error executing command", err)
	}
	cmdStr = fmt.Sprintf("docker images | grep %s | awk '{print $1}'", imagename)
	output, err = exec.Command("/bin/sh", "-c", cmdStr).Output()
	if err != nil {
		fmt.Println("Error executing command", err)
	}
	if strings.TrimSpace(string(output)) != imagename {
		t.Errorf("Test Failed")

	}
}

func Test_stdin(t *testing.T) {

	kjson := `{"name": "httpd","deployments": [{"containers": [{"image": "centos/httpd"}]}]}`
	cmdStr := fmt.Sprintf("%s generate -f - <<EOF\n%s\nEOF\n", BinaryLocation, kjson)
	subproc := exec.Command("/bin/sh", "-c", cmdStr)
	output, err := subproc.Output()
	if err != nil {
		fmt.Println("Error executing command", err)
	}
	g, err := ioutil.ReadFile(Fixtures + "stdin/output.yml")
	if !bytes.Equal(output, g) {
		t.Errorf("Test Failed")
	}
}

func Test_examples(t *testing.T) {
	fileList := []string{}
	for _, dir := range []string{"examples", "docs/examples"} {

		err := filepath.Walk(os.ExpandEnv(ProjectPath)+dir, func(path string, f os.FileInfo, err error) error {
			if filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml" {
				fileList = append(fileList, path)
			}
			return nil
		})
		if err != nil {
			t.Error(err)
		}
	}

	for _, file := range fileList {
		cmdStr := fmt.Sprintf("%s generate -f %s", BinaryLocation, file)
		output, err := exec.Command("/bin/sh", "-c", cmdStr).Output()
		if err != nil {
			t.Errorf("kedge generate failed for - %s\n Error is - %s", file, output)
		}
	}
}


text:
package edu.uci.ics.asterix.transaction.management.service.locking;

/**
 * @author pouria Interface for a hashTable, used in the internal data
 *         structures of lockManager
 * @param <K>
 *            Type of the objects, used as keys
 * @param <V>
 *            Type of the objects, used as values
 */
public interface ILockHashTable<K, V> {

    public void put(K key, V value);

    public V get(K key);

    public V remove(K key);

    public int getKeysetSize();

}


text:
Sigorilla's sudoku manager and solver on C++

# Contributing

If you have idea for improve this projects, I'll be glad to see you [issues](https://github.com/sigorilla/sudoku/issues/new) or [pull requests](https://github.com/sigorilla/sudoku/compare).


text:
#pragma once

#include "core/filesystem/types.h"
#include "core/memory/types.h"
#include "core/strings/string_id.h"
#include "core/types.h"
#include "resource/types.h"
#include "resource/types.h"

namespace crown
{
struct SoundType
{
	enum Enum
	{
		WAV,
		OGG
	};
};

struct SoundResource
{
	u32 version;
	u32 size;
	u32 sample_rate;
	u32 avg_bytes_ps;
	u32 channels;
	u16 block_size;
	u16 bits_ps;
	u32 sound_type;
};

namespace sound_resource_internal
{
	s32 compile(CompileOptions& opts);

} // namespace	sound_resource_internal

namespace sound_resource
{
	/// Returns the sound data.
	const char* data(const SoundResource* sr);

} // namespace sound_resource

} // namespace crown


text:
require 'electric_sheep/spawn'
require 'fileutils'
require 'table_print'
require 'openssl'

module ElectricSheep
  module Util
    class SshHostKeys
      class << self
        include Helpers::ShellSafe

        def refresh(config, logger, force)
          keys = config.hosts.all.map do |_, host|
            fetch_server_keys(shell_safe(host.hostname), host.ssh_port, logger)
          end.flatten
          update_known_hosts(known_hosts(config), keys, force, logger)
        end

        private

        def update_known_hosts(known_hosts, keys, force, logger)
          unless force
            print_table(keys)
            print "Replace the public keys in \"#{known_hosts}\"? [Y/n]:"
            return unless STDIN.gets == 'Y'
          end
          remove_keys(known_hosts, keys.map { |key| key[:host] }.uniq, logger)
          append_keys(known_hosts, keys)
        end

        def known_hosts(config)
          File.expand_path(config.ssh_options.known_hosts)
        end

        def remove_keys(known_hosts, hosts, logger)
          return unless File.exist?(known_hosts)
          hosts.each do |hostname|
            cmd = "ssh-keygen -R -f #{known_hosts} -R #{hostname}"
            result = Spawn.exec(cmd, logger)
            next if (result[:exit_status]).to_i.zero?
            logger.warn "Unable to remove keys from \"#{known_hosts}\" " \
                        "for server #{hostname}"
            logger.warn result[:err]
          end
        end

        def append_keys(known_hosts, keys)
          unless File.exist?(known_hosts)
            FileUtils.touch known_hosts
            FileUtils.chmod 0o600, known_hosts
          end
          File.open(known_hosts, 'ab') do |f|
            keys.each do |key|
              f.puts known_host_entry(key)
            end
          end
        end

        def known_host_entry(key)
          sha1 = OpenSSL::Digest.new('sha1')
          # 160 bits random-value, base-64 encoded
          salt = SecureRandom.random_bytes(20)
          hash = OpenSSL::HMAC.digest(sha1, salt, key[:host])
          salt_and_hash = ['|1', Base64.encode64(salt), Base64.encode64(hash)]
                          .map(&:chomp).join('|')
          "#{salt_and_hash} #{key[:keytype]} #{key[:key]}"
        end

        def print_table(keys)
          table_opts = [
            :host,
            :keytype,
            :size,
            fingerprint: { display_name: 'Fingerprint', width: 50 }
          ]
          printer = TablePrint::Printer.new(keys, table_opts)
          print 'The following public keys have been retrieved:'
          print printer.table_print
        end

        def print(str)
          STDOUT.puts str
        end

        def fetch_server_keys(host, port, logger)
          result = Spawn.exec("ssh-keyscan -p #{port} #{host}", logger)
          unless (result[:exit_status]).to_i.zero?
            logger.error result[:err]
            raise "Unable to fetch key for server #{host}"
          end
          parse_keys(result[:out])
        end

        def parse_keys(scan)
          scan.chomp.split("\n").map do |line|
            parts = line.split(' ')
            server_key = [:host, :keytype, :key]
                         .each_with_object({}) do |key, hsh|
              hsh[key] = parts.shift
            end
            fingerprint(server_key)
          end
        end

        def fingerprint(server_key)
          keyfile(server_key) do |file|
            parts = `ssh-keygen -lf #{file.path}`.chomp.split(' ')
            [:size, :fingerprint].each { |key| server_key[key] = parts.shift }
          end
          server_key
        end

        def keyfile(server_key, &_)
          Tempfile.new('ssh-keyfile').tap do |file|
            file.write "#{server_key[:keytype]} #{server_key[:key]}"
            file.close
            yield file
          end
        end
      end
    end
  end
end


text:
/*
*/

#include <math.h>
#include <iostream>
#include "CGLProgram.h"

//-------------------------------------------------------------
// CGLProgram::CGLProgram()	constructor
//-------------------------------------------------------------
CGLProgram::CGLProgram(){
    program=0;
    fshader=new CGLFragmentShader();
    vshader=new CGLVertexShader();
}

//-------------------------------------------------------------
// CGLProgram::~CGLProgram()	destructor
//-------------------------------------------------------------
CGLProgram::~CGLProgram(){
    DELETE(fshader);
    DELETE(vshader);
}

//-------------------------------------------------------------
// CGLProgram::showGLInfo()	show openGL properties
//-------------------------------------------------------------
    void CGLProgram::showGLInfo(){
    int intbuffer[1];
    std::cout << "Shader program type: " << name()<< std::endl;
    glGetIntegerv( GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB,intbuffer);
    std::cout << " Max Vertex Uniform Componants: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB,intbuffer);
    std::cout << " Max Fragment Uniform Componants: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_VERTEX_ATTRIBS_ARB,intbuffer);
    std::cout << " Max Vertex Attributes: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB,intbuffer);
    std::cout << " Max Fragment Texture Units: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB,intbuffer);
    std::cout << " Max Vertex Texture Units: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_VARYING_FLOATS_ARB,intbuffer);
    std::cout << " Max Varying Floats: " << intbuffer[0] << std::endl;
    glGetIntegerv( GL_MAX_TEXTURE_COORDS_ARB,intbuffer);
    std::cout << " Max Texture Coords: " << intbuffer[0] << std::endl;
    vshader->showGLInfo();
    fshader->showGLInfo();
}


text:
<?php
	session_start();
	include_once ("imports.php");
	include_once ("header.php");
	include_once ("nav.php");
	include_once ("footer.php");
	getImportsUp();
?>

			<?php
				getHeader();
				getNav();
			?>

					<?php
						if(isset($_SESSION['idUsuario'])){
					?>

¡Bienvenido <? echo $_SESSION['nombreUsuario'] ?>!

Se ha detectado una sesión activa.

									Para iniciar sesión con otro usuario porfavor cierre ésta sesión, de lo contrario, no podrá tener 2 sesiones activas.

									Puede dirigirse a administrar el sitio web de Ingnovarq S.A.S.

										Cerrar Sesión
										Administrar Sitio WEB

					<?php
						}
						else{
							?>

Inicio de sesión - ¡Bienvenido Administrador!

										<form class="form-horizontal" id="form-login-ajax" method="post">

										        Usuario:

										        	<input type="name" id="idUsuario" name="idUsuario" class="form-control" placeholder="Usuario">

										        Contraseña:

										            <input type="password" id="password" name="password" class="form-control" placeholder="Contraseña">

										         	<input type="hidden" name="ajax">
										            <button type="submit" id="btn-login-ajax" class="btn btn-success">Iniciar Sesión</button>

										</form>

						<?php
						}
						?>

	<?php
		getFooter();
		getImportsDown();
	?>


text:
		{php $i = 1;}
		{loop $_W['quickmenu']['menus'] $nav}

			{if $i==3}

			{else}

					{if !empty($nav['icon'])}

					{else}

					{/if}

				{$nav['name']}

			{/if}

		{php if($i>=5) break;}
		{php $i++;}
		{/loop}


text:
<?php

/**
 * Attach a filter to a stream
 *
 * @phpstub
 *
 * @param resource $stream
 * @param string $filtername
 * @param int $read_write
 * @param mixed $params
 *
 * @return resource Returns a resource which can be used to refer to this filter
 *                  instance during a call to .
 */
function stream_filter_prepend($stream, $filtername, $read_write = NULL, $params = NULL)
{
}


text:
require 'google/protobuf'

require 'google/api/annotations_pb'
require 'google/firestore/v1beta1/common_pb'
require 'google/firestore/v1beta1/document_pb'
require 'google/protobuf/timestamp_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
  add_message "google.firestore.v1beta1.Write" do
    optional :update_mask, :message, 3, "google.firestore.v1beta1.DocumentMask"
    optional :current_document, :message, 4, "google.firestore.v1beta1.Precondition"
    oneof :operation do
      optional :update, :message, 1, "google.firestore.v1beta1.Document"
      optional :delete, :string, 2
      optional :transform, :message, 6, "google.firestore.v1beta1.DocumentTransform"
    end
  end
  add_message "google.firestore.v1beta1.DocumentTransform" do
    optional :document, :string, 1
    repeated :field_transforms, :message, 2, "google.firestore.v1beta1.DocumentTransform.FieldTransform"
  end
  add_message "google.firestore.v1beta1.DocumentTransform.FieldTransform" do
    optional :field_path, :string, 1
    oneof :transform_type do
      optional :set_to_server_value, :enum, 2, "google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue"
      optional :append_missing_elements, :message, 6, "google.firestore.v1beta1.ArrayValue"
      optional :remove_all_from_array, :message, 7, "google.firestore.v1beta1.ArrayValue"
    end
  end
  add_enum "google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue" do
    value :SERVER_VALUE_UNSPECIFIED, 0
    value :REQUEST_TIME, 1
  end
  add_message "google.firestore.v1beta1.WriteResult" do
    optional :update_time, :message, 1, "google.protobuf.Timestamp"
    repeated :transform_results, :message, 2, "google.firestore.v1beta1.Value"
  end
  add_message "google.firestore.v1beta1.DocumentChange" do
    optional :document, :message, 1, "google.firestore.v1beta1.Document"
    repeated :target_ids, :int32, 5
    repeated :removed_target_ids, :int32, 6
  end
  add_message "google.firestore.v1beta1.DocumentDelete" do
    optional :document, :string, 1
    repeated :removed_target_ids, :int32, 6
    optional :read_time, :message, 4, "google.protobuf.Timestamp"
  end
  add_message "google.firestore.v1beta1.DocumentRemove" do
    optional :document, :string, 1
    repeated :removed_target_ids, :int32, 2
    optional :read_time, :message, 4, "google.protobuf.Timestamp"
  end
  add_message "google.firestore.v1beta1.ExistenceFilter" do
    optional :target_id, :int32, 1
    optional :count, :int32, 2
  end
end

module Google
  module Firestore
    module V1beta1
      Write = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.Write").msgclass
      DocumentTransform = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentTransform").msgclass
      DocumentTransform::FieldTransform = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentTransform.FieldTransform").msgclass
      DocumentTransform::FieldTransform::ServerValue = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue").enummodule
      WriteResult = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.WriteResult").msgclass
      DocumentChange = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentChange").msgclass
      DocumentDelete = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentDelete").msgclass
      DocumentRemove = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.DocumentRemove").msgclass
      ExistenceFilter = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.firestore.v1beta1.ExistenceFilter").msgclass
    end
  end
end


text:
[![Hackage][hackage-badge]][hackage-link]
[![License][license-badge]][license-link]

`silvi` is a Haskell library for generating fake data.

[hackage-badge]:
    https://img.shields.io/hackage/v/silvi.svg?label=Hackage
[hackage-link]:
    https://hackage.haskell.org/package/silvi
[license-badge]:
    https://img.shields.io/badge/License-BSD3-blue.svg
[license-link]:
    https://spdx.org/licenses/BSD3.html


text:
/**
 * Created by usuario on 18/1/2017.
 */
angular.module('AppPrueba')
    .controller('ValidarController', function ($scope,MostrarService,$state,ValidarService) {
        $scope.fincas = [];
        //PARA PODER DEVOLVERNOS
        $scope.gidFinca = "";
        // $scope.apartoGid = VerEditarFormServiceCodigoFincaAparto.gidAparto;
        $scope.codigofinca = "";
        $scope.apartoAtual = "";
        $scope.validarApartoInfo =[];

        $scope.dataFinca = {};
        $scope.heightpanel = screen.height - ((screen.height/3)+ (screen.height/9));
        $scope.heightListaPreg = $scope.heightpanel -(screen.height/9);
        // Se debe de obtener el id del usuario
        $scope.idUser=1;
        MostrarService.getFincas($scope.idUser).then(function (data) {
            $scope.fincas = data;
        });

        $scope.change = function(){

            MostrarService.previewValidar($scope.gidFinca).then(function (data) {
                $scope.numHistoricoActual = data.max;
                $scope.Max = data.max;
                reconvertJsonPolygon(data.finca,false);
            });

            //obtener idUsuario
            MostrarService.getFincasByID("1", $scope.gidFinca).then(function(data){
                $scope.dataFinca = data[0];
                console.log($scope.dataFinca);

                $scope.codigofinca = $scope.dataFinca["gid"];

                console.log("finca:" + $scope.codigofinca);
                ValidarService.getApartosAValidar($scope.codigofinca).then(function (apartoValidarInfo) {
                    console.log($scope.codigofinca);
                    console.log(apartoValidarInfo);
                    if(apartoValidarInfo != false && apartoValidarInfo != "false" && apartoValidarInfo != undefined && apartoValidarInfo != "") {
                        $scope.validarApartoInfo = apartoValidarInfo;
                    }
                    else {
                        $scope.validarApartoInfo = [];
                    }
                });
            });

        };

        $scope.json = [];
        function reconvertJsonPolygon(puntos,aparto) {
            var json = [];
            var points = '';

            for(var i = 0; i < puntos.length; i++) {
                for (var j = 0; j < puntos[i].puntos.length; j++) {
                    points += puntos[i].puntos[j].x + ',' + puntos[i].puntos[j].y + ' ';
                }
                json.push({gid:puntos[i].gid,puntos: points.slice(0, points.length-1)});
                points = '';
            }
            if(!aparto)
                $scope.json = json;
            else
                $scope.jsonSeleccionado=json;
        }

        $scope.gidAparto = "";
        $scope.jsonSeleccionado=[];
        $scope.unir = function(gid, coordenadas){

            $scope.apartoGid = gid;
            $scope.jsonSeleccionado =[];
            $scope.jsonSeleccionado.push({id:gid,puntos:coordenadas});

            console.log($scope.jsonSeleccionado);
            //obtener idUsuario
            MostrarService.getApartoByID($scope.apartoGid,$scope.gidFinca).then(function(data){
                $scope.dataAparto = data[0];
            });

            $scope.apartoAtual = true;
        };

        $scope.aceptarAparto = function (gid) {
            ValidarService.aceptarAparto(gid).then(function (data) {
                console.log(data);
            })
        };

        $scope.rechazarAparto = function (gid) {
            ValidarService.rechazarAparto(gid).then(function (data) {
                console.log(data);
            })
        };

        $scope.gotoForm = function(){

            $state.go("dashboard.formularioGanaderia");
        };
        //********************************************** Llamadas necesarias****************************************************
        $scope.change();

    });


text:
<?php

/**
 * The "searchapplications" collection of methods.
 * Typical usage is:
 *  <code>
 *   $cloudsearchService = new Google_Service_CloudSearch(...);
 *   $searchapplications = $cloudsearchService->searchapplications;
 *  </code>
 */
class Google_Service_CloudSearch_Resource_StatsQuerySearchapplications extends Google_Service_Resource
{
  /**
   * Get the query statistics for search application. **Note:** This API requires
   * a standard end user account to execute. (searchapplications.get)
   *
   * @param string $name The resource id of the search application query stats, in
   * the following format: searchapplications/{application_id}
   * @param array $optParams Optional parameters.
   *
   * @opt_param int fromDate.day Day of month. Must be from 1 to 31 and valid for
   * the year and month.
   * @opt_param int fromDate.month Month of date. Must be from 1 to 12.
   * @opt_param int fromDate.year Year of date. Must be from 1 to 9999.
   * @opt_param int toDate.day Day of month. Must be from 1 to 31 and valid for
   * the year and month.
   * @opt_param int toDate.month Month of date. Must be from 1 to 12.
   * @opt_param int toDate.year Year of date. Must be from 1 to 9999.
   * @return Google_Service_CloudSearch_GetSearchApplicationQueryStatsResponse
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_CloudSearch_GetSearchApplicationQueryStatsResponse");
  }
}


text:
Add HTML support for [textlint](https://github.com/textlint/textlint "textlint").

What is textlint plugin? Please see https://github.com/textlint/textlint/blob/master/docs/plugin.md

## Installation

    npm install textlint-plugin-html

## Default supported extensions

- `.html`
- `.htm`

## Usage

Manually add text plugin to do following:

```
{
    "plugins": [
        "html"
    ]
}
```

Lint HTML file with textlint

```
$ textlint index.html
```

### Options
 - `extensions`: `string[]`
    - Additional file extensions for html

For example, if you want to treat `.custom-ext` as html, put following config to `.textlintrc`

 ```json
{
    "plugins": {
        "html": {
            "extensions": [".custom-ext"]
        }
    }
}
```

## Tests

    npm test

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## License

MIT


text:
import { ConvictSchema } from '../../../../src';

export default class Schema extends ConvictSchema<any, any> {
    build(): Record<string, any> {
        return {
            example: {
                default: 'examples are quick and easy',
                doc: 'A random example schema property',
                format: 'String',
            },
            test_flush: {
                default: false,
                doc: 'Test flushing',
                format: 'Boolean',
            },
        };
    }
}


text:
using RawRabbit.Common;

namespace RawRabbit.Configuration.Queue
{
	public class QueueDeclarationBuilder : IQueueDeclarationBuilder
	{
		public QueueDeclaration Declaration { get;}

		public QueueDeclarationBuilder(QueueDeclaration initialQueue = null)
		{
			Declaration = initialQueue ?? QueueDeclaration.Default;
		}

		public IQueueDeclarationBuilder WithName(string queueName)
		{
			Truncator.Truncate(ref queueName);
			Declaration.Name = queueName;
			return this;
		}

		public IQueueDeclarationBuilder WithNameSuffix(string suffix)
		{
			WithName($"{Declaration.Name}_{suffix}");
			return this;
		}

		public IQueueDeclarationBuilder WithAutoDelete(bool autoDelete = true)
		{
			Declaration.AutoDelete = autoDelete;
			return this;
		}

		public IQueueDeclarationBuilder WithDurability(bool durable = true)
		{
			Declaration.Durable = durable;
			return this;
		}

		public IQueueDeclarationBuilder WithExclusivity(bool exclusive = true)
		{
			Declaration.Exclusive = exclusive;
			return this;
		}

		public IQueueDeclarationBuilder WithArgument(string key, object value)
		{
			Declaration.Arguments.Add(key, value);
			return this;
		}
	}
}


text:
define(['../MVC/MVC', '../basic/util', '../lib/jquery.mockjax'],
  function (MVC, util) {
  'use strict';
  return {
    RunTests: function(moduleName, modelClass){
      $.mockjax({
        url:  'test',
        type:'POST',
        responseText: { primary:1}
      });
      var loadData = [{ID:1, field1:'data1', field2:'data2'},
        {ID:2, field1:'data3', field2:'data4'}];
      $.mockjax({
        url:  'test',
        type:'GET',
        responseText: loadData
      });
      $.mockjax({
        url:  'test/1',
        type: 'PUT',
        responseText: { status:'200'}
      });
      $.mockjax({
        url:  'test/1',
        type: 'DELETE',
        responseText: { status:'ok'}
      });
      $.mockjax({
        url:  'test',
        type: 'DELETE',
        responseText: { status:'ok'}
      });
      $.mockjax({
        url:  'test/1',
        type: 'GET',
        responseText: {ID:1, field1:'data1', field2:'data2'}
      });
      module(moduleName);
      test('Create AjaxModel', function(){
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        equal(model._url, 'test', 'Url is set');
        if (typeof model.destroy == 'function') {
          model.destroy();
        }
      });
      asyncTest('Insert a record', function(){
        expect(6)
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onInsert', function(rec){
          ok(rec.ID ==  1, 'onInsert is trigger');
        });
        var data = {field1:'data1', field2:'data2'}
        model.insert(data,{
          success:function(myData, rec) {
            start();
            ok(myData.primary , 1, 'Response is right');
            ok(rec.ID ==  1, 'Rec ID is set right');
            ok(rec.field1 ==  'data1', 'Rec field1 is set right');
            ok(rec.field2 ==  'data2', 'Rec field2 is set right');
            if (typeof model.destroy == 'function') {
              model.destroy();
            }
          }
        });
      });
      asyncTest('Load records', function(){
        expect(4);
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onLoad', function(){
          ok(true, 'onLoad is trigger');
        });
        var conditions = {condtion1: 'condtion1'}
        model.load({param:conditions, success: function(data, param){
          start();
          deepEqual(conditions, param, 'Param is set');
          deepEqual(data, loadData, 'Data is set');
          if (typeof model.destroy == 'function') {
            model.destroy();
          }
        }})
      });
      asyncTest('Load a record', function(){
        expect(7);
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onInsert', function(rec){
          ok(rec.ID ==  1, 'onInsert: Rec ID is set right');
          ok(rec.field1 ==  'data1', 'onInsert: Rec field1 is set right');
          ok(rec.field2 ==  'data2', 'onInsert: Rec field2 is set right');
        });
        model.loadRecord({key:1, success: function(rec){
          start();
          ok(rec.ID ==  1, 'Rec ID is set right');
          ok(rec.field1 ==  'data1', 'Rec field1 is set right');
          ok(rec.field2 ==  'data2', 'Rec field2 is set right');
          if (typeof model.destroy == 'function') {
            model.destroy();
          }
        }})
      });
      asyncTest('Update a record', function(){
        expect(5);
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onUpdate', function(rec, newRec){
          equal(newRec.field2, 'data3', 'onInsert is trigger');
        });
        var data = {field1:'data1', field2:'data2'}
        model.insert(data,{
          success:function(myData, rec) {
            var record= rec;
            model.update(record, {field2: 'data3'}, {success:function(data){
              start();
              equal(record.field2, 'data3', 'Update at local')
              equal(data.status, '200', 'Update at server');
              if (typeof model.destroy == 'function') {
                model.destroy();
              }
            }});
          }
        });
      });
      asyncTest('Remove a record', function(){
        expect(5);
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onRemove', function(rec){
          ok(rec.ID ==  1, 'onInsert is trigger');
        });
        var data = {field1:'data1', field2:'data2'}
        model.insert(data,{
          success:function(myData, rec) {
            var record= rec;
            model.remove(record, {success:function(data){
              start();
              equal(data.status, 'ok', 'Delete from server');
              if (typeof model.destroy == 'function') {
                model.destroy();
              }
            }});
            equal(model.count(), 0, 'Delete from local')
          }
        });
      });
      asyncTest('Remove all records', function(){
        expect(4);
        var model = new modelClass({
          url:'test',
          fields: [{name: 'ID'}, {name: 'field1'}, {name: 'field2'}],
        });
        model.bind('onChange', function(){
          ok(true, 'onChange');
        });
        model.bind('onClear', function(){
          ok(true, 'onClear is trigger');
        });
        var conditions = {condtion1: 'condtion1'}
        model.load({param:conditions, success: function(data, param){
          model.clear({success: function(data){
            start();
            equal(data.status, 'ok', 'Delete all records');
            if (typeof model.destroy == 'function') {
              model.destroy();
            }
          }})
        }});
      });
    }
  }
})


text:
User stories:

1. I can pass a string as a parameter, and it will check to see whether that string contains either a unix timestamp or a natural language date (example: January 1, 2016)
2. If it does, it returns both the Unix timestamp and the natural language form of that date.
3. If it does not contain a date or Unix timestamp, it returns null for those properties.

Example usage:

- <https://szib-fcc-microservices.herokuapp.com/timestamp/253636>
- <https://szib-fcc-microservices.herokuapp.com/timestamp/December%2015,2016>

Example response:

`{"unix":1481760000,"natural":"December 15,2016"}`

--------------------------------------------------------------------------------

## Header parser service

User Story: I can get the IP address, language and operating system for my browser.

Example usage:

<https://szib-fcc-microservices.herokuapp.com/header_parser>

Example response:

`{"ipaddress":"xxx.xxx.xxx.xxx","software":"Windows NT 10.0; Win64; x64","language":"en-GB"}`

--------------------------------------------------------------------------------

## URL shortener service

User Stories:

- I can pass a URL as a parameter and I will receive a shortened URL in the JSON response.
- If I pass an invalid URL that doesn't follow the valid <http://www.example.com> format, the JSON response will contain an error instead.
- When I visit that shortened URL, it will redirect me to my original link.

Example creation usage:

<https://szib-fcc-microservices.herokuapp.com/tinyurl/new/http://www.google.com>

Example creation response:

`{"url":"<http://www.google.com","id":"ed646a3334ca891fd3467db131372140","_id":"5881f8751313b5001155e01b"}>`

Example usage:

<https://szib-fcc-microservices.herokuapp.com/tinyurl/ed646a3334ca891fd3467db131372140> will redirect to <http://www.google.com>

--------------------------------------------------------------------------------

## Image Search Abstraction Layer

User Stories:

- I can get the image URLs, alt text and page urls for a set of images relating to a given search string.
- I can paginate through the responses by adding a ?offset=2 parameter to the URL.
- I can get a list of the most recently submitted search strings.

Endpoints:

- <https://szib-fcc-microservices.herokuapp.com/imagesearch/lolcat>
- <https://szib-fcc-microservices.herokuapp.com/imagesearch/lolcat/offset/10>
- <https://szib-fcc-microservices.herokuapp.com/imagesearch_history>

--------------------------------------------------------------------------------

## File Metadata service

User Stories:

- I can upload a file and get back its size in JSON

Endpoint:

- <https://szib-fcc-microservices.herokuapp.com/file-metadata>


text:
namespace Merchello.Core.Gateways.Taxation.FixedRate
{
    /// <summary>
    /// Marker interface for the FixRateTaxMethod
    /// </summary>
    public interface IFixedRateTaxationGatewayMethod
    { }
}


text:
package gov.nih.nci.caintegrator.studyQueryService.germline;

import gov.nih.nci.caintegrator.domain.finding.bean.Finding;
import gov.nih.nci.caintegrator.domain.finding.variation.snpFrequency.bean.SNPFrequencyFinding;
import gov.nih.nci.caintegrator.domain.study.bean.Population;
import gov.nih.nci.caintegrator.domain.annotation.snp.bean.SNPAnnotation;
import gov.nih.nci.caintegrator.studyQueryService.dto.FindingCriteriaDTO;
import gov.nih.nci.caintegrator.studyQueryService.dto.study.StudyCriteria;
import gov.nih.nci.caintegrator.studyQueryService.dto.annotation.AnnotationCriteria;
import gov.nih.nci.caintegrator.studyQueryService.dto.germline.SNPFrequencyFindingCriteriaDTO;
import gov.nih.nci.caintegrator.util.HQLHelper;
import gov.nih.nci.caintegrator.util.ArithematicOperator;

import java.util.*;
import java.text.MessageFormat;

import org.hibernate.*;
import org.hibernate.criterion.Restrictions;

/**
 * Author: Ram Bhattaru
 * Date:   Jul 17, 2006
 * Time:   5:52:11 PM
 */
public class SNPFrequencyFindingHandler extends FindingsHandler {

    protected Class getTargeFindingType() {
        return SNPFrequencyFinding.class;
    }
    protected List<? extends Finding> getConcreteTypedFindingList() {
        return new ArrayList<SNPFrequencyFinding>();
    }

    protected Set getConcreteTypedFindingSet() {
        return new HashSet<SNPFrequencyFinding>();
    }

    protected StringBuffer getTargetFindingHQL() {

        StringBuffer targetHQL = new StringBuffer(" FROM SNPFrequencyFinding "+ TARGET_FINDING_ALIAS +
                                                  " {0} {1} WHERE {2} {3} ");

/*
        StringBuffer targetHQL = new StringBuffer(" FROM SNPFrequencyFinding "+ TARGET_FINDING_ALIAS +
                                                 " JOIN "+ TARGET_FINDING_ALIAS + ".snpAnnotation " +
                                                  " {0} {1} WHERE {2} {3} ");
*/

        return targetHQL;
    }

    protected Collection< ? extends Finding> executeFindingSetQuery(FindingCriteriaDTO critDTO,StringBuffer targetHQL,
                                                               Session session, int start, int end ) throws Exception {
        SNPFrequencyFindingCriteriaDTO findingCritDTO = (SNPFrequencyFindingCriteriaDTO) critDTO;
        AnnotationCriteria annotCrit = critDTO.getAnnotationCriteria();
        if ((annotCrit != null) && isOnlyPanelCriteria(annotCrit))
               return executePanelOnlySearch(critDTO, session, start, end);

        HashMap params = new HashMap();
        StringBuffer snpAnnotCond = new StringBuffer();

        /* 0. if AnnotationCrit is specified, then append required HQL (to snpAnnotCondition) for handling AnnotationCrit*/
        appendAnnotationCritHQL(critDTO, params, snpAnnotCond);

        /* 1. Include Annotation Criteria in TargetFinding query   */
        StringBuffer snpAnnotJoin = new StringBuffer("");

       /*  2. Handle population Criteria */
       StringBuffer populationJoin = new StringBuffer("");
       StringBuffer populationCond = new StringBuffer("");
       preparePopulationCriteria(findingCritDTO, session, populationJoin, populationCond, params);

       String hql  = MessageFormat.format(targetHQL.toString(),
                                new Object[] {  snpAnnotJoin.toString(), populationJoin.toString(),
                                                snpAnnotCond.toString(), populationCond.toString() });

       StringBuffer formattedTargetHQL = new StringBuffer(hql);

       /*  3. Handle SNPFrequencyFinding Attributes Criteria itself  and populate targetHQL/params */
       addSNPFrequencyFindingAttriuteCrit(findingCritDTO, formattedTargetHQL, params);

       String andRemovedHQL = HQLHelper.removeTrailingToken(new StringBuffer(formattedTargetHQL), "AND");
       String finalHQL = HQLHelper.removeTrailingToken(new StringBuffer(andRemovedHQL), "WHERE");
       Query q = session.createQuery(finalHQL);
       HQLHelper.setParamsOnQuery(params, q);
       q.setFirstResult(start);
       q.setMaxResults(end - start);

       List<SNPFrequencyFinding> findings = q.list();
       HashSet<SNPFrequencyFinding> results = new HashSet<SNPFrequencyFinding>();
       results.addAll(findings);
       return results;
    }

    private List<Population> handlePopulationCriteria(SNPFrequencyFindingCriteriaDTO findingCritDTO, Session session) {
       String[] populationNames = findingCritDTO.getPopulationNames();
       Long studyId = findingCritDTO.getStudyCriteria().getId();

       if ((populationNames == null || populationNames.length < 1) && (studyId == null )) {
            return new ArrayList<Population>();
       }

       Criteria popCrit = session.createCriteria(Population.class);
       if (populationNames != null && populationNames.length > 0) {
           popCrit.add(Restrictions.in("name", populationNames));
       }

       boolean appendStudy = isAddStudyCriteria(findingCritDTO);
       if (appendStudy) {
            Criteria studyCrit = popCrit.createCriteria("studyCollection");
            addStudyCriteria(findingCritDTO, studyCrit, session);
        }

        List<Population> populationList = popCrit.list();
        return populationList;
    }

    private void addStudyCriteria( SNPFrequencyFindingCriteriaDTO findingCritDTO, Criteria studyCrit, Session session) {
        Long studyId = findingCritDTO.getStudyCriteria().getId();
        if (studyId != null ) {
            studyCrit.add(Restrictions.eq("id", studyId));
        }
    }
    private boolean isAddStudyCriteria( SNPFrequencyFindingCriteriaDTO findingCritDTO) {
            Long studyId = findingCritDTO.getStudyCriteria().getId();
            if (studyId != null)
               return true;

            return false;
    }

    public void addSNPFrequencyFindingAttriuteCrit(SNPFrequencyFindingCriteriaDTO crit, StringBuffer hql, HashMap params) {
        StudyCriteria studyCrit = crit.getStudyCriteria();

        Float hardyWeinbergPValue  = crit.getHardyWeinbergPValue();
        ArithematicOperator hardyWeinbergPValueOperator = crit.getHardyWeinbergPValueOperator();

        Float minorAlleleFreq = crit.getMinorAlleleFrequency();
        ArithematicOperator minorAlleleOperator = crit.getMinorAlleleOperator();

        Double completionRate = crit.getCompletionRate();
        ArithematicOperator completeRateOperator = crit.getCompleteRateOperator();

        Integer heterCount = crit.getHeterozygoteCount();
        Integer missingAlleleCnt = crit.getMissingAlleleCount();
        Integer missingGenotypeCnt = crit.getMissingGenotypeCount();
        String otherAllele = crit.getOtherAllele();
        Integer otherAllelCnt = crit.getOtherAlleleCount();
        Integer otherHomogyoteCnt = crit.getOtherHomogygoteCount();
        String referenceAllele = crit.getReferenceAllele();
        Integer referenceAlleleCnt = crit.getReferenceAlleleCount();
        Integer referenceHomogzoteCnt = crit.getReferenceHomogyzoteCount();

        if (completionRate != null) {
            if (completeRateOperator == null) completeRateOperator = ArithematicOperator.EQ; // default
            String clause =  TARGET_FINDING_ALIAS + ".completionRate {0} :completionRate AND ";
            String condition = HQLHelper.prepareCondition(completeRateOperator);
            String formattedClause = MessageFormat.format(clause, new Object[] {condition} );
            hql.append(formattedClause);
            params.put("completionRate", completionRate);
        }

        if (hardyWeinbergPValue != null) {
            if (hardyWeinbergPValueOperator == null) hardyWeinbergPValueOperator = ArithematicOperator.EQ; // default
            String clause =  TARGET_FINDING_ALIAS + ".hardyWeinbergPValue {0} :hardyWeinbergPValue AND ";
            String condition = HQLHelper.prepareCondition(hardyWeinbergPValueOperator);
            String formattedClause = MessageFormat.format(clause, new Object[] {condition} );
            hql.append(formattedClause);
            params.put("hardyWeinbergPValue", hardyWeinbergPValue);
        }

        if (minorAlleleFreq != null) {
            if (minorAlleleOperator == null) minorAlleleOperator = ArithematicOperator.EQ; // default
            String clause =  TARGET_FINDING_ALIAS + ".minorAlleleFrequency  {0} :minorAlleleFrequency  AND ";
            String condition = HQLHelper.prepareCondition(minorAlleleOperator);
            String formattedClause = MessageFormat.format(clause, new Object[] {condition} );
            hql.append(formattedClause);
            params.put("minorAlleleFrequency", minorAlleleFreq);
        }

        if (heterCount != null) {
           hql.append( TARGET_FINDING_ALIAS + ".heterozygoteCount = :heterCount AND ");
           params.put("heterCount", heterCount);
        }

        if (missingAlleleCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".missingAlleleCount = :missingAlleleCnt AND ");
            params.put("missingAlleleCnt", missingAlleleCnt);
        }
        if (missingGenotypeCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".missingAlleleCount = :missingGenotypeCnt AND ");
            params.put("missingGenotypeCount", missingGenotypeCnt);
        }
        if (otherAllele != null) {
            hql.append( TARGET_FINDING_ALIAS + ".missingAlleleCount = :otherAllele AND ");
            params.put("otherAllele", otherAllele);
        }
        if (otherAllelCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".otherAlleleCount = :otherAllelCnt AND ");
            params.put("otherAllelCnt", otherAllelCnt);
        }
        if (otherHomogyoteCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".otherHomogygoteCount = :otherHomogyoteCnt AND ");
            params.put("otherHomogyoteCnt", otherHomogyoteCnt);
        }
        if (referenceAllele != null) {
            hql.append( TARGET_FINDING_ALIAS + ".referenceAllele = :referenceAllele AND ");
            params.put("referenceAllele", referenceAllele);
        }
        if (referenceAlleleCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".referenceAlleleCount = :referenceAlleleCnt AND ");
            params.put("referenceAlleleCnt", referenceAlleleCnt);
        }
        if (referenceHomogzoteCnt != null) {
            hql.append( TARGET_FINDING_ALIAS + ".referenceHomogyzoteCount = :referenceHomogzoteCnt AND ");
            params.put("referenceHomogzoteCnt", referenceHomogzoteCnt);
        }

        if (studyCrit != null) {
            if (studyCrit.getId() != null) {
                hql.append( TARGET_FINDING_ALIAS + ".study.id = :studyId AND ");
                params.put("studyId", studyCrit.getId());
            }
        }

    }
    protected void initializeProxies(Collection<? extends Finding> findings, Session session) {

        /* initialize SNPAnnotations */
        Collection<Long> snpAnnotsIDs = new HashSet<Long>();
        Collection<Long> populationIDs = new HashSet<Long>();
        for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
                SNPFrequencyFinding finding =  (SNPFrequencyFinding) iterator.next();
                snpAnnotsIDs.add(finding.getSnpAnnotation().getId());
                populationIDs.add(finding.getPopulation().getId());
        }
        if(snpAnnotsIDs.size() >0) {
              ArrayList arrayIDs = new ArrayList(snpAnnotsIDs);
              for (int i = 0; i < arrayIDs.size();) {
                  Collection values = new ArrayList();
                  int begIndex = i;
                  i += IN_PARAMETERS ;
                  int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
                  values.addAll(arrayIDs.subList(begIndex,  lastIndex));
                  Criteria snpAnnotcrit = session.createCriteria(SNPAnnotation.class).
                  setFetchMode("geneBiomarkerCollection", FetchMode.EAGER).
                  add(Restrictions.in("id", values));
                  snpAnnotcrit.list();
              }
        }

        /* initialize Population */
        if (populationIDs.size() > 0) {
            Criteria populationCrit = session.createCriteria(Population.class).
                                add(Restrictions.in("id", populationIDs));
            populationCrit.list();
        }

        Collection findingIDs = new HashSet();
        for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
           SNPFrequencyFinding finding = (SNPFrequencyFinding) iterator.next();
           findingIDs.add(finding.getId());
        }

/*
        Criteria crit;
        ArrayList<String> arrayIDs = new ArrayList<String>(findingIDs);
        for (int i = 0; i < arrayIDs.size();) {
            List<String> values = new ArrayList<String>();
            int begIndex = i;
            i += 1000 ;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex,  lastIndex));
            crit = session.createCriteria(SNPAnnotation.class).
                                      createAlias("snpFrequencyCollection", "findings").
                                      setFetchMode("geneBiomarkerCollection", FetchMode.EAGER).
                                      add(Restrictions.in("findings.id", values));
            crit.list();
        }

        for (int i = 0; i < arrayIDs.size();) {
            List<String> values = new ArrayList<String>();
            int begIndex = i;
            i += 1000 ;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex,  lastIndex));
            crit = session.createCriteria(Population.class).
                                        createAlias("snpFrequencyCollection", "findings").
                                        add(Restrictions.in("findings.id", values));
            crit.list();
        }
*/
    }

   protected Collection<? extends Finding> getFindingsFromResults(List results) {
        Collection<SNPFrequencyFinding> findings = new ArrayList<SNPFrequencyFinding>(results.size());
        Iterator findingsAndAnnotsIter = results.iterator();
        while(findingsAndAnnotsIter.hasNext()) {
            Object[] duplet = (Object[]) findingsAndAnnotsIter.next();
            SNPFrequencyFinding finding = (SNPFrequencyFinding) duplet[0];
            findings.add(finding);
        }
        return findings;
    }

    public Collection<? extends Finding> executePanelOnlySearch(FindingCriteriaDTO critDTO, Session session,
                                                                                int start, int end) {
        SNPFrequencyFindingCriteriaDTO   findingCritDTO = (SNPFrequencyFindingCriteriaDTO)critDTO;
        AnnotationCriteria annotCrit = findingCritDTO.getAnnotationCriteria();

        final StringBuffer snpTargetHQL = new StringBuffer(
                                      " FROM SNPFrequencyFinding "+ TARGET_FINDING_ALIAS + ", SNPAssay s " +
                                     //  " JOIN "+ TARGET_FINDING_ALIAS + ".snpAnnotation " +
                                       " {0} WHERE s.snpPanel.id = {1} AND "+
                                      TARGET_FINDING_ALIAS + ".snpAnnotation = s.snpAnnotation " + " AND {2} ");

        HashMap params = new HashMap();
        StringBuffer populationJoin = new StringBuffer("");
        StringBuffer populationCond = new StringBuffer("");
        preparePopulationCriteria(findingCritDTO, session, populationJoin, populationCond, params);

        StringBuffer hql = new StringBuffer (
                          MessageFormat.format( snpTargetHQL.toString(),
                                        new Object[] { populationJoin.toString(),
                                          annotCrit.getPanelCriteria().getSnpPanelID(), populationCond.toString() }));

        StringBuffer hqlWithAND = new StringBuffer(HQLHelper.removeTrailingToken(new StringBuffer(hql), "AND"));
        hqlWithAND.append(" AND ");

        StringBuffer formattedTargetHQL = new StringBuffer(hqlWithAND);
        addSNPFrequencyFindingAttriuteCrit(findingCritDTO, formattedTargetHQL, params);

        String andRemovedHQL = HQLHelper.removeTrailingToken(new StringBuffer(formattedTargetHQL), "AND");
        String finalHQL = HQLHelper.removeTrailingToken(new StringBuffer(andRemovedHQL), "WHERE");
        Query q = session.createQuery(finalHQL);
        HQLHelper.setParamsOnQuery(params, q);

        if (start == -1 || end == -1) {}
        else {
            q.setFirstResult(start);
            q.setMaxResults(end - start);
        }

        Collection<? extends Finding> finalResults = getFindingsFromResults(q.list());
        //initializeProxies(finalResults, session);  (CALLED FROM FindingsHandler)
        List<SNPFrequencyFinding> results =  new ArrayList<SNPFrequencyFinding>(finalResults.size());
        for (Iterator<? extends Finding> iterator = finalResults.iterator(); iterator.hasNext();) {
            SNPFrequencyFinding finding =  (SNPFrequencyFinding)iterator.next();
            results.add(finding);
        }
        return results;
    }

    private void preparePopulationCriteria(SNPFrequencyFindingCriteriaDTO findingCritDTO, Session session, StringBuffer populationJoin, StringBuffer populationCond, HashMap params) {
        List<Population> populationList = handlePopulationCriteria(findingCritDTO, session);
        if (populationList.size() > 0) {
           populationJoin.append(" LEFT JOIN FETCH " + TARGET_FINDING_ALIAS + ".population ");
           populationCond.append( TARGET_FINDING_ALIAS + ".population IN (:populationList) AND ");
           params.put("populationList", populationList);
        }
    }

}


text:
package cromwell.engine.db.slick

import java.sql.Clob

import cromwell.engine.ExecutionIndex
import cromwell.engine.ExecutionIndex._

case class Symbol
(
  workflowExecutionId: Int,
  scope: String,
  name: String,
  index: Int, // https://bugs.mysql.com/bug.php?id=8173
  io: String,
  reportableResult: Boolean,
  wdlType: String,
  wdlValue: Option[Clob],
  symbolHash: Option[String],
  symbolId: Option[Int] = None
  )

trait SymbolComponent {
  this: DriverComponent with WorkflowExecutionComponent =>

  import driver.api._

  class Symbols(tag: Tag) extends Table[Symbol](tag, "SYMBOL") {
    def symbolId = column[Int]("SYMBOL_ID", O.PrimaryKey, O.AutoInc)

    def workflowExecutionId = column[Int]("WORKFLOW_EXECUTION_ID")

    def scope = column[String]("SCOPE")

    def name = column[String]("NAME")

    def index = column[Int]("INDEX")

    def io = column[String]("IO")

    def reportableResult = column[Boolean]("REPORTABLE_RESULT")

    def wdlType = column[String]("WDL_TYPE")

    def wdlValue = column[Option[Clob]]("WDL_VALUE")

    def symbolHash = column[Option[String]]("HASH")

    override def * = (workflowExecutionId, scope, name, index, io, reportableResult, wdlType, wdlValue, symbolHash, symbolId.?) <>
      (Symbol.tupled, Symbol.unapply)

    def workflowExecution = foreignKey(
      "FK_SYMBOL_WORKFLOW_EXECUTION_ID", workflowExecutionId, workflowExecutions)(_.workflowExecutionId)

    def uniqueKey = index("UK_SYM_WORKFLOW_EXECUTION_ID_SCOPE_NAME_ITERATION_IO",
      (workflowExecutionId, scope, name, index, io), unique = true)
  }

  protected val symbols = TableQuery[Symbols]

  val symbolsAutoInc = symbols returning symbols.
    map(_.symbolId) into ((a, id) => a.copy(symbolId = Some(id)))

  // Convenience function
  def symbolsByWorkflowExecutionUuidAndIoAndMaybeScope(workflowExecutionUuid: String,
                                                       io: String, scopeOption: Option[String], indexOption: Option[Int]) = {
    scopeOption match {
      case Some(scope) => symbolsByWorkflowExecutionUuidAndIoAndScopeAndIndex(workflowExecutionUuid, io, scope, indexOption.fromIndex)
      case None => symbolsByWorkflowExecutionUuidAndIoNoIndex(workflowExecutionUuid, io)
    }
  }

  val allSymbols = Compiled(
    (workflowExecutionUuid: Rep[String]) => for {
      symbol <- symbols
      workflowExecution <- symbol.workflowExecution
      if workflowExecution.workflowExecutionUuid === workflowExecutionUuid
    } yield symbol)

  val symbolsByWorkflowExecutionUuidAndIo = Compiled(
    (workflowExecutionUuid: Rep[String], io: Rep[String]) => for {
      symbol <- symbols
      if symbol.io === io
      workflowExecution <- symbol.workflowExecution
      if workflowExecution.workflowExecutionUuid === workflowExecutionUuid
    } yield symbol)

  val symbolsByWorkflowExecutionUuidAndIoNoIndex = Compiled(
    (workflowExecutionUuid: Rep[String], io: Rep[String]) => for {
      symbol <- symbols
      if symbol.io === io && symbol.index === ExecutionIndex.IndexNone
      workflowExecution <- symbol.workflowExecution
      if workflowExecution.workflowExecutionUuid === workflowExecutionUuid
    } yield symbol)

  val symbolsByWorkflowExecutionUuidAndIoAndScopeAndIndex = Compiled(
    (workflowExecutionUuid: Rep[String], io: Rep[String], scope: Rep[String], index: Rep[Int]) => for {
      symbol <- symbols
      if symbol.io === io && symbol.scope === scope && symbol.index === index
      workflowExecution <- symbol.workflowExecution
      if workflowExecution.workflowExecutionUuid === workflowExecutionUuid
    } yield symbol)

  def symbolsFilterByWorkflowAndScopeAndNameAndIndex(workflowExecutionId: Int, scope: String, name: String, index: Int) = {
    val workflowFilteredQuery = for {
      symbol <- symbols
      if symbol.workflowExecutionId === workflowExecutionId
    } yield symbol

    workflowFilteredQuery filter { s =>
      s.scope === scope &&
      s.name === name &&
      s.index === index
    }
  }

  val symbolsForWorkflowOutput = Compiled(
    (workflowExecutionUuid: Rep[String]) => for {
      symbol <- symbols
      if symbol.reportableResult === true
      workflowExecution <- symbol.workflowExecution
      if workflowExecution.workflowExecutionUuid === workflowExecutionUuid
    } yield symbol)
}


text:
package listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

/**
 * @Author : garyhu
 * @Since : 2017/10/18
 * @Decription :
 */
public class ContextAttributeListener implements ServletContextAttributeListener {
    public void attributeAdded(ServletContextAttributeEvent e) {
        //监听属性的增加
        System.out.println("增加属性");
        System.out.println("属性是:"+e.getName());
        System.out.println("值是 :"+e.getValue());
    }

    public void attributeRemoved(ServletContextAttributeEvent e) {
        //监听属性的移除
        System.out.println("移除属性");
    }

    public void attributeReplaced(ServletContextAttributeEvent e) {
        //监听属性的替换
        System.out.println("属性值替换");
    }
}


text:
export function echo<T>(input: T): T {
  return input;
}


text:
#pragma once

#include <stdint.h>
#include <limits>

#include "TypeElement.h"

#include <string>

class CParameterAccessContext;
class CConfigurationAccessContext;

class CParameterType : public CTypeElement
{
public:
    CParameterType(const std::string& strName);
    virtual ~CParameterType();

    // Size
    uint32_t getSize() const;

    // Unit
    std::string getUnit() const;
    void setUnit(const std::string& strUnit);

    // From IXmlSink
    virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext);

    // From IXmlSource
    virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const;

    /// Conversions
    // String
    virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const = 0;
    virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const = 0;
    // Boolean
    virtual bool toBlackboard(bool bUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(bool& bUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const;
    // Integer
    virtual bool toBlackboard(uint32_t uiUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(uint32_t& uiUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const;
    // Signed Integer
    virtual bool toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const;
    // Double
    virtual bool toBlackboard(double dUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(double& dUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const;

    // XML Serialization value space handling
    // Value space handling for configuration import/export
    virtual void handleValueSpaceAttribute(CXmlElement& xmlConfigurableElementSettingsElement, CConfigurationAccessContext& configurationAccessContext) const;

    // Element properties
    virtual void showProperties(std::string& strResult) const;

    // Default value handling (simulation only)
    virtual uint32_t getDefaultValue() const;

    /**
     * Sign extension (32 bits)
     *
     * @param[in:out] iData the data which will be sign extended
     */
    void signExtend(int32_t& iData) const;

    /**
     * Sign extension (64 bits)
     *
     * @param[in:out] iData the data which will be sign extended
     */
    void signExtend(int64_t& iData) const;

protected:
    // Object creation
    virtual void populate(CElement* pElement) const;
    // Size
    void setSize(uint32_t uiSize);

    // Check data has no bit set outside available range (based on byte size) and
    // check data is consistent with available range, with respect to its sign
    bool isEncodable(uint32_t uiData, bool bIsSigned) const;
    bool isEncodable(uint64_t uiData, bool bIsSigned) const;
    // Remove all bits set outside available range
    uint32_t makeEncodable(uint32_t uiData) const;

    /** Compute max value according to the parameter type */
    template <typename type>
    type getMaxValue() const
    {
        return getSize() < sizeof(type) ?
                    (static_cast<type>(1) << (getSize() * std::numeric_limits<unsigned char>::digits - 1)) - 1 :
                    std::numeric_limits<type>::max();
    }

private:
    void setXmlUnitAttribute(CXmlElement& xmlElement) const;

    // Instantiation
    virtual CInstanceConfigurableElement* doInstantiate() const;
    // Generic Access
    template <typename type>
    void doSignExtend(type& data) const;
    template <typename type>
    bool doIsEncodable(type data, bool bIsSigned) const;

    // Size in bytes
    uint32_t _uiSize;
    // Unit
    std::string _strUnit;

    static const std::string gUnitPropertyName;
};


text:
package org.drools.core.command.runtime.process;

import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.impl.RegistryContext;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.Context;
import org.kie.internal.command.ProcessInstanceIdCommand;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class GetProcessInstanceCommand implements ExecutableCommand<ProcessInstance>, ProcessInstanceIdCommand {

    /** Generated serial version UID */
    private static final long serialVersionUID = 5890677592835087670L;

    @XmlAttribute(required = true)
    private Long processInstanceId;
    @XmlAttribute
    private boolean readOnly = false;

    public GetProcessInstanceCommand() {}

    public GetProcessInstanceCommand(Long processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    @Override
    public Long getProcessInstanceId() {
        return processInstanceId;
    }

    @Override
    public void setProcessInstanceId(Long processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    public boolean isReadOnly() {
		return readOnly;
	}

	public void setReadOnly(boolean readOnly) {
		this.readOnly = readOnly;
	}

	public ProcessInstance execute(Context context) {
        KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
        if (processInstanceId == null) {
            return null;
        }
        return ksession.getProcessInstance(processInstanceId, readOnly);
    }

    public String toString() {
        return "session.getProcessInstance(" + processInstanceId + ");";
    }

}


text:
/*
 Tests
 */

import _ from "lodash"
_.extend(global, require('./shared'))

import {logger} from "../src/utils"

import Client from '../src/client'

// Logging Levels
logger.getLogger("predicthq.client").setLevel('DEBUG')

let test_account_id = process.env.TEST_ACCOUNT_ID
let test_user_password_access_token = process.env.TEST_USER_PASSWORD_ACCESS_TOKEN
let test_client_credentials_access_token = process.env.TEST_CLIENT_CREDENTIALS_ACCESS_TOKEN

describe('Events', () => {

    it('Search', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        c.events.search()
            .then((results)=> {

                // default limit 10 records
                expect(results.toArray().length).toEqual(10)

                // Check for known field
                let keys = _.keys(results.toArray()[0])
                expect(keys).toContain('id')

                // Check iterator
                let events = []
                for (let event of results) {
                    events.push(event)
                }

                expect(events.length).toEqual(10)

                done()

            }).catch(done)

    }),

    it('Search - with filter', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        // singapore
        c.events.search({
            q: 'Macklemore', rank_level: [4, 5], 'place.scope': ['1880251'],
            'start.gte': '2016-09-20', 'start.lt': '2016-09-21', 'start.tz': 'Asia/Singapore'
        })
            .then((results)=> {

                // Expect one record
                expect(results.toArray().length).toEqual(1)

                done()

            }).catch(done)

    }),

    it('Search - scope filter', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        // singapore
        c.events.search({
            q: 'Green Bay', label: ['american-football'], rank_level: [4, 5], 'place.scope': ['5244267', '4887398'],
            'start.gte': '2016-12-10', 'start.lt': '2016-12-20', 'category':'sports', 'sort': 'start'
        })
            .then((results)=> {

                // Expect two record
                expect(results.toArray().length).toEqual(2)

                // Green Bay Packers vs Seattle Seahawks - NFL (11th Dec)
                expect(results.toArray()[0]['id']).toEqual('HyWiCstzPezY83Tvt8')

                // Chicago Bears vs Green Bay Packers - NFL (18th Dec)
                expect(results.toArray()[1]['id']).toEqual('ZLFqzNXgmfKW477iE2')

                done()

            }).catch(done)

    }),

    it('Search - with within filter', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        // boston
        c.events.search({
            'within': '1km@42.35996,-71.06009',
            'rank_level': [4,5],
            'start.gte': '2016-03-08', 'start.lt': '2016-03-09',
        })
            .then((results)=> {

                // Expect one record
                expect(results.toArray().length).toEqual(1)

                expect(results.toArray()[0]['id']).toEqual('d5jeNGOP0qmd')
                expect(results.toArray()[0]['title']).toEqual('The Who')

                done()

            }).catch(done)

    }),

    it('Search - Delta (updated and state filter)', (done) => {

            let c = new Client({access_token: test_client_credentials_access_token})

            c.events.search({
                'updated.gte': '2017-05-01',
                'updated.lte': '2017-05-02',
                'label': ['performing-arts'],
                'country': 'US',
                'sort': ['start'],
                'state': ['deleted']
            })
                .then((results)=> {

                    // Expect some results
                    expect(results.toArray().length).toEqual(10)

                    expect(results.toArray()[0]['id']).toEqual('geABVyeWJm8n')

                    done()

                }).catch(done)

    }),

    it('Search - count only', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        c.events.count({'rank_level': [5], 'category': 'sports'})
            .then((results)=> {

                expect(_.keys(results.toDict())).toEqual([ 'count', 'top_rank', 'top_local_rank', 'top_aviation_rank', 'rank_levels', 'local_rank_levels', 'aviation_rank_levels', 'categories', 'labels' ])

                expect(results.toDict()['count']).toBeGreaterThan(10000)

                done()

            }).catch(done)

    }),

    it('Calendar', (done) => {

        let c = new Client({access_token: test_client_credentials_access_token})

        let options = {
            'active.gte': '2016-01-01',
            'active.lte': '2016-01-02',
            'country': 'CA',
            'top_events.limit': 1,
            'top_events.sort': ['rank']
        }

        c.events.calendar(options)
            .then((results)=> {

                let days = _.keyBy(results.toArray(), 'date')
                expect(_.keys(days)).toEqual(['2016-01-01', '2016-01-02'])

                done()

            }).catch(done)

    })
})