text:
from __future__ import division
from __future__ import unicode_literals
import threading
import time
import os

import serial

import pyfirmata
from .boards import BOARDS

def get_the_board(layout=BOARDS['arduino'], base_dir='/dev/', identifier='tty.usbserial',):
    """
    Helper function to get the one and only board connected to the computer
    running this. It assumes a normal arduino layout, but this can be
    overriden by passing a different layout dict as the ``layout`` parameter.
    ``base_dir`` and ``identifier`` are overridable as well. It will raise an
    IOError if it can't find a board, on a serial, or if it finds more than
    one.
    """
    boards = []
    for device in os.listdir(base_dir):
        if device.startswith(identifier):
            try:
                board = pyfirmata.Board(os.path.join(base_dir, device), layout)
            except serial.SerialException:
                pass
            else:
                boards.append(board)
    if len(boards) == 0:
        raise IOError("No boards found in {0} with identifier {1}".format(base_dir, identifier))
    elif len(boards) > 1:
        raise IOError("More than one board found!")
    return boards[0]

class Iterator(threading.Thread):
    def __init__(self, board):
        super(Iterator, self).__init__()
        self.board = board

    def run(self):
        while 1:
            try:
                while self.board.bytes_available():
                    self.board.iterate()
                time.sleep(0.001)
            except (AttributeError, serial.SerialException, OSError) as e:
                # this way we can kill the thread by setting the board object
                # to None, or when the serial port is closed by board.exit()
                break
            except Exception as e:
                # catch 'error: Bad file descriptor'
                # iterate may be called while the serial port is being closed,
                # causing an "error: (9, 'Bad file descriptor')"
                if getattr(e, 'errno', None) == 9:
                    break
                try:
                    if e[0] == 9:
                        break
                except (TypeError, IndexError):
                    pass
                raise

def to_two_bytes(integer):
    """
    Breaks an integer into two 7 bit bytes.
    """
    if integer > 32767:
        raise ValueError("Can't handle values bigger than 32767 (max for 2 bits)")
    return bytearray([integer % 128, integer >> 7])

def from_two_bytes(bytes):
    """
    Return an integer from two 7 bit bytes.
    """
    lsb, msb = bytes
    try:
        # Usually bytes have been converted to integers with ord already
        return msb << 7 | lsb
    except TypeError:
        # But add this for easy testing
        # One of them can be a string, or both
        try:
            lsb = ord(lsb)
        except TypeError:
            pass
        try:
            msb = ord(msb)
        except TypeError:
            pass
        return msb << 7 | lsb

def two_byte_iter_to_str(bytes):
    """
    Return a string made from a list of two byte chars.
    """
    bytes = list(bytes)
    chars = bytearray()
    while bytes:
        lsb = bytes.pop(0)
        try:
            msb = bytes.pop(0)
        except IndexError:
            msb = 0x00
        chars.append(from_two_bytes([lsb, msb]))
    return chars.decode()

def str_to_two_byte_iter(string):
    """
    Return a iter consisting of two byte chars from a string.
    """
    bstring = string.encode()
    bytes = bytearray()
    for char in bstring:
        bytes.append(char)
        bytes.append(0)
    return bytes

def break_to_bytes(value):
    """
    Breaks a value into values of less than 255 that form value when multiplied.
    (Or almost do so with primes)
    Returns a tuple
    """
    if value < 256:
        return (value,)
    c = 256
    least = (0, 255)
    for i in range(254):
        c -= 1
        rest = value % c
        if rest == 0 and value / c < 256:
            return (c, int(value / c))
        elif rest == 0 and value / c > 255:
            parts = list(break_to_bytes(value / c))
            parts.insert(0, c)
            return tuple(parts)
        else:
            if rest < least[1]:
                least = (c, rest)
    return (c, int(value / c))

def pin_list_to_board_dict(pinlist):
    """
    Capability Response codes:
        INPUT:  0, 1
        OUTPUT: 1, 1
        ANALOG: 2, 10
        PWM:    3, 8
        SERV0:  4, 14
        I2C:    6, 1
    """

    board_dict = {
        'digital': [],
        'analog': [],
        'pwm': [],
        'servo': [],  # 2.2 specs
        #'i2c': [],  # 2.3 specs
        'disabled': [],
    }
    for i, pin in enumerate(pinlist):
        pin.pop()  # removes the 0x79 on end
        if not pin:
            board_dict['disabled'] += [i]
            board_dict['digital'] += [i]
            continue

        for j, _ in enumerate(pin):
            # Iterate over evens
            if j % 2 == 0:
                # This is safe. try: range(10)[5:50]
                if pin[j:j + 4] == [0, 1, 1, 1]:
                    board_dict['digital'] += [i]

                if pin[j:j + 2] == [2, 10]:
                    board_dict['analog'] += [i]

                if pin[j:j + 2] == [3, 8]:
                    board_dict['pwm'] += [i]

                if pin[j:j + 2] == [4, 14]:
                    board_dict['servo'] += [i]

                # Desable I2C
                if pin[j:j + 2] == [6, 1]:
                    pass

    # We have to deal with analog pins:
    # - (14, 15, 16, 17, 18, 19)
    # + (0, 1, 2, 3, 4, 5)
    diff = set(board_dict['digital']) - set(board_dict['analog'])
    board_dict['analog'] = [n for n, _ in enumerate(board_dict['analog'])]

    # Digital pin problems:
    #- (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
    #+ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

    board_dict['digital'] = [n for n, _ in enumerate(diff)]
    # Based on lib Arduino 0017
    board_dict['servo'] = board_dict['digital']

    # Turn lists into tuples
    # Using dict for Python 2.6 compatibility
    board_dict = dict([
        (key, tuple(value))
        for key, value
        in board_dict.items()
    ])

    return board_dict

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>64 Stitches</title>
    <meta name="description" content="knitting pattern generation language" />
    <meta name="author" content="Mariko Kosaka" />

    <link href='https://fonts.googleapis.com/css?family=Averia+Serif+Libre' rel='stylesheet' type='text/css'>

64 Stitches

Pattern Generation language

      64 Stitches is a simple language to explore textile pattern that can be generated in just 64 stitches.

Try it

Here are some initial code I wrote. Feel free to modify and make your own pattern!

      <button id='checker-sample'>checker</button>
      <button id="checker-comm-sample">checker(commented)</button>
      <button id="diagnal-sample">diagonal</button>

      <textarea id="code" name="codebox"></textarea>
      <button id="diagnal-sample">Download Swatch</button>
      <button id="diagnal-sample">Share Pattern (open in new window)</button>

Swatch

      <canvas id="canvas"></canvas>


text:
using namespace llvm;

#define DEBUG_TYPE "mips-isel"

//===----------------------------------------------------------------------===//
// Instruction Selector Implementation
//===----------------------------------------------------------------------===//

//===----------------------------------------------------------------------===//
// MipsDAGToDAGISel - MIPS specific code to select MIPS machine
// instructions for SelectionDAG operations.
//===----------------------------------------------------------------------===//

bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
  Subtarget = &TM.getSubtarget<MipsSubtarget>();
  bool Ret = SelectionDAGISel::runOnMachineFunction(MF);

  processFunctionAfterISel(MF);

  return Ret;
}

/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
  unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
  return CurDAG->getRegister(GlobalBaseReg,
                             getTargetLowering()->getPointerTy()).getNode();
}

