text:
#include "freetype_import.hh"
#include "importtools.hh"
#include <map>
#include <string>
#include <stdexcept>
#include <iostream>
#include "ccfixes.hh"

#include <ft2build.h>
#include FT_FREETYPE_H

#undef __FTERRORS_H__
#define FT_ERRORDEF( e, v, s )  std::make_pair( e, s ),
#define FT_ERROR_START_LIST static const std::map<FT_Error, std::string> ft_errors {
#define FT_ERROR_END_LIST };
#include FT_ERRORS_H

namespace mcufont {

static void checkFT(FT_Error error)
{
    if (error != 0)
    {
        if (ft_errors.count(error))
            throw std::runtime_error("libfreetype error " +
                std::to_string(error) + ": " + ft_errors.at(error));
        else
            throw std::runtime_error("unknown libfreetype error " +
                std::to_string(error));
    }
}

// Automatically allocated & freed wrapper for FT_Library
class _FT_Library
{
public:
    _FT_Library() { checkFT(FT_Init_FreeType(&m_lib)); }
    ~_FT_Library() { checkFT(FT_Done_FreeType(m_lib)); }
    operator FT_Library() { return m_lib; }

private:
    FT_Library m_lib;
};

// Automatically allocated & freed wrapper for FT_Face
class _FT_Face
{
public:
    _FT_Face(FT_Library lib, const std::vector<char> &data)
    {
        checkFT(FT_New_Memory_Face(lib, (const unsigned char *)&data[0],
                                   data.size(), 0, &m_face));
    }
    ~_FT_Face() { checkFT(FT_Done_Face(m_face)); }
    operator FT_Face() { return m_face; }
    FT_Face operator->() { return m_face; }

private:
    FT_Face m_face;
};

// Read all the data from a file into a memory buffer.
static void readfile(std::istream &file, std::vector<char> &data)
{
    while (file.good())
    {
        const size_t blocksize = 4096;
        size_t oldsize = data.size();
        data.resize(oldsize + blocksize);
        file.read(&data[oldsize], blocksize);
        data.resize(oldsize + file.gcount());
    }
}

std::unique_ptr<DataFile> LoadFreetype(std::istream &file, int size, bool bw)
{
    std::vector<char> data;
    readfile(file, data);

    _FT_Library lib;
    _FT_Face face(lib, data);

    checkFT(FT_Set_Pixel_Sizes(face, size, size));

    DataFile::fontinfo_t fontinfo = {};
    std::vector<DataFile::glyphentry_t> glyphtable;
    std::vector<DataFile::dictentry_t> dictionary;

    // Convert size to pixels and round to nearest.
    int u_per_em = face->units_per_EM;
    auto topx = [size, u_per_em](int s) { return (s * size + u_per_em / 2) / u_per_em; };

    fontinfo.name = std::string(face->family_name) + " " +
                    std::string(face->style_name) + " " +
                    std::to_string(size);

    // Reserve 4 pixels on each side for antialiasing + hinting.
    // They will be cropped off later.
    fontinfo.max_width = topx(face->bbox.xMax - face->bbox.xMin) + 8;
    fontinfo.max_height = topx(face->bbox.yMax - face->bbox.yMin) + 8;
    fontinfo.baseline_x = topx(-face->bbox.xMin) + 4;
    fontinfo.baseline_y = topx(face->bbox.yMax) + 4;
    fontinfo.line_height = topx(face->height);

    FT_Int32 loadmode = FT_LOAD_TARGET_NORMAL | FT_LOAD_RENDER;

    if (bw)
        loadmode = FT_LOAD_TARGET_MONO | FT_LOAD_MONOCHROME | FT_LOAD_RENDER;

    FT_ULong charcode;
    FT_UInt gindex;
    charcode = FT_Get_First_Char(face, &gindex);
    while (gindex)
    {
        try
        {
            checkFT(FT_Load_Glyph(face, gindex, loadmode));
        }
        catch (std::runtime_error &e)
        {
            std::cerr << "Skipping glyph " << gindex << ": " << e.what() << std::endl;
            charcode = FT_Get_Next_Char(face, charcode, &gindex);
        }

        DataFile::glyphentry_t glyph;
        glyph.width = (face->glyph->advance.x + 32) / 64;
        glyph.chars.push_back(charcode);
        glyph.data.resize(fontinfo.max_width * fontinfo.max_height);

        int w = face->glyph->bitmap.width;
        int dw = fontinfo.max_width;
        int dx = fontinfo.baseline_x + face->glyph->bitmap_left;
        int dy = fontinfo.baseline_y - face->glyph->bitmap_top;

        /* Some combining diacritics seem to exceed the bounding box.
         * We don't support them all that well anyway, so just move
         * them inside the box in order not to crash.. */
        if (dy < 0)
            dy = 0;
        if (dy + face->glyph->bitmap.rows > fontinfo.max_height)
            dy = fontinfo.max_height - face->glyph->bitmap.rows;

        size_t s = face->glyph->bitmap.pitch;
        for (int y = 0; y < face->glyph->bitmap.rows; y++)
        {
            for (int x = 0; x < face->glyph->bitmap.width; x++)
            {
                size_t index = (y + dy) * dw + x + dx;

                if (face->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
                {
                    uint8_t byte = face->glyph->bitmap.buffer[s * y + x / 8];
                    byte <<= x % 8;
                    glyph.data.at(index) = (byte & 0x80) ? 15 : 0;
                }
                else
                {
                    glyph.data.at(index) =
                        (face->glyph->bitmap.buffer[w * y + x] + 8) / 17;
                }
            }
        }
        glyphtable.push_back(glyph);

        charcode = FT_Get_Next_Char(face, charcode, &gindex);
    }

    eliminate_duplicates(glyphtable);
    crop_glyphs(glyphtable, fontinfo);
    detect_flags(glyphtable, fontinfo);

    std::unique_ptr<DataFile> result(new DataFile(
        dictionary, glyphtable, fontinfo));
    return result;
}

}


text:
namespace ash {

// Defines the mode of the encryption migration screen.
enum class EncryptionMigrationMode {
  // Ask the user if migration should be started.
  ASK_USER,
  // Start migration immediately.
  START_MIGRATION,
  // Resume incomplete migration.
  RESUME_MIGRATION
};

}  // namespace ash

#endif  // CHROME_BROWSER_ASH_LOGIN_SCREENS_ENCRYPTION_MIGRATION_MODE_H_

redpajama_set_name: RedPajamaGithub


text:
const time = Date.now || function () {
  return +new Date()
}

let running = {}
let counter = 1
let desiredFrames = 60
let millisecondsPerSecond = 1000

export default {

  // A requestAnimationFrame wrapper / polyfill.
  requestAnimationFrame: (function () {
    var requestFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame
    return function (callback, root) {
      requestFrame(callback, root)
    }
  })(),

  // Stops the given animation.
  stop (id) {
    var cleared = running[id] != null
    if (cleared) {
      running[id] = null
    }
    return cleared
  },

  // Whether the given animation is still running.
  isRunning (id) {
    return running[id] != null
  },

  // Start the animation.
  start (stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {
    var _this = this
    var start = time()
    var lastFrame = start
    var percent = 0
    var dropCounter = 0
    var id = counter++

    if (!root) {
      root = document.body
    }

    // Compacting running db automatically every few new animations
    if (id % 20 === 0) {
      var newRunning = {}
      for (var usedId in running) {
        newRunning[usedId] = true
      }
      running = newRunning
    }

    // This is the internal step method which is called every few milliseconds
    var step = function (virtual) {
      // Normalize virtual value
      var render = virtual !== true
      // Get current time
      var now = time()

      // Verification is executed before next animation step
      if (!running[id] || (verifyCallback && !verifyCallback(id))) {
        running[id] = null
        completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false)
        return
      }

      // For the current rendering to apply let's update omitted steps in memory.
      // This is important to bring internal state variables up-to-date with progress in time.
      if (render) {
        var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1
        for (var j = 0; j < Math.min(droppedFrames, 4); j++) {
          step(true)
          dropCounter++
        }
      }

      // Compute percent value
      if (duration) {
        percent = (now - start) / duration
        if (percent > 1) {
          percent = 1
        }
      }

      // Execute step callback, then...
      var value = easingMethod ? easingMethod(percent) : percent
      if ((stepCallback(value, now, render) === false || percent === 1) && render) {
        running[id] = null
        completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null)
      } else if (render) {
        lastFrame = now
        _this.requestAnimationFrame(step, root)
      }
    }

    // Mark as running
    running[id] = true
    // Init first step
    _this.requestAnimationFrame(step, root)
    // Return unique animation ID
    return id
  }
}


text:
import * as bridge from '../lib/bridge/bridge';
import * as globals from './globals';
import * as constants from './constants';
import * as _ from 'lodash';
import * as key_verify from './key-verify';
import * as logging from '../lib/logging/logging';
import * as loggingTypes from '../lib/loggingprovider/loggingprovider.types';
import * as net from '../lib/net/net.types';
import * as nat_probe from '../lib/nat/probe';
import * as remote_connection from './remote-connection';
import * as remote_instance from './remote-instance';
import * as remote_user from './remote-user';
import * as user from './remote-user';
import * as social_network from './social';
import * as social from '../interfaces/social';
import * as socks from '../lib/socks/headers';
import StoredValue from './stored_value';
import * as tcp from '../lib/net/tcp';
import * as ui_connector from './ui_connector';
import * as uproxy_core_api from '../interfaces/uproxy_core_api';
import * as version from '../generic/version';
import * as freedomXhr from 'freedom-xhr';
import * as uproxy_cloud_install from 'uproxy-cloud-install';
import * as jsurl from 'jsurl';
// TODO: remove uparams as it doesn't work with ES6 imports and TypeScript,
// see https://github.com/uProxy/uproxy/issues/2782
import uparams = require('uparams');

import ui = ui_connector.connector;
import storage = globals.storage;

declare var freedom: freedom.FreedomInModuleEnv;

var log :logging.Log = new logging.Log('core');
log.info('Loading core', version.UPROXY_VERSION);

// Note that the proxy runs extremely slowly in debug ('*:D') mode.
export var loggingController = freedom['loggingcontroller']();
loggingController.setDefaultFilter(
    loggingTypes.Destination.console,
    loggingTypes.Level.warn);
loggingController.setDefaultFilter(
    loggingTypes.Destination.buffered,
    loggingTypes.Level.debug);

var portControl = globals.portControl;

const CLOUD_PROVIDER_NAME = 'digitalocean';
const CLOUD_DEPLOY_PROGRESS = 20;

// This is the name recommended by the blog post.
const CLOUD_DROPLET_NAME = 'uproxy-cloud-server';

/**
 * Primary uProxy backend. Handles which social networks one is connected to,
 * sends updates to the UI, and handles commands from the UI.
 */
export class uProxyCore implements uproxy_core_api.CoreApi {

  // this should be set iff an update to the core is available
  private availableVersion_ :string = null;

  private connectedNetworks_ = new StoredValue<string[]>('connectedNetworks', []);

