text:
var assert = require('chai').assert;
var httpMocks = require('node-mocks-http');
var sinon = require('sinon');

var redirect = require('../src/redirect');

describe('Redirects', function() {

    var req, res;

    function testRedirect(originalUrl, expectedCode, expectedUrl, options) {
        sinon.stub(res, 'redirect');
        req.originalUrl = originalUrl;

        redirect.init(options);
        redirect.doRedirect(req, res);

        assert.isTrue(res.redirect.calledOnce);
        assert.isTrue(res.redirect.calledWith(expectedCode, expectedUrl));

        res.redirect.restore();
    }

    beforeEach(function() {
        req = httpMocks.createRequest();
        res = httpMocks.createResponse();
    });

    it('Default Usage', function() {
        testRedirect('/unlocalised/path', 302, '/gb/en/unlocalised/path', {});
    });

    it('Preserves a query string', function() {
        testRedirect('/unlocalised/path?a=b&c=d', 302, '/gb/en/unlocalised/path?a=b&c=d', {});
    });

    it('Uppercase Country', function() {
        testRedirect('/unlocalised/path', 302, '/GB/en/unlocalised/path', {
            countryUpper: true
        });
    });

    it('Uppercase Language', function() {
        testRedirect('/unlocalised/path', 302, '/gb/EN/unlocalised/path', {
            languageUpper: true
        });
    });

    it('Uppercase both', function() {
        testRedirect('/unlocalised/path', 302, '/GB/EN/unlocalised/path', {
            countryUpper: true,
            languageUpper: true
        });
    });

    it('Separator: hyphen', function() {
        testRedirect('/unlocalised/path', 302, '/gb-en/unlocalised/path', {
            separator: '-'
        });
    });

    it('Reverse order', function() {
        testRedirect('/unlocalised/path', 302, '/en/gb/unlocalised/path', {
            reverse: true
        });
    });

    it('custom country cookie name', function() {
        req.cookies.my_country = 'BR';
        testRedirect('/unlocalised/path', 302, '/br/en/unlocalised/path', {
            countryCookie: 'my_country'
        });
    });

    it('custom language cookie name', function() {
        req.cookies.my_lang = 'ZH';
        testRedirect('/unlocalised/path', 302, '/gb/zh/unlocalised/path', {
            langCookie: 'my_lang'
        });
    });

    it('3xx http code', function() {
        testRedirect('/unlocalised/path', 301, '/gb/en/unlocalised/path', {
            httpCode: 301
        });
    });

    it('invalid 3xx http code', function() {
        testRedirect('/unlocalised/path', 302, '/gb/en/unlocalised/path', {
            httpCode: 348
        });
    });

    it('non 3xx http code', function() {
        testRedirect('/unlocalised/path', 302, '/gb/en/unlocalised/path', {
            httpCode: 200
        });
    });

    it('Mixture of options', function() {
        req.cookies.my_country = 'TV';
        testRedirect('/unlocalised/path', 302, '/en-TV/unlocalised/path', {
            reverse: true,
            separator: '-',
            countryUpper: true,
            languageUpper: false,
            countryCookie: 'my_country'
        });
    });
});

describe('Redirects - pathIsCorrect', function() {

    var req, res;

    function testPathIsCorrect(originalUrl, expected, options) {
        req.originalUrl = originalUrl;

        redirect.init(options);

        assert.equal(redirect.pathIsCorrect(req), expected);
    }

    beforeEach(function() {
        req = httpMocks.createRequest();
        res = httpMocks.createResponse();
    });

    it('Default Usage - normal path', function() {
        testPathIsCorrect('/unlocalised/path', false, {});
    });

    it('Default Usage - root path', function() {
        testPathIsCorrect('/', false, {});
    });

    it('Default Usage - just locale', function() {
        testPathIsCorrect('/gb/en', true, {});
    });

    it('Default Usage - just locale with extra slash', function() {
        testPathIsCorrect('/gb/en/', true, {});
    });

    it('Default Usage - just locale with query string', function() {
        testPathIsCorrect('/gb/en?a=b', true, {});
    });

    it('With a query string', function() {
        testPathIsCorrect('/unlocalised/path?a=b&c=d', false, {});
    });

    it('Defaul, correct path', function() {
        testPathIsCorrect('/gb/en/unlocalised/path', true, {});
    });

    it('Uppercase Country, bad path', function() {
        testPathIsCorrect('/unlocalised/path', false, {
            countryUpper: true
        });
    });

    it('Uppercase Country, lowercase path', function() {
        testPathIsCorrect('/gb/en/unlocalised/path', true, {
            countryUpper: true
        });
    });

    it('Uppercase Country, uppercase path', function() {
        testPathIsCorrect('/GB/en/unlocalised/path', true, {
            countryUpper: true
        });
    });

    it('Uppercase Language - bad path', function() {
        testPathIsCorrect('/unlocalised/path', false, {
            languageUpper: true
        });
    });

    it('Uppercase Language - lowercase path', function() {
        testPathIsCorrect('/gb/en/unlocalised/path', true, {
            languageUpper: true
        });
    });

    it('Uppercase Language - uppercase path', function() {
        testPathIsCorrect('/gb/EN/unlocalised/path', true, {
            languageUpper: true
        });
    });

    it('Uppercase both - lowercase path', function() {
        testPathIsCorrect('/gb/en/unlocalised/path', true, {
            countryUpper: true,
            languageUpper: true
        });
    });

    it('Uppercase both - uppercase path', function() {
        testPathIsCorrect('/GB/EN/unlocalised/path', true, {
            countryUpper: true,
            languageUpper: true
        });
    });

    it('Separator: hyphen, slash in path', function() {
        testPathIsCorrect('/gb/en/unlocalised/path', false, {
            separator: '-'
        });
    });

    it('Separator: hyphen, good path', function() {
        testPathIsCorrect('/gb-en/unlocalised/path', true, {
            separator: '-'
        });
    });

    it('Mixture of options', function() {
        testPathIsCorrect('/en-GB/unlocalised/path', true, {
            reverse: true,
            separator: '-',
            countryUpper: true,
            languageUpper: false
        });
    });
});


text:
import java.util.*;

public class DeclarationForm
{
    public static final String INPUT_FILE = "input.txt";

