text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Using WARPLab (SISO configuration) to Transmit Bits Over a Wireless
% Channel .
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This matlab srcipt generates a bitstream, modulates the bitstream using
% DQPSK, transmits the modulated symbols over a wireless channel using
% WARPLab, and demodulates the received signal to obtain the
% transmitted bits. Bit error rate (BER) is computed by comparing the
% transmitted bitstream with the bitstream recovered at the receiver

% The specific steps implemented in this script are the following:

% 0. Initialization, define paramters, create pulse shaping filter, and
% create reference matrix for detection of preamble
% 1. Generate a random bit stream and map it to symbols
% 2. Modulate the symbols (map symbols to constellation points) and append
% preamble symbols
% 3. Upsample the modulated symbols with the appended preamble and filter
% using a pulse shaping filter
% 4. Upconvert from baseband to 5MHz to avoid radio DC attenuation
% 5. Transmit the signal over a wireless channel using WARPLab
% 6. Downconvert from 5MHz to baseband
% 7. Filter the received signal with a Matched Filter (matched to the pulse
% shaping filter), detect preamble, and downsample output of Matched Filter
% 8. Demodulate and recover the transmitted bitstream
% 9. Compute the Bit Error Rate (BER)

% Part of this code was adapted from Matlab's commdoc_mod and commdoc_rrc
% examples.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 0. Initialization, define paramters, create pulse shaping filter, and
% create reference matrix for detection of preamble
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define basic parameters
M = 4; % Size of signal constellation
k = log2(M); % Number of bits per symbol
nsamp = 8; % Oversampling rate or Number of samples per symbol

% Define parameters related to the pulse shaping filter and create the
% pulse shaping filter
% This pulse shaping filter is a Squared Root Raised Cosine (SRRC) filter
filtorder = 64; % Filter order
delay = filtorder/(nsamp*2); % Group delay (# of input samples). Group
% delay is the time between the input to the filter and the filter's peak
% response counted in number of input samples. In number of output samples
% the delay would be equal to 'delay*nsam'.
rolloff = 0.3; % Rolloff factor of filter
rrcfilter = rcosine(1,nsamp,'fir/sqrt',rolloff,delay); % Create SRRC filter

% Plot the filter's impulse response in a stem plot
figure; % Create new figure window.
stem(rrcfilter);
title('Raised Cosine Impulse Response');
xlabel('n (samples)'); ylabel('Amplitude');

% Define number of symbols to process, number of bits to process, and the
% preamble.
% The Warplab transmit buffer can store a maximum of 2^14 samples, the
% number of samples per symbol is equal 'nsam', and the SRRC filter delay
% in number of samples is equal to 'delay*nsam'. Consequently, the total
% number of symbols to be transmitted must be less than
% (2^14-200)/nsam-2*delay. We subtract extra 200 to account for jitter in
% sync trigger.
nsym = floor((2^14-200)/nsamp-2*delay);  % Number or symbols to transmit
preamble = [-1;-1;-1;1;-1;0;0;0;0;0;0;0;0]; % Preamble is a Barker sequence
                                            % modulated with BPSK
nsym_preamble = length(preamble); % number of symbols in preamble
nsym_payload = nsym-nsym_preamble;
nbits = floor(nsym_payload*k); % Number of bits to process

% Create a reference matrix used for detection of the preamble in the
% received signal. We will correlate the received signal with the reference
% matrix
preamble_upsamp = upsample(preamble,nsamp); % Upsample preamble
length_preamble_upsamp = length(preamble_upsamp);
corr_window = 300; % We expect to find the preamble within the first
                   % 300 received samples
reference_samples = zeros(corr_window,1); % Create reference vector.
reference_samples(1:length_preamble_upsamp) = preamble_upsamp;
                     % First samples of reference vector correspond to the
                     % preamble upsampled
reference_matrix = toeplitz(reference_samples,...
circshift(reference_samples(corr_window:-1:1),1));
         % Create reference matrix. The first column of the reference
         % matrix is equal to the reference_samples vector. The i-th column
         % of the reference matrix is equal to circular shift of the
         % reference samples vector, it is a shift down by i samples.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 1. Generate a random bit stream and map it to symbols
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create a random binary data stream as a column vector.
x = randint(nbits,1);

% Map bits in vector x into k-bit symbols
xsym = bi2de(reshape(x,k,length(x)/k).','left-msb');

% Stem plot of bits and symbols
% Plot first 40 bits in a stem plot.
figure;
subplot(2,1,1)
stem(x(1:40),'filled');
title('Random Bits');
xlabel('Bit Index'); ylabel('Binary Value');
% Plot first 40/k symbols in a stem plot.
subplot(2,1,2)
stem(xsym(1:40/k),'filled');
title('Random Bits Mapped to Symbols');
xlabel('Symbol Index'); ylabel('Integer Value');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2. Modulate the symbols (map symbols to constellation points) and append
% preamble symbols
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Modulate using DQPSK
ytx_mod = dpskmod(xsym,M);

% Append preamble
ytx_mod = [preamble;ytx_mod];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3. Upsample the modulated symbols with the appended preamble and filter
% using a pulse shaping filter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Upsample and apply square root raised cosine filter.
ytx_mod_filt = rcosflt(ytx_mod,1,nsamp,'filter',rrcfilter);

% Stem Plot of modulated symbols before and after Squared Root Raised
% Cosine (SRRC) filter
% Plots first 30 symbols.
% Plots I and Q in different windows
figure; % Create new figure window.
subplot(2,1,1)
stem([1:nsamp:nsamp*30],real(ytx_mod(1:30)));
hold
stem(real(ytx_mod_filt(1+delay*nsamp:1+30*nsamp+delay*nsamp)),'r');
title('I Signal');
xlabel('n (sample)'); ylabel('Amplitude');
legend('Before SRRC Filter','After SRRC Filter');
subplot(2,1,2)
stem([1:nsamp:nsamp*30],imag(ytx_mod(1:30)));
hold
stem(imag(ytx_mod_filt(1+delay*nsamp:1+30*nsamp+delay*nsamp)),'r');
title('Q Signal');
xlabel('n (sample)'); ylabel('Amplitude');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 4. Upconvert from baseband to 5MHz to avoid radio DC attenuation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
time = [0:1:length(ytx_mod_filt)-1]/40e6; % Sampling Freq. is 40MHz
ytx_mod_filt_up = ytx_mod_filt .* exp(sqrt(-1)*2*pi*5e6*time).';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5. Transmit the signal over a wireless channel using Warplab
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Follow the steps for transmission and reception of data using Warplab.
% These are the steps in the matlab script warplab_example_TxRx.m

% In this example the vector to transmit is the 'ytx_mod_filt' vector. The
% capture offset is zero.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.0. Initializaton and definition of parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Load some global definitions (packet types, etc.)
warplab_defines

% Create Socket handles and intialize nodes
[socketHandles, packetNum] = warplab_initialize;

% Separate the socket handles for easier access
% The first socket handle is always the magic SYNC
% The rest of the handles are the handles to the WARP nodes
udp_Sync = socketHandles(1);
udp_node1 = socketHandles(2);
udp_node2 = socketHandles(3);

% Define WARPLab parameters.
CaptOffset = 100; % Number of noise samples per Rx capture. In [0:2^14]
TxLength =length(ytx_mod_filt_up); % Length of transmission. In [0:2^14-1-CaptOffset]
TxMode = 0; % Transmission mode. In [0:1]
            % 0: Single Transmission
            % 1: Continuous Transmission. Tx board will continue
            % transmitting the vector of samples until the user manually
            % disables the transmitter.
CarrierChannel = 8; % Channel in the 2.4 GHz band. In [1:14]
Node1_Radio2_TxGain_BB = 3; % Tx Baseband Gain. In [0:3]
Node1_Radio2_TxGain_RF = 40; % Tx RF Gain. In [0:63]
Node2_Radio2_RxGain_BB = 12; % Rx Baseband Gain. In [0:31]
Node2_Radio2_RxGain_RF = 1; % Rx RF Gain. In [1:3]
% Note: For this experiment node 1 will be set as the transmitter and node
% 2 will be set as the receiver (this is done later in the code), hence,
% there is no need to define receive gains for node1 and there is no
% need to define transmitter gains for node2.
% For this experiment set CaptOffset to 100 to account for jitter in sync
% trigger.

% Download the WARPLab parameters to the WARP nodes.
% The nodes store the CaptOffset, TxLength, and TxMode parameters in
% registers defined in the WARPLab sysgen model. The nodes set radio
% related parameters CarrierChannel, TxGains, and RxGains, using the
% radio controller functions.
% The CaptOffset is a parameter that needs to be known at the receiver
% node; knowledge of CaptOffset is not required at the transmitter. For
% this exercise node 2 will be set as the receiver (this is done later in
% the code). Since CaptOffset is only required at the receiver we
% download the CaptOffset value only to the receiver node (node 2).
warplab_writeRegister(udp_node2,CAPT_OFFSET,CaptOffset);
% The TxLength and TxMode parameters need to be known at the transmitter;
% the receiver doesn't require knowledge of these parameters (the receiver
% will always capture 2^14 samples). For this exercise node 1 will be set as
% the transmitter (this is done later in the code). Since TxLength and
% TxMode are only required at the transmitter we download the TxLength and
% TxMode parameters only to the transmitter node (node 1).
warplab_writeRegister(udp_node1,TX_LENGTH,TxLength);
warplab_writeRegister(udp_node1,TX_MODE,TxMode);
% The CarrierChannel parameter must be downloaded to all nodes
warplab_setRadioParameter(udp_node1,CARRIER_CHANNEL,CarrierChannel);
warplab_setRadioParameter(udp_node2,CARRIER_CHANNEL,CarrierChannel);
% Node 1 will be set as the transmitter so download Tx gains to node 1.
warplab_setRadioParameter(udp_node1,RADIO2_TXGAINS,(Node1_Radio2_TxGain_RF + Node1_Radio2_TxGain_BB*2^16));
% Node 2 will be set as the receiver so download Rx gains to node 2.
warplab_setRadioParameter(udp_node2,RADIO2_RXGAINS,(Node2_Radio2_RxGain_BB + Node2_Radio2_RxGain_RF*2^16));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.1. Generate a vector of samples to transmit and send the samples to the
% WARP board (Sample Frequency is 40MHz)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Prepare some data to be transmitted

% Scale signal to transmit so that it spans [-1,1] range. We do this to
% use the full range of the DAC at the tranmitter
scale = 1 / max( [ max(real(ytx_mod_filt_up)) , max(imag(ytx_mod_filt_up)) ] );
ytx_mod_filt_up = scale*ytx_mod_filt_up;

Node1_Radio2_TxData = ytx_mod_filt_up.'; % Create a signal to transmit. Signal must be a
% row vector

% Download the samples to be transmitted
warplab_writeSMWO(udp_node1, RADIO2_TXDATA, Node1_Radio2_TxData);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.2. Prepare WARP boards for transmission and reception and send trigger to
% start transmission and reception (trigger is the SYNC packet)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following lines of code set node 1 as transmitter and node 2 as
% receiver; transmission and capture are triggered by sending the SYNC
% packet.

% Enable transmitter radio path in radio 2 in node 1 (enable radio 2 in
% node 1 as transmitter)
warplab_sendCmd(udp_node1, RADIO2_TXEN, packetNum);

% Enable transmission of node1's radio 2 Tx buffer (enable transmission
% of samples stored in radio 2 Tx Buffer in node 1)
warplab_sendCmd(udp_node1, [RADIO2TXBUFF_TXEN], packetNum);