  constructor() {
    log.debug('Preparing uProxy Core');

    this.refreshPortControlSupport();

    globals.loadSettings.then(() => {
      return this.connectedNetworks_.get();
    }).then((networks :string[]) => {
      var logins :Promise<void>[] = [];

      for (var i in networks) {
        var networkName = networks[i]
        if (!(networkName in social_network.networks)) {
          // Network may have been removed, e.g. old "Facebook" network is now
          // "Facebook-Firebase-V2".
          continue;
        }
        logins.push(this.login({
          network: networkName,
          loginType: uproxy_core_api.LoginType.RECONNECT
        }).catch(() => {
          // any failure to login should just be ignored - the user will either
          // be logged in with just some accounts or still on the login screen
          return;
        }));

        // at this point, clear all networks; those that successfully get logged
        // in will be re-added
        this.connectedNetworks_.set([]);
      }

      // this return is meaningless, but it may be useful in the future
      return Promise.all(logins);
    }).then(() => {
      log.info('Finished handling reconnections');
    });
  }

  // sendInstanceHandshakeMessage = (clientId :string) => {
  //   // TODO: Possibly implement this, or get rid of the possibility for
  //   // UI-initiated instance handshakes.
  // }

  changeOption = (option :string) => {
    // TODO: implement options.
  }

  dismissNotification = (instancePath :social.InstancePath) => {
    // TODO: implement options.
  }

  private pendingNetworks_ :{[name :string] :social.Network} = {};
  private portControlSupport_ = uproxy_core_api.PortControlSupport.PENDING;

  /**
   * Access various social networks using the Social API.
   */
  public login = (loginArgs :uproxy_core_api.LoginArgs) :Promise<uproxy_core_api.LoginResult> => {
    var networkName = loginArgs.network;

    if (!(networkName in social_network.networks)) {
      log.warn('Network does not exist', networkName);
      return Promise.reject(new Error('Network does not exist (' + networkName + ')'));
    }

    var network = this.pendingNetworks_[networkName];
    if (typeof network === 'undefined') {
      network = new social_network.FreedomNetwork(networkName, globals.metrics);
      this.pendingNetworks_[networkName] = network;
    }

    return network.login(loginArgs.loginType, loginArgs.userName).then(() => {
      delete this.pendingNetworks_[networkName];
      log.info('Successfully logged in to network', {
        network: networkName,
        userId: network.myInstance.userId
      });

      // Save network to storage so we can reconnect on restart.
      return this.connectedNetworks_.get().then((networks :string[]) => {
        if (_.includes(networks, networkName)) {
          return;
        }
        networks.push(networkName);
        return this.connectedNetworks_.set(networks);
      }).catch((e) => {
        console.warn('Could not save connected networks', e);
      }).then(() => {
        // Fulfill login's returned promise with uproxy_core_api.LoginResult.
        return {
          userId: network.myInstance.userId,
          instanceId: network.myInstance.instanceId
        }
      });
    }, (e) => {
      delete this.pendingNetworks_[networkName];
      throw e;
    });
  }

  /**
   * Log-out of |networkName|.
   * TODO: write a test for this.
   */
  public logout = (networkInfo :social.SocialNetworkInfo) : Promise<void> => {
    var networkName = networkInfo.name;
    let network :social.Network;
    if (networkInfo.userId) {
      const userId = networkInfo.userId;
      network = social_network.getNetwork(networkName, userId);
    } else {
      network = this.getNetworkByName_(networkName);
    }

    if (null === network) {
      log.warn('Could not logout of network', networkName);
      return;
    } else if (network.name === 'Cloud') {
      log.error('Cannot logout from Cloud');
      return Promise.reject(new Error('Cannot logout from Cloud'));
    }

    return network.logout().then(() => {
      log.info('Successfully logged out of network', networkName);

      return this.connectedNetworks_.get().then((networks) => {
        return this.connectedNetworks_.set(_.without(networks, networkName));
      }).catch((e) => {
        log.warn('Could not remove network from list of connected networks', e);
        // we will probably not be able to log back in anyways, ignore this
        return;
      });
    });
  }

  // onUpdate not needed in the real core.
  onUpdate = (update:uproxy_core_api.Update, handler:Function) => {
    throw 'uproxy_core onUpdate not implemented.';
  }

  public updateGlobalSetting = (change: uproxy_core_api.UpdateGlobalSettingArgs) => {
    // Make sure we have the correct settings object loaded and aren't
    // going to write over something we should not
    globals.loadSettings.then(() => {
      (<any>globals.settings)[change.name] = change.value;

      // We could try to speed things up slightly by just manually calling the
      // save here, but that seems like an unnecessary optimization for something
      // that should not be called that often
      this.updateGlobalSettings(globals.settings);
    });
  }

  /**
   * Updates user's description of their current device. This applies to all
   * local instances for every network the user is currently logged onto. Those
   * local instances will then propogate their description update to all
   * instances.
   */
  public updateGlobalSettings = (newSettings :uproxy_core_api.GlobalSettings) => {
    newSettings.version = constants.STORAGE_VERSION;
    if (newSettings.stunServers.length === 0) {
      newSettings.stunServers = constants.DEFAULT_STUN_SERVERS;
    }
    var oldDescription = globals.settings.description;
    globals.storage.save('globalSettings', newSettings)
      .catch((e) => {
        log.error('Could not save globalSettings to storage', e.stack);
      });

    _.merge(globals.settings, newSettings, (a :Object, b :Object) => {
        // ensure we do not merge the arrays and that the reference remains intact
        if (_.isArray(a) && _.isArray(b)) {
          var arrayA = <Object[]>a;
          arrayA.splice(0, arrayA.length);
          var arrayB = <Object[]>b;
          for (var i in b) {
            arrayA.push(arrayB[parseInt(i)]);
          }
          return a;
        }

        // this causes us to fall back to the default merge behaviour
        return undefined;
    });

    if (globals.settings.description !== oldDescription) {
      // Resend instance info to update description for logged in networks.
      for (var networkName in social_network.networks) {
        for (var userId in social_network.networks[networkName]) {
          social_network.networks[networkName][userId].resendInstanceHandshakes();
        }
      }
    }

    loggingController.setDefaultFilter(
      loggingTypes.Destination.console,
      globals.settings.consoleFilter);
  }

  public getFullState = () :Promise<uproxy_core_api.InitialState> => {
    return globals.loadSettings.then(() => {

      let moveToFront = (array :string[], element :string) :void => {
        let i = array.indexOf(element);
        if (i < 1) {
          return;
        }
        array.splice(0, 0, array.splice(i, 1)[0] );
      };

      let networkNames = Object.keys(social_network.networks);

      for (let name of ['Quiver', 'Cloud']) {
        if (name in social_network.networks) {
          moveToFront(networkNames, name);
        }
      }

      return {
        networkNames: networkNames,
        cloudProviderNames: [CLOUD_PROVIDER_NAME],
        globalSettings: globals.settings,
        onlineNetworks: social_network.getOnlineNetworks(),
        availableVersion: this.availableVersion_,
        portControlSupport: this.portControlSupport_,
      };
    });
  }

  /**
   * Modifies the local consent value as the result of a local user action.
   * This is a distinct pathway from receiving consent bits over the wire, which
   * is handled directly inside the relevant social.Network.
   */
  public modifyConsent = (command:uproxy_core_api.ConsentCommand) => {
    // Determine which Network, User, and Instance...
    var user = this.getUser(command.path);
    if (!user) {  // Error msg emitted above.
      log.error('Cannot modify consent for non-existing user', command.path);
      return;
    }
    // Set the instance's new consent levels. It will take care of sending new
    // consent bits over the wire and re-syncing with the UI.
    user.modifyConsent(command.action);
  }

  public inviteGitHubUser = (data :uproxy_core_api.CreateInviteArgs): Promise<void> => {
    var network = social_network.networks[data.network.name][data.network.userId];
    return network.inviteGitHubUser(data);
  }

  public acceptInvitation = (data :uproxy_core_api.AcceptInvitationData) : Promise<void> => {
    var networkName = data.network.name;
    var networkUserId = data.network.userId;
    if (!networkUserId) {
      // Take the first key in the userId to social network map as the current user.
      // Assumes the user is only signed in once to any given network.
      networkUserId = Object.keys(social_network.networks[networkName])[0];
    }
    try {
      return social_network.getNetwork(networkName, networkUserId).acceptInvitation(
          data.tokenObj, data.userId);
    } catch (e) {
      return Promise.reject(e);
    }
  }

  public getInviteUrl = (data :uproxy_core_api.CreateInviteArgs): Promise<string> => {
    var network = social_network.networks[data.network.name][data.network.userId];
    return network.getInviteUrl(data);
  }

  public sendEmail = (data :uproxy_core_api.EmailData) : void => {
    var networkInfo = data.networkInfo;
    var network = social_network.networks[networkInfo.name][networkInfo.userId];
    network.sendEmail(data.to, data.subject, data.body);
  }

  public postReport = (args :uproxy_core_api.PostReportArgs) : Promise<void> => {
    let host = 'd1wtwocg4wx1ih.cloudfront.net';
    let front = 'https://a0.awsstatic.com/';
    let request:XMLHttpRequest = new freedomXhr.auto();
    return new Promise<any>((F, R) => {
      request.onload = F;
      request.onerror = R;
      // Only the front domain is exposed on the wire. The host and path
      // should be encrypted. The path needs to be here and not
      // in the Host header, which can only take a host name.
      request.open('POST', front + args.path, true);
      // The true destination address is set as the Host in the header.
      request.setRequestHeader('Host', host);
      request.send(JSON.stringify(args.payload));
    });
  }

  /**
   * Begin using a peer as a proxy server.
   * Starts SDP negotiations with a remote peer. Assumes |path| to the
   * RemoteInstance exists.
   */
  public start = (path :social.InstancePath) : Promise<net.Endpoint> => {
    var remote = this.getInstance(path);
    if (!remote) {
      log.error('Instance does not exist for proxying', path.instanceId);
      return Promise.reject(new Error('Instance does not exist for proxying (' + path.instanceId + ')'));
    }
    // Remember this instance as our proxy.  Set this before start fulfills
    // in case the user decides to cancel the proxy before it begins.
    return remote.start();
  }

  /**
   * Stop proxying with the current instance, if it exists.
   */
  public stop = (path :social.InstancePath) => {
    var remote = this.getInstance(path);
    if (!remote) {
      log.error('Instance does not exist for proxying', path.instanceId);
      return Promise.reject(new Error('Instance does not exist for proxying (' + path.instanceId + ')'));
    }
    return remote.stop();
    // TODO: Handle revoked permissions notifications.
  }

  /**
   * Obtain the RemoteInstance corresponding to an instance path.
   */
  public getInstance = (path :social.InstancePath) :social.RemoteUserInstance => {
    var user = this.getUser(path);
    if (!user) {
      log.error('No user', path.userId);
      return;
    }
    return user.getInstance(path.instanceId);
  }

  public getUser = (path :social.UserPath) :social.RemoteUser => {
    var network = social_network.getNetwork(path.network.name, path.network.userId);
    if (!network) {
      log.error('No network', path.network.name);
      return;
    }
    return network.getUser(path.userId);
  }