    public static void main (String[] args)
    {
        boolean debug = false;
        boolean verify = false;

        for (int i = 0; i < args.length; i++)
        {
            if ("-help".equals(args[i]))
            {
                System.out.println("Usage: [-debug] [-verify] [-help]");
                System.exit(0);
            }

            if ("-debug".equals(args[i]))
                debug = true;

            if ("-verify".equals(args[i]))
                verify = true;
        }

        if (verify)
        {
            Verifier v = new Verifier(debug);

            if (v.verify())
                System.out.println("Verified ok.");
            else
                System.out.println("Verify failed!");

            System.exit(0);
        }

        Parser p = new Parser(debug);
        Vector<Answers> answers = p.work(INPUT_FILE);
        Enumeration<Answers> iter = answers.elements();
        int count = 0;
        int people = 0;

        while (iter.hasMoreElements())
        {
            Answers a = iter.nextElement();

            count += a.numberOfTrueAnswers();
            people += a.numberOfPeopleInGroup();
        }

        System.out.println("The number of questions to which anyone answered 'yes': "+count);
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const Promise = global.Promise || require('bluebird') // eslint-disable-line global-require
const rq = require('request-promise')
const assert = require('assert')

/**
 * @param {object} settings
 * @param {string} settings.apiUrl
 * @param {string} settings.apiKey
 * @return {Primotexto}
 */
function Primotexto(settings) {
  this.baseApiUrl = settings.apiUrl
  this.apiKey = settings.apiKey

  return this
}

Primotexto._internals = {}

/**
 * Verify and format form data to send
 * @param {string} type
 * @param {object} options
 * @return {object}
 */
Primotexto._internals.formatData = function (type, options) {
  const data = {}

  assert(options, 'Parameters ("options") should be an object (current: "' + JSON.stringify(options) + '").')
  assert(options.number, 'Receiver phone number ("number") is required (current: "' + options.number + '").')
  assert(options.message, 'Content of the sms ("message") is required (current: "' + options.message + '").')

  data.number = options.number
  data.message = options.message
  data.sender = options.sender
  data.campaignName = options.campaignName
  data.category = options.category
  data.date = options.date

  return data
}

/**
 * Verify and format form data to send
 * @param {string} type
 * @param {object} options
 * @param {function} callback
 * @return {Promise}
 */
Primotexto.prototype.send = function (type, options, callback) {
  const self = this

  return new Promise(function (resolve, reject) {
    const cb = function (err, res) {
      if (callback) {
        callback(err, res)
      } else if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    }

    type = type !== 'marketing'
    const relativeApiUrl = type ? '/v2/notification/messages/send' : '/v2/marketing/messages/send'
    const data = Primotexto._internals.formatData(type, options)

    const params = {
      method: 'POST',
      uri: self.baseApiUrl + relativeApiUrl,
      headers: {
        'X-Primotexto-ApiKey': self.apiKey
      },
      body: data,
      json: true
    }

    rq.post(params)
      .then(function (res) {
        cb(null, res)
      })
      .catch(function (err) {
        cb(err)
      })
  })
}

module.exports = Primotexto


text:
<!DOCTYPE html >

          <title></title>
          <meta name="description" content="" />
          <meta name="keywords" content="" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

CompositeSubscription

subscriptions

ComputationScheduler

schedulers

ConnectableObservable

observables

cache

Observable

collect

Observable

combineLatest

Observable

combineLatestWith

Observable

concat

Observable

concatEager

Observable

concatMap

Observable

concatMapEager

Observable

connect

ConnectableObservable

contains

Observable

convertComparisonFuncToRxFunc2

ImplicitFunctionConversions

convertTakeWhileFuncToRxFunc2

ImplicitFunctionConversions

count

Observable

countLong

Observable

create

Observable

createWorker

Scheduler


text:
using std::min;
using std::max;
using std::swap;
using std::reverse;

#include <cstdio>

#include <unordered_map>
using std::unordered_map;

#include <sstream>
#include <vector>
using std::vector;

#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include <gtest/gtest.h>
#include "s2.h"
#include "s2latlng.h"
#include "s2testing.h"
#include "util/math/mathutil.h"

#if 0
#define int8 HTM_int8  // To avoid conflicts with our own 'int8'
#include "third_party/htm/include/SpatialIndex.h"
#include "third_party/htm/include/RangeConvex.h"
#undef int8
#endif

#define FLAGS_iters 20000000
//             "Number of iterations for timing tests with optimized build");

#define FLAGS_htm_level 29
// "Maximum HTM level to use");
#define FLAGS_build_level 5
// "HTM build level to use");

static S2CellId GetCellId(double lat_degrees, double lng_degrees) {
  S2CellId id = S2CellId::FromLatLng(S2LatLng::FromDegrees(lat_degrees,
                                                           lng_degrees));
  LOG(INFO) << hex << id.id();
  return id;
}

TEST(S2CellId, DefaultConstructor) {
  S2CellId id;
  EXPECT_EQ(id.id(), 0);
  EXPECT_FALSE(id.is_valid());
}

TEST(S2CellId, FaceDefinitions) {
  EXPECT_EQ(GetCellId(0, 0).face(), 0);
  EXPECT_EQ(GetCellId(0, 90).face(), 1);
  EXPECT_EQ(GetCellId(90, 0).face(), 2);
  EXPECT_EQ(GetCellId(0, 180).face(), 3);
  EXPECT_EQ(GetCellId(0, -90).face(), 4);
  EXPECT_EQ(GetCellId(-90, 0).face(), 5);
}

TEST(S2CellId, ParentChildRelationships) {
  S2CellId id = S2CellId::FromFacePosLevel(3, 0x12345678,
                                           S2CellId::kMaxLevel - 4);
  EXPECT_TRUE(id.is_valid());
  EXPECT_EQ(id.face(), 3);
  EXPECT_EQ(id.pos(), 0x12345700);
  EXPECT_EQ(id.level(), S2CellId::kMaxLevel - 4);
  EXPECT_FALSE(id.is_leaf());

  EXPECT_EQ(id.child_begin(id.level() + 2).pos(), 0x12345610);
  EXPECT_EQ(id.child_begin().pos(), 0x12345640);
  EXPECT_EQ(id.parent().pos(), 0x12345400);
  EXPECT_EQ(id.parent(id.level() - 2).pos(), 0x12345000);

  // Check ordering of children relative to parents.
  EXPECT_LT(id.child_begin(), id);
  EXPECT_GT(id.child_end(), id);
  EXPECT_EQ(id.child_begin().next().next().next().next(), id.child_end());
  EXPECT_EQ(id.child_begin(S2CellId::kMaxLevel), id.range_min());
  EXPECT_EQ(id.child_end(S2CellId::kMaxLevel), id.range_max().next());

  // Check that cells are represented by the position of their center
  // along the Hilbert curve.
  EXPECT_EQ(id.range_min().id() + id.range_max().id(), 2 * id.id());
}

TEST(S2CellId, Wrapping) {
  // Check wrapping from beginning of Hilbert curve to end and vice versa.
  EXPECT_EQ(S2CellId::Begin(0).prev_wrap(), S2CellId::End(0).prev());

  EXPECT_EQ(S2CellId::Begin(S2CellId::kMaxLevel).prev_wrap(),
            S2CellId::FromFacePosLevel(
                5, ~static_cast<uint64>(0) >> S2CellId::kFaceBits,
                S2CellId::kMaxLevel));
  EXPECT_EQ(S2CellId::Begin(S2CellId::kMaxLevel).advance_wrap(-1),
            S2CellId::FromFacePosLevel(
                5, ~static_cast<uint64>(0) >> S2CellId::kFaceBits,
                S2CellId::kMaxLevel));

  EXPECT_EQ(S2CellId::End(4).prev().next_wrap(), S2CellId::Begin(4));
  EXPECT_EQ(S2CellId::End(4).advance(-1).advance_wrap(1), S2CellId::Begin(4));

  EXPECT_EQ(S2CellId::End(S2CellId::kMaxLevel).prev().next_wrap(),
            S2CellId::FromFacePosLevel(0, 0, S2CellId::kMaxLevel));
  EXPECT_EQ(S2CellId::End(S2CellId::kMaxLevel).advance(-1).advance_wrap(1),
            S2CellId::FromFacePosLevel(0, 0, S2CellId::kMaxLevel));
}

TEST(S2CellId, Advance) {
  S2CellId id = S2CellId::FromFacePosLevel(3, 0x12345678,
                                           S2CellId::kMaxLevel - 4);
  // Check basic properties of advance().
  EXPECT_EQ(S2CellId::Begin(0).advance(7), S2CellId::End(0));
  EXPECT_EQ(S2CellId::Begin(0).advance(12), S2CellId::End(0));
  EXPECT_EQ(S2CellId::End(0).advance(-7), S2CellId::Begin(0));
  EXPECT_EQ(S2CellId::End(0).advance(-12000000), S2CellId::Begin(0));
  int num_level_5_cells = 6 << (2 * 5);
  EXPECT_EQ(S2CellId::Begin(5).advance(500),
            S2CellId::End(5).advance(500 - num_level_5_cells));
  EXPECT_EQ(id.child_begin(S2CellId::kMaxLevel).advance(256),
            id.next().child_begin(S2CellId::kMaxLevel));
  EXPECT_EQ(S2CellId::FromFacePosLevel(1, 0, S2CellId::kMaxLevel)
            .advance(static_cast<int64>(4) << (2 * S2CellId::kMaxLevel)),
            S2CellId::FromFacePosLevel(5, 0, S2CellId::kMaxLevel));

  // Check basic properties of advance_wrap().
  EXPECT_EQ(S2CellId::Begin(0).advance_wrap(7),
            S2CellId::FromFacePosLevel(1, 0, 0));
  EXPECT_EQ(S2CellId::Begin(0).advance_wrap(12), S2CellId::Begin(0));
  EXPECT_EQ(S2CellId::FromFacePosLevel(5, 0, 0).advance_wrap(-7),
            S2CellId::FromFacePosLevel(4, 0, 0));
  EXPECT_EQ(S2CellId::Begin(0).advance_wrap(-12000000), S2CellId::Begin(0));
  EXPECT_EQ(S2CellId::Begin(5).advance_wrap(6644),
            S2CellId::Begin(5).advance_wrap(-11788));
  EXPECT_EQ(id.child_begin(S2CellId::kMaxLevel).advance_wrap(256),
            id.next().child_begin(S2CellId::kMaxLevel));
  EXPECT_EQ(S2CellId::FromFacePosLevel(5, 0, S2CellId::kMaxLevel)
            .advance_wrap(static_cast<int64>(2) << (2 * S2CellId::kMaxLevel)),
            S2CellId::FromFacePosLevel(1, 0, S2CellId::kMaxLevel));
}

TEST(S2CellId, Inverses) {
  // Check the conversion of random leaf cells to S2LatLngs and back.
  for (int i = 0; i < 200000; ++i) {
    S2CellId id = S2Testing::GetRandomCellId(S2CellId::kMaxLevel);
    EXPECT_TRUE(id.is_leaf());
    EXPECT_EQ(id.level(), S2CellId::kMaxLevel);
    S2LatLng center = id.ToLatLng();
    EXPECT_EQ(S2CellId::FromLatLng(center).id(), id.id());
  }
}

TEST(S2CellId, Tokens) {
  // Test random cell ids at all levels.
  for (int i = 0; i < 10000; ++i) {
    S2CellId id = S2Testing::GetRandomCellId();
    string token = id.ToToken();
    EXPECT_LE(token.size(), 16);
    EXPECT_EQ(S2CellId::FromToken(token), id);
  }
  // Check that invalid cell ids can be encoded.
  string token = S2CellId::None().ToToken();
  EXPECT_EQ(S2CellId::FromToken(token), S2CellId::None());
}

static const int kMaxExpandLevel = 3;

static void ExpandCell(S2CellId const& parent, vector<S2CellId>* cells,
                       unordered_map<S2CellId, S2CellId>* parent_map) {
  cells->push_back(parent);
  if (parent.level() == kMaxExpandLevel) return;
  int i, j, orientation;
  int face = parent.ToFaceIJOrientation(&i, &j, &orientation);
  EXPECT_EQ(face, parent.face());

  S2CellId child = parent.child_begin();
  for (int pos = 0; child != parent.child_end(); child = child.next(), ++pos) {
    // Do some basic checks on the children
    EXPECT_EQ(parent.child(pos), child);
    EXPECT_EQ(child.level(), parent.level() + 1);
    EXPECT_FALSE(child.is_leaf());
    int child_orientation;
    EXPECT_EQ(child.ToFaceIJOrientation(&i, &j, &child_orientation), face);
    EXPECT_EQ(child_orientation, orientation ^ S2::kPosToOrientation[pos]);

    (*parent_map)[child] = parent;
    ExpandCell(child, cells, parent_map);
  }
}

TEST(S2CellId, Containment) {
  // Test contains() and intersects().
  unordered_map<S2CellId, S2CellId> parent_map;
  vector<S2CellId> cells;
  for (int face = 0; face < 6; ++face) {
    ExpandCell(S2CellId::FromFacePosLevel(face, 0, 0), &cells, &parent_map);
  }
  for (int i = 0; i < cells.size(); ++i) {
    for (int j = 0; j < cells.size(); ++j) {
      bool contained = true;
      for (S2CellId id = cells[j]; id != cells[i]; id = parent_map[id]) {
        if (parent_map.find(id) == parent_map.end()) {
          contained = false;
          break;
        }
      }
      EXPECT_EQ(cells[i].contains(cells[j]), contained);
      EXPECT_EQ(cells[j] >= cells[i].range_min() &&
                cells[j] <= cells[i].range_max(), contained);
      EXPECT_EQ(cells[i].intersects(cells[j]),
                cells[i].contains(cells[j]) || cells[j].contains(cells[i]));
    }
  }
}

static int const kMaxWalkLevel = 8;

TEST(S2CellId, Continuity) {
  // Make sure that sequentially increasing cell ids form a continuous
  // path over the surface of the sphere, i.e. there are no
  // discontinuous jumps from one region to another.

  double max_dist = S2::kMaxEdge.GetValue(kMaxWalkLevel);
  S2CellId end = S2CellId::End(kMaxWalkLevel);
  S2CellId id = S2CellId::Begin(kMaxWalkLevel);
  for (; id != end; id = id.next()) {
    EXPECT_LE(id.ToPointRaw().Angle(id.next_wrap().ToPointRaw()), max_dist);
    EXPECT_EQ(id.advance_wrap(1), id.next_wrap());
    EXPECT_EQ(id.next_wrap().advance_wrap(-1), id);

    // Check that the ToPointRaw() returns the center of each cell
    // in (s,t) coordinates.
    double u, v;
    S2::XYZtoFaceUV(id.ToPointRaw(), &u, &v);
    static double const kCellSize = 1.0 / (1 << kMaxWalkLevel);
    EXPECT_NEAR(remainder(S2::UVtoST(u), 0.5 * kCellSize), 0.0, 1e-15);
    EXPECT_NEAR(remainder(S2::UVtoST(v), 0.5 * kCellSize), 0.0, 1e-15);
  }
}

TEST(S2CellId, Coverage) {
  // Make sure that random points on the sphere can be represented to the
  // expected level of accuracy, which in the worst case is sqrt(2/3) times
  // the maximum arc length between the points on the sphere associated with
  // adjacent values of "i" or "j".  (It is sqrt(2/3) rather than 1/2 because
  // the cells at the corners of each face are stretched -- they have 60 and
  // 120 degree angles.)

  double max_dist = 0.5 * S2::kMaxDiag.GetValue(S2CellId::kMaxLevel);
  for (int i = 0; i < 1000000; ++i) {
    S2Point p = S2Testing::RandomPoint();
    S2Point q = S2CellId::FromPoint(p).ToPointRaw();
    EXPECT_LE(p.Angle(q), max_dist);
  }
}

static void TestAllNeighbors(S2CellId const& id, int level) {
  DCHECK_GE(level, id.level());
  DCHECK_LT(level, S2CellId::kMaxLevel);

  // We compute AppendAllNeighbors, and then add in all the children of "id"
  // at the given level.  We then compare this against the result of finding
  // all the vertex neighbors of all the vertices of children of "id" at the
  // given level.  These should give the same result.
  vector<S2CellId> all, expected;
  id.AppendAllNeighbors(level, &all);
  S2CellId end = id.child_end(level + 1);
  for (S2CellId c = id.child_begin(level + 1); c != end; c = c.next()) {
    all.push_back(c.parent());
    c.AppendVertexNeighbors(level, &expected);
  }
  // Sort the results and eliminate duplicates.
  sort(all.begin(), all.end());
  sort(expected.begin(), expected.end());
  all.erase(unique(all.begin(), all.end()), all.end());
  expected.erase(unique(expected.begin(), expected.end()), expected.end());
  EXPECT_EQ(expected, all);
}

TEST(S2CellId, Neighbors) {
  // Check the edge neighbors of face 1.
  static int out_faces[] = { 5, 3, 2, 0 };
  S2CellId face_nbrs[4];
  S2CellId::FromFacePosLevel(1, 0, 0).GetEdgeNeighbors(face_nbrs);
  for (int i = 0; i < 4; ++i) {
    EXPECT_TRUE(face_nbrs[i].is_face());
    EXPECT_EQ(face_nbrs[i].face(), out_faces[i]);
  }

  // Check the vertex neighbors of the center of face 2 at level 5.
  vector<S2CellId> nbrs;
  S2CellId::FromPoint(S2Point(0, 0, 1)).AppendVertexNeighbors(5, &nbrs);
  sort(nbrs.begin(), nbrs.end());
  for (int i = 0; i < 4; ++i) {
    EXPECT_EQ(nbrs[i], S2CellId::FromFaceIJ(
                 2, (1 << 29) - (i < 2), (1 << 29) - (i == 0 || i == 3))
             .parent(5));
  }
  nbrs.clear();

  // Check the vertex neighbors of the corner of faces 0, 4, and 5.
  S2CellId id = S2CellId::FromFacePosLevel(0, 0, S2CellId::kMaxLevel);
  id.AppendVertexNeighbors(0, &nbrs);
  sort(nbrs.begin(), nbrs.end());
  EXPECT_EQ(nbrs.size(), 3);
  EXPECT_EQ(nbrs[0], S2CellId::FromFacePosLevel(0, 0, 0));
  EXPECT_EQ(nbrs[1], S2CellId::FromFacePosLevel(4, 0, 0));
  EXPECT_EQ(nbrs[2], S2CellId::FromFacePosLevel(5, 0, 0));

  // Check that AppendAllNeighbors produces results that are consistent
  // with AppendVertexNeighbors for a bunch of random cells.
  for (int i = 0; i < 1000; ++i) {
    S2CellId id = S2Testing::GetRandomCellId();
    if (id.is_leaf()) id = id.parent();

    // TestAllNeighbors computes approximately 2**(2*(diff+1)) cell ids,
    // so it's not reasonable to use large values of "diff".
    int max_diff = min(6, S2CellId::kMaxLevel - id.level() - 1);
    int level = id.level() + S2Testing::rnd.Uniform(max_diff);
    TestAllNeighbors(id, level);
  }
}

TEST(S2CellId, OutputOperator) {
  S2CellId cell(0xbb04000000000000ULL);
  ostringstream s;
  s << cell;
  EXPECT_EQ("5/31200", s.str());
}

TEST(S2CellId, ToPointBenchmark) {
  // This "test" is really a benchmark, so skip it unless we're optimized.
  if (DEBUG_MODE) return;

  // Test speed of conversions from points to leaf cells.
  double control_start = S2Testing::GetCpuTime();
  S2CellId begin = S2CellId::Begin(S2CellId::kMaxLevel);
  S2CellId end = S2CellId::End(S2CellId::kMaxLevel);
  uint64 delta = (begin.id() - end.id()) / FLAGS_iters;
  delta &= ~static_cast<uint64>(1);  // Make sure all ids are leaf cells.

  S2CellId id = begin;
  double sum = 0;
  for (int i = FLAGS_iters; i > 0; --i) {
    sum += static_cast<double>(id.id());
    id = S2CellId(id.id() + delta);
  }
  double control_time = S2Testing::GetCpuTime() - control_start;
  printf("\tControl:    %8.3f usecs\n", 1e6 * control_time / FLAGS_iters);
  EXPECT_NE(sum, 0);  // Don't let the loop get optimized away.

  double test_start = S2Testing::GetCpuTime();
  sum = 0;
  id = begin;
  for (int i = FLAGS_iters; i > 0; --i) {
    sum += id.ToPointRaw()[0];
    id = S2CellId(id.id() + delta);
  }
  double test_time = S2Testing::GetCpuTime() - test_start - control_time;
  printf("\tToPointRaw: %8.3f usecs\n", 1e6 * test_time / FLAGS_iters);
  EXPECT_NE(sum, 0);  // Don't let the loop get optimized away.

  test_start = S2Testing::GetCpuTime();
  sum = 0;
  id = begin;
  for (int i = FLAGS_iters; i > 0; --i) {
    sum += id.ToPoint()[0];
    id = S2CellId(id.id() + delta);
  }
  test_time = S2Testing::GetCpuTime() - test_start - control_time;
  printf("\tToPoint:    %8.3f usecs\n", 1e6 * test_time / FLAGS_iters);
  EXPECT_NE(sum, 0);  // Don't let the loop get optimized away.
}

TEST(S2CellId, FromPointBenchmark) {
  // This "test" is really a benchmark, so skip it unless we're optimized.
  if (DEBUG_MODE) return;

  // The sample points follow a spiral curve that completes one revolution
  // around the z-axis every 1/dt samples.  The z-coordinate increases
  // from -4 to +4 over FLAGS_iters samples.

  S2Point start(1, 0, -4);
  double dz = (-2 * start.z()) / FLAGS_iters;
  double dt = 1.37482937133e-4;

  // Test speed of conversions from leaf cells to points.
  double control_start = S2Testing::GetCpuTime();
  uint64 isum = 0;
  S2Point p = start;
  for (int i = FLAGS_iters; i > 0; --i) {
    // Cheap rotation around the z-axis (spirals inward slightly
    // each revolution).
    p += S2Point(-dt * p.y(), dt * p.x(), dz);
    isum += MathUtil::FastIntRound(p[0] + p[1] + p[2]);
  }
  double control_time = S2Testing::GetCpuTime() - control_start;
  printf("\tControl:    %8.3f usecs\n", 1e6 * control_time / FLAGS_iters);
  EXPECT_NE(isum, 0);  // Don't let the loop get optimized away.

  double test_start = S2Testing::GetCpuTime();
  isum = 0;
  p = start;
  for (int i = FLAGS_iters; i > 0; --i) {
    p += S2Point(-dt * p.y(), dt * p.x(), dz);
    isum += S2CellId::FromPoint(p).id();
  }
  double test_time = S2Testing::GetCpuTime() - test_start - control_time;
  printf("\tFromPoint:  %8.3f usecs\n", 1e6 * test_time / FLAGS_iters);
  EXPECT_NE(isum, 0);  // Don't let the loop get optimized away.
}

#if 0
TEST(S2CellId, HtmBenchmark) {
  // This "test" is really a benchmark, so skip it unless we're optimized.
  if (DEBUG_MODE) return;

  // The HTM methods are about 100 times slower than the S2CellId methods,
  // so we adjust the number of iterations accordingly.
  int htm_iters = FLAGS_iters / 100;

  SpatialVector start(1, 0, -4);
  double dz = (-2 * start.z()) / htm_iters;
  double dt = 1.37482937133e-4;

  double test_start = S2Testing::GetCpuTime();
  uint64 mem_start = MemoryUsage(0);
  MallocInterface* mi = MallocInterface::instance();
  size_t heap_start, heap_end;
  CHECK(mi->GetNumericProperty("generic.current_allocated_bytes", &heap_start));
  SpatialIndex htm(FLAGS_htm_level, FLAGS_build_level);
  double constructor_time = S2Testing::GetCpuTime() - test_start;
  printf("\tHTM constructor time:  %12.3f ms\n", 1e3 * constructor_time);
  printf("\tHTM heap size increase:   %9lld\n", MemoryUsage(0) - mem_start);
  CHECK(mi->GetNumericProperty("generic.current_allocated_bytes", &heap_end));
  printf("\tHTM heap bytes allocated: %9u\n", heap_end - heap_start);

  test_start = S2Testing::GetCpuTime();
  double sum = 0;
  SpatialVector v = start;
  for (int i = htm_iters; i > 0; --i) {
    v.set(v.x() - dt * v.y(), v.y() + dt * v.x(), v.z() + dz);
    sum += v.x();
  }
  double htm_control = S2Testing::GetCpuTime() - test_start;
  printf("\tHTM Control:   %8.3f usecs\n", 1e6 * htm_control / htm_iters);
  EXPECT_NE(sum, 0);  // Don't let the loop get optimized away.

  // Keeping the returned ids in a vector adds a negligible amount of time
  // to the idByPoint test and makes it much easier to test pointById.
  vector<uint64> ids(htm_iters);
  test_start = S2Testing::GetCpuTime();
  v = start;
  for (int i = htm_iters; i > 0; --i) {
    v.set(v.x() - dt * v.y(), v.y() + dt * v.x(), v.z() + dz);
    ids[i-1] = htm.idByPoint(v);
  }
  double idByPoint_time = S2Testing::GetCpuTime() - test_start - htm_control;
  printf("\tHTM FromPoint: %8.3f usecs\n",
          1e6 * idByPoint_time / htm_iters);

  test_start = S2Testing::GetCpuTime();
  sum = 0;
  v = start;
  for (int i = htm_iters; i > 0; --i) {
    SpatialVector v2;
    htm.pointById(v2, ids[i-1]);
    sum += v2.x();
  }
  double pointById_time = S2Testing::GetCpuTime() - test_start;
  printf("\tHTM ToPoint:   %8.3f usecs\n",
          1e6 * pointById_time / htm_iters);
  EXPECT_NE(sum, 0);  // Don't let the loop get optimized away.
}
#endif


text:
CC ?= gcc
CXX ?= g++
CXXFLAGS += -I ../src/ -I ./ -DLINUX
LDFLAGS += -lrt -lpthread

ifeq ($(build),debug)
	CXXFLAGS += -c -g2 -O0 \
		-Wall -Weffc++ \
		-Wextra -Wcast-align \
		-Wchar-subscripts  -Wcomment -Wconversion \
		-Wdisabled-optimization \
		-Wfloat-equal  -Wformat  -Wformat=2 \
		-Wformat-nonliteral -Wformat-security  \
		-Wformat-y2k \
		-Wimplicit  -Wimport  -Winit-self  -Winline \
		-Winvalid-pch   \
		-Wunsafe-loop-optimizations  -Wlong-long -Wmissing-braces \
		-Wmissing-field-initializers -Wmissing-format-attribute   \
		-Wmissing-include-dirs -Wmissing-noreturn \
		-Wpacked  -Wparentheses  -Wpointer-arith \
		-Wredundant-decls -Wreturn-type \
		-Wsequence-point  -Wshadow -Wsign-compare  -Wstack-protector \
		-Wstrict-aliasing -Wstrict-aliasing=2 -Wswitch  -Wswitch-default \
		-Wswitch-enum -Wtrigraphs  -Wuninitialized \
		-Wunknown-pragmas  -Wunreachable-code -Wunused \
		-Wunused-function  -Wunused-label  \
		-Wunused-value  -Wunused-variable \
		-Wvolatile-register-var  -Wwrite-strings

	# Disable some warnings
	CXXFLAGS += -Wno-variadic-macros -Wno-unused-parameter -Wno-vla

	# Uncomment this to get pedantic warnings:
	#CXXFLAGS += -pedantic -Wvariadic-macros -Wunused-parameter -Waggregate-return -Wcast-qual -Wpadded
else
	CXXFLAGS += -c -O3 -w
	LDFLAGS += -s
endif

ifeq ($(target),raspberry)
	CXXFLAGS += -DRASPBERRY
	LDFLAGS += -lwiringPi
endif

SOURCES=main.cpp \
	../src/utility/BlynkDebug.cpp \
	../src/utility/BlynkHandlers.cpp \
	../src/utility/BlynkTimer.cpp

OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=blynk

all: $(SOURCES) $(EXECUTABLE)

clean:
	-rm $(OBJECTS) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
	$(CXX) $(OBJECTS) $(LDFLAGS) -o $@

.cpp.o:
	$(CXX) $(CXXFLAGS) $< -o $@


text:
package com.tajchert.cryptsy.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.util.SparseArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MarketDataSource {
	private SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());

	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;

	List<Market> markets;
	private String[] marketColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MARKET_ID,
			 MySQLiteHelper.COLUMN_SUBSCRIBED , MySQLiteHelper.COLUMN_PRICE_POINT, MySQLiteHelper.COLUMN_PRICE_POINT_DOL
			, MySQLiteHelper.COLUMN_CODE_PRIMARY, MySQLiteHelper.COLUMN_CODE_SECONDARY, MySQLiteHelper.COLUMN_NAME_FULL};
	private String[] priceColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MARKET_ID,
			 MySQLiteHelper.COLUMN_DATE, MySQLiteHelper.COLUMN_PRICE, MySQLiteHelper.COLUMN_PRICE_DOL};
	/*
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MARKET_ID, MySQLiteHelper.COLUMN_DATE ,
			MySQLiteHelper.COLUMN_PRICE, MySQLiteHelper.COLUMN_SUBSCRIBED , MySQLiteHelper.COLUMN_PRICE_POINT, MySQLiteHelper.COLUMN_PRICE_DOL
			, MySQLiteHelper.COLUMN_CODE_PRIMARY, MySQLiteHelper.COLUMN_CODE_SECONDARY, MySQLiteHelper.COLUMN_NAME_FULL};*/

	public MarketDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
		Calendar date = Calendar.getInstance();
		date.setTimeInMillis(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 7));//DELETE older then 7 days
		database.execSQL("DELETE FROM " + MySQLiteHelper.TABLE_PRICES + " WHERE " + MySQLiteHelper.COLUMN_DATE + " < '"+iso8601Format.format(date.getTime())+"'");
		database.execSQL("VACUUM");
	}

	public void close() {
		dbHelper.close();
	}
	public boolean exists(int marketid) {
		Cursor cursor = database.rawQuery("Select 1 from "
				+ MySQLiteHelper.TABLE_MARKETS + " where "
				+ MySQLiteHelper.COLUMN_MARKET_ID + " = ?",
				new String[] { marketid+"" });
		boolean exists = (cursor.getCount() > 0);
		cursor.close();
		return exists;
	}
	public void addMarket(double price, double pricedol,  Calendar date, int marketid, boolean subscribed){
		if(exists(marketid)){
			updateRow( price, pricedol,  date,  marketid,  subscribed);
			Log.d("CryptoCoins", "UPDATE");
		}else{
			//createMarket( price,  date,  marketid,  subscribed);
			Log.d("CryptoCoins", "CREATE");
		}
	}
	public void updateListRow(int marketid, boolean subscribed) {

		ContentValues values = new ContentValues();
		if(subscribed){
			Log.d("CryptoCoins", "1");
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 1);
		}else{
			Log.d("CryptoCoins", "0");
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 0);
		}
		database.update(MySQLiteHelper.TABLE_MARKETS, values, MySQLiteHelper.COLUMN_MARKET_ID + " = " + marketid, null);
		/*
		Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, allColumns, MySQLiteHelper.COLUMN_MARKET_ID +" = "+ marketid, null,null, null, null);
		cursor.moveToFirst();
		Market newSpeed = cursorToMarket(cursor);
		Log.d("CryptoCoins", "newSpeed: " +newSpeed.marketid +":"+ newSpeed.isSubscribed);

		cursor.close();
		return newSpeed;*/
	}
	public void updateRow(double price, double pricedol, Calendar date, int marketid, boolean subscribed) {
		String dateS = iso8601Format.format(date.getTime());
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_PRICE, price);
		values.put(MySQLiteHelper.COLUMN_PRICE_DOL, price);
		values.put(MySQLiteHelper.COLUMN_DATE, dateS);
		if(subscribed){
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 1);
		}else{
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 0);
		}
		database.update(MySQLiteHelper.TABLE_MARKETS, values, MySQLiteHelper.COLUMN_MARKET_ID + " = " + marketid, null);

	}

	public void createMarketPrice(double price, double pricedol, Calendar date, int marketid) {
		String dateS = iso8601Format.format(date.getTime());
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_MARKET_ID, marketid);
		values.put(MySQLiteHelper.COLUMN_PRICE, price);
		values.put(MySQLiteHelper.COLUMN_PRICE_DOL, pricedol);
		values.put(MySQLiteHelper.COLUMN_DATE, dateS);
		database.insert(MySQLiteHelper.TABLE_PRICES, null, values);
	}
	public void updateMarketPricePoint(int marketid, double pricepoint, double pricepointdol) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_PRICE_POINT, pricepoint);
		values.put(MySQLiteHelper.COLUMN_PRICE_POINT_DOL, pricepointdol);
		database.update(MySQLiteHelper.TABLE_MARKETS, values, MySQLiteHelper.COLUMN_MARKET_ID + " = " + marketid, null);
	}
	/*public Market createMarket(String fullName, String primarycode, String secondarycode, double price, double priceDol,
			double pricePoint, double dolPoint, Calendar date, int marketid, boolean subscribed) {
		if(exists(marketid)){
			return null;
		}else{
			String dateS = iso8601Format.format(date.getTime());
			Log.d("CryptoCoins", "Creating new row.");
			ContentValues values = new ContentValues();
			values.put(MySQLiteHelper.COLUMN_PRICE, price);
			values.put(MySQLiteHelper.COLUMN_DATE, dateS);
			values.put(MySQLiteHelper.COLUMN_PRICE_DOL, priceDol);
			values.put(MySQLiteHelper.COLUMN_PRICE_POINT, pricePoint);
			values.put(MySQLiteHelper.COLUMN_PRICE_POINT_DOL, dolPoint);
			values.put(MySQLiteHelper.COLUMN_CODE_PRIMARY, primarycode);
			values.put(MySQLiteHelper.COLUMN_CODE_SECONDARY, secondarycode);
			values.put(MySQLiteHelper.COLUMN_NAME_FULL, fullName);
			if(subscribed){
				values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 1);
			}else{
				values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 0);
			}
			values.put(MySQLiteHelper.COLUMN_MARKET_ID, marketid);
			long insertId = database.insert(MySQLiteHelper.TABLE_MARKETS, null, values);
			Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
			cursor.moveToFirst();
			Market newSpeed = cursorToMarket(cursor);
			cursor.close();
			return newSpeed;
		}
	}*/
	public Market createMarket(int marketid, boolean subscribed, String primaryCode, String secondaryCode, String fullName) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_MARKET_ID, marketid);
		if(subscribed){
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 1);
		}else{
			values.put(MySQLiteHelper.COLUMN_SUBSCRIBED, 0);
		}
		values.put(MySQLiteHelper.COLUMN_CODE_PRIMARY, primaryCode);
		values.put(MySQLiteHelper.COLUMN_CODE_SECONDARY, secondaryCode);
		values.put(MySQLiteHelper.COLUMN_NAME_FULL, fullName);

		long insertId = database.insert(MySQLiteHelper.TABLE_MARKETS, null, values);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, marketColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,null, null, null);
		cursor.moveToFirst();
		Market newSpeed = cursorToMarket(cursor);
		cursor.close();
		return newSpeed;
	}

	public void deleteMarket(Market market) {
		long id = market.marketid;
		database.delete(MySQLiteHelper.TABLE_MARKETS, MySQLiteHelper.COLUMN_MARKET_ID + " = " + id, null);
	}
	public List<Market> getAllMarkets() {
		markets = new ArrayList<Market>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, marketColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Market mark = cursorToMarket(cursor);
			markets.add(mark);
			cursor.moveToNext();
		}
		cursor.close();
		return markets;
	}
	public SparseArray<Market> getAllSubscibedMarkets() {
		SparseArray tmpmarkets = new SparseArray<Market>();
		try {
			Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, marketColumns, MySQLiteHelper.COLUMN_SUBSCRIBED + " = 1", null, null, null, null);
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				Market speed = cursorToMarket(cursor);
				tmpmarkets.put(speed.marketid, speed);
				cursor.moveToNext();
			}
			cursor.close();
			return tmpmarkets;
		} catch (Exception e) {
			return null;
		}
	}

	public boolean isSubscribedTo(int marketId) {
		if(exists(marketId)) {
			Cursor cursor = database.query(MySQLiteHelper.TABLE_PRICES, priceColumns, MySQLiteHelper.COLUMN_MARKET_ID + " = " + marketId, null, null, null, null);
			cursor.moveToFirst();
			boolean isActive = cursorSubscription(cursor);
			cursor.close();
			return isActive;
		}
		return false;
	}

	public int countLastPrices(int marketId) {
		PriceRecord pRecord = new PriceRecord();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_PRICES, priceColumns, MySQLiteHelper.COLUMN_MARKET_ID+" = " +  marketId , null, null, null, null);

		//Cursor cursor = database.rawQuery("SELECT "+priceColumns +" FROM " + MySQLiteHelper.TABLE_PRICES +" WHERE " + MySQLiteHelper.COLUMN_MARKET_ID+" = " +  marketId , null);
		cursor.moveToFirst();
		Log.d("CryptoCoins", "countLastPrices size: " + cursor.getCount());
		return cursor.getCount();
	}
	public PriceRecord getMarketLastPrice(int marketId) {
		PriceRecord pRecord = new PriceRecord();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_PRICES, priceColumns, MySQLiteHelper.COLUMN_MARKET_ID+" = " +  marketId + " order by date DESC limit 1", null, null, null, null);

		//Cursor cursor = database.rawQuery("SELECT "+priceColumns +" FROM " + MySQLiteHelper.TABLE_PRICES +" WHERE " + MySQLiteHelper.COLUMN_MARKET_ID+" = " +  marketId , null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			//Log.d("CryptoCoins", "got date: " + cursor.getString(2));
			/*Market speed = cursorToMarket(cursor);
			prices[0] = cursor.getDouble(columnIndex);
			tmpmarkets.put(speed.marketid, speed);*/
			pRecord.price = cursor.getDouble(3);
			pRecord.priceDol = cursor.getDouble(4);
			pRecord.setDate(cursor.getString(2));
			cursor.moveToNext();
		}
		cursor.close();
		return pRecord;
	}
	/*public SparseArray<Market> getAllSubscibedMarketsOld() {
		SparseArray tmpmarkets = new SparseArray<Market>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_MARKETS, allColumns, MySQLiteHelper.COLUMN_SUBSCRIBED + " = 1", null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Market speed = cursorToMarket(cursor);
			tmpmarkets.put(speed.marketid, speed);
			Log.d("CryptoCoins", "getAllSubscibedMarkets put: " + speed.marketid);
			cursor.moveToNext();
		}
		cursor.close();
		Log.d("CryptoCoins", "getAllSubscibedMarkets size: " + tmpmarkets.size());
		return tmpmarkets;
	}*/

	private boolean cursorSubscription(Cursor cursor) {
		if(cursor.getInt(2) == 1){
			return true;
		}else{
			return false;
		}
	}

	private Market cursorToMarket(Cursor cursor) {
		/*{ MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_MARKET_ID,
			 MySQLiteHelper.COLUMN_SUBSCRIBED , MySQLiteHelper.COLUMN_PRICE_POINT, MySQLiteHelper.COLUMN_PRICE_POINT_DOL
			, MySQLiteHelper.COLUMN_CODE_PRIMARY, MySQLiteHelper.COLUMN_CODE_SECONDARY, MySQLiteHelper.COLUMN_NAME_FULL};*/
		Market market = new Market();
		market.marketid = cursor.getInt(1);
		//market.setDate(cursor.getString(2));
		//market.lasttradeprice = cursor.getFloat(3);
		if(cursor.getInt(2) == 1){
			market.isSubscribed = true;
		}else{
			market.isSubscribed = false;
		}
		market.pricePoint = cursor.getFloat(3);
		market.pricePointDol = cursor.getFloat(4);
		//Log.d("CryptoCoins", "cursor.getFloat(3): " + cursor.getFloat(3));
		//Log.d("CryptoCoins", "cursor.getFloat(4): " + cursor.getFloat(4));
		try {
			market.primarycode = cursor.getString(5);
			market.secondarycode = cursor.getString(6);
			market.name = cursor.getString(7);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return market;
	}
}


