text:
'use strict';

/* ===== Configuration ======== */
var API_KEY = null;  // API KEY HERE!
var SEARCH_DELAY = 500;  // in milliseconds
var SLIDER_INTERVAL = 500;  // in ms
var SCROLL_TRIGGER = 300;  // in pixels, before hitting the bottom

/* ============= Global Variables ============= */
var state = "watching";
var player = null;
var videoDuration = null;
var lastKeystroke = null;
var prev_state = null;
var searchResults = {};
var queue = [];
var nextPageToken = null;
var sliderInUse = false;
var isSearching = false;

var autolinker = new Autolinker({twitter: false, hashtag: false});

window.onload = function() {
    var videoID = window.location.hash.slice(1, 1 + 11)
    if (videoID.length == 11)
        loadVideo(videoID);
    else
        changeVideo('WFxPkhLNrcc');

    setInterval(updateSlider, SLIDER_INTERVAL);

    /* BUGFIX
     *
     * I have no idea why but YouTube's iframe API doesn't always work as documented in the docs in case of
     * `onStateChange` event. So we poll the state of the player every 10 ms.
     *
     * Source:
     *     http://stackoverflow.com/a/17078152/4466589
     *     from https://stackoverflow.com/questions/17078094/youtube-iframe-player-api-onstatechange-not-firing
     */
    setInterval(function() {
        var state = player.getPlayerState();

        if (state != prev_state)
            video_onStateChange();

        prev_state = player.getPlayerState();
    }, 50);
}

function loadVideo(videoId) {
    if (player) {
        player.destroy();
    }

    var page_content = document.getElementsByClassName("page-content")[0];
    page_content.clientWidth;

    player = new YT.Player('player', {
        videoId: videoId,
        width: page_content.clientWidth,
        height: page_content.clientWidth * 9 / 16,
        events: {
          'onReady': video_onReady,
        },
        playerVars: {  // For details: https://developers.google.com/youtube/player_parameters?playerVersion=HTML5
          autohide: 1,
          showinfo: 0,
          disablekb: 1,
          iv_load_policy: 3,
          rel: 0
        }
    });

    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState != 4 || xmlHttp.status != 200)  // check if it's successfull and completely loaded
            return;

        var response = JSON.parse(xmlHttp.responseText);

        var video_title = document.getElementById("video-title");
        var video_desc = document.getElementById("video-desc");
        var view_count = document.getElementById("view-count");

        video_title.textContent = response.items[0].snippet.title;
        video_desc.innerHTML = autolinker.link(response.items[0].snippet.description.split("\n").join("
"));
        view_count.textContent = parseInt(response.items[0].statistics.viewCount).toLocaleString();

        var likes = parseInt(response.items[0].statistics.likeCount);
        var dislikes = parseInt(response.items[0].statistics.dislikeCount);

        document.getElementById("like-dislike").MaterialProgress.setProgress(likes * 100 / (likes + dislikes));

        var tabTitle = document.getElementsByTagName("title")[0];
        tabTitle.textContent = response.items[0].snippet.title + " - EssentialYouTube";

        var slider = document.getElementById("slider");
        slider.setAttribute("max", parseDuration(response.items[0].contentDetails.duration));
        slider.value = 0;

    };

    xmlHttp.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=" + videoId + "&key=" + API_KEY, true);
    xmlHttp.send(null);
}

function nextVideo() {
    if (queue.length) {
        changeVideo(queue.shift().id.videoId);
        refreshQueue();
    }
    else {
        player.stopVideo();
        updateSlider();
    }
}

function updateSlider() {
    if (sliderInUse)
        return;

    var slider = document.getElementById("slider");
    slider.MaterialSlider.change(player.getCurrentTime());
}

function enterSearch() {
    if (state === "searching")
        return;

    var player_container = document.getElementById("player-container");
    var controllers = document.getElementById("controllers");
    var video_info = document.getElementById("info");
    var search_results = document.getElementById("search-results");

    player_container.classList.add("hidden");
    video_info.classList.add("hidden");
    controllers.classList.remove("hidden");
    search_results.classList.remove("hidden");

    state = "searching";
}

function exitSearch() {
    if (state === "watching")
        return;

    var player_container = document.getElementById("player-container");
    var controllers = document.getElementById("controllers");
    var video_info = document.getElementById("info");
    var search_results = document.getElementById("search-results");

    search_results.classList.add("hidden");
    controllers.classList.add("hidden");
    player_container.classList.remove("hidden");
    video_info.classList.remove("hidden");

    state = "watching";
}

function search(nodelay, nextPage) {
    var date = new Date();

    if (!nodelay && date.getTime() - lastKeystroke < SEARCH_DELAY)
        return;

    if (isSearching)
        return;

    isSearching = true;

    var search_i = document.getElementById("search");

    var xmlHttp = new XMLHttpRequest();

    var url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=' + encodeURIComponent(search_i.value) + '&type=video&maxResults=10&key=' + API_KEY;
    if (nextPage && nextPageToken)
        url += '&pageToken=' + nextPageToken;

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState != 4 || xmlHttp.status != 200)  // check if it's successfull and completely loaded
            return;

        var response = JSON.parse(xmlHttp.responseText);

        nextPageToken = response.nextPageToken;

        for (var i=0; i < response.items.length; ++i) {
            var item = response.items[i];

            searchResults[item.id.videoId] = item;
        }

        refreshSearchResults();
        isSearching = false;
    };

    xmlHttp.open('GET', url, true);
    xmlHttp.send(null);

    if (!nextPage)
        searchResults = {};
}

function refreshSearchResults() {
    var searchResultTemplate = "" +
        '
' +
          '
' +
            '
' +
              '
' +
                '{title}' +
              '
' +
            '
' +
            '
' +
              '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="add_onClick(\'{videoID}\')" title="Add to queue">' +
                'playlist_add' +
              '</button>' +
            '
' +
            '
' +
              '
' +
                '' +
                  '' +
                '' +
              '
' +
              '
' +
                '{description}' +
              '
' +
            '
' +
          '
' +
        '
';

    var search_results = document.getElementById("search-results");

    search_results.innerHTML = '';

    for (var itemID in searchResults) {
        var item = searchResults[itemID];

        search_results.innerHTML += searchResultTemplate.supplant({videoID: item.id.videoId,
                                                                   title: item.snippet.title,
                                                                   thumbnailURL: item.snippet.thumbnails.high.url,
                                                                   description: autolinker.link(item.snippet.description)
                                                               });
    }
}

function refreshQueue() {
    var FIRST_ENTRY_TEMPLATE = '
' +
                                 '
' +
                                   '
' +
                                     '
'+
                                       'Next' +
                                     '
' +
                                   '
' +
                                   '
' +
                                     '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="downward_onClick(\'{pos}\')" disabled>' +
                                       'arrow_upward' +
                                     '</button>' +
                                     '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="downward_onClick(\'{pos}\')" title="Move downwards in queue">' +
                                       'arrow_downward' +
                                     '</button>' +
                                     '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="remove_onClick(\'{pos}\')" title="Remove from queue">' +
                                       'remove' +
                                     '</button>' +
                                   '
' +
                                   '
' +
                                     '
' +
                                       '' +
                                     '
' +
                                     '
' +
                                       '{title}' +
                                     '
' +
                                   '
' +
                                 '
' +
                               '
';

    var CONSEQ_ENTRY_TEMPLATE = '
' +
                                  '
' +
                                    '
' +
                                      '{title}' +
                                    '
' +
                                    '
' +
                                      '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="upward_onClick(\'{pos}\')" title="Move upwards in queue">' +
                                        'arrow_upward' +
                                      '</button>' +
                                      '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="downward_onClick(\'{pos}\')" title="Move downwards in queue" {isDisabled}>' +
                                        'arrow_downward' +
                                      '</button>' +
                                      '<button class="mdl-button mdl-button--icon mdl-js-button" onclick="remove_onClick(\'{pos}\')" title="Remove from queue">' +
                                        'remove' +
                                      '</button>' +
                                    '
' +
                                  '
' +
                                '
';

    var queue_list = document.getElementById("queue");

    // delete all the entries
    while (queue_list.lastChild) {
        queue_list.removeChild(queue_list.lastChild);
    }

    // create the first entry
    if (queue.length) {
        queue_list.innerHTML = FIRST_ENTRY_TEMPLATE.supplant({title: queue[0].snippet.title,
                                                              thumbnailURL: queue[0].snippet.thumbnails.high.url,
                                                              pos: 0});
    }

    // create rest of the entries
    for (var i=1; i < queue.length; ++i) {
        queue_list.innerHTML += CONSEQ_ENTRY_TEMPLATE.supplant({title: queue[i].snippet.title,
                                                                pos: i,
                                                                isDisabled: i == queue.length - 1 ? "disabled" : ""});
    }
}

function changeVideo(videoID) {
    window.location.hash = videoID;
}

/* ==================================================== CALLBACKS =================================================== */
window.onhashchange = function() {
    var videoID = window.location.hash.slice(1, 1 + 11);
    if (videoID.length == 11) {
        loadVideo(videoID);
    }
}

function header_title_onClick() {
    document.getElementsByTagName("main")[0].scrollTop = 0;
}

function video_title_onClick(videoID) {
    exitSearch();
    changeVideo(videoID);
}

function add_onClick(id) {
    queue.push(searchResults[id]);
    refreshQueue();
}

function queue_thumbnail_onClick() {
    nextVideo();
}

function queue_title_onClick() {
    nextVideo();
}

function thumbnail_onClick(videoID) {
    exitSearch();
    changeVideo(videoID);
}

function close_onClick() {
    exitSearch();
}

function main_onScroll(main) {
    if (state === "searching" && main.scrollTop + main.clientHeight + SCROLL_TRIGGER >= main.scrollHeight)
        search(true, true);
}

function search_onInput(input_e) {
    if (input_e.value.length === 0) {
        exitSearch();
    }
    else {
        enterSearch();

        var date = new Date();
        lastKeystroke = date.getTime();

        setTimeout(search, SEARCH_DELAY);
    }
}

function search_onKeydown(event) {
    if (event.keyCode == 13) {  // if enter is pressed
        enterSearch();
        search(true);
    }
}

function search_onClick(search_i) {
    if (search_i.value.length) {
        enterSearch();

        if (Object.keys(searchResults).length)
            refreshSearchResults();
        else
            search(true);
    }
}

function slider_onChange(slider) {
    player.seekTo(slider.value, true);
}

function slider_onMousedown() {
    sliderInUse = true;
}

function slider_onMouseup() {
    sliderInUse = false;
}

function remove_onClick(pos) {
    queue.splice(pos, 1);
    refreshQueue();
}

function upward_onClick(pos) {
    pos = parseInt(pos);
    queue.splice(pos - 1, 0, queue.splice(pos, 1)[0]);
    refreshQueue();
}

function downward_onClick(pos) {
    pos = parseInt(pos);
    queue.splice(pos + 1, 0, queue.splice(pos, 1)[0]);
    refreshQueue();
}

function playPause_onClick() {
    if (player.getPlayerState() === YT.PlayerState.PLAYING) {
        player.pauseVideo();
    }
    else {
        player.playVideo();
    }
}

