text:
//=================================================================
// Author  : S.R.Manikandasriram
// Guide   : Bharath Bhikkaji
// Company : Control Engineering Lab, IIT Madras
// Program : Code written in RobotC for use in LEGO Mindstorms NXT 2.0 kit.
// This program is used to employ a custom PID controller for the
// interactive Servo motor. Data is stored using the Datalog feature
// available in NXT.
//
// Objective of this laboratory experiment is to fulfill the system design
// criteria given by maximum percentage overshoot and maximum settling time
// constraints for output.

// Declare useful constants
#define RUN_TIME 10000                            // in milliseconds
#define RECORD_SIZE 4
#define ENCODER_SETPOINT 500                      // Setpoint in degrees

task main()
{
  nMotorEncoder[motorB] = 0;                      // Reset the Motor Encoder of Motor B
  /* Note: nMotorEncoder has a range of -32768 to 32767. So it will "wrap" after about ~90
  revolutions. Hence, nMotorEncoder must be reset often enough to avoid any unexpected
  results */

  nMotorPIDSpeedCtrl[motorB] = mtrNoReg;          // disable PID speed control
  nSyncedMotors = synchNone;                      // ensure no syncronization between motors (i.e.) motorB is independent

  float Kp = 0.454*10.5, Ki = 2.2*0.2, Kd = 0.159*0.2;                  // PID variables. For Lego DC Motor: Ku = 11, Tu = 0.2
  /* Note: PID Tuning methods
  1. Ziegler-Nichols (Z-N) method:
      a. Set Ki and Kd to zero.
      b. Slowly increase Kp to a value Ku at which sustained oscillations - constant amplitude and periodic - are observed.
      c. Note period of oscillation
      d. Refer table below for initial values
      +----------------+----------+----------+----------+
      | Z-N Model      | Kp       | Ki       | Kd       |
      +----------------+----------+----------+----------+
      | P controller   | 0.5*Ku   | 0        | 0        |
      +----------------+----------+----------+----------+
      | PI controller  | 0.455*Ku | 0.833*Tu | 0        |
      +----------------+----------+----------+----------+
      | PID controller | 0.588*Ku | 0.5*Tu   | 0.125*Tu |
      +----------------+----------+----------+----------+
  2. Tyreus-Luyben (T-L) method:
      Since Z-N method usually results in aggressive tuning, alternatively T-L method can be adopted (Refer table below).
      +----------------+----------+--------+----------+
      | T-L Model      | Kp       | Ki     | Kd       |
      +----------------+----------+--------+----------+
      | PI controller  | 0.312*Ku | 2.2*Tu | 0        |
      +----------------+----------+--------+----------+
      | PID controller | 0.454*Ku | 2.2*Tu | 0.159*Tu |
      +----------------+----------+--------+----------+
  */
  float new_err = 0, old_err = 0, sum_err = 0;    // Error variables
  int dt = 20;                                    // in ms
  int motorPIDpower, motorPIDdegrees;

  motor[motorB] = 50;                             // Motor B given a power level of 50/100
  time1[T1] = 0;                                  // arrays to hold the current value of the time in 1ms duration

  nDatalogSize = RECORD_SIZE*RUN_TIME/dt;         // Allocate memory for datalog

  while (time1[T1] < RUN_TIME) {                  // Run for RUN_TIME sec
    motorPIDdegrees = nMotorEncoder[motorB];      // degrees rotated by motor
    new_err = ENCODER_SETPOINT-motorPIDdegrees;   // Calculate current error
    sum_err += new_err*dt/1000;                        // Integral of error ( calculated as a discrete sum of errors)

    // Calculate power to be applied to the motor
    motorPIDpower = Kp*new_err + Ki*sum_err + Kd*(new_err-old_err)*1000/dt;
    old_err = new_err;

    // Ensure power level is between -100 and 100
    if(motorPIDpower >= 100)
      motorPIDpower = 100;
    else if(motorPIDpower <= -100)
      motorPIDpower = -100;

    motor[motorB] = motorPIDpower;                // Apply the calculated power to the motors
    AddToDatalog(1,motorPIDdegrees);              // store value
    wait1Msec(dt);                                // log data every dt ms
  }
  motor[motorB] = 0;                              // Stop the motors
  SaveNxtDatalog();                               // save log file from RAM to Flash memory
}

redpajama_set_name: RedPajamaGithub


text:
var specify  = require('specify')
  , async    = require('async')
  , helpers  = require('../helpers')
  , timeout  = helpers.timeout
  , nano     = helpers.nano
  , nock     = helpers.nock
  ;

var mock = nock(helpers.couch, "db/changes")
  , db   = nano.use("db_changes")
  ;

specify("db_changes:setup", timeout, function (assert) {
  nano.db.create("db_changes", function (err) {
    assert.equal(err, undefined, "Failed to create database");
    async.parallel(
      [ function(cb) { db.insert({"foo": "bar"}, "foobar", cb); }
      , function(cb) { db.insert({"bar": "foo"}, "barfoo", cb); }
      , function(cb) { db.insert({"foo": "baz"}, "foobaz", cb); }
      ]
    , function(error, results){
      assert.equal(error, undefined, "Should have stored docs");
    });
  });
});

specify("db_changes:test", timeout, function (assert) {
  db.changes({since:2}, function (error, response) {
    assert.equal(error, undefined, "Changes should respond");
    assert.equal(response.results.length, 1, 'Gets one result');
    assert.equal(response.last_seq, 3, 'seq is 3');
  });
});

specify("db_changes:teardown", timeout, function (assert) {
  nano.db.destroy("db_changes", function (err) {
    assert.equal(err, undefined, "Failed to destroy database");
    assert.ok(mock.isDone(), "Some mocks didn't run");
  });
});

specify.run(process.argv.slice(2));


text:
namespace ios {
namespace provider {

// Creates a new instance of MailtoHandlerService.
std::unique_ptr<MailtoHandlerService> CreateMailtoHandlerService(
    MailtoHandlerConfiguration* configuration);

}  // namespace provider
}  // namespace ios

#endif  // IOS_PUBLIC_PROVIDER_CHROME_BROWSER_MAILTO_HANDLER_MAILTO_HANDLER_API_H_


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Spicaria javanica Bally, 1923

### Remarks
null


text:
package org.apache.felix.sigil.eclipse.ui.internal.quickfix;

import org.apache.felix.sigil.common.model.ModelElementFactory;
import org.apache.felix.sigil.common.model.osgi.IPackageExport;
import org.apache.felix.sigil.common.model.osgi.IPackageImport;
import org.apache.felix.sigil.common.osgi.VersionRange;
import org.apache.felix.sigil.eclipse.SigilCore;
import org.apache.felix.sigil.eclipse.model.project.ISigilProjectModel;
import org.apache.felix.sigil.eclipse.model.util.ModelHelper;
import org.apache.felix.sigil.eclipse.ui.SigilUI;
import org.apache.felix.sigil.search.ISearchResult;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.ui.CodeStyleConfiguration;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

public class ImportSearchResultProposal implements IJavaCompletionProposal
{

    private ISigilProjectModel project;
    private ICompilationUnit fCompilationUnit;
    private final ISearchResult result;
    private final Shell shell;

    public ImportSearchResultProposal(Shell shell, ISearchResult result, Name node, ISigilProjectModel project)
    {
        this.shell = shell;
        this.result = result;
        this.project = project;
        if (node != null)
        {
            CompilationUnit cu = (CompilationUnit) ASTNodes.getParent(node,
                ASTNode.COMPILATION_UNIT);
            this.fCompilationUnit = (ICompilationUnit) cu.getJavaElement();
        }
    }

    public int getRelevance()
    {
        return 100;
    }

    public void apply(IDocument document)
    {
        IPackageExport e = result.getExport();
        if (result.getExport() == null)
        {
            if (MessageDialog.openQuestion(shell, "Modify "
                + result.getProvider().getBundleInfo().getSymbolicName(),
                result.getPackageName()
                    + " is not exported. Do you want to export it now?"))
            {
                final IPackageExport pe = ModelElementFactory.getInstance().newModelElement(
                    IPackageExport.class);
                pe.setPackageName(result.getPackageName());
                //e.setVersion(version)
                final ISigilProjectModel mod = result.getProvider().getAncestor(
                    ISigilProjectModel.class);
                if (mod == null)
                {
                    throw new IllegalStateException(
                        "Attempt to modify binary package export");
                }
                WorkspaceModifyOperation op = new WorkspaceModifyOperation()
                {
                    @Override
                    protected void execute(IProgressMonitor monitor) throws CoreException
                    {
                        mod.getBundle().getBundleInfo().addExport(pe);
                        mod.save(monitor);
                    }
                };

                SigilUI.runWorkspaceOperation(op, null);
                e = pe;
            }
        }

        final IPackageImport i = ModelElementFactory.getInstance().newModelElement(
            IPackageImport.class);
        i.setPackageName(e.getPackageName());
        VersionRange selectedVersions = ModelHelper.getDefaultRange(e.getVersion());
        i.setVersions(selectedVersions);

        WorkspaceModifyOperation op = new WorkspaceModifyOperation()
        {
            @Override
            protected void execute(IProgressMonitor monitor) throws CoreException
            {
                project.getBundle().getBundleInfo().addImport(i);
                project.save(null);
            }
        };

        SigilUI.runWorkspaceOperation(op, null);
        addSourceImport();
    }

    private void addSourceImport()
    {
        // add import
        try
        {
            ImportRewrite rewrite = CodeStyleConfiguration.createImportRewrite(
                fCompilationUnit, true);
            rewrite.addImport(result.getClassName());
            JavaModelUtil.applyEdit(fCompilationUnit, rewrite.rewriteImports(null),
                false, null);
        }
        catch (CoreException e)
        {
            SigilCore.error("Failed to add import", e);
        }
    }

    public String getAdditionalProposalInfo()
    {
        return null;
    }

    public IContextInformation getContextInformation()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public String getDisplayString()
    {
        String type = result.getClassName();
        String loc = result.getExport() == null ? " from "
            + result.getProvider().getBundleInfo().getSymbolicName() : " version "
            + result.getExport().getVersion();
        return "Import " + type + loc;
    }

    public Image getImage()
    {
        // TODO Auto-generated method stub
        return null;
    }

    public Point getSelection(IDocument document)
    {
        return null;
    }
}


text:
#import <UIKit/UIKit.h>

@class ZXRSSExpandedDecodedInformation;

@interface ZXRSSExpandedBlockParsedResult : NSObject

@property (nonatomic, strong, readonly) ZXRSSExpandedDecodedInformation *decodedInformation;
@property (nonatomic, assign, readonly) BOOL finished;

- (id)initWithFinished:(BOOL)finished;
- (id)initWithInformation:(ZXRSSExpandedDecodedInformation *)information finished:(BOOL)finished;

@end


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Core.Contents;
using Xunit;

namespace Squidex.Domain.Apps.Core.Model.Contents
{
    public class StatusFlowTests
    {
        [Fact]
        public void Should_make_tests()
        {
            Assert.True(StatusFlow.Exists(Status.Draft));
            Assert.True(StatusFlow.Exists(Status.Archived));
            Assert.True(StatusFlow.Exists(Status.Published));

            Assert.True(StatusFlow.CanChange(Status.Draft, Status.Archived));
            Assert.True(StatusFlow.CanChange(Status.Draft, Status.Published));

            Assert.True(StatusFlow.CanChange(Status.Published, Status.Draft));
            Assert.True(StatusFlow.CanChange(Status.Published, Status.Archived));

            Assert.True(StatusFlow.CanChange(Status.Archived, Status.Draft));

            Assert.False(StatusFlow.Exists((Status)int.MaxValue));
            Assert.False(StatusFlow.CanChange(Status.Archived, Status.Published));
        }
    }
}


