text:
{-# LANGUAGE OverloadedStrings #-}
module Ptt.Task
  ( TaskMap(..)
  , Selector
  , Tasks
  , TaskName
  , Task(..)
  , taskLength
  , totalLength
  , addTask
  , deleteTask
  , deleteTasks
  , adjustTask
  , adjustTasks
  , deleteDescription
  , deleteInterval
  , renameTask
  , moveTask
  , getTask
  , getTasksForDay
  , tasksForSelector
  , emptyTaskMap
  , deleteOldTasks
  , groupByDay
  ) where

import Prelude as P
import qualified Data.Text as T
import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Time.Calendar
import Data.Yaml
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Ptt.Time.Interval as I
import Ptt.Time.Date

type TaskName = T.Text
type Selector = (Day, TaskName)
type Tasks = M.Map Selector Task
newtype TaskMap = Tm { getTM :: Tasks } deriving (Show, Eq)

data Task = Task
  { taskDescriptions :: [T.Text]
  , taskTimes :: [I.Interval]
  } deriving (Ord, Eq, Show)

instance ToJSON Task where
  toJSON (Task descs times) = object
    [ "descriptions" .= toJSON descs
    , "times" .= toJSON times ]

instance FromJSON Task where
  parseJSON (Object v) =
    Task <$> v .: "descriptions" <*> v .: "times"
  parseJSON _ = mzero

instance ToJSON TaskMap where
  toJSON (Tm tasks) = toJSON . M.mapKeys formatSelector $ tasks
    where formatSelector (day, name) = T.concat [formatDay day, ":", name]

instance FromJSON TaskMap where
  parseJSON v = Tm <$> do
    m1 <- parseJSON v
    m2 <- mapM convert (M.toList m1)
    return $ M.fromList m2
    where convert (s, tasks) = do
            let (ds, n) = T.break (== ':') s
                name = T.tail n
            day <- maybe mzero return (parseDay ds)
            return ((day, name), tasks)

taskLength :: Task -> Integer
taskLength = sum . map I.intervalLength . taskTimes

totalLength :: TaskMap -> Integer
totalLength = sum . map taskLength . M.elems . getTM

merge :: Task -> Task -> Task
merge (Task descs1 times1) (Task descs2 times2) =
  let descs = descs1 ++ descs2
      times = foldl' (flip I.add) times2 times1
  in Task descs times

addTask :: Selector -> Task -> TaskMap -> TaskMap
addTask selector task (Tm tasks) =
  let existingTask = M.lookup selector tasks
      taskToInsert = maybe task (merge task) existingTask
  in Tm $ M.insert selector taskToInsert tasks

deleteDescription :: Int -> Task -> Task
deleteDescription i (Task ds ts) = Task (deleteNth i ds) ts

deleteNth :: Int -> [a] -> [a]
deleteNth i xs
  | i > 0 = take (i - 1) xs ++ drop i xs
  | otherwise = xs

changeKey :: Selector -> Selector -> TaskMap -> TaskMap
changeKey selector newSelector tasks =
  let updatedTasks = do
        task <- getTask selector tasks
        return $ addTask newSelector task (deleteTask selector tasks)
  in fromMaybe tasks updatedTasks

moveTask :: Selector -> Day -> TaskMap -> TaskMap
moveTask selector day = changeKey selector (day, snd selector)

renameTask :: Selector -> TaskName -> TaskMap -> TaskMap
renameTask selector newName = changeKey selector (fst selector, newName)

deleteInterval :: I.Interval -> Task -> Task
deleteInterval i (Task ds ts) = Task ds (I.remove i ts)

getTask :: Selector -> TaskMap -> Maybe Task
getTask selector = M.lookup selector . getTM

deleteTask :: Selector -> TaskMap -> TaskMap
deleteTask selector = Tm . M.delete selector . getTM

deleteTasks :: DateSelector -> TaskName -> TaskMap -> TaskMap
deleteTasks selector name tasks =
  let foundTasks = tasksWithName name . tasksForSelector selector $ tasks
  in Tm $ M.difference (getTM tasks) foundTasks

adjustTask :: (Task -> Task) -> Selector -> TaskMap -> TaskMap
adjustTask f selector = Tm . M.adjust f selector . getTM

deleteOldTasks :: Day -> TaskMap -> TaskMap
deleteOldTasks d (Tm tasks) = Tm $ M.filterWithKey isNewer tasks
  where isNewer (k, _) _ = k >= d

getTasksForDay :: Day -> TaskMap -> [(TaskName, Task)]
getTasksForDay d = M.toList . M.mapKeys snd . tasksForDay d

tasksForDay :: Day -> TaskMap -> Tasks
tasksForDay day = M.filterWithKey f . getTM
  where f (k, _) _ = k == day

emptyTaskMap :: TaskMap
emptyTaskMap = Tm M.empty

tasksWithName :: TaskName -> Tasks -> Tasks
tasksWithName name = M.filterWithKey f
  where f (_, n) _ = n == name

tasksForSelector :: DateSelector -> TaskMap -> Tasks
tasksForSelector selector tasks =
  case selector of
    AllDates -> getTM tasks
    DateRange from to -> tasksBetweenDays from to tasks
    SingleDate day -> tasksForDay day tasks

tasksBetweenDays :: Day -> Day -> TaskMap -> Tasks
tasksBetweenDays from to = M.filterWithKey f . getTM
  where f (day, _) _ = from <= day && day <= to

adjustTasks :: (Task -> Task) -> DateSelector -> TaskMap -> TaskMap
adjustTasks f selector taskmap =
  mergeTasks taskmap . M.toList . M.map f
  . tasksForSelector selector $ taskmap

mergeTasks :: TaskMap -> [(Selector, Task)] -> TaskMap
mergeTasks = foldl' merger
  where merger tm (selector, task) = addTask selector task tm

groupByDay :: Tasks -> [(Day, S.Set (TaskName, Task))]
groupByDay = sort . M.toList . M.foldlWithKey folder M.empty
  where folder acc (day, name) task =
          M.insertWith S.union day (S.singleton (name, task)) acc


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author: Ilia A. Leviev
Version: $Revision: 1.3 $
-->
<Test
  ID="fcmpl0901"
  date-of-creation="2004-11-26"
  timeout="1"
  >
  <Author value="Ilia A. Leviev"/>
  <Description>
      Tests fcpmg java virtual machine instruction.
      Test checks that fcpmg instruction correctly compares values,
      if value1=POSITIVE_INFINITY and value2=MAX_VALUE then result is 1.

      Covered assertions assert_instr24a082 assert_instr24a083 assert_instr24a090 assert_over425
  </Description>

  <Source name="fcmpl0901p.j"/>

  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.arithm.fcmpl.fcmpl09.fcmpl0901.fcmpl0901p"/>
</Runner>
</Test>

redpajama_set_name: RedPajamaGithub


text:
/*jshint expr:true */
var expect = require('chai').expect;
var nock = require('nock');
var rewire = require('rewire');

var topContribs = rewire('../index.js');

nock.disableNetConnect();

describe('top-gh-contribs', function () {
    it('retry delay should be an exponential backoff in milliseconds', function () {
        var retryDelay = topContribs.__get__('retryDelay');

        expect(retryDelay(0)).to.be.above(1000).and.below(2000);
        expect(retryDelay(1)).to.be.above(2000).and.below(3000);
        expect(retryDelay(2)).to.be.above(4000).and.below(5000);
        expect(retryDelay(3)).to.be.above(8000).and.below(9000);
        expect(retryDelay(4)).to.be.above(16000).and.below(17000);
    });

    describe('getReleaseDatePromise', function () {
        it('should return a date in seconds if releaseDate is passed in as milliseconds', function (done) {
            var ninetyDaysAgo = Date.now() - (1000 * 60 * 60 * 24 * 90);

            topContribs.getReleaseDatePromise(ninetyDaysAgo).then(function (result) {
                expect(result).to.equal(ninetyDaysAgo / 1000);

                done();
            }).catch(done);
        });

        it('should return 0 if not given a releaseDate or releaseTag', function (done) {
            topContribs.getReleaseDatePromise().then(function (result) {
                expect(result).to.equal(0);

                done();
            }).catch(done);
        });

        it('should return a value based on releaseDate if both releaseDate and releaseTag are passed in', function (done) {
            var ninetyDaysAgo = Date.now() - (1000 * 60 * 60 * 24 * 90);

            topContribs.getReleaseDatePromise(ninetyDaysAgo, 'v1.0.0').then(function (result) {
                expect(result).to.equal(ninetyDaysAgo / 1000);

                done();
            }).catch(done);
        });

        it('should make an API request to resolve the release tag', function (done) {
            after(function () {
                nock.cleanAll();
            });

            var repo = 'https://api.github.com/tryghost/ghost';
            var publishedAt = Date.parse('2015-01-12T19:46:50Z') / 1000;

            nock('https://api.github.com')
                .get('/tryghost/ghost/releases')
                .replyWithFile(200, __dirname + '/fixtures/releases.json');

            topContribs.getReleaseDatePromise(null, '0.5.8', repo).then(function (result) {
                expect(result).to.equal(publishedAt);

                done();
            }).catch(done).finally(function () {
                nock.cleanAll();
            });
        });

        it('should return a rejected promise if the release tag cannot be found', function (done) {
            after(function () {
                nock.cleanAll();
            });

            var repo = 'https://api.github.com/tryghost/ghost';

            nock('https://api.github.com')
                .get('/tryghost/ghost/releases')
                .replyWithFile(200, __dirname + '/fixtures/releases.json');

            topContribs.getReleaseDatePromise(null, '1.0.0', repo).then(function () {
                done(new Error('Expected getReleaseDatePromise to reject but it did not'));
            }).catch(function (err) {
                expect(err).to.be.an.instanceof(Error);

                done();
            });
        });
    });

    describe('getTopContributors', function () {
            var fixture = require(__dirname + '/fixtures/contributors.json');

        it('should return all contributors if release date is zero', function () {
            var result = topContribs.getTopContributors(0, fixture, fixture.length);

            expect(result.length).to.equal(fixture.length);
        });

        it('should return contributor objects with the correct properties', function () {
            var result = topContribs.getTopContributors(0, fixture, fixture.length);

            expect(result[3].commitCount).to.equal(197);
            expect(result[3].name).to.equal('jaswilli');
            expect(result[3].githubUrl).to.equal('https://github.com/jaswilli');
            expect(result[3].avatarUrl).to.equal('https://avatars.githubusercontent.com/u/214142?v=3');
        });

        it('should return the list of contributors sorted by number of contributions', function () {
            var result = topContribs.getTopContributors(0, fixture, fixture.length);

            expect(result[0].commitCount).to.be.above(result[1].commitCount);
            expect(result[1].commitCount).to.be.above(result[2].commitCount);
            expect(result[2].commitCount).to.be.above(result[3].commitCount);
            expect(result[3].commitCount).to.be.above(result[4].commitCount);
        });

        it('should not return more contributors than requested', function () {
            var result = topContribs.getTopContributors(0, fixture, 3);

            expect(result.length).to.equal(3);
        });

        it('should not return contributors with no commits in the requested date range', function () {
            // five days ago from when the fixture data was obtained
            var fiveDaysAgo = new Date('2015-02-05').getTime() / 1000 - (60 * 60 * 24 * 5);

            var result = topContribs.getTopContributors(fiveDaysAgo, fixture, 20);

            expect(result.length).to.equal(2);
            expect(result[0].name).to.equal('jaswilli');
            expect(result[1].name).to.equal('PaulAdamDavis');
        });
    });

    describe('requestPromise', function () {
        var requestPromise = topContribs.__get__('requestPromise');

        afterEach(function () {
            nock.cleanAll();
        });

        it('should reject on a status code of >= 500', function (done) {
            nock('http://example.com')
                .get('/')
                .reply(500);

            requestPromise({url: 'http://example.com/'}).then(function () {
                done(new Error('expected requestPromise to reject but it did not'));
            }).catch(function (err) {
                expect(err).to.be.instanceof(Error);

                done();
            });
        });

        it('should reject on a status code of >= 400', function (done) {
            nock('http://example.com')
                .get('/')
                .reply(404);

            requestPromise({url: 'http://example.com/'}).then(function () {
                done(new Error('expected requestPromise to reject but it did not'));
            }).catch(function (err) {
                expect(err).to.be.an.instanceof(Error);

                done();
            });
        });

        it('should return the response body on a status code of 200', function (done) {
            nock('http://example.com')
                .get('/')
                .reply(200, {some: 'thing'});

            requestPromise({url: 'http://example.com/'}).then(function (response) {
                expect(response).to.exist;
                expect(response.some).to.exist;
                expect(response.some).to.equal('thing');

                done();
            }).catch(done);
        });

        it('should reject if status code is 202 and retry is not enabled', function (done) {
            nock('http://example.com')
                .get('/')
                .reply(202);

            requestPromise({url: 'http://example.com/'}).then(function () {
                done(new Error('expected requestPromise to reject but it did not'));
            }).catch(function (err) {
                expect(err).to.be.an.instanceof(Error);

                done();
            });
        });

        it('should retry if status code is 202 and retry is enabled', function (done) {
            this.timeout(5000);

            nock('http://example.com')
                .get('/')
                .reply(202)
                .get('/')
                .reply(200, {r: 'retry worked'});

            requestPromise({url: 'http://example.com/', retry: true}).then(function (response) {
                expect(response).to.exist;
                expect(response.r).to.exist;
                expect(response.r).to.equal('retry worked');

                done();
            }).catch(done);
        });
    });
});


text:
/** @file */

/*
 * This file keeps global constants. Sections are - external standards -
 * internal - ... The top of the file contains a terse listing of actual
 * constants. Descriptions or rationalizations for a particular constant may
 * exist in a commented section further down the file.
 */

#ifndef GLOBALS_H_
#define GLOBALS_H_

/*
 * =============================================================================
 * --------------------------- Based on external standards ----------------------
 */
#define SER_NUM_MAX_SZ              20
#define SUBJ_PUBKEY_EXPONENT        65537
#define SUBJ_PUBKEY_EXPONENT_SZ     3
#define SUBJ_PUBKEY_MAX_SZ          280
#define SUBJ_PUBKEY_MODULUS_SZ      256

/*
 * =============================================================================
 * ----------------------------------- Internal ---------------------------------
 */
#define URI_MAX_SZ                  0xFFF

/*
 * =============================================================================
 * ---------------------------------- Descriptions
 * -------------------------------- SUBJ_PUBKEY_EXPONENT
 * draft-ietf-sidr-rpki-algs-05, 3. Asymmetric Key Pair Formats The RSA key pairs
 * used to compute the signatures MUST have a 2048-bit modulus and a public
 * exponent (e) of 65,537.
 *
 *
 * SUBJ_PUBKEY_EXPONENT_SZ draft-ietf-sidr-rpki-algs-05, 3. Asymmetric Key Pair
 * Formats The RSA key pairs used to compute the signatures MUST have a 2048-bit
 * modulus and a public exponent (e) of 65,537. This value is stored in 3 bytes
 * in ASN encoding.
 *
 *
 * SUBJ_PUBKEY_MAX_SZ draft-ietf-sidr-rpki-algs-05, 3. Asymmetric Key Pair
 * Formats The RSA key pairs used to compute the signatures MUST have a 2048-bit
 * modulus and a public exponent (e) of 65,537. This is the size required to hold
 * to resulting ASN structure.
 *
 *
 * SUBJ_PUBKEY_MODULUS_SZ draft-ietf-sidr-rpki-algs-05, 3. Asymmetric Key Pair
 * Formats The RSA key pairs used to compute the signatures MUST have a 2048-bit
 * modulus and a public exponent (e) of 65,537. The ASN encoding of this value is
 * actually one byte longer to contain a leading zero byte.
 *
 *
 * URI_MAX_SZ A sanity limit to prevent allocating arbitrary memory size.
 *
 */
#endif                          /* GLOBALS_H_ */


text:
#include "MQTT.h"

namespace MQTT {
  // First some convenience functions
  void write(uint8_t *buf, uint32_t& bufpos, uint16_t data) {
    buf[bufpos++] = data >> 8;
    buf[bufpos++] = data & 0xff;
  }

  void write(uint8_t *buf, uint32_t& bufpos, uint8_t *data, uint32_t dlen) {
    memcpy(buf + bufpos, data, dlen);
    bufpos += dlen;
  }

  void write(uint8_t *buf, uint32_t& bufpos, String str) {
    const char* c = str.c_str();
    uint32_t length_pos = bufpos;
    bufpos += 2;
    uint16_t count = 0;
    while (*c) {
      buf[bufpos++] = *c++;
      count++;
    }
    write(buf, length_pos, count);
  }

  template <typename T>
  T read(uint8_t *buf, uint32_t& pos);

  template <>
  uint8_t read<uint8_t>(uint8_t *buf, uint32_t& pos) {
    return buf[pos++];
  }

  template <>
  uint16_t read<uint16_t>(uint8_t *buf, uint32_t& pos) {
    uint16_t val = buf[pos++] << 8;
    val |= buf[pos++];
    return val;
  }

  template <>
  String read<String>(uint8_t *buf, uint32_t& pos) {
    uint16_t len = read<uint16_t>(buf, pos);
    String val;
    val.reserve(len);
    for (uint16_t i = 0; i < len; i++)
      val += (char)read<uint8_t>(buf, pos);

    return val;
  }

  // Message class
  uint8_t Message::fixed_header_length(uint32_t rlength) const {
    if (rlength < 128)
      return 2;
    else if (rlength < 16384)
      return 3;
    else if (rlength < 2097152)
      return 4;
    else
      return 5;
  }

  void Message::write_fixed_header(uint8_t *buf, uint32_t& bufpos, uint32_t rlength) const {
    buf[bufpos] = _type << 4;

    switch (_type) {
    case MQTTPUBLISH:
      buf[bufpos] |= _flags & 0x0f;
      break;
    case MQTTPUBREL:
    case MQTTSUBSCRIBE:
    case MQTTUNSUBSCRIBE:
      buf[bufpos] |= 0x02;
    }
    bufpos++;

    // Remaining length
    do {
      uint8_t digit = rlength & 0x7f;
      rlength >>= 7;
      if (rlength)
	digit |= 0x80;
      buf[bufpos++] = digit;
    } while (rlength);
  }

  void Message::write_packet_id(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _packet_id);
  }

  bool Message::send(WiFiClient& wclient) {
    uint32_t remaining_length = variable_header_length() + payload_length();
    uint32_t packet_length = fixed_header_length(remaining_length) + remaining_length;
    uint8_t *packet = new uint8_t[packet_length];

    uint32_t pos = 0;
    write_fixed_header(packet, pos, remaining_length);
    write_variable_header(packet, pos);
    write_payload(packet, pos);

    uint32_t sent = wclient.write(const_cast<const uint8_t*>(packet), packet_length);
    delete [] packet;
    return (sent == packet_length);
  }

  uint8_t readByte(WiFiClient& client) {
    while(!client.available()) {}
    return client.read();
  }

  // Parser
  Message* readPacket(WiFiClient& client) {
    // Read type and flags
    uint8_t type = readByte(client);
    uint8_t flags = type & 0x0f;
    type >>= 4;

    // Read the remaining length
    uint8_t lenbuf[4], lenlen = 0;
    uint32_t remaining_length = 0;
    uint8_t shifter = 0;
    uint8_t digit;
    do {
      digit = readByte(client);
      lenbuf[lenlen++] = digit;
      remaining_length += (digit & 0x7f) << shifter;
      shifter += 7;
    } while (digit & 0x80);

    // Read variable header and/or payload
    uint8_t *remaining_data = NULL;
    if (remaining_length > 0) {
      remaining_data = new uint8_t[remaining_length];
      uint32_t r = remaining_length;
      while (client.available() && r) {
	r -= client.read(remaining_data, r);
      }
    }

    // Use the type value to return an object of the appropriate class
    Message *obj;
    switch (type) {
    case MQTTCONNACK:
      obj = new ConnectAck(remaining_data, remaining_length);
      break;

    case MQTTPUBLISH:
      obj = new Publish(flags, remaining_data, remaining_length);
      break;

    case MQTTPUBACK:
      obj = new PublishAck(remaining_data, remaining_length);
      break;

    case MQTTPUBREC:
      obj = new PublishRec(remaining_data, remaining_length);
      break;

    case MQTTPUBREL:
      obj = new PublishRel(remaining_data, remaining_length);
      break;

    case MQTTPUBCOMP:
      obj = new PublishComp(remaining_data, remaining_length);
      break;

    case MQTTSUBACK:
      obj = new SubscribeAck(remaining_data, remaining_length);
      break;

    case MQTTUNSUBACK:
      obj = new UnsubscribeAck(remaining_data, remaining_length);
      break;

    case MQTTPINGREQ:
      obj = new Ping(remaining_data, remaining_length);
      break;

    case MQTTPINGRESP:
      obj = new PingResp(remaining_data, remaining_length);
      break;

    }
    if (remaining_data != NULL)
      delete [] remaining_data;

    return obj;
  }

  // Connect class
  Connect::Connect(String cid) :
    Message(MQTTCONNECT),
    _clean_session(true),
    _clientid(cid),
    _keepalive(MQTT_KEEPALIVE)
  {}

  uint32_t Connect::variable_header_length(void) const {
    return 10;
  }

  void Connect::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, "MQTT");	// Protocol name
    buf[bufpos++] = 4;		// Protocol level

    buf[bufpos] = 0;		// Connect flags
    if (_clean_session)
      buf[bufpos] |= 0x02;

    if (_will_topic.length()) {
      buf[bufpos] |= 0x04;

      if (_will_qos > 2)
	buf[bufpos] |= 2 << 3;
      else
	buf[bufpos] |= _will_qos << 3;
      buf[bufpos] |= _will_retain << 5;
    }

    if (_username.length()) {
      buf[bufpos] |= 0x80;
      if (_password.length())
	buf[bufpos] |= 0x40;
    }
    bufpos++;

    write(buf, bufpos, _keepalive);	// Keepalive period
  }

  uint32_t Connect::payload_length(void) const {
    uint32_t len = 2 + _clientid.length();
    if (_will_topic.length()) {
      len += 2 + _will_topic.length();
      len += 2 + _will_message.length();
    }
    if (_username.length()) {
      len += 2 + _username.length();
      if (_password.length())
	len += 2 + _password.length();
    }
    return len;
  }

  void Connect::write_payload(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _clientid);

    if (_will_topic.length()) {
      write(buf, bufpos, _will_topic);
      write(buf, bufpos, _will_message);
    }

    if (_username.length()) {
      write(buf, bufpos, _username);
      if (_password.length())
	write(buf, bufpos, _password);
    }
  }

  // ConnectAck class
  ConnectAck::ConnectAck(uint8_t* data, uint32_t length) :
    Message(MQTTCONNACK)
  {
    uint32_t pos = 0;
    uint8_t reserved = read<uint8_t>(data, pos);
    _rc = read<uint8_t>(data, pos);
  }

  // Publish class
  Publish::Publish(String topic, String payload) :
    Message(MQTTPUBLISH),
    _topic(topic),
    _payload(NULL), _payload_len(0),
    _payload_mine(false)
  {
    if (payload.length() > 0) {
      _payload = new uint8_t[payload.length()];
      memcpy(_payload, payload.c_str(), payload.length());
      _payload_len = payload.length();
      _payload_mine = true;
    }
  }

  Publish::Publish(String topic, const __FlashStringHelper* payload) :
    Message(MQTTPUBLISH),
    _topic(topic),
    _payload_len(strlen_P((PGM_P)payload)), _payload(new uint8_t[_payload_len + 1]),
    _payload_mine(true)
  {
    strncpy((char*)_payload, (PGM_P)payload, _payload_len);
  }

  Publish Publish_P(String topic, PGM_P payload, uint32_t length) {
    uint8_t *p = new uint8_t[length];
    memcpy_P(p, payload, length);
    return Publish(topic, p, length, true);
  }

  Publish::Publish(uint8_t flags, uint8_t* data, uint32_t length) :
    Message(MQTTPUBLISH, flags),
    _payload(NULL), _payload_len(0),
    _payload_mine(false)
  {
    uint32_t pos = 0;
    _topic = read<String>(data, pos);
    if (qos() > 0)
      _packet_id = read<uint16_t>(data, pos);

    _payload_len = length - pos;
    if (_payload_len > 0) {
      _payload = new uint8_t[_payload_len];
      memcpy(_payload, data + pos, _payload_len);
      _payload_mine = true;
    }
  }

  Publish::~Publish() {
    if (_payload_mine)
      delete [] _payload;
  }

  Publish& Publish::set_qos(uint8_t q, uint16_t pid) {
    if (q > 2)
      q = 2;

    _flags &= ~0x06;
    if (q) {
      _flags |= q << 1;
      _packet_id = pid;
    }
    return *this;
  }

  String Publish::payload_string(void) const {
    String str;
    str.reserve(_payload_len);
    for (uint32_t i = 0; i < _payload_len; i++)
      str += (char)_payload[i];

    return str;
  }

  uint32_t Publish::variable_header_length(void) const {
    return 2 + _topic.length() + (qos() ? 2 : 0);
  }

  void Publish::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _topic);
    if (qos())
      write_packet_id(buf, bufpos);
  }

  uint32_t Publish::payload_length(void) const {
    return _payload_len;
  }

  void Publish::write_payload(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _payload, _payload_len);
  }

  uint8_t Publish::response_type(void) const {
    switch (qos()) {
    case 0:
      return 0;
    case 1:
      return MQTTPUBACK;
    case 2:
      return MQTTPUBREC;
    }
  }

  // PublishAck class
  PublishAck::PublishAck(uint16_t pid) :
    Message(MQTTPUBACK, pid)
  {}

  PublishAck::PublishAck(uint8_t* data, uint32_t length) :
    Message(MQTTPUBACK)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);
  }

  // PublishRec class
  PublishRec::PublishRec(uint16_t pid) :
    Message(MQTTPUBREC, pid)
  {}

  PublishRec::PublishRec(uint8_t* data, uint32_t length) :
    Message(MQTTPUBREC)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);
  }

  uint32_t PublishRec::variable_header_length(void) const {
    return 2;
  }

  void PublishRec::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write_packet_id(buf, bufpos);
  }

  // PublishRel class
  PublishRel::PublishRel(uint16_t pid) :
    Message(MQTTPUBREL, pid)
  {}

  PublishRel::PublishRel(uint8_t* data, uint32_t length) :
    Message(MQTTPUBREL)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);
  }

  uint32_t PublishRel::variable_header_length(void) const {
    return 2;
  }

  void PublishRel::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write_packet_id(buf, bufpos);
  }

  // PublishComp class
  PublishComp::PublishComp(uint16_t pid) :
    Message(MQTTPUBREC, pid)
  {}

  PublishComp::PublishComp(uint8_t* data, uint32_t length) :
    Message(MQTTPUBCOMP)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);
  }

  uint32_t PublishComp::variable_header_length(void) const {
    return 2;
  }

  void PublishComp::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write_packet_id(buf, bufpos);
  }

  // Subscribe class
  Subscribe::Subscribe(uint16_t pid) :
    Message(MQTTSUBSCRIBE, pid),
    _buffer(NULL), _buflen(0)
  {}

  Subscribe::Subscribe(uint16_t pid, String topic, uint8_t qos) :
    Message(MQTTSUBSCRIBE, pid),
    _buffer(NULL), _buflen(0)
  {
    _buffer = new uint8_t[2 + topic.length() + 1];
    write(_buffer, _buflen, topic);
    _buffer[_buflen++] = qos;
  }

  Subscribe::~Subscribe() {
    delete [] _buffer;
  }

  Subscribe& Subscribe::add_topic(String topic, uint8_t qos) {
    _buffer = (uint8_t*)realloc(_buffer, _buflen + 2 + topic.length() + 1);
    write(_buffer, _buflen, topic);
    _buffer[_buflen++] = qos;
    return *this;
  }

  uint32_t Subscribe::variable_header_length(void) const {
    return 2;
  }

  void Subscribe::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write_packet_id(buf, bufpos);
  }

  uint32_t Subscribe::payload_length(void) const {
    return _buflen;
  }

  void Subscribe::write_payload(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _buffer, _buflen);
  }

  // SubscribeAck class
  SubscribeAck::SubscribeAck(uint8_t* data, uint32_t length) :
    Message(MQTTSUBACK),
    _rcs(NULL)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);

    _num_rcs = length - pos;
    if (_num_rcs > 0) {
      _rcs = new uint8_t[_num_rcs];
      for (uint32_t i = 0; i < _num_rcs; i++)
	_rcs[i] = read<uint8_t>(data, pos);
    }
  }

  SubscribeAck::~SubscribeAck() {
    if (_rcs != NULL)
      delete [] _rcs;
  }

  // Unsubscribe class
  Unsubscribe::Unsubscribe(uint16_t pid) :
    Message(MQTTSUBSCRIBE, pid),
    _buffer(NULL), _buflen(0)
  {}

  Unsubscribe::Unsubscribe(uint16_t pid, String topic) :
    Message(MQTTSUBSCRIBE, pid),
    _buffer(NULL), _buflen(0)
  {
    _buffer = (uint8_t*)malloc(2 + topic.length());
    write(_buffer, _buflen, topic);
  }

  Unsubscribe::~Unsubscribe() {
    free(_buffer);
  }

  Unsubscribe& Unsubscribe::add_topic(String topic) {
    _buffer = (uint8_t*)realloc(_buffer, _buflen + 2 + topic.length());
    write(_buffer, _buflen, topic);

    return *this;
  }

  uint32_t Unsubscribe::variable_header_length(void) const {
    return 2;
  }

  void Unsubscribe::write_variable_header(uint8_t *buf, uint32_t& bufpos) const {
    write_packet_id(buf, bufpos);
  }

  uint32_t Unsubscribe::payload_length(void) const {
    return _buflen;
  }

  void Unsubscribe::write_payload(uint8_t *buf, uint32_t& bufpos) const {
    write(buf, bufpos, _buffer, _buflen);
  }

  // SubscribeAck class
  UnsubscribeAck::UnsubscribeAck(uint8_t* data, uint32_t length) :
    Message(MQTTUNSUBACK)
  {
    uint32_t pos = 0;
    _packet_id = read<uint16_t>(data, pos);
  }

} // namespace MQTT