  // If the user requests the NAT type while another NAT request is pending,
  // the then() block of doNatProvoking ends up being called twice.
  // We keep track of the timeout that resets the NAT type to make sure
  // there is at most one timeout at a time.
  private natResetTimeout_ :NodeJS.Timer;

  public getNatType = () :Promise<string> => {
    if (globals.natType === '') {
      // Function that returns a promise which fulfills
      // in a given time.
      var countdown = (time:number) : Promise<void> => {
        return new Promise<void>((F, R) => {
          setTimeout(F, time);
        });
      }

      // Return the first Promise that fulfills in the 'race'
      // between a countdown and NAT provoking.
      // i.e., if NAT provoking takes longer than 30s, the countdown
      // will return first, and a time out message is returned.
      return Promise.race(
        [ countdown(30000).then(() => {
            return 'NAT classification timed out.';
          }),
          nat_probe.probe().then((natType:string) => {
            globals.setGlobalNatType(natType);
            // Store NAT type for five minutes. This way, if the user previews
            // their logs, and then submits them shortly after, we do not need
            // to determine the NAT type once for the preview, and once for
            // submission to our backend.
            // If we expect users to check NAT type frequently (e.g. if they
            // switch between networks while troubleshooting), then we might want
            // to remove caching.
            clearTimeout(this.natResetTimeout_);
            this.natResetTimeout_ = setTimeout(() => {globals.setGlobalNatType('');}, 300000);
            return globals.natType;
          })
        ]);
    } else {
      return Promise.resolve(globals.natType);
    }
  }

  public getPortControlSupport = (): Promise<uproxy_core_api.PortControlSupport> => {
    return portControl.probeProtocolSupport().then(
        (probe:freedom.PortControl.ProtocolSupport) => {
          return (probe.natPmp || probe.pcp || probe.upnp) ?
                 uproxy_core_api.PortControlSupport.TRUE :
                 uproxy_core_api.PortControlSupport.FALSE;
    });
  }

  // Probe for NAT-PMP, PCP, and UPnP support
  // Sets this.portControlSupport_ and sends update message to UI
  public refreshPortControlSupport = () :Promise<void> => {
    this.portControlSupport_ = uproxy_core_api.PortControlSupport.PENDING;
    ui.update(uproxy_core_api.Update.PORT_CONTROL_STATUS,
              uproxy_core_api.PortControlSupport.PENDING);

    return this.getPortControlSupport().then((support) => {
      this.portControlSupport_ = support;
      ui.update(uproxy_core_api.Update.PORT_CONTROL_STATUS,
                this.portControlSupport_);
    });
  }

  // Checks to see if socks reproxy server is listening on input port by
  // issuing auth request and checking for successful response.
  public checkReproxy = (port :number) :Promise<uproxy_core_api.ReproxyCheck> => {
    var socksEndpoint = {
      address: '127.0.0.1',
      port: port
    };
    var socksConnection = new tcp.Connection({endpoint: socksEndpoint}, false);
    return socksConnection.onceConnected
      .then((info :tcp.ConnectionInfo) :Promise<ArrayBuffer> => {
        socksConnection.send(socks.composeAuthHandshakeBuffer([socks.Auth.NOAUTH]));
        return socksConnection.receiveNext();
      }).then((buffer :ArrayBuffer) :uproxy_core_api.ReproxyCheck => {
        socks.interpretAuthResponse(buffer);
        return uproxy_core_api.ReproxyCheck.TRUE;
      }).catch((e :Error) :uproxy_core_api.ReproxyCheck => {
        return uproxy_core_api.ReproxyCheck.FALSE;
      }).then((result :uproxy_core_api.ReproxyCheck) :uproxy_core_api.ReproxyCheck => {
        socksConnection.close();
        return result;
      });
  }

  // Probe the NAT type and support for port control protocols
  // Returns an object with the NAT configuration as keys
  public getNetworkInfoObj = () :Promise<uproxy_core_api.NetworkInfo> => {
    var natInfo :uproxy_core_api.NetworkInfo = {
      natType: undefined,
      pmpSupport: undefined,
      pcpSupport: undefined,
      upnpSupport: undefined
    };

    return this.getNatType().then((natType:string) => {
      natInfo.natType = natType;
      return portControl.probeProtocolSupport().then(
        (probe:freedom.PortControl.ProtocolSupport) => {
          natInfo.pmpSupport = probe.natPmp;
          natInfo.pcpSupport = probe.pcp;
          natInfo.upnpSupport = probe.upnp;
          return natInfo;
      }).catch((err:Error) => {
        // Should only catch the error when getInternalIp() times out
        natInfo.errorMsg = 'Could not probe for port control protocols: ' + err.message;
        return natInfo;
      });
    });
  }

  // Returns a string of the NAT type and support for port control protocols
  public getNetworkInfo = () :Promise<string> => {
    return this.getNetworkInfoObj().then((natInfo:uproxy_core_api.NetworkInfo) => {
      var natInfoStr = 'NAT Type: ' + natInfo.natType + '\n';
      if (natInfo.errorMsg) {
        natInfoStr += natInfo.errorMsg + '\n';
      } else {
        natInfoStr += 'NAT-PMP: ' +
                  (natInfo.pmpSupport ? 'Supported' : 'Not supported') + '\n';
        natInfoStr += 'PCP: ' +
                  (natInfo.pcpSupport ? 'Supported' : 'Not supported') + '\n';
        natInfoStr += 'UPnP IGD: ' +
                  (natInfo.upnpSupport ? 'Supported' : 'Not supported') + '\n';
      }
      return natInfoStr;
    });
  }

  public getLogs = () :Promise<string> => {
    return loggingController.getLogs().then((rawLogs:string[]) => {
        var formattedLogsWithVersionInfo =
            'Version: ' + JSON.stringify(version.UPROXY_VERSION) + '\n\n';
        formattedLogsWithVersionInfo += this.formatLogs_(rawLogs);
        return formattedLogsWithVersionInfo;
      });
  }

  public getLogsAndNetworkInfo = () :Promise<string> => {
    return Promise.all([this.getNetworkInfo(),
                        this.getLogs()])
      .then((natAndLogs) => {
        // natAndLogs is an array of returned values corresponding to the
        // array of Promises in Promise.all.
        return natAndLogs[0] + '\n' + natAndLogs[1];
      });
  }

  private formatLogs_ = (logs :string[]) :string => {
    // Searches through text for all JSON fields of the specified key, then
    // replaces the values with the prefix + a counter.
    // e.g.
    //   jsonFieldReplace(
    //       '{"name":"Alice"}...{\\"name\\":\\"Bob\\"}...Alice...Bob...',
    //        'name', 'NAME_');
    // will return:
    //   '{"name":"NAME_1"}...{\\"name\\":\\"NAME_2\\"}...NAME_1...NAME_2...'
    var jsonFieldReplace = (text :string, key :string, prefix :string)
        : string => {
      // Allow for escaped JSON to be matched, e.g. {\"name\":\"Bob\"}
      var re = new RegExp('\\\\*"' + key + '\\\\*":\\\\*"([^"]+)"', 'g');
      var matches :string[];
      var uniqueValueSet :{[value :string] :Boolean} = {};
      while (matches = re.exec(text)) {
        matches[1].replace(/\\+$/, '');  // Removing trailing \
        uniqueValueSet[matches[1]] = true;  // Add userId, name, etc to set.
      }
      var index = 1;
      for (var value in uniqueValueSet) {
        // Replace all occurances of value in text.
        var escapedRegex = new RegExp(
            // Escape all special regex characters, from
            // http://stackoverflow.com/questions/3446170/
            value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'),
            'g');
        text = text.replace(escapedRegex, prefix + index);
        ++index;
      }
      return text;
    }

    var text = logs.join('\n');

    text = jsonFieldReplace(text, 'name', 'NAME_');
    text = jsonFieldReplace(text, 'userId', 'USER_ID_');
    text = jsonFieldReplace(text, 'imageData', 'IMAGE_DATA_');
    text = jsonFieldReplace(text, 'url', 'URL_');

    // Replace any emails that may have been missed when replacing userIds.
    // Email regex taken from regular-expressions.info
    text = text.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/ig,
                        'EMAIL_ADDRESS');
    return text;
  }

  public pingUntilOnline = (pingUrl :string) : Promise<void> => {
    var ping = () : Promise<void> => {
      return new Promise<void>(function(fulfill, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', pingUrl);
        xhr.onload = function() { fulfill(); };
        xhr.onerror = function(e) { reject(new Error('Ping failed')); };
        xhr.send();
      });
    }

    return new Promise<void>((fulfill, reject) => {
      let intervalId: NodeJS.Timer;
      const checkIfOnline = () => {
        ping().then(() => {
          clearInterval(intervalId);
          fulfill();
        }).catch((e) => {
          // Ping failed (may be because the internet is disconnected),
          // we will try again on the next interval.
        });
      };
      intervalId = setInterval(checkIfOnline, 5000);
      checkIfOnline();
    });
  }

  public getVersion = () :Promise<{ version :string }> => {
    return Promise.resolve(version.UPROXY_VERSION);
  }

  public handleUpdate = (details :{version :string}) => {
    this.availableVersion_ = details.version;
    ui.update(uproxy_core_api.Update.CORE_UPDATE_AVAILABLE, details);
  }

  public cloudUpdate = (args: uproxy_core_api.CloudOperationArgs)
      :Promise<void> => {
    if (args.providerName !== CLOUD_PROVIDER_NAME) {
      return Promise.reject(new Error('unsupported cloud provider'));
    }

    switch (args.operation) {
      case uproxy_core_api.CloudOperationType.CLOUD_INSTALL:
        if (!args.region) {
          return Promise.reject(new Error('no region specified for cloud provider'));
        }
        return this.createCloudServer_(args.region);
      default:
        return Promise.reject(new Error('cloud operation not supported'));
    }
  }

  private createCloudServer_ = (region: string) => {
    log.debug('creating cloud server in %1', region);

    const REDIRECT_URL = 'https://fmdppkkepalnkeommjadgbhiohihdhii.chromiumapp.org';
    const oauthUrl = uproxy_cloud_install.getDigitalOceanOAuthURL(
          '7d16974f756b4843669d0b04a13dabe89413df90e9de05b9410a829191acf076',
          REDIRECT_URL);
    let oauthProvider = freedom['core.oauth']();
    return oauthProvider.initiateOAuth([REDIRECT_URL]).then((obj: any) => {
      return oauthProvider.launchAuthFlow(oauthUrl, obj).then((responseUrl: string) => {
        const accessToken = responseUrl.match(/access_token=([^&]*)/)[1];
        return uproxy_cloud_install.installOnDigitalOcean(
            accessToken, CLOUD_DROPLET_NAME, region).then((inviteUrl :string) => {
          const params = uparams(inviteUrl);
          let networkDataObj = jsurl.parse(params['networkData']);
          // Set flag so Cloud social provider knows this invite is for the admin
          // user, who just created the server.
          networkDataObj['isAdmin'] = true;
          return this.loginIfNeeded_('Cloud').then((cloudNetwork) => {
            return cloudNetwork.acceptInvitation(<any>{
              v: 2,
              networkName: 'Cloud',
              networkData: JSON.stringify(networkDataObj)
            });
          });
        });
      });
    });
  }

  // Gets a social.Network, and logs the user in if they aren't yet logged in.
  private loginIfNeeded_ = (networkName :string) : Promise<social.Network> => {
    let network = this.getNetworkByName_(networkName);
    if (network) {
      return Promise.resolve(network);
    }

    // User is not yet logged in.
    return this.login({
      network: networkName,
      loginType: uproxy_core_api.LoginType.INITIAL
    }).then(() => {
      return this.getNetworkByName_(networkName);
    });
  }

  // The social_network module in theory should support multiple userIds
  // being logged into the same network.  However that has never been tested
  // and is not used by the rest of uProxy code.  This method just returns
  // the first (and currently only) network for the given networkName, or null
  // if the network is not logged in.
  private getNetworkByName_ = (networkName :string) : social.Network => {
    for (var userId in social_network.networks[networkName]) {
      return social_network.networks[networkName][userId];
    }
    return null;
  }

  public updateOrgPolicy = (policy :uproxy_core_api.ManagedPolicyUpdate): void => {
    // have to load settings first to make sure we don't overwrite anything
    globals.loadSettings.then(() => {
      globals.settings.enforceProxyServerValidity =
          policy.enforceProxyServerValidity;
      globals.settings.validProxyServers = policy.validProxyServers;
      this.updateGlobalSettings(globals.settings);

      ui.update(uproxy_core_api.Update.REFRESH_GLOBAL_SETTINGS, globals.settings);
    });
  }

  public verifyUser = (inst:social.InstancePath) :void => {
    log.info('app.core: verifyUser:', inst);
    // There are additional things our social_network system supports
    // beyond what the freedom social api supports.  So we have to
    // cast into our local API's types to get access to RemoteInstance
    // (which implements no related interfaces).
    var network = <social_network.AbstractNetwork>this.getNetworkByName_(
      inst.network.name);
    var remoteUser :remote_user.User = network.getUser(inst.userId);
    var remoteInstance :remote_instance.RemoteInstance =
      remoteUser.getInstance(inst.instanceId);
    remoteInstance.verifyUser();
  }

  public finishVerifyUser = (args:uproxy_core_api.FinishVerifyArgs) :void => {
    let inst = args.inst;
    log.info('app.core: finishVerifyUser:', inst, ' with result ', args.sameSAS);
    var network = <social_network.AbstractNetwork>this.getNetworkByName_(
      inst.network.name);
    var remoteUser :remote_user.User = network.getUser(inst.userId);
    var remoteInstance :remote_instance.RemoteInstance =
      remoteUser.getInstance(inst.instanceId);
    remoteInstance.finishVerifyUser(args.sameSAS);
  }

  // Remove contact from friend list and storage
  public removeContact = (args :uproxy_core_api.RemoveContactArgs) : Promise<void> => {
    log.info('removeContact', args);
    const network = this.getNetworkByName_(args.networkName);
    return network.removeUserFromStorage(args.userId).then(() => {
      return ui.removeFriend({
        networkName: args.networkName,
        userId: args.userId
      });
    });
  }
}  // class uProxyCore