function volume_onClick(pp_btn) {
    if (player.isMuted()) {
        pp_btn.innerHTML = 'volume_up';
        player.unMute();
    }
    else {
        player.mute();
        pp_btn.innerHTML = 'volume_off';
    }
}

function video_onStateChange() {
    var pp_btn = document.getElementById("play-pause");

    if (player.getPlayerState() === YT.PlayerState.ENDED) {
        if (document.getElementById("loopSwitch").checked) {
            player.seekTo(0, true);
            player.playVideo();
        }
        else {
            pp_btn.innerHTML = 'play_arrow';
            nextVideo();
        }
    }
    else if (player.getPlayerState() === YT.PlayerState.PLAYING) {
        pp_btn.innerHTML = 'pause';
    }
    else {
        pp_btn.innerHTML = 'play_arrow';
    }
}

function video_onReady(event) {
    event.target.playVideo();
}

function next_onClick() {
    nextVideo();
}

/* ==================================================== UTILITIES =================================================== */
// http://javascript.crockford.com/remedial.html
if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(
            /\{([^{}]*)\}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

// http://stackoverflow.com/a/25209563
function parseDuration(duration) {
    var matches = duration.match(/[0-9]+[HMS]/g);

    var seconds = 0;

    matches.forEach(function (part) {
        var unit = part.charAt(part.length-1);
        var amount = parseInt(part.slice(0,-1));

        switch (unit) {
            case 'H':
                seconds += amount * 60 * 60;
                break;
            case 'M':
                seconds += amount * 60;
                break;
            case 'S':
                seconds += amount;
                break;
            default:
        }
    });

    return seconds;
}


text:
<!DOCTYPE html>

    <title>Dynamo  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

Dynamo Docs (17% documented)

        Dynamo Reference

        Dynamo  Reference

            Classes

                ApplicationSwiftlet

                BundleSwiftlet

                DocumentSwiftlet

                DynamoHTTPConnection

                DynamoHTTPRequest

                DynamoSSLWebServer

                DynamoWebServer

                ExampleAppSwiftlet

                HTMLApplicationSwiftlet

                LoggingSwiftlet

                ProxySwiftlet

                SSLProxySwiftlet

                ServerPagesSwiftlet

                SessionApplication

                SessionSwiftlet

                _NSObject_

                _NSObject_

            Global Variables

                dynamoHtmlMimeType

                dynamoMimeTypeMapping

                dynamoPollingUsec

                dynamoStatusText

                dynanmoDefaultSessionExpiry

            Enums

                DynamoProcessed

                DynamoResponse

            Extensions

                NSData

                String

            Functions

                addressForHost(_:port:)

                dynamoTrace(_:)

            Protocols

                DynamoBrowserSwiftlet

                DynamoSwiftlet

Dynamo - Dynamic Swift Web Server

Starting this project the intention was to code the simplest possible Web Server entirely
in Swift. Unfortunately I got a bit carried away adding features such as proxying and dynamic
reloading of server code. Dynamo now also works on Linux, see DynamoLinux.

So.. while Dynamo can be used in an iOS application as is demonstrated in this project, the focus
has turned to the server side to set up a simple framework inside which it is possible to experiment
with SSL, Proxies and what you could call <q>Swift Server Pages</q> which are loadable bundles of code
placed in the document hierarchy.

The Dynamo server core is based on <q>Swiftlets</q>, instances implementing the DynamoSwiftlet protocol.
These are presented with incoming HTTP requests from the browser and can choose to process it in any
manner it chooses. The developer passes in an array of swiftlet instances combining the features
and applications desired on server startup.

    @objc public protocol DynamoSwiftlet {

        @objc func present( httpClient: DynamoHTTPConnection ) -> DynamoProcessed
    }

    @objc public enum DynamoProcessed : Int {
        case
            NotProcessed, // does not recognise the request
            Processed, // has processed the request
            ProcessedAndReusable // "" and connection may be reused in HTTP/1.1
    }

For further information about the classes and protools that make up Dynamo please consult the jazzy docs
here. The Swiftlets included in the framework are as follows:

DocumentSwiftlet

The default swiftlet to serve documents from ~/Sites/host:port or the applications resources directory for iOS.

ProxySwiftlet, SSLProxySwiftlet

Dynamo can act as a proxy server logging what can be a surprising about of traffic from your browser.
To use the proxy, run OSX target and set your proxy to localhost:8080.

ApplicationSwiftlet, SessionSwiftlet

ApplicationSwiftlet is the abstract superclass of all <q>application</q> swiftlets parsing browser GET and POST
parameters and any Cookies. SessionSwiftlet adds the ability to have an application Swiftlet
created separately for each unique web user using Cookies.

BundleSwiftlet, ServerPagesSwiftlet

BundleSwiftlet, loads a swiftlet from a bundle with extension <q>.ssp</q> in an OSX application’s resources.
A simple python script can generate the Swift source for the bundle from a <q>.shtml</q> mixing HTML and Swift
language. The ServerPagesSwiftlet takes this a step further where the bundle is loaded from the
document root for the sever when used from the command line. If the bundle is updated for new functionality,
provided it contains the <q>AutoLoader.m</q> stub the new code will be <q>swizzled</q> into operation.

ExampleAppSwiftlet, TickTackToe, NumberGuesser

The ExampleAppSwiftlet is used in the tests for checking character encoding in GET and POST
form submission. TickTackToe is an example .ssp application in a bundle target. NumberGuesser is
implemented as a .shtml template compiled into swift code by the Utilities/sspcompiler.py script.
Changes made to these Swiftlets will take effect when you reload the page after a project build.

DynamoWebServer, DynamoSSLWebServer severs.

Consult OSX/AppDelegate.swift or iOS/AppDelegate.m of the OSX and iOS targets for how to create
instances of these classes.

    // create shared swiftlet for server applications
    let exampleTableGenerator = ExampleAppSwiftlet( pathPrefix: "/example" )
    let tickTackToeGame = BundleSwiftlet( pathPrefix: "/ticktacktoe", bundleName: "TickTackToe" )!

    let logger = {
        (msg: String) in
        println( msg )
    }

    // create non-SSL server/proxy on 8080
    DynamoWebServer( portNumber: serverPort, swiftlets: [
        LoggingSwiftlet( logger: dynamoTrace ),
        exampleTableGenerator,
        tickTackToeGame,
        SSLProxySwiftlet( logger: logger ),
        ProxySwiftlet( logger: logger ),
        ServerPagesSwiftlet( documentRoot: documentRoot ),
        DocumentSwiftlet( documentRoot: documentRoot )
    ] )

Creating the instance is sufficient for the server to start and run in it’s own threads.
There is an additional <q>Daemon</q> target creating a command line version of the sever which should
be run from inside the DynamoApp.app’s resources so it can find the Dynamo framework.

The Dynamo framework has a .podspec file so it can be brought into your project with the following:

    use_frameworks!

    target "<project>" do

        pod 'Dynamo', :git => 'https://github.com/johnno1962/Dynamo.git'

    end

Running an SSL server requires set of certificates which can be generated using code slightly modified
from robbiehanson’s CocoaHTTPServer under a
BSD license contained in the Utilities/DDKeyChain.[hm] source.

Performance

Testing with JMeter has shown Dynamo is capable of serving:

40,000 requests per minute for a static file in the documents directory (25 threads)

40,000 requests per minute for the NumberGuesser which reuses connections (see below)

18,000 requests per minute for TickTckToe which does not reuse connections (see below)

Reusing connections is important for large numbers of requests from the same client. This is
achieved by using a single DynamoHTTPConnection.response( html ) method call rather than
individual calls to method DynamoHTTPConnection.print( html ).

As ever, announcements of major commits to the repo will be made on twitter
@Injection4Xcode.

MIT License

Copyright © 2015 John Holdsworth

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the <q>Software</q>), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED <q>AS IS</q>, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

© 2016 johnno1962. All rights reserved. (Last updated: 2016-02-23)

Generated by jazzy ♪♫ v0.4.1, a Realm project.

redpajama_set_name: RedPajamaGithub


text:
const crypto = require('crypto');
const chalk = require('chalk');

/**
 * Display a warning message.
 *
 * @param {string} message
 */
function warn( message )
{
  if ( message in warn.cache ) {
    return;
  }

  const prefix = chalk.hex('#CC4A8B')('WARNING:');

  console.warn(chalk`${prefix} ${message}`);
}

warn.cache = Object.create(null);

/**
 * Display a warning message once.
 *
 * @param {string} message
 */
warn.once = function( message ) {
  warn( message );
  warn.cache[ message ] = true;
};

/**
 * @param  {*} data
 * @return {array}
 */
function maybeArrayWrap( data )
{
  return Array.isArray( data ) ? data : [ data ];
}

/**
 * Filter out invalid hash algorithms.
 *
 * @param  {array} hashes
 * @return {array} Valid hash algorithms
 */
function filterHashes( hashes )
{
  const validHashes = crypto.getHashes();

  return hashes.filter( hash => {
    if ( validHashes.includes(hash) ) {
      return true;
    }

    warn(chalk`{blueBright ${hash}} is not a supported hash algorithm`);

    return false;
  });
}

/**
 * See {@link https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity|Subresource Integrity} at MDN
 *
 * @param  {array} hashes - The algorithms you want to use when hashing `content`
 * @param  {string} content - File contents you want to hash
 * @return {string} SRI hash
 */
function getSRIHash( hashes, content )
{
  return Array.isArray( hashes ) ? hashes.map( hash => {
    const integrity = crypto.createHash(hash).update(content, 'utf-8').digest('base64');

    return `${hash}-${integrity}`;
  }).join(' ') : '';
}

/**
 * Get the data type of an argument.
 *
 * @param  {*} v - Some variable
 * @return {string} Data type
 */
function varType( v )
{
  const [ , type ] = Object.prototype.toString.call( v ).match(/\[object\s(\w+)\]/);

  return type;
}

/**
 * Get an object sorted by keys.
 *
 * @param  {object} object
 * @param {function} compareFunction
 * @return {object}
 */
function getSortedObject(object, compareFunction)
{
  const keys = Object.keys(object);

  keys.sort( compareFunction );

  return keys.reduce(
    (sorted, key) => (sorted[ key ] = object[ key ], sorted),
    Object.create(null)
  );
}

module.exports = {
  maybeArrayWrap,
  filterHashes,
  getSRIHash,
  warn,
  varType,
  getSortedObject,
};