% Enable receiver radio path in radio 2 in node 2 (enable radio 2 in
% node 2 as receiver)
warplab_sendCmd(udp_node2, RADIO2_RXEN, packetNum);

% Enable capture in node2's radio 2 Rx Buffer (enable radio 2 rx buffer in
% node 2 for storage of samples)
warplab_sendCmd(udp_node2, [RADIO2RXBUFF_RXEN], packetNum);

% Prime transmitter state machine in node 1. Node 1 will be
% waiting for the SYNC packet. Transmission from node 1 will be triggered
% when node 1 receives the SYNC packet.
warplab_sendCmd(udp_node1, TX_START, packetNum);

% Prime receiver state machine in node 2. Node 2 will be waiting
% for the SYNC packet. Capture at node 2 will be triggered when node 2
% receives the SYNC packet.
warplab_sendCmd(udp_node2, RX_START, packetNum);

% Send the SYNC packet
warplab_sendSync(udp_Sync);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.3. Read the received smaples from the Warp board
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read back the received samples (Read extra 100 to account for jitter in sync trigger)
[Node2_Radio2_RawRxData] = warplab_readSMRO(udp_node2, RADIO2_RXDATA,TxLength+CaptOffset+100);
% Process the received samples to obtain meaningful data
[Node2_Radio2_RxData,Node2_Radio2_RxOTR] = warplab_processRawRxData(Node2_Radio2_RawRxData);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.4. Reset and disable the boards
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set radio 2 Tx buffer in node 1 back to Tx disabled mode
warplab_sendCmd(udp_node1, RADIO2TXBUFF_TXDIS, packetNum);

% Disable the transmitter radio
warplab_sendCmd(udp_node1, RADIO2_TXDIS, packetNum);

% Let the receiver know that samples have been read and system is ready for
% a new capture
warplab_sendCmd(udp_node2, RX_DONEREADING, packetNum);

% Set radio 2 Rx buffer in node 2 back to Rx disabled mode
warplab_sendCmd(udp_node2, RADIO2RXBUFF_RXDIS, packetNum);

% Disable the receiver radio
warplab_sendCmd(udp_node2, RADIO2_RXDIS, packetNum);

% Close sockets
pnet('closeall');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 5.5. Plot the transmitted and received data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;
subplot(2,2,1);
plot(real(Node1_Radio2_TxData));
title('Tx Node 1 Radio 2 I');
xlabel('n (samples)'); ylabel('Amplitude');
axis([0 2^14 -1 1]); % Set axis ranges.
subplot(2,2,2);
plot(imag(Node1_Radio2_TxData));
title('Tx Node 1 Radio 2 Q');
xlabel('n (samples)'); ylabel('Amplitude');
axis([0 2^14 -1 1]); % Set axis ranges.
subplot(2,2,3);
plot(real(Node2_Radio2_RxData));
title('Rx Node 2 Radio 2 I');
xlabel('n (samples)'); ylabel('Amplitude');
axis([0 2^14 -1 1]); % Set axis ranges.
subplot(2,2,4);
plot(imag(Node2_Radio2_RxData));
title('Rx Node 2 Radio 2 Q');
xlabel('n (samples)'); ylabel('Amplitude');
axis([0 2^14 -1 1]); % Set axis ranges.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 6. Downconvert from 5MHz to baseband
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
time = [0:1:length(Node2_Radio2_RxData)-1]/40e6; % Sampling Freq. is 40MHz
yrx_bb = Node2_Radio2_RxData .* exp(-sqrt(-1)*2*pi*5e6*time);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 7. Filter the received signal with a Matched Filter (matched to the pulse
% shaping filter), detect preamble, and downsample output of Matched Filter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Store received samples as a column vector
yrx_bb = yrx_bb.';

% Matched filter: Filter received signal using the SRRC filter
yrx_bb_mf = rcosflt(yrx_bb,1,nsamp,'Fs/filter',rrcfilter);