text:
class Sketchup::DefinitionsObserver

  # Instance Methods

  # The {#onComponentAdded} method is called whenever a definition is added to
  # the definitions collection.
  #
  # @example
  #   def onComponentAdded(definitions, definition)
  #     puts "onComponentAdded: #{definition}"
  #   end
  #
  # @param [Sketchup::DefinitionList] definitions
  #
  # @param [Sketchup::ComponentDefinition] definition
  #
  # @return [nil]
  #
  # @version SketchUp 6.0
  def onComponentAdded(definitions, definition)
  end

  # The {#onComponentPropertiesChanged} method is called whenever a definition's
  # name or description are changed.
  #
  # This does not fire when "Glue To", "Cuts Opening", or "Face Camera" settings
  # are changed.
  #
  # @example
  #   def onComponentPropertiesChanged(definitions, definition)
  #     puts "onComponentPropertiesChanged: #{definition}"
  #   end
  #
  # @param [Sketchup::DefinitionList] definitions
  #
  # @param [Sketchup::ComponentDefinition] definition
  #
  # @return [nil]
  #
  # @version SketchUp 6.0
  def onComponentPropertiesChanged(definitions, definition)
  end

  # The {#onComponentAdded} method is called whenever a definition is removed
  # from the definitions collection.
  #
  # @example
  #   def onComponentRemoved(definitions, definition)
  #     puts "onComponentRemoved: #{definition}"
  #   end
  #
  # @note This methods fires twice for each Component/Group erased.
  #
  # @param [Sketchup::DefinitionList] definitions
  #
  # @param [Sketchup::ComponentDefinition] definition
  #
  # @return [nil]
  #
  # @version SketchUp 6.0
  def onComponentRemoved(definitions, definition)
  end

  # The {#onComponentTypeChanged} event is fired when a component is converted to
  # a group or vice versa. (In the underlying implementation, {Sketchup::Group}s
  # are just a special kind of definition that is allowed to only have a single
  # instance.)
  #
  # @example
  #   def onComponentTypeChanged(definitions, definition)
  #     puts "onComponentTypeChanged: #{definition}"
  #   end
  #
  # @param [Sketchup::DefinitionList] definitions
  #
  # @param [Sketchup::ComponentDefinition] definition
  #
  # @return [nil]
  #
  # @version SketchUp 6.0
  def onComponentTypeChanged(definitions, definition)
  end

end


text:
package com.github.sbugat.rundeckmonitor.tools;

/**
 * Exception to use when the detected Rundeck version is invalid.
 *
 * @author Sylvain Bugat
 *
 */
public final class InvalidRundeckVersion extends Exception {

	/** Unique Serial ID. */
	private static final long serialVersionUID = -9196136377007898216L;

	/** Version of the Rundeck. */
	private final String rundeckVersion;

	/**
	 * Constructor copy detected Rundeck version.
	 *
	 * @param rundeckVersionArg Rundeck version
	 */
	public InvalidRundeckVersion(final String rundeckVersionArg) {
		rundeckVersion = rundeckVersionArg;
	}

	/**
	 * Get the invalid Rundeck version.
	 *
	 * @return Rundeck version
	 */
	public String getRundeckVersion() {
		return rundeckVersion;
	}
}


text:
class AddIndexToDeviceToken < ActiveRecord::Migration
  def self.up
    add_index :users, :device_token
  end

  def self.down
    add_index :users, :device_token
  end
end


text:
package com.yourtion.Pattern16

/**
  * Created by Yourtion on 05/04/2017.
  */
object DiscountBuilder {

  def discount(percent: Double) = {
    if(percent < 0.0 || percent > 100.0)
      throw new IllegalArgumentException("Discounts must be between 0.0 and 100.0.")
    (originalPrice: Double) =>
      originalPrice - (originalPrice * percent * 0.01)
  }

  def run(): Unit = {
    println("DiscountBuilder :")
    println("200 50% discount -> " + discount(50)(200))
    println("200 0% discount -> " + discount(0)(200))
    println("200 100% discount -> " + discount(100)(200))
    val twentyFivePercentOff = discount(25)
    println("Multi1 : " + (Vector(100.0, 25.0, 50.0, 25.0) map twentyFivePercentOff sum))
    println("Multi2 : " + (Vector(75.0, 25.0) map twentyFivePercentOff sum))
  }

}


text:
package com.llfix.util;

import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.llfix.ISimpleQueue;

public final class MemoryQueue<E> implements ISimpleQueue<E> {

	private final Queue<E> q = new ConcurrentLinkedQueue<E>();

	@Override
	public void offer(E e) {
		q.offer(e);
	}

	@Override
	public Iterator<E> iterator() {
		return q.iterator();
	}

}


text:
$(function() {
  var slideToUnlockNew = new Dragdealer('slide-to-unlock-new', {
    x: 1,
    steps: 2,
    loose: true,
    callback: function(x, y) {
      // Only 0 and 1 are the possible values because of "steps: 2"
      if (!x) {
        this.disable();
        $('#slide-to-unlock-new').fadeOut();
        // Bring unlock screen back after a while
        setTimeout(function() {
          slideToUnlockNew.enable();
          slideToUnlockNew.setValue(1, 0, true);
          $('#slide-to-unlock-new').fadeIn();
        }, 5000);
      }
    }
  });
})


text:
{% load thumbnail i18n %}
{% load url from future %}

{% for clipboard in user.filer_clipboards.all %}

