text:
@extends('voyager::master')

@section('css')
    <link rel="stylesheet" type="text/css" href="{{ config('voyager.assets_path') }}/css/nestable.css">
@stop

@section('page_header')

        目录生成器 ({{ $menu->name }})

 新建

    @include('voyager::multilingual.language-selector')
@stop

@section('content')
    @include('voyager::menus.partial.notice')

支持拖放操作

                            {!! menu($menu->name, 'admin', ['isModelTranslatable' => $isModelTranslatable]) !!}

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 确定要删除当前目录吗

                    <form action="{{ route('voyager.menus.item.destroy', ['menu' => $menu->id, 'id' => '__id']) }}" id="delete_form"
                          method="POST">
                        {{ method_field("DELETE") }}
                        {{ csrf_field() }}
                        <input type="submit" class="btn btn-danger pull-right delete-confirm"
                               value="确定删除当前目录">
                    </form>
                    <button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 新建

                <form action="{{ route('voyager.menus.item.add', ['menu' => $menu->id]) }}" id="add_form" method="POST">

                        @include('voyager::multilingual.language-selector')
                        标题
                        @include('voyager::multilingual.input-hidden-menu', ['_field_name' => 'add_title', '_field_trans' => ''])
                        <input type="text" class="form-control" id="add_title" name="title" placeholder="Title">

                        地址
                        <input type="text" class="form-control" name="url" placeholder="URL">

                        图标 (Use a Voyager Font Class)
                        <input type="text" class="form-control" name="icon_class"
                               placeholder="Icon Class (optional)">

                        颜色 (选填)
                        <input type="color" class="form-control" name="color"
                               placeholder="Color (ex. #ffffff or rgb(255, 255, 255)">

                        打开方式
                        <select id="edit_target" class="form-control" name="target">
                            <option value="_self">当前窗口</option>
                            <option value="_blank">新建窗口</option>
                        </select>
                        <input type="hidden" name="menu_id" value="{{ $menu->id }}">

                    {{ csrf_field() }}

                        <input type="submit" class="btn btn-success pull-right delete-confirm" value="新建">
                        <button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>

                </form>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 编辑目录

                <form action="{{ route('voyager.menus.item.update', ['menu' => $menu->id]) }}" id="edit_form" method="POST">
                    {{ method_field("PUT") }}
                    {{ csrf_field() }}

                        @include('voyager::multilingual.language-selector')
                        标题
                        @include('voyager::multilingual.input-hidden-menu', ['_field_name' => 'edit_title', '_field_trans' => ''])
                        <input type="text" class="form-control" id="edit_title" name="title" placeholder="Title">

                        链接类型
                        <select id="edit_type" class="form-control" name="type">
                            <option value="url" selected="selected">静态URL</option>
                            <option value="route">动态路由</option>
                        </select>

                            URL地址
                            <input type="text" class="form-control" id="edit_url" name="url" placeholder="URL">

                            路由
                            <input type="text" class="form-control" id="edit_route" name="route" placeholder="Route">

                            路由参数 (如果有)
                            <textarea rows="3" class="form-control" id="edit_parameters" name="parameters" placeholder="{{ json_encode(['key' => 'value'], JSON_PRETTY_PRINT) }}"></textarea>

                        图标 (Use a Voyager Font Class)
                        <input type="text" class="form-control" id="edit_icon_class" name="icon_class"
                               placeholder="Icon Class (optional)">

                        颜色 (选填)
                        <input type="color" class="form-control" id="edit_color" name="color"
                               placeholder="Color (ex. #ffffff or rgb(255, 255, 255)">

                        打开方式
                        <select id="edit_target" class="form-control" name="target">
                             <option value="_self">当前窗口</option>
                            <option value="_blank">新建窗口</option>
                        </select>
                        <input type="hidden" name="id" id="edit_id" value="">

                        <input type="submit" class="btn btn-success pull-right delete-confirm" value="保存">
                        <button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>

                </form>

@stop

@section('javascript')

    @if($isModelTranslatable)

    @endif

@stop


text:
require('dotenv-extended').load();

var builder = require('botbuilder');
var restify = require('restify');
var Store = require('./store');
var spellService = require('./spell-service');

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log('%s listening to %s', server.name, server.url);
});
// Create connector and listen for messages
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());

var bot = new builder.UniversalBot(connector, function (session) {
    session.send('Sorry, I did not understand \'%s\'. Type \'help\' if you need assistance.', session.message.text);
});

// You can provide your own model by specifing the 'LUIS_MODEL_URL' environment variable
// This Url can be obtained by uploading or creating your model from the LUIS portal: https://www.luis.ai/
var recognizer = new builder.LuisRecognizer(process.env.LUIS_MODEL_URL);
bot.recognizer(recognizer);

bot.dialog('SearchHotels', [
    function (session, args, next) {
        session.send('Welcome to the Hotels finder! We are analyzing your message: \'%s\'', session.message.text);

        // try extracting entities
        var cityEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.geography.city');
        var airportEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'AirportCode');
        if (cityEntity) {
            // city entity detected, continue to next step
            session.dialogData.searchType = 'city';
            next({ response: cityEntity.entity });
        } else if (airportEntity) {
            // airport entity detected, continue to next step
            session.dialogData.searchType = 'airport';
            next({ response: airportEntity.entity });
        } else {
            // no entities detected, ask user for a destination
            builder.Prompts.text(session, 'Please enter your destination');
        }
    },
    function (session, results) {
        var destination = results.response;

        var message = 'Looking for hotels';
        if (session.dialogData.searchType === 'airport') {
            message += ' near %s airport...';
        } else {
            message += ' in %s...';
        }

        session.send(message, destination);

        // Async search
        Store
            .searchHotels(destination)
            .then(function (hotels) {
                // args
                session.send('I found %d hotels:', hotels.length);

                var message = new builder.Message()
                    .attachmentLayout(builder.AttachmentLayout.carousel)
                    .attachments(hotels.map(hotelAsAttachment));

                session.send(message);

                // End
                session.endDialog();
            });
    }
]).triggerAction({
    matches: 'SearchHotels',
    onInterrupted: function (session) {
        session.send('Please provide a destination');
    }
});

bot.dialog('ShowHotelsReviews', function (session, args) {
    // retrieve hotel name from matched entities
    var hotelEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'Hotel');
    if (hotelEntity) {
        session.send('Looking for reviews of \'%s\'...', hotelEntity.entity);
        Store.searchHotelReviews(hotelEntity.entity)
            .then(function (reviews) {
                var message = new builder.Message()
                    .attachmentLayout(builder.AttachmentLayout.carousel)
                    .attachments(reviews.map(reviewAsAttachment));
                session.endDialog(message);
            });
    }
}).triggerAction({
    matches: 'ShowHotelsReviews'
});

bot.dialog('Help', function (session) {
    session.endDialog('Hi! Try asking me things like \'search hotels in Seattle\', \'search hotels near LAX airport\' or \'show me the reviews of The Bot Resort\'');
}).triggerAction({
    matches: 'Help'
});

// Spell Check
if (process.env.IS_SPELL_CORRECTION_ENABLED === 'true') {
    bot.use({
        botbuilder: function (session, next) {
            spellService
                .getCorrectedText(session.message.text)
                .then(function (text) {
                    session.message.text = text;
                    next();
                })
                .catch(function (error) {
                    console.error(error);
                    next();
                });
        }
    });
}

// Helpers
function hotelAsAttachment(hotel) {
    return new builder.HeroCard()
        .title(hotel.name)
        .subtitle('%d stars. %d reviews. From $%d per night.', hotel.rating, hotel.numberOfReviews, hotel.priceStarting)
        .images([new builder.CardImage().url(hotel.image)])
        .buttons([
            new builder.CardAction()
                .title('More details')
                .type('openUrl')
                .value('https://www.bing.com/search?q=hotels+in+' + encodeURIComponent(hotel.location))
        ]);
}