% Correlate with the reference matrix to find preamble sequence
correlation = abs( (yrx_bb_mf(1:corr_window).') * reference_matrix );
preamble_start = find(correlation == max(correlation)); % Start of preamble
first_sample_index = preamble_start+length_preamble_upsamp; % Start of
                                         % first symbol after preamble

% Downsample output of Matched Filter
yrx_bb_mf_ds = yrx_bb_mf(first_sample_index:end);
yrx_bb_mf_ds = downsample(yrx_bb_mf_ds,nsamp);

% Slice symbols of interest (nsym_payload symbols were transmitted so if
% yrx_bb_mf_ds has more than nsym_payload elements the extra elements of the
% yrx_bb_mf_ds vector are due to the extra samples read from the Rx buffer
% and the extra samples added by the delay of the filters)
yrx_bb_mf_ds = yrx_bb_mf_ds(1:nsym_payload);

% Stem Plot of signal before Matched Filter, after Matched Filter, and
% after downsampling
% Plots first 30 symbols.
% Plots real and imaginary parts in different windows
figure; % Create new figure window.
subplot(2,1,1)
stem(real(yrx_bb(first_sample_index-(1+delay*nsamp):first_sample_index-(1+delay*nsamp)+30*nsamp)),'b');
hold
stem(real(yrx_bb_mf(first_sample_index:first_sample_index+30*nsamp)),'r');
stem([1:nsamp:nsamp*30],real(yrx_bb_mf_ds(1:30)),'k');
title('I Symbols');
xlabel('n (sample)'); ylabel('Amplitude');
legend('Before Matched Filter','After Matched Filter','After Downsample');
subplot(2,1,2)
stem(imag(yrx_bb(first_sample_index-(1+delay*nsamp):first_sample_index-(1+delay*nsamp)+30*nsamp)),'b');
hold
stem(imag(yrx_bb_mf(first_sample_index:first_sample_index+30*nsamp)),'r');
stem([1:nsamp:nsamp*30],imag(yrx_bb_mf_ds(1:30)),'k');
title('Q Symbols');
xlabel('n (sample)'); ylabel('Amplitude');

% Scatter Plot of received and transmitted constellation points
h = scatterplot(yrx_bb_mf_ds(1:end),1,0,'g.');
hold on;
scatterplot(ytx_mod(nsym_preamble+1:end),1,0,'k*',h);
title('Constellations');
legend('Received','Transmitted');
axis([-2 2 -2 2]); % Set axis ranges.
hold off;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 8. Demodulate and recover the transmitted bitstream
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Demodulate signal using DQPSK
zsym = dpskdemod(yrx_bb_mf_ds,M);

% Map Symbols to Bits
z = de2bi(zsym,'left-msb'); % Convert integers to bits.
% Convert z from a matrix to a vector.
z = reshape(z.',prod(size(z)),1);

% Plot first 80 transmitted bits and first 80 received bits in a stem plot
figure;
subplot(2,1,1)
stem(x(1:80),'filled');
title('Transmitted Bits');
xlabel('Bit Index'); ylabel('Binary Value');
subplot(2,1,2)
stem(z(1:80),'filled');
title('Received Bits');
xlabel('Bit Index'); ylabel('Binary Value');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 9. Compute the Bit Error Rate (BER)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Compare x and z to obtain the number of errors and the bit error rate
[number_of_errors,bit_error_rate] = biterr(x(3:length(z)),z(3:length(z)))
% We start comparing at three because the first two bits are are always
% lost in DQPSK. We compare until minlen because z may be shorter
% than x due to the jitter of the synch pulse.


text:
package com.antsoft.ant.manager.projectmanager;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.File;
import javax.swing.border.*;
import com.antsoft.ant.util.*;

/**
 * NewProject Dialog
 *
 * @author kim sang kyun
 */
public class ProjectDialog extends JDialog {
	static public final String FILE = "FILE";
	static public final String OK = "OK";
	static public final String CANCEL = "CANCEL";

  private JTextField nameTf, fileTf;
  private JTextArea descTa;
  private JButton fileBtn, okBtn, cancelBtn;
  private String projectFile;
  private String projectName;
  private JFrame parent;
  private boolean isOK = false;

  public ProjectDialog(JFrame frame, String title, boolean modal) {

    super(frame, title, modal);
    this.parent = frame;
    try  {
      jbInit();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public ProjectDialog() {
    this(null, "", true);
  }

  void jbInit() throws Exception {
		// register window event handler
		addWindowListener(WindowDisposer.getDisposer());
		addKeyListener(WindowDisposer.getDisposer());

    ActionListener al = new ActionEventHandler();
    DocumentListener dl = new DocumentEventHandler();

    //name panel
    JLabel nameLbl = new JLabel("Name");
    nameLbl.setPreferredSize(new Dimension(40,20));
    //nameLbl.setForeground(Color.black);
    nameTf = new JTextField(17);

    JPanel nameP = new JPanel(new FlowLayout(FlowLayout.LEFT));
    nameP.add(nameLbl);
    nameP.add(nameTf);

    //file panel
    JLabel fileLbl = new JLabel("File");
    fileLbl.setPreferredSize(new Dimension(40,20));
    //fileLbl.setForeground(Color.black);
    fileTf = new JTextField(17);
    fileTf.getDocument().addDocumentListener(dl);
    fileBtn = new JButton("..");
    fileBtn.setPreferredSize(new Dimension(20,20));
    fileBtn.setActionCommand(FILE);
    fileBtn.addActionListener(al);

    JPanel fileP = new JPanel(new FlowLayout(FlowLayout.LEFT));
    fileP.add(fileLbl);
    fileP.add(fileTf);
    fileP.add(fileBtn);

    //top panel
    Box box = Box.createVerticalBox();
    box.add(nameP);
    box.add(fileP);

    //desc panel
    JLabel descLbl = new JLabel("Description");
    //descLbl.setForeground(Color.black);

    descTa = new JTextArea();
    descTa.setMargin(new Insets(6, 6, 6, 6));
    JScrollPane pane = new JScrollPane(descTa);
    pane.setPreferredSize(new Dimension(230,170));

    JPanel descP = new JPanel(new BorderLayout());
    descP.add(descLbl, BorderLayout.NORTH);
    descP.add(pane, BorderLayout.CENTER);

    //button panel
    okBtn = new JButton("OK");
    okBtn.setEnabled(false);
    okBtn.setActionCommand(OK);
    okBtn.addActionListener(al);

    cancelBtn = new JButton("Cancel");
    cancelBtn.setActionCommand(CANCEL);
    cancelBtn.addActionListener(al);

    JPanel buttonP = new JPanel();
    buttonP.add(okBtn);
    buttonP.add(cancelBtn);

    JPanel mainP = new JPanel(new BorderLayout());
    TitledBorder border = new TitledBorder(new EtchedBorder(),"New Project");
    border.setTitleColor(Color.black);
    border.setTitleFont(FontList.regularFont);
    mainP.setBorder(border);
    mainP.add(box, BorderLayout.NORTH);
    mainP.add(descP, BorderLayout.CENTER);
    mainP.add(new JPanel(),BorderLayout.WEST);
    mainP.add(new JPanel(),BorderLayout.EAST);
    mainP.add(new JPanel(),BorderLayout.SOUTH);

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(mainP, BorderLayout.CENTER);
    getContentPane().add(buttonP,BorderLayout.SOUTH);
    getContentPane().add(new JPanel(),BorderLayout.WEST);
    getContentPane().add(new JPanel(),BorderLayout.EAST);

    setSize(310, 280);
    this.setResizable(false);

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension dlgSize = getSize();
    if (dlgSize.height > screenSize.height)
      dlgSize.height = screenSize.height;
    if (dlgSize.width > screenSize.width)
      dlgSize.width = screenSize.width;
    setLocation((screenSize.width - dlgSize.width) / 2,
                (screenSize.height - dlgSize.height) / 2);

  }

  public boolean isOK(){
    return this.isOK;
  }

  public void fileSelected(){
    FileDialog filedlg = new FileDialog(parent, "New Project");
    filedlg.setFile("*.apr");
    filedlg.setVisible(true);

    if (filedlg.getFile() != null && filedlg.getFile().endsWith(".apr")) {
      fileTf.setText(filedlg.getDirectory()+filedlg.getFile());
      if(fileTf.getText().endsWith("apr")) okBtn.setEnabled(true);
    }
  }

  public String getProjectFilePath(){
    return this.fileTf.getText();
  }

  public String getProjectName(){
    return this.nameTf.getText();
  }

  public String getComment(){
    String ret = descTa.getText();
    if(ret == null || ret.length() == 0) return null;
    else return ret;
  }

  class DocumentEventHandler implements DocumentListener{

    public void process(DocumentEvent e){
      if(fileTf.getText().endsWith("apr")) okBtn.setEnabled(true);
    }
    public void insertUpdate(DocumentEvent e){ process(e);  }
    public void changedUpdate(DocumentEvent e){ process(e); }
    public void removeUpdate(DocumentEvent e){ process(e); }
  }

  class ActionEventHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
      String cmd = e.getActionCommand();

      // We can use == because cmd is static
      if(cmd == FILE){
        fileSelected();
      }
      else if(cmd == OK){
        isOK = true;
        dispose();
      }
      else if(cmd == CANCEL ){
        isOK = false;
        dispose();
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package me.majiajie.http;

public class Test {

    private String name;

    private int id;

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

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


text:
describe('EventReaperService', function() {
    var q, scope;

    // mock dependencies
    var matrixService = {
        roomInitialSync: function(roomId, limit) {
            return {};
        }
    };

    var modelService = {
        removeRoom: function(roomId){},
        getRoom: function(roomId){return {};}
    };

    var eventHandlerService = {
        wipeDuplicateDetection: function(roomId) {},
        handleRoomInitialSync: function(room, response) {}
    };

    var recentsService = {
        BROADCAST_SELECTED_ROOM_ID: "BROADCAST_SELECTED_ROOM_ID"
    };

    // setup the dependencies
    beforeEach(function() {

        // reset test data

        // dependencies
        module(function ($provide) {
          $provide.value('matrixService', matrixService);
          $provide.value('modelService', modelService);
          $provide.value('recentsService', recentsService);
          $provide.value('eventHandlerService', eventHandlerService);
        });

        // tested service
        module('eventReaperService');
    });

    beforeEach(inject(function($q, $rootScope) {
        q = $q;
        scope = $rootScope;
    }));

    it('should not reap rooms if it is not enabled.', inject(
    function(eventReaperService) {
        eventReaperService.setEnabled(false);

        var roomId = "!reaper:matrix.org";

        var event = {
            content: {},
            room_id: roomId,
            event_id: "f",
            type: "m.room.message"
        };

        var eventsArray = [event];
        spyOn(modelService, "getRoom").and.callFake(function(roomId) {
            return {
                events: eventsArray
            }
        });

        spyOn(matrixService, "roomInitialSync").and.callFake(function() {
            return q.defer().promise;
        });

        for (var i=0; i< eventReaperService.MAX_EVENTS + 1; i++) {
            eventsArray.push(event);
            scope.$broadcast(eventHandlerService.MSG_EVENT, event, true);
            scope.$digest();
        }

        expect(matrixService.roomInitialSync).not.toHaveBeenCalled();
    }));

    it('should be able to force reap a room, even if it is not enabled.', inject(
    function(eventReaperService) {
        eventReaperService.setEnabled(false);

        var roomId = "!reaper:matrix.org";
        spyOn(modelService, "removeRoom");
        spyOn(eventHandlerService, "wipeDuplicateDetection");
        spyOn(eventHandlerService, "handleRoomInitialSync");
        spyOn(matrixService, "roomInitialSync").and.callFake(function() {
            var defer = q.defer();
            defer.resolve({
                data: {
                    state: [],
                    messages: [],
                    presence: []
                }
            });
            return defer.promise;
        });

        eventReaperService.reap(roomId);
        scope.$digest();

        expect(modelService.removeRoom).toHaveBeenCalledWith(roomId);
        expect(eventHandlerService.wipeDuplicateDetection).toHaveBeenCalledWith(roomId);
        expect(eventHandlerService.handleRoomInitialSync).toHaveBeenCalled();
    }));

    it('should not reap the room being viewed currently.', inject(
    function(eventReaperService) {
        eventReaperService.setEnabled(true);

        var roomId = "!reaper:matrix.org";
        scope.$broadcast(recentsService.BROADCAST_SELECTED_ROOM_ID, roomId);
        scope.$digest();

        var event = {
            content: {},
            room_id: roomId,
            event_id: "f",
            type: "m.room.message"
        };

        var eventsArray = [event];
        spyOn(modelService, "getRoom").and.callFake(function(roomId) {
            return {
                events: eventsArray
            }
        });

        spyOn(matrixService, "roomInitialSync").and.callFake(function() {
            return q.defer().promise;
        });

        for (var i=0; i< eventReaperService.MAX_EVENTS + 1; i++) {
            eventsArray.push(event);
            scope.$broadcast(eventHandlerService.MSG_EVENT, event, true);
            scope.$digest();
        }

        expect(matrixService.roomInitialSync).not.toHaveBeenCalled();
    }));

    it('should reap rooms with more than MAX_EVENTS events.', inject(
    function(eventReaperService) {
        eventReaperService.setEnabled(true);

        var roomId = "!reaper:matrix.org";
        scope.$broadcast(recentsService.BROADCAST_SELECTED_ROOM_ID, "!a:b.com");
        scope.$digest();

        var aevent = {
            event: {
                content: {},
                room_id: roomId,
                event_id: "f",
                type: "m.room.message"
            }
        };

        var aeventsArray = [aevent];
        spyOn(modelService, "getRoom").and.callFake(function(roomId) {
            return {
                aevents: aeventsArray
            }
        });

        spyOn(matrixService, "roomInitialSync").and.callFake(function() {
            return q.defer().promise;
        });

        for (var i=0; i< eventReaperService.MAX_EVENTS + 1; i++) {
            aeventsArray.push(aevent);
            scope.$broadcast(eventHandlerService.MSG_EVENT, aevent.event, true);
            scope.$digest();
        }

        expect(matrixService.roomInitialSync).toHaveBeenCalled();
    }));

    it('should not reap a room whilst a reap of that room is ongoing.', inject(
    function(eventReaperService) {
        var roomId = "!foo:bar";
        spyOn(matrixService, "roomInitialSync").and.callFake(function() {
            return q.defer().promise;
        });

        eventReaperService.reap(roomId);
        expect(matrixService.roomInitialSync).toHaveBeenCalled();
        eventReaperService.reap(roomId);
        expect(matrixService.roomInitialSync.calls.count()).toEqual(1);
    }));
});


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="view_vertical_margin">16dp</dimen>
    <dimen name="layout_padding">16dp</dimen>
    <dimen name="view_height">48dp</dimen>
    <dimen name="title_view_height">64dp</dimen>
    <dimen name="list_item_horizontal_margin">4dp</dimen>
    <dimen name="list_item_vertical_margin">4dp</dimen>
    <dimen name="list_item_height">64dp</dimen>

    </resources>


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
function registerCommands(context) {
    // https://css-tricks.com/snippets/javascript/get-url-variables/
    var getQueryVariable = function (query, variable) {
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
    };
    // Open command (used internally for browsing documentation pages)
    var disposableOpen = vscode.commands.registerCommand('solargraph._openDocument', (uriString) => {
        var uri = vscode.Uri.parse(uriString);
        var label = (uri.path == '/search' ? 'Search for ' : '') + getQueryVariable(uri.query, "query");
        vscode.commands.executeCommand('vscode.previewHtml', uri, vscode.ViewColumn.Two, label);
    });
    context.subscriptions.push(disposableOpen);
    // Open URL command (used internally for browsing documentation pages)
    var disposableOpenUrl = vscode.commands.registerCommand('solargraph._openDocumentUrl', (uriString) => {
        var uri = vscode.Uri.parse(uriString);
        var label = (uri.path == '/search' ? 'Search for ' : '') + getQueryVariable(uri.query, "query");
        vscode.commands.executeCommand('vscode.previewHtml', uri, vscode.ViewColumn.Two, label);
    });
    context.subscriptions.push(disposableOpenUrl);
    // Restart command
    var disposableRestart = vscode.commands.registerCommand('solargraph.restart', () => {
        restartLanguageServer().then(() => {
            vscode.window.showInformationMessage('Solargraph server restarted.');
        });
    });
    context.subscriptions.push(disposableRestart);
    // Search command
    var disposableSearch = vscode.commands.registerCommand('solargraph.search', () => {
        vscode.window.showInputBox({ prompt: 'Search Ruby documentation:' }).then(val => {
            if (val) {
                var uri = 'solargraph:/search?query=' + encodeURIComponent(val);
                vscode.commands.executeCommand('solargraph._openDocument', uri);
            }
        });
    });
    context.subscriptions.push(disposableSearch);
    // Check gem version command
    var disposableCheckGemVersion = vscode.commands.registerCommand('solargraph.checkGemVersion', () => {
        // languageClient.sendNotification('$/solargraph/checkGemVersion', { verbose: true });
        solargraph.verifyGemIsCurrent(solargraphConfiguration).then((result) => {
            if (result) {
                vscode.window.showInformationMessage('The Solargraph gem is up to date.');
            }
            else {
                notifyGemUpdate();
            }
        }).catch(() => {
            console.log('An error occurred checking the Solargraph gem version.');
        });
    });
    context.subscriptions.push(disposableSearch);
    // Build gem documentation command
    var disposableBuildGemDocs = vscode.commands.registerCommand('solargraph.buildGemDocs', () => {
        languageClient.sendNotification('$/solargraph/documentGems', { rebuild: false });
    });
    context.subscriptions.push(disposableBuildGemDocs);
    // Rebuild gems documentation command
    var disposableRebuildAllGemDocs = vscode.commands.registerCommand('solargraph.rebuildAllGemDocs', () => {
        languageClient.sendNotification('$/solargraph/documentGems', { rebuild: true });
    });
    context.subscriptions.push(disposableRebuildAllGemDocs);
}
exports.registerCommands = registerCommands;
//# sourceMappingURL=registration.js.map


text:
namespace chrono {

/// Forward definition (not needed in MSVC!?)
class type_constraint_tuple;
class ChPhysicsItem;

/// Interface for objects that generate contacts
/// One should inherit from ChContactable_1vars, ChContactable_2vars  etc. depending
/// on the number of ChVariable objects contained in the object (i.e. the variable chuncks
/// to whom the contact point position depends, also the variables affected by contact force).

class ChContactable  {
public:
        /// Tell if the object must be considered in collision detection
    virtual bool IsContactActive() = 0;

        /// Return the pointer to the surface material.
        /// Use dynamic cast to understand if this is a
        /// ChMaterialSurfaceDEM, ChMaterialSurfaceDVI or others.
        /// This function returns a reference to the shared pointer member
        /// variable and is therefore THREAD SAFE. ///***TODO*** use thread-safe shared ptrs and merge to GetMaterialSurface
    virtual ChSharedPtr<ChMaterialSurfaceBase>& GetMaterialSurfaceBase() =0;

        /// Get the absolute speed of point abs_point if attached to the
        /// surface.
    virtual ChVector<> GetContactPointSpeed(const ChVector<>& abs_point) = 0;

        /// ChCollisionModel might call this to get the position of the
        /// contact model (when rigid) and sync it
     virtual ChCoordsys<> GetCsysForCollisionModel() =0;

        /// Apply the force, expressed in absolute reference, applied in pos, to the
        /// coordinates of the variables. Force for example could come from a penalty model.
    virtual void ContactForceLoadResidual_F(const ChVector<>& F, const ChVector<>& abs_point,
                                ChVectorDynamic<>& R) = 0;

        /// This can be useful in some DEM code:
    virtual double GetContactableMass() = 0;

        /// This is only for backward compatibility. Note that in recent code
        /// the reference to the ChPhysicsItem should disappear.
        /// The ChPhysicsItem could be the ChContactable itself (ex. see the ChBody) or
        /// a container (ex. the ChMEsh, for ChContactTriangle)
    virtual ChPhysicsItem* GetPhysicsItem() = 0;
};

// Note that template T1 is the number of DOFs in the referenced ChVariable,
// for instance = 6 for rigid bodies, =3 for ChNodeXYZ, etc.

template <int T1>
class ChContactable_1vars : public ChContactable,  public ChLcpVariableTupleCarrier_1vars<T1> {
public:
    typedef ChLcpVariableTupleCarrier_1vars<T1> type_variable_tuple_carrier;
    typedef typename ChLcpVariableTupleCarrier_1vars<T1>::type_constraint_tuple type_constraint_tuple;

        /// Compute the jacobian(s) part(s) for this contactable item. For example,
        /// if the contactable is a ChBody, this should update the three corresponding 1x6 jacobian rows.
    virtual void ComputeJacobianForContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) =0;

        /// Compute the jacobian(s) part(s) for this contactable item, for rolling about N,u,v
        /// (used only for rolling friction DVI contacts)
    virtual void ComputeJacobianForRollingContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) {};
};

// Note that template T1 and T2 are the number of DOFs in the referenced ChVariable s,
// for instance 3 and 3 for an 'edge' betweeen two xyz nodes.

template <int T1, int T2>
class ChContactable_2vars : public ChContactable,  public ChLcpVariableTupleCarrier_2vars<T1,T2> {
public:
    typedef ChLcpVariableTupleCarrier_2vars<T1, T2> type_variable_tuple_carrier;
    typedef typename ChLcpVariableTupleCarrier_2vars<T1, T2>::type_constraint_tuple type_constraint_tuple;

        /// Compute the jacobian(s) part(s) for this contactable item. For example,
        /// if the contactable is a ChBody, this should update the corresponding 1x6 jacobian.
    virtual void ComputeJacobianForContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) =0;

        /// Compute the jacobian(s) part(s) for this contactable item, for rolling about N,u,v
        /// (used only for rolling friction DVI contacts)
    virtual void ComputeJacobianForRollingContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) {};
};

// Note that template T1 and T2 and T3 are the number of DOFs in the referenced ChVariable s,
// for instance 3 and 3 and 3 for a 'triangle face' betweeen two xyz nodes.

template <int T1, int T2, int T3>
class ChContactable_3vars : public ChContactable,  public ChLcpVariableTupleCarrier_3vars<T1,T2,T3> {
public:
    typedef ChLcpVariableTupleCarrier_3vars<T1, T2, T3> type_variable_tuple_carrier;
    typedef typename ChLcpVariableTupleCarrier_3vars<T1, T2, T3>::type_constraint_tuple type_constraint_tuple;

        /// Compute the jacobian(s) part(s) for this contactable item. For example,
        /// if the contactable is a ChBody, this should update the corresponding 1x6 jacobian.
    virtual void ComputeJacobianForContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) =0;

        /// Compute the jacobian(s) part(s) for this contactable item, for rolling about N,u,v
        /// (used only for rolling friction DVI contacts)
    virtual void ComputeJacobianForRollingContactPart(
                            const ChVector<>& abs_point,
                            ChMatrix33<>& contact_plane,
                            type_constraint_tuple& jacobian_tuple_N,
                            type_constraint_tuple& jacobian_tuple_U,
                            type_constraint_tuple& jacobian_tuple_V,
                            bool second) {};
};

}  // END_OF_NAMESPACE____

#endif


text:
@interface UIScrollView (ZFQLoadView)

@property (nonatomic,strong) ZFQLoadHeaderView *zfqHeaderView;
@property (nonatomic,strong) ZFQLoadFooterView *zfqFooterView;

- (void)addLoadHeaderWithRefreshingBlk:(void (^)())blk;

- (void)addLoadFooterWithRefreshingBlk:(void (^)())blk;

@end


text:
/* jslint node: true */
'use strict';

var React = require('react');
var ReactDom = require('react-dom');
var MapboxSocket = require('lightstream-socket').MapboxSocket;
var VelomaggCollection = require('./VelomaggCollection');
var MapQuadtree = require('../lib/MapQuadtree');
var BoundingBox = require('../lib/BoundingBox');
var L = require('mapbox.js');

var VeloMap = require('./VeloMap.jsx');

function MapFlow(config, i18n) {
  this.config = config;
  this.i18n = i18n;
}

MapFlow.prototype.setUp = function setUp() {
  this.velomagg = new VelomaggCollection();

  this._initializeMap();
  this._initializeQuadtree();
  this._createLayer();
  this._openSocket();
};

MapFlow.prototype._initializeMap = function _initializeMap() {
  var leaflet_bounds = L.latLngBounds(
    L.latLng(this.config.bounding_box.south_west[1],this.config.bounding_box.south_west[0]),
    L.latLng(this.config.bounding_box.north_east[1],this.config.bounding_box.north_east[0])
  );
  this.map = L.mapbox.map('map')
    .fitBounds(leaflet_bounds);
};

MapFlow.prototype._initializeQuadtree = function _initializeQuadtree() {
  var bounds = this._fixedQuadtreeBounds();
  var quadtree = this.quadtree = new MapQuadtree(bounds, 1);

  this.velomagg.on('add', function (model) {
    quadtree.addItem(model);
  });
};

MapFlow.prototype._fixedQuadtreeBounds = function _fixedQuadtreeBounds() {
  return new BoundingBox(
    this.config.bounding_box.south_west[0],
    this.config.bounding_box.south_west[1],
    this.config.bounding_box.north_east[0],
    this.config.bounding_box.north_east[1]);
};

MapFlow.prototype._createLayer = function _createLayer() {
  var mapElement = React.createElement(VeloMap, {
    quadtree: this.quadtree,
    map: this.map,
    config: this.config,
    i18n: this.i18n
  });
  ReactDom.render(mapElement, document.getElementById('map-component'));
};

MapFlow.prototype._openSocket = function _openSocket() {
  var options = {
    retry_interval: 5000
  };
  var socket = new MapboxSocket('ws://' + this.config.hostname + '/socket/', 'station', options);

  socket.on('opened', function () {
    socket.attachMap(this.map);
  }.bind(this));

  socket.on('new_items', function (station) {
    this.velomagg.set([station], { remove:false });
  }.bind(this));

  socket.on('error', function (error) {
    console.log('error in socket', error);
  });

  socket.on('closed', function () {
    console.log('socket has been closed');
  });

  socket.connect();
};

module.exports = MapFlow;


text:
model = models.Base.extend({
    schema: {
        name:       { type: 'Text', validators: ['required'] },
        country:    { type: 'Select', options: ['USA', 'China'], validators: ['required'] },
        created:    { type: 'Date', validators: ['required'] },
        location:   { type: 'Text' }
    }
});


text:
package com.aviary.android.feather.graphics;

import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

/**
 * Drawable used as overlay {@link Drawable} in conjunction with {@link OverlayGalleryCheckboxDrawable}.<br />
 * Create a circle drawable using radius and blur_size.
 *
 * @author alessandro
 *
 */
public class GalleryCircleDrawable extends Drawable {

	private Paint mPaint;
	private Paint mShadowPaint;
	final int mShadowOffset = 3;
	float mStrokeWidth = 5.0f;
	float mRadius, mOriginalRadius;
	float centerX, centerY;

	/**
	 * Instantiates a new gallery circle drawable.
	 *
	 * @param radius
	 *           Radius of the circle
	 * @param blur_size
	 *           blur size, if > 0 create a blur mask around the circle
	 */
	public GalleryCircleDrawable( float radius, int blur_size ) {
		super();

		mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
		mPaint.setStrokeWidth( mStrokeWidth );
		mPaint.setStyle( Paint.Style.STROKE );
		mPaint.setColor( Color.WHITE );

		mShadowPaint = new Paint( mPaint );
		mShadowPaint.setColor( Color.BLACK );

		update( radius, blur_size );
	}

	/**
	 * Sets the stroke width.
	 *
	 * @param value
	 *           the new stroke width
	 */
	public void setStrokeWidth( float value ) {
		mStrokeWidth = value;
		mPaint.setStrokeWidth( mStrokeWidth );
		invalidateSelf();
	}

	/**
	 * Update.
	 *
	 * @param radius
	 *           the radius
	 * @param blur_size
	 *           the blur_size
	 */
	public void update( float radius, int blur_size ) {
		mOriginalRadius = radius;
		if ( blur_size > 0 )
			mPaint.setMaskFilter( new BlurMaskFilter( blur_size, Blur.NORMAL ) );
		else
			mPaint.setMaskFilter( null );
		invalidateSelf();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
	 */
	@Override
	public void draw( Canvas canvas ) {
		canvas.drawCircle( centerX, centerY + mShadowOffset, mRadius, mShadowPaint );
		canvas.drawCircle( centerX, centerY, mRadius, mPaint );
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect)
	 */
	@Override
	protected void onBoundsChange( Rect rect ) {
		super.onBoundsChange( rect );
		invalidateSelf();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#invalidateSelf()
	 */
	@Override
	public void invalidateSelf() {
		super.invalidateSelf();
		invalidate();
	}

	/**
	 * Invalidate.
	 */
	protected void invalidate() {
		Rect rect = getBounds();
		int minSize = Math.max( 1, Math.min( rect.width(), rect.height() ) );
		mRadius = ( (float) minSize * mOriginalRadius ) / 2;
		centerX = rect.centerX();
		centerY = rect.centerY();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#getOpacity()
	 */
	@Override
	public int getOpacity() {
		return PixelFormat.TRANSLUCENT;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#setAlpha(int)
	 */
	@Override
	public void setAlpha( int alpha ) {}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
	 */
	@Override
	public void setColorFilter( ColorFilter cf ) {}
}


text:
FROM ubuntu:latest

MAINTAINER Raymond Barbiero <raymond.barbiero.dev@gmail.com>

ENV DEBIAN_FRONTEND noninteractive
ENV NOKOGIRI_USE_SYSTEM_LIBRARIES 1

# Nokogiri dependencies
RUN true \
 && apt-get update \
 && apt-get install -qy --force-yes git ruby ruby-dev build-essential \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN true \
 && apt-get update \
 && apt-get install -qy libxslt1-dev libxml2-dev libssl-dev libyaml-dev \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN true \
 && apt-get update \
 && apt-get install -qy --no-install-recommends openjdk-8-jdk openjdk-8-jre \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN true \
 && apt-get update \
 && apt-get install -qy --no-install-recommends curl\
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN curl -sL https://services.gradle.org/distributions/gradle-5.6.4-bin.zip -o gradle-5.6.4.zip \
 && unzip -d /usr/share gradle-5.6.4.zip \
 && ln -s /usr/share/gradle-5.6.4/bin/gradle /usr/bin/gradle \
 && gradle --version \
 && rm gradle-5.6.4.zip

RUN true \
 && apt-get update \
 && apt-get install -qy vim curl lsof libxml2 libxml2-dev pkg-config \
 && apt-get clean \
 && gem install bundler nokogiri \
 && rm -rf /var/lib/apt/lists/*

RUN true \
 && git clone https://github.com/jenkinsci/job-dsl-plugin.git /jdsl \
 && cd /jdsl \
 && gradle oneJar

ENV DSL_JAR "/jdsl/job-dsl-core/build/libs/job-dsl-core-*-standalone.jar"

ENV APP_HOME /app
ENV HOME /root
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
COPY Gemfile* $APP_HOME/
RUN bundle config --global silence_root_warning 1 \
 && bundle install

# Upload source
COPY . $APP_HOME

# Start server
ENV PORT 3000
EXPOSE 3000

VOLUME ["/var/www/uploads"]
CMD ["ruby", "server.rb"]


text:
<?php
/**
 * The config information is passed to the relevant components by the
 * ServiceManager. The controllers section provides a list of all the
 * controllers provided by the module.
 *
 * Within the view_manager section, we add our view directory to the
 * TemplatePathStack configuration.
 *
 * @return array
 */
namespace Authentication;

return array(

    'controllers' => array(
        'invokables' => array(
            'Authentication\Controller\Dashboard' =>
                'Authentication\Controller\DashboardController',
        ),
        'factories' => array(
            'Authentication\Controller\Authentication' =>
                    'Authentication\Services\AuthControllerFactory',
        ),
    ),

    'router' => array(
        'routes' => array(

            'login' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/login[/:action]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Authentication\Controller',
                        'controller'    => 'Authentication\Controller\Authentication',
                        'action'        => 'login',
                    ),
                ),
            ),

            'dashboard' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/dashboard[/:action]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Authentication\Controller',
                        'controller'    => 'Authentication\Controller\Dashboard',
                        'action'        => 'index',
                    ),
                ),
            ),

        ),
    ),

    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',

        'template_path_stack'   => array(
            __DIR__ . '/../view',
        ),

    ),

    'service_manager' => array(
        'factories' => array(

            //neccessary for using authentication in ViewHelper and Controller
            'Zend\Authentication\AuthenticationService'       =>
                'Authentication\Services\AuthService',
            'Authentication\Services\FormFactory'   =>
                'Authentication\Services\FormFactory',
            'Authentication\Services\SessionService'   =>
                'Authentication\Services\SessionService',
            'Authentication\Services\AuthOptionsService'   =>
                'Authentication\Services\AuthOptionsService',
            'Authentication\Services\AuthAdapterService'   =>
                'Authentication\Services\AuthAdapterService',
            'Zend\Session\SessionManager' => 'Zend\Session\Service\SessionManagerFactory',
            'Zend\Session\Config\ConfigInterface' => 'Zend\Session\Service\SessionConfigFactory',

        ),
    ),

    'translator' => array(
        'translation_file_patterns' => array(
            array(
                'type'          => 'gettext',
                'base_dir'      => __DIR__ . '/../language',
                'pattern'       => '%s.mo',
                'text_domain'   => 'Auth',
            ),
             array(
                'type'        => 'phparray',
                'base_dir'    => __DIR__ . '/../resources/languages',
                'pattern'     => '%s.php',

             ),
        ),

    ),

    //Doctrine Authentication provided by DoctrineModule\Options\Authentication
    //identity class => performing authentication ; this has to be done
    //identity_property => username or email
    //credential_property => password
    'doctrine' => array(
        'driver' => array(
            __NAMESPACE__ . '_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(
                    __DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
           ),
           'orm_default' => array(
               'drivers' => array(
                __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
               )
           )
        ),
        'authentication' => array(
            'orm_default' => array(
                'object_manager' => 'Doctrine\ORM\EntityManager',
                'identity_class' => 'User\Entity\User',
                'identity_property' => 'username',
                'credential_property' => 'password',
            ),
        ),
    ),

);