{% trans "Clipboard" %}

                <form action="{% url 'admin:filer-paste_clipboard_to_folder' %}" method="post" style="display: inline;">
                    {% csrf_token %}
                    <input type="hidden" name="folder_id" value="{{ folder.id }}" />
                    <input type="hidden" name="clipboard_id" value="{{ clipboard.id }}" />
                    <input type="hidden" name="redirect_to" value="{{ current_url }}" />
                    {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
                    {% if select_folder %}<input type="hidden" name="select_folder" value="1" />{% endif %}
                    <input type="submit" value="⇐"{% if folder.is_root or not permissions.has_add_children_permission %} disabled="disabled" style="color: gray;"{% endif %} title="{% trans "Paste all items here" %}"/>
                </form>
                <form action="{% url 'admin:filer-discard_clipboard' %}" method="post"  style="display: inline;">{% csrf_token %}
                    <input type="hidden" name="clipboard_id" value="{{ clipboard.id }}" />
                    <input type="hidden" name="redirect_to" value="{{ current_url }}" />
                    {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
                    {% if select_folder %}<input type="hidden" name="select_folder" value="1" />{% endif %}
                    <input type="submit" value="{% trans "discard" %}" title="{% trans "Move all clipboard files to" %} '{% trans "unfiled files" %}' {% trans "folder" %}"/>
                </form>{% comment %}
                <form action="{% url 'admin:filer-delete_clipboard' %}" method="post"  style="display: inline;">{% csrf_token %}
                    <input type="hidden" name="clipboard_id" value="{{ clipboard.id }}" />
                    <input type="hidden" name="redirect_to" value="{{ current_url }}" />
                    {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
                    <input type="submit" value="{% trans "delete files" %}" title="{% trans "Delete all files in the clipboard" %}" />
                </form>{% endcomment %}

{% if clipboard.files.count %}{% with clipboard.files.all as items %}
        {% include "admin/filer/tools/clipboard/clipboard_item_rows.html" %}
        {% endwith %}
    {% else %}

            {% trans "the clipboard is empty" %}

    {% endif %}

{% endfor %}


text:
test_description="Test installation and some basic commands"

. lib/test-lib.sh

test_expect_success "current dir is writable" '
	echo "It works!" >test.txt
'

test_expect_success "ipfs version succeeds" '
	ipfs version >version.txt
'

test_expect_success "ipfs version output looks good" '
	egrep "^ipfs version [0-9]+\.[0-9]+\.[0-9]" version.txt >/dev/null ||
	test_fsh cat version.txt
'

test_expect_success "ipfs version --all has all required fields" '
	ipfs version --all > version_all.txt &&
	grep "go-ipfs version" version_all.txt &&
	grep "Repo version" version_all.txt &&
	grep "System version" version_all.txt &&
	grep "Golang version" version_all.txt
'

test_expect_success "ipfs help succeeds" '
	ipfs help >help.txt
'

test_expect_success "ipfs help output looks good" '
	egrep -i "^Usage" help.txt >/dev/null &&
	egrep "ipfs .* <command>" help.txt >/dev/null ||
	test_fsh cat help.txt
'

test_expect_success "'ipfs commands' succeeds" '
	ipfs commands >commands.txt
'

test_expect_success "'ipfs commands' output looks good" '
	grep "ipfs add" commands.txt &&
	grep "ipfs daemon" commands.txt &&
	grep "ipfs update" commands.txt
'

test_expect_success "All commands accept --help" '
	while read -r cmd
	do
		echo "running: $cmd --help"
		$cmd --help </dev/null >/dev/null || return
	done <commands.txt
'

test_expect_success "'ipfs commands --flags' succeeds" '
	ipfs commands --flags >commands.txt
'

test_expect_success "'ipfs commands --flags' output looks good" '
	grep "ipfs pin add --recursive / ipfs pin add -r" commands.txt &&
	grep "ipfs id --format / ipfs id -f" commands.txt &&
	grep "ipfs repo gc --quiet / ipfs repo gc -q" commands.txt
'

test_done


text:
namespace DataStructures.Tests.TestModels
{
    internal class TreeItemData<T> : TreeItemData
    {
        public TreeItemData(int id, int? parentId, T value)
            : base(id, parentId, value)
        {
            this.Value = value;
        }

        public new T Value { get; private set; }
    }

    internal abstract class TreeItemData
    {
        public int Id { get; private set; }

        public int? ParentId { get; private set; }

        public object Value { get; private set; }

        protected TreeItemData(int id, int? parentId, object value)
        {
            this.Value = value;
            this.Id = id;
            this.ParentId = parentId;
        }

        public static TreeItemData<T> Create<T>(int id, int? parentId, T value)
        {
            return new TreeItemData<T>(id, parentId, value);
        }
    }
}


text:
from __future__ import absolute_import
import sys
if sys.version_info >= (3, 0):  # pragma: no cover
    from .py3_parser.FclParser import *  # noqa: F403,F401
else:  # pragma: no cover
    from .py2_parser.FclParser import *  # noqa: F403,F401

class FclParserException(RuntimeError):
    """
    Exception raised by any error during the parse of the FCL file
    """
    def __init__(self, node):
        payload = node.getPayload()
        symbol = node.getText()
        message = "Error parsing FCL. '{}' is not valid in the line {}:{}.".format(
            symbol,
            payload.line,
            payload.column
        )
        self.message = message
        self.node = node
        super(FclParserException, self).__init__(message)


text:
{{post.title}}

            {{post.desc}}

            @{{post.user.name}}

         {{post.udate * 1000 | date:'yyyy年MM月dd日 HH:mm'}}

        再生回数

        ええね

        コメント

        {{post.playCount}}

        {{post.eeneCount}}

        {{post.commentCount}}

        <audio src={{post.mp3}} controls class="col-xs-12" (play)="play(post)"></audio>

        コメントする
        <button type="button" class="btn btn-outline-primary eene-btn" [ngClass]="{'eene-btn-primary': eene}" (click)="setEeene()">
            ええね
        </button>
        <button type="button" class="btn btn-outline-primary btn-gray">{{post.eeneCount}}</button>

            ログインすると、ええね、コメントができます。

        <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" [(ngModel)]="commentText"></textarea>

        <button type="button" class="btn btn-primary btn-sm" (click)="newComment()">コメント</button>

            @{{comment.user.name}}
            {{comment.udate | timestampAgo}}

{{comment.comment}}

        <button type="button" class="btn btn-sm btn-gray" (click)="removeComment(comment)" *ngIf="user != null && user._id === comment.user._id">削除</button>


text:
require 'roo'
require 'roo-xls'
require 'ole/storage'
require 'ndr_support/safe_file'
require_relative 'office_file_helper'
require_relative 'registry'

module NdrImport
  # This is one of a collection of file handlers that deal with individual formats of data.
  # They can be instantiated directly or via the factory method Registry.tables
  module File
    # This class is an excel file handler that returns tables (worksheets).
    # It provides a file reader method and methods to cast raw values
    # appropriately. These methods can be overridden or aliased as required.
    #
    class Excel < Base
      include OfficeFileHelper

      # Iterate through the file table by table, yielding each one in turn.
      def tables
        return enum_for(:tables) unless block_given?

        workbook = load_workbook(@filename)
        workbook.sheets.each do |sheet_name|
          yield sheet_name, excel_rows(workbook, sheet_name)
        end
      end

      protected

      def cast_excel_value(raw_value)
        return raw_value if raw_value.nil?

        if raw_value.is_a?(Date) || raw_value.is_a?(DateTime) || raw_value.is_a?(Time)
          cast_excel_datetime_as_date(raw_value)
        elsif raw_value.is_a?(Float)
          if raw_value.to_f == raw_value.to_i
            # Whole number
            return raw_value.to_i.to_s
          else
            return raw_value.to_f.to_s
          end
        else
          return raw_value.to_s.strip
        end
      end

      def cast_excel_datetime_as_date(raw_value)
        raw_value.to_s(:db)
      end

      private

      # Iterate through the sheet line by line, yielding each one in turn.
      def excel_rows(workbook, sheet_name, &block)
        return enum_for(:excel_rows, workbook, sheet_name) unless block

        if workbook.is_a?(Roo::Excelx)
          # FIXME: xlsx_rows(sheet, &block) should produce the same output as xls_rows
          xls_rows(workbook, sheet_name, &block)
        else
          xls_rows(workbook, sheet_name, &block)
        end
      end

      # Iterate through an xls sheet line by line, yielding each one in turn.
      def xls_rows(workbook, sheet_name)
        return enum_for(:xls_rows, workbook, sheet_name) unless block_given?

        return unless workbook.first_row(sheet_name)
        rows    = workbook.first_row(sheet_name)..workbook.last_row(sheet_name)
        columns = workbook.first_column(sheet_name)..workbook.last_column(sheet_name)

        rows.each do |row|
          yield columns.map { |col| cast_excel_value(workbook.cell(row, col, sheet_name)) }
        end
      end

      # Iterate through an xlsx sheet line by line, yielding each one in turn.
      # This method uses streaming https://github.com/roo-rb/roo#excel-xlsx-and-xlsm-support
      def xlsx_rows(workbook, sheet_name)
        return enum_for(:xlsx_rows, workbook, sheet_name) unless block_given?

        workbook.each_row_streaming(sheet: sheet_name, pad_cells: true) do |row|
          yield row.map { |cell| cast_excel_value(cell.value) }
        end
      end

      def load_workbook(path)
        case SafeFile.extname(path).downcase
        when '.xls'
          Roo::Excel.new(SafeFile.safepath_to_string(path))
        when '.xlsm', '.xlsx'
          if @options['file_password']
            Roo::Excelx.new(StringIO.new(decrypted_file_string(path, @options['file_password'])))
          else
            Roo::Excelx.new(SafeFile.safepath_to_string(path))
          end
        else
          raise "Received file path with unexpected extension #{SafeFile.extname(path)}"
        end
      rescue Ole::Storage::FormatError => e
        # TODO: Do we need to remove the new_file after using it?

        # try to load the .xls file as an .xlsx file, useful for sources like USOM
        # roo check file extensions in file_type_check (GenericSpreadsheet),
        # so we create a duplicate file in xlsx extension
        raise e.message unless /(.*)\.xls$/.match(path)

        new_file_name = SafeFile.basename(path).gsub(/(.*)\.xls$/, '\1_amend.xlsx')
        new_file_path = SafeFile.dirname(path).join(new_file_name)
        copy_file(path, new_file_path)

        load_workbook(new_file_path)
      rescue RuntimeError, ::Zip::Error => e
        raise ["Unable to read the file '#{path}'", e.message].join('; ')
      end

      # Note that this method can produce insecure calls. All callers must protect
      # their arguments.
      # Arguments:
      #   * source - SafeFile
      #   * dest - SafeFile
      #
      def copy_file(source, dest)
        # SECURE: TVB Mon Aug 13 13:53:02 BST 2012 : Secure SafePath will do the security checks
        # before it is converted to string.
        # SafeFile will make sure that the arguments are actually SafePath
        FileUtils.mkdir_p(SafeFile.safepath_to_string(SafeFile.dirname(dest)))
        FileUtils.cp(SafeFile.safepath_to_string(source), SafeFile.safepath_to_string(dest))
      end
    end

    Registry.register(Excel, 'xls', 'xlsm', 'xlsx')
  end
end


text:
use rustc_middle::mir::{self, BasicBlock, Location};

use super::{Analysis, Direction, Results};

/// Calls the corresponding method in `ResultsVisitor` for every location in a `mir::Body` with the
/// dataflow state at that location.
pub fn visit_results<F, V>(
    body: &'mir mir::Body<'tcx>,
    blocks: impl IntoIterator<Item = BasicBlock>,
    results: &V,
    vis: &mut impl ResultsVisitor<'mir, 'tcx, FlowState = F>,
) where
    V: ResultsVisitable<'tcx, FlowState = F>,
{
    let mut state = results.new_flow_state(body);

    #[cfg(debug_assertions)]
    let reachable_blocks = mir::traversal::reachable_as_bitset(body);

    for block in blocks {
        #[cfg(debug_assertions)]
        assert!(reachable_blocks.contains(block));

        let block_data = &body[block];
        V::Direction::visit_results_in_block(&mut state, block, block_data, results, vis);
    }
}

pub trait ResultsVisitor<'mir, 'tcx> {
    type FlowState;

    fn visit_block_start(
        &mut self,
        _state: &Self::FlowState,
        _block_data: &'mir mir::BasicBlockData<'tcx>,
        _block: BasicBlock,
    ) {
    }

    /// Called with the `before_statement_effect` of the given statement applied to `state` but not
    /// its `statement_effect`.
    fn visit_statement_before_primary_effect(
        &mut self,
        _state: &Self::FlowState,
        _statement: &'mir mir::Statement<'tcx>,
        _location: Location,
    ) {
    }

    /// Called with both the `before_statement_effect` and the `statement_effect` of the given
    /// statement applied to `state`.
    fn visit_statement_after_primary_effect(
        &mut self,
        _state: &Self::FlowState,
        _statement: &'mir mir::Statement<'tcx>,
        _location: Location,
    ) {
    }

    /// Called with the `before_terminator_effect` of the given terminator applied to `state` but not
    /// its `terminator_effect`.
    fn visit_terminator_before_primary_effect(
        &mut self,
        _state: &Self::FlowState,
        _terminator: &'mir mir::Terminator<'tcx>,
        _location: Location,
    ) {
    }

    /// Called with both the `before_terminator_effect` and the `terminator_effect` of the given
    /// terminator applied to `state`.
    ///
    /// The `call_return_effect` (if one exists) will *not* be applied to `state`.
    fn visit_terminator_after_primary_effect(
        &mut self,
        _state: &Self::FlowState,
        _terminator: &'mir mir::Terminator<'tcx>,
        _location: Location,
    ) {
    }

    fn visit_block_end(
        &mut self,
        _state: &Self::FlowState,
        _block_data: &'mir mir::BasicBlockData<'tcx>,
        _block: BasicBlock,
    ) {
    }
}

/// Things that can be visited by a `ResultsVisitor`.
///
/// This trait exists so that we can visit the results of multiple dataflow analyses simultaneously.
/// DO NOT IMPLEMENT MANUALLY. Instead, use the `impl_visitable` macro below.
pub trait ResultsVisitable<'tcx> {
    type Direction: Direction;
    type FlowState;

    /// Creates an empty `FlowState` to hold the transient state for these dataflow results.
    ///
    /// The value of the newly created `FlowState` will be overwritten by `reset_to_block_entry`
    /// before it can be observed by a `ResultsVisitor`.
    fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState;

    fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock);

    fn reconstruct_before_statement_effect(
        &self,
        state: &mut Self::FlowState,
        statement: &mir::Statement<'tcx>,
        location: Location,
    );

    fn reconstruct_statement_effect(
        &self,
        state: &mut Self::FlowState,
        statement: &mir::Statement<'tcx>,
        location: Location,
    );

    fn reconstruct_before_terminator_effect(
        &self,
        state: &mut Self::FlowState,
        terminator: &mir::Terminator<'tcx>,
        location: Location,
    );

    fn reconstruct_terminator_effect(
        &self,
        state: &mut Self::FlowState,
        terminator: &mir::Terminator<'tcx>,
        location: Location,
    );
}

impl<'tcx, A> ResultsVisitable<'tcx> for Results<'tcx, A>
where
    A: Analysis<'tcx>,
{
    type FlowState = A::Domain;

    type Direction = A::Direction;

    fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState {
        self.analysis.bottom_value(body)
    }

    fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock) {
        state.clone_from(&self.entry_set_for_block(block));
    }

    fn reconstruct_before_statement_effect(
        &self,
        state: &mut Self::FlowState,
        stmt: &mir::Statement<'tcx>,
        loc: Location,
    ) {
        self.analysis.apply_before_statement_effect(state, stmt, loc);
    }

    fn reconstruct_statement_effect(
        &self,
        state: &mut Self::FlowState,
        stmt: &mir::Statement<'tcx>,
        loc: Location,
    ) {
        self.analysis.apply_statement_effect(state, stmt, loc);
    }

    fn reconstruct_before_terminator_effect(
        &self,
        state: &mut Self::FlowState,
        term: &mir::Terminator<'tcx>,
        loc: Location,
    ) {
        self.analysis.apply_before_terminator_effect(state, term, loc);
    }

    fn reconstruct_terminator_effect(
        &self,
        state: &mut Self::FlowState,
        term: &mir::Terminator<'tcx>,
        loc: Location,
    ) {
        self.analysis.apply_terminator_effect(state, term, loc);
    }
}