text:
package org.pitest.mutationtest.mocksupport;

import static org.junit.Assert.assertEquals;
import static org.pitest.mutationtest.LocationMother.aLocation;
import static org.pitest.mutationtest.LocationMother.aMutationId;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Before;
import org.junit.Test;
import org.pitest.mutationtest.engine.Mutant;
import org.pitest.mutationtest.engine.MutationDetails;
import org.pitest.util.StreamUtil;

public class JavassistInterceptorTest {

  public class AClassWithAOpenClassFileMethod {
    public InputStream openClassfile(final String name) {
      return new ByteArrayInputStream("original".getBytes());
    }
  }

  private AClassWithAOpenClassFileMethod interceptedClass;
  private Mutant                         mutant;

  @Before
  public void setUp() {
    this.interceptedClass = new AClassWithAOpenClassFileMethod();
    final byte[] bytes = "replaced".getBytes();
    this.mutant = new Mutant(new MutationDetails(aMutationId().withLocation(aLocation().withClass("match")), "foo", "foo", 0, 0), bytes);
  }

  @Test
  public void shouldNotReplaceRequestedClassWithMutantWhenClassNameIsDifferent()
      throws IOException {
    JavassistInterceptor.setMutant(this.mutant);
    final InputStream actual = JavassistInterceptor.openClassfile(
        this.interceptedClass, "nomatch");
    assertEquals(streamToString(actual),
        streamToString(this.interceptedClass.openClassfile("")));
  }

  @Test
  public void shouldNotReplaceRequestedClassWithMutantWhenNoMutantIsSet()
      throws IOException {
    JavassistInterceptor.setMutant(null);
    final InputStream actual = JavassistInterceptor.openClassfile(
        this.interceptedClass, "nomatch");
    assertEquals(streamToString(actual),
        streamToString(this.interceptedClass.openClassfile("")));
  }

  @Test
  public void shouldReplaceRequestedClassWithMutantWhenClassNameMatches()
      throws IOException {
    JavassistInterceptor.setMutant(this.mutant);
    final InputStream actual = JavassistInterceptor.openClassfile(
        this.interceptedClass, "match");

    assertEquals(streamToString(actual), "replaced");
  }

  private String streamToString(final InputStream is) throws IOException {
    return new String(StreamUtil.streamToByteArray(is));
  }

}


text:
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>{{TITLE}}</title>

    <!-- Bootstrap Core CSS -->
    <link href="/{{_ROOT}}/resource/theme/{{_THEME}}/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="/{{_ROOT}}/resource/theme/{{_THEME}}/css/sb-admin.css" rel="stylesheet">

    <!-- Bootstrap RTL-->
    {{RTL}}

    <!-- Morris Charts CSS -->
    <link href="/{{_ROOT}}/resource/theme/{{_THEME}}/css/plugins/morris.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="/{{_ROOT}}/resource/theme/{{_THEME}}/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

	<!-- jQuery -->
    <script src="/{{_ROOT}}/resource/theme/{{_THEME}}/js/jquery.js"></script>

</head>

<body>

    <div id="wrapper">


text:
'use strict';

const EventEmitter = require('events');
const assert = require('assert');
const dgram = require('dgram');
const fork = require('child_process').fork;
const net = require('net');
const util = require('util');
const SCHED_NONE = 1;
const SCHED_RR = 2;

const uv = process.binding('uv');

const cluster = new EventEmitter();
module.exports = cluster;
cluster.Worker = Worker;
cluster.isWorker = ('NODE_UNIQUE_ID' in process.env);
cluster.isMaster = (cluster.isWorker === false);

function Worker(options) {
  if (!(this instanceof Worker))
    return new Worker(options);

  EventEmitter.call(this);

  if (options === null || typeof options !== 'object')
    options = {};

  this.suicide = undefined;
  this.state = options.state || 'none';
  this.id = options.id | 0;

  if (options.process) {
    this.process = options.process;
    this.process.on('error', this.emit.bind(this, 'error'));
    this.process.on('message', this.emit.bind(this, 'message'));
  }
}
util.inherits(Worker, EventEmitter);

Worker.prototype.kill = function() {
  this.destroy.apply(this, arguments);
};

Worker.prototype.send = function() {
  this.process.send.apply(this.process, arguments);
};

Worker.prototype.isDead = function isDead() {
  return this.process.exitCode != null || this.process.signalCode != null;
};

Worker.prototype.isConnected = function isConnected() {
  return this.process.connected;
};

// Master/worker specific methods are defined in the *Init() functions.

function SharedHandle(key, address, port, addressType, backlog, fd, flags) {
  this.key = key;
  this.workers = [];
  this.handle = null;
  this.errno = 0;

  // FIXME(bnoordhuis) Polymorphic return type for lack of a better solution.
  var rval;
  if (addressType === 'udp4' || addressType === 'udp6')
    rval = dgram._createSocketHandle(address, port, addressType, fd, flags);
  else
    rval = net._createServerHandle(address, port, addressType, fd);

  if (typeof rval === 'number')
    this.errno = rval;
  else
    this.handle = rval;
}

SharedHandle.prototype.add = function(worker, send) {
  assert(this.workers.indexOf(worker) === -1);
  this.workers.push(worker);
  send(this.errno, null, this.handle);
};

SharedHandle.prototype.remove = function(worker) {
  var index = this.workers.indexOf(worker);
  if (index === -1) return false; // The worker wasn't sharing this handle.
  this.workers.splice(index, 1);
  if (this.workers.length !== 0) return false;
  this.handle.close();
  this.handle = null;
  return true;
};

// Start a round-robin server. Master accepts connections and distributes
// them over the workers.
function RoundRobinHandle(key, address, port, addressType, backlog, fd) {
  this.key = key;
  this.all = {};
  this.free = [];
  this.handles = [];
  this.handle = null;
  this.server = net.createServer(assert.fail);

  if (fd >= 0)
    this.server.listen({ fd: fd });
  else if (port >= 0)
    this.server.listen(port, address);
  else
    this.server.listen(address);  // UNIX socket path.

  var self = this;
  this.server.once('listening', function() {
    self.handle = self.server._handle;
    self.handle.onconnection = self.distribute.bind(self);
    self.server._handle = null;
    self.server = null;
  });
}

RoundRobinHandle.prototype.add = function(worker, send) {
  assert(worker.id in this.all === false);
  this.all[worker.id] = worker;

  var self = this;
  function done() {
    if (self.handle.getsockname) {
      var out = {};
      self.handle.getsockname(out);
      // TODO(bnoordhuis) Check err.
      send(null, { sockname: out }, null);
    } else {
      send(null, null, null);  // UNIX socket.
    }
    self.handoff(worker);  // In case there are connections pending.
  }

  if (this.server === null) return done();
  // Still busy binding.
  this.server.once('listening', done);
  this.server.once('error', function(err) {
    // Hack: translate 'EADDRINUSE' error string back to numeric error code.
    // It works but ideally we'd have some backchannel between the net and
    // cluster modules for stuff like this.
    var errno = uv['UV_' + err.errno];
    send(errno, null);
  });
};

RoundRobinHandle.prototype.remove = function(worker) {
  if (worker.id in this.all === false) return false;
  delete this.all[worker.id];
  var index = this.free.indexOf(worker);
  if (index !== -1) this.free.splice(index, 1);
  if (Object.getOwnPropertyNames(this.all).length !== 0) return false;
  for (var handle; handle = this.handles.shift(); handle.close());
  this.handle.close();
  this.handle = null;
  return true;
};

RoundRobinHandle.prototype.distribute = function(err, handle) {
  this.handles.push(handle);
  var worker = this.free.shift();
  if (worker) this.handoff(worker);
};

RoundRobinHandle.prototype.handoff = function(worker) {
  if (worker.id in this.all === false) {
    return;  // Worker is closing (or has closed) the server.
  }
  var handle = this.handles.shift();
  if (handle === undefined) {
    this.free.push(worker);  // Add to ready queue again.
    return;
  }
  var message = { act: 'newconn', key: this.key };
  var self = this;
  sendHelper(worker.process, message, handle, function(reply) {
    if (reply.accepted)
      handle.close();
    else
      self.distribute(0, handle);  // Worker is shutting down. Send to another.
    self.handoff(worker);
  });
};

if (cluster.isMaster)
  masterInit();
else
  workerInit();