text:
[![NPM Version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]

Intent: Create an npm module for use with mailservices DSL feature testing.

# Setup

- Requires
  - npm install -g webdriver-manager
  - npm install -g codeclimate-test-reporter
  - npm install -g coveralls
  - webdriver-manager update --standalone
- git clone https://github.com/ctrees/msfeature
- cd msfeature
- npm install
- phantomjs -w
- webdriver-manager start
- npm start
- npm run coverage

# Debug

- Change test/runner.js  config.tags = ['@wip'];
- comment out additional browsers ( I just use chrome to debug )
- tag @wip to feature file Scenario you want to debug
- npm run coverage

# Add feature
- Create new feature file: (example test/features/scroll.feature )
- Add new target site page feature (routes.js, views) if required (example test/site/views/partials/compact-post.swig )
- npm run coverage (to pick up the new regex you need to write)
- add regex to lib/step_definitions/index.js with Ext.somefunction (example Ext.Custom.scrolltoid )
- add the function to corresponding file lib/step_definitins/ext/somefunction.js (example lib/step_definitions/ext/custom.js )

# view coverage

- cd msfeature/coverage
- serve -p 3333
- browse to: http://localhost:3333/lcov-report/

# pre-Setup

- create github repo: [git-url]
- create npm account
- Follow instructions: [Publish npm package](https://docs.npmjs.com/getting-started/publishing-npm-packages)
    - npm login
    - npm publish
- push to github
- turn on travis sync [travis-profile]
- check travis status [travis-url]
- check npm package [npm-url]

# Maintainers

The npm module for this library is maintained by:

* [Chris Trees](http://github.com/ctrees)
* [mfeature Issues / Bugs][git-bug]

[List of all contributors](https://github.com/ctrees/msfeature/graphs/contributors)

# License

[MIT](LICENSE) © [Chris Trees](http://github.com/ctrees)

## Notes

[webdriver-docs]
[travis-docs]
[npm-docs]

# Inspired

This module is inspired by [Arnaud Dezandee](https://github.com/Adezandee/cucumber-mink) and PHP [Behat/MinkExtension](https://github.com/Behat/MinkExtension).

[git-url]: https://github.com/ctrees/msfeature
[git-bug]: https://github.com/ctrees/msfeature/issues
[npm-image]: https://img.shields.io/npm/v/msfeature.svg?style=flat
[npm-url]: https://www.npmjs.com/package/msfeature
[travis-image]: https://img.shields.io/travis/ctrees/msfeature.svg?style=flat
[travis-url]: https://travis-ci.org/ctrees/msfeature
[travis-profile]: https://travis-ci.org/profile/ctrees
[bithound-image]: https://www.bithound.io/github/ctrees/msfeature/badges/score.svg
[bithound-url]: https://www.bithound.io/github/ctrees/msfeature

[webdriver-docs]: http://webdriver.io/

[travis-docs]: https://travis-ci.org/getting_started
[npm-docs]: https://docs.npmjs.com/getting-started/creating-node-modules


text:
static float delay_cache_r[AUDIO_BUFFER_SIZE * 2];
static float delay_cache_w[AUDIO_BUFFER_SIZE * 2];

CTSS_DSPNode *ctss_delay_sdram(char *id,
                               CTSS_DSPNode *src,
                               uint32_t len,
                               float feedback,
                               uint8_t channels) {
  CTSS_DSPNode *node     = ctss_node(id, channels);
  CTSS_DelayState *state = malloc(sizeof(CTSS_DelayState));
  state->delayLine       = ct_sdram_calloc(len * channels, sizeof(float));
  state->src             = src->buf;
  state->len             = len * channels;
  state->feedback        = feedback;
  state->channels        = channels;
  state->writePos        = 0;
  state->readPos         = channels;
  state->writePtr        = state->delayLine;
  state->readPtr         = state->delayLine + channels;
  node->state            = state;
  node->handler          = ctss_process_delay_sdram;
  return node;
}

uint8_t ctss_process_delay_sdram(CTSS_DSPNode *node,
                                 CTSS_DSPStack *stack,
                                 CTSS_Synth *synth) {
  CTSS_UNUSED(synth);
  CTSS_UNUSED(stack);
  CTSS_DelayState *state = node->state;
  float fb               = state->feedback;
  uint32_t read          = 0;
  uint32_t write         = 0;
  uint32_t raddr         = (uint32_t)state->delayLine + state->readPos * 4;
  uint32_t waddr         = (uint32_t)state->delayLine + state->writePos * 4;
  float *src             = state->src;
  float *buf             = node->buf;
  size_t len             = AUDIO_BUFFER_SIZE * state->channels;
  BSP_SDRAM_ReadData(waddr, (uint32_t *)delay_cache_w, len);
  BSP_SDRAM_ReadData(raddr, (uint32_t *)delay_cache_r, len);
  while (len--) {
    delay_cache_w[write] = (*src++) + delay_cache_r[read++] * fb;
    *buf++               = delay_cache_w[write++];
    if (++state->readPos == state->len) {
      state->readPos = 0;
      read           = 0;
      raddr          = (uint32_t)state->delayLine;
      BSP_SDRAM_ReadData(raddr, (uint32_t *)delay_cache_r, len);
    }
    if (++state->writePos == state->len) {
      BSP_SDRAM_WriteData(waddr, (uint32_t *)delay_cache_w, write);
      waddr           = (uint32_t)state->delayLine;
      state->writePos = 0;
      write           = 0;
      BSP_SDRAM_ReadData(waddr, (uint32_t *)delay_cache_w, len);
    }
  }
  BSP_SDRAM_WriteData(waddr, (uint32_t *)delay_cache_w, write);
  return 0;
}


text:
package co.orderly.prestasac.representations

// Java
import java.lang.{Integer => JInteger}
import java.lang.{Long => JLong}

// Scala
import scala.reflect.BeanProperty

// JAXB
import javax.xml.bind.annotation._

// MOXy
import org.eclipse.persistence.oxm.annotations.XmlNameTransformer

// Narcolepsy
import co.orderly.narcolepsy._
import marshallers.jaxb.moxy.CamelCase2Underscore

// Prestasac
import shared._

/**
 * The Address representation holds the information pertaining to an
 * address in PrestaShop.
 *
 * A typical representation looks a little like this:
 *
 * <?xml version="1.0" encoding="UTF-8"?>
 * <prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
 *   <address>
 *     <id><![CDATA[13]]></id>
 *     <id_customer xlink:href="http://www.psychicbazaar.com/api/customers/10"><![CDATA[10]]></id_customer>
 *     <id_manufacturer></id_manufacturer>
 *     <id_supplier></id_supplier>
 *     <id_country xlink:href="http://www.psychicbazaar.com/api/countries/1"><![CDATA[1]]></id_country>
 *     <id_state></id_state>
 *     <alias><![CDATA[My address]]></alias>
 *     <company></company>
 *     <lastname><![CDATA[lala]]></lastname>
 *     <firstname><![CDATA[john]]></firstname>
 *     <address1><![CDATA[wqeqwewq]]></address1>
 *     <address2></address2>
 *     <postcode><![CDATA[01999]]></postcode>
 *     <city><![CDATA[Berlin]]></city>
 *     <other></other>
 *     <phone></phone>
 *     <phone_mobile></phone_mobile>
 *     <dni></dni>
 *     <vat_number></vat_number>
 *     <deleted><![CDATA[0]]></deleted>
 *     <date_add><![CDATA[2012-09-07 10:41:26]]></date_add>
 *     <date_upd><![CDATA[2012-09-07 10:41:26]]></date_upd>
 *   </address>
 * </prestashop>
 */
@XmlRootElement(name = "prestashop")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlNameTransformer(classOf[CamelCase2Underscore])
class Address extends Representation {

  @XmlElement(required = true)
  @BeanProperty
  var address: AddressElement = _
}

/**
 * The AddressElement holds the core fields for the address.
 */
@XmlAccessorType(XmlAccessType.FIELD)
class AddressElement extends PrestaShopTimestampedIdentity {

  // -------------------------------------------------------------------------------------------------------------------
  // XLinks into other resources
  // -------------------------------------------------------------------------------------------------------------------

  // TODO: retrieve the xlink:href as well
  @XmlElement(nillable = true)
  @BeanProperty
  var idCustomer: PrestaShopXLink = _ // JLong = _

  // TODO: retrieve the xlink:href as well
  @XmlElement(nillable = true)
  @BeanProperty
  var idManufacturer: PrestaShopXLink = _ // JLong = _

  // TODO: retrieve the xlink:href as well
  @XmlElement(nillable = true)
  @BeanProperty
  var idSupplier: PrestaShopXLink = _ // JLong = _

  // TODO: retrieve the xlink:href as well
  @BeanProperty
  var idCountry: PrestaShopXLink = _ // JLong = _

  // TODO: retrieve the xlink:href as well
  @XmlElement(nillable = true)
  @BeanProperty
  var idState: PrestaShopXLink = _ // JLong = _

  // -------------------------------------------------------------------------------------------------------------------
  // Resource-specific fields
  // -------------------------------------------------------------------------------------------------------------------

  @BeanProperty
  var alias: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var company: String = _

  @XmlElement(name = "lastname")
  @BeanProperty
  var lastName: String = _

  @XmlElement(name = "firstname")
  @BeanProperty
  var firstName: String = _

  @BeanProperty
  var address1: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var address2: String = _

  @BeanProperty
  var postcode: String = _

  @BeanProperty
  var city: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var other: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var phone: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var phoneMobile: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var dni: String = _

  @XmlElement(nillable = true)
  @BeanProperty
  var vatNumber: String = _

  @BeanProperty
  var deleted: JInteger = _

  // -------------------------------------------------------------------------------------------------------------------
  // Associations
  // -------------------------------------------------------------------------------------------------------------------

  // None
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
FlightPlan::Application.initialize!


text:
\hypertarget{structseqan_1_1_performance_sample}{\section{seqan\-:\-:\-Performance\-Sample \-Struct \-Reference}
\label{structseqan_1_1_performance_sample}\index{seqan\-::\-Performance\-Sample@{seqan\-::\-Performance\-Sample}}
}
\subsection*{\-Public \-Member \-Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{structseqan_1_1_performance_sample_a715fe9ca22322f3d51e27e19783ca11d}{{\bfseries \-Performance\-Sample} (\-Char\-String n)}\label{structseqan_1_1_performance_sample_a715fe9ca22322f3d51e27e19783ca11d}

\item
\hypertarget{structseqan_1_1_performance_sample_abb034f31c5c550ce6c027806df55f2cb}{{\bfseries \-Performance\-Sample} (\-Char\-String n, double start)}\label{structseqan_1_1_performance_sample_abb034f31c5c550ce6c027806df55f2cb}

\item
\hypertarget{structseqan_1_1_performance_sample_aa32edc31e6ad815364f5351959bef27f}{void {\bfseries start} ()}\label{structseqan_1_1_performance_sample_aa32edc31e6ad815364f5351959bef27f}

\item
\hypertarget{structseqan_1_1_performance_sample_a77c483d55c1ce27e7e436d968ec24752}{void {\bfseries end} ()}\label{structseqan_1_1_performance_sample_a77c483d55c1ce27e7e436d968ec24752}

\item
\hypertarget{structseqan_1_1_performance_sample_a5eff59afa1efeb5ff09975f2a70c6795}{double {\bfseries get\-Time} ()}\label{structseqan_1_1_performance_sample_a5eff59afa1efeb5ff09975f2a70c6795}

\item
\hypertarget{structseqan_1_1_performance_sample_a339cf52d519b7948043f9aa1ea152eb6}{void {\bfseries print\-To\-Stdout} ()}\label{structseqan_1_1_performance_sample_a339cf52d519b7948043f9aa1ea152eb6}

\item
\hypertarget{structseqan_1_1_performance_sample_a3fbe8137dc6639d13c536f1e5f5d9bd2}{void {\bfseries take\-Average\-Values} (\-String$<$ \hyperlink{structseqan_1_1_performance_sample}{\-Performance\-Sample} $>$ list)}\label{structseqan_1_1_performance_sample_a3fbe8137dc6639d13c536f1e5f5d9bd2}

\end{DoxyCompactItemize}
\subsection*{\-Public \-Attributes}
\begin{DoxyCompactItemize}
\item
\hypertarget{structseqan_1_1_performance_sample_ad57c1dc73d7aeead774dc52c2bc9c21e}{\-Char\-String {\bfseries name}}\label{structseqan_1_1_performance_sample_ad57c1dc73d7aeead774dc52c2bc9c21e}

\item
\hypertarget{structseqan_1_1_performance_sample_aa836fab9103241ea23d5da5642aea14f}{double {\bfseries start\-Time}}\label{structseqan_1_1_performance_sample_aa836fab9103241ea23d5da5642aea14f}

\item
\hypertarget{structseqan_1_1_performance_sample_a56846d44d5d90ff877cb09ac3a50408d}{double {\bfseries end\-Time}}\label{structseqan_1_1_performance_sample_a56846d44d5d90ff877cb09ac3a50408d}

\end{DoxyCompactItemize}

\-The documentation for this struct was generated from the following file\-:\begin{DoxyCompactItemize}
\item
include/seqan/\-G\-Structs/\-Performance\-Sample.\-h\end{DoxyCompactItemize}


text:
import json

REL = "rel"
VAL = "val"

# Catalogue structure
CATALOGUE_METADATA  = "item-metadata"    # Name of the array of metadata about the catalogue itself
ITEMS = "items"
HREF = "href"
ITEM_METADATA = "i-object-metadata" # Name of the array of metadata about each item in the catalogue

# Mandatory relations & types
ISCONTENTTYPE_RELATION = "urn:X-tsbiot:rels:isContentType"  # Mandatory for catalogues, but not resources
CATALOGUE_TYPE = "application/vnd.tsbiot.catalogue+json"
DESCRIPTION_RELATION = "urn:X-tsbiot:rels:hasDescription:en"

# Optional relations & types
SUPPORTS_SEARCH_RELATION = "urn:X-tsbiot:rels:supportsSearch"
SUPPORTS_SEARCH_VAL = "urn:X-tsbiot:search:simple"
HAS_HOMEPAGE_RELATION = "urn:X-tsbiot:rels:hasHomepage"
CONTAINS_CONTENT_TYPE_RELATION = "urn:X-tsbiot:rels:containsContentType"

# We manage Catalogues and Resources as raw Python JSON objects (i.e. we construct them in their final form)

def _values(metadata, rel):
    """Searches a set <metadata> to find all relations <rel>
    Returns a list of the values of those relations
    (A list, because a rel can occur more than once)"""
    result = []
    for r in metadata:
        if(r[REL] == rel):
            result.append(r[VAL])

    return result

class Base:
    # Functionality common to both Catalogues and Resources
    def __init__(self):
        self.metadata = []  # Called either CATALOGUE_METADATA or RESOURCE_METADATA
        self.items = []     # Only for Catalogues. Held as list of instances.
        self.href = None    # Only for Resources

    def addRelation(self, rel, val):
        self.metadata += [{REL:rel, VAL:val}]

    def replaceRelation(self, rel, val):
        for i in range(len(self.metadata)):
            if self.metadata[i][REL]==rel:
                self.metadata[i][REL]=val

    def rels(self):
        """Returns a LIST of all the metadata relations"""
        r = []
        for i in self.metadata:
            r = r + i[REL]
        return []

    def values(self, rel):
        """Returns a LIST of the values of all relations of type rel, since HyperCat allows rels to be repeated"""
        return _values(self.metadata, rel)

    def prettyprint(self):
        """Return hypercat formatted prettily"""
        return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))

    def asJSONstr(self):
        """Return hypercat as a string, of minimum length"""
        return json.dumps(self.asJSON(), sort_keys=True, separators=(',', ':'))

    def isCatalogue(self):
        return CATALOGUE_TYPE in self.values(ISCONTENTTYPE_RELATION)

    def setHref(self,href):
        self.href=href

class Hypercat(Base):
    """Create a valid Hypercat catalogue"""
    # Catalogues must be of type catalogue, have a description, and contain at least an empty array of items

    def __init__(self, description):
        Base.__init__(self)
        assert isinstance(description, basestring), "Description argument must be a string"
        # TODO: Check description is ASCII, since JSON can only encode that
        self.metadata = [
            { REL:ISCONTENTTYPE_RELATION, VAL:CATALOGUE_TYPE },
            { REL:DESCRIPTION_RELATION, VAL:description }]

    def asJSON(self, asChild=False):
        j = {}
        if(asChild):
            j[HREF] = self.href
            j[ITEM_METADATA] = self.metadata
        else:
            j[CATALOGUE_METADATA] = self.metadata
            j[ITEMS]=[]
            for c in self.items:
                j[ITEMS] += [c.asJSON(asChild=True)]
        return j

    def addItem(self, child, href):
        """Add a new item (a catalogue or resource) as a child of this catalogue."""
        assert isinstance(child, Base), "child must be a hypercat Catalogue or Resource"
        child.setHref(href)
        for item in self.items:
            assert item.href != href, "All items in a catalogue must have unique hrefs : "+href
        self.items += [child]           # Add new
        return

    def replaceItem(self, child, href):
        """Replace an existing child (by matching the href). Guarantees not to change the order of items[]"""
        assert isinstance(child, Base), "child item must be a hypercat Catalogue or Resource"
        for i in range(len(self.items)):
            if(self.items[i].href == href):
                self.items[i] = child   # Replace existing
                return
        assert False, "No such child item to replace as "+href

    def description(self):  # 1.0 spec is unclear about whether there can be more than one description. We assume not.
        return self.values(DESCRIPTION_RELATION)[0]

    def items(self):
        return self.items

    def supportsSimpleSearch(self):
        self.addRelation(SUPPORTS_SEARCH_RELATION, SUPPORTS_SEARCH_VAL)

    def hasHomepage(self, url):
        self.addRelation(HAS_HOMEPAGE_RELATION, url)

    def containsContentType(self, contentType):
        self.addRelation(CONTAINS_CONTENT_TYPE_RELATION, contentType)

    def findByPath(self, rel, path):
        """Traverses children, building a path based on relation <rel>, until given path is found."""
        if((path=="") or (path=="/")):
            return(self)
        (front,dummy,rest) = path.lstrip("/").partition("/")
        for child in self.items:
            if front in child.values(rel):
                return child.findByPath(rel, rest)
        return None

    def recurse(self, fn, *args):
        """Calls fn on a hypercat and all its child hypercats (not resources)"""
        fn(self, *args)
        for i in self.items:
            if isinstance(i, Hypercat):
                self.recurse(i, *args)

class Resource(Base):
    """Create a valid Hypercat Resource"""
    # Resources must have an href, have a declared type, and have a description
    def __init__(self, description, contentType):
        """contentType must be a string containing an RFC2046 MIME type"""
        Base.__init__(self)
        self.metadata = [
            {REL:ISCONTENTTYPE_RELATION,VAL:contentType},
            {REL:DESCRIPTION_RELATION,VAL:description}]

    def asJSON(self, asChild=True):
        # Resources can only be children
        j = {}
        j[ITEM_METADATA] = self.metadata
        j[HREF] = self.href
        return j

def loads(inputStr):
    """Takes a string and converts it into an internal hypercat object, with some checking"""
    inCat = json.loads(inputStr)
    assert CATALOGUE_TYPE in _values(inCat[CATALOGUE_METADATA], ISCONTENTTYPE_RELATION)
    # Manually copy mandatory fields, to check that they are they, and exclude other garbage
    desc = _values(inCat[CATALOGUE_METADATA], DESCRIPTION_RELATION)[0]  # TODO: We are ASSUMING just one description, which may not be true
    outCat = Hypercat(desc)
    for i in inCat[ITEMS]:
        href = i[HREF]
        contentType = _values(i[ITEM_METADATA], ISCONTENTTYPE_RELATION) [0]
        desc = _values(i[ITEM_METADATA], DESCRIPTION_RELATION) [0]
        if contentType == CATALOGUE_TYPE:
            r = Hypercat(desc)
        else:
            r = Resource(desc, contentType)
        outCat.addItem(r, href)

    return outCat

#if __name__ == '__main__':
    # Unit tests
    #import unittest
    #unittest.unittest()


text:
<?php

/*
 * This file is part of the Silex framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Silex\Tests\Provider;

use Silex\Application;
use Silex\WebTestCase;
use Silex\Provider\RememberMeServiceProvider;
use Silex\Provider\SecurityServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Symfony\Component\HttpKernel\Client;

/**
 * SecurityServiceProvider.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class RememberMeServiceProviderTest extends WebTestCase
{
    public function testRememberMeAuthentication()
    {
        $app = $this->createApplication();

        $event = false;
        $app->on(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, function ($event) use ($app, &$event) {
            $event = true;
        });

        $client = new Client($app);

        $client->request('get', '/');
        $this->assertFalse($event, 'The interactive login has not been triggered yet');
        $client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'foo', '_remember_me' => 'true'));
        $client->followRedirect();
        $this->assertEquals('AUTHENTICATED_FULLY', $client->getResponse()->getContent());
        $this->assertTrue($event, 'The interactive login has been triggered');

        $this->assertNotNull($client->getCookiejar()->get('REMEMBERME'), 'The REMEMBERME cookie is set');
        $event = false;

        $client->getCookiejar()->expire('MOCKSESSID');

        $client->request('get', '/');
        $this->assertEquals('AUTHENTICATED_REMEMBERED', $client->getResponse()->getContent());
        $this->assertTrue($event, 'The interactive login has been triggered');

        $client->request('get', '/logout');
        $client->followRedirect();

        $this->assertNull($client->getCookiejar()->get('REMEMBERME'), 'The REMEMBERME cookie has been removed');
    }

    public function createApplication($authenticationMethod = 'form')
    {
        $app = new Application();

        $app['debug'] = true;
        unset($app['exception_handler']);

        $app->register(new SessionServiceProvider(), array(
            'session.test' => true,
        ));
        $app->register(new SecurityServiceProvider());
        $app->register(new RememberMeServiceProvider());

        $app['security.firewalls'] = array(
            'http-auth' => array(
                'pattern' => '^.*$',
                'form' => true,
                'remember_me' => array(),
                'logout' => true,
                'users' => array(
                    'fabien' => array('ROLE_USER', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
                ),
            ),
        );

        $app->get('/', function () use ($app) {
            if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) {
                return 'AUTHENTICATED_FULLY';
            } elseif ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
                return 'AUTHENTICATED_REMEMBERED';
            } else {
                return 'AUTHENTICATED_ANONYMOUSLY';
            }
        });

        return $app;
    }
}


text:
package org.jbb.system.impl;

import org.jbb.lib.commons.security.UserDetailsSource;
import org.jbb.lib.db.DbPropertyChangeListener;
import org.jbb.permissions.api.PermissionService;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class MockSystemConfig {

    @Bean
    @Primary
    public DbPropertyChangeListener dbPropertyChangeListener() {
        return Mockito.mock(DbPropertyChangeListener.class);
    }

    @Bean
    @Primary
    public UserDetailsSource userDetailsSource() {
        return Mockito.mock(UserDetailsSource.class);
    }

    @Bean
    @Primary
    public PermissionService permissionService() {
        return Mockito.mock(PermissionService.class);
    }

}


text:
<?php
namespace Procure\Application\Service\Output;

use Psr\Log\LoggerInterface;
use Exception;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
abstract class AbstractProcureDocSaveAs
{

    protected $logger;

    protected $filter;

    public function __toString()
    {
        return get_class($this->getFilter());
    }

    /**
     *
     * @return \Psr\Log\LoggerInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    /**
     *
     * @param LoggerInterface $logger
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    protected function logInfo($message)
    {
        if ($this->getLogger() != null) {
            $this->getLogger()->info($message);
        }
    }

    protected function logAlert($message)
    {
        if ($this->getLogger() != null) {
            $this->getLogger()->alert($message);
        }
    }

    protected function logException(Exception $e)
    {
        if ($this->getLogger() != null) {
            $this->getLogger()->alert($e->getMessage());
        }
    }

    /**
     *
     * @return mixed
     */
    public function getFilter()
    {
        return $this->filter;
    }

    /**
     *
     * @param mixed $filter
     */
    public function setFilter($filter)
    {
        $this->filter = $filter;
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Captcha_model extends CI_Model {

	public $variable;

	public function __construct()
	{
		parent::__construct();

	}

	public function insert_capt($time,$ip,$word)
	{
		$data = array(
	        'captcha_time'  => $time,
	        'ip_address'    => $ip,
	        'word'          => $word
		);
		$this->db->insert('captcha',$data);
	}

	public function check_captcha()
	{
		$expiration = time() - 7200; // Two hour limit
		$this->db->where('captcha_time < ', $expiration)
        ->delete('captcha');
		$sql = 'SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?';
		$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
		$query = $this->db->query($sql, $binds);
		$row = $query->row();

		if ($row->count == 0)
		{
		    return false; // phai nhap capt
		}
		else
		{
			return true;
		}
	}

}

/* End of file Captcha_model.php */
/* Location: ./application/models/Captcha_model.php */


text:
<link rel="stylesheet" type="text/css" href="gameComponents/loadGame.css">

Saves

                <button id="savesListRefresh">Refresh</button>

                <button id="loadScreenBackButton">Back</button>
                <button id="loadScreenDeleteButton">Delete</button>
                <button id="loadScreenLoadButton">Load</button>


text:
layout: "docs"
page_title: "group Stanza - Job Specification"
sidebar_current: "docs-job-specification-group"
description: |-
  The "group" stanza defines a series of tasks that should be co-located on the
  same Nomad client. Any task within a group will be placed on the same client.
---

# `group` Stanza

    Placement

      job -> **group**

The `group` stanza defines a series of tasks that should be co-located on the
same Nomad client. Any [task][] within a group will be placed on the same
client.

```hcl
job "docs" {
  group "example" {
    # ...
  }
}
```

## `group` Parameters

- `constraint` ([Constraint][]: nil) -
  This can be provided multiple times to define additional constraints.

- `count` `(int: 1)` - Specifies the number of the task groups that should
  be running under this group. This value must be non-negative.

- `ephemeral_disk` ([EphemeralDisk][]: nil) - Specifies the
  ephemeral disk requirements of the group. Ephemeral disks can be marked as
  sticky and support live data migrations.

- `meta` ([Meta][]: nil) - Specifies a key-value map that annotates
  with user-defined metadata.

- `restart` ([Restart][]: nil) - Specifies the restart policy for
  all tasks in this group. If omitted, a default policy exists for each job
  type, which can be found in the [restart stanza documentation][restart].

- `task` ([Task][]: <required>) - Specifies one or more tasks to run
  within this group. This can be specified multiple times, to add a task as part
  of the group.

- `vault` ([Vault][]: nil) - Specifies the set of Vault policies
  required by all tasks in this group. Overrides a `vault` block set at the
  `job` level.

## `group` Examples

The following examples only show the `group` stanzas. Remember that the
`group` stanza is only valid in the placements listed above.

### Specifying Count

This example specifies that 5 instances of the tasks within this group should be
running:

```hcl
group "example" {
  count = 5
}
```

### Tasks with Constraint

This example shows two abbreviated tasks with a constraint on the group. This
will restrict the tasks to 64-bit operating systems.

```hcl
group "example" {
  constraint {
    attribute = "${attr.arch}"
    value     = "amd64"
  }

  task "cache" {
    # ...
  }

  task "server" {
    # ...
  }
}
```

### Metadata

This example show arbitrary user-defined metadata on the group:

```hcl
group "example" {
  meta {
    "my-key" = "my-value"
  }
}
```

[task]: /docs/job-specification/task.html "Nomad task Job Specification"
[job]: /docs/job-specification/job.html "Nomad job Job Specification"
[constraint]: /docs/job-specification/constraint.html "Nomad constraint Job Specification"
[ephemeraldisk]: /docs/job-specification/ephemeral_disk.html "Nomad ephemeral_disk Job Specification"
[meta]: /docs/job-specification/meta.html "Nomad meta Job Specification"
[restart]: /docs/job-specification/restart.html "Nomad restart Job Specification"


text:
You can handle prefectures information more easily in Android.

---

## Usage
Add dependencies

```gradle
compile 'com.github.sakebook:Zipangu:0.1.0@aar'
```

In Application or first Activity

 * java

```java
Zipangu.beginning(this);
```

 * kotlin

```kotlin
Zipangu.beginning(this);
```

Support narrowing

 * code(1 ~ 47)
 * name(ex `北海道`, `東京都`)
 * area(ex `東北`)
 * segment(`北日本`, `東日本`, `西日本`, `沖縄・那覇`)
    * Based on the Japan Meteorological Agency([JMA](http://www.jma.go.jp/jma/kishou/know/yougo_hp/tiikimei.html))

The return value of the exception

 * Zipangu is will not return value of null.
Instead, it returns a dummy prefecture.

## Option

### Use custom dummy prefecture

 * java

```java
Zipangu.beginning(this, new Prefecture(0, "カスタム県", "カスタムエリア", Segment.None));
```

 * kotlin

```kotlin
Zipangu.beginning(this, Prefecture(0, "県外", "県外", Segment.None))
```

## LICENSE
```
Copyright (C) 2016 Shinya Sakemoto

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.
```


text:
@interface MTUnsentMessage () {
 @public
  jlong messageId_;
  jint len_;
}

@end

@implementation MTUnsentMessage

- (instancetype)initWithLong:(jlong)messageId
                     withInt:(jint)len {
  MTUnsentMessage_initWithLong_withInt_(self, messageId, len);
  return self;
}

- (instancetype)initWithBSDataInput:(BSDataInput *)stream {
  MTUnsentMessage_initWithBSDataInput_(self, stream);
  return self;
}

- (jlong)getMessageId {
  return messageId_;
}

- (jint)getLen {
  return len_;
}

- (jbyte)getHeader {
  return MTUnsentMessage_HEADER;
}

- (void)writeBodyWithBSDataOutput:(BSDataOutput *)bs {
  [((BSDataOutput *) nil_chk(bs)) writeLongWithLong:messageId_];
  [bs writeIntWithInt:len_];
}

- (void)readBodyWithBSDataInput:(BSDataInput *)bs {
  messageId_ = [((BSDataInput *) nil_chk(bs)) readLong];
  len_ = [bs readInt];
}

- (NSString *)description {
  return JreStrcat("$JC", @"UnsentMessage[", messageId_, ']');
}

@end

void MTUnsentMessage_initWithLong_withInt_(MTUnsentMessage *self, jlong messageId, jint len) {
  (void) MTProtoStruct_init(self);
  self->messageId_ = messageId;
  self->len_ = len;
}

MTUnsentMessage *new_MTUnsentMessage_initWithLong_withInt_(jlong messageId, jint len) {
  MTUnsentMessage *self = [MTUnsentMessage alloc];
  MTUnsentMessage_initWithLong_withInt_(self, messageId, len);
  return self;
}

void MTUnsentMessage_initWithBSDataInput_(MTUnsentMessage *self, BSDataInput *stream) {
  (void) MTProtoStruct_initWithBSDataInput_(self, stream);
}

MTUnsentMessage *new_MTUnsentMessage_initWithBSDataInput_(BSDataInput *stream) {
  MTUnsentMessage *self = [MTUnsentMessage alloc];
  MTUnsentMessage_initWithBSDataInput_(self, stream);
  return self;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(MTUnsentMessage)


text:
package org.seqcode.gsebricks.verbs;

import java.util.*;

public class FilteredExpander<A,B,C> implements Expander<A,C> {

    private Expander<A,B> expander;
    private Filter<B,C> filter;

    public FilteredExpander(Expander<A,B> e, Filter<B,C> f) {
        expander = e;
        filter = f;
    }

    public Iterator<C> execute(A input) {
        return new FilterIterator<B,C>(filter, expander.execute(input));
    }

}


text: Bridge.define("System.HResults");


text:
package com.so.okamnk.alarmclock.util;

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

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by araiyuuichi on 2016/11/11.
 */

public class AlarmDBAdapter {

    public static final String TABLE_NAME = "tbl_alarms";
    public static final String COL_ID = "alarm_id";
    public static final String COL_REGISTERED_DATE = "regist_date";
    public static final String COL_ALARM_NAME = "alarm_name";
    public static final String COL_ALARM_TIME = "alarm_time";
    public static final String COL_SOUND_PATH = "sound_path";
    public static final String COL_VOLUME_PATTERN = "sound_mode";
    public static final String COL_VOLUME = "sound_volume";
    public static final String COL_MANOR_MODE = "manor_mode";
    public static final String COL_HOW_TO_STOP = "stop_mode";
    public static final String COL_SNOOZE_INTERVAL = "snooze_interval";
    public static final String COL_SNOOZE_NUM = "snooze_num";
    public static final String COL_REPEAT_MONDAY = "repeat_monday";
    public static final String COL_REPEAT_TUESDAY = "repeat_tuesday";
    public static final String COL_REPEAT_WEDNESDAY = "repeat_wednesday";
    public static final String COL_REPEAT_THURSDAY = "repeat_thursday";
    public static final String COL_REPEAT_FRIDAY = "repeat_friday";
    public static final String COL_REPEAT_SATURDAY = "repeat_saturday";
    public static final String COL_REPEAT_SUNDAY = "repeat_sunday";
    public static final String COL_ALARM_ENABLED = "alarm_enabled";

    private Context context;
    private AlarmDBHelper dbHelper = null;

    public AlarmDBAdapter(Context context) {
        this.context = context;
        this.dbHelper = new AlarmDBHelper(this.context);
    }

    public AlarmEntity saveAlarm(AlarmEntity entity) {
        ContentValues values = new ContentValues();
        values.put(COL_ALARM_NAME, entity.getAlarmName());
        values.put(COL_ALARM_TIME, entity.getAlarmTime());
        values.put(COL_SOUND_PATH, entity.getSoundPath());
        values.put(COL_VOLUME_PATTERN, entity.getSoundMode());
        values.put(COL_VOLUME, entity.getSoundVolume());
        values.put(COL_MANOR_MODE, entity.getManorMode());
        values.put(COL_HOW_TO_STOP, entity.getStopMode());
        values.put(COL_SNOOZE_INTERVAL, entity.getSnoozeInterval());
        values.put(COL_SNOOZE_NUM, entity.getSnoozeNum());

        final int REPEAT_TRUE = 1;
        final int REPEAT_FALSE = 0;

        int repeatMonday = REPEAT_TRUE;
        if (!entity.getRepeatMonday()) {
            repeatMonday = REPEAT_FALSE;
        }

        int repeatTuesday = REPEAT_TRUE;
        if (!entity.getRepeatTuesday()) {
            repeatTuesday = REPEAT_FALSE;
        }

        int repeatWednesday = REPEAT_TRUE;
        if (!entity.getRepeatWednesday()) {
            repeatWednesday = REPEAT_FALSE;
        }

        int repeatThrsday = REPEAT_TRUE;
        if (!entity.getRepeatThrsday()) {
            repeatThrsday = REPEAT_FALSE;
        }

        int repeatFriday = REPEAT_TRUE;
        if (!entity.getRepeatFriday()) {
            repeatFriday = REPEAT_FALSE;
        }

        int repeatSaturday = REPEAT_TRUE;
        if (!entity.getRepeatSaturday()) {
            repeatSaturday = REPEAT_FALSE;
        }

        int repeatSunday = REPEAT_TRUE;
        if (!entity.getRepeatSunday()) {
            repeatSunday = REPEAT_FALSE;
        }

        int alarmEnabled = REPEAT_TRUE;
        if (!entity.getAlarmEnabled()) {
            alarmEnabled = REPEAT_FALSE;
        }

        values.put(COL_REPEAT_MONDAY, repeatMonday);
        values.put(COL_REPEAT_TUESDAY, repeatTuesday);
        values.put(COL_REPEAT_WEDNESDAY, repeatWednesday);
        values.put(COL_REPEAT_THURSDAY, repeatThrsday);
        values.put(COL_REPEAT_FRIDAY, repeatFriday);
        values.put(COL_REPEAT_SATURDAY, repeatSaturday);
        values.put(COL_REPEAT_SUNDAY, repeatSunday);
        values.put(COL_ALARM_ENABLED, alarmEnabled);

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        int row = entity.getAlarmId();
        try {
            if (row == 0) {
                values.put(COL_REGISTERED_DATE, getCurrentDate());
                row = (int) db.insert(TABLE_NAME, null, values);
            } else {
                db.update(TABLE_NAME, values, COL_ID + "=?", new String[]{String.valueOf(row)});
            }
        } finally {
            db.close();
        }

        return getAlarm(row);
    }

    public void deleteAlarm(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.delete(TABLE_NAME, COL_ID + "=" + String.valueOf(id), null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            db.close();
        }
    }

    public void deleteAll() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.delete(TABLE_NAME, null, null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            db.close();
        }
    }

    public List<AlarmEntity> getAll() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor query = null;
        List<AlarmEntity> itemList = new ArrayList<AlarmEntity>();

        try {
            query = db.query(TABLE_NAME, null, null, null, null, null, COL_REGISTERED_DATE + " ASC");
            query.moveToFirst();
            while (!query.isAfterLast()) {
                itemList.add(getAlarmEntity(query));
                query.moveToNext();
            }
            query.close();
        } finally {
            db.close();
        }

        return itemList;
    }

    public AlarmEntity getAlarm(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor query;
        AlarmEntity entity = null;

        try {
            query = db.query(TABLE_NAME, null, COL_ID + "=" + String.valueOf(id), null, null, null, null, null);
            query.moveToFirst();
            entity = getAlarmEntity(query);
            query.close();
        } finally {
            db.close();
        }

        return entity;
    }

    public List<AlarmEntity> search(String condition) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor query;
        List<AlarmEntity> itemList = new ArrayList<AlarmEntity>();

        try {
            query = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ?", new String[]{condition});
            query.moveToFirst();
            while (!query.isAfterLast()) {
                itemList.add(getAlarmEntity(query));
                query.moveToNext();
            }
            query.close();
        } finally {
            db.close();
        }
        return itemList;
    }

    private AlarmEntity getAlarmEntity(Cursor cursor) {

        boolean repeatMonday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_MONDAY)) == 0) {
            repeatMonday = false;
        }

        boolean repeatTuesday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_TUESDAY)) == 0) {
            repeatTuesday = false;
        }

        boolean repeatWednesday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_WEDNESDAY)) == 0) {
            repeatWednesday = false;
        }

        boolean repeatThrsday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_THURSDAY)) == 0) {
            repeatThrsday = false;
        }

        boolean repeatFriday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_FRIDAY)) == 0) {
            repeatFriday = false;
        }

        boolean repeatSaturday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_SATURDAY)) == 0) {
            repeatSaturday = false;
        }

        boolean repeatSunday = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_REPEAT_SUNDAY)) == 0) {
            repeatSunday = false;
        }

        boolean alarmEnabled = true;
        if (cursor.getInt(cursor.getColumnIndex(COL_ALARM_ENABLED)) == 0) {
            alarmEnabled = false;
        }

        return new AlarmEntity(
                cursor.getInt(cursor.getColumnIndex(COL_ID)),
                cursor.getString(cursor.getColumnIndex(COL_REGISTERED_DATE)),
                cursor.getString(cursor.getColumnIndex(COL_ALARM_NAME)),
                cursor.getString(cursor.getColumnIndex(COL_ALARM_TIME)),
                cursor.getString(cursor.getColumnIndex(COL_SOUND_PATH)),
                cursor.getInt(cursor.getColumnIndex(COL_VOLUME_PATTERN)),
                cursor.getInt(cursor.getColumnIndex(COL_VOLUME)),
                cursor.getInt(cursor.getColumnIndex(COL_MANOR_MODE)),
                cursor.getInt(cursor.getColumnIndex(COL_HOW_TO_STOP)),
                cursor.getInt(cursor.getColumnIndex(COL_SNOOZE_INTERVAL)),
                cursor.getInt(cursor.getColumnIndex(COL_SNOOZE_NUM)),
                repeatSunday,
                repeatMonday,
                repeatTuesday,
                repeatWednesday,
                repeatThrsday,
                repeatFriday,
                repeatSaturday,
                alarmEnabled);
    }

    private static String getCurrentDate() {
        final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
        final Date date = new Date(System.currentTimeMillis());
        return df.format(date);
    }
}