text:
<?php
/**
 * DI Configuration
 *
 * @author: Thomas Bähr t.baehr@flyeralarm.de
 * @package: backend\php1\
 * @link: http://www.meetup.com/flyeralarm/events/185109082/
 * @version: 1
 */

namespace CD2048\bundle\BackendBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('cd2048bundle_backend');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jme3.gde.scenecomposer.tools.shortcuts;

import com.jme3.asset.AssetManager;
import com.jme3.gde.core.sceneexplorer.SceneExplorerTopComponent;
import com.jme3.gde.core.sceneexplorer.nodes.JmeNode;
import com.jme3.gde.core.sceneexplorer.nodes.JmeSpatial;
import com.jme3.gde.core.sceneviewer.SceneViewerTopComponent;
import com.jme3.gde.core.undoredo.AbstractUndoableSceneEdit;
import com.jme3.gde.scenecomposer.SceneComposerToolController;
import com.jme3.input.KeyInput;
import com.jme3.input.event.KeyInputEvent;
import com.jme3.math.Vector2f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import org.openide.loaders.DataObject;
import org.openide.util.Lookup;

/**
 *
 * @author dokthar
 */
public class DuplicateShortcut extends ShortcutTool {

    @Override
    public boolean isActivableBy(KeyInputEvent kie) {
        if (kie.getKeyCode() == KeyInput.KEY_D && kie.isPressed()) {
            if (Lookup.getDefault().lookup(ShortcutManager.class).isShiftDown()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void cancel() {
        terminate();
    }

    @Override
    public void activate(AssetManager manager, Node toolNode, Node onTopToolNode, Spatial selectedSpatial, SceneComposerToolController toolController) {
        super.activate(manager, toolNode, onTopToolNode, selectedSpatial, toolController); //To change body of generated methods, choose Tools | Templates.
        hideMarker();
        if (selectedSpatial != null) {
            duplicate();
            terminate();

            //then enable move shortcut
            toolController.doKeyPressed(new KeyInputEvent(KeyInput.KEY_G, 'g', true, false));
        } else {
            terminate();
        }
    }

    private void duplicate() {
        Spatial selected = toolController.getSelectedSpatial();

        Spatial clone = selected.clone();
        clone.move(1, 0, 1);

        selected.getParent().attachChild(clone);
        actionPerformed(new DuplicateUndo(clone, selected.getParent()));
        selected = clone;
        final Spatial cloned = clone;
        final JmeNode rootNode = toolController.getRootNode();
        refreshSelected(rootNode, selected.getParent());

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                if (cloned != null) {
                    SceneViewerTopComponent.findInstance().setActivatedNodes(new org.openide.nodes.Node[]{rootNode.getChild(cloned)});
                    SceneExplorerTopComponent.findInstance().setSelectedNode(rootNode.getChild(cloned));
                }
            }
        });

        toolController.updateSelection(selected);
    }

    private void refreshSelected(final JmeNode jmeRootNode, final Node parent) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                jmeRootNode.getChild(parent).refresh(false);
            }
        });
    }

    @Override
    public void keyPressed(KeyInputEvent kie) {

    }

    @Override
    public void actionPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) {
    }

    @Override
    public void actionSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject dataObject) {
    }

    @Override
    public void mouseMoved(Vector2f screenCoord, JmeNode rootNode, DataObject dataObject) {
    }

    @Override
    public void draggedPrimary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) {
    }

    @Override
    public void draggedSecondary(Vector2f screenCoord, boolean pressed, JmeNode rootNode, DataObject currentDataObject) {
    }

    private class DuplicateUndo extends AbstractUndoableSceneEdit {

        private Spatial spatial;
        private Node parent;

        DuplicateUndo(Spatial spatial, Node parent) {
            this.spatial = spatial;
            this.parent = parent;
        }

        @Override
        public void sceneUndo() {
            spatial.removeFromParent();
        }

        @Override
        public void sceneRedo() {
            parent.attachChild(spatial);
        }
    }
}


text:
<?php

/**
 * @author Саша Стаменковић <umpirsky@gmail.com>
 */

$schema = new \Doctrine\DBAL\Schema\Schema();