/// ComplexPattern used on MipsInstrInfo
/// Used on Mips Load/Store instructions
bool MipsDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
                                        SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectAddrRegReg(SDValue Addr, SDValue &Base,
                                        SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
                                         SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
                                     SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectIntAddrMM(SDValue Addr, SDValue &Base,
                                       SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectIntAddrMSA(SDValue Addr, SDValue &Base,
                                        SDValue &Offset) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectAddr16(SDNode *Parent, SDValue N, SDValue &Base,
                                    SDValue &Offset, SDValue &Alias) {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplat(SDNode *N, APInt &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm1(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm2(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm3(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm4(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm5(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm6(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimm8(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatSimm5(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimmPow2(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatUimmInvPow2(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatMaskL(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

bool MipsDAGToDAGISel::selectVSplatMaskR(SDValue N, SDValue &Imm) const {
  llvm_unreachable("Unimplemented function.");
  return false;
}

/// Select instructions not customized! Used for
/// expanded, promoted and normal instructions
SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
  unsigned Opcode = Node->getOpcode();

  // Dump information about the Node being selected
  DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");

  // If we have a custom node, we already have selected!
  if (Node->isMachineOpcode()) {
    DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
    Node->setNodeId(-1);
    return nullptr;
  }

  // See if subclasses can handle this node.
  std::pair<bool, SDNode*> Ret = selectNode(Node);

  if (Ret.first)
    return Ret.second;

  switch(Opcode) {
  default: break;

  // Get target GOT address.
  case ISD::GLOBAL_OFFSET_TABLE:
    return getGlobalBaseReg();

#ifndef NDEBUG
  case ISD::LOAD:
  case ISD::STORE:
    assert((Subtarget->systemSupportsUnalignedAccess() ||
            cast<MemSDNode>(Node)->getMemoryVT().getSizeInBits() / 8 <=
            cast<MemSDNode>(Node)->getAlignment()) &&
           "Unexpected unaligned loads/stores.");
    break;
#endif
  }

  // Select the default instruction
  SDNode *ResNode = SelectCode(Node);

  DEBUG(errs() << "=> ");
  if (ResNode == nullptr || ResNode == Node)
    DEBUG(Node->dump(CurDAG));
  else
    DEBUG(ResNode->dump(CurDAG));
  DEBUG(errs() << "\n");
  return ResNode;
}

bool MipsDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
                             std::vector<SDValue> &OutOps) {
  assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
  OutOps.push_back(Op);
  return false;
}

/// createMipsISelDag - This pass converts a legalized DAG into a
/// MIPS-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
  if (TM.getSubtargetImpl()->inMips16Mode())
    return llvm::createMips16ISelDag(TM);

  return llvm::createMipsSEISelDag(TM);
}


text:
@implementation Cat

@end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getUnixTimestampInSeconds(dateTimeString) {
    if (!dateTimeString) {
        dateTimeString = new Date().getTime();
    }
    return Math.round(getUnixTimestampInMilliseconds(dateTimeString) / 1000);
}
exports.getUnixTimestampInSeconds = getUnixTimestampInSeconds;
function getUnixTimestampInMilliseconds(dateTimeString) {
    if (!dateTimeString) {
        return new Date().getTime();
    }
    return new Date(dateTimeString).getTime();
}
exports.getUnixTimestampInMilliseconds = getUnixTimestampInMilliseconds;
function getTimeSinceString(unixTimestamp) {
    if (!unixTimestamp) {
        return "never";
    }
    // @ts-ignore
    var secondsAgo = getSecondsAgo(unixTimestamp);
    if (secondsAgo > 2 * 24 * 60 * 60) {
        return Math.round(secondsAgo / (24 * 60 * 60)) + " days ago";
    }
    if (secondsAgo > 2 * 60 * 60) {
        return Math.round(secondsAgo / (60 * 60)) + " hours ago";
    }
    if (secondsAgo > 2 * 60) {
        return Math.round(secondsAgo / (60)) + " minutes ago";
    }
    return secondsAgo + " seconds ago";
}
exports.getTimeSinceString = getTimeSinceString;
function getSecondsAgo(unixTimestamp) {
    return Math.round((getUnixTimestampInSeconds() - unixTimestamp));
}
exports.getSecondsAgo = getSecondsAgo;
//# sourceMappingURL=qm.time-helper.js.map


text:
from django.core.exceptions import ValidationError
from django.core.mail import EmailMessage
from django.core.validators import validate_email
from django.template import Context, RequestContext
from django.template.loader import render_to_string
from django.utils.translation import get_language, activate
from pynliner import Pynliner

def send_html_mail(subject, template_name, dictionary, from_email=None,
                   to=None, cc=None, bcc=None, fail_silently=False,
                   request=None, css_files=None, lang=None):
    """Custom sned_mail for sending HTML emails rendered from a template"""

    if lang:
        current_lang = get_language()
        activate(lang)

    if request:
        context = RequestContext(dictionary)
    else:
        context = Context(dictionary)
    message_body = render_to_string(template_name, context_instance=context)
    message_body = Pynliner().from_string(message_body).run()

    message = EmailMessage(subject, message_body, from_email, to, bcc, cc=cc)
    message.content_subtype = 'html'
    result = message.send(fail_silently)

    if lang:
        activate(current_lang)

    return result

def valid_email_or_empty(email):
    """Validates that the email is correct, or return an empty string."""
    try:
        validate_email(email)
        return email
    except ValidationError:
        return ""


text:
package com.cassianetworks.fall;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cassianetworks.fall.domain.Record;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

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

/**
 * Created by ZhangMin on 2016/8/17.
 */
public class RecordAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    private List<Record> recordList;
    private Context context;

    public RecordAdapter(Context context) {
        this.context = context;
        recordList = new ArrayList<>();
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void refreshData(List<Record> recordList) {
        if (recordList == null) recordList = new ArrayList<>();
        this.recordList = recordList;
    }

    @Override
    public int getCount() {
        return recordList == null ? 0 : recordList.size();
    }

    @Override
    public Record getItem(int position) {
        return recordList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addRecordItem(Record record) {
        if (record != null)
            recordList.add(record);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Record record = getItem(position);
        int type = getItemViewType(position);
        ViewHolderHead holderHead;
        ViewHolderBody holderBody;

        if (convertView == null) {
            switch (type) {
                case 0:
                    convertView = mInflater.inflate(R.layout.item_lv_record_head, parent, false);
                    holderHead = new ViewHolderHead();
                    x.view().inject(holderHead, convertView);
                    holderHead.tvData.setText(record.getTime().split(" ")[0]);
                    convertView.setTag(holderHead);
                    break;

                case 1:
                    convertView = mInflater.inflate(R.layout.item_lv_record_body, parent, false);
                    holderBody = new ViewHolderBody();
                    x.view().inject(holderBody, convertView);
                    setBodyViewValue(record, holderBody);
                    convertView.setTag(holderBody);
                    break;
                default:
                    break;
            }

        } else {
            switch (type) {
                case 0:
                    holderHead = (ViewHolderHead) convertView.getTag();
                    holderHead.tvData.setText(record.getTime().split(" ")[0]);
                    break;
                case 1:
                    holderBody = (ViewHolderBody) convertView.getTag();
                    setBodyViewValue(record, holderBody);
                    break;

                default:
                    break;
            }
        }
        return convertView;
    }

    private void setBodyViewValue(Record record, ViewHolderBody holderBody) {
        holderBody.tvTime.setText(String.format(context.getString(R.string.record_time), record.getTime().split(" ")[1]));
        holderBody.tvDataType.setText(String.format(context.getString(R.string.record_dataType), record.getDataType()));
        holderBody.tvHandle.setText(String.format(context.getString(R.string.record_handle), record.getHandle()));
        holderBody.tvName.setText(String.format(context.getString(R.string.record_name), record.getName()));
        holderBody.tvValue.setText(String.format(context.getString(R.string.record_value), record.getValue()));
    }

    /**
     * 根据数据源的position返回需要显示的的layout的type
     * <p/>
     * type的值必须从0开始
     */
    @Override
    public int getItemViewType(int position) {
        return getItem(position).getType();
    }

    /**
     * 返回所有的layout的数量
     */
    @Override
    public int getViewTypeCount() {
        return 2;
    }

    class ViewHolderHead {
        @ViewInject(R.id.tv_data)
        private TextView tvData;
    }

    class ViewHolderBody {
        @ViewInject(R.id.tv_time)
        private TextView tvTime;
        @ViewInject(R.id.tv_value)
        private TextView tvValue;
        @ViewInject(R.id.tv_name)
        private TextView tvName;
        @ViewInject(R.id.tv_dataType)
        private TextView tvDataType;
        @ViewInject(R.id.tv_handle)
        private TextView tvHandle;
    }

}


text:
from __future__ import absolute_import, division, print_function

from licensedcode.match import get_texts
from licensedcode.match import LicenseMatch
from licensedcode.seq import match_blocks
from licensedcode.spans import Span

TRACE = False
TRACE2 = False

def logger_debug(*args): pass

if TRACE:
    import logging
    import sys

    logger = logging.getLogger(__name__)

    def logger_debug(*args):
        return logger.debug(' '.join(isinstance(a, basestring) and a or repr(a) for a in args))

    logging.basicConfig(stream=sys.stdout)
    logger.setLevel(logging.DEBUG)

"""
Matching strategy using pair-wise multiple local sequences alignment and diff-
like approaches.
"""

MATCH_SEQ = '3-seq'

def match_sequence(idx, candidate, query_run, start_offset=0):
    """
    Return a list of LicenseMatch by matching the `query_run` tokens sequence
    against the `idx` index for the `candidate` rule tuple (rid, rule,
    intersection).
    """
    if not candidate:
        return []

    rid, rule, _intersection = candidate
    high_postings = idx.high_postings_by_rid[rid]
    itokens = idx.tids_by_rid[rid]

    len_junk = idx.len_junk

    qbegin = query_run.start + start_offset
    qfinish = query_run.end
    qtokens = query_run.query.tokens
    query = query_run.query

    matches = []
    qstart = qbegin
    qlen = len(query_run)

    # match as long as long we find alignments and have high matchable tokens
    # this allows to find repeated instances of the same rule in the query run
    query_run_matchables = query_run.matchables

    while qstart <= qfinish:
        if not query_run_matchables:
            break
        block_matches = match_blocks(qtokens, itokens, qstart, qlen, high_postings, len_junk, query_run_matchables)
        if not block_matches:
            break
        if TRACE2:
            logger_debug('block_matches:')
            for m in block_matches:
                i, j, k = m
                print(m)
                print('qtokens:', ' '.join(idx.tokens_by_tid[t] for t in qtokens[i:i + k]))
                print('itokens:', ' '.join(idx.tokens_by_tid[t] for t in itokens[j:j + k]))

        # create one match for each matching block: this not entirely correct
        # but this will be sorted out at LicenseMatch merging and filtering time
        for qpos, ipos, mlen in block_matches:
            qspan = Span(range(qpos, qpos + mlen))
            iposses = range(ipos, ipos + mlen)
            hispan = Span(p for p in iposses if itokens[p] >= len_junk)
            ispan = Span(iposses)
            match = LicenseMatch(rule, qspan, ispan, hispan, qbegin, matcher=MATCH_SEQ, query=query)
            if TRACE2:
                qt, it = get_texts(
                    match, location=query.location, query_string=query.query_string, idx=idx)
                print('###########################')
                print(match)
                print('###########################')
                print(qt)
                print('###########################')
                print(it)
                print('###########################')

            matches.append(match)
            qstart = max([qstart, qspan.end + 1])

    if TRACE: map(logger_debug, matches)
    return matches


text:
package io.fabric8.forge.camel.commands.project.converter;

import io.fabric8.forge.camel.commands.project.dto.NodeDto;
import org.jboss.forge.addon.convert.Converter;

public class NodeDtoLabelConverter implements Converter<NodeDto, String> {

    @Override
    public String convert(NodeDto nodeDto) {
        if (nodeDto != null) {
            return nodeDto.getLabel();
        }
        return null;
    }

}


text:
Financial backtest module using Quandl database

**This library is discontinued as Quandl stopped providing certain data set**


text:
#ifndef BOOST_COMPUTE_IMAGE_HPP
#define BOOST_COMPUTE_IMAGE_HPP

/// \file
///
/// Meta-header to include all Boost.Compute image headers.

#include <boost/compute/image/image1d.hpp>
#include <boost/compute/image/image2d.hpp>
#include <boost/compute/image/image3d.hpp>
#include <boost/compute/image/image_format.hpp>
#include <boost/compute/image/image_object.hpp>
#include <boost/compute/image/image_sampler.hpp>

#endif // BOOST_COMPUTE_IMAGE_HPP


text:
@interface MQPublishViewController : UIViewController

@end


text:
package com.jakewharton.resourcefs;

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.WatchService;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collections;
import java.util.Set;

import static java.util.Objects.requireNonNull;

final class ResourceFileSystem extends FileSystem {
  private final Iterable<Path> rootDirectories;
  private final Iterable<FileStore> fileStores;
  private final Set<String> supportedFileAttributeViews;
  private final ResourceFileSystemProvider provider;

  ResourceFileSystem(ResourceFileSystemProvider provider) {
    this.provider = requireNonNull(provider, "provider");

    rootDirectories = Collections.<Path>singletonList(new ResourcePath(this, URI.create("/")));
    fileStores = Collections.singletonList(provider.fileStore);
    supportedFileAttributeViews = Collections.singleton("basic");
  }

  @Override public FileSystemProvider provider() {
    return provider;
  }

  @Override public void close() throws IOException {
  }

  @Override public boolean isOpen() {
    return true;
  }

  @Override public boolean isReadOnly() {
    return true;
  }

  @Override public String getSeparator() {
    return "/";
  }

  @Override public Iterable<Path> getRootDirectories() {
    return rootDirectories;
  }

  @Override public Iterable<FileStore> getFileStores() {
    return fileStores;
  }

  @Override public Set<String> supportedFileAttributeViews() {
    return supportedFileAttributeViews;
  }

  @Override public Path getPath(String first, String... more) {
    StringBuilder builder = new StringBuilder(first);
    for (String m : more) {
      builder.append(getSeparator()).append(m);
    }
    return new ResourcePath(this, URI.create(builder.toString()));
  }

  @Override public PathMatcher getPathMatcher(String syntaxAndPattern) {
    return null; // TODO
  }

  @Override public UserPrincipalLookupService getUserPrincipalLookupService() {
    return null; // TODO
  }

  @Override public WatchService newWatchService() throws IOException {
    return null; // TODO
  }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.ComponentModel;
using System.Threading;

namespace System.Reactive.PlatformServices
{
    /// <summary>
    /// (Infrastructure) Provides access to local system clock services.
    /// </summary>
    /// <remarks>
    /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
    /// No guarantees are made about forward compatibility of the type's functionality and its usage.
    /// </remarks>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class SystemClock
    {
        private static Lazy<ISystemClock> s_serviceSystemClock = new Lazy<ISystemClock>(InitializeSystemClock);
        private static Lazy<INotifySystemClockChanged> s_serviceSystemClockChanged = new Lazy<INotifySystemClockChanged>(InitializeSystemClockChanged);

        private static int _refCount;

        /// <summary>
        /// Gets the local system clock time.
        /// </summary>
        public static DateTimeOffset UtcNow
        {
            get { return s_serviceSystemClock.Value.UtcNow; }
        }

        /// <summary>
        /// Event that gets raised when a system clock change is detected, if there's any interest as indicated by AddRef calls.
        /// </summary>
        public static event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;

        /// <summary>
        /// Adds a reference to the system clock monitor, causing it to be sending notifications.
        /// </summary>
        /// <exception cref="NotSupportedException">Thrown when the system doesn't support sending clock change notifications.</exception>
        public static void AddRef()
        {
            if (Interlocked.Increment(ref _refCount) == 1)
            {
                s_serviceSystemClockChanged.Value.SystemClockChanged += OnSystemClockChanged;
            }
        }

        /// <summary>
        /// Removes a reference to the system clock monitor, causing it to stop sending notifications
        /// if the removed reference was the last one.
        /// </summary>
        public static void Release()
        {
            if (Interlocked.Decrement(ref _refCount) == 0)
            {
                s_serviceSystemClockChanged.Value.SystemClockChanged -= OnSystemClockChanged;
            }
        }

        private static void OnSystemClockChanged(object sender, SystemClockChangedEventArgs e)
        {
            var scc = SystemClockChanged;
            if (scc != null)
                scc(sender, e);
        }

        private static ISystemClock InitializeSystemClock()
        {
            return PlatformEnlightenmentProvider.Current.GetService<ISystemClock>() ?? new DefaultSystemClock();
        }

        private static INotifySystemClockChanged InitializeSystemClockChanged()
        {
            return PlatformEnlightenmentProvider.Current.GetService<INotifySystemClockChanged>() ?? new DefaultSystemClockMonitor();
        }
    }

    /// <summary>
    /// (Infrastructure) Provides access to the local system clock.
    /// </summary>
    /// <remarks>
    /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
    /// No guarantees are made about forward compatibility of the type's functionality and its usage.
    /// </remarks>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public interface ISystemClock
    {
        /// <summary>
        /// Gets the current time.
        /// </summary>
        DateTimeOffset UtcNow { get; }
    }

    /// <summary>
    /// (Infrastructure) Provides a mechanism to notify local schedulers about system clock changes.
    /// </summary>
    /// <remarks>
    /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
    /// No guarantees are made about forward compatibility of the type's functionality and its usage.
    /// </remarks>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public interface INotifySystemClockChanged
    {
        /// <summary>
        /// Event that gets raised when a system clock change is detected.
        /// </summary>
        event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;
    }

    /// <summary>
    /// (Infrastructure) Event arguments for system clock change notifications.
    /// </summary>
    /// <remarks>
    /// This type is used by the Rx infrastructure and not meant for public consumption or implementation.
    /// No guarantees are made about forward compatibility of the type's functionality and its usage.
    /// </remarks>
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class SystemClockChangedEventArgs : EventArgs
    {
        /// <summary>
        /// Creates a new system clock notification object with unknown old and new times.
        /// </summary>
        public SystemClockChangedEventArgs()
            : this(DateTimeOffset.MinValue, DateTimeOffset.MaxValue)
        {
        }

        /// <summary>
        /// Creates a new system clock notification object with the specified old and new times.
        /// </summary>
        /// <param name="oldTime">Time before the system clock changed, or DateTimeOffset.MinValue if not known.</param>
        /// <param name="newTime">Time after the system clock changed, or DateTimeOffset.MaxValue if not known.</param>
        public SystemClockChangedEventArgs(DateTimeOffset oldTime, DateTimeOffset newTime)
        {
            OldTime = oldTime;
            NewTime = newTime;
        }

        /// <summary>
        /// Gets the time before the system clock changed, or DateTimeOffset.MinValue if not known.
        /// </summary>
        public DateTimeOffset OldTime { get; private set; }

        /// <summary>
        /// Gets the time after the system clock changed, or DateTimeOffset.MaxValue if not known.
        /// </summary>
        public DateTimeOffset NewTime { get; private set; }
    }
}


text:
/**
 * use `angular.isRegexp` instead of other comparisons
 *
 * DEPRECATED! You should use the angular.isRegexp method instead of the default JavaScript implementation (toString.call(/^A/) === "[object RegExp]").
 *
 * @linkDescription DEPRECATED! use `angular.isRegexp` instead of other comparisons (no native angular method)
 * @version 0.1.0
 */
'use strict';

module.exports = function(context) {
    var utils = require('./utils/utils');

    function recordError(node, origin) {
        if (node.type === 'Literal' && node.value === '[object RegExp]') {
            context.report(origin, 'You should use the angular.isRegexp method', {});
        }
    }

    function checkNode(node) {
        return node.type === 'Identifier' || utils.isToStringStatement(node);
    }

    return {

        BinaryExpression: function(node) {
            if (node.operator === '===' || node.operator === '!==') {
                if (checkNode(node.left)) {
                    recordError(node.right, node);
                } else if (checkNode(node.right)) {
                    recordError(node.left, node);
                }
            }
        }
    };
};

module.exports.schema = [
    // JSON Schema for rule options goes here
];


text:
<?php

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $eventManager->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($event) {
            $controller      = $event->getTarget();
            $controllerName  = get_class($controller);
            $moduleNamespace = substr($controllerName, 0, strpos($controllerName, '\\'));
            $configs         = $event->getApplication()->getServiceManager()->get('config');
            if (isset($configs['moduleLayouts'][$moduleNamespace])) {
                $controller->layout($configs['moduleLayouts'][$moduleNamespace]);
            }
        }, 100);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}


text:
class RemoveNotNullConstraintFromEmailAddressees < ActiveRecord::Migration
  def change
    change_column :email_addressees, :addressee_id, :integer, null: true
  end
end


text:
// This file is automatically generated.

package adila.db;

/*
 * Hisense D2-M
 *
 * DEVICE: HS6735MT
 * MODEL: D2-M
 */
final class hs6735mt_d22dm {
    public static final String DATA = "Hisense|D2-M|";
}


text:
#ifndef REF_H_
#define REF_H_

namespace gameplay
{

/**
 * Defines the base class for game objects that require lifecycle management.
 *
 * This class provides reference counting support for game objects that
 * contain system resources or data that is normally long lived and
 * referenced from possibly several sources at the same time. The built-in
 * reference counting eliminates the need for programmers to manually
 * keep track of object ownership and having to worry about when to
 * safely delete such objects.
 */
class Ref
{
public:

    /**
     * Increments the reference count of this object.
     *
     * The release() method must be called when the caller relinquishes its
     * handle to this object in order to decrement the reference count.
     */
    void addRef();

    /**
     * Decrements the reference count of this object.
     *
     * When an object is initially created, its reference count is set to 1.
     * Calling addRef() will increment the reference and calling release()
     * will decrement the reference count. When an object reaches a
     * reference count of zero, the object is destroyed.
     */
    void release();

    /**
     * Returns the current reference count of this object.
     *
     * @return This object's reference count.
     */
    unsigned int getRefCount() const;

protected:

    /**
     * Constructor.
     */
    Ref();

    /**
     * Copy constructor.
     *
     * @param copy The Ref object to copy.
     */
    Ref(const Ref& copy);

    /**
     * Destructor.
     */
    virtual ~Ref();

private:

    unsigned int _refCount;

    // Memory leak diagnostic data (only included when GP_USE_MEM_LEAK_DETECTION is defined)
#ifdef GP_USE_MEM_LEAK_DETECTION
    friend class Game;
    static void printLeaks();
    void* __record;
#endif
};

}

#endif


text:
package org.dashbuilder.client.navigation.widget;

/**
 * Interface implemented for those {@link NavWidget} implementations that allows for
 * the definition of a default nav item to display.
 */
public interface HasDefaultNavItem {

    String getDefaultNavItemId();

    void setDefaultNavItemId(String navItemId);
}


text:
#ifndef ATOM_H
#define ATOM_H

#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
#include "matrix.h"

class Atom
{
public:
  typedef boost::shared_ptr<Atom> Ptr;
  typedef double PosType;

  /**
   * @brief Default Atom Cosntructor
   */
  Atom();

  /**
   * @brief Copy constructor
   * @param a atom to copy
   */
  Atom(const Atom& a);

  /**
   * @brief get a copy of the Atom
   * @return smart pointer to a copy of the atom
   */
  Atom::Ptr copy() const;

  /**
   * @brief Custom atom name (example: H1, C4b)
   */
  std::string name_;

  /**
   * @brief Atom type, see AtomProperties
   */
  std::string type_;

  /**
   * @brief Atom position
   */
  Matrix::Ptr pos_;  // column matrix expected
};

#endif // ATOM_H


text:
package org.apache.ignite.internal.processors.cache.distributed.near;

import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.processors.cache.IgniteMvccTxSingleThreadedAbstractTest;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;

/**
 * Tests for partitioned cache transactions.
 */
public class GridCachePartitionedMvccTxSingleThreadedSelfTest extends IgniteMvccTxSingleThreadedAbstractTest {
    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        CacheConfiguration<?, ?> ccfg = defaultCacheConfiguration();

        ccfg.setCacheMode(PARTITIONED);
        ccfg.setBackups(1);
        ccfg.setAtomicityMode(TRANSACTIONAL_SNAPSHOT);

        ccfg.setNearConfiguration(null);
        ccfg.setEvictionPolicy(null);

        ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_ASYNC);

        cfg.setCacheConfiguration(ccfg);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return 4;
    }

    /** {@inheritDoc} */
    @Override protected int keyCount() {
        return 3;
    }

    /** {@inheritDoc} */
    @Override protected int maxKeyValue() {
        return 3;
    }

    /** {@inheritDoc} */
    @Override protected int iterations() {
        return 3000;
    }

    /** {@inheritDoc} */
    @Override protected boolean isTestDebug() {
        return false;
    }

    /** {@inheritDoc} */
    @Override protected boolean printMemoryStats() {
        return true;
    }
}


text:
package com.tymons.entity;

/**
 * Created by tymons on 21.02.17.
 */
public enum AuthorityName {
    ROLE_USER, ROLE_ADMIN
}


text:
<?php

$directory = 0;
$handle = opendir('/var/www/html/storage');
while (false !== ($entry = readdir($handle))) {
    if ($entry === ".."
        || $entry === "."
        || $entry === ".svn")
        continue;
    if (strval($entry) >= $directory)
        $directory = strval($entry);
}
closedir($handle);

$directory = strval($directory + 1);
$sequence = "storage/" . $directory . "/2fft.fasta"; // this is pushd so its relative
$dir_num = $directory;
$directory = "/var/www/html/storage/" . $directory;
system("mkdir " . $directory);

$result = $directory . "/result";

$write_seq = fopen($sequence, "w");
fwrite($write_seq, $_POST['seq']);
fwrite($write_seq, "\n");
fclose($write_seq);

# TIME FOR THE MIRACLE!
ignore_user_abort();
$cmd = "bash -c \"exec /usr/bin/php -f /var/www/cgi-bin/sting_exec.php " .
    $sequence . " " . $_POST['email'] .
    " " . $result . " " . $dir_num . "

?>


text:
<?php

namespace YnloFramework\YnloAssetsBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use YnloFramework\YnloAssetsBundle\Assets\AssetContext;
use YnloFramework\YnloAssetsBundle\Assets\AssetFactory;
use YnloFramework\YnloAssetsBundle\Assets\AssetRegistry;

/**
 * YnloAssetsExtension.
 */
class YnloAssetsExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('ynlo.assets.config', $config);

        $configDir = __DIR__.'/../Resources/config';
        $loader = new YamlFileLoader($container, new FileLocator($configDir));
        $loader->load('services.yml');
    }

    /**
     * {@inheritdoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        if (!$container->hasExtension('assetic')) {
            throw new \LogicException('The assetic bundle is required.');
        }

        $asseticConfig = $container->getExtensionConfig('assetic')[0];
        $assetConfig = $container->getExtensionConfig('ynlo_assets')[0];

        //Assetic base configuration
        $asseticConfig['bundles'][] = 'YnloFrameworkBundle';
        $asseticConfig['filters']['cssrewrite'] = null;
        if (empty($asseticConfig['assets'])) {
            $asseticConfig['assets'] = [];
        }

        $useRequireJs = (!isset($assetConfig['requirejs']) || $assetConfig['requirejs'] !== false);

        AssetRegistry::build($container, $useRequireJs);

        if ($useRequireJs) {
            AssetRegistry::prependAssets(
                [
                    AssetFactory::asset('switchery_js', 'bundles/ynloform/vendor/switchery/switchery.min.js'),
                    AssetFactory::asset('requirejs', 'bundles/ynloassets/vendor/requirejs/require.min.js'),
                    AssetFactory::asset('requirejs_config', 'bundles/ynloassets/js/require_js_config.js', ['require_js_config']),
                ]
            );

            AssetRegistry::addAsset(
                AssetFactory::asset('jquery_plugins_overrides', 'bundles/ynloassets/js/jquery_plugins_overrides.js', ['jquery_plugin_override'])
            );
        }

        $this->processAssetContexts($container);

        //save the array of assets in a param to restore the registry later
        $container->setParameter('ynlo.assets', AssetRegistry::serialize());
        $registeredAssets = AssetRegistry::getAsseticAssetsArray();
        $asseticConfig['assets'] = array_merge($registeredAssets, $asseticConfig['assets']);

        $container->prependExtensionConfig('assetic', $asseticConfig);
    }

    private function processAssetContexts(ContainerBuilder $containerBuilder)
    {
        $config = $this->processConfiguration(new Configuration(), $containerBuilder->getExtensionConfig('ynlo_assets'));
        $exclude = [];
        if ($containerBuilder->hasExtension('ynlo_admin')) {
            $exclude[] = 'bundle_ynlo_admin';
        }
        $defaultContexts = [
            'app' => [
                'include' => ['all'],
                'exclude' => $exclude,
            ],
        ];

        $config['contexts'] = array_merge_recursive($config['contexts'], $defaultContexts);

        foreach ($config['contexts'] as $context => $contextConfig) {
            $context = new AssetContext($context);
            $context->setInclude(array_key_value($contextConfig, 'include', []));
            $context->setExclude(array_key_value($contextConfig, 'exclude', []));
            $context->setOverride(array_key_value($contextConfig, 'override', []));

            if (empty($contextConfig['include'])) {
                $msg = sprintf('The context `%s` don`t have any assets to include.', $context);
                throw new \LogicException($msg);
            }

            AssetRegistry::registerAssetBundle($context->getName(), $context->getAssets());
        }
    }
}


text:
/*

Package checkers is a simple example of the classic checkers game. It exercises
a grid-like board.

*/
package checkers

import (
	"errors"
	"reflect"
	"strings"

	"github.com/jkomoros/boardgame"
	"github.com/jkomoros/boardgame/base"
	"github.com/jkomoros/boardgame/moves"
)

//go:generate boardgame-util codegen

type gameDelegate struct {
	base.GameDelegate
}

var memoizedDelegateName string

func (g *gameDelegate) Name() string {

	//If our package name and delegate.Name() don't match, NewGameManager will
	//fail with an error. Given they have to be the same, we might as well
	//just ensure they are actually the same, via a one-time reflection.

	if memoizedDelegateName == "" {
		pkgPath := reflect.ValueOf(g).Elem().Type().PkgPath()
		pathPieces := strings.Split(pkgPath, "/")
		memoizedDelegateName = pathPieces[len(pathPieces)-1]
	}
	return memoizedDelegateName
}

func (g *gameDelegate) Description() string {
	return "Checkers is the classic game on a grid where players compete to capture opponents' pieces."
}

func (g *gameDelegate) MinNumPlayers() int {
	return 2
}

func (g *gameDelegate) MaxNumPlayers() int {
	return 2
}

func (g *gameDelegate) DefaultNumPlayers() int {
	return 2
}

func (g *gameDelegate) ConfigureMoves() []boardgame.MoveConfig {

	auto := moves.NewAutoConfigurer(g)

	return moves.Combine(
		moves.AddOrderedForPhase(phaseSetup,
			auto.MustConfig(
				new(movePlaceToken),
				moves.WithHelpText("Places one token at a time on the board."),
			),
			auto.MustConfig(
				new(moves.StartPhase),
				moves.WithPhaseToStart(phasePlaying, phaseEnum),
			),
		),
		moves.AddForPhase(phasePlaying,
			auto.MustConfig(
				new(moveCrownToken),
				moves.WithHelpText("Crowns tokens that make it to the other end of the board."),
				moves.WithSourceProperty("Spaces"),
			),
			auto.MustConfig(
				new(moves.FinishTurn),
			),
			auto.MustConfig(
				new(moveMoveToken),
				moves.WithHelpText("Moves a token from one place to another"),
			),
		),
	)
}

func (g *gameDelegate) ConfigureConstants() boardgame.PropertyCollection {
	return boardgame.PropertyCollection{
		"BOARD_SIZE": boardSize,
	}
}

func (g *gameDelegate) GameStateConstructor() boardgame.ConfigurableSubState {
	return new(gameState)
}

func (g *gameDelegate) PlayerStateConstructor(index boardgame.PlayerIndex) boardgame.ConfigurableSubState {
	return new(playerState)
}

func (g *gameDelegate) DynamicComponentValuesConstructor(deck *boardgame.Deck) boardgame.ConfigurableSubState {
	if deck.Name() != tokenDeckName {
		return nil
	}
	return new(tokenDynamic)
}

func (g *gameDelegate) DistributeComponentToStarterStack(state boardgame.ImmutableState, c boardgame.Component) (boardgame.ImmutableStack, error) {
	game := state.ImmutableGameState().(*gameState)
	if c.Deck().Name() == tokenDeckName {
		return game.UnusedTokens, nil
	}
	return nil, errors.New("Unknown deck")
}

func (g *gameDelegate) GameEndConditionMet(state boardgame.ImmutableState) bool {
	_, players := concreteStates(state)
	for _, p := range players {
		if p.CapturedTokens.NumComponents() >= numTokens {
			return true
		}
	}

	return false
}

func (g *gameDelegate) PlayerScore(pState boardgame.ImmutableSubState) int {
	p := pState.(*playerState)
	return p.CapturedTokens.NumComponents()
}

func (g *gameDelegate) ConfigureDecks() map[string]*boardgame.Deck {
	return map[string]*boardgame.Deck{
		tokenDeckName: newTokenDeck(),
	}
}

//NewDelegate is the primary entrypoint of the package, returning a new delegate
//that configures a game of checkers.
func NewDelegate() boardgame.GameDelegate {
	return &gameDelegate{}
}


text:
using OpenTK.Graphics;
using OpenTK.Platform.SDL2;

namespace OpenTK.Platform.Egl
{
    internal class EglSdl2PlatformFactory : Sdl2Factory
    {
        public override OpenTK.Graphics.IGraphicsContext CreateGLContext(
            GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering,
            int major, int minor, GraphicsContextFlags flags)
        {
            flags |= GraphicsContextFlags.Embedded;
            return base.CreateGLContext(mode, window, shareContext, directRendering, major, minor, flags);
        }
    }
}
#endif


text:
package org.tdc.schemaparse;

import java.nio.file.Path;

import org.apache.xerces.xs.XSImplementation;
import org.apache.xerces.xs.XSLoader;
import org.apache.xerces.xs.XSModel;
import org.w3c.dom.DOMErrorHandler;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;

/**
 * Builder that creates an Apache Xerses {@link XSModel} in-memory representation of a set of schemas.
 */
public class ModelDefXSModelBuilder {

	private final boolean failOnParserWarning;
	private final boolean failOnParserNonFatalError;
	private final DOMImplementationRegistry domRegistry;
	private final XSLoader xsLoader;

	public ModelDefXSModelBuilder(boolean failOnParserWarning, boolean failOnParserNonFatalError) {
		this.failOnParserWarning = failOnParserWarning;
		this.failOnParserNonFatalError = failOnParserNonFatalError;
		this.domRegistry = initDOMRegistry();
		this.xsLoader = initXSLoader();
	}

	public XSModel buildXSModelFromSchemas(Path rootSchemaFile) {
		String uri = rootSchemaFile.toUri().toString();
		return xsLoader.loadURI(uri);
	}

	private XSLoader initXSLoader() {
		DOMErrorHandler errorHandler =
				new ModelDefDOMErrorHandler(failOnParserWarning, failOnParserNonFatalError);
		XSImplementation xsImpl = (XSImplementation)domRegistry.getDOMImplementation("XS-Loader");
		XSLoader loader = xsImpl.createXSLoader(null);
		loader.getConfig().setParameter("error-handler", errorHandler);
		return loader;
	}

	private DOMImplementationRegistry initDOMRegistry() {
		System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
		try {
			return DOMImplementationRegistry.newInstance();
		}
		catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) {
			// intentionally converting mostly checked exceptions to unchecked, as any exception
			// is not something the system can be expected to resolve; indicates a coding or configuration problem
			throw new RuntimeException("Unable to instantiate DOMImplementationRegistry", e);
		}
	}
}


text:
<?php

namespace WellCommerce\Bundle\ProducerBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Configurator\AbstractLayoutBoxConfiguratorTestCase;
use WellCommerce\Bundle\LayoutBundle\Configurator\LayoutBoxConfiguratorInterface;

/**
 * Class ProducerMenuBoxConfiguratorTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProducerMenuBoxConfiguratorTest extends AbstractLayoutBoxConfiguratorTestCase
{
    protected function getService(): LayoutBoxConfiguratorInterface
    {
        return $this->container->get('producer_menu.layout_box.configurator');
    }

    public function provideLayoutBoxConfiguration()
    {
        return [
            ['ProducerMenu', 'producer_menu.layout_box.controller'],
        ];
    }
}


text:
An npm script based utility for running PHP based sites locally, and processing SCSS on the fly.
You can use this on it's own, or fold it into another PHP based site system, like [Kirby](http://getkirby.com), for example.

## Requirements

The only requirement is that you have [Node.js](https://nodejs.org/en/) installed, which comes with npm. I've only tested this on OS X 10.11.1, which comes with a PHP pre-installed, so it might not work in other OSes.

## Install

Like any npm script, do a one time install: `npm install`

## Use

This one command will get you running: `npm run dev`

## What's hapening?

Two things mainly: SCSS is getting processed into CSS, and the directory is being served via your
local PHP server.

![Screenshot](php-local-screenshot.png)

## The full CSS process

Each time your SCSS files are saved

0. The old CSS file is deleted.
1. The SCSS is processed to CSS.
2. The processed CSS is run through POSTCSS and the Autoprefixer plugin.
3. The CSS is minified

## What's not here?

Tons of goodies such as live-reloading in the browser, or any kind of javascript processing.
This and more can be added in a purely npm script environment, but at a certain
level of complexity you might benefit from helpers like Gulp, Webpack, etc.

## How to I modify for my own use?

It's all in the package.json file, you can:

* change the directory where SCSS/CSS are stored
* add more functions
* change the default serving port

## POSTCSS options

These are stored in the postcss.json file, you can modify Autoprefixer's browser compatibility settings there for example.


text:
package org.apache.beam.runners.apex.translation;

import com.datatorrent.api.DAG;
import java.util.HashMap;
import java.util.Map;
import org.apache.beam.runners.apex.ApexPipelineOptions;
import org.apache.beam.runners.apex.ApexRunner.CreateApexPCollectionView;
import org.apache.beam.runners.apex.translation.operators.ApexProcessFnOperator;
import org.apache.beam.runners.apex.translation.operators.ApexReadUnboundedInputOperator;
import org.apache.beam.runners.core.SplittableParDoViaKeyedWorkItems;
import org.apache.beam.runners.core.SplittableParDoViaKeyedWorkItems.GBKIntoKeyedWorkItems;
import org.apache.beam.runners.core.construction.PrimitiveCreate;
import org.apache.beam.runners.core.construction.UnboundedReadFromBoundedSource.BoundedToUnboundedSourceAdapter;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.runners.TransformHierarchy;
import org.apache.beam.sdk.transforms.Flatten;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.View.CreatePCollectionView;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@link ApexPipelineTranslator} translates {@link Pipeline} objects into Apex logical plan {@link
 * DAG}.
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class ApexPipelineTranslator extends Pipeline.PipelineVisitor.Defaults {
  private static final Logger LOG = LoggerFactory.getLogger(ApexPipelineTranslator.class);

  /**
   * A map from {@link PTransform} subclass to the corresponding {@link TransformTranslator} to use
   * to translate that transform.
   */
  private static final Map<Class<? extends PTransform>, TransformTranslator> transformTranslators =
      new HashMap<>();

  private final TranslationContext translationContext;

  static {
    // register TransformTranslators
    registerTransformTranslator(ParDo.MultiOutput.class, new ParDoTranslator<>());
    registerTransformTranslator(
        SplittableParDoViaKeyedWorkItems.ProcessElements.class,
        new ParDoTranslator.SplittableProcessElementsTranslator());
    registerTransformTranslator(GBKIntoKeyedWorkItems.class, new GBKIntoKeyedWorkItemsTranslator());
    registerTransformTranslator(Read.Unbounded.class, new ReadUnboundedTranslator());
    registerTransformTranslator(Read.Bounded.class, new ReadBoundedTranslator());
    registerTransformTranslator(GroupByKey.class, new GroupByKeyTranslator());
    registerTransformTranslator(Flatten.PCollections.class, new FlattenPCollectionTranslator());
    registerTransformTranslator(PrimitiveCreate.class, new CreateValuesTranslator());
    registerTransformTranslator(
        CreateApexPCollectionView.class, new CreateApexPCollectionViewTranslator());
    registerTransformTranslator(CreatePCollectionView.class, new CreatePCollectionViewTranslator());
    registerTransformTranslator(Window.Assign.class, new WindowAssignTranslator());
  }

  public ApexPipelineTranslator(ApexPipelineOptions options) {
    this.translationContext = new TranslationContext(options);
  }

  public void translate(Pipeline pipeline, DAG dag) {
    pipeline.traverseTopologically(this);
    translationContext.populateDAG(dag);
  }

  @Override
  public CompositeBehavior enterCompositeTransform(TransformHierarchy.Node node) {
    LOG.debug("entering composite transform {}", node.getTransform());
    return CompositeBehavior.ENTER_TRANSFORM;
  }

  @Override
  public void leaveCompositeTransform(TransformHierarchy.Node node) {
    LOG.debug("leaving composite transform {}", node.getTransform());
  }

  @Override
  public void visitPrimitiveTransform(TransformHierarchy.Node node) {
    LOG.debug("visiting transform {}", node.getTransform());
    PTransform transform = node.getTransform();
    TransformTranslator translator = getTransformTranslator(transform.getClass());
    if (null == translator) {
      throw new UnsupportedOperationException("no translator registered for " + transform);
    }
    translationContext.setCurrentTransform(node.toAppliedPTransform(getPipeline()));
    translator.translate(transform, translationContext);
  }

  @Override
  public void visitValue(PValue value, TransformHierarchy.Node producer) {
    LOG.debug("visiting value {}", value);
  }

  /**
   * Records that instances of the specified PTransform class should be translated by default by the
   * corresponding {@link TransformTranslator}.
   */
  private static <TransformT extends PTransform> void registerTransformTranslator(
      Class<TransformT> transformClass,
      TransformTranslator<? extends TransformT> transformTranslator) {
    if (transformTranslators.put(transformClass, transformTranslator) != null) {
      throw new IllegalArgumentException("defining multiple translators for " + transformClass);
    }
  }

  /**
   * Returns the {@link TransformTranslator} to use for instances of the specified PTransform class,
   * or null if none registered.
   */
  private <TransformT extends PTransform<?, ?>>
      TransformTranslator<TransformT> getTransformTranslator(Class<TransformT> transformClass) {
    return transformTranslators.get(transformClass);
  }

  private static class ReadBoundedTranslator<T> implements TransformTranslator<Read.Bounded<T>> {
    private static final long serialVersionUID = 1L;

    @Override
    public void translate(Read.Bounded<T> transform, TranslationContext context) {
      // TODO: adapter is visibleForTesting
      BoundedToUnboundedSourceAdapter unboundedSource =
          new BoundedToUnboundedSourceAdapter<>(transform.getSource());
      ApexReadUnboundedInputOperator<T, ?> operator =
          new ApexReadUnboundedInputOperator<>(unboundedSource, true, context.getPipelineOptions());
      context.addOperator(operator, operator.output);
    }
  }

  private static class CreateApexPCollectionViewTranslator<ElemT, ViewT>
      implements TransformTranslator<CreateApexPCollectionView<ElemT, ViewT>> {
    private static final long serialVersionUID = 1L;

    @Override
    public void translate(
        CreateApexPCollectionView<ElemT, ViewT> transform, TranslationContext context) {
      context.addView(transform.getView());
      LOG.debug("view {}", transform.getView().getName());
    }
  }

  private static class CreatePCollectionViewTranslator<ElemT, ViewT>
      implements TransformTranslator<CreatePCollectionView<ElemT, ViewT>> {
    private static final long serialVersionUID = 1L;

    @Override
    public void translate(
        CreatePCollectionView<ElemT, ViewT> transform, TranslationContext context) {
      context.addView(transform.getView());
      LOG.debug("view {}", transform.getView().getName());
    }
  }

  private static class GBKIntoKeyedWorkItemsTranslator<K, InputT>
      implements TransformTranslator<GBKIntoKeyedWorkItems<K, InputT>> {

    @Override
    public void translate(GBKIntoKeyedWorkItems<K, InputT> transform, TranslationContext context) {
      // https://issues.apache.org/jira/browse/BEAM-1850
      ApexProcessFnOperator<KV<K, InputT>> operator =
          ApexProcessFnOperator.toKeyedWorkItems(context.getPipelineOptions());
      context.addOperator(operator, operator.outputPort);
      context.addStream(context.getInput(), operator.inputPort);
    }
  }
}


text:
module.exports = async function(ctx) {
  try {
    const { token } = this.settings
    const { commands, hears, on } = this.actions
    const { scenes } = this.flow
    const { user_id, peer_id, body, text, attachments = [] } = ctx
    const types = attachments.map(item => item.type)
    const flow = !!this.redis && await this.redis.get(`flow_${token}_${user_id || peer_id}`)
    const command = commands.find(item => item.command === (body || text))
    const hear = hears.find(item => item.command.test(body || text))
    const reserved = on
      .sort((a, b) => b.type == 'message' ? -1 : 1)
      .find(({ type }) => types.indexOf(type) !== -1 || type === 'message')

    if (flow) {
      const { scene, step, session } = flow
      const { [scene]: callbacks } = scenes
      const callback = callbacks[step]

      if (!(command && command.isPriority)) {
        return callback({
          ...flow,
          ...ctx,
          session,
        })
      }
    }

    if (command) {
      command.callback(ctx)
    } else if (hear) {
      hear.callback(ctx)
    } else if (reserved) {
      reserved.callback(ctx)
    }
  } catch (err) {
    this.catch(err)
  }
}


text:
package org.apache.hadoop.hbase.zookeeper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HConstants;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Common methods and attributes used by SplitLogManager and SplitLogWorker running distributed
 * splitting of WAL logs.
 * @deprecated since 2.4.0 and 3.0.0 replaced by procedure-based WAL splitting; see SplitWALManager.
 */
@Deprecated
@InterfaceAudience.Private
public final class ZKSplitLog {
  private static final Logger LOG = LoggerFactory.getLogger(ZKSplitLog.class);

  private ZKSplitLog() {
  }

  /**
   * Gets the full path node name for the log file being split. This method will url encode the
   * filename.
   * @param zkw      zk reference
   * @param filename log file name (only the basename)
   */
  public static String getEncodedNodeName(ZKWatcher zkw, String filename) {
    return ZNodePaths.joinZNode(zkw.getZNodePaths().splitLogZNode, encode(filename));
  }

  public static String getFileName(String node) {
    String basename = node.substring(node.lastIndexOf('/') + 1);
    return decode(basename);
  }

  static String encode(String s) {
    try {
      return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("URLENCODER doesn't support UTF-8");
    }
  }

  static String decode(String s) {
    try {
      return URLDecoder.decode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("URLDecoder doesn't support UTF-8");
    }
  }

  public static String getRescanNode(ZKWatcher zkw) {
    return ZNodePaths.joinZNode(zkw.getZNodePaths().splitLogZNode, "RESCAN");
  }

  /**
   * @param name the last part in path
   * @return whether the node name represents a rescan node
   */
  public static boolean isRescanNode(String name) {
    return name.startsWith("RESCAN");
  }

  /**
   * Checks if the given path represents a rescan node.
   * @param zkw  reference to the {@link ZKWatcher} which also contains configuration and constants
   * @param path the absolute path, starts with '/'
   * @return whether the path represents a rescan node
   */
  public static boolean isRescanNode(ZKWatcher zkw, String path) {
    String prefix = getRescanNode(zkw);
    if (path.length() <= prefix.length()) {
      return false;
    }
    for (int i = 0; i < prefix.length(); i++) {
      if (prefix.charAt(i) != path.charAt(i)) {
        return false;
      }
    }
    return true;
  }

  public static Path getSplitLogDir(Path rootdir, String tmpname) {
    return new Path(new Path(rootdir, HConstants.SPLIT_LOGDIR_NAME), tmpname);
  }

  public static void markCorrupted(Path rootdir, String logFileName, FileSystem fs) {
    Path file = new Path(getSplitLogDir(rootdir, logFileName), "corrupt");
    try {
      fs.createNewFile(file);
    } catch (IOException e) {
      LOG.warn("Could not flag a log file as corrupted. Failed to create " + file, e);
    }
  }

  public static boolean isCorrupted(Path rootdir, String logFileName, FileSystem fs)
    throws IOException {
    Path file = new Path(getSplitLogDir(rootdir, logFileName), "corrupt");
    boolean isCorrupt;
    isCorrupt = fs.exists(file);
    return isCorrupt;
  }
}


text:
echo "Building the current Factomd as a linux binary"
./build_factomd.sh
if [ $? -eq 0 ]; then
    echo "was binary updated? Current:`date`"
    ls -G -lh "/tmp/factomd-p2p-test-build/factomd"
    echo "Updating all the servers...."

    while IFS='' read -r line || [[ -n "$line" ]]; do
      echo "Updating: $line"
      ./copy_files_to_test_box.sh $line
    done < "./leaders.conf"

    while IFS='' read -r line || [[ -n "$line" ]]; do
      echo "Updating: $line"
      ./copy_files_to_test_box.sh $line
    done < "./followers.conf"
fi


text:
package co.cask.cdap;

import co.cask.cdap.api.app.AbstractApplication;
import co.cask.cdap.api.data.schema.UnsupportedTypeException;
import co.cask.cdap.api.data.stream.Stream;
import co.cask.cdap.api.dataset.lib.ObjectStores;
import co.cask.cdap.api.mapreduce.AbstractMapReduce;
import co.cask.cdap.api.mapreduce.MapReduceContext;
import co.cask.cdap.api.workflow.AbstractWorkflow;
import co.cask.cdap.api.workflow.AbstractWorkflowAction;
import co.cask.cdap.api.workflow.Value;
import co.cask.cdap.api.workflow.WorkflowActionConfigurer;
import co.cask.cdap.api.workflow.WorkflowActionSpecification;
import co.cask.cdap.api.workflow.WorkflowContext;
import co.cask.cdap.api.workflow.WorkflowToken;
import co.cask.cdap.internal.app.runtime.batch.WordCount;
import com.google.common.base.Throwables;
import org.apache.hadoop.mapreduce.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * App with workflow.
 */
public class AppWithWorkflow extends AbstractApplication {
  public static final String NAME = "AppWithWorkflow";

  @Override
  public void configure() {
    try {
      setName(NAME);
      setDescription("Sample application");
      addStream(new Stream("stream"));
      ObjectStores.createObjectStore(getConfigurer(), "input", String.class);
      ObjectStores.createObjectStore(getConfigurer(), "output", String.class);
      addMapReduce(new WordCountMapReduce());
      addWorkflow(new SampleWorkflow());
    } catch (UnsupportedTypeException e) {
      throw Throwables.propagate(e);
    }
  }

  /**
   * Sample workflow. has a dummy action.
   */
  public static class SampleWorkflow extends AbstractWorkflow {
    public static final String NAME = "SampleWorkflow";
    public static String firstActionName = "firstAction";
    public static String secondActionName = "secondAction";

    @Override
    public void configure() {
      setName(NAME);
      setDescription("SampleWorkflow description");
      addAction(new DummyAction(firstActionName));
      addAction(new DummyAction(secondActionName));
      addMapReduce(WordCountMapReduce.class.getSimpleName());
    }
  }

  /**
   * DummyAction
   */
  public static class DummyAction extends AbstractWorkflowAction {
    private static final Logger LOG = LoggerFactory.getLogger(DummyAction.class);
    public static final String TOKEN_KEY = "tokenKey";
    public static final String TOKEN_VALUE = "tokenValue";
    private final String name;

    public DummyAction(String name) {
      this.name = name;
    }

    @Override
    public void configure(WorkflowActionConfigurer configurer) {
      super.configure(configurer);
      setName(name);
    }

    @Override
    public void initialize(WorkflowContext context) throws Exception {
      super.initialize(context);
      WorkflowToken workflowToken = context.getToken();
      workflowToken.put(TOKEN_KEY, TOKEN_VALUE);
    }

    @Override
    public void run() {
      LOG.info("Ran dummy action");
    }
  }

  /**
   * WordCount MapReduce job
   */
  public static final class WordCountMapReduce extends AbstractMapReduce {
    public static final String NAME = "WordCountMapReduce";

    @Override
    public void configure() {
      setName(NAME);
      setDescription("WordCount job from Hadoop examples");
    }

    @Override
    @SuppressWarnings("ConstantConditions")
    public void beforeSubmit(MapReduceContext context) throws Exception {
      Map<String, String> args = context.getRuntimeArguments();
      String inputPath = args.get("inputPath");
      String outputPath = args.get("outputPath");
      WordCount.configureJob((Job) context.getHadoopJob(), inputPath, outputPath);
      WorkflowToken workflowToken = context.getWorkflowToken();
      if (workflowToken == null) {
        return;
      }
      // Put something in the token
      workflowToken.put("action_type", "MapReduce");
      workflowToken.put("start_time", Value.of(System.currentTimeMillis()));
    }
  }
}


text:
package com.softwaremill.common.cdi.transaction;

import org.slf4j.Logger;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.Status;
import javax.transaction.UserTransaction;
import java.io.Serializable;

/**
 * An interceptor for the {@link com.softwaremill.common.cdi.transaction.Transactional} annotation.
 *
 * @author Adam Warski (adam at warski dot org)
 * @link http://smokeandice.blogspot.com/2009/12/cdi-and-declarative-transactions.html
 */
@Transactional
@Interceptor
public class TransactionalInterceptor implements Serializable {

    @Inject
    private Logger logger;

    @Resource
    private UserTransaction utx;

    @AroundInvoke
    public Object intercept(InvocationContext ic) throws Throwable {
        boolean startedTransaction = false;
        if (utx.getStatus() != Status.STATUS_ACTIVE) {
            logger.debug("Starting a new transaction!");
            utx.begin();
            startedTransaction = true;
        }

        Object ret;
        try {
            ret = ic.proceed();

            if (startedTransaction) {
                logger.debug("Transaction was executed properly!");
                utx.commit();
            }
        } catch (Throwable t) {
            if (utx.getStatus() == Status.STATUS_ACTIVE || utx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                logger.debug("Rolling back transaction!");
                utx.rollback();
            }
            throw t;
        }

        return ret;
    }

}


text:
<component name="libraryTable">
  <library name="Maven: org.apache.curator:curator-client:2.4.0">
    <CLASSES>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/org/apache/curator/curator-client/2.4.0/curator-client-2.4.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/org/apache/curator/curator-client/2.4.0/curator-client-2.4.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/org/apache/curator/curator-client/2.4.0/curator-client-2.4.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
Bean2D
======

A JavaScript 3D block to 2D pixel Engine


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.znb.java</groupId>
    <artifactId>util</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>java-utils</name>
    <packaging>jar</packaging>

    <dependencies>
        <!-- json支持 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- common utils-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>

        <!--http client-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <!--log-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.13</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.13</version>
        </dependency>

        <!-- 发送邮件 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>thrift</artifactId>
            <version>0.5.0-fix-thrift1190</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

        <!-- DateTime 依赖包-->
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>1.6.5</version>
        </dependency>

        <!-- google 工具包 -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

    </dependencies>

    <build>
        <!-- build所需要的资源 -->
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <!-- build所需要的资源 -->
        <plugins>

            <!-- 编译使用1.6 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <fork>true</fork>
                    <verbose>true</verbose>
                    <encoding>UTF-8</encoding>
                    <compilerArguments>
                        war
                        <sourcepath>
                            ${project.basedir}/src/main/java
                        </sourcepath>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <!-- 忽略测试 -->
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Rose>*</Rose>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <!--包依赖插件,强制依赖处理-->
            <!--plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>analyze</id>
                        <goals>
                            <goal>analyze-only</goal>
                        </goals>
                        <configuration>
                            <failOnWarning>true</failOnWarning>
                            <ignoreNonCompile>true</ignoreNonCompile>
                        </configuration>
                    </execution>
                </executions>
            </plugin-->

            <!--plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-sources</id>
                        <phase>generate-sources</phase>
                        <configuration>
                            <tasks>
                                <exec executable="/bin/sh">
                                    <arg value="src/main/thrift/reader.sh"/>
                                </exec>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin-->

            <!--
            <plugin>
                <groupId>org.apache.thrift.tools</groupId>
                <artifactId>maven-thrift-plugin</artifactId>
                <version>0.1.10</version>
                <configuration>
                    <thriftExecutable>/usr/local/bin/thrift</thriftExecutable>
                    <generator>java</generator>
                    <outputDirectory>src/test/resources</outputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <id>thrift-sources</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.0.4</version>
                <configuration>
                    <includes>src/main/java</includes>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            -->

        </plugins>
    </build>

</project>


text:
from distutils.core import setup

setup(
    name='WebAppManager',
    version='0.2.5',
    author='Andrew Udvare',
    author_email='audvare@gmail.com',
    packages=['webappman'],
    url='https://github.com/Appdynamics/python-webappman',
    license='LICENSE.txt',
    description='Management of common web apps (Drupal, WordPress).',
    long_description=open('README.rst').read(),
    scripts=['bin/wam-install-drupal', 'bin/wam-install-wordpress'],
    install_requires=[
        'beautifulsoup4==4.3.2',
        'httpext>=0.1.3',
        'langutil>=0.1.4',
        'osextension>=0.1.2',
        'sh==1.09',
    ],
)


text:
using namespace std::chrono;

namespace
{
bool AreEqualEntries(std::vector<Cloud::EntryPtr> const & entries1,
                     std::vector<Cloud::EntryPtr> const & entries2)
{
  if (entries1.size() != entries2.size())
    return false;

  for (size_t i = 0; i < entries1.size(); ++i)
  {
    if (*entries1[i] != *entries2[i])
      return false;
  }

  return true;
}
}  // namespace

UNIT_TEST(Cloud_SerDes)
{
  Cloud::Index index;
  index.m_entries.emplace_back(std::make_shared<Cloud::Entry>("bm1.kml", 100, false));
  index.m_entries.emplace_back(std::make_shared<Cloud::Entry>("bm2.kml", 50, true));
  auto const h = duration_cast<hours>(system_clock::now().time_since_epoch()).count();
  index.m_lastUpdateInHours = static_cast<uint64_t>(h);
  index.m_isOutdated = true;

  std::string data;
  {
    using Sink = MemWriter<string>;
    Sink sink(data);
    coding::SerializerJson<Sink> ser(sink);
    ser(index);
  }

  Cloud::Index indexDes;
  {
    coding::DeserializerJson des(data);
    des(indexDes);
  }

  TEST_EQUAL(index.m_isOutdated, indexDes.m_isOutdated, ());
  TEST_EQUAL(index.m_lastUpdateInHours, indexDes.m_lastUpdateInHours, ());
  TEST(AreEqualEntries(index.m_entries, indexDes.m_entries), ());
}


text:
package bdv.ui.sourcegrouptree;

import bdv.ui.UIUtils;
import bdv.ui.sourcegrouptree.SourceGroupTreeModel.GroupModel;
import bdv.ui.sourcegrouptree.SourceGroupTreeModel.SourceModel;
import com.formdev.flatlaf.ui.FlatUIUtils;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;

/**
 * @author Tobias Pietzsch
 */
class SourceGroupTreeCellRenderer implements TreeCellRenderer
{
	/**
	 * Last tree the renderer was painted in.
	 */
	private JTree tree;

	/**
	 * Is the value currently selected.
	 */
	private boolean selected;

	/**
	 * True if has focus.
	 */
	private boolean hasFocus;

	// Color to use for the foreground for selected nodes.
	private Color selectionForeground;

	// TODO
	private Color selectionInactiveForeground;

	// Color to use for the foreground for non-selected nodes.
	private Color foreground;

	// Color to use for the background when the node isn't selected.
	private Color background;

	// Color to use for the background when the node is selected and the tree has focus.
	private Color selectionBackground;

	// Color to use for the background when the node is selected and the tree doesn't have focus.
	private Color selectionInactiveBackground;

	// Whether the tree has focus.
	private boolean treeHasFocus;

	// Color to use for the focus indicator when the node has focus.
	private Color selectionBorderColor;

	// TODO
	private Color dropCellBackground;

	// TODO
	private boolean rendererFillBackground;

	// If true, a dashed line is drawn as the focus indicator.
	private boolean drawDashedFocusIndicator;

	// If drawDashedFocusIndicator is true, the following are used.

	// Background color of the tree.
	private Color treeBGColor;

	// Color to draw the focus indicator in, determined from the background color.
	private Color focusBGColor;

	// actual renderers
	private GroupRenderer groupRenderer = new GroupRenderer();
	private SourceRenderer sourceRenderer = new SourceRenderer();

	// fallback for debugging
	private final DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

	SourceGroupTreeCellRenderer()
	{
		updateUI();
	}

	void updateUI()
	{
		foreground = UIManager.getColor( "Tree.foreground" ); // TODO: "foreground"?
		background = UIManager.getColor( "Tree.background" ); // TODO: "background"?
		selectionForeground = UIManager.getColor( "Tree.selectionForeground" );
		selectionInactiveForeground = FlatUIUtils.getUIColor(
				"Tree.selectionInactiveForeground",
				UIUtils.mix( selectionForeground, foreground, 0.0 )
		);
		selectionBackground = UIManager.getColor( "Tree.selectionBackground" );
		selectionInactiveBackground = FlatUIUtils.getUIColor(
				"Tree.selectionInactiveBackground",
				UIUtils.mix( selectionBackground, background, 0.5 )
		);
		selectionBorderColor = UIManager.getColor( "Tree.selectionBorderColor" );
		dropCellBackground = FlatUIUtils.getUIColor( "Tree.dropCellBackground", selectionBackground );
		rendererFillBackground = UIUtils.getUIBoolean( "Tree.rendererFillBackground", true );
		drawDashedFocusIndicator = UIUtils.getUIBoolean( "Tree.drawDashedFocusIndicator", false );
		SwingUtilities.updateComponentTreeUI( groupRenderer );
		SwingUtilities.updateComponentTreeUI( sourceRenderer );
	}

	/**
	 * Sets the color to use for the background if node is selected,
	 * depending on whether the tree has focus.
	 */
	public void setTreeHasFocus( final boolean hasFocus )
	{
		treeHasFocus = hasFocus;
	}

	/**
	 * Returns the color to use for the background if node is selected.
	 */
	public Color getBackgroundSelectionColor()
	{
		return treeHasFocus ? selectionBackground : selectionInactiveBackground;
	}

	@Override
	public Component getTreeCellRendererComponent( final JTree tree, final Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus )
	{
		this.tree = tree;
		this.hasFocus = hasFocus;
		this.selected = selected;

		if ( value instanceof GroupModel )
			return groupRenderer.getTreeCellRendererComponent( ( GroupModel ) value );
		else if ( value instanceof SourceModel )
			return sourceRenderer.getTreeCellRendererComponent( ( SourceModel ) value );
		else
			return defaultRenderer.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
	}

	public int determineOffset( final Object value )
	{
		if ( value instanceof GroupModel )
			return groupRenderer.getOffset();
		else if ( value instanceof SourceModel )
			return sourceRenderer.getOffset();
		else
			return 0;
	}

	public boolean currentHit( final int x, final int y )
	{
		return groupRenderer.currentHit( x, y );
	}

	public boolean activeHit( final int x, final int y )
	{
		return groupRenderer.activeHit( x, y );
	}

	class TreeLabel extends JLabel
	{
		@Override
		public void setFont( Font font )
		{
			if ( font instanceof FontUIResource )
				font = null;
			super.setFont( font );
		}

		@Override
		public Font getFont()
		{
			Font font = super.getFont();
			if ( font == null && tree != null )
			{
				font = tree.getFont();
			}
			return font;
		}
	}

	private void paintFocus( Graphics g, int x, int y, int w, int h, Color notColor )
	{
		Color bsColor = selectionBorderColor;

		if ( bsColor != null && ( selected || !drawDashedFocusIndicator ) )
		{
			g.setColor( bsColor );
			g.drawRect( x, y, w - 1, h - 1 );
		}
		if ( drawDashedFocusIndicator && notColor != null )
		{
			if ( treeBGColor != notColor )
			{
				treeBGColor = notColor;
				focusBGColor = new Color( ~notColor.getRGB() );
			}
			g.setColor( focusBGColor );
			BasicGraphicsUtils.drawDashedRect( g, x, y, w, h );
		}
	}

	class GroupRenderer extends JPanel
	{
		private final TreeLabel nameLabel;

		private final JRadioButton currentRadioButton;

		private final JCheckBox activeCheckBox;

		GroupRenderer()
		{
			setLayout( new BoxLayout( this, BoxLayout.X_AXIS ) );
			setBorder( new EmptyBorder( 0, 0, 0, 0 ) );
			nameLabel = new TreeLabel();
//			UIUtils.setPreferredWidth( nameLabel, 100 );
			currentRadioButton = new JRadioButton();
			currentRadioButton.setBorder( new EmptyBorder( 0, 0, 0, 5 ) );
			currentRadioButton.setOpaque( false );
			activeCheckBox = new JCheckBox();
			activeCheckBox.setBorder( new EmptyBorder( 0, 0, 0, 5 ) );
			activeCheckBox.setOpaque( false );
			add( currentRadioButton );
			add( activeCheckBox );
			add( nameLabel );
			setOpaque( false );
			invalidate();
		}

		@Override
		public void setFont( Font font )
		{
			if ( font instanceof FontUIResource )
				font = null;
			super.setFont( font );
		}

		@Override
		public Font getFont()
		{
			Font font = super.getFont();
			if ( font == null && tree != null )
			{
				font = tree.getFont();
			}
			return font;
		}

		public Component getTreeCellRendererComponent( final GroupModel group )
		{
			nameLabel.setText( group.getName() );
			currentRadioButton.setSelected( group.isCurrent() );
			activeCheckBox.setSelected( group.isActive() );

			final Color fg;
			final Color bg;
			if ( selected )
			{
				fg = treeHasFocus ? selectionForeground : selectionInactiveForeground;
				bg = treeHasFocus ? selectionBackground : selectionInactiveBackground;
			}
			else
			{
				fg = foreground;
				bg = background;
			}
			nameLabel.setForeground( fg );
			nameLabel.setBackground( bg );

			final boolean enabled = tree.isEnabled();
			setEnabled( enabled );
			nameLabel.setEnabled( enabled );
			currentRadioButton.setEnabled( enabled );
			activeCheckBox.setEnabled( enabled );

			final ComponentOrientation componentOrientation = tree.getComponentOrientation();
			setComponentOrientation( componentOrientation );
			nameLabel.setComponentOrientation( componentOrientation );
			currentRadioButton.setComponentOrientation( componentOrientation );
			activeCheckBox.setComponentOrientation( componentOrientation );

			invalidate();
			return this;
		}

		// TODO
		private boolean isDropCell = false;

		/**
		 * Paints the value.  The background is filled based on selected.
		 */
		@Override
		public void paint( Graphics g )
		{
			Color bColor;

			if ( isDropCell )
				bColor = dropCellBackground;
			else if ( selected )
				bColor = getBackgroundSelectionColor();
			else
				bColor = background;

			if ( bColor == null )
				bColor = getBackground();

			if ( bColor != null && rendererFillBackground )
			{
				g.setColor( bColor );
				g.fillRect( 0, 0, getWidth(), getHeight() );
			}

			if ( hasFocus )
				paintFocus( g, 0, 0, getWidth(), getHeight(), bColor );

			super.paint( g );
		}

		public int getOffset()
		{
			return nameLabel.getX();
		}

		public boolean currentHit( final int x, final int y )
		{
			return currentRadioButton.getBounds().contains( x, y );
		}

		public boolean activeHit( final int x, final int y )
		{
			return activeCheckBox.getBounds().contains( x, y );
		}
	}

	class SourceRenderer extends TreeLabel
	{
		SourceRenderer()
		{
			setBorder( new EmptyBorder( 0, 35, 0, 0 ) );
			setOpaque( false );
		}

		public Component getTreeCellRendererComponent( final SourceModel source )
		{
			setText( source.getName() );

			final Color fg;
			final Color bg;
			if ( selected )
			{
				fg = treeHasFocus ? selectionForeground : selectionInactiveForeground;
				bg = treeHasFocus ? selectionBackground : selectionInactiveBackground;
			}
			else
			{
				fg = foreground;
				bg = background;
			}
			setForeground( fg );
			setBackground( bg );

			final boolean enabled = tree.isEnabled();
			setEnabled( enabled );

			final ComponentOrientation componentOrientation = tree.getComponentOrientation();
			setComponentOrientation( componentOrientation );

			return this;
		}

		// TODO
		private boolean isDropCell = false;

		/**
		 * Paints the value.  The background is filled based on selected.
		 */
		@Override
		public void paint( Graphics g )
		{
			Color bColor;

			if ( isDropCell )
				bColor = dropCellBackground;
			else if ( selected )
				bColor = getBackgroundSelectionColor();
			else
				bColor = background;

			if ( bColor == null )
				bColor = getBackground();

			if ( bColor != null && rendererFillBackground )
			{
				g.setColor( bColor );
				g.fillRect( 0, 0, getWidth(), getHeight() );
			}

			if ( hasFocus )
				paintFocus( g, 0, 0, getWidth(), getHeight(), bColor );

			super.paint( g );
		}

		public int getOffset()
		{
			return getX();
		}
	}
}


text:
module ParserUtil ( runGet
                  , runGetMaybe
                  , parseManyLazily
                  , parseManyLazyByteStringLazily
                  , parseKeepRaw
                  , match
                  , match_
                  , eof
                  ) where

import qualified Control.Monad as M
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import qualified Data.Serialize.Get as Get
import Control.Applicative ((<$>), (*>), (<*>), pure)

runGet :: Get.Get a -> BS.ByteString -> a
runGet p s = either error id $ Get.runGet p s
{-# INLINE runGet #-}

runGetMaybe :: Get.Get a -> BS.ByteString -> Maybe a
runGetMaybe p s = either (const Nothing) Just $ Get.runGet p s
{-# INLINE runGetMaybe #-}

parseManyLazily :: Get.Get a -> BS.ByteString -> [a]
parseManyLazily p s  | BS.null s = []
                     | otherwise = case Get.runGetState p s 0 of
  Right (r, rest) -> r : parseManyLazily p rest
  Left _ -> []
{-# INLINE parseManyLazily #-}

parseManyLazyByteStringLazily :: Get.Get a -> BSL.ByteString -> [a]
parseManyLazyByteStringLazily p = concatMap (parseManyLazily p) . BSL.toChunks

match :: Eq a => Get.Get a -> a -> Get.Get a
match p test = do
  result <- p
  if result == test
    then return result
    else fail ""
{-# INLINE match #-}

match_ :: Eq a => Get.Get a -> a -> Get.Get ()
match_ p test = match p test *> pure ()
{-# INLINE match_ #-}

parseKeepRaw :: Get.Get a -> Get.Get (BS.ByteString, a)
parseKeepRaw g = do
  (len, r) <- Get.lookAhead $ do
                (res,after) <- Get.lookAhead $ (,) <$> g <*> Get.remaining
                total <- Get.remaining
                return (total-after, res)
  bs <- Get.getBytes len
  return (bs, r)
{-# INLINE parseKeepRaw #-}

eof :: Get.Get ()
eof = do
  empty <- Get.isEmpty
  M.unless empty $ fail "expected eof"
{-# INLINE eof #-}


text:
var _ = require('lodash'),
    settingsCache = require('../../services/settings/cache');

function getTitle(data, root, options) {
    var title = '',
        context = root ? root.context : null,
        postSdTitle,
        blogTitle = settingsCache.get('title'),
        pagination = root ? root.pagination : null,
        pageString = '';

    options = options ? options : {};

    if (pagination && pagination.total > 1) {
        pageString = ' (Page ' + pagination.page + ')';
    }

    // If there's a specific meta title
    if (data.meta_title) {
        title = data.meta_title;
    // Home title
    } else if (_.includes(context, 'home')) {
        title = blogTitle;
    // Author title, paged
    } else if (_.includes(context, 'author') && data.author && _.includes(context, 'paged')) {
        title = data.author.name + ' - ' + blogTitle + pageString;
    // Author title, index
    } else if (_.includes(context, 'author') && data.author) {
        title = data.author.name + ' - ' + blogTitle;
    // Tag title, paged
    } else if (_.includes(context, 'tag') && data.tag && _.includes(context, 'paged')) {
        title = data.tag.meta_title || data.tag.name + ' - ' + blogTitle + pageString;
    // Tag title, index
    } else if (_.includes(context, 'tag') && data.tag) {
        title = data.tag.meta_title || data.tag.name + ' - ' + blogTitle;
    // Post title
    } else if ((_.includes(context, 'post') || _.includes(context, 'page')) && data.post) {
        if (options && options.property) {
            postSdTitle = options.property + '_title';
            title = data.post[postSdTitle] || '';
        } else {
            title = data.post.meta_title || data.post.title;
        }
    // Fallback
    } else {
        title = blogTitle + pageString;
    }

    return (title || '').trim();
}

module.exports = getTitle;


text:
from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate

if __name__ == '__main__':
    migrator = PostgresqlMigrator(db.database)

    with db.database.transaction():
        # Change the uniqueness constraint on data source name to be (org, name):
        # In some cases it's a constraint:
        db.database.execute_sql('ALTER TABLE data_sources DROP CONSTRAINT IF EXISTS unique_name')
        # In others only an index:
        db.database.execute_sql('DROP INDEX IF EXISTS data_sources_name')

        migrate(
            migrator.add_index('data_sources', ('org_id', 'name'), unique=True)
        )

    db.close_db(None)