text:
package com.blazebit.persistence.impl.function.datetime.quarter;

/**
 *
 * @author Jan-Willem Gmelig Meyling
 * @since 1.4.0
 */
public class AccessQuarterFunction extends QuarterFunction {

    public AccessQuarterFunction() {
        super("datepart('q', ?1)");
    }
}


text:
import contextlib

from oslo_config import cfg
from oslo_db import api as oslo_db_api
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import session
from oslo_utils import uuidutils
from sqlalchemy import exc

from neutron_lib.common import exceptions as n_exc
from neutron_lib.db import common_db_mixin

_FACADE = None

MAX_RETRIES = 10
is_deadlock = lambda e: isinstance(e, db_exc.DBDeadlock)
retry_db_errors = oslo_db_api.wrap_db_retry(
    max_retries=MAX_RETRIES,
    retry_on_request=True,
    exception_checker=is_deadlock
)

def _create_facade_lazily():
    global _FACADE

    if _FACADE is None:
        _FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True)

    return _FACADE

def get_engine():
    """Helper method to grab engine."""
    facade = _create_facade_lazily()
    return facade.get_engine()

def dispose():
    # Don't need to do anything if an enginefacade hasn't been created
    if _FACADE is not None:
        get_engine().pool.dispose()

def get_session(autocommit=True, expire_on_commit=False, use_slave=False):
    """Helper method to grab session."""
    facade = _create_facade_lazily()
    return facade.get_session(autocommit=autocommit,
                              expire_on_commit=expire_on_commit,
                              use_slave=use_slave)