function masterInit() {
  cluster.workers = {};

  var intercom = new EventEmitter();
  cluster.settings = {};

  // XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings?
  var schedulingPolicy = {
    'none': SCHED_NONE,
    'rr': SCHED_RR
  }[process.env.NODE_CLUSTER_SCHED_POLICY];

  if (schedulingPolicy === undefined) {
    // FIXME Round-robin doesn't perform well on Windows right now due to the
    // way IOCP is wired up. Bert is going to fix that, eventually.
    schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR;
  }

  cluster.schedulingPolicy = schedulingPolicy;
  cluster.SCHED_NONE = SCHED_NONE;  // Leave it to the operating system.
  cluster.SCHED_RR = SCHED_RR;      // Master distributes connections.

  // Keyed on address:port:etc. When a worker dies, we walk over the handles
  // and remove() the worker from each one. remove() may do a linear scan
  // itself so we might end up with an O(n*m) operation. Ergo, FIXME.
  const handles = require('internal/cluster').handles;

  var initialized = false;
  cluster.setupMaster = function(options) {
    var settings = {
      args: process.argv.slice(2),
      exec: process.argv[1],
      execArgv: process.execArgv,
      silent: false
    };
    settings = util._extend(settings, cluster.settings);
    settings = util._extend(settings, options || {});
    // Tell V8 to write profile data for each process to a separate file.
    // Without --logfile=v8-%p.log, everything ends up in a single, unusable
    // file. (Unusable because what V8 logs are memory addresses and each
    // process has its own memory mappings.)
    if (settings.execArgv.some(function(s) { return /^--prof/.test(s); }) &&
        !settings.execArgv.some(function(s) { return /^--logfile=/.test(s); }))
    {
      settings.execArgv = settings.execArgv.concat(['--logfile=v8-%p.log']);
    }
    cluster.settings = settings;
    if (initialized === true)
      return process.nextTick(setupSettingsNT, settings);
    initialized = true;
    schedulingPolicy = cluster.schedulingPolicy;  // Freeze policy.
    assert(schedulingPolicy === SCHED_NONE || schedulingPolicy === SCHED_RR,
           'Bad cluster.schedulingPolicy: ' + schedulingPolicy);

    var hasDebugArg = process.execArgv.some(function(argv) {
      return /^(--debug|--debug-brk)(=\d+)?$/.test(argv);
    });

    process.nextTick(setupSettingsNT, settings);

    // Send debug signal only if not started in debug mode, this helps a lot
    // on windows, because RegisterDebugHandler is not called when node starts
    // with --debug.* arg.
    if (hasDebugArg)
      return;

    process.on('internalMessage', function(message) {
      if (message.cmd !== 'NODE_DEBUG_ENABLED') return;
      var key;
      for (key in cluster.workers) {
        var worker = cluster.workers[key];
        if (worker.state === 'online' || worker.state === 'listening') {
          process._debugProcess(worker.process.pid);
        } else {
          worker.once('online', function() {
            process._debugProcess(this.process.pid);
          });
        }
      }
    });
  };

  function setupSettingsNT(settings) {
    cluster.emit('setup', settings);
  }

  var debugPortOffset = 1;

  function createWorkerProcess(id, env) {
    var workerEnv = util._extend({}, process.env);
    var execArgv = cluster.settings.execArgv.slice();

    workerEnv = util._extend(workerEnv, env);
    workerEnv.NODE_UNIQUE_ID = '' + id;

    for (var i = 0; i < execArgv.length; i++) {
      var match = execArgv[i].match(/^(--debug|--debug-(brk|port))(=\d+)?$/);

      if (match) {
        const debugPort = process.debugPort + debugPortOffset;
        ++debugPortOffset;
        execArgv[i] = match[1] + '=' + debugPort;
      }
    }

    return fork(cluster.settings.exec, cluster.settings.args, {
      env: workerEnv,
      silent: cluster.settings.silent,
      execArgv: execArgv,
      gid: cluster.settings.gid,
      uid: cluster.settings.uid
    });
  }

  var ids = 0;

  function removeWorker(worker) {
    assert(worker);

    delete cluster.workers[worker.id];

    if (Object.keys(cluster.workers).length === 0) {
      assert(Object.keys(handles).length === 0, 'Resource leak detected.');
      intercom.emit('disconnect');
    }
  }

  function removeHandlesForWorker(worker) {
    assert(worker);

    for (var key in handles) {
      var handle = handles[key];
      if (handle.remove(worker)) delete handles[key];
    }
  }

  cluster.fork = function(env) {
    cluster.setupMaster();
    const id = ++ids;
    const workerProcess = createWorkerProcess(id, env);
    const worker = new Worker({
      id: id,
      process: workerProcess
    });

    worker.on('message', this.emit.bind(this, 'message'));

    worker.process.once('exit', function(exitCode, signalCode) {
      /*
       * Remove the worker from the workers list only
       * if it has disconnected, otherwise we might
       * still want to access it.
       */
      if (!worker.isConnected()) {
        removeHandlesForWorker(worker);
        removeWorker(worker);
      }

      worker.suicide = !!worker.suicide;
      worker.state = 'dead';
      worker.emit('exit', exitCode, signalCode);
      cluster.emit('exit', worker, exitCode, signalCode);
    });

    worker.process.once('disconnect', function() {
      /*
       * Now is a good time to remove the handles
       * associated with this worker because it is
       * not connected to the master anymore.
       */
      removeHandlesForWorker(worker);

      /*
       * Remove the worker from the workers list only
       * if its process has exited. Otherwise, we might
       * still want to access it.
       */
      if (worker.isDead()) removeWorker(worker);

      worker.suicide = !!worker.suicide;
      worker.state = 'disconnected';
      worker.emit('disconnect');
      cluster.emit('disconnect', worker);
    });

    worker.process.on('internalMessage', internal(worker, onmessage));
    process.nextTick(emitForkNT, worker);
    cluster.workers[worker.id] = worker;
    return worker;
  };

  function emitForkNT(worker) {
    cluster.emit('fork', worker);
  }

  cluster.disconnect = function(cb) {
    var workers = Object.keys(cluster.workers);
    if (workers.length === 0) {
      process.nextTick(intercom.emit.bind(intercom, 'disconnect'));
    } else {
      for (var key in workers) {
        key = workers[key];
        if (cluster.workers[key].isConnected())
          cluster.workers[key].disconnect();
      }
    }
    if (cb) intercom.once('disconnect', cb);
  };

  Worker.prototype.disconnect = function() {
    this.suicide = true;
    send(this, { act: 'disconnect' });
    removeHandlesForWorker(this);
    removeWorker(this);
  };

  Worker.prototype.destroy = function(signo) {
    signo = signo || 'SIGTERM';
    var proc = this.process;
    if (this.isConnected()) {
      this.once('disconnect', proc.kill.bind(proc, signo));
      this.disconnect();
      return;
    }
    proc.kill(signo);
  };

  function onmessage(message, handle) {
    var worker = this;
    if (message.act === 'online')
      online(worker);
    else if (message.act === 'queryServer')
      queryServer(worker, message);
    else if (message.act === 'listening')
      listening(worker, message);
    else if (message.act === 'suicide')
      worker.suicide = true;
    else if (message.act === 'close')
      close(worker, message);
  }

  function online(worker) {
    worker.state = 'online';
    worker.emit('online');
    cluster.emit('online', worker);
  }

  function queryServer(worker, message) {
    var args = [message.address,
                message.port,
                message.addressType,
                message.fd,
                message.index];
    var key = args.join(':');
    var handle = handles[key];
    if (handle === undefined) {
      var constructor = RoundRobinHandle;
      // UDP is exempt from round-robin connection balancing for what should
      // be obvious reasons: it's connectionless. There is nothing to send to
      // the workers except raw datagrams and that's pointless.
      if (schedulingPolicy !== SCHED_RR ||
          message.addressType === 'udp4' ||
          message.addressType === 'udp6') {
        constructor = SharedHandle;
      }
      handles[key] = handle = new constructor(key,
                                              message.address,
                                              message.port,
                                              message.addressType,
                                              message.backlog,
                                              message.fd,
                                              message.flags);
    }
    if (!handle.data) handle.data = message.data;

    // Set custom server data
    handle.add(worker, function(errno, reply, handle) {
      reply = util._extend({
        errno: errno,
        key: key,
        ack: message.seq,
        data: handles[key].data
      }, reply);
      if (errno) delete handles[key];  // Gives other workers a chance to retry.
      send(worker, reply, handle);
    });
  }

  function listening(worker, message) {
    var info = {
      addressType: message.addressType,
      address: message.address,
      port: message.port,
      fd: message.fd
    };
    worker.state = 'listening';
    worker.emit('listening', info);
    cluster.emit('listening', worker, info);
  }

  // Server in worker is closing, remove from list.  The handle may have been
  // removed by a prior call to removeHandlesForWorker() so guard against that.
  function close(worker, message) {
    var key = message.key;
    var handle = handles[key];
    if (handle && handle.remove(worker)) delete handles[key];
  }

  function send(worker, message, handle, cb) {
    sendHelper(worker.process, message, handle, cb);
  }
}

function workerInit() {
  var handles = {};
  var indexes = {};

  // Called from src/node.js
  cluster._setupWorker = function() {
    var worker = new Worker({
      id: +process.env.NODE_UNIQUE_ID | 0,
      process: process,
      state: 'online'
    });
    cluster.worker = worker;
    process.once('disconnect', function() {
      worker.emit('disconnect');
      if (!worker.suicide) {
        // Unexpected disconnect, master exited, or some such nastiness, so
        // worker exits immediately.
        process.exit(0);
      }
    });
    process.on('internalMessage', internal(worker, onmessage));
    send({ act: 'online' });
    function onmessage(message, handle) {
      if (message.act === 'newconn')
        onconnection(message, handle);
      else if (message.act === 'disconnect')
        worker.disconnect();
    }
  };

  // obj is a net#Server or a dgram#Socket object.
  cluster._getServer = function(obj, options, cb) {
    const key = [ options.address,
                options.port,
                options.addressType,
                options.fd ].join(':');
    if (indexes[key] === undefined)
      indexes[key] = 0;
    else
      indexes[key]++;

    const message = util._extend({
      act: 'queryServer',
      index: indexes[key],
      data: null
    }, options);

    // Set custom data on handle (i.e. tls tickets key)
    if (obj._getServerData) message.data = obj._getServerData();
    send(message, function(reply, handle) {
      if (obj._setServerData) obj._setServerData(reply.data);

      if (handle)
        shared(reply, handle, cb);  // Shared listen socket.
      else
        rr(reply, cb);              // Round-robin.
    });
    obj.once('listening', function() {
      cluster.worker.state = 'listening';
      const address = obj.address();
      message.act = 'listening';
      message.port = address && address.port || options.port;
      send(message);
    });
  };

  // Shared listen socket.
  function shared(message, handle, cb) {
    var key = message.key;
    // Monkey-patch the close() method so we can keep track of when it's
    // closed. Avoids resource leaks when the handle is short-lived.
    var close = handle.close;
    handle.close = function() {
      send({ act: 'close', key: key });
      delete handles[key];
      return close.apply(this, arguments);
    };
    assert(handles[key] === undefined);
    handles[key] = handle;
    cb(message.errno, handle);
  }

  // Round-robin. Master distributes handles across workers.
  function rr(message, cb) {
    if (message.errno)
      return cb(message.errno, null);

    var key = message.key;
    function listen(backlog) {
      // TODO(bnoordhuis) Send a message to the master that tells it to
      // update the backlog size. The actual backlog should probably be
      // the largest requested size by any worker.
      return 0;
    }

    function close() {
      // lib/net.js treats server._handle.close() as effectively synchronous.
      // That means there is a time window between the call to close() and
      // the ack by the master process in which we can still receive handles.
      // onconnection() below handles that by sending those handles back to
      // the master.
      if (key === undefined) return;
      send({ act: 'close', key: key });
      delete handles[key];
      key = undefined;
    }

    function getsockname(out) {
      if (key) util._extend(out, message.sockname);
      return 0;
    }

    // XXX(bnoordhuis) Probably no point in implementing ref() and unref()
    // because the control channel is going to keep the worker alive anyway.
    function ref() {
    }

    function unref() {
    }

    // Faux handle. Mimics a TCPWrap with just enough fidelity to get away
    // with it. Fools net.Server into thinking that it's backed by a real
    // handle.
    var handle = {
      close: close,
      listen: listen,
      ref: ref,
      unref: unref,
    };
    if (message.sockname) {
      handle.getsockname = getsockname;  // TCP handles only.
    }
    assert(handles[key] === undefined);
    handles[key] = handle;
    cb(0, handle);
  }

  // Round-robin connection.
  function onconnection(message, handle) {
    var key = message.key;
    var server = handles[key];
    var accepted = server !== undefined;
    send({ ack: message.seq, accepted: accepted });
    if (accepted) server.onconnection(0, handle);
  }

  Worker.prototype.disconnect = function() {
    this.suicide = true;
    let waitingCount = 1;

    function checkWaitingCount() {
      waitingCount--;
      if (waitingCount === 0) {
        send({ act: 'suicide' });
        process.disconnect();
      }
    }

    for (const key in handles) {
      const handle = handles[key];
      delete handles[key];
      waitingCount++;
      handle.owner.close(checkWaitingCount);
    }

    checkWaitingCount();
  };

  Worker.prototype.destroy = function() {
    this.suicide = true;
    if (!this.isConnected()) process.exit(0);
    var exit = process.exit.bind(null, 0);
    send({ act: 'suicide' }, exit);
    process.once('disconnect', exit);
    process.disconnect();
  };

  function send(message, cb) {
    sendHelper(process, message, null, cb);
  }
}

var seq = 0;
var callbacks = {};
function sendHelper(proc, message, handle, cb) {
  // Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js
  message = util._extend({ cmd: 'NODE_CLUSTER' }, message);
  if (cb) callbacks[seq] = cb;
  message.seq = seq;
  seq += 1;
  proc.send(message, handle);
}

// Returns an internalMessage listener that hands off normal messages
// to the callback but intercepts and redirects ACK messages.
function internal(worker, cb) {
  return function(message, handle) {
    if (message.cmd !== 'NODE_CLUSTER') return;
    var fn = cb;
    if (message.ack !== undefined) {
      fn = callbacks[message.ack];
      delete callbacks[message.ack];
    }
    fn.apply(worker, arguments);
  };
}


text:
#include /* */  "ace/SOCK_Netlink.h"

#ifdef ACE_HAS_NETLINK

#include "ace/Log_Category.h"
#include "ace/ACE.h"
#include "ace/OS_NS_string.h"
#include "ace/OS_NS_unistd.h"
#include "ace/SOCK_Netlink.h"
#include "ace/OS_NS_sys_socket.h"
#if defined (ACE_HAS_ALLOC_HOOKS)
# include "ace/Malloc_Base.h"
#endif /* ACE_HAS_ALLOC_HOOKS */