text:
package org.gradle.buildinit.plugins.internal;

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

abstract class TemplateBasedProjectInitDescriptor implements ProjectInitDescriptor {
    private List<TemplateOperation> templateOperations = new ArrayList<TemplateOperation>();

    public void generate() {
        for (TemplateOperation templateOperation : templateOperations) {
            templateOperation.generate();
        }
    }

    protected void register(TemplateOperation templateOperation) {
        this.templateOperations.add(templateOperation);
    }
}


text:
<?php

/* @Framework/Form/form_widget_compound.html.php */
class __TwigTemplate_ccaaa74beb9420bc01f0236ae72ddbdcd21c5eaccb780bd35ae33b016968a4fb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_e11cefa961227f38a4853d1ac13a26e502a37df95d475e75594bc79a2dd96dd9 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_e11cefa961227f38a4853d1ac13a26e502a37df95d475e75594bc79a2dd96dd9->enter($__internal_e11cefa961227f38a4853d1ac13a26e502a37df95d475e75594bc79a2dd96dd9_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Framework/Form/form_widget_compound.html.php"));

        $__internal_ca87da3234a11a5e4131ceef36708aa3f930576e2201e1d37087ec9aad4b82f9 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_ca87da3234a11a5e4131ceef36708aa3f930576e2201e1d37087ec9aad4b82f9->enter($__internal_ca87da3234a11a5e4131ceef36708aa3f930576e2201e1d37087ec9aad4b82f9_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Framework/Form/form_widget_compound.html.php"));

        // line 1
        echo "<div <?php echo \$view['form']->block(\$form, 'widget_container_attributes') ?>>
    <?php if (!\$form->parent && \$errors): ?>
    <?php echo \$view['form']->errors(\$form) ?>
    <?php endif ?>
    <?php echo \$view['form']->block(\$form, 'form_rows') ?>
    <?php echo \$view['form']->rest(\$form) ?>
</div>
";

        $__internal_e11cefa961227f38a4853d1ac13a26e502a37df95d475e75594bc79a2dd96dd9->leave($__internal_e11cefa961227f38a4853d1ac13a26e502a37df95d475e75594bc79a2dd96dd9_prof);

        $__internal_ca87da3234a11a5e4131ceef36708aa3f930576e2201e1d37087ec9aad4b82f9->leave($__internal_ca87da3234a11a5e4131ceef36708aa3f930576e2201e1d37087ec9aad4b82f9_prof);

    }

    public function getTemplateName()
    {
        return "@Framework/Form/form_widget_compound.html.php";
    }

    public function getDebugInfo()
    {
        return array (  25 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("<div <?php echo \$view['form']->block(\$form, 'widget_container_attributes') ?>>
    <?php if (!\$form->parent && \$errors): ?>
    <?php echo \$view['form']->errors(\$form) ?>
    <?php endif ?>
    <?php echo \$view['form']->block(\$form, 'form_rows') ?>
    <?php echo \$view['form']->rest(\$form) ?>
</div>
", "@Framework/Form/form_widget_compound.html.php", "C:\\wamp64\\www\\Ecommerce\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\FrameworkBundle\\Resources\\views\\Form\\form_widget_compound.html.php");
    }
}


text:
<!DOCTYPE HTML>

		<title>Moto Website Template | Blog :: w3layouts</title>
		<link href="css/bootstrap.css" rel='stylesheet' type='text/css' />

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

		<meta name="viewport" content="width=device-width, initial-scale=1">

		</script>

		<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text/css'>

					Moto

Home

About

Services

Blog

Contact

Blog

Home :

Blog

Recent-posts

Visualizing Tweets around Emmy-nominated shows

Written by Garry Walt

19/09

Art

WebDesign

Logotypes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin felis vitae urna auctor sodales. Donec semper justo nec mauris aliquam mattis. Donec faucibus orci quis tortor accumsan, in iaculis ipsum euismod. Phasellus consequat tempus ipsum, in porta magna ultricies cursus. Pellentesque scelerisque orci justo, non elementum purus lacinia id.

Nunc id mi rutrum, sollicitudin elit eget, pretium risus. Quisque molestie nunc sed justo ornare, ipsum lorem mattis urna, eu feugiat augue justo quis risus. Sed vitae lacus dignissim, sodales justo sit amet, tristique justo. Proin eget erat quis leo suscipit laoreet at ac diam. Integer eu interdum mauris. Aenean a aliquam turpis, eu tincidunt urna.

									ReadMore...

London Fashion Week drives more buzz than ever on Twitter

Written by Garry Walt

19/09

Art

WebDesign

Logotypes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin felis vitae urna auctor sodales. Donec semper justo nec mauris aliquam mattis. Donec faucibus orci quis tortor accumsan, in iaculis ipsum euismod. Phasellus consequat tempus ipsum, in porta magna ultricies cursus. Pellentesque scelerisque orci justo, non elementum purus lacinia id.

Nunc id mi rutrum, sollicitudin elit eget, pretium risus. Quisque molestie nunc sed justo ornare, ipsum lorem mattis urna, eu feugiat augue justo quis risus. Sed vitae lacus dignissim, sodales justo sit amet, tristique justo. Proin eget erat quis leo suscipit laoreet at ac diam. Integer eu interdum mauris. Aenean a aliquam turpis, eu tincidunt urna.

									ReadMore...

#RockInRio 2013

Written by Garry Walt

19/09

Art

WebDesign

Logotypes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin felis vitae urna auctor sodales. Donec semper justo nec mauris aliquam mattis. Donec faucibus orci quis tortor accumsan, in iaculis ipsum euismod. Phasellus consequat tempus ipsum, in porta magna ultricies cursus. Pellentesque scelerisque orci justo, non elementum purus lacinia id.

Nunc id mi rutrum, sollicitudin elit eget, pretium risus. Quisque molestie nunc sed justo ornare, ipsum lorem mattis urna, eu feugiat augue justo quis risus. Sed vitae lacus dignissim, sodales justo sit amet, tristique justo. Proin eget erat quis leo suscipit laoreet at ac diam. Integer eu interdum mauris. Aenean a aliquam turpis, eu tincidunt urna.

									ReadMore...

Vine videos that grew on us - Sept 13

Written by Garry Walt

19/09

Art

WebDesign

Logotypes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sollicitudin felis vitae urna auctor sodales. Donec semper justo nec mauris aliquam mattis. Donec faucibus orci quis tortor accumsan, in iaculis ipsum euismod. Phasellus consequat tempus ipsum, in porta magna ultricies cursus. Pellentesque scelerisque orci justo, non elementum purus lacinia id.

Nunc id mi rutrum, sollicitudin elit eget, pretium risus. Quisque molestie nunc sed justo ornare, ipsum lorem mattis urna, eu feugiat augue justo quis risus. Sed vitae lacus dignissim, sodales justo sit amet, tristique justo. Proin eget erat quis leo suscipit laoreet at ac diam. Integer eu interdum mauris. Aenean a aliquam turpis, eu tincidunt urna.

									ReadMore...

1

2

3

4

CaTEGORIES

						<link rel="stylesheet" href="css/vallenato.css" type="text/css" media="screen" charset="utf-8">

Webdesign

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Art design

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Logotypes

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Photography

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Videos

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Other

adipiscing elit.

consectetur

Pellentesque

sollicitudin felis

Tag's

Art

WebDesign

Logotypes

Photo

Video

Other

WEb

Last Comments

										Endy Brown

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

										Millana Watson

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

										Andrew Haching

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

										Bruse Loome

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Contact us

 55 Main St.Toronto, ON M1H 3A5

 (416) 555-5252

 hello@moto.com

Latest posts

  Made With Love In Toronto

  Startup News & Emerging Tech

  Bitcoin Will Soon Rule The World

  Wearable Technology On The Rise

  Learn Web Design In 30 Days!

Latest tweets

Confucius: Life is really simple, but we insist on making it complicated. #famousquotes 8 mins ago

Confucius: Life is really simple, but we insist on making it complicated. #famousquotes 8 mins ago

© Copyright 2014 Template by W3layouts


text:
var tests = require("../dist/test/tests")
var Failure = require("../dist/test/failure").Failure
require("../dist/test/all")
require("../dist/test/browser/all")

var gen = 0

function runTests() {
  var filters = document.location.hash.slice(1).split(",")
  var myGen = ++gen
  var runnable = []
  for (var name in tests.tests) if (tests.filter(name, filters)) runnable.push(name)

  document.querySelector("#output").textContent = ""

  function run(i) {
    var t0 = Date.now()
    for (;; i++) {
      if (gen != myGen) return
      if (i == runnable.length) return finish()
      var name = runnable[i]
      document.querySelector("#info").textContent = (i + 1) + " of " + runnable.length + " tests"
      document.querySelector("#status").textContent = "Running " + name
      document.querySelector("#measure").style.width = (((i + 1) / runnable.length) * 100) + "%"

      try {
        tests.tests[name]()
      } catch(e) {
        logFailure(name, e)
      }
      if (Date.now() > t0 + 200) {
        setTimeout(() => run(i + 1), 50)
        return
      }
    }
  }

  var failed = 0

  function finish() {
    document.querySelector("#info").textContent = "Ran " + runnable.length + " tests"
    var status = document.querySelector("#status")
    status.textContent = failed ? failed + " failed" : "All passed"
    status.className = failed ? "bad" : "good"
  }

  function logFailure(name, err) {
    ++failed
    var elt = document.querySelector("#output").appendChild(document.createElement("pre"))
    var nm = elt.appendChild(document.createElement("a"))
    nm.className = "bad"
    nm.href= "#" + name
    nm.textContent = name
    elt.appendChild(document.createTextNode(": " + err))
    if (!(err instanceof Failure))
      console.log(name + ": " + (err.stack || err))
  }

  setTimeout(() => run(0), 50)
}

runTests()

addEventListener("hashchange", runTests)


text:
<?php

namespace FeedbackFieldBundle\Twig;

class FiltersDatesExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('FiltersDatesMonthly', array($this, 'filtersDatesMonthly')),
        );
    }

    public function filtersDatesMonthly()
    {

        $out = array();

        $create = new \DateTime();
        $subInterval = new \DateInterval("P1M");

        for ($i = 1; $i <= 4; $i++) {

            $from = clone $create;
            $from->setTime(0,0,0);
            $from->setDate($from->format("Y"), $from->format("m"), 1);

            $to = clone $create;
            $to->setTime(23,59,59);
            $to->setDate($from->format("Y"), $from->format("m"), cal_days_in_month(CAL_GREGORIAN, $from->format("m"), $from->format("Y")));

            $out[] = array(
                'label' => $create->format("M Y"),
                'from' => $from,
                'to' => $to,
            );

            $create->sub($subInterval);
        }

        return $out;
    }

    public function getName()
    {
        return 'FiltersDatesExtension';
    }
}