function reviewAsAttachment(review) {
    return new builder.ThumbnailCard()
        .title(review.title)
        .text(review.text)
        .images([new builder.CardImage().url(review.image)]);
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file   key_store.c
 * @author Catalin Ionita <catalin.ionita@intel.com>
 * @date   Mon Oct 14 17:56:53 2013
 *
 * @brief
 * Key store interface for EFS
 *
 */

/**
 * Copyright (C) 2013 Intel Corporation, All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Catalin Ionita <catalin.ionita@intel.com>
 */

#include <openssl/evp.h>
#include <openssl/sha.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <dirent.h>
#include <efs/key_chain.h>
#include <efs/file_utils.h>
#include <efs/efs.h>
#include <efs/process.h>
#include <efs/crypto.h>
#include <efs/key_store.h>

/**
 * Construction to get the private storage path
 * The private storage path for /data/my_encrypted_storage will be /data/.my_encrypted_storage
 *
 * @param path Private EFS path
 * @param storage_path EFS path
 *
 * @return 0 on succes, negative value on error
 */
int get_private_storage_path(char *path, char *storage_path)
{
    int i = strlen(storage_path);

    if (i >= MAX_PATH_LENGTH)
        return -1;

    /* Look for the next '/' */
    for (; i > 0; i--)
        if (storage_path[i] == '/')
            break;

    /* Insert a "." in the new path */
    if (i != 0) {
        strncpy(path, storage_path, i + 1);
        path[i + 1] = '.';
        strcpy(path + i + 2, storage_path + i + 1);
    } else {
        path[0] = '.';
        strcpy(path + 1, storage_path);
    }

    return 0;
}

/**
 * Get the recovery path
 * Recovery path is a temporary path were data recovery is attempted
 * Recovery path can be specified by setting DATA_RECOVERY_PATH
 *
 * @param recovery_path Recovery path
 * @param storage_path EFS path
 *
 * @return 0 on success, negative value on error
 */
int get_recovery_path(char *recovery_path, char *storage_path)
{
    int i = strlen(storage_path) - 1;
    int len = strlen(DATA_RECOVERY_PATH);

    for (; i > 0; i--)
        if (storage_path[i] == '/')
            break;

    if (len + strlen(storage_path) - i > MAX_PATH_LENGTH)
        return -1;

    strcpy(recovery_path, DATA_RECOVERY_PATH);
    strcpy(recovery_path + len, storage_path + i);

    return 0;
}

/**
 * Clean up a path by remove multiple //
 * No relative paths are allowed
 *
 * @param storage_path Path
 *
 * @return 0 on succes, negative value on error
 */
int sanitize_storage_path(char *storage_path)
{
    int ret = -1, i = 0;

    if (!storage_path) {
        LOGE("Storage path is null");
        return -1;
    }

    i = strlen(storage_path) - 1;
    if (i > MAX_PATH_LENGTH - 1) {
        LOGE("Invalid storage_path size");
        return -1;
    }

    if (storage_path[0] != '/') {
        LOGE("Full path is required starting from /");
        return -1;
    }
    /* Remove end "/" */
    for (; i >= 0; i--) {
        if (storage_path[i] != '/')
            break;
        storage_path[i] = 0;
    }

    if (storage_path[0] == 0) {
        LOGE("root encrypted storage is not allowed");
        return -1;
    }

    ret = access(storage_path, F_OK);
    if (ret < 0) {
        LOGE("Can't access %s", storage_path);
        return ret;
    }

    return 0;
}

/**
 * Get the path were crypto material is stored for a particular EFS
 *
 * @param path Key storage path
 * @param storage_path EFS storage path
 *
 * @return positive value on success, negative value on error
 */
int get_key_storage_path(char *path, char *storage_path)
{
    unsigned char hash[SHA512_DIGEST_LENGTH];
    char id[2 * SHA512_DIGEST_LENGTH + 1];
    char input[MAX_PATH_LENGTH];
    unsigned int i = 0;

    memset(id, 0, sizeof(id));
    memset(input, 0, sizeof(input));
    strncpy(input, storage_path, sizeof(input));

    SHA512((unsigned char *)input, sizeof(hash), hash);

    for (; i < sizeof(hash); i++) {
        snprintf(id + 2 * i, 3, "%02x", hash[i]);
    }

    return snprintf(path, MAX_PATH_LENGTH, "%s%s.%s", KEY_STORAGE_PATH,
            KEY_FILE_NAME, id);
}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var _ = require('lodash');  /* jshint ignore:line */
var util = require('util');  /* jshint ignore:line */
var AuthRegistrationsCredentialListMappingList = require(
    './authRegistrationsMapping/authRegistrationsCredentialListMapping').AuthRegistrationsCredentialListMappingList;

var AuthTypeRegistrationsList;

/* jshint ignore:start */
/**
 * Initialize the AuthTypeRegistrationsList
 *
 * @constructor Twilio.Api.V2010.AccountContext.SipContext.DomainContext.AuthTypesContext.AuthTypeRegistrationsList
 *
 * @param {Twilio.Api.V2010} version - Version of the resource
 * @param {string} accountSid - The SID of the Account that created the resource
 * @param {string} domainSid - The unique string that identifies the resource
 */
/* jshint ignore:end */
AuthTypeRegistrationsList = function AuthTypeRegistrationsList(version,
    accountSid, domainSid) {
  /* jshint ignore:start */
  /**
   * @function registrations
   * @memberof Twilio.Api.V2010.AccountContext.SipContext.DomainContext.AuthTypesContext#
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Api.V2010.AccountContext.SipContext.DomainContext.AuthTypesContext.AuthTypeRegistrationsContext}
   */
  /* jshint ignore:end */
  function AuthTypeRegistrationsListInstance(sid) {
    return AuthTypeRegistrationsListInstance.get(sid);
  }

  AuthTypeRegistrationsListInstance._version = version;
  // Path Solution
  AuthTypeRegistrationsListInstance._solution = {accountSid: accountSid, domainSid: domainSid};

  // Components
  AuthTypeRegistrationsListInstance._credentialListMappings = undefined;

  Object.defineProperty(AuthTypeRegistrationsListInstance,
    'credentialListMappings', {
      get: function credentialListMappings() {
        if (!this._credentialListMappings) {
          this._credentialListMappings = new AuthRegistrationsCredentialListMappingList(
            this._version,
            this._solution.accountSid,
            this._solution.domainSid
          );
        }

        return this._credentialListMappings;
      }
  });

  /* jshint ignore:start */
  /**
   * Provide a user-friendly representation
   *
   * @function toJSON
   * @memberof Twilio.Api.V2010.AccountContext.SipContext.DomainContext.AuthTypesContext.AuthTypeRegistrationsList#
   *
   * @returns Object
   */
  /* jshint ignore:end */
  AuthTypeRegistrationsListInstance.toJSON = function toJSON() {
    return this._solution;
  };

  AuthTypeRegistrationsListInstance[util.inspect.custom] = function inspect(depth,
      options) {
    return util.inspect(this.toJSON(), options);
  };

  return AuthTypeRegistrationsListInstance;
};

module.exports = {
  AuthTypeRegistrationsList: AuthTypeRegistrationsList
};


text:
package org.apache.lucene.store;

import java.io.EOFException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;

import org.apache.lucene.store.Directory; // javadoc
import org.apache.lucene.store.IOContext.Context;
import org.apache.lucene.util.SuppressForbidden;

// TODO
//   - newer Linux kernel versions (after 2.6.29) have
//     improved MADV_SEQUENTIAL (and hopefully also
//     FADV_SEQUENTIAL) interaction with the buffer
//     cache; we should explore using that instead of direct
//     IO when context is merge

/**
 * A {@link Directory} implementation for all Unixes that uses
 * DIRECT I/O to bypass OS level IO caching during
 * merging.  For all other cases (searching, writing) we delegate
 * to the provided Directory instance.
 *
 *
See Overview
 * for more details.
 *
 *
To use this you must compile
 * NativePosixUtil.cpp (exposes Linux-specific APIs through
 * JNI) for your platform, by running ant
 * build-native-unix, and then putting the resulting
 * libNativePosixUtil.so (from
 * lucene/build/native) onto your dynamic
 * linker search path.
 *
 *
WARNING: this code is very new and quite easily
 * could contain horrible bugs.  For example, here's one
 * known issue: if you use seek in IndexOutput, and then
 * write more than one buffer's worth of bytes, then the
 * file will be wrong.  Lucene does not do this today (only writes
 * small number of bytes after seek), but that may change.
 *
 *
This directory passes Solr and Lucene tests on Linux
 * and OS X; other Unixes should work but have not been
 * tested!  Use at your own risk.
 *
 * @lucene.experimental
 */
public class NativeUnixDirectory extends FSDirectory {

  // TODO: this is OS dependent, but likely 512 is the LCD
  private final static long ALIGN = 512;
  private final static long ALIGN_NOT_MASK = ~(ALIGN-1);

  /** Default buffer size before writing to disk (256 KB);
   *  larger means less IO load but more RAM and direct
   *  buffer storage space consumed during merging. */

  public final static int DEFAULT_MERGE_BUFFER_SIZE = 262144;

  /** Default min expected merge size before direct IO is
   *  used (10 MB): */
  public final static long DEFAULT_MIN_BYTES_DIRECT = 10*1024*1024;

  private final int mergeBufferSize;
  private final long minBytesDirect;
  private final Directory delegate;

  /** Create a new NIOFSDirectory for the named location.
   *
   * @param path the path of the directory
   * @param lockFactory to use
   * @param mergeBufferSize Size of buffer to use for
   *    merging.  See {@link #DEFAULT_MERGE_BUFFER_SIZE}.
   * @param minBytesDirect Merges, or files to be opened for
   *   reading, smaller than this will
   *   not use direct IO.  See {@link
   *   #DEFAULT_MIN_BYTES_DIRECT}
   * @param delegate fallback Directory for non-merges
   * @throws IOException If there is a low-level I/O error
   */
  public NativeUnixDirectory(Path path, int mergeBufferSize, long minBytesDirect, LockFactory lockFactory, Directory delegate) throws IOException {
    super(path, lockFactory);
    if ((mergeBufferSize & ALIGN) != 0) {
      throw new IllegalArgumentException("mergeBufferSize must be 0 mod " + ALIGN + " (got: " + mergeBufferSize + ")");
    }
    this.mergeBufferSize = mergeBufferSize;
    this.minBytesDirect = minBytesDirect;
    this.delegate = delegate;
  }

  /** Create a new NIOFSDirectory for the named location.
   *
   * @param path the path of the directory
   * @param lockFactory the lock factory to use
   * @param delegate fallback Directory for non-merges
   * @throws IOException If there is a low-level I/O error
   */
  public NativeUnixDirectory(Path path, LockFactory lockFactory, Directory delegate) throws IOException {
    this(path, DEFAULT_MERGE_BUFFER_SIZE, DEFAULT_MIN_BYTES_DIRECT, lockFactory, delegate);
  }

  /** Create a new NIOFSDirectory for the named location with {@link FSLockFactory#getDefault()}.
   *
   * @param path the path of the directory
   * @param delegate fallback Directory for non-merges
   * @throws IOException If there is a low-level I/O error
   */
  public NativeUnixDirectory(Path path, Directory delegate) throws IOException {
    this(path, DEFAULT_MERGE_BUFFER_SIZE, DEFAULT_MIN_BYTES_DIRECT, FSLockFactory.getDefault(), delegate);
  }

  @Override
  public IndexInput openInput(String name, IOContext context) throws IOException {
    ensureOpen();
    if (context.context != Context.MERGE || context.mergeInfo.estimatedMergeBytes < minBytesDirect || fileLength(name) < minBytesDirect) {
      return delegate.openInput(name, context);
    } else {
      return new NativeUnixIndexInput(getDirectory().resolve(name), mergeBufferSize);
    }
  }

  @Override
  public IndexOutput createOutput(String name, IOContext context) throws IOException {
    ensureOpen();
    if (context.context != Context.MERGE || context.mergeInfo.estimatedMergeBytes < minBytesDirect) {
      return delegate.createOutput(name, context);
    } else {
      ensureCanWrite(name);
      return new NativeUnixIndexOutput(getDirectory().resolve(name), mergeBufferSize);
    }
  }

  @SuppressForbidden(reason = "java.io.File: native API requires old-style FileDescriptor")
  private final static class NativeUnixIndexOutput extends IndexOutput {
    private final ByteBuffer buffer;
    private final FileOutputStream fos;
    private final FileChannel channel;
    private final int bufferSize;

    //private final File path;

    private int bufferPos;
    private long filePos;
    private long fileLength;
    private boolean isOpen;

    public NativeUnixIndexOutput(Path path, int bufferSize) throws IOException {
      super("NativeUnixIndexOutput(path=\"" + path.toString() + "\")");
      //this.path = path;
      final FileDescriptor fd = NativePosixUtil.open_direct(path.toString(), false);
      fos = new FileOutputStream(fd);
      //fos = new FileOutputStream(path);
      channel = fos.getChannel();
      buffer = ByteBuffer.allocateDirect(bufferSize);
      this.bufferSize = bufferSize;
      isOpen = true;
    }

    @Override
    public void writeByte(byte b) throws IOException {
      assert bufferPos == buffer.position(): "bufferPos=" + bufferPos + " vs buffer.position()=" + buffer.position();
      buffer.put(b);
      if (++bufferPos == bufferSize) {
        dump();
      }
    }

    @Override
    public void writeBytes(byte[] src, int offset, int len) throws IOException {
      int toWrite = len;
      while(true) {
        final int left = bufferSize - bufferPos;
        if (left <= toWrite) {
          buffer.put(src, offset, left);
          toWrite -= left;
          offset += left;
          bufferPos = bufferSize;
          dump();
        } else {
          buffer.put(src, offset, toWrite);
          bufferPos += toWrite;
          break;
        }
      }
    }

    //@Override
    //public void setLength() throws IOException {
    //   TODO -- how to impl this?  neither FOS nor
    //   FileChannel provides an API?
    //}

    private void dump() throws IOException {
      buffer.flip();
      final long limit = filePos + buffer.limit();
      if (limit > fileLength) {
        // this dump extends the file
        fileLength = limit;
      } else {
        // we had seek'd back & wrote some changes
      }

      // must always round to next block
      buffer.limit((int) ((buffer.limit() + ALIGN - 1) & ALIGN_NOT_MASK));

      assert (buffer.limit() & ALIGN_NOT_MASK) == buffer.limit() : "limit=" + buffer.limit() + " vs " + (buffer.limit() & ALIGN_NOT_MASK);
      assert (filePos & ALIGN_NOT_MASK) == filePos;
      //System.out.println(Thread.currentThread().getName() + ": dump to " + filePos + " limit=" + buffer.limit() + " fos=" + fos);
      channel.write(buffer, filePos);
      filePos += bufferPos;
      bufferPos = 0;
      buffer.clear();
      //System.out.println("dump: done");

      // TODO: the case where we'd seek'd back, wrote an
      // entire buffer, we must here read the next buffer;
      // likely Lucene won't trip on this since we only
      // write smallish amounts on seeking back
    }

    @Override
    public long getFilePointer() {
      return filePos + bufferPos;
    }

    @Override
    public long getChecksum() throws IOException {
      throw new UnsupportedOperationException("this directory currently does not work at all!");
    }

    @Override
    public void close() throws IOException {
      if (isOpen) {
        isOpen = false;
        try {
          dump();
        } finally {
          try {
            //System.out.println("direct close set len=" + fileLength + " vs " + channel.size() + " path=" + path);
            channel.truncate(fileLength);
            //System.out.println("  now: " + channel.size());
          } finally {
            try {
              channel.close();
            } finally {
              fos.close();
              //System.out.println("  final len=" + path.length());
            }
          }
        }
      }
    }
  }

  @SuppressForbidden(reason = "java.io.File: native API requires old-style FileDescriptor")
  private final static class NativeUnixIndexInput extends IndexInput {
    private final ByteBuffer buffer;
    private final FileInputStream fis;
    private final FileChannel channel;
    private final int bufferSize;

    private boolean isOpen;
    private boolean isClone;
    private long filePos;
    private int bufferPos;

    public NativeUnixIndexInput(Path path, int bufferSize) throws IOException {
      super("NativeUnixIndexInput(path=\"" + path + "\")");
      final FileDescriptor fd = NativePosixUtil.open_direct(path.toString(), true);
      fis = new FileInputStream(fd);
      channel = fis.getChannel();
      this.bufferSize = bufferSize;
      buffer = ByteBuffer.allocateDirect(bufferSize);
      isOpen = true;
      isClone = false;
      filePos = -bufferSize;
      bufferPos = bufferSize;
      //System.out.println("D open " + path + " this=" + this);
    }

    // for clone
    public NativeUnixIndexInput(NativeUnixIndexInput other) throws IOException {
      super(other.toString());
      this.fis = null;
      channel = other.channel;
      this.bufferSize = other.bufferSize;
      buffer = ByteBuffer.allocateDirect(bufferSize);
      filePos = -bufferSize;
      bufferPos = bufferSize;
      isOpen = true;
      isClone = true;
      //System.out.println("D clone this=" + this);
      seek(other.getFilePointer());
    }

    @Override
    public void close() throws IOException {
      if (isOpen && !isClone) {
        try {
          channel.close();
        } finally {
          if (!isClone) {
            fis.close();
          }
        }
      }
    }

    @Override
    public long getFilePointer() {
      return filePos + bufferPos;
    }

    @Override
    public void seek(long pos) throws IOException {
      if (pos != getFilePointer()) {
        final long alignedPos = pos & ALIGN_NOT_MASK;
        filePos = alignedPos-bufferSize;

        final int delta = (int) (pos - alignedPos);
        if (delta != 0) {
          refill();
          buffer.position(delta);
          bufferPos = delta;
        } else {
          // force refill on next read
          bufferPos = bufferSize;
        }
      }
    }

    @Override
    public long length() {
      try {
        return channel.size();
      } catch (IOException ioe) {
        throw new RuntimeException("IOException during length(): " + this, ioe);
      }
    }

    @Override
    public byte readByte() throws IOException {
      // NOTE: we don't guard against EOF here... ie the
      // "final" buffer will typically be filled to less
      // than bufferSize
      if (bufferPos == bufferSize) {
        refill();
      }
      assert bufferPos == buffer.position() : "bufferPos=" + bufferPos + " vs buffer.position()=" + buffer.position();
      bufferPos++;
      return buffer.get();
    }

    private void refill() throws IOException {
      buffer.clear();
      filePos += bufferSize;
      bufferPos = 0;
      assert (filePos & ALIGN_NOT_MASK) == filePos : "filePos=" + filePos + " anded=" + (filePos & ALIGN_NOT_MASK);
      //System.out.println("X refill filePos=" + filePos);
      int n;
      try {
        n = channel.read(buffer, filePos);
      } catch (IOException ioe) {
        throw new IOException(ioe.getMessage() + ": " + this, ioe);
      }
      if (n < 0) {
        throw new EOFException("read past EOF: " + this);
      }
      buffer.rewind();
    }

    @Override
    public void readBytes(byte[] dst, int offset, int len) throws IOException {
      int toRead = len;
      //System.out.println("\nX readBytes len=" + len + " fp=" + getFilePointer() + " size=" + length() + " this=" + this);
      while(true) {
        final int left = bufferSize - bufferPos;
        if (left < toRead) {
          //System.out.println("  copy " + left);
          buffer.get(dst, offset, left);
          toRead -= left;
          offset += left;
          refill();
        } else {
          //System.out.println("  copy " + toRead);
          buffer.get(dst, offset, toRead);
          bufferPos += toRead;
          //System.out.println("  readBytes done");
          break;
        }
      }
    }

    @Override
    public NativeUnixIndexInput clone() {
      try {
        return new NativeUnixIndexInput(this);
      } catch (IOException ioe) {
        throw new RuntimeException("IOException during clone: " + this, ioe);
      }
    }

    @Override
    public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {
      // TODO: is this the right thing to do?
      return BufferedIndexInput.wrap(sliceDescription, this, offset, length);
    }
  }
}


text:
#ifndef MULTISPANSLIDER_H_0874895466
#define MULTISPANSLIDER_H_0874895466

/** \file   MultiSpanSlider.h
  * \brief  Defines \ref Carna::qt::MultiSpanSlider.
  */

#include <Carna/qt/CarnaQt.h>
#include <Carna/base/math/Span.h>
#include <Carna/qt/NullIntSpanPainter.h>
#include <Carna/qt/MultiSpanSliderTracker.h>
#include <Carna/qt/MultiSpanSliderModelViewMapping.h>
#include <QWidget>
#include <vector>
#include <map>

namespace Carna
{

namespace qt
{

// ----------------------------------------------------------------------------------
// MultiSpanSlider
// ----------------------------------------------------------------------------------

/** \brief
  * Defines a widget that provides an intuitive way of creating, editing and removing
  * disjoint intervals within some given boundaries through its user interface.
  *
  * \ingroup Widgets
  *
  * Example:
  *
  * \image html MultiSpanSlider01.png
  *
  * This widget can operate either vertically or horizontally. By default it operates
  * vertically.
  *
  * \todo Implement horizontal orientation support.
  *
  * In the following documentation \f$ \overline I \f$ is used to denote the set of
  * all legal intervals, \f$ I \f$ is used to identify the *ascendingly* sorted set
  * of currently existing intervals.
  *
  * The widget draws the axis that the trackers are moving along. It also draws the
  * ticks. Drawing trackers is delegated to themselves by calling
  * \ref MultiSpanSliderTracker::paint. This means that by supplying any custom
  * \ref MultiSpanSliderTracker implementation you can easily change the appearance
  * of the trackers. The supplied \ref IntSpanPainter implementation is responsible
  * for visualizing the inner intervals. By default, a null-implementation is used,
  * which simply does not visualize the inner intervals.
  *
  * \author Leonid Kostrykin
  * \date   12.8.11 - 2.4.15
  */
class CARNAQT_LIB MultiSpanSlider : public QWidget
{

    Q_OBJECT

public:

    /** \brief
      * Instantiates.
      *
      * \param orientation
      *     defines whether the trackers are moving horizontally or vertically.
      *
      * \param tracker
      *     is the prototype of the trackers to use.
      *
      * \param spanPainter
      *     defines the visualization of spans.
      *
      * \param parent
      *     is passed through to the `QWidget` constructor.
      */
    explicit MultiSpanSlider
        ( Qt::Orientation orientation = Qt::Vertical
        , MultiSpanSliderTracker* tracker = new MultiSpanSliderTracker()
        , IntSpanPainter* spanPainter = new NullIntSpanPainter()
        , QWidget* parent = nullptr );

    /** \brief
      * Returns \f$ \min \{ \min J, J \in \overline I \} \f$.
      */
    int getFirst() const
    {
        return first;
    }

    /** \brief
      * Returns \f$ \max \{ \max J, J \in \overline I \} \f$.
      */
    int getLast() const
    {
        return last;
    }

    /** \brief
      * Returns the number of values spent between two ticks.
      *
      * If set to \f$0\f$, no ticks will be drawn at all. Behavior is undefined for
      * negative values.
      */
    int getTickInterval() const
    {
        return tickInterval;
    }

    /** \brief
      * Returns the number of values spent between two labeled ticks.
      *
      * If set to \f$0\f$, no labeled ticks will be drawn at all. Behavior is
      * undefined for negative values.
      */
    int getCaptionInterval() const
    {
        return captionInterval;
    }

    /** \brief
      * Returns \f$ \left| I \right| \f$.
      */
    unsigned int getSpanCount() const
    {
        return spans.size();
    }

    /** \brief
      * References a certain element within \f$ I \f$.
      */
    const base::math::Span< int >& getSpan( unsigned int index ) const
    {
        return spans[ index ];
    }

    /** \brief
      * Tells whether an invocation to \ref updateSpan would satisfy all
      * pre-conditions.
      *
      * These are in particular:
      *
      *   - `index <= 0 || getSpan( index - 1 ).last < span.first`
      *   - `index + 1 >= getSpanCount() || getSpan( index + 1 ).first > span.last`
      *   - `span.first < span.last`
      *   - `span.first >= getFirst() && span.last <= getLast()`
      */
    bool canTakeUpdatedSpan( unsigned int index, const base::math::Span< int >& span ) const;

    /** \brief
      * Manipulates a particular element within \f$ I \f$.
      *
      * \pre `index <= 0 || getSpan( index - 1 ).last < span.first`
      * \pre `index + 1 >= getSpanCount() || getSpan( index + 1 ).first > span.last`
      * \pre `span.first < span.last`
      * \pre `span.first >= getFirst() && span.last <= getLast()`
      */
    void updateSpan( unsigned int index, const base::math::Span< int >& span );

    /** \brief
      * Sets a new span visualization definition.
      */
    void setSpanPainter( IntSpanPainter* );

    /** \brief
      * References the supplied tracker prototype.
      */
    MultiSpanSliderTracker& getTracker()
    {
        return *tracker;
    }

    /** \brief
      * References the supplied tracker prototype.
      */
    const MultiSpanSliderTracker& getTracker() const
    {
        return *tracker;
    }

    /** \brief
      * References the supplied span visualization definition.
      */
    IntSpanPainter& getSpanPainter()
    {
        return *spanPainter;
    }

    /** \brief
      * References the supplied span visualization definition.
      */
    const IntSpanPainter& getSpanPainter() const
    {
        return *spanPainter;
    }

public slots:

    /** \brief
      * Sets \f$ \min \{ \min J, J \in \overline I \} \f$.
      *
      * \pre
      * No existing span becomes out of bounds by the requested boundary alternation.
      */
    void setFirst( int );

    /** \brief
      * Sets \f$ \max \{ \max J, J \in \overline I \} \f$.
      *
      * \pre
      * No existing span becomes out of bounds by the requested boundary alternation.
      */
    void setLast( int );

    /** \brief
      * Sets the number of values spent between two ticks.
      *
      * If set to \f$0\f$, no ticks will be drawn at all. Behavior is undefined for
      * negative values.
      */
    void setTickInterval( int );

    /** \brief
      * Sets the number of values spent between two labeled ticks.
      *
      * If set to \f$0\f$, no labeled ticks will be drawn at all. Behavior is
      * undefined for negative values.
      */
    void setCaptionInterval( int );

    /** \brief
      * Adds given span to \f$ I \f$.
      *
      * \pre `span.first < span.last`
      *
      * \throws std::runtime_error
      *     thrown when the new span would either overlap with another span or exceed
      *     the previously configured limits.
      */
    unsigned int addSpan( const base::math::Span< int >& span );

    /** \brief
      * Makes \f$ I = \emptyset \f$.
      */
    void removeAllSpans();

protected:

    /** \brief
      * Paints the widget.
      */
    virtual void paintEvent( QPaintEvent* );

    /** \brief
      * Performs tracker interaction.
      */
    virtual void mousePressEvent( QMouseEvent* ev );

    /** \brief
      * Performs tracker interaction.
      */
    virtual void mouseMoveEvent( QMouseEvent* ev );

    /** \brief
      * Performs tracker interaction.
      */
    virtual void mouseReleaseEvent( QMouseEvent* ev );

    /** \brief
      * Does nothing.
      *
      * Override this in order to implement some custom tracker interaction behavior.
      */
    virtual void processTrackerMousePress( base::math::Span< int >&, int index, MultiSpanSliderTracker::Role )
    {
    }

    /** \brief
      * Does nothing.
      */
    virtual void processNewSpan( base::math::Span< int >&, int index )
    {
    }

    /** \brief
      * Does nothing.
      */
    virtual void processRemovedSpan( base::math::Span< int >&, int index )
    {
    }

    /** \brief
      * Does nothing.
      */
    virtual void processModifiedSpan( base::math::Span< int >&, int index )
    {
    }

private:

    /** \brief
      * Holds whether the trackers are moving horizontally or vertically.
      */
    Qt::Orientation orientation;

    /** \brief
      * Holds a tracker prototype.
      */
    std::unique_ptr< MultiSpanSliderTracker > tracker;

    /** \brief
      * Defines the visualization of spans.
      */
    std::unique_ptr< IntSpanPainter > spanPainter;

    /** \brief
      * Holds \f$ \min \{ \min J, J \in \overline I \} \f$.
      */
    int first;

    /** \brief
      * Holds \f$ \max \{ \max J, J \in \overline I \} \f$.
      */
    int last;

    /** \brief
      * Holds the number of values spent between two ticks.
      */
    unsigned int tickInterval;

    /** \brief
      * Holds the number of values spent between two labeled ticks.
      */
    unsigned int captionInterval;

    /** \brief
      * Type definition of \f$ I \f$
      */
    typedef std::vector< base::math::Span< int > > SpanSet;

    /** \brief
      * Instantiation of \f$ I \f$
      */
    SpanSet spans;

    /** \brief
      * Maps numerical values from model space to pixels in view space and vise
      * versa.
      */
    MultiSpanSliderModelViewMapping mvm;

    /** \brief
      * Holds the index of the span, the user is currently interacting with, or
      * \f$-1\f$, when no interaction is happening.
      */
    int grabbedIndex;

    /** \brief
      * When \ref grabbedIndex is not \f$-1\f$, \ref grabbedMode determines which
      * ending of the span referenced by \c grabbedIndex is being modified.
      */
    MultiSpanSliderTracker::Role grabbedMode;

    /** \brief
     * Holds the pixel offset between the currently grabbed tracker's real position
     * and the result of mapping current mouse position to model space.
      */
    int grabOffset;

    /** \brief
      * Holds the previously captured significant mouse coordinate.
      */
    int prevMouseY;

    /** \brief
      * Holds whether a new span will be spawn next time the mouse is moved with
      * primary button pressed down while no span grabbed.
      */
    bool spawnNewSpan;

signals:

    /** \brief
      * Emitted when changes have been made to the model.
      */
    void spansChanged( Carna::qt::MultiSpanSlider& );

    /** \brief
      * Emitted when changes have been made to the model.
      */
    void spansChanged();

}; // MultiSpanSlider

}  // namespace Carna :: qt

}  // namespace Carna

#endif // MULTISPANSLIDER_H_0874895466


text:
require "bundler"

Bundler.setup
Bundler.require(:default)

$LOAD_PATH.unshift(File.expand_path("../../../lib", __FILE__))

require "amq/client/adapters/coolio"
require "amq/client/queue"
require "amq/client/exchange"

if RUBY_VERSION.to_s =~ /^1.9/
  Encoding.default_internal = Encoding::UTF_8
  Encoding.default_external = Encoding::UTF_8
end

def amq_client_example(description = "", &block)
  AMQ::Client::CoolioClient.connect(:port => 5672, :vhost => "amq_client_testbed") do |client|
    begin
      puts
      puts
      puts "=============> #{description}"

      block.call(client)
    rescue Interrupt
      warn "Manually interrupted, terminating ..."
    rescue Exception => exception
      STDERR.puts "\n\e[1;31m[#{exception.class}] #{exception.message}\e[0m"
      exception.backtrace.each do |line|
        line = "\e[0;36m#{line}\e[0m" if line.match(Regexp::quote(File.basename(__FILE__)))
        STDERR.puts "  - " + line
      end
    end
  end

  cool.io.run
end


text:
package fr.esir.nsoc.tsen.core;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Iterator;

import fr.esir.nsoc.tsen.ade.database.DataBase;
import fr.esir.nsoc.tsen.ade.object.Project;
import fr.esir.nsoc.tsen.ade.object.TreeObject;

public class ADE_Scope {

	private DataBase dataBase;
	private HashSet<TreeObject> scope;
	private LocalDate startPoint;
	private LocalDate endPoint;
	private Project project;

	public ADE_Scope(DataBase dataBase) {
		super();
		this.dataBase = dataBase;
		this.scope = new HashSet<TreeObject>();
	}

	public ADE_Scope(ADE_Scope scope) {
		super();
		this.dataBase = scope.getDataBase();
		this.scope = scope.getScope();
	}

	public boolean addChildrenToScope(TreeObject treeObject) {
		if (treeObject.getType().equals("leaf")) {
			scope.add(treeObject);
			System.out.println("ADD: " + treeObject.getType() + ": \"" + treeObject.getName()
					+ "\", id: \"" + treeObject.getId() + "\", level:"
					+ treeObject.getLevel());
			return true;
		} else if (treeObject.getType().equals("branch")) {
			HashSet<TreeObject> tos = dataBase
					.getTreeObjectChildren(treeObject);
			Iterator<TreeObject> i = tos.iterator();
			while (i.hasNext()) {
				TreeObject to = i.next();
				new ADE_Scope(this).addChildrenToScope(to);
				System.out.println("---: " + to.getType() + ": \"" + to.getName()
						+ "\", id: \"" + to.getId() + "\", level:"
						+ to.getLevel());
				//scope.add(i.next());
			}
			return true;
		}
		return false;
	}

	public LocalDate getStartPoint() {
		return startPoint;
	}

	public void setStartPoint(LocalDate startPoint) {
		this.startPoint = startPoint;
	}

	public LocalDate getEndPoint() {
		return endPoint;
	}

	public void setEndPoint(LocalDate endPoint) {
		this.endPoint = endPoint;
	}

	public void dropScope() {
		this.scope.clear();
	}

	public HashSet<TreeObject> getScope() {
		return scope;
	}

	public DataBase getDataBase() {
		return dataBase;
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

}


text:
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/download/download_stats.h"

#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/notreached.h"
#include "build/build_config.h"
#include "components/download/public/common/download_content.h"
#include "components/profile_metrics/browser_profile_type.h"
#include "components/safe_browsing/content/browser/download/download_stats.h"

void RecordDownloadCount(ChromeDownloadCountTypes type) {
  base::UmaHistogramEnumeration("Download.CountsChrome", type,
                                CHROME_DOWNLOAD_COUNT_TYPES_LAST_ENTRY);
}

void RecordDownloadSource(ChromeDownloadSource source) {
  base::UmaHistogramEnumeration("Download.SourcesChrome", source,
                                CHROME_DOWNLOAD_SOURCE_LAST_ENTRY);
}

void RecordDangerousDownloadWarningShown(
    download::DownloadDangerType danger_type,
    const base::FilePath& file_path,
    bool is_https,
    bool has_user_gesture) {
  base::UmaHistogramEnumeration("Download.ShowedDownloadWarning", danger_type,
                                download::DOWNLOAD_DANGER_TYPE_MAX);
  safe_browsing::RecordDangerousDownloadWarningShown(
      danger_type, file_path, is_https, has_user_gesture);
}

void RecordOpenedDangerousConfirmDialog(
    download::DownloadDangerType danger_type) {
  base::UmaHistogramEnumeration(
      "Download.ShowDangerousDownloadConfirmationPrompt", danger_type,
      download::DOWNLOAD_DANGER_TYPE_MAX);
}

void RecordDownloadOpen(ChromeDownloadOpenMethod open_method,
                        const std::string& mime_type_string) {
  base::RecordAction(base::UserMetricsAction("Download.Open"));
  base::UmaHistogramEnumeration("Download.OpenMethod", open_method,
                                DOWNLOAD_OPEN_METHOD_LAST_ENTRY);
  download::DownloadContent download_content =
      download::DownloadContentFromMimeType(
          mime_type_string, /*record_content_subcategory=*/false);
  if (download_content == download::DownloadContent::DOCUMENT ||
      download_content == download::DownloadContent::PDF ||
      download_content == download::DownloadContent::SPREADSHEET ||
      download_content == download::DownloadContent::TEXT ||
      download_content == download::DownloadContent::UNRECOGNIZED) {
    // TODO(crbug.com/1372476): Remove this histogram after debugging.
    base::UmaHistogramEnumeration(
        "Download.OpenMethod." +
            download::GetDownloadContentString(download_content),
        open_method, DOWNLOAD_OPEN_METHOD_LAST_ENTRY);
  }
  base::UmaHistogramEnumeration("Download.Open.ContentType", download_content,
                                download::DownloadContent::MAX);
}

void RecordDownloadOpenButtonPressed(bool is_download_completed) {
  base::UmaHistogramBoolean("Download.OpenButtonPressed.IsDownloadCompleted",
                            is_download_completed);
}

void RecordDatabaseAvailability(bool is_available) {
  base::UmaHistogramBoolean("Download.Database.IsAvailable", is_available);
}

void RecordDownloadPathGeneration(DownloadPathGenerationEvent event,
                                  bool is_transient) {
  if (is_transient) {
    base::UmaHistogramEnumeration("Download.PathGenerationEvent.Transient",
                                  event, DownloadPathGenerationEvent::COUNT);
  } else {
    base::UmaHistogramEnumeration("Download.PathGenerationEvent.UserDownload",
                                  event, DownloadPathGenerationEvent::COUNT);
  }
}

void RecordDownloadPathValidation(download::PathValidationResult result,
                                  bool is_transient) {
  if (is_transient) {
    base::UmaHistogramEnumeration("Download.PathValidationResult.Transient",
                                  result,
                                  download::PathValidationResult::COUNT);
  } else {
    base::UmaHistogramEnumeration("Download.PathValidationResult.UserDownload",
                                  result,
                                  download::PathValidationResult::COUNT);
  }
}

void RecordDownloadCancelReason(DownloadCancelReason reason) {
  base::UmaHistogramEnumeration("Download.CancelReason", reason);
}

void RecordDownloadShelfDragInfo(DownloadDragInfo drag_info) {
  base::UmaHistogramEnumeration("Download.Shelf.DragInfo", drag_info,
                                DownloadDragInfo::COUNT);
}

void RecordDownloadBubbleDragInfo(DownloadDragInfo drag_info) {
  base::UmaHistogramEnumeration("Download.Bubble.DragInfo", drag_info,
                                DownloadDragInfo::COUNT);
}

void RecordDownloadStartPerProfileType(Profile* profile) {
  base::UmaHistogramEnumeration(
      "Download.Start.PerProfileType",
      profile_metrics::GetBrowserProfileType(profile));
}

#if BUILDFLAG(IS_ANDROID)
// Records whether the download dialog is shown to the user.
void RecordDownloadPromptStatus(DownloadPromptStatus status) {
  base::UmaHistogramEnumeration("MobileDownload.DownloadPromptStatus", status,
                                DownloadPromptStatus::MAX_VALUE);
}
#endif  // BUILDFLAG(IS_ANDROID)

#if BUILDFLAG(IS_CHROMEOS)
void RecordDownloadNotificationSuppressed() {
  base::UmaHistogramBoolean("Download.Notification.Suppressed", true);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

DownloadShelfContextMenuAction DownloadCommandToShelfAction(
    DownloadCommands::Command download_command,
    bool clicked) {
  switch (download_command) {
    case DownloadCommands::Command::MAX:
      NOTREACHED();
      return DownloadShelfContextMenuAction::kMaxValue;
    case DownloadCommands::Command::SHOW_IN_FOLDER:
      return clicked ? DownloadShelfContextMenuAction::kShowInFolderClicked
                     : DownloadShelfContextMenuAction::kShowInFolderEnabled;
    case DownloadCommands::Command::OPEN_WHEN_COMPLETE:
      return clicked ? DownloadShelfContextMenuAction::kOpenWhenCompleteClicked
                     : DownloadShelfContextMenuAction::kOpenWhenCompleteEnabled;
    case DownloadCommands::Command::ALWAYS_OPEN_TYPE:
      return clicked ? DownloadShelfContextMenuAction::kAlwaysOpenTypeClicked
                     : DownloadShelfContextMenuAction::kAlwaysOpenTypeEnabled;
    case DownloadCommands::Command::PLATFORM_OPEN:
      return clicked ? DownloadShelfContextMenuAction::kPlatformOpenClicked
                     : DownloadShelfContextMenuAction::kPlatformOpenEnabled;
    case DownloadCommands::Command::CANCEL:
      return clicked ? DownloadShelfContextMenuAction::kCancelClicked
                     : DownloadShelfContextMenuAction::kCancelEnabled;
    case DownloadCommands::Command::PAUSE:
      return clicked ? DownloadShelfContextMenuAction::kPauseClicked
                     : DownloadShelfContextMenuAction::kPauseEnabled;
    case DownloadCommands::Command::RESUME:
      return clicked ? DownloadShelfContextMenuAction::kResumeClicked
                     : DownloadShelfContextMenuAction::kResumeEnabled;
    case DownloadCommands::Command::DISCARD:
      return clicked ? DownloadShelfContextMenuAction::kDiscardClicked
                     : DownloadShelfContextMenuAction::kDiscardEnabled;
    case DownloadCommands::Command::KEEP:
      return clicked ? DownloadShelfContextMenuAction::kKeepClicked
                     : DownloadShelfContextMenuAction::kKeepEnabled;
    case DownloadCommands::Command::LEARN_MORE_SCANNING:
      return clicked
                 ? DownloadShelfContextMenuAction::kLearnMoreScanningClicked
                 : DownloadShelfContextMenuAction::kLearnMoreScanningEnabled;
    case DownloadCommands::Command::LEARN_MORE_INTERRUPTED:
      return clicked
                 ? DownloadShelfContextMenuAction::kLearnMoreInterruptedClicked
                 : DownloadShelfContextMenuAction::kLearnMoreInterruptedEnabled;
    case DownloadCommands::Command::LEARN_MORE_MIXED_CONTENT:
      return clicked
                 ? DownloadShelfContextMenuAction::kLearnMoreMixedContentClicked
                 : DownloadShelfContextMenuAction::
                       kLearnMoreMixedContentEnabled;
    case DownloadCommands::Command::COPY_TO_CLIPBOARD:
      return clicked ? DownloadShelfContextMenuAction::kCopyToClipboardClicked
                     : DownloadShelfContextMenuAction::kCopyToClipboardEnabled;
    case DownloadCommands::Command::DEEP_SCAN:
      return clicked ? DownloadShelfContextMenuAction::kDeepScanClicked
                     : DownloadShelfContextMenuAction::kDeepScanEnabled;
    case DownloadCommands::Command::BYPASS_DEEP_SCANNING:
      return clicked
                 ? DownloadShelfContextMenuAction::kBypassDeepScanningClicked
                 : DownloadShelfContextMenuAction::kBypassDeepScanningEnabled;

    // The following are not actually visible in the context menu so should
    // never be logged.
    case DownloadCommands::Command::REVIEW:
    case DownloadCommands::Command::RETRY:
      NOTREACHED();
      return DownloadShelfContextMenuAction::kNotReached;
  }
}


text:
using System;
using System.IO;
using System.Text;
using CookComputing.XmlRpc;
using XenAdmin;
using XenAdmin.Network;
using Newtonsoft.Json.Linq;

namespace XenAPI
{
    public partial class Session
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public bool IsElevatedSession = false;

        private Session(int timeout, IXenConnection connection, string url)
            :this(timeout, url)
        {
            Connection = connection;
            XmlRpcProxy.RequestEvent += LogRequest;
#if DEBUG
            XmlRpcProxy.ResponseEvent += LogResponse;
#endif
        }

        public Session(Proxy proxy, IXenConnection connection)
        {
            Connection = connection;
            XmlRpcProxy = proxy;
        }

        public Session(int timeout, IXenConnection connection, string host, int port)
            : this(timeout, connection, GetUrl(host, port))
        {
        }

        public Session(Session session, Proxy proxy, IXenConnection connection)
            : this(proxy, connection)
        {
            opaque_ref = session.opaque_ref;
            APIVersion = session.APIVersion;
            CopyADFromSession(session);
        }

        /// <summary>
        /// Create a new Session instance, using the given instance and timeout.  The connection details and Xen-API session handle will be
        /// copied from the given instance, but a new connection will be created.  Use this if you want a duplicate connection to a host,
        /// for example when you need to cancel an operation that is blocking the primary connection.
        /// </summary>
        public Session(Session session, IXenConnection connection, int timeout)
            : this(session, timeout)
        {
            Connection = connection;

            if (session.JsonRpcClient != null)
            {
                JsonRpcClient.RequestEvent += LogJsonRequest;
            }
            else if (session.XmlRpcProxy != null)
            {
                XmlRpcProxy.RequestEvent += LogRequest;
#if DEBUG
                XmlRpcProxy.ResponseEvent += LogResponse;
#endif
            }
        }

        /// <summary>
        /// When the CacheWarming flag is set, we output logging at Debug rather than Info level.
        /// This means that we don't spam the logs when the application starts.
        /// </summary>
        public bool CacheWarming { get; set; }

        /// <summary>
        /// Do not log while downloading objects;
        /// also exclude calls occurring frequently, we don't need to know about them
        /// </summary>
        private bool CanLogCall(string call)
        {
            return CacheWarming ||
                   call == "event.next" || call == "event.from" || call == "host.get_servertime" ||
                   call.StartsWith("task.get_");
        }

        private void LogJsonRequest(string json)
        {
#if DEBUG
            string methodName = "";
            string parameters = "";

            try
            {
                JObject obj = JObject.Parse(json);
                methodName = obj.Property("method").Value.ToString();
                parameters = obj.Property("params").Value.ToString();
            }
            catch
            {
                //ignore
            }

            // only log the full parameters at Debug level because it may contain sensitive data
            if (CanLogCall(methodName))
                log.DebugFormat("Invoking JSON-RPC method '{0}' with params: {1}", methodName, parameters);
            else
                log.InfoFormat("Invoking JSON-RPC method '{0}'", methodName);
#else
            string methodName = json;

            if (CanLogCall(methodName))
                log.DebugFormat("Invoking JSON-RPC method '{0}'", methodName);
            else
                log.InfoFormat("Invoking JSON-RPC method '{0}'", methodName);
#endif
        }

        private void LogRequest(object o, XmlRpcRequestEventArgs args)
        {
            string xml = DumpStream(args.RequestStream, String.Empty);

            // Find the method name within the XML
            string methodName = "";
            int methodNameStart = xml.IndexOf("<methodName>");
            if (methodNameStart >= 0)
            {
                methodNameStart += 12; // skip past "<methodName>"
                int methodNameEnd = xml.IndexOf('<', methodNameStart);
                if (methodNameEnd > methodNameStart)
                    methodName = xml.Substring(methodNameStart, methodNameEnd - methodNameStart);
            }

            // do not log while downloading objects
            // also exclude calls occurring frequently; we don't need to know about them;
            // only log the full XML at Debug level because it may have sensitive data in: CA-80174

            if (CanLogCall(methodName))
            {
#if DEBUG
                log.DebugFormat("Invoking XML-RPC method {0}: {1}", methodName, xml);
#else
                log.DebugFormat("Invoking XML-RPC method {0}", methodName);
#endif
            }
            else
            {
                log.InfoFormat("Invoking XML-RPC method {0}", methodName);
            }
        }

#if DEBUG
        private void LogResponse(object o, XmlRpcResponseEventArgs args)
        {
            if(log.IsDebugEnabled)
                log.DebugFormat(DumpStream(args.ResponseStream, "XML-RPC response: "));
        }
#endif

        private string DumpStream(Stream s, string header)
        {
            try
            {
                StringBuilder stringBuilder = new StringBuilder(header);
                using (TextReader r = new StreamReader(s))
                {
                    string l;
                    while ((l = r.ReadLine()) != null)
                        stringBuilder.Append(l);
                }
                return stringBuilder.ToString();
            }
            catch(OutOfMemoryException ex)
            {
                log.DebugFormat("Session ran out of memory while trying to log the XML response stream: {0}", ex.Message);
                return String.Empty;
            }
        }

        /// <summary>
        /// The i18n'd string for the 'Logged in as:' username (AD or local root).
        /// </summary>
        public string UserFriendlyName()
        {
            if (IsLocalSuperuser)
                return Messages.AD_LOCAL_ROOT_ACCOUNT;

            if (CurrentUserDetails != null && !string.IsNullOrEmpty(CurrentUserDetails.UserDisplayName))
                return CurrentUserDetails.UserDisplayName.Ellipsise(50);

            if (CurrentUserDetails != null && !string.IsNullOrEmpty(CurrentUserDetails.UserName))
                return CurrentUserDetails.UserName.Ellipsise(50);

            return Messages.UNKNOWN_AD_USER;
        }

        /// <summary>
        /// Useful as a unique name for logging purposes
        /// </summary>
        public string UserLogName()
        {
            if (IsLocalSuperuser)
                return Messages.AD_LOCAL_ROOT_ACCOUNT;

            if (CurrentUserDetails != null && !string.IsNullOrEmpty(CurrentUserDetails.UserName))
                return CurrentUserDetails.UserName;

            return UserSid;
        }

        /// <summary>
        /// This gives either a friendly csv list of the sessions roles or a friendly string for Local root account.
        /// If Pre MR gives Pool Admin for AD users.
        /// </summary>
        public string FriendlyRoleDescription()
        {
            if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetCoordinator(Connection).external_auth_type != Auth.AUTH_TYPE_AD)
                return Messages.AD_LOCAL_ROOT_ACCOUNT;

            return Role.FriendlyCSVRoleList(Roles);
        }

        /// <summary>
        /// This gives either a friendly string for the dominant role on the session or a friendly string for Local root account.
        /// If Pre MR gives Pool Admin for AD users.
        /// </summary>
        public string FriendlySingleRoleDescription()
        {
            if (IsLocalSuperuser || XenAdmin.Core.Helpers.GetCoordinator(Connection).external_auth_type != Auth.AUTH_TYPE_AD)
                return Messages.AD_LOCAL_ROOT_ACCOUNT;

            //Sort roles from highest to lowest
            roles.Sort((r1, r2) => r2.CompareTo(r1));
            //Take the highest role
            return roles[0].FriendlyName();
        }
    }
}


text:
package org.csanchez.jenkins.plugins.kubernetes.pod.retention;

import static org.junit.Assert.*;

import org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud;
import org.junit.Before;
import org.junit.Test;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodStatus;
import io.fabric8.kubernetes.api.model.PodStatusBuilder;

public class PodRetentionTest {

    private KubernetesCloud cloud;
    private Pod pod;

    @Before
    public void setUp() {
        this.cloud = new KubernetesCloud("kubernetes");
        this.pod = new Pod();
    }

    @Test
    public void testAlwaysPodRetention() {
        PodRetention subject = new Always();
        assertFalse(subject.shouldDeletePod(cloud, pod));
    }

    @Test
    public void testNeverPodRetention() {
        PodRetention subject = new Never();
        assertTrue(subject.shouldDeletePod(cloud, pod));
    }

    @Test
    public void testDefaultPodRetention() {
        PodRetention subject = new Default();
        cloud.setPodRetention(new Always());
        assertFalse(subject.shouldDeletePod(cloud, pod));
        cloud.setPodRetention(new Never());
        assertTrue(subject.shouldDeletePod(cloud, pod));
        cloud.setPodRetention(new Default());
        assertTrue(subject.shouldDeletePod(cloud, pod));
        cloud.setPodRetention(null);
        assertTrue(subject.shouldDeletePod(cloud, pod));
    }

    @Test
    public void testOnFailurePodRetention() {
        PodRetention subject = new OnFailure();
        pod.setStatus(buildStatus("Failed"));
        assertFalse(subject.shouldDeletePod(cloud, pod));
        pod.setStatus(buildStatus("Unknown"));
        assertFalse(subject.shouldDeletePod(cloud, pod));
        pod.setStatus(buildStatus("Running"));
        assertTrue(subject.shouldDeletePod(cloud, pod));
        pod.setStatus(buildStatus("Pending"));
        assertTrue(subject.shouldDeletePod(cloud, pod));
    }

    private PodStatus buildStatus(String phase) {
        return new PodStatusBuilder().withPhase(phase).build();
    }

}


text:
package io.trane.ndbc.flow;

import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

final class Filter<T> implements Flow<T> {

  private final Flow<T>      flow;
  private final Predicate<T> p;

  public Filter(Flow<T> flow, Predicate<T> p) {
    this.flow = flow;
    this.p = p;
  }

  @Override
  public void subscribe(Subscriber<? super T> sb) {

    flow.subscribe(new Subscriber<T>() {

      private final AtomicLong filteredOut = new AtomicLong(0);
      private final AtomicLong pending     = new AtomicLong(0);

      private Subscription s = null;

      @Override
      public void onSubscribe(Subscription s) {
        this.s = new Subscription() {

          @Override
          public void request(long n) {
            Scheduler.submit(() -> {
              filteredOut.set(0);
              pending.set(n);
              s.request(n);
            });
          }

          @Override
          public void cancel() {
            s.cancel();
          }
        };
        sb.onSubscribe(this.s);
      }

      @Override
      public void onNext(T t) {
        if (p.test(t))
          sb.onNext(t);
        else
          filteredOut.incrementAndGet();
        long p = pending.decrementAndGet();
        if (p == 0L) {
          long f = filteredOut.get();
          if (f > 0)
            s.request(f);
        }
      }

      @Override
      public void onError(Throwable t) {
        sb.onError(t);
      }

      @Override
      public void onComplete() {
        sb.onComplete();
      }
    });
  }

}


text:
java-socks-proxy
================

simple implementation of a java socks proxy using Java NIO


text:
namespace streetlearn {

constexpr char TestDataset::kStreetName[];
constexpr char TestDataset::kRegion[];
constexpr char TestDataset::kFullAddress[];
constexpr char TestDataset::kDescription[];
constexpr char TestDataset::kCountryCode[];
constexpr char TestDataset::kPanoDate[];
constexpr float TestDataset::kAltitude;
constexpr float TestDataset::kLatitude;
constexpr float TestDataset::kLongitude;
constexpr float TestDataset::kIncrement;
constexpr float TestDataset::kRollDegrees;
constexpr float TestDataset::kPitchDegrees;
constexpr float TestDataset::kHeadingDegrees;
constexpr float TestDataset::kMinLatitude;
constexpr float TestDataset::kMinLongitude;
constexpr float TestDataset::kMaxLatitude;
constexpr float TestDataset::kMaxLongitude;
constexpr int TestDataset::kImageWidth;
constexpr int TestDataset::kImageHeight;
constexpr int TestDataset::kImageDepth;
constexpr int TestDataset::kPanoCount;
constexpr int TestDataset::kNeighborCount;
constexpr int TestDataset::kMinGraphDepth;
constexpr int TestDataset::kMaxGraphDepth;
constexpr int TestDataset::kMaxNeighborDepth;
constexpr int TestDataset::kMaxCacheSize;

Pano TestDataset::GeneratePano(int pano_id) {
  Pano pano;
  pano.set_id(absl::StrCat(pano_id));
  pano.set_street_name(kStreetName);
  pano.set_full_address(kFullAddress);
  pano.set_region(kRegion);
  pano.set_country_code(kCountryCode);
  pano.set_pano_date(kPanoDate);
  pano.set_alt(kAltitude);
  pano.set_roll_deg(kRollDegrees);
  pano.set_pitch_deg(kPitchDegrees);
  pano.set_heading_deg(kHeadingDegrees);
  pano.set_pano_date(kPanoDate);
  LatLng* coords = pano.mutable_coords();
  // Place the panos in a line.
  coords->set_lat(kLatitude + kIncrement * pano_id);
  coords->set_lng(kLongitude + kIncrement * pano_id);
  return pano;
}

std::vector<uint8_t> TestDataset::GenerateCompressedTestImage() {
  auto image = GenerateTestImage();
  cv::Mat mat(image.height(), image.width(), CV_8UC3,
              const_cast<uint8_t*>(image.pixel(0, 0)));
  // Convert to BGR as the defaul OpenCV format is BGR.
  cv::Mat bgr_mat;
  cvtColor(mat, bgr_mat, CV_RGB2BGR);

  std::vector<uint8_t> compressed_image;
  cv::imencode(".png", bgr_mat, compressed_image);
  return compressed_image;
}

// The panos are numbered 1-10 and arranged in a line, each connecting to both
// its immediate neighbors, except the ends.
void TestDataset::AddNeighbors(int pano_id, Pano* pano) {
  if (pano_id < kPanoCount) {
    int next = pano_id + 1;
    PanoNeighbor* neighbor = pano->add_neighbor();
    neighbor->set_id(absl::StrCat(next));
    neighbor->set_pano_date(kPanoDate);
    LatLng* coords = neighbor->mutable_coords();
    coords->set_lat(kLatitude + kIncrement * next);
    coords->set_lng(kLongitude + kIncrement * next);
  }

  if (pano_id > 1) {
    int previous = pano_id - 1;
    PanoNeighbor* neighbor = pano->add_neighbor();
    neighbor->set_id(absl::StrCat(previous));
    neighbor->set_pano_date(kPanoDate);
    LatLng* coords = neighbor->mutable_coords();
    coords->set_lat(kLatitude + kIncrement * previous);
    coords->set_lng(kLongitude + kIncrement * previous);
  }
}

// The panos are numbered 1-10 and arranged in a line, each connecting to both
// its immediate neighbors except the ends.
void TestDataset::AddNeighborMetadata(int pano_id, PanoConnection* connection) {
  connection->set_subgraph_size(kPanoCount);
  connection->set_id(absl::StrCat(pano_id));

  if (pano_id < kPanoCount) {
    auto* neighbor = connection->add_neighbor();
    *neighbor = absl::StrCat(pano_id + 1);
  }

  if (pano_id > 1) {
    auto* neighbor = connection->add_neighbor();
    *neighbor = absl::StrCat(pano_id - 1);
  }
}

bool TestDataset::Generate() {
  leveldb::DB* db_ptr;
  leveldb::Options options;
  options.create_if_missing = true;

  leveldb::Status leveldb_status =
      leveldb::DB::Open(options, GetPath(), &db_ptr);
  if (!leveldb_status.ok()) {
    LOG(ERROR) << "Cannot initialize dataset: " << leveldb_status.ToString();
    return false;
  }

  auto db = absl::WrapUnique<leveldb::DB>(db_ptr);
  const auto compressed_pano_image = GenerateCompressedTestImage();

  // Create panos.
  for (int i = 1; i <= kPanoCount; ++i) {
    Pano pano = GeneratePano(i);
    AddNeighbors(i, &pano);
    pano.mutable_compressed_image()->assign(compressed_pano_image.begin(),
                                            compressed_pano_image.end());

    leveldb_status =
        db->Put(leveldb::WriteOptions(), pano.id(), pano.SerializeAsString());
    if (!leveldb_status.ok()) {
      return false;
    }
  }

  // Create connectivity graph.
  StreetLearnGraph metadata;
  metadata.mutable_min_coords()->set_lat(kMinLatitude);
  metadata.mutable_min_coords()->set_lng(kMinLongitude);
  metadata.mutable_max_coords()->set_lat(kMaxLatitude);
  metadata.mutable_max_coords()->set_lng(kMaxLongitude);

  for (int i = 1; i <= kPanoCount; ++i) {
    PanoConnection* connection = metadata.add_connection();
    *metadata.add_pano() = GeneratePano(i);
    AddNeighborMetadata(i, connection);
  }

  leveldb_status = db->Put(leveldb::WriteOptions(), LevelDBDataset::kGraphKey,
                           metadata.SerializeAsString());
  return leveldb_status.ok();
}

std::string TestDataset::GetPath() {
  return ::testing::TempDir() + "/streetlearn_test_dataset";
}

bool TestDataset::GenerateInvalid() {
  leveldb::DB* db_ptr;
  leveldb::Options options;
  options.create_if_missing = true;

  auto status = leveldb::DB::Open(options, GetInvalidDatasetPath(), &db_ptr);
  if (!status.ok()) {
    LOG(ERROR) << "Cannot initialize dataset: " << status.ToString();
    return false;
  }

  auto db = absl::WrapUnique<leveldb::DB>(db_ptr);
  return true;
}

std::string TestDataset::GetInvalidDatasetPath() {
  return ::testing::TempDir() + "/streetlearn_invalid_dataset";
}

Image3_b TestDataset::GenerateTestImage() {
  Image3_b test_image(kImageWidth, kImageHeight);
  for (int x = 0; x < kImageWidth; ++x) {
    for (int y = 0; y < kImageHeight; ++y) {
      auto pixel = test_image.pixel(x, y);
      pixel[0] = 16;
      pixel[1] = 32;
      pixel[2] = 64;
    }
  }

  return test_image;
}

std::vector<std::string> TestDataset::GetPanoIDs() {
  std::vector<std::string> pano_ids(kPanoCount);
  for (int i = 0; i < kPanoCount; ++i) {
    pano_ids[i] = absl::StrCat(i + 1);
  }
  return pano_ids;
}

}  // namespace streetlearn


text:
using UnityEngine;
using UnityEngine.EventSystems;

// Controls a single handle.
public class HandleController : MonoBehaviour {

	// Every handle needs an ID that the server refers to it by.
	public long id;

	// The hideable components of the handles.
	private HideableInterfaceElement[] hideables;

	// Initialize this component.
	void Start () {
		hideables = GetComponentsInChildren<HideableInterfaceElement> ();
		SetVisible (true);
	}

	#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER

	// Called when the mouse drags this component.
	void OnMouseDrag () {
		Vector3 worldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
		transform.position = new Vector2 (worldPoint.x, worldPoint.y);
	}

	#endif

	// Sets whether or not this handle is visible.
	public void SetVisible (bool visible) {

		if (hideables == null) {
			hideables = GetComponentsInChildren<HideableInterfaceElement> ();
		}

		// Show/hide handles.
		for (int i = 0; i < hideables.Length; i++) {
			hideables [i].SetShown (visible);
		}

		// Enable/disable collider.
		GetComponent<Collider2D> ().enabled = visible;
	}

	// Fires when this handle begins dragging.
	public void OnBeginDrag () {
	}

	// Fires while this handle is being dragged.
	public void OnDrag () {
		transform.position = Input.GetTouch (0).position;
	}
}


text:
/*
  Header to remove use of my_functions in functions where we need speed and
  where calls to posix functions should work
*/
#ifndef _my_nosys_h
#define _my_nosys_h
#ifdef	__cplusplus
extern "C" {
#endif

#ifndef __MY_NOSYS__
#define __MY_NOSYS__

#ifndef HAVE_STDLIB_H
#include <malloc.h>
#endif

#undef my_read
#undef my_write
#undef my_seek
#define my_read(a,b,c,d) my_quick_read(a,b,c,d)
#define my_write(a,b,c,d) my_quick_write(a,b,c)
extern size_t my_quick_read(File Filedes,uchar *Buffer,size_t Count,
                            myf myFlags);
extern size_t my_quick_write(File Filedes,const uchar *Buffer,size_t Count);

#if defined(USE_HALLOC)
#define my_malloc(a,b) halloc(a,1)
#define my_no_flags_free(a) hfree(a)
#endif

#endif /* __MY_NOSYS__ */

#ifdef	__cplusplus
}
#endif
#endif


text:
export builddir_name ?= build/./drafter/.
.PHONY: all
all:
	$(MAKE) -C .. libsos libdrafter


text:
#ifndef THRIFT_TEST_LOADGEN_LATENCYSCOREBOARD_H_
#define THRIFT_TEST_LOADGEN_LATENCYSCOREBOARD_H_ 1

#include <folly/stats/Histogram.h>

#include <thrift/lib/cpp/test/loadgen/ScoreBoard.h>
#include <thrift/lib/cpp/test/loadgen/ScoreBoardOpVector.h>

#include <chrono>

namespace apache {
namespace thrift {
namespace loadgen {

/**
 * A ScoreBoard that tracks number of queries per second, as well as
 * information about how long each operation takes.
 *
 * This ScoreBoard calls gettimeofday() twice for each operation, so it does
 * add a small amount of overhead.  If you have extremely high performance
 * requirements, you could use QpsScoreBoard to track just the QPS rate and
 * eliminate the gettimeofday() calls.
 */
class LatencyScoreBoard : public ScoreBoard {
 public:
  class OpData {
   public:
    OpData();

    void addDataPoint(uint64_t latencyUsecs);

    void zero();
    void accumulate(const OpData* other);

    uint64_t getCount() const;
    uint64_t getCountSince(const OpData* other) const;
    double getLatencyAvg() const;
    double getLatencyAvgSince(const OpData* other) const;
    double getLatencyPct(double pct) const;
    double getLatencyPctSince(double pct, const OpData* other) const;
    double getLatencyStdDev() const;
    double getLatencyStdDevSince(const OpData* other) const;

    uint64_t count_;
    uint64_t usecSum_;
    uint64_t sumOfSquares_;

    // latency distribution histogram
    folly::Histogram<uint64_t> latDistHist_;
  };

  explicit LatencyScoreBoard(uint32_t numOpsHint)
      : startTime_(), opData_(numOpsHint) {}

  void opStarted(uint32_t opType) override;
  void opSucceeded(uint32_t opType) override;
  void opFailed(uint32_t opType) override;

  /**
   * Get the OpData for a particular operation type
   */
  const OpData* getOpData(uint32_t opType);

  /**
   * Compute an OpData object with aggregate information over all operation
   * types.
   *
   * @param result A pointer to the OpData object to fill in with aggregate
   *               information.
   */
  void computeOpAggregate(OpData* result) const;

  /**
   * Zero out the statistics.
   */
  void zero();

  /**
   * Add the counters from another scoreboard to this one.
   */
  void accumulate(const LatencyScoreBoard* other);

 private:
  std::chrono::steady_clock::time_point startTime_;
  ScoreBoardOpVector<OpData> opData_;
};

} // namespace loadgen
} // namespace thrift
} // namespace apache

#endif // THRIFT_TEST_LOADGEN_LATENCYSCOREBOARD_H_


text:
namespace Network{
namespace IRC{

    class Command{
    public:
        enum Type{
            Unknown,
            Pass,
            Nick,
            User,
            Userhost,
            Server,
            Oper,
            Quit,
            Squit,
            Join,
            Part,
            Mode,
            Topic,
            Names,
            List,
            Invite,
            Kick,
            Version,
            Stats,
            Links,
            Time,
            Connect,
            Trace,
            Admin,
            Info,
            PrivateMessage,
            Notice,
            Who,
            Whois,
            Whowas,
            Kill,
            Ping,
            Pong,
            Error,
            ErrorNickInUse,
            ErrorNoSuchNick,
            ErrorNoSuchChannel,
            ErrorNeedMoreParams,
            ErrorBannedFromChannel,
            ErrorInviteOnlyChannel,
            ErrorBadChannelKey,
            ErrorChannelIsFull,
            ReplyNames,
            ReplyNamesEndOf,
            ReplyNoTopic,
            ReplyTopic,
            ReplyTopicAuthor,
            ReplyMOTD,
            ReplyMOTDStart,
            ReplyMOTDEndOf,
            ReplyUserhost,
        };
        // Initializes it from an incoming message off of socket
        Command(const std::string &);
        // Create a message with owner and type
        Command(const std::string &, const Type &);
        Command(const Command &);
        virtual ~Command();

        virtual const Command & operator=(const Command &);

        virtual std::string getSendable() const;
        virtual std::string getCTCPSendable() const;

        virtual inline const std::string & getOwner() const {
            return this->owner;
        }

        virtual inline const Type & getType() const {
            return this->type;
        }

        virtual inline void setParameters(const std::string & param1){
            this->parameters.clear();
            this->parameters.push_back(param1);
        }

        virtual inline void setParameters(const std::string & param1, const std::string & param2){
            this->parameters.clear();
            this->parameters.push_back(param1);
            this->parameters.push_back(param2);
        }

        virtual inline void setParameters(const std::string & param1, const std::string & param2, const std::string & param3){
            this->parameters.clear();
            this->parameters.push_back(param1);
            this->parameters.push_back(param2);
            this->parameters.push_back(param3);
        }

        virtual inline void setParameters(const std::string & param1, const std::string & param2, const std::string & param3, const std::string & param4){
            this->parameters.clear();
            this->parameters.push_back(param1);
            this->parameters.push_back(param2);
            this->parameters.push_back(param3);
            this->parameters.push_back(param4);
        }

        virtual inline void setParameters(const std::vector< std::string > & params){
            this->parameters = params;
        }

        virtual inline const std::vector< std::string > & getParameters() const {
            return this->parameters;
        }

        virtual inline bool hasCtcp() const {
            return !this->ctcp.empty();
        }

        virtual inline const std::vector< std::string > & getCtcp() const {
            return this->ctcp;
        }

    protected:
        std::string owner;
        Type type;
        std::vector< std::string > parameters;
        std::vector< std::string > ctcp;
    };

    class Channel{
    public:
        Channel();
        Channel(const std::string &);
        Channel(const Channel &);
        ~Channel();

        const Channel & operator=(const Channel &);

        void addUser(const std::string &);
        void removeUser(const std::string &);
        void replaceUser(const std::string &, const std::string &);
        void addUsers(const std::vector<std::string> &);

        inline const std::vector<std::string> & getUsers() const{
            return this->users;
        }

        inline const std::string & getName() const {
            return this->name;
        }

        inline void setTopic(const std::string & topic){
            this->topic = topic;
        }

        inline void setTopicAuthor(const std::string & topicAuthor, uint64_t topicDate){
            this->topicAuthor = topicAuthor;
            this->topicDate = topicDate;
        }

    protected:
        std::string name;
        std::string topic;
        std::string topicAuthor;
        uint64_t topicDate;
        std::vector<std::string> users;
    };

    // Channel ReferenceCount
    typedef Util::ReferenceCount<Channel> ChannelPointer;

    class Client : public Chat::Threadable{
    public:
        Client(const std::string &, int port);
        virtual ~Client();

        virtual void connect(const std::string & name = "paintown-test");

        virtual void run();

        virtual bool hasCommands() const;

        virtual Command nextCommand() const;

        virtual void sendCommand(const Command &);

        virtual void sendCommand(const Command::Type &);
        virtual void sendCommand(const Command::Type &, const std::string &);
        virtual void sendCommand(const Command::Type &, const std::string &, const std::string &);
        virtual void sendCommand(const Command::Type &, const std::string &, const std::string &, const std::string &);
        virtual void sendCommand(const Command::Type &, const std::string &, const std::string &, const std::string &, const std::string &);

        virtual void setName(const std::string &);

        virtual inline const std::string & getName() const {
            return this->username;
        }

        virtual void joinChannel(const std::string &);
        virtual void partChannel(const std::string &);

        virtual inline ChannelPointer getChannel() const {
            if (this->activeChannels.empty()){
                return ChannelPointer(NULL);
            }
            return this->activeChannels[this->currentChannel];
        }

        virtual inline std::vector< ChannelPointer > & channelList(){
            return this->activeChannels;
        }

        virtual std::string channelListAsString();

        virtual unsigned int getChannelIndex(const std::string &);

        virtual bool isCurrentChannel(const std::string &);

        virtual void setChannel(unsigned int channel);

        virtual void nextChannel();

        virtual void previousChannel();

        virtual void sendMessage(const std::string &);

        virtual void sendPong(const Command &);

        virtual inline void setMessagesDisabled(bool disabled){
            this->disableMessages = disabled;
        }

    protected:

        void removeChannel(const std::string &);

        ChannelPointer findChannel(const std::string &);

        std::string readMessage();

        //! Doesn't do anything to the command just handle some internal changes like username and channel stuff
        void checkResponseAndHandle(const Command &);

        Network::Socket socket;
        std::string previousUsername;
        std::string username;
        unsigned int previousActiveChannel;
        unsigned int currentChannel;
        std::vector< ChannelPointer > activeChannels;
        std::string hostname;
        int port;
        bool end;
        mutable std::queue< Command > commands;
        bool disableMessages;
    };

namespace Message{

    class EventInterface{
    public:
        EventInterface();
        virtual ~EventInterface();
        // Notify by message from local user
        virtual void localNotify(const std::string &);
        // Notify by command from local user
        virtual void localCommand(const std::vector<std::string> &);
        // Notify by message from remote
        virtual void remoteNotify(const std::string &);
        // Notify by command from remote
        virtual void remoteCommand(const Command &);
    };

    class HandlerInterface{
    public:
        HandlerInterface();
        virtual ~HandlerInterface();

        typedef void *(*NotifyCallback)(const std::string &);

        virtual inline void subscribe(NotifyCallback subscriber){
            this->callbacks.push_back(subscriber);
        }

        virtual inline void subscribe(EventInterface * subscriber){
            this->subscribers.push_back(subscriber);
        }
    protected:
        // Callbacks for events and messages
        std::vector<NotifyCallback> callbacks;
        std::vector<EventInterface *> subscribers;
    };

    class QueueInterface{
    public:
        QueueInterface();
        virtual ~QueueInterface();

        virtual void addMessage(const std::string &) = 0;

        class FontWrapper{
        public:
            FontWrapper();
            virtual ~FontWrapper();

            virtual int getWidth(const std::string &)=0;
            virtual int getHeight()=0;
        };
        virtual void processMessages(FontWrapper &, int width, int height);

    protected:
        std::queue<std::string> messages;
        std::deque<std::string> buffer;
    };
}
    // Create a tabbed chatter to implement in games
    class ChatInterface: public Message::HandlerInterface{
    public:
        ChatInterface(const std::string &, int port, const std::string &);
        virtual ~ChatInterface();
        void act();
        void draw(const Graphics::Bitmap &);

        void nextChannel();
        void previousChannel();
        void gotoChannel(const std::string &);

        Util::ReferenceCount<Client> getClient();

        Util::ReferenceCount<Gui::TabItem> getCurrentTab();

        Util::ReferenceCount<Gui::TabItem> getTabByName(const std::string &);

        void addMessageToTab(const std::string &);

        void addMessageToTab(const std::string &, const std::string &);

        inline void setWidthRatio(double ratio){
            this->widthRatio = ratio;
        }
        inline void setHeightRatio(double ratio){
            this->heightRatio = ratio;
        }

        inline Gui::LineEdit & getInputBox() {
            return this->inputBox;
        }

    protected:
        void updateDimensions();
        void remoteNotify(const std::string &);
        void processRemoteCommands();

        static void submit(void *);
        // Notifications and commands for submit
        void localNotify(const std::string &);
        void localCommand(const std::vector<std::string> &);

        // Update user list
        void updateUserList();
        void removeUser(const std::string &);
        void changeUserName(const std::string &, const std::string &);

        Util::ReferenceCount<Client> client;
        const std::string & host;
        Gui::TabContainer chatBox;
        Gui::LineEdit inputBox;
        Gui::SimpleList listBox;
        double widthRatio;
        double heightRatio;
        int width;
        int height;
        int checkWidth;
        int checkHeight;
        Util::ReferenceCount<Gui::TabItem> serverTab;
        // check ctcp reply
        std::map<std::string, uint64_t> pingReply;
        std::map< std::string, std::vector<std::string> > namesRequest;
    };

}// end irc
}
#endif


text:
FactoryGirl.define do
  factory :position_application do
    position  :position_member
    factory :kirjakerho_application do
      user { TestSingletons.eija }
      call { TestSingletons.lukurinki }
    end
    factory :helsinki_uni_board_application do
      user { TestSingletons.helsinki_uni_student_union_employee }
      call { TestSingletons.call_for_student_council_board }
    end
    custom Hash[*['degree','VTT']]
  end
end


text:
import THREE from 'three';
const simplex = new(require('simplex-noise'))
const random = require('random-float')
const randomInt = require('random-int')

/**
 * CubeGeometry class
 */
class CloudGeometry extends THREE.TetrahedronGeometry {

  /**
   * Constructor function
   */
  constructor() {
    super(1, 2)

    this.seed = randomInt(1, 100)

    for (let i = 0; i < this.vertices.length; i++) {
      const vertex = this.vertices[i];
      vertex.x += simplex.noise3D(this.seed + vertex.y * 0.2, vertex.z * 0.1, 1)
      vertex.y += simplex.noise3D(this.seed + vertex.x * 0.1, vertex.z * 0.5, 1)
      vertex.z += simplex.noise3D(this.seed + vertex.x * 0.5, vertex.y * 0.1, 1)
    }

    this.computeFaceNormals();
    this.computeVertexNormals();
  }

  /**
   * Update function
   * @param {number} time Time
   */
  update(time) {

    for (let i = 0; i < this.vertices.length; i++) {
      const vertex = this.vertices[i];
      vertex.x *= simplex.noise3D(this.seed + vertex.y * 0.2, vertex.z * 0.1, time * 0.01)
      vertex.y *= simplex.noise3D(this.seed + vertex.x * 0.1, vertex.z * 0.5, time * 0.01)
      vertex.z *= simplex.noise3D(this.seed + vertex.x * 0.5, vertex.y * 0.1, time * 0.01)
    }

  //  this.verticesNeedUpdate = true
  }
}

export default CloudGeometry;


text:
<?php use \Tuanduimao\Loader\App as App; ?>

	   <form class="js-validation-sourdate form-horizontal push-10-t" action="<?=App::NR('SourceData','save')?>" method="post">

                        <input  type="text" id="title" name="title" placeholder="请填写标题" value="<?=!empty($data['title'])?$data['title']:"" ?>" class="form-control">
                        标题 *

                        类型 *
                        <select class="js-select2 form-control" s name="type" required style="width:100%;">
                            <option>邮件/短信</option>
                            <option value="mail" <?php
                                    if ($data['type']=="mail"){
                                        echo "selected";
                                    }?>>邮件</option>
                            <option value="sms" <?php
                                    if ($data['type']=="sms"){
                                        echo "selected";
                                    }?>>短信</option>
                        </select>

<?=!empty($data['content'])?$data['content']:"" ?>

                        正文 *

            <input type="text" name="_id" value="<?=!empty($data['_id'])?$data['_id']:"" ?>" class="hide">

                            <button class="btn btn-minw btn-primary pull-left" type="submit">保存</button>

                            <button class="btn btn-minw btn-primary pull-right change-type content-yuedu" type="button">阅读模式</button>

        </form>


text:
/**
 * Created by malaka on 10/10/17.
 */

import {Injectable} from "@angular/core";
import {SchoolService} from "./school/shool.service";
import {UserService} from "./users/user.service";
import {ToastService} from "./toastr.service";
@Injectable()
export class APIService {

  private toastOptions = {
    enable: false,
    onError: false,
    onSuccess: false,
  };
  constructor(private toast: ToastService,
              private schoolService: SchoolService,
              private userService: UserService) {
  }

  public sendGet(service: Services, path: string, dataPath?: Array<string>, options?: any, success?: number, auth?: boolean): Promise<any> {
    return this.handleToast(
      this.getHandler(service).apiGet(this.getPath(service) + path, dataPath, options, auth, success)
    );
  }

  public sendPost(service: Services, path:string, body: any, dataPath?: Array<string>, options?: any, success ?: number, auth?: boolean) : Promise<any>{
    return this.handleToast(
      this.getHandler(service).apiPost(this.getPath(service) + path, body, dataPath, options, auth, success)
    );
  }

  public sendPut(service: Services, path:string, body: any, dataPath?: Array<string>, options?: any, success ?: number, auth?: boolean) : Promise<any>{
    return this.handleToast(
      this.getHandler(service).apiPut(this.getPath(service) + path, body, dataPath, options, auth, success)
    );
  }

  public sendDelete(service: Services, path:string, dataPath?: Array<string>, options?: any, success ?: number, auth?: boolean) : Promise<any>{
    return this.handleToast(
      this.getHandler(service).apiDelete(this.getPath(service) + path, dataPath, options, auth, success)
    );
  }

  public callCustom(service: Services, func: string): Promise<any> {
    return this.handleToast(
      this.getHandler(service)[func]()
    );
  }

  public setToastEnable(val: boolean){ this.toastOptions.enable = val};
  public setToastOnError(val: boolean){ this.toastOptions.onError = val};
  public setToastOnSuccess(val: boolean){ this.toastOptions.onSuccess = val};

  private handleToast(promise: Promise<any>): Promise<any> {
    if(this.toastOptions.enable){
      return new Promise((resolve, reject) => {
        promise.then(data => {
          if(this.toastOptions.onSuccess){
            this.toast.toast().success('Success') // TODO extendable
          }
          resolve(data);
        }).catch(error => {
          if(this.toastOptions.onError){
            // TODO identify the error code
            this.toast.toast().success('Error') // TODO extendable
          }
          reject(error);
        })
      });
    } else {
      return promise;
    }
  }

  private getHandler(service: Services): any{
    switch (service) {
      case Services.SCHOOL:
        return this.schoolService;
      case Services.USER:
        return this.userService;
    }
  }

  private getPath(service: Services): string{
    switch (service) {
      case Services.SCHOOL:
        return 'school/';
      case Services.USER:
        return 'user/';
    }
  }
}

export enum Services{
  SCHOOL,
  USER,
}


text:
package packet

import (
	"bytes"
	"fmt"
	"strings"
	"text/template"
	"time"

	"github.com/packethost/packngo"
	"github.com/supergiant/supergiant/bindata"
	"github.com/supergiant/supergiant/pkg/core"
	"github.com/supergiant/supergiant/pkg/model"
	"github.com/supergiant/supergiant/pkg/util"
)

// CreateNode creates a new minion on DO kubernetes cluster.
func (p *Provider) CreateNode(m *model.Node, action *core.Action) error {

	// setup provider steps.
	procedure := &core.Procedure{
		Core:   p.Core,
		Name:   "Create Kube",
		Model:  m,
		Action: action,
	}

	// fetch client.
	client, err := p.Client(m.Kube)
	if err != nil {
		return err
	}

	project, err := getProject(m.Kube, client, m.Kube.PACKConfig.Project)
	if err != nil {
		return err
	}
	plan, err := getPlan(m.Kube, client, m.Size)
	if err != nil {
		return err
	}
	procedure.AddStep("Creating Kubernetes Minion Node...", func() error {

		m.Name = m.Kube.Name + "-minion" + "-" + strings.ToLower(util.RandomString(5))

		mversion := strings.Split(m.Kube.KubernetesVersion, ".")

		userDatatemplate := "config/providers/common/" + mversion[0] + "." + mversion[1] + "/minion.yaml"
		oS := "coreos_stable"

		if m.Size == "Type 2A" {
			userDatatemplate = "config/providers/common/" + mversion[0] + "." + mversion[1] + "/arm/ubuntu/minion.yaml"
			oS = "ubuntu_17_04"
		}
		// Build template
		masterUserdataTemplate, err := bindata.Asset(userDatatemplate)
		if err != nil {
			return err
		}
		masterTemplate, err := template.New("master_template").Parse(string(masterUserdataTemplate))
		if err != nil {
			return err
		}

		data := struct {
			*model.Node
			Token string
		}{
			m,
			m.Kube.CloudAccount.Credentials["api_token"],
		}

		var masterUserdata bytes.Buffer
		if err = masterTemplate.Execute(&masterUserdata, data); err != nil {
			return err
		}
		userData := string(masterUserdata.Bytes())

		createRequest := &packngo.DeviceCreateRequest{
			HostName:     m.Name,
			Plan:         plan,
			Facility:     m.Kube.PACKConfig.Facility,
			OS:           oS,
			BillingCycle: "hourly",
			ProjectID:    project,
			UserData:     userData,
			Tags:         []string{"supergiant", "kubernetes", m.Name, "minion"},
		}

		server, resp, err := client.Devices.Create(createRequest)
		if err != nil {
			fmt.Println(err.Error())
			fmt.Println(resp.String())
			return err
		}

		return action.CancellableWaitFor("Kubernetes Minion Launch", 30*time.Minute, 3*time.Second, func() (bool, error) {
			resp, _, serr := client.Devices.Get(server.ID)
			if serr != nil {
				return false, serr
			}

			// Save Master info when ready
			if resp.State == "active" {
				m.ProviderID = resp.ID
				m.Name = resp.Hostname
				m.ProviderCreationTimestamp = time.Now()
				if serr := p.Core.DB.Save(m); serr != nil {
					return false, serr
				}
			}
			return resp.State == "active", nil
		})
	})

	return procedure.Run()
}