#if !defined (__ACE_INLINE__)
#include "ace/SOCK_Netlink.inl"
#endif /* __ACE_INLINE__ */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE (ACE_SOCK_Netlink)

int ACE_SOCK_Netlink::open (ACE_Netlink_Addr &local,
                            int protocol_family,
                            int protocol) //! protocol of your choosing
{
  ACE_TRACE ("ACE_SOCK_Netlink::open");

  if ( ACE_SOCK::open (SOCK_RAW,
                       protocol_family, //! RAW or DGRAM valid
                       protocol,0) < 0 ) {
    ACE_TRACE ("ACE_SOCK_Netlink::open failed to open");
    return -1;
  }

  if (ACE_OS::bind(this->get_handle(),
                   (sockaddr*)local.get_addr(),
                   local.get_addr_size())  == -1 ) {
    ACE_TRACE ("ACE_SOCK_Netlink::open failed to bind socket");
    return -1;
  }
  return 0;
}

ACE_SOCK_Netlink::ACE_SOCK_Netlink (ACE_Netlink_Addr &local,
                                    int protocol_family,
                                    int protocol)
{
  ACE_TRACE ("ACE_SOCK_Netlink::ACE_SOCK_Netlink");

  if (this->open (local,
                  protocol_family,
                  protocol)  == -1)
    ACELIB_ERROR ((LM_ERROR,
                ACE_TEXT ("%p\n"),
                ACE_TEXT ("ACE_SOCK_Netlink")));
}

ssize_t
ACE_SOCK_Netlink::send (const iovec iov[],
                        int n,
                        const ACE_Addr &addr,
                        int flags) const
{
  ACE_TRACE ("ACE_SOCK_Netlink::send");
  msghdr send_msg;

  send_msg.msg_iov = (iovec *) iov;
  send_msg.msg_iovlen = n;
  send_msg.msg_name = (char *) addr.get_addr ();
  send_msg.msg_namelen = addr.get_size ();
  send_msg.msg_control = 0;
  send_msg.msg_controllen = 0;
  send_msg.msg_flags = 0;

  return ACE_OS::sendmsg (this->get_handle (),
                          &send_msg,
                          flags);
}

ssize_t
ACE_SOCK_Netlink::recv (iovec iov[],
                        int n,
                        ACE_Addr &addr,
                        int flags) const
{
  ACE_TRACE ("ACE_SOCK_Netlink::recv");
  msghdr recv_msg;

  recv_msg.msg_iov = (iovec *) iov;
  recv_msg.msg_iovlen = n;
  recv_msg.msg_name = (char *) addr.get_addr ();
  recv_msg.msg_namelen = addr.get_size ();
  recv_msg.msg_control = 0;
  recv_msg.msg_controllen = 0;
  recv_msg.msg_flags = 0;

  ssize_t status = ACE_OS::recvmsg (this->get_handle (),
                                    &recv_msg,
                                    flags);

  if (recv_msg.msg_flags & MSG_TRUNC)
    return -1;

  addr.set_size (recv_msg.msg_namelen);
  addr.set_type (((sockaddr_in *) addr.get_addr())->sin_family);

  return status;
}

ACE_END_VERSIONED_NAMESPACE_DECL

#endif /* ACE_HAS_NETLINK */


text:
using std::string;
using std::vector;

class TestSubcommand : public Subcommand
{
public:
  struct Flags : public virtual flags::FlagsBase
  {
    Flags()
    {
      add(&Flags::b, "b", "bool");
      add(&Flags::i, "i", "int");
      add(&Flags::s, "s", "string");
      add(&Flags::s2, "s2", "string with single quote");
      add(&Flags::s3, "s3", "string with double quote");
      add(&Flags::d, "d", "Duration");
      add(&Flags::y, "y", "Bytes");
      add(&Flags::j, "j", "JSON::Object");
    }

    void populate()
    {
      b = true;
      i = 42;
      s = "hello";
      s2 = "we're";
      s3 = "\"geek\"";
      d = Seconds(10);
      y = Bytes(100);

      JSON::Object object;
      object.values["strings"] = "string";
      object.values["integer1"] = 1;
      object.values["integer2"] = -1;
      object.values["double1"] = 1;
      object.values["double2"] = -1;
      object.values["double3"] = -1.42;

      JSON::Object nested;
      nested.values["string"] = "string";
      object.values["nested"] = nested;

      JSON::Array array;
      array.values.push_back(nested);
      object.values["array"] = array;

      j = object;
    }

    Option<bool> b;
    Option<int> i;
    Option<string> s;
    Option<string> s2;
    Option<string> s3;
    Option<Duration> d;
    Option<Bytes> y;
    Option<JSON::Object> j;
  };

  explicit TestSubcommand(const string& name) : Subcommand(name) {}

  Flags flags;

protected:
  virtual int execute() { return 0; }
  virtual flags::FlagsBase* getFlags() { return &flags; }
};

// Generates a vector of arguments from flags.
static vector<string> getArgv(const flags::FlagsBase& flags)
{
  vector<string> argv;
  foreachpair (const string& name, const flags::Flag& flag, flags) {
    Option<string> value = flag.stringify(flags);
    if (value.isSome()) {
      argv.push_back("--" + name + "=" + value.get());
    }
  }
  return argv;
}

TEST(SubcommandTest, Flags)
{
  TestSubcommand::Flags flags;
  flags.populate();

  // Construct the command line arguments.
  vector<string> _argv = getArgv(flags);
  int argc = static_cast<int>(_argv.size()) + 2;
  char** argv = new char*[argc];
  argv[0] = (char*) "command";
  argv[1] = (char*) "subcommand";
  for (int i = 2; i < argc; i++) {
    argv[i] = ::strdup(_argv[i - 2].c_str());
  }

  TestSubcommand subcommand("subcommand");

  ASSERT_EQ(0, Subcommand::dispatch(
      None(),
      argc,
      argv,
      &subcommand));

  EXPECT_EQ(flags.b, subcommand.flags.b);
  EXPECT_EQ(flags.i, subcommand.flags.i);
  EXPECT_EQ(flags.s, subcommand.flags.s);
  EXPECT_EQ(flags.s2, subcommand.flags.s2);
  EXPECT_EQ(flags.s3, subcommand.flags.s3);
  EXPECT_EQ(flags.d, subcommand.flags.d);
  EXPECT_EQ(flags.y, subcommand.flags.y);
  EXPECT_EQ(flags.j, subcommand.flags.j);

  for (int i = 2; i < argc; i++) {
    ::free(argv[i]);
  }
  delete[] argv;
}

TEST(SubcommandTest, Dispatch)
{
  TestSubcommand subcommand("subcommand");
  TestSubcommand subcommand2("subcommand2");

  int argc = 2;
  char* argv[] = {
    (char*) "command",
    (char*) "subcommand"
  };

  EXPECT_EQ(1, Subcommand::dispatch(
      None(),
      argc,
      argv,
      &subcommand2));

  // Duplicated subcommand names.
  EXPECT_EQ(1, Subcommand::dispatch(
      None(),
      argc,
      argv,
      &subcommand,
      &subcommand));

  EXPECT_EQ(0, Subcommand::dispatch(
      None(),
      argc,
      argv,
      &subcommand,
      &subcommand2));
}


text:
import { Serialize, Deserialize, DeserializeInto } from '../src/serialize';
class HookTest {
    static OnDeserialized(instance, json) { }
    static OnSerialized(instance, json) { }
}
describe("OnDeserialized hooks", function () {
    it("should always call OnDeserialized with Deserialize", function () {
        var x = { hello: 'Guten Tag' };
        spyOn(HookTest, 'OnDeserialized');
        var inst = Deserialize(x, HookTest);
        expect(HookTest.OnDeserialized).toHaveBeenCalledWith(inst, x);
    });
    it("should always call OnDeserialized with DeserializeInto", function () {
        var x = { hello: 'Guten Tag' };
        spyOn(HookTest, 'OnDeserialized');
        var inst = DeserializeInto(x, HookTest, new HookTest());
        expect(HookTest.OnDeserialized).toHaveBeenCalledWith(inst, x);
    });
    it("should always call OnSerialized with Serialize", function () {
        var inst = new HookTest();
        spyOn(HookTest, 'OnSerialized');
        var json = Serialize(inst);
        expect(HookTest.OnSerialized).toHaveBeenCalledWith(inst, json);
    });
});


text:
'use strict';

const assert = require('assert');
const fs = require('fs');

const sharp = require('../../lib');
const fixtures = require('../fixtures');

describe('failOn', () => {
  it('handles truncated JPEG', function (done) {
    sharp(fixtures.inputJpgTruncated, { failOn: 'none' })
      .resize(32, 24)
      .toBuffer(function (err, data, info) {
        if (err) throw err;
        assert.strictEqual('jpeg', info.format);
        assert.strictEqual(32, info.width);
        assert.strictEqual(24, info.height);
        fixtures.assertSimilar(fixtures.expected('truncated.jpg'), data, done);
      });
  });

  it('handles truncated PNG, emits warnings', function (done) {
    let isWarningEmitted = false;
    sharp(fixtures.inputPngTruncated, { failOn: 'none' })
      .on('warning', function (warning) {
        assert.ok(
          ['read gave 2 warnings', 'not enough data', 'end of stream']
            .some(m => warning.includes(m)));
        isWarningEmitted = true;
      })
      .resize(32, 24)
      .toBuffer(function (err, data, info) {
        if (err) throw err;
        assert.strictEqual(true, isWarningEmitted);
        assert.strictEqual('png', info.format);
        assert.strictEqual(32, info.width);
        assert.strictEqual(24, info.height);
        done();
      });
  });

  it('throws for invalid options', () => {
    assert.throws(
      () => sharp({ failOn: 'zoinks' }),
      /Expected one of: none, truncated, error, warning for failOn but received zoinks of type string/
    );
    assert.throws(
      () => sharp({ failOn: 1 }),
      /Expected one of: none, truncated, error, warning for failOn but received 1 of type number/
    );
  });

  it('deprecated failOnError', () => {
    assert.doesNotThrow(
      () => sharp({ failOnError: true })
    );
    assert.doesNotThrow(
      () => sharp({ failOnError: false })
    );
    assert.throws(
      () => sharp({ failOnError: 'zoinks' }),
      /Expected boolean for failOnError but received zoinks of type string/
    );
    assert.throws(
      () => sharp({ failOnError: 1 }),
      /Expected boolean for failOnError but received 1 of type number/
    );
  });

  it('returns errors to callback for truncated JPEG', function (done) {
    sharp(fixtures.inputJpgTruncated, { failOn: 'truncated' }).toBuffer(function (err, data, info) {
      assert.ok(err.message.includes('VipsJpeg: Premature end of'), err);
      assert.strictEqual(data, undefined);
      assert.strictEqual(info, undefined);
      done();
    });
  });

  it('returns errors to callback for truncated PNG', function (done) {
    sharp(fixtures.inputPngTruncated, { failOn: 'truncated' }).toBuffer(function (err, data, info) {
      assert.ok(err.message.includes('read error'), err);
      assert.strictEqual(data, undefined);
      assert.strictEqual(info, undefined);
      done();
    });
  });

  it('rejects promises for truncated JPEG', function (done) {
    sharp(fixtures.inputJpgTruncated, { failOn: 'error' })
      .toBuffer()
      .then(() => {
        throw new Error('Expected rejection');
      })
      .catch(err => {
        done(err.message.includes('VipsJpeg: Premature end of') ? undefined : err);
      });
  });

  it('handles stream-based input', async () => {
    const writable = sharp({ failOn: 'none' }).resize(32, 24);
    fs.createReadStream(fixtures.inputJpgTruncated).pipe(writable);
    return writable.toBuffer();
  });
});


text:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();

mongoose.Promise = global.Promise;

mongoose.connect(
  process.env.MONGODB_URI ||
  "mongodb://localhost:27017/woosreads",
  {
    useMongoClient: true
  }
).then(
  console.log("connected to MongoDB on localhost")
)

// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(routes);

// Send every request to the React app
// Define any API routes before this runs
app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "./client/build/index.html"));
});

app.listen(PORT, function() {
  console.log(`🌎 ==> Server now on port ${PORT}!`);
});


text:
Example of redmine+mariadb for CJK languages on docker-compose.

- modify mysqld character set to utf8mb4.
- add `ENGINE=InnoDB ROW_FORMAT=DYNAMIC` to CREATE TABLE.

# How to use

1. clone this repos.
2. `cd` to cloned dir.
3. run `docker-compose up --build db` to DB initialization.
4. hit `Ctrl-C` after `[Note] mysqld: ready for connections.` shown.
5. run `docker-compose up -d --build`.

# LICENSE

The MIT License.


text:
;(function($n2) {
"use strict";

var
 _loc = function(str,args){ return $n2.loc(str,'nunaliit2',args); }
 ,DH = 'n2.instance'
 ;

//--------------------------------------------------------------------------
var Service = $n2.Class({

	dispatchService: null,

	initialize: function(opts_){
		var opts = $n2.extend({
			dispatchService: null
		},opts_);

		var _this = this;

		this.dispatchService = opts.dispatchService;

		// Register to events
		if( this.dispatchService ){
			var f = function(m, addr, dispatcher){
				_this._handle(m, addr, dispatcher);
			};
			this.dispatchService.register(DH,'instanceCreate',f);
		};
	},

	_handle: function(m, addr, dispatcher){
		if( 'instanceCreate' === m.type ){
			if( typeof m.instanceConfiguration !== 'object' ){
				$n2.log('instanceConfiguration must be provided when creating an instance');
				return;
			};

			if( typeof m.instanceConfiguration.type !== 'string' ){
				$n2.log('instanceConfiguration.type must be a string when creating an instance');
				return;
			};

			if( $n2.mapInitialBounds
			 && typeof $n2.mapInitialBounds.handleInstanceCreate === 'function' ){
				$n2.mapInitialBounds.handleInstanceCreate(m, addr, dispatcher);
			};

			if( $n2.utilitiesModel
			 && typeof $n2.utilitiesModel.handleInstanceCreate === 'function' ){
				$n2.utilitiesModel.handleInstanceCreate(m, addr, dispatcher);
			};
		};
	}
});

//--------------------------------------------------------------------------
$n2.instance = {
	Service: Service
};

})(nunaliit2);


text:
"use strict";

var should = require("should"),
  options = require("../lib/options.js");

describe("options", function () {
  describe("#set()", function () {
    var validInput;
    beforeEach(function () {
      validInput = {
        pathToOutput: "test/",
        pathToImages: "test/path/",
        output: "pdf",
        filename: "test"
      };
      options.reset();
    });
    it("should set all the options passed to it", function (done) {
      options.set(validInput, function (err, opts) {
        var prop;
        should.not.exist(err);
        for (prop in validInput) {
          if (validInput.hasOwnProperty(prop)) {
            opts[prop].should.equal(validInput[prop]);
          }
        }
        done();
      });
    });
    it("should should complain if options without a default aren't set", function (done) {
      delete validInput.filename;
      options.set(validInput, function (err) {
        should.exist(err);
        done();
      });
    });
    it("should not set options that don't exist", function (done) {
      validInput.thisShouldNotBeSet = "this";
      options.set(validInput, function (err, opts) {
        should.not.exist(err);
        opts.should.not.have.property("thisShouldNotBeSet");
        done();
      });
    });
    it("should set options even when keys aren't camel cased", function (done) {
      delete validInput.filename;
      delete validInput.pathToImages;
      validInput.Filename = "test";
      validInput["Path to images"] = "path/to/images";
      options.set(validInput, function (err, opts) {
        should.not.exist(err);
        opts.filename.should.equal(validInput.Filename);
        opts.pathToImages.should.equal(validInput["Path to images"]);
        done();
      });
    });
  });
});


text:
import redis
import os
import json
from .RedisQueue import RedisQueue

# NOTE: We don't use J here because this file
# is imported during the bootstrap process where J is not available

class RedisDict(dict):

    def __init__(self, client, key):
        self._key = key
        self._client = client

    def __getitem__(self, key):
        value = self._client.hget(self._key, key)
        return json.loads(value)

    def __setitem__(self, key, value):
        value = json.dumps(value)
        self._client.hset(self._key, key, value)

    def __contains__(self, key):
        return self._client.hexists(self._key, key)

    def __repr__(self):
        return repr(self._client.hgetall(self._key))

    def copy(self):
        result = dict()
        allkeys = self._client.hgetalldict(self._key)
        for key, value in list(allkeys.items()):
            result[key] = json.loads(value)
        return result

    def pop(self, key):
        value = self._client.hget(self._key, key)
        self._client.hdel(self._key, key)
        return json.loads(value)

    def keys(self):
        return self._client.hkeys(self._key)

    def iteritems(self):
        allkeys = self._client.hgetalldict(self._key)
        for key, value in list(allkeys.items()):
            yield key, json.loads(value)

class Redis(redis.Redis):
    hgetalldict = redis.Redis.hgetall

    def getDict(self, key):
        return RedisDict(self, key)

    def getQueue(self, name, namespace="queues", newconnection=False):
        """
        get redis queue

        :param name: name of the queue
        :param namespace: namespace of the queue
        :param newconnection: if True will create a new connection, if False will use an existing connection from the pool
        """
        if not newconnection:
            return RedisQueue(self, name, namespace=namespace)
        else:
            client = redis.Redis(**self.connection_pool.connection_kwargs)
            return RedisQueue(client, name, namespace=namespace)

    def createStoredProcedure(self, path):
        """
        create stored procedure from path

        :param path: the path where the stored procedure exist

        :raises Exception when we can not find the stored procedure on the path
        """
        if not os.path.exists(path):
            path0 = os.path.join(os.getcwd(), path)
        if not os.path.exists(path0, followlinks=True):
            raise Exception("cannot find stored procedure on path:%s" % path)
        lua = ''
        with open(path) as f:
            lua = f.read()

        return self.register_script(lua)


text:
import java.util.ArrayList;
import java.awt.*; // The Point class needs this.
/**
 * Maze is essentially a grid of booleans
 * representing the terrain of "dots" a
 * reference to the player, a bunch of monsters.
 *
 * @author Ryan Seys
 * @version 1.0
 */
public abstract class Maze
{
    // instance variables - replace the example below with your own
    public static final int SIZE = 5;
    public Item grid[][];
    protected Player p;
    protected ArrayList<Monster> monsters;
    private int points;
    private String msg;
    public static final int DEFAULT_PLAYER_X = 4;
    public static final int DEFAULT_PLAYER_Y = 2;
    public static final int DEFAULT_EXIT_X = 3;
    public static final int DEFAULT_EXIT_Y = 3;
    public static final String EMPTY = ".";
    // horizontal spacer to make it look like a square
    public static final String H_SPACER_STRING = "   ";
    // vertical spacer to make it look like a square
    public static final String V_SPACER_STRING = "\n\n";
    public static final String COMMAND_REQUEST = "Enter a command: ";

    /**
     * Constructor for objects of class Maze
     */
    public Maze(String option)
    {
        if(option.equals("Mouseville")){
            p = new Elephant(DEFAULT_PLAYER_X, DEFAULT_PLAYER_Y, this);
        }
        else p = new Player(DEFAULT_PLAYER_X, DEFAULT_PLAYER_Y, this);
        grid = new Item[SIZE][SIZE];
        points = 1000; //initial points to give player. Reduce to make it harder to win.
    }

    public Maze()
    {
        this("");
    }

        /**
     * @return true if the whole board has no dots left (player hit all dots)
     */
    public abstract boolean hasWon(); //checks to see if won.

    /**
     * "Resolves" the new state of the game.
     */
    public abstract void  resolve();

    /**
     * Returns the string associated with any object on a given space.
     */
    public abstract String gridNull(int x, int y);

    /**
     * Fetch and return the Player object.
     * @return A reference to the Player.
    */
    public Player getPlayer()
    {
        return p;
    }

    //add points to the score.
    public void addPoints(int amount)
    {
        points += amount;
    }

    /**
     * All the monsters created.
     * @return The ArrayList of monsters
    */
    public ArrayList<Monster> getMonsters()
    {
        return monsters;
    }

    /**
     * Add a monster to the list of monsters.
     * @param Monster to add.
    */
    public void addMonster(Monster m)
    {
        monsters.add(m);
    }