@contextlib.contextmanager
def autonested_transaction(sess):
    """This is a convenience method to not bother with 'nested' parameter."""
    try:
        session_context = sess.begin_nested()
    except exc.InvalidRequestError:
        session_context = sess.begin(subtransactions=True)
    finally:
        with session_context as tx:
            yield tx

# Common database operation implementations
def get_object(context, model, **kwargs):
    with context.session.begin(subtransactions=True):
        return (common_db_mixin.model_query(context, model)
                .filter_by(**kwargs)
                .first())

def get_objects(context, model, **kwargs):
    with context.session.begin(subtransactions=True):
        return (common_db_mixin.model_query(context, model)
                .filter_by(**kwargs)
                .all())

def create_object(context, model, values):
    with context.session.begin(subtransactions=True):
        if 'id' not in values:
            values['id'] = uuidutils.generate_uuid()
        db_obj = model(**values)
        context.session.add(db_obj)
    return db_obj.__dict__

def _safe_get_object(context, model, id):
    db_obj = get_object(context, model, id=id)
    if db_obj is None:
        raise n_exc.ObjectNotFound(id=id)
    return db_obj

def update_object(context, model, id, values):
    with context.session.begin(subtransactions=True):
        db_obj = _safe_get_object(context, model, id)
        db_obj.update(values)
        db_obj.save(session=context.session)
    return db_obj.__dict__