text:
import pdb;pdb.set_trace()

def sqlQuery_oldimage_newpo_duplimerge(oldpo, newpo):
    import sqlalchemy,sys
    orcl_engine = sqlalchemy.create_engine('oracle+cx_oracle://prod_team_ro:9thfl00r@borac101-vip.l3.bluefly.com:1521/bfyprd11')
    connection = orcl_engine.connect()
    query_image_duplimerge = "WITH data AS ( SELECT POMGR.PO_LINE.PO_HDR_ID AS ponumber, POMGR.PRODUCT_COLOR.ID  AS colorstyle, POMGR.PRODUCT_COLOR.VENDOR_STYLE AS vendor_style, sum( case when POMGR.PRODUCT_COLOR.IMAGE_READY_DT is not null   then 1   else null end ) is_ready FROM POMGR.PO_LINE JOIN POMGR.PRODUCT_COLOR ON POMGR.PRODUCT_COLOR.ID = POMGR.PO_LINE.PRODUCT_COLOR_ID WHERE POMGR.PO_LINE.PO_HDR_ID IN ('{0}', '{1}') GROUP BY POMGR.PO_LINE.PO_HDR_ID, POMGR.PRODUCT_COLOR.ID, POMGR.PRODUCT_COLOR.VENDOR_STYLE ORDER BY 3, 4 asc nulls last, 2 DESC ) SELECT COUNT(DISTINCT data.colorstyle), data.vendor_style, MIN(data.colorstyle) as oldstyle, MAX(data.colorstyle)  as newstyle,  data.is_ready FROM data GROUP BY data.vendor_style, data.is_ready HAVING COUNT(data.vendor_style) = 2 AND MIN(data.colorstyle) <> MAX(data.colorstyle) order by data.is_ready nulls last".format(oldpo, newpo)
    result = connection.execute(query_image_duplimerge)
    merge_styles = []
    total_count_rem = result.rowcount
    total_count_incr = 0
    for row in result:
        styles = {}
        styles['oldstyle'] = str(row['oldstyle'])
        styles['newstyle'] = str(row['newstyle'])
        total_count_incr += 1
        total_count_rem -= 1
        print "Styles Total: {}\vRemaining: {}".format(total_count_incr, total_count_rem)
        merge_styles.append(styles)
    connection.close()
    return merge_styles