$gloves = $schema->createTable('ismartbrowse_orders');
$gloves->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
$gloves->addColumn('firstName', 'string', array('length' => 255));
$gloves->addColumn('lastName', 'string', array('length' => 255));
$gloves->addColumn('address1Billing', 'string', array('length' => 255));
$gloves->addColumn('address2Billing', 'string', array('length' => 255));
$gloves->addColumn('zipBilling', 'string', array('length' => 255));
$gloves->addColumn('cityBilling', 'string', array('length' => 255));
$gloves->addColumn('stateBilling', 'string', array('length' => 255));
$gloves->addColumn('countryBilling', 'string', array('length' => 255));
$gloves->addColumn('address1Shipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('address2Shipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('zipShipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('cityShipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('stateShipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('countryShipping', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('email', 'string', array('length' => 255));
$gloves->addColumn('gender', 'string', array('length' => 1));
$gloves->addColumn('quantity', 'integer', array('length' => 11));
$gloves->addColumn('paymentChoice', 'integer', array('length' => 2));
$gloves->addColumn('sameAsShipping', 'integer', array('length' => 2));
$gloves->addColumn('trackingNumber', 'string', array('length' => 255, 'notnull' => false));
$gloves->addColumn('shipped', 'boolean', array('notnull' => false));
$gloves->setPrimaryKey(array('id'));

return $schema;


text:
#ifndef __InverseDynamicsTool_h__
#define __InverseDynamicsTool_h__

#include "osimToolsDLL.h"
#include <OpenSim/Common/Object.h>
#include <OpenSim/Common/PropertyBool.h>
#include <OpenSim/Common/PropertyDbl.h>
#include <OpenSim/Common/PropertyStr.h>
#include <OpenSim/Common/PropertyDblArray.h>
#include "DynamicsTool.h"

#ifdef SWIG
	#ifdef OSIMTOOLS_API
		#undef OSIMTOOLS_API
		#define OSIMTOOLS_API
	#endif
#endif

namespace OpenSim {

class Model;
class JointSet;

//=============================================================================
//=============================================================================
/**
 * A Tool that performs an Inverse Dynamics analysis with a given model.
 * Inverse Dynamics is the solution for the generalized-coordinate forces that
 * generate given generalized-coordinate accelerations at a given state.
 * This Tool determines the state from provided coordinate trajectories as
 * functions as that are twice differntiable to estimate velocities and
 * accelerations.
 *
 * @author Ajay Seth
 * @version 1.0
 */
class OSIMTOOLS_API InverseDynamicsTool: public DynamicsTool {
OpenSim_DECLARE_CONCRETE_OBJECT(InverseDynamicsTool, DynamicsTool);

//=============================================================================
// MEMBER VARIABLES
//=============================================================================
	Storage* _coordinateValues;
protected:

	/** name of storage file that contains coordinate values for inverse dynamics solving */
	PropertyStr _coordinatesFileNameProp;
	std::string &_coordinatesFileName;

	/** Low-pass cut-off frequency for filtering the coordinates (does not apply to states). */
	PropertyDbl _lowpassCutoffFrequencyProp;
	double &_lowpassCutoffFrequency;

	// name of storage file containing generalized forces from innverse dynamics
	PropertyStr _outputGenForceFileNameProp;
	std::string &_outputGenForceFileName;

	/** Idenitify the list of joints for which equivalent body forces acting at the joint should be reported */
	PropertyStrArray _jointsForReportingBodyForcesProp;
	Array<std::string> &_jointsForReportingBodyForces;

	// name of storage file containing generalized forces from innverse dynamics
	PropertyStr _outputBodyForcesAtJointsFileNameProp;
	std::string &_outputBodyForcesAtJointsFileName;

//=============================================================================
// METHODS
//=============================================================================
	//--------------------------------------------------------------------------
	// CONSTRUCTION
	//--------------------------------------------------------------------------
public:
	virtual ~InverseDynamicsTool();
	InverseDynamicsTool();
	InverseDynamicsTool(const std::string &aFileName, bool aLoadModel=true) SWIG_DECLARE_EXCEPTION;
	InverseDynamicsTool(const InverseDynamicsTool &aObject);

	/* Register types to be used when reading an InverseDynamicsTool object from xml file. */
	static void registerTypes();
	/* Handle reading older formats/Versioning */
	virtual void updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber=-1);

protected:
	/** helper method to get a list of model joints by name */
	void getJointsByName(Model &model, const Array<std::string> &jointNames, JointSet &joints) const;

private:
	void setNull();
	void setupProperties();

	//--------------------------------------------------------------------------
	// OPERATORS
	//--------------------------------------------------------------------------
public:
#ifndef SWIG
	InverseDynamicsTool& operator=(const InverseDynamicsTool &aInverseDynamicsTool);
#endif

	//--------------------------------------------------------------------------
	// GET AND SET
	//--------------------------------------------------------------------------
	void setCoordinateValues(const OpenSim::Storage& aStorage);
	bool hasCoordinateValues();
    /**
     * get/set the name of the file to be used as ouput from the tool
     */
	std::string getOutputGenForceFileName() const { return _outputGenForceFileName;}
    void setOutputGenForceFileName(const std::string& desiredOutputFileName) {
        _outputGenForceFileName = desiredOutputFileName;
    }
    /**
     * get/set the name of the file containing coordinates
     */
	const std::string& getCoordinatesFileName() const { return _coordinatesFileName;};
	void setCoordinatesFileName(const std::string& aCoordinateFile)  {
		_coordinatesFileName=aCoordinateFile;
	};
	const double getLowpassCutoffFrequency() const {
		return _lowpassCutoffFrequency;
	};
	void setLowpassCutoffFrequency(double aFrequency) {
		_lowpassCutoffFrequency = aFrequency;
	}
	//--------------------------------------------------------------------------
	// INTERFACE
	//--------------------------------------------------------------------------
	virtual bool run() SWIG_DECLARE_EXCEPTION;

//=============================================================================
};	// END of class InverseDynamicsTool
//=============================================================================
} // namespace

#endif // __InverseDynamicsTool_h__


text:
The driver communicates with Cassandra over TCP, using the Cassandra
binary protocol. This protocol is asynchronous, which allows each TCP
connection to handle multiple simultaneous requests:

* when a query gets executed, a *stream id* gets assigned to it. It is a
  unique identifier for the current connection;
* the driver writes a request containing the stream id and the query on
  the connection, and then proceeds without waiting for the response (if
  you're using the asynchronous API, this is when the driver will send you
  back a [ResultSetFuture][result_set_future]).
  Once the request has been written to the
  connection, we say that it is *in flight*;
* at some point, Cassandra will send back a response on the connection.
  This response also contains the stream id, which allows the driver to
  trigger a callback that will complete the corresponding query (this is
  the point where your `ResultSetFuture` will get completed).

Version 2.0.x of the driver uses version 1 of the binary protocol when
connecting to Cassandra 1.2, and version 2 when connecting to Cassandra
2.0 or higher. In both cases, that gives you **128 stream ids per
connection**.

Because the number of stream ids per connection is limited, we use a
pool with multiple connections to each host. **For each `Session`
object, there is one connection pool per connected host**. The number of
connections per pool depends on the configuration, this will be
described in the next section.

```ditaa
+-------+1   n+-------+1   n+----+1   n+----------+1   128+-------+
|Cluster+-----+Session+-----+Pool+-----+Connection+-------+Request+
+-------+     +-------+     +----+     +----------+       +-------+
```

### Configuring the connection pool

Connections pools are configured with a [PoolingOptions][pooling_options] object, which
is global to a `Cluster` instance. You can pass that object when
building the cluster:

```java
PoolingOptions poolingOptions = new PoolingOptions();
// customize options...

Cluster cluster = Cluster.builder()
    .withContactPoints("127.0.0.1")
    .withPoolingOptions(poolingOptions)
    .build();
```

Most options can also be changed at runtime. If you don't have a
reference to the `PoolingOptions` instance, here's how you can get it:

```java
PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
// customize options...
```

#### Pool size

Connection pools have a variable size, which gets adjusted automatically
depending on the current load. There will always be at least a *core*
number of connections, and at most a *max* number. These values can be
configured independently by host *distance* (the distance is determined
by your [LoadBalancingPolicy][lbp], and will generally indicate whether a
host is in the same datacenter or not).

```java
poolingOptions
    .setCoreConnectionsPerHost(HostDistance.LOCAL,  4)
    .setMaxConnectionsPerHost( HostDistance.LOCAL, 10)
    .setCoreConnectionsPerHost(HostDistance.REMOTE, 2)
    .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
```

Note: the setters always enforce core <= max, which can get annoying
when you try to set both values at once.
[JAVA-662](https://datastax-oss.atlassian.net/browse/JAVA-662) will
address this issue.

[PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct]
has a slightly misleading name: it does not limit the number of requests per
connection, but only determines the threshold that triggers the creation
of a new connection when the pool is not at its maximum capacity. In
general, you shouldn't have to change its default value.

#### Heartbeat

If connections stay idle for too long, they might be dropped by
intermediate network devices (routers, firewalls...). Normally, TCP
keepalive should take care of this; but tweaking low-level keepalive
settings might be impractical in some environments.

The driver provides application-side keepalive in the form of a
connection heartbeat: when a connection has been idle for a given amount
of time, the driver will simulate activity by writing a dummy request to
it.

This feature is enabled by default. The default heartbeat interval is 30
seconds, it can be customized with the following method:

```java
poolingOptions.setHeartbeatIntervalSeconds(60);
```

If it gets changed at runtime, only connections created after that will
use the new interval. Most users will want to do this at startup.

The heartbeat interval should be set higher than
[SocketOptions.readTimeoutMillis][rtm]:
the read timeout is the maximum time that the driver waits for a regular
query to complete, therefore the connection should not be considered
idle before it has elapsed.

To disable heartbeat, set the interval to 0.

Implementation note: the dummy request sent by heartbeat is an
[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278)
message.

#### Acquisition timeout

When the driver tries to send a request to a host, it will first try to
acquire a connection from this host's pool. If the pool is busy (i.e.
all connections are already handling their maximum number of in flight
requests), the client thread will block for a while, until a connection
becomes available (note that this will block even if you're using the
asynchronous API, like [Session.executeAsync][exec_async]).

The time that the driver blocks is controlled by
[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
available after this timeout, the driver will try the next host.

For some applications, blocking is not acceptable, and it is preferable
to fail fast if the request cannot be fulfilled. If that's your case,
set the pool timeout to 0. If all hosts are busy, you will get a
[NoHostAvailableException][nhae] (if you look at the exception's details, you
will see a `java.util.concurrent.TimeoutException` for each host).

### Monitoring and tuning the pool

The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's
a simple example that will print the number of open connections, active
requests, and maximum capacity for each host, every 5 seconds:

```java
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
scheduled.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        Session.State state = session.getState();
        for (Host host : state.getConnectedHosts()) {
            int connections = state.getOpenConnections(host);
            int inFlightQueries = state.getInFlightQueries(host);
            System.out.printf("%s connections=%d current load=%d max load=%d%n",
                host, connections, inFlightQueries, connections * 128);
        }
    }
}, 5, 5, TimeUnit.SECONDS);
```

In real life, you'll probably want something more sophisticated, like
exposing a JMX MBean or sending the data to your favorite monitoring
tool.

If you find that the current load stays close or equal to the maximum
load at all time, it's a sign that your connection pools are saturated
and you should raise the max connections per host. On the other hand, if
the load is often less than core * 128, your pools are underused and you
could get away with less core connections.

[result_set_future]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/ResultSetFuture.html
[pooling_options]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html
[lbp]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
[msrpct]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
[rtm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
[exec_async]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
[ptm]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
[nhae]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
[get_state]:http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Session.html#getState()


text:
package org.ovirt.engine.core.utils.serialization.json;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.As;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;

@SuppressWarnings("serial")
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
public abstract class JsonVdcActionParametersBaseMixIn extends VdcActionParametersBase {
    /**
     * Ignore this method since Jackson will try to recursively dereference it and fail to serialize.
     */
    @JsonIgnore
    @Override
    public abstract VdcActionParametersBase getParentParameters();

}


text:
Replipy
=======

CouchDB Replication Protocol implementation in Python.

Goals
=====

- Understand how replication protocol actually works;
- Implement the peer: endpoint that may be bidirectional synced with CouchDB;
- Implement the replicator: service that runs the replication between two peers;
- First of all, this is tutorial project that aims to be simple and stupid,
  without ambitions to fit production requirements (may be later)


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.FileModifier;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateBuilderImpl;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Function;

public class RenameWrongRefFix implements IntentionAction, LowPriorityAction {
  private final PsiReferenceExpression myRefExpr;
  @NonNls private static final String INPUT_VARIABLE_NAME = "INPUTVAR";
  @NonNls private static final String OTHER_VARIABLE_NAME = "OTHERVAR";
  private final boolean myUnresolvedOnly;

  public RenameWrongRefFix(@NotNull PsiReferenceExpression refExpr) {
    this(refExpr, false);
  }

  public RenameWrongRefFix(@NotNull PsiReferenceExpression refExpr, final boolean unresolvedOnly) {
    myRefExpr = refExpr;
    myUnresolvedOnly = unresolvedOnly;
  }

  @Override
  public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
    return new RenameWrongRefFix(PsiTreeUtil.findSameElementInCopy(myRefExpr, target), myUnresolvedOnly);
  }

  @Override
  @NotNull
  public String getText() {
    return QuickFixBundle.message("rename.wrong.reference.text");
  }

  @Override
  @NotNull
  public String getFamilyName() {
    return QuickFixBundle.message("rename.wrong.reference.family");
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!myRefExpr.isValid() || !BaseIntentionAction.canModify(myRefExpr)) return false;
    PsiElement refName = myRefExpr.getReferenceNameElement();
    if (refName == null) return false;

    return !CreateFromUsageUtils.isValidReference(myRefExpr, myUnresolvedOnly);
  }

  private LookupElement @NotNull [] collectItems() {
    Set<LookupElement> items = new LinkedHashSet<>();
    boolean qualified = myRefExpr.getQualifierExpression() != null;

    if (!qualified && !(myRefExpr.getParent() instanceof PsiMethodCallExpression)) {
      PsiVariable[] vars = CreateFromUsageUtils.guessMatchingVariables(myRefExpr);
      for (PsiVariable var : vars) {
        items.add(createLookupElement(var, v-> v.getName()));
      }
    } else {
      class MyScopeProcessor implements PsiScopeProcessor {
        final ArrayList<PsiElement> myResult = new ArrayList<>();
        final boolean myFilterMethods;
        boolean myFilterStatics;

        MyScopeProcessor(PsiReferenceExpression refExpression) {
          myFilterMethods = refExpression.getParent() instanceof PsiMethodCallExpression;
          PsiExpression qualifier = refExpression.getQualifierExpression();
          if (qualifier instanceof PsiReferenceExpression) {
            PsiElement e = ((PsiReferenceExpression) qualifier).resolve();
            myFilterStatics = e instanceof PsiClass;
          } else if (qualifier == null) {
            PsiModifierListOwner scope = PsiTreeUtil.getParentOfType(refExpression, PsiModifierListOwner.class);
            myFilterStatics = scope != null && scope.hasModifierProperty(PsiModifier.STATIC);
          }
        }

        @Override
        public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
          if (element instanceof PsiNamedElement
              && element instanceof PsiModifierListOwner
              && myFilterMethods == element instanceof PsiMethod) {
            if (((PsiModifierListOwner)element).hasModifierProperty(PsiModifier.STATIC) == myFilterStatics) {
              myResult.add(element);
            }
          }
          return true;
        }

        public PsiElement[] getVariants () {
          return PsiUtilCore.toPsiElementArray(myResult);
        }
      }

      if (!ApplicationManager.getApplication().isUnitTestMode()) items.add(createLookupElement(myRefExpr, r -> r.getReferenceName()));
      MyScopeProcessor processor = new MyScopeProcessor(myRefExpr);
      myRefExpr.processVariants(processor);
      PsiElement[] variants = processor.getVariants();
      for (PsiElement variant : variants) {
        items.add(createLookupElement((PsiNamedElement)variant, v -> v.getName()));
      }
    }

    return items.toArray(LookupElement.EMPTY_ARRAY);
  }

  @NotNull
  private static <T extends PsiElement> LookupElementBuilder createLookupElement(T variant, Function<? super T, String> toPresentableElement) {
    return LookupElementBuilder.create(variant, toPresentableElement.apply(variant));
  }

  @Override
  public void invoke(@NotNull Project project, final Editor editor, PsiFile file) {
    PsiReferenceExpression[] refs = CreateFromUsageUtils.collectExpressions(myRefExpr, PsiMember.class, PsiFile.class);
    PsiElement element = PsiTreeUtil.getParentOfType(myRefExpr, PsiMember.class, PsiFile.class);
    if (element == null) return;
    LookupElement[] items = collectItems();
    ReferenceNameExpression refExpr = new ReferenceNameExpression(items, myRefExpr.getReferenceName());

    TemplateBuilderImpl builder = new TemplateBuilderImpl(element);
    for (PsiReferenceExpression expr : refs) {
      if (!expr.equals(myRefExpr)) {
        builder.replaceElement(expr.getReferenceNameElement(), OTHER_VARIABLE_NAME, INPUT_VARIABLE_NAME, false);
      }
      else {
        builder.replaceElement(expr.getReferenceNameElement(), INPUT_VARIABLE_NAME, refExpr, true);
      }
    }

    final float proportion = EditorUtil.calcVerticalScrollProportion(editor);
    editor.getCaretModel().moveToOffset(element.getTextRange().getStartOffset());

    Template template = builder.buildInlineTemplate();
    editor.getCaretModel().moveToOffset(element.getTextRange().getStartOffset());

    TemplateManager.getInstance(project).startTemplate(editor, template);

    if (file.isPhysical()) {
      EditorUtil.setVerticalScrollProportion(editor, proportion);
    }
  }

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


text:
/**
 * Created by visitante on 19/06/2017.
 */
declare var module;
declare var sails;
declare var Usuario;
  //En typescript podemos usar arrow fuction

// /Saludo/crearUsuarioQuemado
module.exports = {
  welcome:(req,res)=>{
    //POST
    //.error
    //.silly
    sails.log.info(req.method);
    if(req.method=="POST"){
      return res.json({saludo:"hola"})
    }else{
      return res.send("Error en metodo")
    }
     //Metodo : GET POST PUT DELETE
    //Si no ponen el metodo devolver
    //Metodo:perteneces al req.method;
    // return res.send("Error en metodo")
  },

  //otra ruta que hace lo mismo pero resumen res y req y evia texto plano
  bienvenido:(req,res)=>{
    //PUT
    sails.log.info(req.method);
    if(req.method=="PUT"){
      return res.json("hola")
    }else{
      return res.send("Error en metodo (ruta bienvenida)")
    }
  },

  crearUsuarioQuemado:(req,res)=>{
    let nuevoUsuario = {
      nombres:'Jonathan',
      apellidos:'Pachacama',
      password:'12345',
      correo:'jonathan.pachacama@epn.edu.ec',
      fechaNacimiento:new Date()
    };

    //nombreModelo.metodo(parametros).exec((err,registro)=>{})
    Usuario.create(nuevoUsuario)
      .exec(
        (error,usuarioCreado)=>{
          if(error){
            return res.serverError(error)
          }else{
            return res.ok(usuarioCreado);
          }
        }
      )

  },

  crearUsuarioQP:(req,res)=>{

    //localhost:1337/Saludo/crearUsuarioQP ==> PATH absoluto
    //  /Saludo/crearUsuarioQP    ==> PATH relativo
    let parametros = req.allParams();
    sails.log.info("Parametros",parametros);
    //  Ejemplo para crear por parametros query
    // http://localhost:1337/Saludo/crearUsuarioQuemado?nombres=Vicente&fechaNacimiento=2016-01-02
    let nuevoUsuario = {
      nombres:parametros.nombres,
      apellidos:parametros.apellidos,
      password:parametros.password,
      correo:parametros.correo,
      fechaNacimiento:parametros.fechaNacimiento
    };
    // 1 - Query Parameters ?nombre=Adrian&apellidos=Eguez

    // 2 - Forms Parameters

    //nombreModelo.metodo(parametros).exec((err,registro)=>{})

    Usuario.create(nuevoUsuario)
      .exec(
        (error,usuarioCreado)=>{
          if(error){
            return res.serverError(error)
          }else{
            // return res.ok(usuarioCreado);
            /*

                             Usuario.find().exec((err,usuarios)=>{
                               if(err) return res.negotiate(err);
                               sails.log.info("Usuarios",usuarios);

                               return res.view('homepage',{
                                 usuarios:usuarios
                               })
                             })
                            */
            return res.redirect("/");
          }
        }
      )

  },
  contar:(req,res)=>{
    Usuario.count({nombres:'Jonathan'}).exec(function countCB(error, found) {
      console.log('Hay' + found + ' Usuario llamado jonathan');

      return res.send("contado exitoso")
    });
  },
  eliminarUsuario:(req,res)=>{
    let parametros = req.allParams();
    Usuario.destroy({id:parametros.id}).exec(function (err){
      if (err) {
        return res.negotiate(err);
      }
      sails.log('Usuario eliminado');
      console.log(parametros);
      return res.redirect("/");
    });
  },
  actualizar:(req,res)=>{

    Usuario.update({nombres:'Jonathan'},{nombres:'Paul'}).exec(function afterwards(err, updated){

      if (err) {

        sails.log('No actualizado');
        return res.negotiate(err);
      }else {
        console.log('Actualizado el nombre de jonathan a paul');
        return res.send('actualizado')
      }

    });

  },
  encontrar:(req,res)=>{
    let parametros = req.allParams();
    Usuario.find({nombres:parametros.nombres}).exec(function (err, UsuarioEncontrado){
      if (err) {
        return res.serverError(err);
      }
      sails.log('Hay %d usuarios de nombre Jonathan.', UsuarioEncontrado.length, UsuarioEncontrado);
      return res.json(UsuarioEncontrado);
    });

  },
  encontrarUno:(req,res)=>{
    let parametros = req.allParams();
    Usuario.findOne({
      nombres:parametros.nombres
    }).exec(function (err, encontrarJonathan){
      if (err) {
        return res.serverError(err);
      }
      if (!encontrarJonathan) {
        return res.notFound('No se pudo encontrar Jonathan, Lo siento.');
      }

      sails.log('Usuario Encontrado');
      return res.json(encontrarJonathan);
    });
  },

};


text:
module Spree
  class SaleImage < Asset
    validates_attachment_presence :attachment
    validate :no_attachment_errors

    # attr_accessible :alt, :attachment, :position, :viewable_type, :viewable_id

    has_attached_file :attachment,
                      :styles => { :mini => '48x48>', :small => '100x100>', :sale => '240x240>', :large => '600x600>' },
                      :default_style => :sale,
                      :url => '/spree/sales/:id/:style/:basename.:extension',
                      :path => ':rails_root/public/spree/sales/:id/:style/:basename.:extension',
                      :convert_options => { :all => '-strip' }
    # save the w,h of the original image (from which others can be calculated)
    # we need to look at the write-queue for images which have not been saved yet
    after_post_process :find_dimensions

    include Spree::Core::S3Support
    supports_s3 :attachment

    #used by admin sales autocomplete
    def mini_url
      attachment.url(:mini, false)
    end

    def find_dimensions
      temporary = attachment.queued_for_write[:original]
      filename = temporary.path unless temporary.nil?
      filename = attachment.path if filename.blank?
      geometry = Paperclip::Geometry.from_file(filename)
      self.attachment_width  = geometry.width
      self.attachment_height = geometry.height
    end

    # if there are errors from the plugin, then add a more meaningful message
    def no_attachment_errors
      unless attachment.errors.empty?
        # uncomment this to get rid of the less-than-useful interrim messages
        # errors.clear
        errors.add :attachment, "Paperclip returned errors for file '#{attachment_file_name}' - check ImageMagick installation or image source file."
        false
      end
    end

    def viewable_type=(event_type)
      super event_type.to_s.classify.constantize.base_class.to_s
    end
  end
end


text:
  Condat-sur-Ganaveix est
       un village
       situé dans le département de Corrèze en Limousin. Elle totalisait 658 habitants en 2008.

À proximité de Condat-sur-Ganaveix sont localisées les communes de
Peyrissac localisée à 9 km, 137 habitants,
Saint-Jal localisée à 8 km, 625 habitants,
Saint-Ybard située à 6 km, 643 habitants,
Lamongerie localisée à 7 km, 104 habitants,
Masseret à 9 km, 659 habitants,
Espartignac à 5 km, 372 habitants,
 entre autres. De plus, Condat-sur-Ganaveix est située à seulement 26 km de Tulle.

À Condat-sur-Ganaveix, la valeur moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 400 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.

Si vous pensez demenager à Condat-sur-Ganaveix, vous pourrez facilement trouver une maison à acheter.

La commune offre quelques  aménagements, elle dispose, entre autres, de un terrain de tennis.

Le nombre de logements, à Condat-sur-Ganaveix, se décomposait en 2011 en sept appartements et 401 maisons soit
 un marché relativement équilibré.


text:
package uk.hfox.morphix.utils.search;

/**
 * Represents a search criteria used by {@link Search}
 */
public interface SearchCriteria {

    /**
     * Returns if this search criteria is satisfied with the supplied class
     *
     * @param cls The class to check
     *
     * @return True if the criteria is satisfied, otherwise false
     */
    boolean isSatisfied(Class<?> cls);

}