text:
package com.github.gserv.serv.wx.support.api.userinfo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 微信用户信息
 *
 * @author shiying
 *
 */
public class WeixinUser implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 8307256121691974884L;

	/**
	 * 是否关注
	 */
	private boolean subscribe;

	/**
	 * Openid
	 */
	private String openid;

	/**
	 * 昵称的Base64
	 */
	private String nickname;

	/**
	 * 性别
	 */
	private Sex sex;

	/**
	 * 城市
	 */
	private String city;

	/**
	 * 用户所在国家
	 */
	private String country;

	/**
	 * 用户所在省份
	 */
	private String province;

	/**
	 * 用户的语言,简体中文为zh_CN
	 */
	private String language;

	/**
	 * 头像URL地址
	 */
	private String headimgurl;

	/**
	 * 最后关注时间
	 */
	private Date subscribe_time;

	/**
	 * Unionid, 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)
	 */
	private String unionid;

	/**
	 * 公众号运营者对粉丝的备注
	 */
	private String remark;

	/**
	 * 用户所在的分组ID
	 */
	private Integer groupid;

	/**
	 * 特权信息
	 */
	private List<String> privilege;

	/**
	 * 性别枚举
	 *
	 * @author shiying
	 *
	 */
	public static enum Sex {
		unknown, man, woman
	}

	public boolean isSubscribe() {
		return subscribe;
	}

	public void setSubscribe(boolean subscribe) {
		this.subscribe = subscribe;
	}

	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openid) {
		this.openid = openid;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public Sex getSex() {
		return sex;
	}

	public void setSex(Sex sex) {
		this.sex = sex;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getHeadimgurl() {
		return headimgurl;
	}

	public void setHeadimgurl(String headimgurl) {
		this.headimgurl = headimgurl;
	}

	public Date getSubscribe_time() {
		return subscribe_time;
	}

	public void setSubscribe_time(Date subscribe_time) {
		this.subscribe_time = subscribe_time;
	}

	public String getUnionid() {
		return unionid;
	}

	public void setUnionid(String unionid) {
		this.unionid = unionid;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Integer getGroupid() {
		return groupid;
	}

	public void setGroupid(Integer groupid) {
		this.groupid = groupid;
	}

	public List<String> getPrivilege() {
		return privilege;
	}

	public void setPrivilege(List<String> privilege) {
		this.privilege = privilege;
	}

}


text:
from django.shortcuts import render_to_response
from django.template import RequestContext
from utils.twitter import User

def index(request):
	return render_to_response('index.html', context_instance=RequestContext(request))

def iphone(request):
	return render_to_response('index_iphone.html')

def mobile(request):
	return render_to_response('index_mobile.html')

def hide_from_google_analytics(request):
	return render_to_response('tracking_cookie.html')


text:
/**
 * @class Admin_Form_UserInvite
 * @extends CM_Form_Abstract
 */
var Admin_Form_UserInvite = CM_Form_Abstract.extend({

	/** @type String */
	_class: 'Admin_Form_UserInvite'
});