def url_download_file(url,dest_filepath):
    import urllib
    try:
        resp = urllib.urlretrieve(url, dest_filepath)
        if resp:
            print "Retrieved: " + url + " ---> " + dest_filepath
            return dest_filepath
        else:
            return
    except IOError:
        print 'IOERROR 30'

# def url_download_file(url,dest_filepath):
#     import requests
#     resp = requests.get(url, dest_filepath)
#     if resp:
#         print "Retrieved: " + url + " ---> " + dest_filepath
#         with open(dest_filepath, 'wb+') as f:
#             f.write(resp.content)
#         return dest_filepath
#     else:
#         return

def main():
    #### Run ###
    import sys, urllib
    from os import chdir,curdir,path
    args = sys.argv[1:]
    print 'Moving images from PO: {} to PO --> {}'.format(*args)
    try:
        if len(args) == 2:
            merge_styles = sqlQuery_oldimage_newpo_duplimerge(*args)
        else:
            print "You neew to provide both the original po number and the po number to move images to.\nPo numbers are 6 digits each separated by a space."
            pass
    except IndexError:
        print "Enter at least PO Number as 1st Arg or Nothing will Happen"

    for item in merge_styles:
        netsrv101_url = 'ftp://imagedrop:imagedrop0@netsrv101.l3.bluefly.com//mnt/images/images/'
        old_colorstyle = item['oldstyle']
        new_colorstyle = item['newstyle']
        ext_PNG     = '.png'
        ext_JPG     = '.jpg'

        netsrv101_url_file = path.join(netsrv101_url, old_colorstyle[:4], old_colorstyle + ext_PNG)
        renamed_from_newpo_toload = path.join(path.abspath(path.expanduser('~')), 'Pictures', new_colorstyle + ext_PNG)

        url_download_file(netsrv101_url_file, renamed_from_newpo_toload)
        alt = 0
        for x in range(1,6):
            alt = x
            ext_ALT = '_alt0{0}{1}'.format(str(alt),ext_PNG)
            colorstyleoldalt = old_colorstyle + ext_ALT
            netsrv101_url_filealt = path.join(netsrv101_url, old_colorstyle[:4], colorstyleoldalt)
            colorstylenewalt = new_colorstyle + ext_ALT
            renamed_from_newpo_toloadalt = path.join(path.abspath(path.expanduser('~')), 'Pictures', colorstylenewalt)
            if url_download_file(netsrv101_url_filealt, renamed_from_newpo_toloadalt):
                url_download_file(netsrv101_url_filealt, renamed_from_newpo_toloadalt)