text:
mkdir -p build/network_saves

echo "Compiling ..."
echo ""
g++ src/main_old.cpp src/Network.h src/Network.cpp -o build/old_main -std=c++14
./build/old_main $1
#python src/plotXY.py build/X build/Y


text:
<?php
// This sheet is diplayed when the admin wants to modify perms for registered users
// or remove the profiles of some of them

// The admin has required an action to be done
if (isset($FORM_SEND) && $FORM_SEND == 1)
{
	// A registred user have to be deleted or banished?
	$DELETE_MODE = (stripslashes($submit_type) == A_SHEET1_6)? 1:0;
	$BANISH_MODE = (stripslashes($submit_type) == A_SHEET1_9)? 1:0;

	// Get the list of the users
	$DbLink->query("SELECT username,perms FROM ".C_REG_TBL." WHERE perms != 'admin'");
	$users = Array();
	while (list($username, $perms) = $DbLink->next_record())
	{
		$users[] = $username;
	}
	$DbLink->clean_results();

	for (reset($users); $username=current($users); next($users))
	{
		$usrHash = md5($username);
		$VarName = "user_".$usrHash;
		if (!isset($$VarName)) continue;
		// Delete a profile after having sent a message to the user if he is connected
		if ($DELETE_MODE)
		{
			$VarName = "selected_".$usrHash;
			if (isset($$VarName))
			{
				$uuu = addslashes($username);
				$DbLink->query("DELETE FROM ".C_REG_TBL." WHERE username='$uuu'");
				$DbLink->query("SELECT room FROM ".C_USR_TBL." WHERE username='$uuu' LIMIT 1");
				$in_room = ($DbLink->num_rows() != 0);
				if ($in_room)
				{
					list($room) = $DbLink->next_record();
					$DbLink->clean_results();
					$DbLink->query("SELECT type FROM ".C_MSG_TBL." WHERE room='".addslashes($room)."' LIMIT 1");
					list($type) = $DbLink->next_record();
					$DbLink->clean_results();
					$DbLink->query("UPDATE ".C_USR_TBL." SET status='u' WHERE username='$uuu'");
					$DbLink->query("INSERT INTO ".C_MSG_TBL." VALUES ('$type', '".addslashes($room)."', 'SYS delreg', '', ".time().", '$uuu', 'L_ADM_2')");
				};
				// Optimize the registered users table when a MySQL DB is used
				$DbLink->optimize(C_REG_TBL);
			};
		}
		// Banish an user
		elseif ($BANISH_MODE)
		{
			$VarName = "selected_".$usrHash;
			if (isset($$VarName))
			{
				$uuu = addslashes($username);
				$DbLink->query("SELECT latin1,ip FROM ".C_REG_TBL." WHERE username='$uuu' LIMIT 1");
				list($Latin1, $IP) = $DbLink->next_record();
				$DbLink->clean_results();
				$DbLink->query("SELECT count(*) FROM ".C_BAN_TBL." WHERE username='$uuu' LIMIT 1");
				list($Nb) = $DbLink->next_record();
				$DbLink->clean_results();
				if ($Nb == "0")
				{
					$Until = time() + round(C_BANISH * 60 * 60 * 24);
					if ($Until > 2147483647) $Until = "2147483647";
					$DbLink->query("INSERT INTO ".C_BAN_TBL." VALUES ('$uuu','$Latin1','$IP','**ToDefine**','$Until')");
				};
				$Warning = A_SHEET1_10;
			};
		}
		// Modify perms for a registered user and send him a message if he is connected
		else
		{
			$VarName = "perms_".$usrHash; $ppp = $$VarName;
			$VarName = "rooms_".$usrHash; $rrr = $$VarName;
			$VarName = "old_perms_".$usrHash; $old_ppp = $$VarName;
			$VarName = "old_rooms_".$usrHash; $old_rrr = $$VarName;
			if ($ppp == $old_ppp && $rrr == $old_rrr) continue;
			$uuu = addslashes($username);
			$DbLink->query("UPDATE ".C_REG_TBL." SET perms='$ppp', rooms='$rrr' WHERE username='$uuu'");
			$DbLink->query("SELECT room FROM ".C_USR_TBL." WHERE username='$uuu' LIMIT 1");
			$in_room = ($DbLink->num_rows() != 0);
			if ($in_room)
			{
				list($room) = $DbLink->next_record();
				$DbLink->clean_results();

				// Find the changes in moderated rooms list
				if ($ppp != $old_ppp)
				{
					if ($ppp == 'user')
						$diff_rooms = explode(",", $old_rrr);
					else
						$diff_rooms = explode(",", $rrr);
				}
				else
				{
					$old_rooms_Tab = explode(",",$old_rrr);
					$new_rooms_Tab = explode(",",$rrr);
					$diff_rooms_Tab = array();
					for (reset($old_rooms_Tab); $room2Check=current($old_rooms_Tab); next($old_rooms_Tab))
					{
						if ($room2Check == "") continue;
						if (!room_in($room2Check, $rrr)) $diff_rooms_Tab[] = $room2Check;
					}
					for (reset($new_rooms_Tab); $room2Check=current($new_rooms_Tab); next($new_rooms_Tab))
					{
						if ($room2Check == "") continue;
						if (!room_in($room2Check, $old_rrr)) $diff_rooms_Tab[] = $room2Check;
					}
					unset($old_rooms_Tab);
					unset($new_rooms_Tab);

					if (count($diff_rooms_Tab) > 0)
						$diff_rooms = str_replace(",,",",",ereg_replace("^,|,$","",implode(",",$diff_rooms_Tab)));
					unset($diff_rooms_Tab);
				}

				// Send a message to the user if he chats into one of the 'diff' rooms
				if (room_in(addslashes($room), $diff_rooms))
				{
					if ($ppp == 'moderator' && room_in(addslashes($room), $rrr))	// user becomes moderator for the room he chats into
					{
						$status = "m";
						$message = "sprintf(L_MODERATOR, \"".addslashes(htmlspecialchars(stripslashes($uuu)))."\")";
					}
					else	// user becomes user for the room he chats into
					{
						$status = "r";
						$message = "sprintf(L_ADM_1, \"".addslashes(htmlspecialchars(stripslashes($uuu)))."\")";
					};
					$DbLink->query("UPDATE ".C_USR_TBL." SET status='$status' WHERE username='$uuu'");
					$DbLink->query("SELECT type FROM ".C_MSG_TBL." WHERE room='".addslashes($room)."' LIMIT 1");
					list($type) = $DbLink->next_record();
					$DbLink->clean_results();
					$DbLink->query("INSERT INTO ".C_MSG_TBL." VALUES ('$type', '".addslashes($room)."', 'SYS promote', '', ".time().", '', '$message')");
				};
			}
			else
			{
				$DbLink->clean_results();
			};
		};
	};
};