    /**
     * Whether or not there is a mouse at the coordinate.
     * @return True if there is a mouse there, false if there isn't.
    */
    public boolean hasMonster(int i, int j)
    {
        for (Monster m : monsters)
        {
            if ((i == m.getX()) && (j == m.getY()))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * @return if the player and monster are in the same spot.
    */
    public boolean hasLost()
    {
        for (Monster m : monsters)
        {
            if (hasMonster(getPlayer().getX(), getPlayer().getY()))
            {
                return true;
            }
        }
        return false;
    }

        /**
     * Returns a string representation of the grid:
     * - put an "G" at the location of a Ghost
     * - put a "P" if Pacman is at a given coordinate;
     * - print an "D" for an uneaten dot.
     * - print a "." for an eaten dot.
     * @return A string representation of the grid.
     */
    public String toString(String message) {
        String output = ""; //initialize
        for(int j = 0; j < SIZE; j++)
        {
            for(int i = 0; i < SIZE; i++)
            {
                // Note: The order of the following IF statements controls precedence over which letter
                // is displayed when two objects overlap.
                output += gridNull(i, j);
                if(gridNull(i, j).equals("")) {
                    output += grid[i][j].getLetter();
                }
                output += H_SPACER_STRING;
            }
            output = output + V_SPACER_STRING;
        }
        output += message;
        return output;
    }

    /**
     * Ouput a string representation of the grid to the console.
     */
    public void print(String message)
    {
        System.out.println(toString(message));
    }
}


text:
package vt100

import (
	"errors"
	"expvar"
	"fmt"
	"image/color"
	"regexp"
	"strconv"
	"strings"
)

// UnsupportedError indicates that we parsed an operation that this
// terminal does not implement. Such errors indicate that the client
// program asked us to perform an action that we don't know how to.
// It MAY be safe to continue trying to do additional operations.
// This is a distinct category of errors from things we do know how
// to do, but are badly encoded, or errors from the underlying io.RuneScanner
// that we're reading commands from.
type UnsupportedError struct {
	error
}

var (
	supportErrors = expvar.NewMap("vt100-unsupported-operations")
)

func supportError(e error) error {
	supportErrors.Add(e.Error(), 1)
	return UnsupportedError{e}
}

// Command is a type of object that the terminal can process to perform
// an update.
type Command interface {
	display(v *VT100) error
}

// runeCommand is a simple command that just writes a rune
// to the current cell and advances the cursor.
type runeCommand rune

func (r runeCommand) display(v *VT100) error {
	v.put(rune(r))
	return nil
}

// escapeCommand is a control sequence command. It includes a variety
// of control and escape sequences that move and modify the cursor
// or the terminal.
type escapeCommand struct {
	cmd  rune
	args string
}

func (c escapeCommand) String() string {
	return fmt.Sprintf("[%q %U](%v)", c.cmd, c.cmd, c.args)
}

type intHandler func(*VT100, []int) error

var (
	// intHandlers are handlers for which all arguments are numbers.
	// This is most of them -- all the ones that we process. Eventually,
	// we may add handlers that support non-int args. Those handlers
	// will instead receive []string, and they'll have to choose on their
	// own how they might be parsed.
	intHandlers = map[rune]intHandler{
		's': save,
		'7': save,
		'u': unsave,
		'8': unsave,
		'A': relativeMove(-1, 0),
		'B': relativeMove(1, 0),
		'C': relativeMove(0, 1),
		'D': relativeMove(0, -1),
		'K': eraseColumns,
		'J': eraseLines,
		'H': home,
		'f': home,
		'm': updateAttributes,
	}
)

func save(v *VT100, _ []int) error {
	v.save()
	return nil
}

func unsave(v *VT100, _ []int) error {
	v.unsave()
	return nil
}

var (
	codeColors = []color.RGBA{
		Black,
		Red,
		Green,
		Yellow,
		Blue,
		Magenta,
		Cyan,
		White,
		{}, // Not used.
		DefaultColor,
	}
)

// A command to update the attributes of the cursor based on the arg list.
func updateAttributes(v *VT100, args []int) error {
	f := &v.Cursor.F

	var unsupported []int
	for _, x := range args {
		switch x {
		case 0:
			*f = Format{}
		case 1:
			f.Intensity = Bright
		case 2:
			f.Intensity = Dim
		case 22:
			f.Intensity = Normal
		case 4:
			f.Underscore = true
		case 24:
			f.Underscore = false
		case 5, 6:
			f.Blink = true // We don't distinguish between blink speeds.
		case 25:
			f.Blink = false
		case 7:
			f.Inverse = true
		case 27:
			f.Inverse = false
		case 8:
			f.Conceal = true
		case 28:
			f.Conceal = false
		case 30, 31, 32, 33, 34, 35, 36, 37, 39:
			f.Fg = codeColors[x-30]
		case 40, 41, 42, 43, 44, 45, 46, 47, 49:
			f.Bg = codeColors[x-40]
			// 38 and 48 not supported. Maybe someday.
		default:
			unsupported = append(unsupported, x)
		}
	}

	if unsupported != nil {
		return supportError(fmt.Errorf("unknown attributes: %v", unsupported))
	}
	return nil
}

func relativeMove(y, x int) func(*VT100, []int) error {
	return func(v *VT100, args []int) error {
		c := 1
		if len(args) >= 1 {
			c = args[0]
		}
		// home is 1-indexed, because that's what the terminal sends us. We want to
		// reuse its sanitization scheme, so we'll just modify our args by that amount.
		return home(v, []int{v.Cursor.Y + y*c + 1, v.Cursor.X + x*c + 1})
	}
}

func eraseColumns(v *VT100, args []int) error {
	d := eraseForward
	if len(args) > 0 {
		d = eraseDirection(args[0])
	}
	if d > eraseAll {
		return fmt.Errorf("unknown erase direction: %d", d)
	}
	v.eraseColumns(d)
	return nil
}

func eraseLines(v *VT100, args []int) error {
	d := eraseForward
	if len(args) > 0 {
		d = eraseDirection(args[0])
	}
	if d > eraseAll {
		return fmt.Errorf("unknown erase direction: %d", d)
	}
	v.eraseLines(d)
	return nil
}

func sanitize(v *VT100, y, x int) (int, int, error) {
	var err error
	if y < 0 || y >= v.Height || x < 0 || x >= v.Width {
		err = fmt.Errorf("out of bounds (%d, %d)", y, x)
	} else {
		return y, x, nil
	}

	if y < 0 {
		y = 0
	}
	if y >= v.Height {
		y = v.Height - 1
	}
	if x < 0 {
		x = 0
	}
	if x >= v.Width {
		x = v.Width - 1
	}
	return y, x, err
}

func home(v *VT100, args []int) error {
	var y, x int
	if len(args) >= 2 {
		y, x = args[0]-1, args[1]-1 // home args are 1-indexed.
	}
	y, x, err := sanitize(v, y, x) // Clamp y and x to the bounds of the terminal.
	v.home(y, x)                   // Try to do something like what the client asked.
	return err
}

func (c escapeCommand) display(v *VT100) error {
	f, ok := intHandlers[c.cmd]
	if !ok {
		return supportError(c.err(errors.New("unsupported command")))
	}

	args, err := c.argInts()
	if err != nil {
		return c.err(fmt.Errorf("while parsing int args: %v", err))
	}

	return f(v, args)
}

// err enhances e with information about the current escape command
func (c escapeCommand) err(e error) error {
	return fmt.Errorf("%s: %s", c, e)
}

var csArgsRe = regexp.MustCompile("^([^0-9]*)(.*)$")

// argInts parses c.args as a slice of at least arity ints. If the number
// of ; separated arguments is less than arity, the remaining elements of
// the result will be zero. errors only on integer parsing failure.
func (c escapeCommand) argInts() ([]int, error) {
	if len(c.args) == 0 {
		return make([]int, 0), nil
	}
	args := strings.Split(c.args, ";")
	out := make([]int, len(args))
	for i, s := range args {
		x, err := strconv.ParseInt(s, 10, 0)
		if err != nil {
			return nil, err
		}
		out[i] = int(x)
	}
	return out, nil
}

type controlCommand rune

const (
	backspace      controlCommand = '\b'
	_horizontalTab                = '\t'
	linefeed                      = '\n'
	_verticalTab                  = '\v'
	_formfeed                     = '\f'
	carriageReturn                = '\r'
)

func (c controlCommand) display(v *VT100) error {
	switch c {
	case backspace:
		v.backspace()
	case linefeed:
		v.Cursor.Y++
		v.Cursor.X = 0
	case carriageReturn:
		v.Cursor.X = 0
	default:
		return supportError(fmt.Errorf("control code not implemented %0x", uint(c)))
	}
	return nil
}


text:
/** String utilities, includes:
 * is-null/empty/whitespace, is-upper/lower/digit, pad-start/end, and remove-leading/trailing
 */
module Strings {

    /** Check if a string is null or empty
     * @param str the string to check
     * @returns true if the 'str' is null or empty, false if not
     */
    export function isNullOrEmpty(str: string | null | undefined): boolean {
        return str == null || str.length === 0;
    }

    /** Check if a string is null or empty or contains only whitespace
     * @param str the string to check
     * @returns true if the 'str' is null, empty or contains only
     * whitespace characters, false otherwise
     */
    export function isNullOrWhiteSpace(str: string | null | undefined): boolean {
        return str == null || str.trim().length === 0;
    }

    /** Check that a string is NOT null nor empty
     * @param str the string to check
     * @returns true if the 'str' is not null and not empty, false if null or empty
     */
    export function notNullOrEmpty(str: string | null | undefined): str is string {
        return str != null && str.length > 0;
    }

    /** Check that a string is NOT null nor empty nor contains only whitespace
     * @param str the string to check
     * @returns true if the 'str' is not null, not empty, nor contains only whitespace characters,
     * false otherwise
     */
    export function notNullOrWhiteSpace(str: string | null | undefined): str is string {
        return str != null && str.trim().length > 0;
    }

    /** Check if a character at a specific index in a string is a digit
     * @param str the string to get the character from
     * @param i the index of the character
     * @returns true if the character at the specified index is a digit [0-9], false if not
     */
    export function isCharAtDigit(str: string | null | undefined, i: number): boolean {
        if (str == null || i < 0 || i >= str.length) {
            return false;
        }
        var ch = str.charCodeAt(i) - 48;
        return ch >= 0 && ch <= 9;
    }

    /** Check if all characters in a string are digits
     * @param str the string to check
     * @returns true if every character in the string is a digit [0-9], false if the string is empty or contains non-digits
     */
    export function isDigit(str: string | null | undefined): boolean {
        var size = 0;
        if (str == null || (size = str.length) === 0) {
            return false;
        }
        for (var i = 0; i < size; i++) {
            var ch = str.charCodeAt(i) - 48;
            if (ch < 0 || ch > 9) {
                return false;
            }
        }
        return true;
    }

    /** Check if a char at a specific index in a string is upper case
     * Example: isCharAtUpperCase("Super", 0)
     * returns: true
     * Example: isCharAtUpperCase("Super", 4)
     * returns false
     *
     * @param str the string that the char resides in
     * @param i the index of the character in 'str' to test
     * @returns true if the character at index 'i' is upper case
     */
    export function isCharAtUpperCase(str: string | null | undefined, i: number): boolean {
        if (str == null || i < 0 || i >= str.length) {
            return false;
        }
        var ch = str.charAt(i);
        return ch === ch.toUpperCase();
    }

    /** Check if a char at a specific index in a string is lower case
     * Example: isCharAtLowerCase("Super", 0)
     * returns: false
     * Example: isCharAtLowerCase("Super", 4)
     * returns true
     *
     * @param str the string that the char resides in
     * @param i the index of the character in 'str' to test
     * @returns true if the character at index 'i' is lower case
     */
    export function isCharAtLowerCase(str: string | null | undefined, i: number): boolean {
        if (str == null || i < 0 || i >= str.length) {
            return false;
        }
        var ch = str.charAt(i);
        return ch === ch.toLowerCase();
    }

    /** Compare two strings, ignoring leading/trailing whitespace and ignoring upper/lower case
     * @param str1 the first string to compare
     * @param str2 the second string to compare
     * @returns true if the strings are loosely equal (ignoring case and whitespace)
     */
    export function looseEqual(str1: string | null | undefined, str2: string | null | undefined): boolean {
        return str1 != null && str2 != null && str1.trim().toUpperCase() === str2.trim().toUpperCase();
    }

    /** Truncates the maximum length of a string
     * @param str the string to truncate
     * @param maxLen the max length of the string
     * @param ellipsis an optional string to append to the returned string if it is truncated, this string is appended in addition to the 'maxLen'
     */
    export function truncate(str: string, maxLen: number, ellipsis?: string): string;
    export function truncate(str: string | null | undefined, maxLen: number, ellipsis?: string): string;
    export function truncate(str: string | null | undefined, maxLen: number, ellipsis: string = ""): string {
        return str != null && str.length > maxLen ? str.substring(0, maxLen - ellipsis.length) + ellipsis : str || "";
    }

    /** Prepend padding to the 'String(value)' representation of 'value' to increase it's length to 'targetLen'
     * @param value the value to convert to a string and pad
     * @param targetLen the maximum length of the returned string
     * @param padChar an character to use as padding
     * @returns the 'value' converted to a string and padded with 'padChar' until the string is 'targetLen' long,
     * or returns the 'value' as a string without modification if the string is longer than 'targetLen'
     */
    export function padStart(value: string | number, targetLen: number, padChar: string): string {
        var valStr = String(value);
        if (valStr.length >= targetLen) {
            return valStr;
        }
        return value != null ? padChar.repeat(targetLen - valStr.length) + valStr : valStr;
    }

    /** Append padding to the 'String(value)' representation of 'value' to increase it's length to 'targetLen'
     * @param value the value to convert to a string and pad
     * @param targetLen the maximum length of the returned string
     * @param padChar an character to use as padding
     * @returns the 'value' converted to a string and padded with 'padChar' until the string is 'targetLen' long,
     * or returns the 'value' as a string without modification if the string is longer than 'targetLen'
     */
    export function padEnd(value: string | number, targetLen: number, padChar: string): string {
        var valStr = String(value);
        if (valStr.length >= targetLen) {
            return valStr;
        }
        return value != null ? valStr + padChar.repeat(targetLen - valStr.length) : valStr;
    }

    /** Remove 'leadingStr' string from the beginning of 'str' as many times as it appears.
     * Example: removeTrailingStrings("stubstubAlpha", "stub")
     * returns: "Alpha"
     *
     * @param str the string to remove the leading values from
     * @param leadingStr the sub-string to search for and remove from the beginning of 'str''
     * @returns 'str' with the matching leading strings removed
     */
    export function removeLeading(str: string, leadingStr: string, removeRepeats: boolean = false) {
        var res = str;
        var leadingStrLen = leadingStr.length;

        if (res.indexOf(leadingStr) === 0) {
            res = res.substr(leadingStrLen);
        }

        if (removeRepeats) {
            while (res.indexOf(leadingStr) === 0) {
                res = res.substr(leadingStrLen);
            }
        }
        return res;
    }

    /** Remove 'trailingStr' string from the end of 'str' as many times as it appears.
     * Example: removeTrailingStrings("alphaPiePiePie", "Pie")
     * returns: "alpha"
     *
     * @param str the string to remove the trailing values from
     * @param trailingStr the sub-string to search for and remove from the end of 'str''
     * @returns 'str' with the matching trailing strings removed
     */
    export function removeTrailing(str: string, trailingStr: string, removeRepeats: boolean = false) {
        var res = str;
        var trailingStrLen = trailingStr.length;

        if (res.lastIndexOf(trailingStr) === res.length - trailingStrLen) {
            res = res.substr(0, res.length - trailingStrLen);
        }

        if (removeRepeats) {
            while (res.lastIndexOf(trailingStr) === res.length - trailingStrLen) {
                res = res.substr(0, res.length - trailingStrLen);
            }
        }
        return res;
    }

    /** Replace all occurances of a specified substring with a replacement string
     * Example: replaceAll("cat in the hat", "at", "ab")
     * returns: "cab in the hab"
     *
     * @param str the string to search and replace
     * @param find the string to search for
     * @param replace the replacement string
     * @returns the 'str' with all instances of 'find' replaced with 'replace'
     */
    export function replaceAll(str: string, find: string, replace: string): string {
        if (str == null || find == null) {
            throw new Error("incorrect usage (" + str + ", " + find + ", " + replace + "), expected (String str, String find, String replace)");
        }
        return str.split(find).join(replace);
    }

}

export = Strings;


text:
package com.yahoo.dba.perf.myperf.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

public class AlertSettings {

	public static final float CPU_THRESHOLD = 70.0f;
	public static final float IOWAITS_THRESHOLD = 30.0f;
	public static final float LOADAVG_THRESHOLD = 50.0f;
	public static final int THREAD_THRESHOLD = 100;
	public static final int REPLLAG_THRESHOLD = 1800;
	public static final int SLOWQUERY_THRESHOLD = 200;//200/minute
	public static final int ABORTED_CONNECTS_THRESHOLDS = 10;//600/minute
	public static final int DEADLOCKS_THRESHOLDS = 0;//since we use greater than, so any positive detection should be alerted
	public static final int DISK_USED_PCT_THRESHOLD = 90;

	public static final String[] COMMON_ALERTS = new String[]{"CPU", "IO", "LOADAVG", "THREAD", "REPLLAG",
		"SLOW", "CONNECT_FAILURE", "DEADLOCKS","DISKUSAGE"};

	private static final HashMap<String, Float> DEFAULT_THRESHOLD = new HashMap<String, Float>();
	private static Logger logger = Logger.getLogger(AlertSettings.class.getName());

	static
	{
		DEFAULT_THRESHOLD.put("CPU", CPU_THRESHOLD);
		DEFAULT_THRESHOLD.put("IO", IOWAITS_THRESHOLD);
		DEFAULT_THRESHOLD.put("LOADAVG", LOADAVG_THRESHOLD);
		DEFAULT_THRESHOLD.put("THREAD", new Float(THREAD_THRESHOLD));
		DEFAULT_THRESHOLD.put("REPLLAG", new Float(REPLLAG_THRESHOLD));
		DEFAULT_THRESHOLD.put("SLOW", new Float(SLOWQUERY_THRESHOLD));
		DEFAULT_THRESHOLD.put("CONNECT_FAILURE", new Float(ABORTED_CONNECTS_THRESHOLDS));
		DEFAULT_THRESHOLD.put("DEADLOCKS", new Float(DEADLOCKS_THRESHOLDS));
		DEFAULT_THRESHOLD.put("DISKUSAGE", new Float(DISK_USED_PCT_THRESHOLD));
	}

	static class HostSettings
	{
		private HashMap<String, Float> thresholds = new HashMap<String, Float>();

		public Float getThreshold(String alertType)
		{
			if(thresholds.containsKey(alertType))
				return thresholds.get(alertType);
			return null;
		}

		public void updateThreshold(String alertType, Float threshold)
		{
			this.thresholds.put(alertType, threshold);
		}
	}
	static class GroupSettings
	{
		private HashMap<String, Float> groupThresholds = new HashMap<String, Float>();
		private HashMap<String, HostSettings> hostSettings = new HashMap<String, HostSettings>();

		public HostSettings getHostSettings(String dbhost)
		{
			if(this.hostSettings.containsKey(dbhost))
				return this.hostSettings.get(dbhost);
			return null;
		}

		public Float getGroupDefaultThreshold(String alertType)
		{
			if(this.groupThresholds.containsKey(alertType))
				return this.groupThresholds.get(alertType);
			else
				return null;
		}
		public void updateDefault(String alertType, Float threshold)
		{
			this.groupThresholds.put(alertType, threshold);
		}
		public void updateHostThreshold(String dbhost, String alertType, Float threshold)
		{
			if(!this.hostSettings.containsKey(dbhost))
				this.hostSettings.put(dbhost, new HostSettings());
			this.hostSettings.get(dbhost).updateThreshold(alertType, threshold);
		}
	}

	private HashMap<String, GroupSettings> groupSettings = new HashMap<String, GroupSettings>();
	private MyPerfContext context;
	private List<AlertDefinition> alertDefinitions = new ArrayList<AlertDefinition>();

	public AlertSettings()
	{

	}

	synchronized public float getAlertThreshold(String dbgroup, String dbhost, String alertType)
	{
		alertType = alertType.toUpperCase();
		//do we have group?
		if(!this.groupSettings.containsKey(dbgroup))
		{
			if(DEFAULT_THRESHOLD.containsKey(alertType))return DEFAULT_THRESHOLD.get(alertType);
			else return Float.MAX_VALUE;
		}
		GroupSettings grpSetting = groupSettings.get(dbgroup);
		HostSettings hostSetting = grpSetting.getHostSettings(dbhost);
		Float threshold = null;
		if(hostSetting != null)
			threshold = hostSetting.getThreshold(alertType);
		if(threshold == null)
			threshold = grpSetting.getGroupDefaultThreshold(alertType);
		if(threshold == null && DEFAULT_THRESHOLD.containsKey(alertType))return DEFAULT_THRESHOLD.get(alertType);
		if(threshold == null)
			threshold = Float.MAX_VALUE;
		return threshold;

	}

	synchronized public Float getAlertThreshold(DBInstanceInfo dbinfo, String alertType)
    {
		  return getAlertThreshold(dbinfo.getDbGroupName(), dbinfo.getHostName(), alertType);
    }

	synchronized public boolean updateAlertThreshold(String dbgroup, String dbhost, String alertType, Float threshold, boolean save)
	{
		String alertSettingString = "(" + dbgroup +", "+dbhost +", "+alertType+", " + threshold+", " + save + ")";
		float prevValue = getAlertThreshold(dbgroup, dbhost, alertType);
		if(prevValue!=0.0f && Math.abs((prevValue - threshold.floatValue())/prevValue)<0.01f)
		{
			logger.info("Change too small, ignore: " + alertSettingString);
			return false;//ignore if change is less than 1%
		}
		if(prevValue==0.0f && threshold.floatValue()==0.0f)return false;

		if(dbgroup==null || dbgroup.isEmpty())return false;
		if(this.context.getDbInfoManager().findGroup(dbgroup)==null)
		{
			logger.info("Unknow DB GROUP, ignore: " + alertSettingString);
			return false;//no such dbgroup
		}
		if(dbhost==null || dbhost.isEmpty())dbhost = "all";
		if(!"all".equals(dbhost) && this.context.getDbInfoManager().findDB(dbgroup, dbhost)==null)
		{
			logger.info("Unknown DB, ignore: " + alertSettingString);
			return false;//no such db
		}
		if(!this.groupSettings.containsKey(dbgroup))
			this.groupSettings.put(dbgroup, new GroupSettings());
		GroupSettings grpSetting  = this.groupSettings.get(dbgroup);
		if("all".equals(dbhost))
		{
			if(save)this.context.getMetricDb().upsertAlertSetting(dbgroup, dbhost, alertType, threshold, null);
			grpSetting.updateDefault(alertType, threshold);
		}else
		{
			if(save)this.context.getMetricDb().upsertAlertSetting(dbgroup, dbhost, alertType, threshold, null);
			grpSetting.updateHostThreshold(dbhost, alertType, threshold);
		}
		return true;
	}

	public MyPerfContext getContext() {
		return context;
	}

	public void setContext(MyPerfContext context) {
		this.context = context;
	}

	public List<AlertDefinition> getAlertDefinitions() {
		return alertDefinitions;
	}

	public boolean addAlertDefinition(AlertDefinition alertDef)
	{
	  synchronized(this.alertDefinitions)
	  {
		  String name  = alertDef.getName();
		  for(int i = this.alertDefinitions.size() - 1; i>=0; i--)
		  {
			if(this.alertDefinitions.get(i).getName().equals(name))
			{
				return false;
			}
		  }
		this.alertDefinitions.add(alertDef);
	  }
	  return true;
	}
	public boolean removeAlertDefinition(String name)
	{
	  synchronized(this.alertDefinitions)
	  {
		for(int i = this.alertDefinitions.size() - 1; i>=0; i--)
		{
			if(this.alertDefinitions.get(i).getName().equals(name))
			{
				this.alertDefinitions.remove(i);
				return true;
			}
		}
	  }
		return false;
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>vroom vroom: include/socket_exception.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

vroom vroom

An HTTP server that interprets server-side JavaScript

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

 All Classes Files Functions Variables Groups Pages

include

socket_exception.h

    1

    2 #ifndef SOCKET_EXCEPTION_H

    3 #define SOCKET_EXCEPTION_H

    4

    5 namespace vv {

    6     using namespace std;

    7

   11     class SocketException : public exception {

   12     public:

   18         explicit SocketException(const string& message) : message_("SocketException: " + message) {

   19

   20         }

   21

   26         const char* what() const throw() {

   27             return message_.c_str();

   28         }

   29     private:

   33         string message_;

   34     };

   35 }

   36

   37 #endif

<address class="footer">
Generated by

 1.8.2
</address>


text:
#import <AppKit/AppKit.h>

@interface NSFont (CFTraits)

/// Returns YES if this font exists in a bold variant and NO otherwise.
@property (readonly) BOOL fontInFamilyExistsInBold;

/// Returns YES if this font exists in an italic variant and NO otherwise.
@property (readonly) BOOL fontInFamilyExistsInItalic;

/// Returns YES if this font is bold.
@property (readonly) BOOL isBold;

/// Returns YES if this font is italic.
@property (readonly) BOOL isItalic;

/// Returns YES if this font is condensed.
@property (readonly) BOOL isCondensed;

/// Returns YES if this font is expanded.
@property (readonly) BOOL isExpanded;

/// Returns YES if this font is monospaced.
@property (readonly) BOOL isMonospaced;

/// Returns YES if this font is vertical.
//@property (readonly) BOOL isVertical;

/// Returns YES if this font is UI optimized.
@property (readonly) BOOL isUIOptimized;

/// Returns the font size for this font instance.
@property (readonly) float fontSize;

/// Returns the bold variation of the font or the font itself
/// if such a variation does not exist.
@property (readonly) NSFont *fontVariationBold;

/// Returns the italic variation of the font or the font itself
/// if such a variation does not exist.
@property (readonly) NSFont *fontVariationItalic;

/// Returns the bold-italic variation of the font or the font itself
/// if such a variation does not exist.
@property (readonly) NSFont *fontVariationBoldItalic;

/// Returns the regular variation of the font or the font itself
/// if such a variation does not exist.
@property (readonly) NSFont *fontVariationRegular;

@end


text:
package com.health.script.runtime;

/**
 * Represents a string value in the script.
 */
public final class StringValue extends WrapperValue<String> {
    /**
     * Creates a new value with the default value (null).
     */
    public StringValue() {
        super(null);
    }

    /**
     * Creates a new value with the given value.
     *
     * @param value
     *            the value of the string.
     */
    public StringValue(final String value) {
        super(value);
    }
}


text:
module Control.Wire.Prefab.Sample
    ( -- * Sampling
      --history,
      keep,
      sample,
      window,
      windowList
    )
    where

import qualified Data.Foldable as F
import qualified Data.Sequence as Seq
import Control.Wire.Wire
import Data.Sequence (Seq, (|>))

-- | Produce the most recent inputs in the given time window.  The left
-- input signal is the sample, the right input signal is the time
-- window.
--
-- * Complexity: O(n), where n the number of samples in the time window.
--
-- * Depends: current instant.

--history :: (Reactive cat) => Wire e cat (a, Time) (Seq (a, Time))
--history = undefined

-- | Keep the input signal of the first instant forever.
--
-- Depends: first instant.

keep :: Wire e m a a
keep = mkPure (\_ x -> (Right x, constant x))

-- | Sample the left signal at discrete intervals given by the right
-- signal.
--
-- * Depends: instant of the last sample.

sample :: Wire e m (a, Time) a
sample = mkPure $ \dt (x, _) -> (Right x, sample' dt x)
    where
    sample' t0' x' =
        mkPure $ \dt (x, t1) ->
            let t0 = t0' + dt in
            if t0 >= t1
              then (Right x, sample' (t0 - t1) x)
              else (Right x', sample' t0 x')

-- | Produce up to the given number of most recent inputs.
--
-- * Complexity: O(n), where n is the given argument.
--
-- * Depends: current instant.

window :: Int -> Wire e m a (Seq a)
window = collect' Seq.empty
    where
    collect' s' 0 = window' s'
    collect' s' n =
        mkPure $ \_ x ->
            let s = s' |> x in
            s `seq` (Right s, collect' s (n - 1))

    window' s' =
        mkPure $ \_ x ->
            let s = Seq.drop 1 (s' |> x) in
            s `seq` (Right s, window' s)

-- | Same as @fmap toList . window@.

windowList :: (Monad m) => Int -> Wire e m a [a]
windowList = fmap F.toList . window


text:
You bend down and call out to the little marshmallow hand.

Out of the corner of your eye, you see a movement on your left side.

You turn around slightly and you see a small hand emerge from the left wall.

It moves towards you and little marshmallow hand pops out of the wall.

It seems it had the ability to blend in  and move within the walls.

You throw the lighter to the opposite end of the room.

You keep you hand extended hoping it will see you mean no harm.

After a little hesitation, it climbs onto your hand.

Soon lots of little marshmallow hands are coming out of the walls around you.

They climb onto your shoulders and hold onto your legs.

All the while they are singing and pointing above you.

You look up and realize that the room has no roof.

The sun is shining brightly and it seems to get brighter.

The whole scene fades out and you wake up in your own bed.

The alarm is blaring and it shows that its time to get ready for work.

You reach out to turn it off and touch something soft.

You open the light and can't believe what is sitting on your nightstand.

Its a stuffed marshmallow toy and next to it the yummiest smore, still warm.

You remember you wanted to eat smores for breakfast, Yet......

How did that smore get there?

You don't remember putting it there!


text:
package io.lettuce.core.output;

import static io.lettuce.core.StringMatchResult.MatchedPosition;
import static io.lettuce.core.StringMatchResult.Position;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import io.lettuce.core.StringMatchResult;
import io.lettuce.core.codec.RedisCodec;

/**
 * Command output for {@code STRALGO} returning {@link StringMatchResult}.
 *
 * @author dengliming
 * @since 6.0
 */
public class StringMatchResultOutput<K, V> extends CommandOutput<K, V, StringMatchResult> {

    private final boolean withIdx;

    private String matchString;

    private int len;

    private List<Long> positions;

    private final List<MatchedPosition> matchedPositions = new ArrayList<>();

    public StringMatchResultOutput(RedisCodec<K, V> codec, boolean withIdx) {
        super(codec, null);
        this.withIdx = withIdx;
    }

    @Override
    public void set(ByteBuffer bytes) {

        if (!withIdx && matchString == null) {
            matchString = (String) codec.decodeKey(bytes);
        }
    }

    @Override
    public void set(long integer) {

        this.len = (int) integer;

        if (positions == null) {
            positions = new ArrayList<>();
        }
        positions.add(integer);
    }

    @Override
    public void complete(int depth) {

        if (depth == 2) {
            matchedPositions.add(buildMatchedString(positions));
            positions = null;
        }

        if (depth == 0) {
            output = new StringMatchResult(matchString, matchedPositions, len);
        }
    }

    private static MatchedPosition buildMatchedString(List<Long> positions) {

        if (positions == null) {
            throw new IllegalStateException("No matched positions");
        }

        int size = positions.size();
        // not WITHMATCHLEN
        long matchLen = size % 2 == 0 ? 0L : positions.get(size - 1);
        return new MatchedPosition(new Position(positions.get(0), positions.get(1)),
                new Position(positions.get(2), positions.get(3)), matchLen);
    }

}


text:
Current Version: **0.9.2**

Change log:

<https://github.com/apache/usergrid/blob/master/sdks/ios/changelog.md>

##Overview
This open source SDK simplifies writing iOS applications that connect to App Services (Usergrid). The repo is located here:

<https://github.com/apache/usergrid/tree/master/sdks/ios>

You can download the SDK as part of the Usergrid stack here:

* Download as a tar.gz file: <http://usergrid.apache.org/releases/>

To find out more about how to use the iOS SDK within Usergrid, see:

<http://usergrid.apache.org/docs/sdks/ios-new.html>

##Installing
Once you have downloaded the SDK, add the UGAPI folder to your project by dragging and dropping it into your project.

**Note:** Make sure you check the "Copy items into destination group's folder", and also make sure the appropriate boxes are checked next to "Add to targets".

##Getting started
If you haven't done so, make sure you know your organization name and your application name. Your organization name will be the same as the username you signed up with.

Within your organization, you can have multiple application namespaces.  By default, an application named "Sandbox" has been created for you to use for testing, but you can also log into the [Admin Portal](http://apigee.com/usergrid) and create an application with any name you want.

Once you have your application name, you will want to create a UGClient object like so:

	//configure the org and app
	NSString * orgName = @"ApigeeOrg";
	NSString * appName = @"MessageeApp";

	//make new client
	usergridClient = [[UGClient alloc]initWithOrganizationId: orgName withApplicationID: appName];

Now use the usergridClient object to invoke other methods that access the API.  For example, to log a user in:

	[usergridClient logInUser:username password:password];
	UGUser *user = [usergridClient getLoggedInUser];

Or, to create a user:

	UGClientResponse *response = [usergridClient addUser:@"myusername" email:@"email@email.com" name:@"my name" password:@"mypassword"];
    if (response.transactionState == 0) {
    	//user created!
    }

##Sample Code
If you are ready to look at a fully functional app that uses this SDK, check out the example Apigee Messagee application. It is a twitter-type app that exercises many parts of the API including: Login / Authentication, GET and POST operations, activities (tweets), and social features such as following relationships.

The Messagee Xcode project is located here:

<https://github.com/apigee/usergrid-sample-ios-messagee>

##Running Tests

The iOS SDK unit tests are written with Nu. You'll need to install the language itself to run the tests, and use the Nukefile to create a Usergrid.framework. For installation directions go [here](https://github.com/timburks/nu)

To compile the Usergrid SDK as an Objective-C framework simple type `nuke` to build the framework and then `nuke install` to install it in the /Library/Frameworks path.

To run the unit tests written for the SDK use the command `nuke test` this will run all tests.

## Contributing
We welcome your enhancements!

Like [Usergrid](https://github.com/apache/usergrid/), the Usergrid iOS SDK is open source and licensed under the Apache License, Version 2.0.

1. Fork it
2. Create an issue in [JIRA](https://issues.apache.org/jira/browse/USERGRID/)
3. Create your feature branch (`git checkout -b USERGRID-${JIRA_NUMBER}`)
4. Commit your changes (`git commit -am '${JIRA_NUMBER} ${JIRA_TITLE}'`)
5. Push your changes to the upstream branch (`git push origin my-new-feature`)
6. Create new Pull Request (make sure you describe what you did and why your mod is needed)


text:
/*global sparks */

/**
 * report:
 * {
 *   pageReports: {
 *         pageX:
 *           {
 *             sessionReports: [
 *                       {
 *                         questions: [],
 *                         log: {},
 *                         score: x,
 *                         maxScore: y
 *                       },
 *              highestScore: x,  ?
 *              maxScore: y       ?
 */
(function() {
  sparks.Log = function(startTime){
    this.events = [];
    this.startTime = startTime;
    this.endTime = -1;
  };

  sparks.LogEvent = function(name, value, time){
    this.name = name;
    this.value = value;
    this.time = time;
  };

  sparks.LogEvent.CLICKED_TUTORIAL = "Clicked tutorial";
  sparks.LogEvent.CHANGED_TUTORIAL = "Changed tutorial";
  sparks.LogEvent.BLEW_FUSE = "Blew fuse";
  sparks.LogEvent.DMM_MEASUREMENT = "DMM measurement";
  sparks.LogEvent.CHANGED_CIRCUIT = "Changed circuit";
  sparks.LogEvent.OSCOPE_MEASUREMENT = "OScope measurement";
  sparks.LogEvent.OSCOPE_V1_SCALE_CHANGED = "OScope V1 scale changed";
  sparks.LogEvent.OSCOPE_V2_SCALE_CHANGED = "OScope V2 scale changed";
  sparks.LogEvent.OSCOPE_T_SCALE_CHANGED = "OScope T scale changed";

  sparks.Log.prototype = {

    measurements: function () {
      return sparks.logController.numEvents(this, sparks.LogEvent.DMM_MEASUREMENT);
    },

    uniqueVMeasurements: function () {
      return sparks.logController.numUniqueMeasurements(this, "voltage");
    },

    uniqueIMeasurements: function () {
      return sparks.logController.numUniqueMeasurements(this, "current");
    },

    uniqueRMeasurements: function () {
      return sparks.logController.numUniqueMeasurements(this, "resistance");
    },

    connectionBreaks: function() {
      return sparks.logController.numConnectionChanges(this, "disconnect lead");
    },

    connectionMakes: function() {
      return sparks.logController.numConnectionChanges(this, "connect lead");
    },

    blownFuses: function () {
      return sparks.logController.numEvents(this, sparks.LogEvent.BLEW_FUSE);
    }
  };

})();