if __name__ == '__main__':
    main()


text:
@interface LMChatSingleTransferViewController ()
@property(nonatomic, strong) UIImageView *userImageView;
@property(nonatomic, strong) UILabel *usernameLabel;
// money balance
@property(nonatomic, strong) UILabel *BalanceLabel;
@property(nonatomic, strong) BitcoinInfo *binfo;
@property(nonatomic, assign) float accoutMoney;
// money
@property(nonatomic, strong) TransferInputView *inputAmountView;

@end

@implementation LMChatSingleTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak __typeof(&*self) weakSelf = self;

    self.title = LMLocalizedString(@"Wallet Transfer", nil);

    [self addNewCloseBarItem];
    // message
    [self initUserInfomation];
    // transfer money
    [self initTopView];
    // packet money
    [self initTabelViewCell];

    self.ainfo = [[LKUserCenter shareCenter] currentLoginUser];

    self.trasferComplete = ^{
        [GCDQueue executeInMainQueue:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    };

}

- (void)initUserInfomation {
    self.userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(AUTO_WIDTH(319), AUTO_HEIGHT(30) + 64, AUTO_WIDTH(100), AUTO_WIDTH(100))];
    [self.userImageView setPlaceholderImageWithAvatarUrl:self.info.avatar];
    self.userImageView.layer.cornerRadius = 5;
    self.userImageView.layer.masksToBounds = YES;
    [self.view addSubview:self.userImageView];

    self.usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(AUTO_WIDTH(100), CGRectGetMaxY(self.userImageView.frame) + AUTO_HEIGHT(10), VSIZE.width - AUTO_WIDTH(200), AUTO_HEIGHT(40))];
    self.usernameLabel.text = [NSString stringWithFormat:LMLocalizedString(@"Wallet Transfer To User", nil), self.info.username];
    self.usernameLabel.textAlignment = NSTextAlignmentCenter;
    self.usernameLabel.font = [UIFont systemFontOfSize:FONT_SIZE(28)];
    self.usernameLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.usernameLabel];
}