def delete_object(context, model, id):
    with context.session.begin(subtransactions=True):
        db_obj = _safe_get_object(context, model, id)
        context.session.delete(db_obj)


text:
using System;
using System.Collections.Generic;
using System.Data;

namespace Emigrace.Core.Database.Generator
{
	/// <summary>
	///
	/// </summary>
	/// <typeparam name="T"></typeparam>
	class Switch<T>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="Switch{T}" /> class.
		/// </summary>
		/// <param name="o">The o.</param>
		public Switch(T o)
		{
			Object = o;
		}

		/// <summary>
		/// Gets the object.
		/// </summary>
		/// <value>
		/// The object.
		/// </value>
		public T Object { get; private set; }
	}

	/// <summary>
	///
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <typeparam name="R"></typeparam>
	class Switch<T, R> : Switch<T>
	{
		public Switch(T o) :
			base(o)
		{
		}
		/// <summary>
		/// Gets a value indicating whether this instance has value.
		/// </summary>
		/// <value>
		///   <c>true</c> if this instance has value; otherwise, <c>false</c>.
		/// </value>
		public bool HasValue { get; private set; }
		/// <summary>
		/// Gets the value.
		/// </summary>
		/// <value>
		/// The value.
		/// </value>
		public R Value { get; private set; }

		/// <summary>
		/// Sets the specified value.
		/// </summary>
		/// <param name="value">The value.</param>
		public void Set(R value)
		{
			Value = value;
			HasValue = true;
		}

		//public static operator implicit R (Switch<T, R> @switch)
		//{
		//    return @switch.Value;
		//}

		internal object Case(string p, Func<string, Rule> func)
		{
			throw new NotImplementedException();
		}
	}

	/// <summary>
	///
	/// </summary>
	static class SwitchExtensions
	{
		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static Switch<T> Case<T>(this Switch<T> @switch, T @case, Action<T> @do)
		{
			return Case(@switch, @case, @do, false);
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <param name="fallThrough">if set to <c>true</c> [fall through].</param>
		/// <returns></returns>
		public static Switch<T> Case<T>(this Switch<T> @switch, T @case, Action<T> @do, bool fallThrough)
		{
			return Case(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), @do, fallThrough);
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static Switch<T> Case<T>(this Switch<T> @switch, Func<T, bool> @case, Action<T> @do)
		{
			return Case(@switch, @case, @do, false);
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <param name="fallThrough">if set to <c>true</c> [fall through].</param>
		/// <returns></returns>
		public static Switch<T> Case<T>(this Switch<T> @switch, Func<T, bool> @case, Action<T> @do, bool fallThrough)
		{
			if (@switch == null)
			{
				return null;
			}
			else if (@case(@switch.Object))
			{
				@do(@switch.Object);
				return fallThrough ? @switch : null;
			}

			return @switch;
		}

		/// <summary>
		/// Defaults the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="do">The do.</param>
		public static void Default<T>(this Switch<T> @switch, Action<T> @do)
		{
			if (@switch != null)
			{
				@do(@switch.Object);
			}
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, T @case, R result)
		{
			return Case<T, R>(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), r => result);
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, T @case, Func<T, R> @do)
		{
			return Case<T, R>(@switch, x => EqualityComparer<T>.Default.Equals(x, @case), @do);
		}

		/// <summary>
		/// Cases the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="case">The case.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static Switch<T, R> Case<T, R>(this Switch<T, R> @switch, Func<T, bool> @case, Func<T, R> @do)
		{
			if (!@switch.HasValue && @case(@switch.Object))
			{
				@switch.Set(@do(@switch.Object));
			}

			return @switch;
		}

		/// <summary>
		/// Defaults the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static R Default<T, R>(this Switch<T, R> @switch, Func<T, R> @do)
		{
			if (!@switch.HasValue)
			{
				@switch.Set(@do(@switch.Object));
			}

			return @switch.Value;
		}

		/// <summary>
		/// Defaults the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="do">The do.</param>
		/// <returns></returns>
		public static R Default<T, R>(this Switch<T, R> @switch, Func<R> @do)
		{
			if (!@switch.HasValue)
				@switch.Set(@do());
			return @switch.Value;
		}

		/// <summary>
		/// Defaults the specified switch.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="R"></typeparam>
		/// <param name="switch">The switch.</param>
		/// <param name="result">The result.</param>
		/// <returns></returns>
		public static R Default<T, R>(this Switch<T, R> @switch, R result)
		{
			if (!@switch.HasValue)
				@switch.Set(result);
			return @switch.Value;
		}
	}
}


text:
layout: default
---

    {% if page.reading_time %}

~
        {% capture words %}
          {{ content | number_of_words | minus: 180 }}
        {% endcapture %}
        {% unless words contains "-" %}
          {{ words | plus: 180 | divided_by: 180 | append: " min" }}
        {% endunless %}

    {% endif %}

        {% if page.thumb %}

        {% endif %}

{{ page.title }}

        {{ content }}

        {% if page.date %}

Date

            {{ page.date | date: "%B %-d, %Y" }}

        {% endif %}
        {% if page.author %}

Author

            {{ page.author }}

        {% endif %}
        {% if page.show_categories %}

Categories

                {% for category in page.categories %}
                    {{ category | capitalize }}
                {% endfor %}

        {% endif %}

    {% include share.html %}
    {% include disqus.html %}


text:
package com.jlj.dao.imp;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.jlj.dao.IBgmusicDao;
import com.jlj.model.Bgmusic;
@Component("bgmusicDao")
public class BgmusicDaoImp implements IBgmusicDao  {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	//保存一条记录
	public void save(Bgmusic bgmusic) {
		this.hibernateTemplate.save(bgmusic);
	}

	//删除一条记录
	public void delete(Bgmusic bgmusic) {
		this.hibernateTemplate.delete(bgmusic);
	}
	//根据ID删除一条记录
	public void deleteById(int id) {
		this.hibernateTemplate.delete(this.loadById(id));
	}

	//修改一条记录
	public void update(Bgmusic bgmusic) {
		this.hibernateTemplate.update(bgmusic);
	}