// Remove profiles of users that have not been chatting for a time > C_REG_DEL
if (!isset($FORM_SEND) && C_REG_DEL != 0) $DbLink->query("DELETE FROM ".C_REG_TBL." WHERE reg_time < ".(time() - C_REG_DEL * 60 * 60 * 24)." AND perms != 'admin'");

// Remove moderator status if no room is specified
$DbLink->query("UPDATE ".C_REG_TBL." SET perms='user' WHERE perms='moderator' AND rooms=''");
?>

<?php echo(A_SHEET1_1); ?>

<?php
if (isset($Warning) && $Warning != "") echo("
$Warning

\n");
?>

<?php
// Ensure at least one registered user exist (exept the administrator) before displaying the modify status
$DbLink->query("SELECT COUNT(*) FROM ".C_REG_TBL." WHERE perms != 'admin' LIMIT 1");
list($count_RegUsers) = $DbLink->next_record();
$DbLink->clean_results();
if ($count_RegUsers != 0)
{
?>

		<FORM ACTION="<?php echo("$From?$URLQueryBody"); ?>" METHOD="POST" AUTOCOMPLETE="OFF" NAME="Form1">
		<INPUT TYPE=hidden NAME="From" value="<?php echo($From); ?>">
		<INPUT TYPE=hidden NAME="user" value="<?php echo(htmlspecialchars(stripslashes($user))); ?>">
		<INPUT TYPE=hidden NAME="pswd" value="<?php echo($pswd); ?>">
		<INPUT TYPE=hidden NAME="sortBy" value="<?php echo($sortBy); ?>">
		<INPUT TYPE=hidden NAME="sortOrder" value="<?php echo($sortOrder); ?>">
		<INPUT TYPE=hidden NAME="startReg" value="<?php echo($startReg); ?>">
		<INPUT TYPE=hidden NAME="FORM_SEND" value="1">

			<TD VALIGN=CENTER ALIGN="<?php echo($CellAlign); ?>">
				<A HREF="<?php echo("$From?$URLQueryBody_SortLinks&sortBy=username"); if ($sortBy == "username") echo("&sortOrder=$New_sortOrder"); ?>"><?php echo(A_SHEET1_2); ?>

				<A HREF="<?php echo("$From?$URLQueryBody_SortLinks&sortBy=reg_time"); if ($sortBy == "reg_time") echo("&sortOrder=$New_sortOrder"); ?>"><?php echo(A_SHEET1_11); ?>

				<A HREF="<?php echo("$From?$URLQueryBody_SortLinks&sortBy=ip"); if ($sortBy == "ip") echo("&sortOrder=$New_sortOrder"); ?>"><?php echo(A_SHEET2_2); ?>

				<A HREF="<?php echo("$From?$URLQueryBody_SortLinks&sortBy=perms"); if ($sortBy == "perms") echo("&sortOrder=$New_sortOrder"); ?>"><?php echo(A_SHEET1_3); ?>

				<?echo(A_SHEET1_4)?> *

		<?php
		function special_char($str,$lang)
		{
			return ($lang ? htmlentities($str) : htmlspecialchars($str));
		}

		$lastPage_startReg = floor(($count_RegUsers - 1) / 10) * 10;
		if ($startReg > $lastPage_startReg) $startReg = $lastPage_startReg;
		if (C_DB_TYPE == "mysql") $limits = " LIMIT $startReg,10";
		elseif (C_DB_TYPE == "pgsql") $limits = " LIMIT 10 OFFSET $startReg";
		else $limits = "";

		$DbLink->query("SELECT username,latin1,perms,rooms,reg_time,ip FROM ".C_REG_TBL." WHERE perms != 'admin' ORDER BY $sortBy $sortOrder".$limits);
		while (list($username,$Latin1,$perms,$rooms,$lastTime,$IP) = $DbLink->next_record())
		{
			$usrHash = md5($username);
			?>
			<INPUT TYPE="hidden" NAME="user_<?echo($usrHash)?>" VALUE="1">

					<INPUT type=checkbox name="selected_<?echo($usrHash)?>" value="1">

				<TD VALIGN=CENTER ALIGN="<?php echo($CellAlign); ?>">
					<?echo(special_char($username,$Latin1));?>

				<TD VALIGN=CENTER ALIGN="<?php echo($CellAlign); ?>">
					<?echo(date("M j, Y - h:i a",$lastTime + C_TMZ_OFFSET*60*60));?>

					<?php echo($IP); ?>

					<SELECT name="perms_<?echo($usrHash)?>">
						<OPTION value="user"<?if($perms=="user") echo(" SELECTED")?>><?echo(A_USER)?></OPTION>
						<OPTION value="moderator"<?if($perms=="moderator") echo(" SELECTED")?>><?echo(A_MODER)?></OPTION>
					</SELECT>
					<INPUT type="hidden" name="old_perms_<?echo($usrHash)?>" value="<?echo($perms)?>">

					<INPUT type=text name="rooms_<?echo($usrHash)?>" value="<?echo(stripslashes(htmlspecialchars($rooms)))?>" SIZE="40" onChange="reset_perms('<?echo($usrHash)?>');">
					<INPUT type="hidden" name="old_rooms_<?echo($usrHash)?>" value="<?echo(htmlspecialchars($rooms))?>">

			<?
		};
		$DbLink->clean_results();
		?>

				* <?echo(A_SHEET1_5)?>

				<INPUT TYPE="submit" NAME="submit_type" VALUE="<?php echo(A_SHEET1_6); ?>">

				<INPUT TYPE="submit" NAME="submit_type" VALUE="<?php echo(A_SHEET1_9); ?>">

				<INPUT TYPE="submit" NAME="submit_type" VALUE="<?php echo(A_SHEET1_7); ?>">

		</FORM>

			<TD ALIGN="<?php echo($CellAlign); ?>" VALIGN=CENTER WIDTH=70 HEIGHT=20 CLASS=tabtitle>
			<?php
			if ($startReg > 0)
			{
				$downReg = $startReg - 10;
				if ($downReg < 0) $downReg = "0";
				?>
				 <A HREF="<?php echo("$From?$URLQueryBody_MoveLinks&startReg=0"); ?>"><IMG SRC="images/admin/<?php echo($BeginGif); ?>" HEIGHT=20 WIDTH=21 BORDER=0>
				   <A HREF="<?php echo("$From?$URLQueryBody_MoveLinks&startReg=$downReg"); ?>"><IMG SRC="images/admin/<?php echo($DownGif); ?>" HEIGHT=20 WIDTH=20 BORDER=0>
				<?php
			}
			else
			{
				echo("&nbsp");
			};
			?>

				<?php
				$PageNum = ceil(($startReg + 1) / 10);
				$PagesCount = ceil($count_RegUsers / 10);
				echo(sprintf(A_PAGE_CNT,$PageNum,$PagesCount)."   |   $count_RegUsers ".A_MENU_1);
				?>

			<TD ALIGN="<?php echo($CellAlign); ?>" VALIGN=CENTER WIDTH=70 HEIGHT=20 CLASS=tabtitle>
			<?php
			if ($startReg < $lastPage_startReg)
			{
				$upReg = $startReg + 10;
				?>
				 <A HREF="<?php echo("$From?$URLQueryBody_MoveLinks&startReg=$upReg"); ?>"><IMG SRC="images/admin/<?php echo($UpGif); ?>" HEIGHT=20 WIDTH=20 BORDER=0>
				   <A HREF="<?php echo("$From?$URLQueryBody_MoveLinks&startReg=$lastPage_startReg"); ?>"><IMG SRC="images/admin/<?php echo($EndGif); ?>" HEIGHT=20 WIDTH=21 BORDER=0>
				<?php
			}
			else
			{
				echo("&nbsp");
			};
			?>

<?php
}
else
{
?>

	<?php echo(A_SHEET1_8); ?>

<?php
};
?>

<?php
?>


text:
static NSTimeInterval DEFAULT_TIMEOUT = 0.5;

@interface PromiseTests : XCTestCase

@end

@implementation PromiseTests

- (void)testPreResolution
{
    NWPromise *p = [NWPromise promise];

    NSString *obj = @"";
    [p resolve:obj];

    __block NSError *promiseObj = nil;
    p.done(^(id obj) {
        promiseObj = obj;

        XCTAssertFalse([NSThread isMainThread], @"Promise should not be called on main thead");
        [self notify:XCTAsyncTestCaseStatusSucceeded];
    });

    [self waitForTimeout:DEFAULT_TIMEOUT];

    XCTAssertEqualObjects(obj, promiseObj, @"Objects not equal");
    XCTAssertTrue([p isResolved], @"Promise should be resolved");
    XCTAssertFalse([p isRejected], @"Promise should be not rejected");
}

- (void)testPostResolution
{
    NWPromise *p = [NWPromise promise];

    __block NSError *promiseObj = nil;
    p.done(^(id obj) {
        promiseObj = obj;

        XCTAssertFalse([NSThread isMainThread], @"Promise should not be called on main thead");
        [self notify:XCTAsyncTestCaseStatusSucceeded];
    });

    NSString *obj = @"";
    [p resolve:obj];

    [self waitForTimeout:DEFAULT_TIMEOUT];

    XCTAssertEqualObjects(obj, promiseObj, @"Objects not equal");
    XCTAssertTrue([p isResolved], @"Promise should be resolved");
    XCTAssertFalse([p isRejected], @"Promise should be not rejected");
}

#pragma mark Rejection

- (void)testPreRejection
{
    NWPromise *p = [NWPromise promise];

    NSError *error = [NSError new];
    [p reject:error];

    __block NSError *promiseError = nil;
    p.error(^(NSError *error) {
        promiseError = error;

        XCTAssertFalse([NSThread isMainThread], @"Promise should not be called on main thead");
        [self notify:XCTAsyncTestCaseStatusSucceeded];
    });

    [self waitForTimeout:DEFAULT_TIMEOUT];

    XCTAssertEqualObjects(error, promiseError, @"Objects not equal");
    XCTAssertTrue([p isRejected], @"Promise should be rejected");
    XCTAssertFalse([p isResolved], @"Promise should not be resolved");
}

- (void)testPostRejection
{
    NWPromise *p = [NWPromise promise];

    __block NSError *promiseError = nil;
    p.error(^(NSError *error) {
        promiseError = error;

        XCTAssertFalse([NSThread isMainThread], @"Promise should not be called on main thead");
        [self notify:XCTAsyncTestCaseStatusSucceeded];
    });

    NSError *error = [NSError new];
    [p reject:error];

    [self waitForTimeout:DEFAULT_TIMEOUT];

    XCTAssertEqualObjects(error, promiseError, @"");
    XCTAssertTrue([p isRejected], @"Promise should be rejected");
    XCTAssertFalse([p isResolved], @"Promise should not be resolved");
}

@end


text:
Custom Analyzer

 {{errorMessage}}

    <form class="form" role="form">

            Name
            <input ng-disabled="viewOnlyModal"
                   ng-model="name" type="text"
                   class="form-control" id="tname" placeholder="Name">

          Character Filters
          <ul class="list-group"
              ng-show="analyzer.char_filters.length < 1">

None

 0"
              ui-sortable
              ng-model="analyzer.char_filters">

               {{ analyzerCharFilter }}

            <select ng-change="addCharFilterChanged()"
                    ng-model="addCharacterFilterName"
                    class="form-control"
                    id="addCharacterFilters">
              <option ng-repeat="charFilter in charFilterNames">{{charFilter}}</option>
            </select>

            <button ng-click="addCharFilter(this)" type="button"
                    class="btn btn-default pull-right">Add</button>

          Tokenizer
          <select ng-disabled="viewOnlyModal"
                  ng-change="tokenizerChanged()"
                  ng-model="analyzer.tokenizer"
                  class="form-control"
                  id="analyzerTokenizer">
            <option ng-repeat="tokenizer in tokenizerNames">{{tokenizer}}</option>
          </select>

          Token Filters
          <ul class="list-group"
              ng-show="analyzer.token_filters.length < 1">

None

 0"
              ui-sortable
              ng-model="analyzer.token_filters">

               {{ analyzerTokenFilter }}

            <select ng-change="addTokenFilterChanged()"
                    ng-model="addTokenFilterName"
                    class="form-control"
                    id="addTokenFilters">
              <option ng-repeat="tokenFilter in tokenFilterNames">{{tokenFilter}}</option>
            </select>

            <button ng-click="addTokenFilter(this)" type="button"
                    class="btn btn-default pull-right">Add</button>

    </form>

    <button ng-if="viewOnlyModal" class="btn btn-default"
            ng-click="cancel()">Close</button>
    <button ng-if="!viewOnlyModal" class="btn btn-default"
            ng-click="cancel()">Cancel</button>
    <button ng-if="!viewOnlyModal"
            ng-click="build(name)"
            type="button" class="btn btn-primary pull-right">Save</button>


text:
#region S# License

#endregion S# License
namespace StockSharp.ETrade.Native
{
	using System;
	using System.Threading;
	using System.Collections.Generic;
	using Timer = System.Timers.Timer;

	using Ecng.Common;
	using Ecng.Collections;

	using StockSharp.Logging;

	using StockSharp.Localization;

	partial class ETradeClient
	{
		private abstract class ETradeModule
		{
			//private const double _requestsLimitMultiplier = 1d;

			private double _requestsPerSecond;
			//private DateTime _nextIntervalStartsAt;
			private DateTime _lastLimitsUpdateTime;
			//private readonly TimeSpan _updateLimitsInterval = TimeSpan.FromMinutes(5);

			private readonly string _name;
			protected ETradeClient Client { get; private set; }

			protected bool IsStarted { get; private set; }
			protected bool IsStopping { get; private set; }

			private readonly SynchronizedQueue<ETradeRequest> _userRequests = new SynchronizedQueue<ETradeRequest>();
			private readonly AutoResetEvent _wakeupEvt = new AutoResetEvent(false);
			private readonly ManualResetEvent _doneEvt = new ManualResetEvent(false);

			private readonly Timer _wakeupTimer = new Timer();

			private readonly List<DateTime> _recentRequests = new List<DateTime>();

			protected ETradeRequest CurrentAutoRequest { get; private set; }

			protected ETradeModule(string name, ETradeClient client)
			{
				_name = name;
				Client = client;
				Client.Connection.ConnectionStateChanged += HandleClientState;

				_wakeupTimer.AutoReset = false;
				_wakeupTimer.Enabled = false;
				_wakeupTimer.Elapsed += (sender, args) => _wakeupEvt.Set();
			}

			public void HandleClientState()
			{
				if (Client.IsConnected)
				{
					Start();
					Wakeup();
				}
				else
				{
					Stop();
				}
			}

			protected virtual void Start()
			{
				if (IsStarted) return;

				IsStarted = true;
				IsStopping = false;
				_doneEvt.Reset();

				_lastLimitsUpdateTime = DateTime.MinValue;
				//_nextIntervalStartsAt = DateTime.MinValue;
				_requestsPerSecond = 0;

				CurrentAutoRequest = null;

				_recentRequests.Clear();

				UpdateLimitsIfNecessary();

				ThreadingHelper
					.Thread(() =>
					{
						try
							{ ModuleThreadFunc(); }
						catch (Exception e)
							{ Client.RaiseError(new ETradeException(LocalizedStrings.Str3362Params.Put(_name), e)); }
						finally
							{ _doneEvt.Set(); }
					})
					.Background(true)
					.Name("etrade_" + _name)
					.Launch();
			}

			internal void Stop()
			{
				if (!IsStarted) return;

				_wakeupTimer.Stop();
				IsStopping = true;
				_wakeupEvt.Set();
				_doneEvt.WaitOne();
				IsStarted = IsStopping = false;
			}

			protected abstract ETradeRequest GetNextAutoRequest();

			public void ExecuteUserRequest<TResp>(ETradeRequest<TResp> request, Action<ETradeResponse<TResp>> responseHandler)
			{
				request.ResponseHandler = responseHandler;
				_userRequests.Enqueue(request);
				_wakeupEvt.Set();
			}

			private void ModuleThreadFunc()
			{
				Client.AddDebugLog("Module '{0}' has started.", _name);
				CurrentAutoRequest = GetNextAutoRequest();

				while (!IsStopping)
				{
					_wakeupEvt.WaitOne();

					while (!IsStopping)
					{
						var now = DateTime.UtcNow;
						var removeBefore = now - TimeSpan.FromSeconds(.999d);
						_recentRequests.RemoveAll(dt => dt < removeBefore);
						var canDoRequestNow = _recentRequests.Count + 1 <= _requestsPerSecond;

						if(CurrentAutoRequest == null)
							CurrentAutoRequest = GetNextAutoRequest();

						var request = !_userRequests.IsEmpty() ? _userRequests.Peek() : CurrentAutoRequest;

						if(request == null) break;

						if (request.IsRequestRateLimited)
						{
							if (!canDoRequestNow)
							{
								StartWakeupTimer(_recentRequests.Count > 0 ? 1 - (now - _recentRequests[0]).TotalSeconds : 1);
								break;
							}

							_recentRequests.Add(now);
						}

						Client.AddDebugLog("{0}: executing request: {1}", _name, request.ToString());

						var response = request.ExecuteNextPart(Client);

						if (response.Exception is ETradeUnauthorizedException)
						{
							Client.AddWarningLog("{0}: Response returned Unauthorized exception.", _name);
							IsStopping = true;
							Client.Connection.ReconnectAsync();
							break;
						}

						ProcessResponse(response);

						if (request.IsDone)
						{
							if(request == CurrentAutoRequest)
								CurrentAutoRequest = GetNextAutoRequest();
							else
								_userRequests.Dequeue();

							if(response.Exception == null)
								UpdateLimitsIfNecessary();
						}
					}
				}
			}

			protected virtual void ProcessResponse(ETradeResponse response)
			{
				response.Process();
			}

			private void StartWakeupTimer(double seconds)
			{
				_wakeupTimer.Stop();
				_wakeupTimer.Interval = seconds * 1000;
				_wakeupTimer.Start();
			}

			public void Wakeup()
			{
				StartWakeupTimer(0.01);
			}

			private void UpdateLimitsIfNecessary()
			{
				if (_lastLimitsUpdateTime != DateTime.MinValue)
					return;

				_lastLimitsUpdateTime = DateTime.UtcNow;
				//_nextIntervalStartsAt = DateTime.MaxValue;
				_requestsPerSecond = 2;

				#region "limits" api was removed in latest version of ETradeApi
//				var now = DateTime.UtcNow;
//				if (now - _lastLimitsUpdateTime < _updateLimitsInterval && now < _nextIntervalStartsAt)
//					return;
//
//				_lastLimitsUpdateTime = now;
//
//				ExecuteUserRequest(new ETradeRateLimitsRequest(_name), response =>
//				{
//					if (response.Exception != null)
//					{
//						Client.RaiseError(new ETradeException("Запрос RateLimits вернул ошибку", response.Exception));
//						_nextIntervalStartsAt = now + _updateLimitsInterval;
//						_requestsPerSecond = 1;
//						Client.AddWarningLog("{0}: Failed to update rate limits. next interval: {1}, requests per second: {2:F4}",
//											_name, _nextIntervalStartsAt, _requestsPerSecond);
//						return;
//					}
//
//					_lastLimitsUpdateTime = DateTime.UtcNow;
//					_nextIntervalStartsAt = ETradeUtil.ETradeTimestampToUTC(response.Data.resetTimeEpochSeconds);
//					// .2 because ETrade allows 2 requests per second for limit of 7000 requests per hour, or 4 requests per second for 14000/hour
//					_requestsPerSecond = .2 + (_requestsLimitMultiplier * response.Data.requestsLimit) / response.Data.limitIntervalInSeconds;
//
//					if (_nextIntervalStartsAt > _lastLimitsUpdateTime)
//					{
//						var actualRequestsPerSecond = .2 + (_requestsLimitMultiplier * response.Data.requestsRemaining) / (_nextIntervalStartsAt - _lastLimitsUpdateTime).TotalSeconds;
//						if(actualRequestsPerSecond < _requestsPerSecond)
//							_requestsPerSecond = actualRequestsPerSecond;
//					}
//					else if (_lastLimitsUpdateTime - _nextIntervalStartsAt > TimeSpan.FromDays(1)) // workaround for Sandbox mode, which returns year 2010.
//					{
//						_nextIntervalStartsAt = now + _updateLimitsInterval;
//					}
//
//					if(_requestsPerSecond < 1) _requestsPerSecond = 1;
//
//					Client.AddDebugLog("{0}: Rate limits updated. next interval: {1}, requests per second: {2:F4}",
//										_name, _nextIntervalStartsAt, _requestsPerSecond);
//				});
				#endregion
			}
		}
	}
}


text:
layout: post
title: Swift 3 模組最佳化 (英文)
date: 2016-10-21T03:00:00-07:00
comments: true
paginate: true
categories: [Swift blog, Swift, Xcode]
---

  Erik Eckstein

Whole-module optimization is an optimization mode of the Swift compiler.
The performance win of whole-module optimization heavily depends on the project, but it can be up to two or even five times.

Whole-module optimization can be enabled with the -whole-module-optimization (or -wmo) compiler flag, and in Xcode 8 it is turned on by default for new projects.
Also the Swift Package Manager compiles with whole-module optimizations in release builds.

So what is it about? Let's first look at how the compiler works without whole-module optimizations.

Modules and how to compile them

A module is a set of Swift files. Each module compiles down to a single unit of distribution—either a framework or an executable. In single-file compilation (without -wmo) the Swift compiler is invoked for each file in the module separately. Actually, this is what happens behind the scenes. As a user you don't have to do this manually. It is automatically done by the compiler driver or the Xcode build system.

After reading and parsing a source file (and doing some other stuff, like type checking), the compiler optimizes the Swift code, generates machine code and writes an object file. Finally the linker combines all object files and generates the shared library or executable.

In single-file compilation the scope of the compiler's optimizations is just a single file. This limits cross-function optimizations, like function inlining or generic specialization, to functions which are called and defined in the same file.

Let's look at an example. Let's assume one file of our module, named utils.swift, contains a generic utility data structure Container<T> with a method getElement and this method is called throughout the module, for example in main.swift.

main.swift:

func add (c1: Container<Int>, c2: Container<Int>) -> Int {
  return c1.getElement() + c2.getElement()
}

utils.swift:

struct Container<T> {
  var element: T

  func getElement() -> T {
    return element
  }
}

When the compiler optimizes main.swift it does not know how getElement is implemented. It just knows that it exists. So the compiler generates a call to getElement. On the other hand, when the compiler optimizes utils.swift, it does not know for which concrete types the function is called. So it can only generate the generic version of the function which is much slower than code which is specialized for a concrete type.

Even the simple return statement in getElement needs a lookup in the type's metadata to figure out how to copy the element. It could be a simple Int, but it could also be a larger type, even involving some reference counting operations. The compiler just doesn't know.

Whole-module optimization

With whole-module optimization the compiler can do a lot better. When compiling with the -wmo option, the compiler optimizes all files of a module as a whole.

This has two big advantages. First, the compiler sees the implementation of all functions in a module, so it can perform optimizations like function inlining and function specialization.
Function specialization means that the compiler creates a new version of a function which is optimized for a specific call-context. For example, the compiler can specialize a generic function for concrete types.

In our example, the compiler produces a version of the generic Container which is specialized for the concrete type Int.

struct Container {
  var element: Int

  func getElement() -> Int {
    return element
  }
}

Then the compiler can inline the specialized getElement function into the add function.

func add (c1: Container<Int>, c2: Container<Int>) -> Int {
  return c1.element + c2.element
}

This compiles down to just a few machine instructions. That's a big difference compared to the single-file code where we had two calls to the generic getElement function.

Function specialization and inlining across files are just examples of optimizations the compiler is able to do with whole-module optimizations. Even if the compiler decides not to inline a function, it helps a lot if the compiler sees the implementation of the function.
For example it can reason about its behavior regarding reference counting operations. With this knowledge the compiler is able to remove redundant reference counting operations around a function call.

The second important benefit of whole-module optimization is that the compiler can reason about all uses of non-public functions. Non-public functions can only be used within the module, so the compiler can be sure to see all references to such functions. What can the compiler do with this information?

One very basic optimization is the elimination of so called "dead" functions and methods. These are functions and methods which are never called or otherwise used. With whole-module optimizations the compiler knows if a non-public function or method is not used at all, and if that's the case it can eliminate it.
So why would a programmer write a function, which is not used at all? Well, this is not the most important use case for dead function elimination. Often functions become dead as a side-effect of other optimizations.

Let's assume that the add function is the only place where Container.getElement is called. After inlining getElement, this function is not used anymore, so it can be removed. Even if the compiler decides to not inline getElement, the compiler can remove the original generic version of getElement, because the add function only calls the specialized version.

Compile time

With single-file compilation the compiler driver starts the compilation for each file in a separate process, which can be done in parallel. Also, files which were not modified since the last compilation don't need to be recompiled (assuming all dependencies are also unmodified). That's called incremental compilation.
All this saves a lot of compile time, especially if you only make a small change.
How does this work in whole-module compilation?
Let's look at how the compiler works in whole-module optimization mode in more detail.

Internally the compiler runs in multiple phases: parser, type checking, SIL optimizations, LLVM backend.

Parsing and type checking is very fast in most cases, and we expect it to get even faster in subsequent Swift releases.
The SIL optimizer (SIL stands for "Swift Intermediate Language") performs all the important Swift-specific optimizations, like generic specialization, function inlining, etc. This phase of the compiler typically takes about one third of the compilation time.
Most of the compilation time is consumed by the LLVM backend which runs lower-level optimizations and does the code generation.

After performing whole-module optimizations in the SIL optimizer the module is split again into multiple parts. The LLVM backend processes the split parts in multiple threads. It also avoids re-processing of a part if that part didn't change since the previous build.
So even with whole-module optimizations, the compiler is able to perform a big part of the compilation work in parallel (multi-threaded) and incrementally.

Conclusion

Whole-module optimization is a great way to get maximum performance without having to worry about how to distribute Swift code across files in a module.
If optimizations, like described above, kick in at a critical code section, performance can be up to five times better than with single-file compilation.
And you get this high performance with much better compile times than typical to monolithic whole-program optimization approaches.


text:
<!DOCTYPE html>
<!--[if lt IE 7]>      <html lang="en" ng-app="petStoreApp" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html lang="en" ng-app="petStoreApp" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html lang="en" ng-app="petStoreApp" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en" ng-app="petStoreApp" class="no-js"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>YaPetStore</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="bower_components/angular-material/angular-material.min.css">
  <link rel="stylesheet" href="bower_components/components-font-awesome/css/font-awesome.css">
  <link rel="stylesheet" href="app.css">
  <script src="bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>

  <div ng-view layout="row" layout-fill></div>

  <script src="bower_components/lodash/dist/lodash.min.js"></script>
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-animate/angular-animate.min.js"></script>
  <script src="bower_components/angular-aria/angular-aria.min.js"></script>
  <script src="bower_components/angular-sanitize/angular-sanitize.min.js"></script>
  <script src="bower_components/angular-material/angular-material.min.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="app.js"></script>
  <script src="common/services/auth/auth.service.js"></script>
  <script src="common/filters/truncate.js"></script>
  <script src="common/services/pet/pet.service.js"></script>
  <script src="common/services/cart/cart.service.js"></script>
  <script src="common/services/toast/toast.service.js"></script>
  <script src="login/login.component.js"></script>
  <script src="pets/pets.component.js"></script>
  <script src="pets/pet-create.component.js"></script>
</body>
</html>


text:
package org.examples.spring.databinding.map;

import java.util.Map;

public class Form {

	private Map<Long, User> users;

	public Map<Long, User> getUsers() {
		return users;
	}

	public void setUsers(Map<Long, User> users) {
		this.users = users;
	}

}


text:
package util

import (
	"net/http"
	"testing"

	"net/url"

	"bytes"
	"io/ioutil"

	. "github.com/bborbe/assert"
)

func TestResponseToByteArray(t *testing.T) {
	var err error
	var content []byte

	response := new(http.Response)
	response.Body = ioutil.NopCloser(bytes.NewBufferString("test"))

	if content, err = ResponseToByteArray(response); err != nil {
		t.Fatal(err)
	}

	if err := AssertThat(string(content), Is("test")); err != nil {
		t.Fatal(err)
	}
}

func TestResponseToString(t *testing.T) {
	var err error
	var content string

	response := new(http.Response)
	response.Body = ioutil.NopCloser(bytes.NewBufferString("test"))

	if content, err = ResponseToString(response); err != nil {
		t.Fatal(err)
	}

	if err := AssertThat(content, Is("test")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtension(t *testing.T) {
	var err error
	response := &http.Response{}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NotNilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtensionUrlWithDot(t *testing.T) {
	var err error
	var u *url.URL
	if u, err = url.ParseRequestURI("http://www.example/robots.txt"); err != nil {
		t.Fatal(err)
	}
	response := &http.Response{Request: &http.Request{URL: u}}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("txt")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtensionUrlWithDotAtLast(t *testing.T) {
	var err error
	var u *url.URL
	if u, err = url.ParseRequestURI("http://www.example/robots."); err != nil {
		t.Fatal(err)
	}
	response := &http.Response{Request: &http.Request{URL: u}}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NotNilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtensionHeader(t *testing.T) {
	var err error
	response := &http.Response{Header: http.Header{}}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NotNilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtensionHeaderContentTypeKownType(t *testing.T) {
	var err error
	response := &http.Response{Header: http.Header{"Content-Type": []string{"image/jpeg"}}}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("jpg")); err != nil {
		t.Fatal(err)
	}
}

func TestFindFileExtensionHeaderContentTypeUnkownType(t *testing.T) {
	var err error
	response := &http.Response{Header: http.Header{"Content-Type": []string{"text/foo"}}}
	ext, err := FindFileExtension(response)
	if err := AssertThat(err, NotNilValue()); err != nil {
		t.Fatal(err)
	}
	if err := AssertThat(ext, Is("")); err != nil {
		t.Fatal(err)
	}
}


text:
layout: post
title: "QualtricsTools : Automated Survey Processing"
modified: ""
tags: [rstats, web-apps]
categories: [web-programming]
comments: true
---

QualtricsTools is an open source application built in R Shiny that I
started while working at Tufts that allows users to upload a
Qualtrics JSON QSF Survey File, and response data in CSV format and
automatically calculate tables and frequencies custom to the survey's
questions types, format, and responses.

QualtricsTools, an R web-app

The project is now maintained by Emma Morgan at Tufts -- so check out
the [her GitHub repository](https://github.com/emmamorgan-tufts/QualtricsTools) for more information.


text:
/*
 * catom2D1BlockCode.cpp
 *
 *  Created on: 12 avril 2013
 *      Author: ben
 */

#include <iostream>
#include <sstream>
#include "catoms3DWorld.h"
#include "simpleCatom3DBlockCode.h"
#include "scheduler.h"
#include "events.h"
#include <memory>

#define verbose 1

using namespace std;
using namespace Catoms3D;

SimpleCatom3DBlockCode::SimpleCatom3DBlockCode(Catoms3DBlock *host):Catoms3DBlockCode(host) {
	cout << "SimpleCatom3DBlockCode constructor" << endl;
	scheduler = getScheduler();
	catom = (Catoms3DBlock*)hostBlock;
}

SimpleCatom3DBlockCode::~SimpleCatom3DBlockCode() {
	cout << "SimpleCatom3DBlockCode destructor" << endl;
}

void SimpleCatom3DBlockCode::startup() {
	stringstream info;

	info << "Starting ";
	/*int n=0;
	for (int i=0; i<12; i++) {
        if (catom->getInterface(i)->connectedInterface!=NULL) {
            n++;
        }
	}
	switch (n) {
        case 0 : catom->setColor(DARKGREY); break;
        case 1 : catom->setColor(RED); break;
        case 2 : catom->setColor(ORANGE); break;
        case 3 : catom->setColor(PINK); break;
        case 4 : catom->setColor(YELLOW); break;
        case 5 : catom->setColor(GREEN); break;
        case 6 : catom->setColor(LIGHTGREEN); break;
        case 7 : catom->setColor(LIGHTBLUE); break;
        case 8 : catom->setColor(BLUE); break;
        case 9 : catom->setColor(MAGENTA); break;
        case 10 : catom->setColor(GOLD); break;
        case 11 : catom->setColor(DARKORANGE); break;
        case 12 : catom->setColor(WHITE); break;
	}*/

	/* skeleton test */
	Catoms3DWorld*wrl = Catoms3DWorld::getWorld();
	Vector3D pos(catom->ptrGlBlock->position[0],catom->ptrGlBlock->position[1],catom->ptrGlBlock->position[2]);
	potentiel = wrl->getSkeletonPotentiel(pos);
	catom->setColor(potentiel>1.0?YELLOW:DARKORANGE);

	info << potentiel;
	scheduler->trace(info.str(),hostBlock->blockId);

	if (catom->blockId==1) {
        Vector3D position=wrl->lattice->gridToWorldPosition(Cell3DPosition(2,1,0));
        int id=1000000;
        int i=0;
        Catoms3DBlock *voisin=NULL;
        P2PNetworkInterface *p2p;
        while (i<12) {
            p2p = catom->getInterface(i);
            if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
                voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
                id = voisin->blockId;
            }
            i++;
        }
        Matrix m_1;
        voisin->getGlBlock()->mat.inverse(m_1);
        // recherche le voisin d'indice minimum
        //Rotations3D rotations(catom,voisin,m_1*Vector3D(0,1,0),35.2643896828,m_1*Vector3D(-1,1, -M_SQRT2),35.2643896828);
        Rotations3D rotations(catom,voisin,m_1*Vector3D(0,0,1),45.0,m_1*Vector3D(-1,1,0),45.0);
        Time t = scheduler->now()+2000;
        scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
#ifdef verbose
        stringstream info;
        info.str("");
        info << "Rotation3DStartEvent(" << t << ") around #" << voisin->blockId;
        scheduler->trace(info.str(),catom->blockId,LIGHTGREY);
#endif
	}
}

void SimpleCatom3DBlockCode::processLocalEvent(EventPtr pev) {
	MessagePtr message;
	stringstream info;

	switch (pev->eventType) {
        case EVENT_ROTATION3D_END: {
#ifdef verbose
			info.str("");
			info << "rec.: EVENT_MOTION_END";
			scheduler->trace(info.str(),hostBlock->blockId);
#endif
            Catoms3DBlock *voisin=NULL;
            P2PNetworkInterface *p2p;
            int i=0,id=10000;
            while (i<12) {
                p2p = catom->getInterface(i);

                if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
                    voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
                    id = voisin->blockId;
                }
                i++;
            }
            Matrix m_1;
            voisin->getGlBlock()->mat.inverse(m_1);
            // Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,1,M_SQRT2),35.26,m_1*Vector3D(-1,-1, -M_SQRT2),35.26);
            Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,-1,0),45.0,m_1*Vector3D(0,0,1),45.0);
            Time t = scheduler->now()+1002000;
            // scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
        }
        break;
        case EVENT_NI_RECEIVE: {
            message = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message;
            P2PNetworkInterface * recv_interface = message->destinationInterface;

        }
        break;
	}
}

// bool SimpleCatom3DBlockCode::getAttribute(const string &att,ostringstream &sout) {
//     if (att=="potentiel") {
//         sout << potentiel << endl;
//         return true;
//     }
//     return Catoms3DBlockCode::getAttribute(att,sout);
// }


text:
SYNONYM

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

#### Published in
Syll. fung. (Abellini) 3: 220 (1884)

#### Original name
Sphaeropsis acicola Lév., 1848

### Remarks
null


text:
Cortex XDR is the world's first detection and response app that natively integrates network, endpoint, and cloud data to stop sophisticated attacks.
XQL Query Engine enables you to run XQL queries on your data sources.

### Generate an API Key and API Key ID

1. In your Cortex XDR platform, go to **Settings**.

2. Click the **+New Key** button in the top right corner.

3. Generate a key of type **Advanced**.

4. Copy and paste the key.

5. From the ID column, copy the Key ID.

### URL
1. In your Cortex XDR platform, go to **Settings**.
2. Click the **Copy URL** button in the top right corner.

### Note
If you choose to use the credentials from XSOAR credential manager, create two credentials, one for the api-key and one for the api-key-id, then enter the key in the password field.

---
[View Integration Documentation](https://xsoar.pan.dev/docs/reference/integrations/cortex-xdr---xql-query-engine)