- (void)initTopView {

    __weak __typeof(&*self) weakSelf = self;
    TransferInputView *view = [[TransferInputView alloc] init];
    self.inputAmountView = view;
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usernameLabel.mas_bottom).offset(AUTO_HEIGHT(20));
        make.width.equalTo(self.view);
        make.height.mas_equalTo(AUTO_HEIGHT(334));
        make.left.equalTo(self.view);
    }];
    if (self.trasferAmount.doubleValue > 0) {
        view.textDefaultAmount = self.trasferAmount.doubleValue;
    }
    view.topTipString = LMLocalizedString(@"Wallet Amount", nil);
    view.resultBlock = ^(NSDecimalNumber *btcMoney, NSString *note) {
        [weakSelf createTranscationWithMoney:btcMoney note:note];
    };
    view.lagelBlock = ^(BOOL enabled) {
        weakSelf.comfrimButton.enabled = enabled;
    };
    [[PayTool sharedInstance] getRateComplete:^(NSDecimalNumber *rate, NSError *error) {
        if (!error) {
            weakSelf.rate = rate.floatValue;
            [[MMAppSetting sharedSetting] saveRate:[rate floatValue]];
            [weakSelf.inputAmountView reloadWithRate:rate.floatValue];
        } else {
            [GCDQueue executeInMainQueue:^{
                [MBProgressHUD showToastwithText:LMLocalizedString(@"Fail to get rate.", nil) withType:ToastTypeFail showInView:weakSelf.view complete:nil];
            }];
        }
    }];

    [NSNotificationCenter.defaultCenter addObserverForName:UIKeyboardWillChangeFrameNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
        CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        int distence = weakSelf.inputAmountView.bottom - (DEVICE_SIZE.height - keyboardFrame.size.height - AUTO_HEIGHT(100));
        [GCDQueue executeInMainQueue:^{
            [UIView animateWithDuration:duration animations:^{
                if (keyboardFrame.origin.y != DEVICE_SIZE.height) {
                    if (distence > 0) {
                        weakSelf.view.top -= distence;
                    }
                } else {
                    weakSelf.view.top = 0;
                }
            }];
        }];
    }];
}

- (void)initTabelViewCell {

    self.BalanceLabel = [[UILabel alloc] init];
    self.BalanceLabel.text = [NSString stringWithFormat:LMLocalizedString(@"Wallet Balance", nil), [PayTool getBtcStringWithAmount:[[MMAppSetting sharedSetting] getBalance]]];
    self.BalanceLabel.textColor = [UIColor colorWithHexString:@"38425F"];
    self.BalanceLabel.font = [UIFont systemFontOfSize:FONT_SIZE(28)];
    self.BalanceLabel.textAlignment = NSTextAlignmentCenter;
    self.BalanceLabel.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:self.BalanceLabel];
    [self.view sendSubviewToBack:self.BalanceLabel];

    [self.BalanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputAmountView.mas_bottom).offset(AUTO_HEIGHT(60));
        make.centerX.equalTo(self.view);
    }];

    __weak __typeof(&*self) weakSelf = self;
    [[PayTool sharedInstance] getBlanceWithComplete:^(NSString *blance, UnspentAmount *unspentAmount, NSError *error) {
        weakSelf.blance = unspentAmount.avaliableAmount;
        weakSelf.BalanceLabel.text = [NSString stringWithFormat:LMLocalizedString(@"Wallet Balance", nil), [PayTool getBtcStringWithAmount:unspentAmount.avaliableAmount]];
    }];

    self.comfrimButton = [[ConnectButton alloc] initWithNormalTitle:LMLocalizedString(@"Wallet Transfer", nil) disableTitle:LMLocalizedString(@"Wallet Transfer", nil)];
    [self.comfrimButton addTarget:self action:@selector(tapConfrim) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.comfrimButton];
    [self.comfrimButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.BalanceLabel.mas_bottom).offset(AUTO_HEIGHT(30));
        make.width.mas_equalTo(self.comfrimButton.width);
        make.height.mas_equalTo(self.comfrimButton.height);
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.inputAmountView hidenKeyBoard];
}

- (void)tapConfrim {
    self.comfrimButton.enabled = NO;
    [self.inputAmountView executeBlock];
}

- (void)createTranscationWithMoney:(NSDecimalNumber *)money note:(NSString *)note {
    __weak typeof(&*self) weakSelf = self;
    // balance
    if ([PayTool getPOW8Amount:money] > self.blance) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showToastwithText:LMLocalizedString(@"Wallet Insufficient balance", nil) withType:ToastTypeFail showInView:weakSelf.view complete:nil];

        self.comfrimButton.enabled = YES;
        return;
    }
    [MBProgressHUD showTransferLoadingViewtoView:self.view];
    [self.view endEditing:YES];

    NSArray *toAddresses = @[@{@"address": self.info.address, @"amount": money.stringValue}];
    AccountInfo *ainfo = [[LKUserCenter shareCenter] currentLoginUser];
    [WallteNetWorkTool unspentV2WithAddress:ainfo.address fee:[[MMAppSetting sharedSetting] getTranferFee] toAddress:toAddresses createRawTranscationModelComplete:^(UnspentOrderResponse *unspent, NSError *error) {
        [LMPayCheck payCheck:nil withVc:weakSelf withTransferType:TransferTypeChatSingle unSpent:unspent withArray:toAddresses withMoney:money withNote:note withType:0 withRedPackage:nil withError:error];

    }];
}

- (void)checkChangeWithRawTrancationModel:(LMRawTransactionModel *)rawModel
                                   amount:(NSDecimalNumber *)amount
                                     note:(NSString *)note {
    // Check for change
    __weak __typeof(&*self) weakSelf = self;
    rawModel = [LMUnspentCheckTool checkChangeDustWithRawTrancation:rawModel];
    switch (rawModel.unspentErrorType) {
        case UnspentErrorTypeChangeDust: {
            [MBProgressHUD hideHUDForView:self.view];
            NSString *tips = [NSString stringWithFormat:LMLocalizedString(@"Wallet Charge small calculate to the poundage", nil),
                                                        [PayTool getBtcStringWithAmount:rawModel.change]];
            [UIAlertController showAlertInViewController:self withTitle:LMLocalizedString(@"Set tip title", nil) message:tips cancelButtonTitle:LMLocalizedString(@"Common Cancel", nil) destructiveButtonTitle:nil otherButtonTitles:@[LMLocalizedString(@"Common OK", nil)] tapBlock:^(UIAlertController *_Nonnull controller, UIAlertAction *_Nonnull action, NSInteger buttonIndex) {
                self.comfrimButton.enabled = YES;
                switch (buttonIndex) {
                    case 0: {
                        self.comfrimButton.enabled = YES;
                    }
                        break;
                    case 2: // click ok
                    {
                        LMRawTransactionModel *rawModelNew = [LMUnspentCheckTool createRawTransactionWithRawTrancation:rawModel addDustToFee:YES];
                        // pay money
                        [weakSelf makeTransfer:rawModelNew decimalMoney:amount note:note];
                    }
                        break;
                    default:
                        break;
                }
            }];
        }
            break;
        case UnspentErrorTypeNoError: {
            LMRawTransactionModel *rawModelNew = [LMUnspentCheckTool createRawTransactionWithRawTrancation:rawModel addDustToFee:NO];
            // pay money
            [weakSelf makeTransfer:rawModelNew decimalMoney:amount note:note];
        }
            break;
        default:
            break;
    }
}