	//根据hql语句、条件、条件值修改某些记录
	public void updateByHql(final String hql,final String[] paramNames,final Object[] values) {
		this.hibernateTemplate.execute(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				for (int i = 0; i < paramNames.length; i++) {
					query.setParameter(paramNames[i], values[i]);
				}
				query.executeUpdate();
				return null;
			}

		});
	}

	//获得所有记录
	public List<Bgmusic> getBgmusics() {
		return this.hibernateTemplate.loadAll(Bgmusic.class);
	}

	//根据hql语句来查询所有记录
	public List<Bgmusic> queryList(String queryString) {
		return this.hibernateTemplate.find(queryString);
	}

	//根据hql、条件值查询某些记录
	public List<Bgmusic> getObjectsByCondition(String queryString, Object[] p) {
		return this.hibernateTemplate.find(queryString,p);
	}

	//根据hql语句、条件、条件值查询某些记录
	public List<Bgmusic> queryList(String queryString, String[] paramNames,
			Object[] values)
	{
		List list =  this.hibernateTemplate.findByNamedParam(queryString, paramNames, values);
		return list;
	}

	//根据hql、id列表查询某些记录
	public List<Bgmusic> getObjectsByIdList(final String hql,final List<Integer> idList) {
		return this.hibernateTemplate.executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				query.setParameterList("idList", idList);
				return query.list();
			}

		});
	}

	//根据hql语句、条件值、分页查询某些记录
	public List<Bgmusic> pageList(final String queryString,final Object[] p,final Integer page,
			final Integer size) {
		return this.hibernateTemplate.executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(queryString);
				if(p!=null&&p.length>0){
					for (int i = 0; i < p.length; i++) {
						query.setParameter(i, p[i]);
					}
				}
				if(page!=null&&page>0&&size!=null&&size>0){
					query.setFirstResult((page-1)*size).setMaxResults(size);
				}
				return query.list();
			}

		});
	}

	//根据hql、条件值获得一个唯一值
	public int getUniqueResult(final String queryString,final Object[] p) {
		Session session=this.hibernateTemplate.getSessionFactory().getCurrentSession();
		Query query= session.createQuery(queryString);
		if(p!=null&&p.length>0){
			for (int i = 0; i < p.length; i++) {
				query.setParameter(i, p[i]);
			}
		}
		Object obj=query.uniqueResult();
		return ((Long)obj).intValue();

	}

	//根据id查询一条记录
	public Bgmusic loadById(int id) {
		return (Bgmusic) this.hibernateTemplate.load(Bgmusic.class, id);
	}

	//根据hql语句、条件、值来查询一条记录
	public Bgmusic queryByNamedParam(String queryString, String[] paramNames,
			Object[] values) {
		List list=this.hibernateTemplate.findByNamedParam(queryString, paramNames, values);
		return list.size()>0?(Bgmusic)list.get(0):null;
	}

	//根据hql语句、条件值来查询是否存在该记录
	public boolean checkClientExistsWithName(String queryString, Object[] p) {
		List list =  this.hibernateTemplate.find(queryString,p);
		return list.size()>0 ? true : false;
	}

}


text:
package com.amazonaws.services.medialive.model;

import javax.annotation.Generated;

/**
 * Maximum bitrate in megabits per second
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ReservationMaximumBitrate {

    MAX_10_MBPS("MAX_10_MBPS"),
    MAX_20_MBPS("MAX_20_MBPS"),
    MAX_50_MBPS("MAX_50_MBPS");

    private String value;

    private ReservationMaximumBitrate(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ReservationMaximumBitrate corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ReservationMaximumBitrate fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ReservationMaximumBitrate enumEntry : ReservationMaximumBitrate.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * Simple example how to invoke Nashorn JavaScript engine from Java 8
 * @author Pavel Janecka
 */
public class NashornExample {