- (void)makeTransfer:(LMRawTransactionModel *)rawModel decimalMoney:(NSDecimalNumber *)amount note:(NSString *)note {
    [MBProgressHUD showTransferLoadingViewtoView:self.view];
    self.rawTransaction = rawModel.rawTrancation;
    self.vtsArray = rawModel.vtsArray;
    __weak __typeof(&*self) weakSelf = self;
    [[PayTool sharedInstance] payVerfifyFingerWithComplete:^(BOOL result, NSString *errorMsg) {
        if (result) {
            [weakSelf transferToAddress:weakSelf.info.address decimalMoney:amount tips:note complete:^(NSString *hashId, NSError *error) {
                [GCDQueue executeInMainQueue:^{
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                }];
                if (error) {
                    weakSelf.comfrimButton.enabled = YES;
                } else {
                    // update money blance
                    [[PayTool sharedInstance] getBlanceWithComplete:^(NSString *blance, UnspentAmount *unspentAmount, NSError *error) {
                        [GCDQueue executeInMainQueue:^{
                            weakSelf.blance = unspentAmount.avaliableAmount;
                            weakSelf.BalanceLabel.text = [NSString stringWithFormat:LMLocalizedString(@"Wallet Balance", nil), [PayTool getBtcStringWithAmount:unspentAmount.avaliableAmount]];
                        }];
                    }];
                    if (weakSelf.didGetTransferMoney) {
                        weakSelf.didGetTransferMoney(amount.stringValue, hashId, note);
                        [weakSelf dismissViewControllerAnimated:YES completion:nil];
                    }
                }
            }];
        } else {
            if ([errorMsg isEqualToString:@"NO"]) {
                [GCDQueue executeInMainQueue:^{
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                    weakSelf.comfrimButton.enabled = YES;
                }];
                return;
            }
            [InputPayPassView showInputPayPassWithComplete:^(InputPayPassView *passView, NSError *error, BOOL result) {
                if (result) {
                    [weakSelf transferToAddress:weakSelf.info.address decimalMoney:amount tips:note complete:^(NSString *hashId, NSError *error) {
                        if (error) {
                            weakSelf.comfrimButton.enabled = YES;
                            if (passView.requestCallBack) {
                                passView.requestCallBack(error);
                            }
                        } else {
                            if (passView.requestCallBack) {
                                passView.requestCallBack(nil);
                            }
                            // update money blance
                            [[PayTool sharedInstance] getBlanceWithComplete:^(NSString *blance, UnspentAmount *unspentAmount, NSError *error) {
                                [GCDQueue executeInMainQueue:^{
                                    weakSelf.blance = unspentAmount.avaliableAmount;
                                    weakSelf.BalanceLabel.text = [NSString stringWithFormat:LMLocalizedString(@"Wallet Balance", nil), [PayTool getBtcStringWithAmount:unspentAmount.avaliableAmount]];
                                }];
                            }];
                            if (weakSelf.didGetTransferMoney) {
                                weakSelf.didGetTransferMoney(amount.stringValue, hashId, note);
                                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                            }
                        }
                    }];
                } else {
                    weakSelf.comfrimButton.enabled = YES;
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                    if (![errorMsg isEqualToString:@"NO"]) {
                        [GCDQueue executeInMainQueue:^{
                            [MBProgressHUD showToastwithText:LMLocalizedString(@"Wallet Transfer Failed", nil) withType:ToastTypeFail showInView:weakSelf.view complete:nil];
                        }];
                    }
                }
            }                              forgetPassBlock:^{
                [GCDQueue executeInMainQueue:^{
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                    weakSelf.comfrimButton.enabled = YES;
                    PaySetPage *page = [[PaySetPage alloc] initIsNeedPoptoRoot:YES];
                    [weakSelf.navigationController pushViewController:page animated:YES];
                }];
            }                                   closeBlock:^{
                [GCDQueue executeInMainQueue:^{
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                    weakSelf.comfrimButton.enabled = YES;
                }];
            }];
        }
    }];
}

@end


text:
package com.morihacky.android.rxjava.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.morihacky.android.rxjava.R;
import com.morihacky.android.rxjava.wiring.LogAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import timber.log.Timber;

import static android.os.Looper.getMainLooper;
import static android.os.Looper.myLooper;

public class TimingDemoFragment
      extends BaseFragment {

    @InjectView(R.id.list_threading_log) ListView _logsList;

    private LogAdapter _adapter;
    private List<String> _logs;

    private Subscription _subscription1 = null;
    private Subscription _subscription2 = null;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        _setupLogger();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_demo_timing, container, false);
        ButterKnife.inject(this, layout);
        return layout;
    }

    // -----------------------------------------------------------------------------------

    @OnClick(R.id.btn_demo_timing_1)
    public void Btn1_RunSingleTaskAfter2s() {
        _log(String.format("A1 [%s] --- BTN click", _getCurrentTimestamp()));

        Observable.timer(2, TimeUnit.SECONDS)//
              //.just(1).delay(2, TimeUnit.SECONDS)//
              .subscribe(new Observer<Long>() {
                  @Override
                  public void onCompleted() {
                      _log(String.format("A1 [%s] XXX COMPLETE", _getCurrentTimestamp()));
                  }

                  @Override
                  public void onError(Throwable e) {
                      Timber.e(e, "something went wrong in TimingDemoFragment example");
                  }

                  @Override
                  public void onNext(Long number) {
                      _log(String.format("A1 [%s]     NEXT", _getCurrentTimestamp()));
                  }
              });
    }

    @OnClick(R.id.btn_demo_timing_2)
    public void Btn2_RunTask_IntervalOf1s() {
        if (_subscription1 != null && !_subscription1.isUnsubscribed()) {
            _subscription1.unsubscribe();
            _log(String.format("B2 [%s] XXX BTN KILLED", _getCurrentTimestamp()));
            return;
        }

        _log(String.format("B2 [%s] --- BTN click", _getCurrentTimestamp()));

        _subscription1 = Observable//
              .interval(1, TimeUnit.SECONDS)//
              .subscribe(new Observer<Long>() {
                  @Override
                  public void onCompleted() {
                      _log(String.format("B2 [%s] XXXX COMPLETE", _getCurrentTimestamp()));
                  }

                  @Override
                  public void onError(Throwable e) {
                      Timber.e(e, "something went wrong in TimingDemoFragment example");
                  }

                  @Override
                  public void onNext(Long number) {
                      _log(String.format("B2 [%s]     NEXT", _getCurrentTimestamp()));
                  }
              });
    }

    @OnClick(R.id.btn_demo_timing_3)
    public void Btn3_RunTask_IntervalOf1s_StartImmediately() {
        if (_subscription2 != null && !_subscription2.isUnsubscribed()) {
            _subscription2.unsubscribe();
            _log(String.format("C3 [%s] XXX BTN KILLED", _getCurrentTimestamp()));
            return;
        }

        _log(String.format("C3 [%s] --- BTN click", _getCurrentTimestamp()));

        _subscription2 = Observable//
              .timer(0, 1, TimeUnit.SECONDS)//
              .subscribe(new Observer<Long>() {
                  @Override
                  public void onCompleted() {
                      _log(String.format("C3 [%s] XXXX COMPLETE", _getCurrentTimestamp()));
                  }

                  @Override
                  public void onError(Throwable e) {
                      Timber.e(e, "something went wrong in TimingDemoFragment example");
                  }

                  @Override
                  public void onNext(Long number) {
                      _log(String.format("C3 [%s]     NEXT", _getCurrentTimestamp()));
                  }
              });
    }

    @OnClick(R.id.btn_demo_timing_4)
    public void Btn4_RunTask5Times_IntervalOf3s() {
        _log(String.format("D4 [%s] --- BTN click", _getCurrentTimestamp()));

        Observable//
              .interval(3, TimeUnit.SECONDS).take(5)//
              .subscribe(new Observer<Long>() {
                  @Override
                  public void onCompleted() {
                      _log(String.format("D4 [%s] XXX COMPLETE", _getCurrentTimestamp()));
                  }

                  @Override
                  public void onError(Throwable e) {
                      Timber.e(e, "something went wrong in TimingDemoFragment example");
                  }

                  @Override
                  public void onNext(Long number) {
                      _log(String.format("D4 [%s]     NEXT", _getCurrentTimestamp()));
                  }
              });
    }

    // -----------------------------------------------------------------------------------
    // Method that help wiring up the example (irrelevant to RxJava)

    @OnClick(R.id.btn_clr)
    public void OnClearLog() {
        _logs = new ArrayList<>();
        _adapter.clear();
    }

    private void _setupLogger() {
        _logs = new ArrayList<>();
        _adapter = new LogAdapter(getActivity(), new ArrayList<String>());
        _logsList.setAdapter(_adapter);
    }

    private void _log(String logMsg) {
        _logs.add(0, String.format(logMsg + " [MainThread: %b]", getMainLooper() == myLooper()));

        // You can only do below stuff on main thread.
        new Handler(getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                _adapter.clear();
                _adapter.addAll(_logs);
            }
        });
    }

    private String _getCurrentTimestamp() {
        return new SimpleDateFormat("k:m:s:S a").format(new Date());
    }

}


text:
<html>
    <body>
        <form action="http://localhost:5000/estibador" method="POST"
                enctype="multipart/form-data">
        <input type="file" name="archivo" />
        <input type="submit"/>
        </form>
    </body>
</html>


text:
import lutils from "loader-utils"
import sysPath from "path"

export default function loader() {}

loader.pitch = function(remainingRequest, precedingRequest) {
  const tplPath = sysPath.join(__dirname, "AsyncComponent.js")
  this.addDependency(tplPath)
  this.cacheable()

  // ---

  const options = this.options.asyncComponentLoader || {}
  const query = lutils.parseQuery(this.query)
  const opts = Object.assign({}, options.defaults, query)

  // ---

  const bundleQs = "lazy" + (!opts.name ? "" : `&name=${opts.name}`)

  let strLoaderImport = ""
  let strLoaderProp = ""
  if (opts.loader) {
    strLoaderImport = `var Loader = require(${lutils.stringifyRequest(this, opts.loader)})`
    strLoaderProp = "Loader: Loader,"
  }

  // ---

  // Concat preceding and remaining request, and prepend bundle-loader.
  // In this way we make sure that this loader does not depend from it's position in loaders chain and always will be the last.
  // It means "let all other loaders to process requested module as they want, then I will just load their result asynchronously".
  //
  // It's very important for convenient usage, because otherwise you'd need to manually maintain proper loaders order.
  // For example, if you process all your JS with { test: /\.js$/, loaders: [ "react-hot", "babel" ] },
  // you'd need to always put config for react-async-component loader *before* that one.
  //
  // With this approach, just add config for react-async-component loader wherever you want, and enjoy.
  const request = [ `bundle-loader?${bundleQs}`, precedingRequest, remainingRequest ].filter(x => x).join("!")

  return `
    var React = require('react');
    var loadComponent = require(${lutils.stringifyRequest(this, `!!${request}`)});
    var Component = require(${lutils.stringifyRequest(this, tplPath)});
    ${strLoaderImport}
    module.exports = function AsyncComponentDefaults(props) {
      return React.createElement(Component, Object.assign({}, props, {
        loadComponent: loadComponent,
        ${strLoaderProp}
      }));
    }
  `
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('members', '0004_member_real_working_hours_per_week'),
    ]

    operations = [
        migrations.AlterField(
            model_name='member',
            name='api_key',
            field=models.CharField(blank=True, default=None, max_length=128, null=True, verbose_name='Trello API key'),
        ),
        migrations.AlterField(
            model_name='member',
            name='api_secret',
            field=models.CharField(blank=True, default=None, max_length=128, null=True, verbose_name='Trello API secret'),
        ),
        migrations.AlterField(
            model_name='member',
            name='real_working_hours_per_week',
            field=models.PositiveIntegerField(blank=True, default=None, null=True, verbose_name='Number of hours this developer should achieve eachweek'),
        ),
        migrations.AlterField(
            model_name='member',
            name='token',
            field=models.CharField(blank=True, default=None, max_length=128, null=True, verbose_name='Trello token'),
        ),
        migrations.AlterField(
            model_name='member',
            name='token_secret',
            field=models.CharField(blank=True, default=None, max_length=128, null=True, verbose_name='Trello token secret'),
        ),
    ]


text:
if ("geolocation" in navigator) {
	navigator.geolocation.getCurrentPosition(function(position) {
	  console.log(String(position.coords.latitude) + " : " +  String(position.coords.longitude));
	  localStorage.lat = position.coords.latitude;
	  localStorage.lon = position.coords.longitude;
	});
}