    public NashornExample() throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("print('Hello World!');");
    }

    public static void main(String[] args) {
        try {
            new NashornExample();
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.hive.util;

import com.google.common.collect.AbstractIterator;
import io.airlift.units.DataSize;
import io.prestosql.orc.OrcDataSource;
import io.prestosql.orc.OrcPredicate;
import io.prestosql.orc.OrcReader;
import io.prestosql.orc.OrcRecordReader;
import io.prestosql.spi.Page;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.type.Type;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static io.prestosql.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static io.prestosql.orc.OrcReader.INITIAL_BATCH_SIZE;
import static io.prestosql.plugin.hive.HiveErrorCode.HIVE_WRITER_DATA_ERROR;
import static java.util.Objects.requireNonNull;
import static org.joda.time.DateTimeZone.UTC;

public class TempFileReader
        extends AbstractIterator<Page>
{
    private final int columnCount;
    private final OrcRecordReader reader;

    public TempFileReader(List<Type> types, OrcDataSource dataSource)
    {
        requireNonNull(types, "types is null");
        this.columnCount = types.size();

        try {
            OrcReader orcReader = new OrcReader(
                    dataSource,
                    new DataSize(1, MEGABYTE),
                    new DataSize(8, MEGABYTE),
                    new DataSize(16, MEGABYTE));

            Map<Integer, Type> includedColumns = new HashMap<>();
            for (int i = 0; i < types.size(); i++) {
                includedColumns.put(i, types.get(i));
            }

            reader = orcReader.createRecordReader(
                    includedColumns,
                    OrcPredicate.TRUE,
                    UTC,
                    newSimpleAggregatedMemoryContext(),
                    INITIAL_BATCH_SIZE);
        }
        catch (IOException e) {
            throw new PrestoException(HIVE_WRITER_DATA_ERROR, "Failed to read temporary data");
        }
    }

    @Override
    protected Page computeNext()
    {
        try {
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedIOException();
            }

            int batchSize = reader.nextBatch();
            if (batchSize <= 0) {
                return endOfData();
            }

            Block[] blocks = new Block[columnCount];
            for (int i = 0; i < columnCount; i++) {
                blocks[i] = reader.readBlock(i).getLoadedBlock();
            }
            return new Page(batchSize, blocks);
        }
        catch (IOException e) {
            throw new PrestoException(HIVE_WRITER_DATA_ERROR, "Failed to read temporary data");
        }
    }
}


text:
/*
 * This program checks if a string has duplicate characters.
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<assert.h>

/*
 * Maximum number of characters possible in 'char' in
 * C-programming language
 */
#define NUM_POSSIBLE_CHARACTERS    (1 << (sizeof(char) * 8))

/*
 * This function partitions the array around a 'pivot' element
 * and returns the index of the pivot element. This functionu
 * uses the element at index 'high' as the pivot.
 */
int partition (char* ch, int low, int high)
{
    char temp, pivot;
    int i, pindex;

    /*
     * Set 'pivot' as the element at index 'high' in the array
     */
    pivot = ch[high];

    pindex = low;
    for (i = low; i < high; ++i) {

        /*
         * If the array elemnt is less than pivot element
         * then move the element to the left of the pivot
         */
        if (pivot > ch[i]) {
            temp = ch[i];
            ch[i] = ch[pindex];
            ch[pindex] = temp;
            ++pindex;
        }
    }

    /*
     * At this point all elements less than 'pivot' are present to
     * the left of 'pindex'. So swap and move the element at 'high'
     * to index 'pindex'
     */
    temp = ch[high];
    ch[high] = ch[pindex];
    ch[pindex] = temp;

    /*
     * Return the partition index to the quick sort routine
     */
    return(pindex);
}

/*
 * This function sorts a character array from indicies 'low' to
 * 'high' in ascending order using quick sort.
 */
void quicksort (char* ch, int low, int high)
{
    int partition_index;

    /*
     * If array is NULL or 'low' or 'high' are less than zero, then
     * there is no need to sory the array. So return.
     */
    if (!ch || (low < 0) || (high < 0)) {
        return;
    }

    /*
     * If 'low' is less than 'high', partition the array using
     * and recursively sory the parts around the partition index
     * using quick sort
     */
    if (low < high) {
        int partition_index = partition(ch, low, high);
        quicksort(ch, low, partition_index - 1);
        quicksort(ch, partition_index + 1, high);
    }
}

/*
 * This function checks if a characte string has duplicate characters. If the
 * character string has duplicate characters, then this function returns 'true'
 * otherwise this function returns false'. This function uses the following
 * approach to find if there are duplicate characters in a string:-
 * 1. Sort the string using quick sort.
 * 2. Compare the consecutive characters in the character array to find
 *    if they are equal. In case they are equal return 'true'.
 * 3. If we reach towards the end of the function, then return 'false' as
 *    here are no duplicate characters in the string.
 * The time complexity of this function is O(n*log(n)), where 'n' is the
 * number of characters in either string. The time complexity of the
 * function depends on the time taken by quick sort which could be O(n^2)
 * in worst case.
 * The space complexity of this function is O(1).
 */
bool check_if_a_str_has_duplicate_chars_v1 (char* ch)
{
    int len, i, j;

    /*
     * If the string is NULL or its length is zero, then return
     * 'false'
     */
    if (!ch || !strlen(ch)) {
        return(false);
    }

    len = strlen(ch);

    /*
     * Sort the characters of the string using quicksort
     */
    quicksort(ch, 0, len -1);

    /*
     * Iterate through the character array to find if any of the
     * consecutive characters are same. IF so, then return 'true'.
     */
    for (i = 0; i < (len - 1); ++i) {

        /*
         * If the consecutive characters are same, then return 'true'
         */
        if (ch[i] == ch[i+1]) {
            return(true);
        }
    }

    /*
     * Return 'false' if no duplicate characters are found
     */
    return(false);
}

/*
 * This function checks if a characte string has duplicate characters. If the
 * character string has duplicate characters, then this function returns 'true'
 * otherwise this function returns false'. This function uses the following
 * approach to find if there are duplicate characters in a string:-
 * 1. Iterate over the length of the string to see if there exists another
 *    another character which same as the character under test. If so,
 *    then return 'true'.
 * The time complexity of this function is O(n^2), where 'n' is the
 * number of characters in either string.
 * The space complexity of this function is O(1).
 */
bool check_if_a_str_has_duplicate_chars_v2 (char* ch)
{
    int len, i, j;

    /*
     * If the string is NULL or its length is zero, then return
     * 'false'
     */
    if (!ch || !strlen(ch)) {
        return(false);
    }

    len = strlen(ch);

    /*
     * For a given character in the array, check if there are any characters
     * on the right which are same as the current character.
     */
    for (i = 0; i < (len - 1); ++i) {
        for (j = i + 1; j < len; ++j) {

            /*
             * If the ith character is same as the jth character, then
             * return true, as a duplicate character exists
             */
            if (ch[i] == ch[j]) {
                return(true);
            }
        }
    }

    /*
     * Return 'false' if no duplicate characters are found
     */
    return(false);
}

/*
 * This function checks if a characte string has duplicate characters. If the
 * character string has duplicate characters, then this function returns 'true'
 * otherwise this function returns false'. This function uses the following
 * approach to find if there are duplicate characters in a string:-
 * 1. Define a count array to record the if a particular character has been
 *    found in the character array previously. Initialize this array to 0.
 * 2. Iterate over the character and map the characters into the cout array
 * 3. If the mapped character in the count array is zero, then increment the
 *    array entry by one otherwise we this mapped entry in the count array
 *    is a duplicate character. Return 'true', from this function.
 * 4. If we reach towards the end of the function, then return 'false' as
 *    here are no duplicate characters in the string.
 * The time complexity of this function is O(n), where 'n' is the
 * number of characters in either string sinze we iterate through the
 * character array once.
 * The space complexity of this function is O(m) where 'm' is the number
 * of characters suported by the programming language.
 */
bool check_if_a_str_has_duplicate_chars_v3 (char* ch)
{
    int len, i;
    int count[NUM_POSSIBLE_CHARACTERS];
    int mapped_char;

    /*
     * If the string is NULL or its length is zero, then return
     * 'false'
     */
    if (!ch || !strlen(ch)) {
        return(false);
    }

    len = strlen(ch);

    /*
     * Set all elements of the count array to be zero
     */
    memset(count, 0, sizeof(int) * NUM_POSSIBLE_CHARACTERS);

    /*
     * Iterate over the entire array and map the characters of the string
     * into the count array
     */
    for (i = 0; i < len; ++i) {

        /*
         * The mapped character is the addition of the ascii value of the
         * character and the helf of the maximum number of characters in the
         * programming language set.
         */
        mapped_char = ch[i] + NUM_POSSIBLE_CHARACTERS / 2;

        /*
         * If the value of the count array in the mapped character slot is
         * non-zero, then we have found a duplicate character. Return 'true'
         */
        if (count[mapped_char]) {
            return(true);
        } else {

            /*
             * Increment the count array for the mapped character
             */
            count[mapped_char]++;
        }
    }

    /*
     * Return 'false' if no duplicate characters are found
     */
    return(false);
}

int main ()
{
    /*
     * Test 0: Test with a NULL string. This should not be character array
     *         having duplicate characters
     */
    char* str0 = NULL;
    assert(false == check_if_a_str_has_duplicate_chars_v1(str0));
    assert(false == check_if_a_str_has_duplicate_chars_v2(str0));
    assert(false == check_if_a_str_has_duplicate_chars_v3(str0));

    /*
     * Test 1: Test with an empty string. This should not be character
     *         array having duplicate characters
     */
    char str1[] = "";
    assert(false == check_if_a_str_has_duplicate_chars_v1(str1));
    assert(false == check_if_a_str_has_duplicate_chars_v2(str1));
    assert(false == check_if_a_str_has_duplicate_chars_v3(str1));

    /*
     * Test 2: Test with a string having duplicate characters. This should
     *         not be character array having duplicate characters
     */
    char str2[] = "geeks";
    assert(true == check_if_a_str_has_duplicate_chars_v1(str2));
    assert(true == check_if_a_str_has_duplicate_chars_v2(str2));
    assert(true == check_if_a_str_has_duplicate_chars_v3(str2));

    /*
     * Test 3: Test with a string having no duplicate characters. This
     *         should not be character array having duplicate characters
     */
    char str3[] = "water";
    assert(false == check_if_a_str_has_duplicate_chars_v1(str3));
    assert(false == check_if_a_str_has_duplicate_chars_v2(str3));
    assert(false == check_if_a_str_has_duplicate_chars_v3(str3));

    /*
     * Test 4: Test with a string having a single character. This
     *         should not be character array having duplicate characters
     */
    char str4[] = "w";
    assert(false == check_if_a_str_has_duplicate_chars_v1(str4));
    assert(false == check_if_a_str_has_duplicate_chars_v2(str4));
    assert(false == check_if_a_str_has_duplicate_chars_v3(str4));

    return(0);
}


text:
package org.asynchttpclient.cookie;

import org.asynchttpclient.date.CalendarTimeConverter;
import org.asynchttpclient.date.TimeConverter;

public class CookieDecoder {

    public static final TimeConverter DEFAULT_TIME_CONVERTER = new CalendarTimeConverter();

    public static Cookie decode(String header) {
        return decode(header, DEFAULT_TIME_CONVERTER);
    }

    /**
     * Decodes the specified HTTP header value into {@link Cookie}.
     *
     * @return the decoded {@link Cookie}
     */
    public static Cookie decode(String header, TimeConverter timeConverter) {

        if (timeConverter == null)
            timeConverter = DEFAULT_TIME_CONVERTER;

        if (header.isEmpty())
            return null;

        KeyValuePairsParser pairsParser = new KeyValuePairsParser(timeConverter);

        final int headerLen = header.length();
        loop: for (int i = 0;;) {

            // Skip spaces and separators.
            for (;;) {
                if (i == headerLen) {
                    break loop;
                }
                char c = header.charAt(i);
                if (c == ',') {
                    // Having multiple cookies in a single Set-Cookie header is
                    // deprecated, modern browsers only parse the first one
                    break loop;

                } else if (c == '\t' || c == '\n' || c == 0x0b || c == '\f' || c == '\r' || c == ' ' || c == ';') {
                    i++;
                    continue;
                }
                break;
            }

            int newNameStart = i;
            int newNameEnd = i;
            String value;
            String rawValue;
            boolean first = true;

            if (i == headerLen) {
                value = rawValue = null;
            } else {
                keyValLoop: for (;;) {

                    char curChar = header.charAt(i);
                    if (curChar == ';') {
                        // NAME; (no value till ';')
                        newNameEnd = i;
                        value = rawValue = null;
                        first = false;
                        break keyValLoop;
                    } else if (curChar == '=') {
                        // NAME=VALUE
                        newNameEnd = i;
                        i++;
                        if (i == headerLen) {
                            // NAME= (empty value, i.e. nothing after '=')
                            value = rawValue = "";
                            first = false;
                            break keyValLoop;
                        }

                        int newValueStart = i;
                        char c = header.charAt(i);
                        if (c == '"' || c == '\'') {
                            // NAME="VALUE" or NAME='VALUE'
                            StringBuilder newValueBuf = new StringBuilder(header.length() - i);

                            int rawValueStart = i;
                            int rawValueEnd = i;

                            final char q = c;
                            boolean hadBackslash = false;
                            i++;
                            for (;;) {
                                if (i == headerLen) {
                                    value = newValueBuf.toString();
                                    // only need to compute raw value for cookie
                                    // value which is at most in 2nd position
                                    rawValue = first ? header.substring(rawValueStart, rawValueEnd) : null;
                                    first = false;
                                    break keyValLoop;
                                }
                                if (hadBackslash) {
                                    hadBackslash = false;
                                    c = header.charAt(i++);
                                    rawValueEnd = i;
                                    switch (c) {
                                    case '\\':
                                    case '"':
                                    case '\'':
                                        // Escape last backslash.
                                        newValueBuf.setCharAt(newValueBuf.length() - 1, c);
                                        break;
                                    default:
                                        // Do not escape last backslash.
                                        newValueBuf.append(c);
                                    }
                                } else {
                                    c = header.charAt(i++);
                                    rawValueEnd = i;
                                    if (c == q) {
                                        value = newValueBuf.toString();
                                        // only need to compute raw value for
                                        // cookie value which is at most in 2nd
                                        // position
                                        rawValue = first ? header.substring(rawValueStart, rawValueEnd) : null;
                                        first = false;
                                        break keyValLoop;
                                    }
                                    newValueBuf.append(c);
                                    if (c == '\\') {
                                        hadBackslash = true;
                                    }
                                }
                            }
                        } else {
                            // NAME=VALUE;
                            int semiPos = header.indexOf(';', i);
                            if (semiPos > 0) {
                                value = rawValue = header.substring(newValueStart, semiPos);
                                i = semiPos;
                            } else {
                                value = rawValue = header.substring(newValueStart);
                                i = headerLen;
                            }
                        }
                        break keyValLoop;
                    } else {
                        i++;
                    }

                    if (i == headerLen) {
                        // NAME (no value till the end of string)
                        newNameEnd = headerLen;
                        first = false;
                        value = rawValue = null;
                        break;
                    }
                }
            }

            pairsParser.parseKeyValuePair(header, newNameStart, newNameEnd, value, rawValue);
        }
        return pairsParser.cookie();
    }
}


text:
package com.codeborne.pdftest.matchers;

import com.codeborne.pdftest.PDF;
import org.hamcrest.Description;

import java.util.Arrays;

public class ContainsText extends PDFMatcher {
  private final String text;
  private final String[] texts;

  public ContainsText(String text, String... texts) {
    this.text = text;
    this.texts = texts;
  }

  @Override
  protected boolean matchesSafely(PDF item) {
    String reducedPdfText = reduceSpaces(item.text);
    return reducedPdfText.contains(reduceSpaces(text)) &&
            Arrays.stream(texts).allMatch(str -> reducedPdfText.contains(reduceSpaces(str)));
  }

  @Override
  protected void describeMismatchSafely(PDF item, Description mismatchDescription) {
    mismatchDescription.appendText("was \"").appendText(reduceSpaces(item.text)).appendText("\"");
  }

  @Override
  public void describeTo(Description description) {
    description.appendText("a PDF containing ");
    buildErrorMessage(description, text, texts);
  }

}


text:
Evite que seus sites sejam copiados, encrypte suas páginas e mantenha o nivel do SEO intacto.

## Instalação
- Baixe a ultima versão dos arquivos;
- Coloque na pasta do seu site;
- Copie o site sem encriptação para a pasta *desencriptado*;
- Encripte as partes html do seu site em http://www.smartgb.com/free_encrypthtml.php ou qualquer outro encriptador de html;
- Coloque os arquivos encriptados na pasta *encriptado*;

## Créditos
- Victor Hugo Scatolon de Souza;