text:
/**
 * @module Application
 */
define([
    'framework/BaseModel'
], function(BaseModel) {
    /**
     * @class DataVocab
     * @extends BaseModel
     */
    var DataVocab = BaseModel.extend({
        /**
         * @method initialize
         */
        initialize: function() {},
        /**
         * @property idAttribute
         * @type String
         */
        idAttribute: 'id',
        /**
         * @property defaults
         * @type Object
         */
        defaults: {},
        /**
         * @method cache
         * @param {Function} [callback]
         */
        cache: function(callback) {
            app.user.data.flagVocabUpdate(this.id);
            app.storage.putItems('vocabs', this.toJSON(), function() {
                if (typeof callback === 'function') {
                    callback();
                }
            });
        },
        /**
         * @method getAudio
         * @returns {Boolean|String}
         */
        getAudio: function() {
            if (this.has('audio')) {
                return app.isNative() ? this.get('audio').replace('/sounds?file=', '') : this.get('audio');
            }
            return false;
        },
        /**
         * @method getCanvasCharacter
         * @returns {CanvasCharacter}
         */
        getCanvasCharacter: function() {
            return this.getStroke() ? this.getStroke().getCanvasCharacter() : undefined;
        },
        /**
         * @method getCharacterCount
         * @returns {Number}
         */
        getCharacterCount: function() {
            return this.getCharacters().length;
        },
        /**
         * @method getCharacters
         * @returns {Array}
         */
        getCharacters: function() {
            var characters = [];
            if (this.has('containedVocabIds')) {
                var containedVocabIds = this.get('containedVocabIds');
                for (var i = 0, length = containedVocabIds.length; i < length; i++) {
                    if (this.isChinese()) {
                        characters.push(app.fn.mapper.fromBase(containedVocabIds[i]));
                    } else {
                        characters.push(containedVocabIds[i].split('-')[1]);
                    }
                }
            } else {
                characters.push(this.get('writing'));
            }
            return characters;
        },
        /**
         * @method getContainedItemIds
         * @param {String} part
         * @param {Boolean} [excludeKana]
         * @returns {Array}
         */
        getContainedItemIds: function(part, excludeKana) {
            var containedItemIds = [];
            //creates an array of item items based on contained vocab ids
            if (this.has('containedVocabIds')) {
                var containedVocabIds = this.get('containedVocabIds');
                for (var i = 0, length = containedVocabIds.length; i < length; i++) {
                    var containedVocabId = containedVocabIds[i];
                    var containedSplit = containedVocabId.split('-');
                    if (part === 'rune') {
                        containedItemIds.push(app.user.id + '-' + containedVocabId + '-' + part);
                    } else if (parseInt(containedSplit[2], 10) > 1) {
                        containedItemIds.push(app.user.id + '-' + containedVocabId + '-' + part);
                    } else {
                        containedItemIds.push(app.user.id + '-' + containedSplit[0] + '-' + containedSplit[1] + '-0-' + part);
                    }
                }
            }
            //filters out kana that is included is a contained vocab id
            if (this.isJapanese() && excludeKana) {
                containedItemIds = containedItemIds.filter(function(itemId) {
                    return !app.fn.isKana(itemId.split('-')[2]);
                });
            }
            return containedItemIds;
        },
        /**
         * @method getContainedRows
         * @returns {String}
         */
        getContainedRows: function() {
            var containedHTML = '';
            var containedVocabs = _.without(this.getContainedVocabs(), undefined);
            containedHTML += "

";
            for (var a = 0, lengthA = containedVocabs.length; a < lengthA; a++) {
                var vocabItem = containedVocabs[a];
                containedHTML += "
";
                containedHTML += "" + vocabItem.get('writing') + '	';
                if (vocabItem.get('kana')) {
                    containedHTML += "	";
                    containedHTML += "kana	";
                } else {
                    containedHTML += "" + vocabItem.getReading() + '	';
                    containedHTML += "" + vocabItem.getDefinition() + '	';
                }
                containedHTML += "
";
            }
            containedHTML += "

";
            return containedHTML;
        },
        /**
         * @method getContainedVocabIds
         * @param {Boolean} [excludeKana]
         * @returns {Array}
         */
        getContainedVocabIds: function(excludeKana) {
            var containedVocabIds = [];
            if (this.has('containedVocabIds')) {
                if (excludeKana) {
                    containedVocabIds = this.get('containedVocabIds').filter(function(vocabId) {
                        return !app.fn.isKana(vocabId.split('-')[1]);
                    });
                } else {
                    containedVocabIds = this.get('containedVocabIds');
                }
            }
            return containedVocabIds;
        },
        /**
         * @method getContainedVocabs
         * @returns {Array}
         */
        getContainedVocabs: function() {
            var vocabs = [];
            var containedIds = this.has('containedVocabIds') ? this.get('containedVocabIds') : [this.id];
            for (var i = 0, length = containedIds.length; i < length; i++) {
                var vocab = this.collection.get(containedIds[i]);
                if (vocab) {
                    vocabs.push(this.collection.get(containedIds[i]));
                } else {
                    //create a temporary kana item when missing for collection
                    vocabs.push(app.user.data.vocabs.add(new DataVocab({
                        id: containedIds[i],
                        kana: true, writing: containedIds[i].split('-')[1]
                    }), {merge: true, silent: true}));
                }
            }
            return vocabs;
        },
        /**
         * @method getDecomp
         * @param {Boolean|DataDecomp}
         */
        getDecomp: function() {
            if (this.getCharacters().length === 1) {
                var decomp = app.user.data.decomps.get(this.getCharacters()[0]);
                if (decomp && !decomp.get('atomic')) {
                    return decomp;
                }
            }
            return false;
        },
        /**
         * @method getDefinition
         * @param {Boolean} [skipFormat]
         * @returns {String}
         */
        getDefinition: function(skipFormat) {
            var customDefinition = this.get('customDefinition');
            var definition = this.get('definitions')[app.user.settings.get('sourceLang')];
            if (customDefinition && customDefinition !== '') {
                definition = this.get('customDefinition');
            } else if (definition) {
                definition = definition;
            } else {
                definition = this.get('definitions').en;
            }
            return skipFormat ? definition : app.fn.textToHTML(definition);
        },
        /**
         * @method getKana
         * @returns {Array}
         */
        getKana: function() {
            return _.without(this.get('writing').split('').map(function(value) {
                return app.fn.isKana(value) ? value : false;
            }), false);
        },
        /**
         * @method getMnemonicText
         * @returns {String}
         */
        getMnemonicText: function() {
            return app.fn.textToHTML(this.get('mnemonic') ? this.get('mnemonic').text : '');
        },
        /**
         * @method getReading
         * @param {Number} [startFrom]
         * @param {Object} [options]
         * @returns {String}
         */
        getReading: function(startFrom, options) {
            var html = '';
            var segment = '';
            var position = 1;
            var fillers = [" ... ", "'", " "];
            var segments = [];
            //TODO: fix for single character prompts with multiple readings
            startFrom = startFrom ? startFrom : false;
            options = options ? options : {};
            options.classes = Array.isArray(options.classes) ? options.classes : [options.classes];
            options.hide = options.hide ? options.hide : false;
            options.hideKana = options.hideKana ? options.hideKana : [];
            options.mask = options.mask ? options.mask : false;
            options.style = options.style === 'zhuyin' ? true : false;
            if (!startFrom) {
               options.classes.push('no-spacing');
            }
            html += "
";
            if (this.isChinese()) {
                segments = app.fn.segmentReading(this.get('reading'));
                for (var a = 0, lengthA = segments.length; a < lengthA; a++) {
                    segment = segments[a];
                    html += "
";
                    for (var b = 0, lengthB = segment.length; b < lengthB; b++) {
                        var piece = segment[b];
                        if (fillers.indexOf(piece) === -1) {
                            var pieceMasked = piece.replace(/[1-5]/g, '');
                            var pieceMaskedZhuyin = app.fn.pinyin.toZhuyin(pieceMasked + '5');
                            var pieceTone = app.fn.pinyin.toTone(piece);
                            var pieceZhuyin = app.fn.pinyin.toZhuyin(piece);
                            pieceMasked = pieceMasked.replace('lv', 'lü');
                            pieceMaskedZhuyin = pieceMaskedZhuyin.replace('˙', '');
                            if (!startFrom || startFrom > position) {
                                if (!startFrom && options.hide) {
                                    html += "
";
                                    html += options.style ? pieceMaskedZhuyin : pieceMasked;
                                    html += "
";
                                } else {
                                    html += "
";
                                    html += options.style ? pieceZhuyin : pieceTone;
                                    html += "
";
                                }
                            } else {
                                if (options.hide) {
                                    html += "
";
                                    html += options.style ? pieceMaskedZhuyin : pieceMasked;
                                    html += "
";
                                } else if (options.mask) {
                                    html += "
";
                                    html += options.style ? pieceMaskedZhuyin : pieceMasked;
                                    html += "
";
                                } else {
                                    html += "
";
                                    html += "" + piece + "
";
                                }
                            }
                            position++;
                        } else {
                            html += "" + piece + "";
                        }
                    }
                    if (a < segments.length - 1) {
                        html += ", ";
                    }
                    html += "
";
                }
            } else {
                segments = this.get('reading').split('');
                html += "
";
                for (var c = 0, lengthC = segments.length; c < lengthC; c++) {
                    segment = segments[c];
                    if (options.hideKana.indexOf(segment) === -1) {
                        html += "
" + segment + "
";
                    } else {
                        html += "
 ー
";
                    }
                    position++;
                }
                html += "
";
            }
            return html + '
';
        },
        /**
         * @method getStroke
         * @returns {DataStroke}
         */
        getStroke: function() {
            return app.user.data.strokes.get(this.get('writing'));
        },
        /**
         * @method getStyle
         * @returns {String}
         */
        getStyle: function() {
            var activeStyles = app.user.settings.getActiveStyles();
            var style = this.get('style');
            if (style && ['both', 'none'].indexOf(style) === -1 &&
                activeStyles.indexOf('simp') > -1 && activeStyles.indexOf('trad') > -1) {
                return style;
            }
            return '';
        },
        /**
         * @method getTones
         * @param {Number} position
         * @returns {Array}
         */
        getTones: function(position) {
            var tones = [];
            var reading = this.get('reading');
            if (this.isChinese()) {
                if (reading.indexOf(', ') === -1) {
                    reading = reading.match(/[0-9]+/g);
                    for (var a = 0, lengthA = reading.length; a < lengthA; a++) {
                        tones.push([parseInt(reading[a], 10)]);
                    }
                } else {
                    reading = reading.split(', ');
                    for (var b = 0, lengthB = reading.length; b < lengthB; b++) {
                        tones.push([app.fn.arrayToInt(reading[b].match(/[0-9]+/g))]);
                    }
                }
                return _.flatten(this.getCharacterCount() > 1 ? tones[position - 1] : tones);
            }
            return tones;
        },
        /**
         * @method getWriting
         * @param {Number} [startFrom]
         * @param {Object} [options]
         * @returns {String}
         */
        getWriting: function(startFrom, options) {
            var html = '';
            var position = 1;
            var allCharacters = this.get('writing').split('');
            var containedCharacters = this.getCharacters();
            options = options ? options : {};
            options.classes = Array.isArray(options.classes) ? options.classes : [options.classes];
            html += "
";
            for (var i = 0, length = allCharacters.length; i < length; i++) {
                var character = allCharacters[i];
                if (containedCharacters.indexOf(character) > -1) {
                    if (!startFrom || startFrom > position) {
                        html += "" + character + "";
                    } else {
                        html += "";
                        html += "" + character + "";
                    }
                    position++;
                } else {
                    html += "" + character + "";
                }
            }
            return html + '
';
        },
        /**
         * @method isBanned
         * @returns {Boolean}
         */
        isBanned: function() {
            return this.get('bannedParts').length ? true : false;
        },
        /**
         * @method isChinese
         * @returns {Boolean}
         */
        isChinese: function() {
            return this.get('lang') === 'zh';
        },
        /**
         * @method isJapanese
         * @returns {Boolean}
         */
        isJapanese: function() {
            return this.get('lang') === 'ja';
        },
        /**
         * @method isStarred
         * @returns {Boolean}
         */
        isStarred: function() {
            return this.get('starred');
        },
        /**
         * @method playAudio
         * @returns {Boolean}
         */
        playAudio: function() {
            if (this.getAudio()) {
                app.assets.playAudio(this.getAudio());
                return true;
            }
            return false;
        }
    });

    return DataVocab;
});


text:
import io
import sys
import pytest
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.rest._requests_basic import RestRequestsTransportResponse
from azure.core.exceptions import HttpResponseError
import xml.etree.ElementTree as ET
from utils import readonly_checks

@pytest.fixture
def send_request(client):
    def _send_request(request):
        response = client.send_request(request, stream=False)
        response.raise_for_status()
        return response
    return _send_request

def test_response(send_request, port):
    response = send_request(
        request=HttpRequest("GET", "/basic/string"),
    )
    assert response.status_code == 200
    assert response.reason == "OK"
    assert response.text() == "Hello, world!"
    assert response.request.method == "GET"
    assert response.request.url == "http://localhost:{}/basic/string".format(port)

def test_response_content(send_request):
    response = send_request(
        request=HttpRequest("GET", "/basic/bytes"),
    )
    assert response.status_code == 200
    assert response.reason == "OK"
    assert response.text() == "Hello, world!"

def test_response_text(send_request):
    response = send_request(
        request=HttpRequest("GET", "/basic/string"),
    )
    assert response.status_code == 200
    assert response.reason == "OK"
    assert response.text() == "Hello, world!"
    assert response.headers["Content-Length"] == '13'
    assert response.headers['Content-Type'] == "text/plain; charset=utf-8"
    assert response.content_type == "text/plain; charset=utf-8"

def test_response_html(send_request):
    response = send_request(
        request=HttpRequest("GET", "/basic/html"),
    )
    assert response.status_code == 200
    assert response.reason == "OK"
    assert response.text() == "Hello, world!"

def test_raise_for_status(client):
    response = client.send_request(
        HttpRequest("GET", "/basic/string"),
    )
    response.raise_for_status()

    response = client.send_request(
        HttpRequest("GET", "/errors/403"),
    )
    assert response.status_code == 403
    with pytest.raises(HttpResponseError):
        response.raise_for_status()

    response = client.send_request(
        HttpRequest("GET", "/errors/500"),
        retry_total=0,  # takes too long with retires on 500
    )
    assert response.status_code == 500
    with pytest.raises(HttpResponseError):
        response.raise_for_status()

def test_response_repr(send_request):
    response = send_request(
        request=HttpRequest("GET", "/basic/string")
    )
    assert repr(response) == "<HttpResponse: 200 OK, Content-Type: text/plain; charset=utf-8>"

def test_response_content_type_encoding(send_request):
    """
    Use the charset encoding in the Content-Type header if possible.
    """
    response = send_request(
        request=HttpRequest("GET", "/encoding/latin-1")
    )
    assert response.content_type == "text/plain; charset=latin-1"
    assert response.text() == u"Latin 1: ÿ"
    assert response.encoding == "latin-1"

def test_response_autodetect_encoding(send_request):
    """
    Autodetect encoding if there is no Content-Type header.
    """
    response = send_request(
        request=HttpRequest("GET", "/encoding/latin-1")
    )

    assert response.text() == u'Latin 1: ÿ'
    assert response.encoding == "latin-1"

def test_response_fallback_to_autodetect(send_request):
    """
    Fallback to autodetection if we get an invalid charset in the Content-Type header.
    """
    response = send_request(
        request=HttpRequest("GET", "/encoding/invalid-codec-name")
    )

    assert response.headers["Content-Type"] == "text/plain; charset=invalid-codec-name"
    assert response.text() == u"おはようございます。"
    assert response.encoding is None

def test_response_no_charset_with_ascii_content(send_request):
    """
    A response with ascii encoded content should decode correctly,
    even with no charset specified.
    """
    response = send_request(
        request=HttpRequest("GET", "/encoding/no-charset"),
    )

    assert response.headers["Content-Type"] == "text/plain"
    assert response.status_code == 200
    assert response.encoding is None
    assert response.text() == "Hello, world!"

def test_response_no_charset_with_iso_8859_1_content(send_request):
    """
    We don't support iso-8859-1 by default following conversations
    about encoding flow
    """
    response = send_request(
        request=HttpRequest("GET", "/encoding/iso-8859-1"),
    )
    assert response.text() == u"Accented: �sterreich"
    assert response.encoding is None

def test_json(send_request):
    response = send_request(
        request=HttpRequest("GET", "/basic/json"),
    )
    assert response.json() == {"greeting": "hello", "recipient": "world"}
    assert response.encoding is None

def test_json_with_specified_encoding(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/json"),
    )
    assert response.json() == {"greeting": "hello", "recipient": "world"}
    assert response.encoding == "utf-16"

def test_emoji(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/emoji"),
    )
    assert response.text() == u"👩"

def test_emoji_family_with_skin_tone_modifier(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/emoji-family-skin-tone-modifier"),
    )
    assert response.text() == u"👩🏻👩🏽👧🏾👦🏿 SSN: 859-98-0987"

def test_korean_nfc(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/korean"),
    )
    assert response.text() == u"아가"

def test_urlencoded_content(send_request):
    send_request(
        request=HttpRequest(
            "POST",
            "/urlencoded/pet/add/1",
            data={ "pet_type": "dog", "pet_food": "meat", "name": "Fido", "pet_age": 42 }
        ),
    )

def test_multipart_files_content(send_request):
    request = HttpRequest(
        "POST",
        "/multipart/basic",
        files={"fileContent": io.BytesIO(b"<file content>")},
    )
    send_request(request)

def test_multipart_data_and_files_content(send_request):
    request = HttpRequest(
        "POST",
        "/multipart/data-and-files",
        data={"message": "Hello, world!"},
        files={"fileContent": io.BytesIO(b"<file content>")},
    )
    send_request(request)

def test_multipart_encode_non_seekable_filelike(send_request):
    """
    Test that special readable but non-seekable filelike objects are supported,
    at the cost of reading them into memory at most once.
    """

    class IteratorIO(io.IOBase):
        def __init__(self, iterator):
            self._iterator = iterator

        def read(self, *args):
            return b"".join(self._iterator)

    def data():
        yield b"Hello"
        yield b"World"

    fileobj = IteratorIO(data())
    files = {"file": fileobj}
    request = HttpRequest(
        "POST",
        "/multipart/non-seekable-filelike",
        files=files,
    )
    send_request(request)

def test_get_xml_basic(send_request):
    request = HttpRequest(
        "GET",
        "/xml/basic",
    )
    response = send_request(request)
    parsed_xml = ET.fromstring(response.text())
    assert parsed_xml.tag == 'slideshow'
    attributes = parsed_xml.attrib
    assert attributes['title'] == "Sample Slide Show"
    assert attributes['date'] == "Date of publication"
    assert attributes['author'] == "Yours Truly"

def test_put_xml_basic(send_request):

    basic_body = """<?xml version='1.0' encoding='UTF-8'?>
<slideshow
        title="Sample Slide Show"
        date="Date of publication"
        author="Yours Truly">
    <slide type="all">
        <title>Wake up to WonderWidgets!</title>
    </slide>
    <slide type="all">
        <title>Overview</title>
        <item>Why WonderWidgets are great</item>
        <item></item>
        <item>Who buys WonderWidgets</item>
    </slide>
</slideshow>"""

    request = HttpRequest(
        "PUT",
        "/xml/basic",
        content=ET.fromstring(basic_body),
    )
    send_request(request)

def test_send_request_return_pipeline_response(client):
    # we use return_pipeline_response for some cases in autorest
    request = HttpRequest("GET", "/basic/string")
    response = client.send_request(request, _return_pipeline_response=True)
    assert hasattr(response, "http_request")
    assert hasattr(response, "http_response")
    assert hasattr(response, "context")
    assert response.http_response.text() == "Hello, world!"
    assert hasattr(response.http_request, "content")

def test_text_and_encoding(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/emoji"),
    )
    assert response.content == u"👩".encode("utf-8")
    assert response.text() == u"👩"

    # try setting encoding as a property
    response.encoding = "utf-16"
    assert response.text() == u"鿰ꦑ" == response.content.decode(response.encoding)

    # assert latin-1 changes text decoding without changing encoding property
    assert response.text("latin-1") == u'ð\x9f\x91©' == response.content.decode("latin-1")
    assert response.encoding == "utf-16"

def test_passing_encoding_to_text(send_request):
    response = send_request(
        request=HttpRequest("GET", "/encoding/emoji"),
    )
    assert response.content == u"👩".encode("utf-8")
    assert response.text() == u"👩"

    # pass in different encoding
    assert response.text("latin-1") == u'ð\x9f\x91©'

    # check response.text() still gets us the old value
    assert response.text() == u"👩"

def test_initialize_response_abc():
    with pytest.raises(TypeError) as ex:
        HttpResponse()
    assert "Can't instantiate abstract class" in str(ex)

def test_readonly(send_request):
    """Make sure everything that is readonly is readonly"""
    response = send_request(HttpRequest("GET", "/health"))

    assert isinstance(response, RestRequestsTransportResponse)
    from azure.core.pipeline.transport import RequestsTransportResponse
    readonly_checks(response, old_response_class=RequestsTransportResponse)

redpajama_set_name: RedPajamaGithub


text:
namespace {

// Tracks whether the URL passed to the constructor is requested and whether
// the request bypasses the cache.
class TestResourceDispatcherHostDelegate
    : public content::ResourceDispatcherHostDelegate {
 public:
  explicit TestResourceDispatcherHostDelegate(const GURL& url)
      : url_(url), was_requested_(false), bypassed_cache_(false) {}
  ~TestResourceDispatcherHostDelegate() override {}

  void Reset() {
    was_requested_ = false;
    bypassed_cache_ = false;
  }

  // Resturns whether |url_| was requested.
  bool was_requested() const { return was_requested_; }

  // Returns whether any of the requests bypassed the HTTP cache.
  bool bypassed_cache() const { return bypassed_cache_; }

 private:
  // content::ResourceDispatcherHostDelegate:
  bool ShouldBeginRequest(const std::string& method,
                          const GURL& url,
                          content::ResourceType resource_type,
                          content::ResourceContext* resource_context) override {
    return true;
  }

  void RequestBeginning(
      net::URLRequest* request,
      content::ResourceContext* resource_context,
      content::AppCacheService* appcache_service,
      content::ResourceType resource_type,
      ScopedVector<content::ResourceThrottle>* throttles) override {
    if (request->url() == url_) {
      was_requested_ = true;
      if (request->load_flags() & net::LOAD_BYPASS_CACHE)
        bypassed_cache_ = true;
    }
  }

  void DownloadStarting(
      net::URLRequest* request,
      content::ResourceContext* resource_context,
      int child_id,
      int route_id,
      int request_id,
      bool is_content_initiated,
      bool must_download,
      ScopedVector<content::ResourceThrottle>* throttles) override {}

 private:
  GURL url_;
  bool was_requested_;
  bool bypassed_cache_;

  DISALLOW_COPY_AND_ASSIGN(TestResourceDispatcherHostDelegate);
};

// Checks whether the FaviconTabHelper is waiting for a download to complete or
// for data from the FaviconService.
class FaviconTabHelperPendingTaskChecker {
 public:
  virtual ~FaviconTabHelperPendingTaskChecker() {}

  virtual bool HasPendingTasks() = 0;
};

// Waits for the following the finish:
// - The pending navigation.
// - FaviconHandler's pending favicon database requests.
// - FaviconHandler's pending downloads.
class PendingTaskWaiter : public content::NotificationObserver {
 public:
  PendingTaskWaiter(content::WebContents* web_contents,
                    FaviconTabHelperPendingTaskChecker* checker)
      : checker_(checker), load_stopped_(false), weak_factory_(this) {
    registrar_.Add(this, chrome::NOTIFICATION_FAVICON_UPDATED,
                   content::Source<content::WebContents>(web_contents));
    registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
                   content::Source<content::NavigationController>(
                       &web_contents->GetController()));
  }
  ~PendingTaskWaiter() override {}

  void Wait() {
    if (load_stopped_ && !checker_->HasPendingTasks())
      return;

    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    run_loop.Run();
  }

 private:
  // content::NotificationObserver:
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override {
    if (type == content::NOTIFICATION_LOAD_STOP)
      load_stopped_ = true;

    if (!quit_closure_.is_null()) {
      // We stop waiting based on changes in state to FaviconHandler which occur
      // immediately after NOTIFICATION_FAVICON_UPDATED is sent. Post a task to
      // check if we can stop waiting.
      base::MessageLoopForUI::current()->PostTask(
          FROM_HERE, base::Bind(&PendingTaskWaiter::EndLoopIfCanStopWaiting,
                                weak_factory_.GetWeakPtr()));
    }
  }

  void EndLoopIfCanStopWaiting() {
    if (!quit_closure_.is_null() &&
        load_stopped_ &&
        !checker_->HasPendingTasks()) {
      quit_closure_.Run();
    }
  }

  FaviconTabHelperPendingTaskChecker* checker_;  // Not owned.
  bool load_stopped_;
  base::Closure quit_closure_;
  content::NotificationRegistrar registrar_;
  base::WeakPtrFactory<PendingTaskWaiter> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(PendingTaskWaiter);
};

}  // namespace

class FaviconTabHelperTest : public InProcessBrowserTest,
                             public FaviconTabHelperPendingTaskChecker {
 public:
  FaviconTabHelperTest() {}
  ~FaviconTabHelperTest() override {}

  content::WebContents* web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  // FaviconTabHelperPendingTaskChecker:
  bool HasPendingTasks() override {
    favicon::FaviconHandler* favicon_handler =
        FaviconTabHelper::FromWebContents(web_contents())
            ->favicon_handler_.get();
    return !favicon_handler->download_requests_.empty() ||
        favicon_handler->cancelable_task_tracker_.HasTrackedTasks();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(FaviconTabHelperTest);
};

// Test that when a user reloads a page ignoring the cache that the favicon is
// is redownloaded and (not returned from either the favicon cache or the HTTP
// cache).
IN_PROC_BROWSER_TEST_F(FaviconTabHelperTest, ReloadIgnoringCache) {
  ASSERT_TRUE(test_server()->Start());
  GURL url = test_server()->GetURL("files/favicon/page_with_favicon.html");
  GURL icon_url = test_server()->GetURL("files/favicon/icon.ico");

  scoped_ptr<TestResourceDispatcherHostDelegate> delegate(
      new TestResourceDispatcherHostDelegate(icon_url));
  content::ResourceDispatcherHost::Get()->SetDelegate(delegate.get());

  // Initial visit in order to populate the cache.
  {
    PendingTaskWaiter waiter(web_contents(), this);
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
    waiter.Wait();
  }
  ASSERT_TRUE(delegate->was_requested());
  EXPECT_FALSE(delegate->bypassed_cache());
  delegate->Reset();

  ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));

  // A normal visit should fetch the favicon from either the favicon database or
  // the HTTP cache.
  {
    PendingTaskWaiter waiter(web_contents(), this);
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
    waiter.Wait();
  }
  EXPECT_FALSE(delegate->bypassed_cache());
  delegate->Reset();

  // A reload ignoring the cache should refetch the favicon from the website.
  {
    PendingTaskWaiter waiter(web_contents(), this);
    chrome::ExecuteCommand(browser(), IDC_RELOAD_IGNORING_CACHE);
    waiter.Wait();
  }
  ASSERT_TRUE(delegate->was_requested());
  EXPECT_TRUE(delegate->bypassed_cache());
}


text:
<!DOCTYPE html>

    <title>Conway's Game of Life</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/main.css" rel="stylesheet" />

                    <canvas id="myCanvas" width="800" height="800"></canvas>

Cycle: 0

Conway's Game of Life

Rules of the game

Any live cell with fewer than two live neighbours dies.

Any live cell with two or three live neighbours lives on to the next generation.

Any live cell with more than three live neighbours dies.

Any dead cell with exactly three live neighbours becomes a live cell.

                    Cycles:
                    <input type="number" class="form-control" id="cycles" placeholder="Cycles to run" />

Run cycles

Play

Step

LIFE

Glider Gun

Clear Grid

                        GitHub Repo
                        <button class="btn btn-primary" data-toggle="modal" data-target="#aboutModal">About</button>

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

About Conway's Game of Life

Written by Laurance Walden using HTML Canvas and Javascript.

View more of my work on my Portfolio Page.

Read more about Conway's Game of Life on Wikipedia.

The board contains 6400 cells. Cells on the edge of the grid are considered connected to cells on the opposite side. This
                    casues 'gliders' and simlar patterns to wrap around the screen.

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
const Employee = require('./employee.model');
const { signToken } = require('../../db/helpers');
const controller = {};

controller.createNewEmployee = (res, rej, req, params) => {
  const {
    username,
    password,
    firstName,
    lastName,
    email,
    phoneNo,
  } = req.body;

  return Employee.create({ username, password, firstName, lastName, email, phoneNo })
    .then((user) => ({ token: signToken(user.id), user }))
    .then((data) => res({ data }));
};

controller.getEmployee = (res, rej, req, params) => {

};

controller.putEmployee = (res, rej, req, params) => {

};

module.exports = controller;


text:
const { Event } = require("klasa");

module.exports = class extends Event {
    constructor(...args) {
        super(...args, {
            enabled: true,
            name: "guildMemberRemove"
        });
    }

    async run(member) {
        const leaveMsg = member.guild.settings.leaveMsg;
        const leaveChannel = member.guild.channels.cache.get(member.guild.settings.defaultChannel);
        let warnlog = JSON.parse(member.guild.settings.warnlog);

        if (warnlog[member.id]) {
            delete warnlog[member.id];
            await member.guild.settings.update("warnlog", JSON.stringify(warnlog));
        }

        if (!leaveMsg || !leaveChannel) { return; } // No message/channel set, return.

        leaveChannel.send(
            leaveMsg.replace("-pinguser", `<@!${member.id}>`)
                .replace("-servername", member.guild.name)
                .replace("-userid", member.id)
                .replace("-username", member.user.username)
        );
    }
};


text:
<?php

require_once('models/common/common_node.php');
require_once('models/ecommerce/ecommerce_store.php');

class Onxshop_Controller_Component_Ecommerce_Store_Nearby_Radius extends Onxshop_Controller {

	/**
	 * main action
	 */
	public function mainAction()
	{
		// get selected store for detail
		$node_id = (int) $this->GET['node_id'];

		if ($node_id > 0) {

			$Node = new common_node();
			$Store = new ecommerce_store();
			$current_store = $Store->findStoreByNode($node_id);

			if ($current_store & is_numeric($current_store['id'])) {

				$distance = 0.20;
				$lat1 = (float) ((float) $current_store['latitude'] - $distance);
				$lat2 = (float) ((float) $current_store['latitude'] + $distance);
				$lng1 = (float) ((float) $current_store['longitude'] - $distance);
				$lng2 = (float) ((float) $current_store['longitude'] + $distance);
				$stores = $Store->listing("id != {$current_store['id']} AND publish = 1 AND " .
					"latitude BETWEEN $lat1 AND $lat2 AND longitude BETWEEN $lng1 AND $lng2");

				if (count($stores) > 0) {

					$distances = array();
					foreach ($stores as $i => $store) {
						$distance = $this->distance($current_store['latitude'], $current_store['longitude'],
							$store['latitude'], $store['longitude']);
						$distances[$i] = $distance;
					}

					asort($distances, SORT_NUMERIC);

					$i = 0;

					foreach ($distances as $store_index => $distance) {

						$store = $stores[$store_index];

						if ($distance < 1) $distance = round($distance * 1000) . " meters";
						else $distance = number_format($distance, 1) . " km";
						$store['distance'] = $distance;

						// get store page for url
						$page = $Store->getStoreHomepage($store['id']);
						$store['node_id'] = $page['id'];

						$this->tpl->assign("STORE", $store);

						$column = $i % 3 + 1;
						$this->tpl->parse("content.list.column$column");

						$i++;
						if ($i == 9) break; // 9 sotres is enough

					}
					$this->tpl->parse("content.list");
				}
			}
		}

		return true;
	}

	/**
	 * Get distance between two points on sphere (in km)
	 * http://en.wikipedia.org/wiki/Haversine_formula
	 *
	 * @param  float $lat1 First point latitude
	 * @param  float $lng1 First point longitude
	 * @param  float $lat2 Second point latitude
	 * @param  float $lng2 Second point longitude
	 * @return float
	 */
	public function distance($lat1, $lng1, $lat2, $lng2)
	{
		$earth_radius = 6371;

		$sin_lat = sin(deg2rad($lat2  - $lat1) / 2.0);
		$sin2_lat = $sin_lat * $sin_lat;

		$sin_lng = sin(deg2rad($lng2 - $lng1) / 2.0);
		$sin2_lng = $sin_lng * $sin_lng;

		$cos_lat1 = cos($lat1);
		$cos_lat2 = cos($lat2);

		$sqrt = sqrt($sin2_lat + ($cos_lat1 * $cos_lat2 * $sin2_lng));

		$distance = 2.0 * $earth_radius * asin($sqrt);

		return $distance;
	}

}


text:
using NUnit.Framework;
using VkNet.Enums.SafetyEnums;

namespace VkNet.Tests.Enum.SafetyEnums
{
	[TestFixture]
    public class SafetyEnumsTest
    {

		[Test]
        public void AppFilterTest()
        {
			// get test
			Assert.That(AppFilter.Installed.ToString(), Is.EqualTo("installed"));
			Assert.That(AppFilter.Featured.ToString(), Is.EqualTo("featured"));
			// parse test
			Assert.That(AppFilter.FromJson("installed"), Is.EqualTo(AppFilter.Installed));
			Assert.That(AppFilter.FromJson("featured"), Is.EqualTo(AppFilter.Featured));
		}

		[Test]
        public void AppPlatformsTest()
        {
			// get test
			Assert.That(AppPlatforms.Ios.ToString(), Is.EqualTo("ios"));
			Assert.That(AppPlatforms.Android.ToString(), Is.EqualTo("android"));
			Assert.That(AppPlatforms.WinPhone.ToString(), Is.EqualTo("winphone"));
			Assert.That(AppPlatforms.Web.ToString(), Is.EqualTo("web"));
			// parse test
			Assert.That(AppPlatforms.FromJson("ios"), Is.EqualTo(AppPlatforms.Ios));
			Assert.That(AppPlatforms.FromJson("android"), Is.EqualTo(AppPlatforms.Android));
			Assert.That(AppPlatforms.FromJson("winphone"), Is.EqualTo(AppPlatforms.WinPhone));
			Assert.That(AppPlatforms.FromJson("web"), Is.EqualTo(AppPlatforms.Web));
		}

		[Test]
        public void AppRatingTypeTest()
        {
			// get test
			Assert.That(AppRatingType.Level.ToString(), Is.EqualTo("level"));
			Assert.That(AppRatingType.Points.ToString(), Is.EqualTo("points"));
			// parse test
			Assert.That(AppRatingType.FromJson("level"), Is.EqualTo(AppRatingType.Level));
			Assert.That(AppRatingType.FromJson("points"), Is.EqualTo(AppRatingType.Points));
		}

		[Test]
        public void AppRequestTypeTest()
        {
			// get test
			Assert.That(AppRequestType.Invite.ToString(), Is.EqualTo("invite"));
			Assert.That(AppRequestType.Request.ToString(), Is.EqualTo("request"));
			// parse test
			Assert.That(AppRequestType.FromJson("invite"), Is.EqualTo(AppRequestType.Invite));
			Assert.That(AppRequestType.FromJson("request"), Is.EqualTo(AppRequestType.Request));
		}

		[Test]
        public void AppSortTest()
        {
			// get test
			Assert.That(AppSort.PopularToday.ToString(), Is.EqualTo("popular_today"));
			Assert.That(AppSort.Visitors.ToString(), Is.EqualTo("visitors"));
			Assert.That(AppSort.CreateDate.ToString(), Is.EqualTo("create_date"));
			Assert.That(AppSort.GrowthRate.ToString(), Is.EqualTo("growth_rate"));
			Assert.That(AppSort.PopularWeek.ToString(), Is.EqualTo("popular_week"));
			// parse test
			Assert.That(AppSort.FromJson("popular_today"), Is.EqualTo(AppSort.PopularToday));
			Assert.That(AppSort.FromJson("visitors"), Is.EqualTo(AppSort.Visitors));
			Assert.That(AppSort.FromJson("create_date"), Is.EqualTo(AppSort.CreateDate));
			Assert.That(AppSort.FromJson("growth_rate"), Is.EqualTo(AppSort.GrowthRate));
			Assert.That(AppSort.FromJson("popular_week"), Is.EqualTo(AppSort.PopularWeek));
		}

		[Test]
        public void ChangeNameStatusTest()
        {
			// get test
			Assert.That(ChangeNameStatus.Processing.ToString(), Is.EqualTo("processing"));
			Assert.That(ChangeNameStatus.Declined.ToString(), Is.EqualTo("declined"));
			Assert.That(ChangeNameStatus.Success.ToString(), Is.EqualTo("success"));
			Assert.That(ChangeNameStatus.WasAccepted.ToString(), Is.EqualTo("was_accepted"));
			Assert.That(ChangeNameStatus.WasDeclined.ToString(), Is.EqualTo("was_declined"));
			// parse test
			Assert.That(ChangeNameStatus.FromJson("processing"), Is.EqualTo(ChangeNameStatus.Processing));
			Assert.That(ChangeNameStatus.FromJson("declined"), Is.EqualTo(ChangeNameStatus.Declined));
			Assert.That(ChangeNameStatus.FromJson("success"), Is.EqualTo(ChangeNameStatus.Success));
			Assert.That(ChangeNameStatus.FromJson("was_accepted"), Is.EqualTo(ChangeNameStatus.WasAccepted));
			Assert.That(ChangeNameStatus.FromJson("was_declined"), Is.EqualTo(ChangeNameStatus.WasDeclined));
		}

		[Test]
        public void CommentObjectTypeTest()
        {
			// get test
			Assert.That(CommentObjectType.Post.ToString(), Is.EqualTo("post"));
			Assert.That(CommentObjectType.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(CommentObjectType.Video.ToString(), Is.EqualTo("video"));
			Assert.That(CommentObjectType.Topic.ToString(), Is.EqualTo("topic"));
			Assert.That(CommentObjectType.Note.ToString(), Is.EqualTo("note"));
			// parse test
			Assert.That(CommentObjectType.FromJson("post"), Is.EqualTo(CommentObjectType.Post));
			Assert.That(CommentObjectType.FromJson("photo"), Is.EqualTo(CommentObjectType.Photo));
			Assert.That(CommentObjectType.FromJson("video"), Is.EqualTo(CommentObjectType.Video));
			Assert.That(CommentObjectType.FromJson("topic"), Is.EqualTo(CommentObjectType.Topic));
			Assert.That(CommentObjectType.FromJson("note"), Is.EqualTo(CommentObjectType.Note));
		}

		[Test]
        public void CommentsSortTest()
        {
			// get test
			Assert.That(CommentsSort.Asc.ToString(), Is.EqualTo("asc"));
			Assert.That(CommentsSort.Desc.ToString(), Is.EqualTo("desc"));
			// parse test
			Assert.That(CommentsSort.FromJson("asc"), Is.EqualTo(CommentsSort.Asc));
			Assert.That(CommentsSort.FromJson("desc"), Is.EqualTo(CommentsSort.Desc));
		}

		[Test]
        public void DeactivatedTest()
        {
			// get test
			Assert.That(Deactivated.Deleted.ToString(), Is.EqualTo("deleted"));
			Assert.That(Deactivated.Banned.ToString(), Is.EqualTo("banned"));
			Assert.That(Deactivated.Activated.ToString(), Is.EqualTo("activated"));
			// parse test
			Assert.That(Deactivated.FromJson("deleted"), Is.EqualTo(Deactivated.Deleted));
			Assert.That(Deactivated.FromJson("banned"), Is.EqualTo(Deactivated.Banned));
			Assert.That(Deactivated.FromJson("activated"), Is.EqualTo(Deactivated.Activated));
		}

		[Test]
        public void DisplayTest()
        {
			// get test
			Assert.That(Display.Page.ToString(), Is.EqualTo("page"));
			Assert.That(Display.Popup.ToString(), Is.EqualTo("popup"));
			Assert.That(Display.Wap.ToString(), Is.EqualTo("wap"));
			// parse test
			Assert.That(Display.FromJson("page"), Is.EqualTo(Display.Page));
			Assert.That(Display.FromJson("popup"), Is.EqualTo(Display.Popup));
			Assert.That(Display.FromJson("wap"), Is.EqualTo(Display.Wap));
		}

		[Test]
        public void FeedTypeTest()
        {
			// get test
			Assert.That(FeedType.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(FeedType.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
			// parse test
			Assert.That(FeedType.FromJson("photo"), Is.EqualTo(FeedType.Photo));
			Assert.That(FeedType.FromJson("photo_tag"), Is.EqualTo(FeedType.PhotoTag));
		}

		[Test]
        public void FriendsFilterTest()
        {
			// get test
			Assert.That(FriendsFilter.Mutual.ToString(), Is.EqualTo("mutual"));
			Assert.That(FriendsFilter.Contacts.ToString(), Is.EqualTo("contacts"));
			Assert.That(FriendsFilter.MutualContacts.ToString(), Is.EqualTo("mutual_contacts"));
			// parse test
			Assert.That(FriendsFilter.FromJson("mutual"), Is.EqualTo(FriendsFilter.Mutual));
			Assert.That(FriendsFilter.FromJson("contacts"), Is.EqualTo(FriendsFilter.Contacts));
			Assert.That(FriendsFilter.FromJson("mutual_contacts"), Is.EqualTo(FriendsFilter.MutualContacts));
		}

		[Test]
        public void FriendsOrderTest()
        {
			// get test
			Assert.That(FriendsOrder.Name.ToString(), Is.EqualTo("name"));
			Assert.That(FriendsOrder.Hints.ToString(), Is.EqualTo("hints"));
			Assert.That(FriendsOrder.Random.ToString(), Is.EqualTo("random"));
			// parse test
			Assert.That(FriendsOrder.FromJson("name"), Is.EqualTo(FriendsOrder.Name));
			Assert.That(FriendsOrder.FromJson("hints"), Is.EqualTo(FriendsOrder.Hints));
			Assert.That(FriendsOrder.FromJson("random"), Is.EqualTo(FriendsOrder.Random));
		}

		[Test]
        public void GroupsSortTest()
        {
			// get test
			Assert.That(GroupsSort.IdAsc.ToString(), Is.EqualTo("id_asc"));
			Assert.That(GroupsSort.IdDesc.ToString(), Is.EqualTo("id_desc"));
			Assert.That(GroupsSort.TimeAsc.ToString(), Is.EqualTo("time_asc"));
			Assert.That(GroupsSort.TimeDesc.ToString(), Is.EqualTo("time_desc"));
			// parse test
			Assert.That(GroupsSort.FromJson("id_asc"), Is.EqualTo(GroupsSort.IdAsc));
			Assert.That(GroupsSort.FromJson("id_desc"), Is.EqualTo(GroupsSort.IdDesc));
			Assert.That(GroupsSort.FromJson("time_asc"), Is.EqualTo(GroupsSort.TimeAsc));
			Assert.That(GroupsSort.FromJson("time_desc"), Is.EqualTo(GroupsSort.TimeDesc));
		}

		[Test]
        public void GroupTypeTest()
        {
			// get test
			Assert.That(GroupType.Page.ToString(), Is.EqualTo("page"));
			Assert.That(GroupType.Group.ToString(), Is.EqualTo("group"));
			Assert.That(GroupType.Event.ToString(), Is.EqualTo("event"));
			Assert.That(GroupType.Undefined.ToString(), Is.EqualTo("undefined"));
			// parse test
			Assert.That(GroupType.FromJson("page"), Is.EqualTo(GroupType.Page));
			Assert.That(GroupType.FromJson("group"), Is.EqualTo(GroupType.Group));
			Assert.That(GroupType.FromJson("event"), Is.EqualTo(GroupType.Event));
			Assert.That(GroupType.FromJson("undefined"), Is.EqualTo(GroupType.Undefined));
		}

		[Test]
        public void LikeObjectTypeTest()
        {
			// get test
			Assert.That(LikeObjectType.Post.ToString(), Is.EqualTo("post"));
			Assert.That(LikeObjectType.Comment.ToString(), Is.EqualTo("comment"));
			Assert.That(LikeObjectType.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(LikeObjectType.Audio.ToString(), Is.EqualTo("audio"));
			Assert.That(LikeObjectType.Video.ToString(), Is.EqualTo("video"));
			Assert.That(LikeObjectType.Note.ToString(), Is.EqualTo("note"));
			Assert.That(LikeObjectType.PhotoComment.ToString(), Is.EqualTo("photo_comment"));
			Assert.That(LikeObjectType.VideoComment.ToString(), Is.EqualTo("video_comment"));
			Assert.That(LikeObjectType.TopicComment.ToString(), Is.EqualTo("topic_comment"));
			Assert.That(LikeObjectType.SitePage.ToString(), Is.EqualTo("sitepage"));
			Assert.That(LikeObjectType.Market.ToString(), Is.EqualTo("market"));
			Assert.That(LikeObjectType.MarketComment.ToString(), Is.EqualTo("market_comment"));
			// parse test
			Assert.That(LikeObjectType.FromJson("post"), Is.EqualTo(LikeObjectType.Post));
			Assert.That(LikeObjectType.FromJson("comment"), Is.EqualTo(LikeObjectType.Comment));
			Assert.That(LikeObjectType.FromJson("photo"), Is.EqualTo(LikeObjectType.Photo));
			Assert.That(LikeObjectType.FromJson("audio"), Is.EqualTo(LikeObjectType.Audio));
			Assert.That(LikeObjectType.FromJson("video"), Is.EqualTo(LikeObjectType.Video));
			Assert.That(LikeObjectType.FromJson("note"), Is.EqualTo(LikeObjectType.Note));
			Assert.That(LikeObjectType.FromJson("photo_comment"), Is.EqualTo(LikeObjectType.PhotoComment));
			Assert.That(LikeObjectType.FromJson("video_comment"), Is.EqualTo(LikeObjectType.VideoComment));
			Assert.That(LikeObjectType.FromJson("topic_comment"), Is.EqualTo(LikeObjectType.TopicComment));
			Assert.That(LikeObjectType.FromJson("sitepage"), Is.EqualTo(LikeObjectType.SitePage));
			Assert.That(LikeObjectType.FromJson("market"), Is.EqualTo(LikeObjectType.Market));
			Assert.That(LikeObjectType.FromJson("market_comment"), Is.EqualTo(LikeObjectType.MarketComment));
		}

		[Test]
        public void LikesFilterTest()
        {
			// get test
			Assert.That(LikesFilter.Likes.ToString(), Is.EqualTo("likes"));
			Assert.That(LikesFilter.Copies.ToString(), Is.EqualTo("copies"));
			// parse test
			Assert.That(LikesFilter.FromJson("likes"), Is.EqualTo(LikesFilter.Likes));
			Assert.That(LikesFilter.FromJson("copies"), Is.EqualTo(LikesFilter.Copies));
		}

		[Test]
        public void LinkAccessTypeTest()
        {
			// get test
			Assert.That(LinkAccessType.NotBanned.ToString(), Is.EqualTo("not_banned"));
			Assert.That(LinkAccessType.Banned.ToString(), Is.EqualTo("banned"));
			Assert.That(LinkAccessType.Processing.ToString(), Is.EqualTo("processing"));
			// parse test
			Assert.That(LinkAccessType.FromJson("not_banned"), Is.EqualTo(LinkAccessType.NotBanned));
			Assert.That(LinkAccessType.FromJson("banned"), Is.EqualTo(LinkAccessType.Banned));
			Assert.That(LinkAccessType.FromJson("processing"), Is.EqualTo(LinkAccessType.Processing));
		}

		[Test]
        public void MediaTypeTest()
        {
			// get test
			Assert.That(MediaType.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(MediaType.Video.ToString(), Is.EqualTo("video"));
			Assert.That(MediaType.Audio.ToString(), Is.EqualTo("audio"));
			Assert.That(MediaType.Doc.ToString(), Is.EqualTo("doc"));
			Assert.That(MediaType.Link.ToString(), Is.EqualTo("link"));
			Assert.That(MediaType.Market.ToString(), Is.EqualTo("market"));
			Assert.That(MediaType.Wall.ToString(), Is.EqualTo("wall"));
			Assert.That(MediaType.Share.ToString(), Is.EqualTo("share"));
			// parse test
			Assert.That(MediaType.FromJson("photo"), Is.EqualTo(MediaType.Photo));
			Assert.That(MediaType.FromJson("video"), Is.EqualTo(MediaType.Video));
			Assert.That(MediaType.FromJson("audio"), Is.EqualTo(MediaType.Audio));
			Assert.That(MediaType.FromJson("doc"), Is.EqualTo(MediaType.Doc));
			Assert.That(MediaType.FromJson("link"), Is.EqualTo(MediaType.Link));
			Assert.That(MediaType.FromJson("market"), Is.EqualTo(MediaType.Market));
			Assert.That(MediaType.FromJson("wall"), Is.EqualTo(MediaType.Wall));
			Assert.That(MediaType.FromJson("share"), Is.EqualTo(MediaType.Share));
		}

		[Test]
        public void NameCaseTest()
        {
			// get test
			Assert.That(NameCase.Nom.ToString(), Is.EqualTo("nom"));
			Assert.That(NameCase.Gen.ToString(), Is.EqualTo("gen"));
			Assert.That(NameCase.Dat.ToString(), Is.EqualTo("dat"));
			Assert.That(NameCase.Acc.ToString(), Is.EqualTo("acc"));
			Assert.That(NameCase.Ins.ToString(), Is.EqualTo("ins"));
			Assert.That(NameCase.Abl.ToString(), Is.EqualTo("abl"));
			// parse test
			Assert.That(NameCase.FromJson("nom"), Is.EqualTo(NameCase.Nom));
			Assert.That(NameCase.FromJson("gen"), Is.EqualTo(NameCase.Gen));
			Assert.That(NameCase.FromJson("dat"), Is.EqualTo(NameCase.Dat));
			Assert.That(NameCase.FromJson("acc"), Is.EqualTo(NameCase.Acc));
			Assert.That(NameCase.FromJson("ins"), Is.EqualTo(NameCase.Ins));
			Assert.That(NameCase.FromJson("abl"), Is.EqualTo(NameCase.Abl));
		}

		[Test]
        public void NewsObjectTypesTest()
        {
			// get test
			Assert.That(NewsObjectTypes.Wall.ToString(), Is.EqualTo("wall"));
			Assert.That(NewsObjectTypes.Tag.ToString(), Is.EqualTo("tag"));
			Assert.That(NewsObjectTypes.ProfilePhoto.ToString(), Is.EqualTo("profilephoto"));
			Assert.That(NewsObjectTypes.Video.ToString(), Is.EqualTo("video"));
			Assert.That(NewsObjectTypes.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(NewsObjectTypes.Audio.ToString(), Is.EqualTo("audio"));
			// parse test
			Assert.That(NewsObjectTypes.FromJson("wall"), Is.EqualTo(NewsObjectTypes.Wall));
			Assert.That(NewsObjectTypes.FromJson("tag"), Is.EqualTo(NewsObjectTypes.Tag));
			Assert.That(NewsObjectTypes.FromJson("profilephoto"), Is.EqualTo(NewsObjectTypes.ProfilePhoto));
			Assert.That(NewsObjectTypes.FromJson("video"), Is.EqualTo(NewsObjectTypes.Video));
			Assert.That(NewsObjectTypes.FromJson("photo"), Is.EqualTo(NewsObjectTypes.Photo));
			Assert.That(NewsObjectTypes.FromJson("audio"), Is.EqualTo(NewsObjectTypes.Audio));
		}

		[Test]
        public void NewsTypesTest()
        {
			// get test
			Assert.That(NewsTypes.Post.ToString(), Is.EqualTo("post"));
			Assert.That(NewsTypes.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(NewsTypes.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
			Assert.That(NewsTypes.WallPhoto.ToString(), Is.EqualTo("wall_photo"));
			Assert.That(NewsTypes.Friend.ToString(), Is.EqualTo("friend"));
			Assert.That(NewsTypes.Note.ToString(), Is.EqualTo("note"));
			// parse test
			Assert.That(NewsTypes.FromJson("post"), Is.EqualTo(NewsTypes.Post));
			Assert.That(NewsTypes.FromJson("photo"), Is.EqualTo(NewsTypes.Photo));
			Assert.That(NewsTypes.FromJson("photo_tag"), Is.EqualTo(NewsTypes.PhotoTag));
			Assert.That(NewsTypes.FromJson("wall_photo"), Is.EqualTo(NewsTypes.WallPhoto));
			Assert.That(NewsTypes.FromJson("friend"), Is.EqualTo(NewsTypes.Friend));
			Assert.That(NewsTypes.FromJson("note"), Is.EqualTo(NewsTypes.Note));
		}

		[Test]
        public void OccupationTypeTest()
        {
			// get test
			Assert.That(OccupationType.Work.ToString(), Is.EqualTo("work"));
			Assert.That(OccupationType.School.ToString(), Is.EqualTo("school"));
			Assert.That(OccupationType.University.ToString(), Is.EqualTo("university"));
			// parse test
			Assert.That(OccupationType.FromJson("work"), Is.EqualTo(OccupationType.Work));
			Assert.That(OccupationType.FromJson("school"), Is.EqualTo(OccupationType.School));
			Assert.That(OccupationType.FromJson("university"), Is.EqualTo(OccupationType.University));
		}

		[Test]
        public void PhotoAlbumTypeTest()
        {
			// get test
			Assert.That(PhotoAlbumType.Wall.ToString(), Is.EqualTo("wall"));
			Assert.That(PhotoAlbumType.Profile.ToString(), Is.EqualTo("profile"));
			Assert.That(PhotoAlbumType.Saved.ToString(), Is.EqualTo("saved"));
			// parse test
			Assert.That(PhotoAlbumType.FromJson("wall"), Is.EqualTo(PhotoAlbumType.Wall));
			Assert.That(PhotoAlbumType.FromJson("profile"), Is.EqualTo(PhotoAlbumType.Profile));
			Assert.That(PhotoAlbumType.FromJson("saved"), Is.EqualTo(PhotoAlbumType.Saved));
		}

		[Test]
        public void PhotoFeedTypeTest()
        {
			// get test
			Assert.That(PhotoFeedType.Photo.ToString(), Is.EqualTo("photo"));
			Assert.That(PhotoFeedType.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
			// parse test
			Assert.That(PhotoFeedType.FromJson("photo"), Is.EqualTo(PhotoFeedType.Photo));
			Assert.That(PhotoFeedType.FromJson("photo_tag"), Is.EqualTo(PhotoFeedType.PhotoTag));
		}

		[Test]
        public void PhotoSearchRadiusTest()
        {
			// get test
			Assert.That(PhotoSearchRadius.Ten.ToString(), Is.EqualTo("10"));
			Assert.That(PhotoSearchRadius.OneHundred.ToString(), Is.EqualTo("100"));
			Assert.That(PhotoSearchRadius.Eighty.ToString(), Is.EqualTo("800"));
			Assert.That(PhotoSearchRadius.SixThousand.ToString(), Is.EqualTo("6000"));
			Assert.That(PhotoSearchRadius.FiftyThousand.ToString(), Is.EqualTo("50000"));
			// parse test
			Assert.That(PhotoSearchRadius.FromJson("10"), Is.EqualTo(PhotoSearchRadius.Ten));
			Assert.That(PhotoSearchRadius.FromJson("100"), Is.EqualTo(PhotoSearchRadius.OneHundred));
			Assert.That(PhotoSearchRadius.FromJson("800"), Is.EqualTo(PhotoSearchRadius.Eighty));
			Assert.That(PhotoSearchRadius.FromJson("6000"), Is.EqualTo(PhotoSearchRadius.SixThousand));
			Assert.That(PhotoSearchRadius.FromJson("50000"), Is.EqualTo(PhotoSearchRadius.FiftyThousand));
		}

		[Test]
        public void PhotoSizeTypeTest()
        {
			// get test
			Assert.That(PhotoSizeType.S.ToString(), Is.EqualTo("s"));
			Assert.That(PhotoSizeType.M.ToString(), Is.EqualTo("m"));
			Assert.That(PhotoSizeType.X.ToString(), Is.EqualTo("x"));
			Assert.That(PhotoSizeType.O.ToString(), Is.EqualTo("o"));
			Assert.That(PhotoSizeType.P.ToString(), Is.EqualTo("p"));
			Assert.That(PhotoSizeType.Q.ToString(), Is.EqualTo("q"));
			Assert.That(PhotoSizeType.R.ToString(), Is.EqualTo("r"));
			Assert.That(PhotoSizeType.Y.ToString(), Is.EqualTo("y"));
			Assert.That(PhotoSizeType.Z.ToString(), Is.EqualTo("z"));
			Assert.That(PhotoSizeType.W.ToString(), Is.EqualTo("w"));
			// parse test
			Assert.That(PhotoSizeType.FromJson("s"), Is.EqualTo(PhotoSizeType.S));
			Assert.That(PhotoSizeType.FromJson("m"), Is.EqualTo(PhotoSizeType.M));
			Assert.That(PhotoSizeType.FromJson("x"), Is.EqualTo(PhotoSizeType.X));
			Assert.That(PhotoSizeType.FromJson("o"), Is.EqualTo(PhotoSizeType.O));
			Assert.That(PhotoSizeType.FromJson("p"), Is.EqualTo(PhotoSizeType.P));
			Assert.That(PhotoSizeType.FromJson("q"), Is.EqualTo(PhotoSizeType.Q));
			Assert.That(PhotoSizeType.FromJson("r"), Is.EqualTo(PhotoSizeType.R));
			Assert.That(PhotoSizeType.FromJson("y"), Is.EqualTo(PhotoSizeType.Y));
			Assert.That(PhotoSizeType.FromJson("z"), Is.EqualTo(PhotoSizeType.Z));
			Assert.That(PhotoSizeType.FromJson("w"), Is.EqualTo(PhotoSizeType.W));
		}

		[Test]
        public void PlatformTest()
        {
			// get test
			Assert.That(Platform.Android.ToString(), Is.EqualTo("android"));
			Assert.That(Platform.IPhone.ToString(), Is.EqualTo("iphone"));
			Assert.That(Platform.WindowsPhone.ToString(), Is.EqualTo("wphone"));
			// parse test
			Assert.That(Platform.FromJson("android"), Is.EqualTo(Platform.Android));
			Assert.That(Platform.FromJson("iphone"), Is.EqualTo(Platform.IPhone));
			Assert.That(Platform.FromJson("wphone"), Is.EqualTo(Platform.WindowsPhone));
		}

		[Test]
        public void PostSourceTypeTest()
        {
			// get test
			Assert.That(PostSourceType.Vk.ToString(), Is.EqualTo("vk"));
			Assert.That(PostSourceType.Widget.ToString(), Is.EqualTo("widget"));
			Assert.That(PostSourceType.Api.ToString(), Is.EqualTo("api"));
			Assert.That(PostSourceType.Rss.ToString(), Is.EqualTo("rss"));
			Assert.That(PostSourceType.Sms.ToString(), Is.EqualTo("sms"));
			// parse test
			Assert.That(PostSourceType.FromJson("vk"), Is.EqualTo(PostSourceType.Vk));
			Assert.That(PostSourceType.FromJson("widget"), Is.EqualTo(PostSourceType.Widget));
			Assert.That(PostSourceType.FromJson("api"), Is.EqualTo(PostSourceType.Api));
			Assert.That(PostSourceType.FromJson("rss"), Is.EqualTo(PostSourceType.Rss));
			Assert.That(PostSourceType.FromJson("sms"), Is.EqualTo(PostSourceType.Sms));
		}

		[Test]
        public void PostTypeTest()
        {
			// get test
			Assert.That(PostType.Post.ToString(), Is.EqualTo("post"));
			Assert.That(PostType.Copy.ToString(), Is.EqualTo("copy"));
			Assert.That(PostType.Reply.ToString(), Is.EqualTo("reply"));
			Assert.That(PostType.Postpone.ToString(), Is.EqualTo("postpone"));
			Assert.That(PostType.Suggest.ToString(), Is.EqualTo("suggest"));
			// parse test
			Assert.That(PostType.FromJson("post"), Is.EqualTo(PostType.Post));
			Assert.That(PostType.FromJson("copy"), Is.EqualTo(PostType.Copy));
			Assert.That(PostType.FromJson("reply"), Is.EqualTo(PostType.Reply));
			Assert.That(PostType.FromJson("postpone"), Is.EqualTo(PostType.Postpone));
			Assert.That(PostType.FromJson("suggest"), Is.EqualTo(PostType.Suggest));
		}

		[Test]
        public void PostTypeOrderTest()
        {
			// get test
			Assert.That(PostTypeOrder.Post.ToString(), Is.EqualTo("post"));
			Assert.That(PostTypeOrder.Copy.ToString(), Is.EqualTo("copy"));
			// parse test
			Assert.That(PostTypeOrder.FromJson("post"), Is.EqualTo(PostTypeOrder.Post));
			Assert.That(PostTypeOrder.FromJson("copy"), Is.EqualTo(PostTypeOrder.Copy));
		}

		[Test]
        public void PrivacyTest()
        {
			// get test
			Assert.That(Privacy.All.ToString(), Is.EqualTo("all"));
			Assert.That(Privacy.Friends.ToString(), Is.EqualTo("friends"));
			Assert.That(Privacy.FriendsOfFriends.ToString(), Is.EqualTo("friends_of_friends"));
			Assert.That(Privacy.FriendsOfFriendsOnly.ToString(), Is.EqualTo("friends_of_friends_only"));
			Assert.That(Privacy.Nobody.ToString(), Is.EqualTo("nobody"));
			Assert.That(Privacy.OnlyMe.ToString(), Is.EqualTo("only_me"));
			// parse test
			Assert.That(Privacy.FromJson("all"), Is.EqualTo(Privacy.All));
			Assert.That(Privacy.FromJson("friends"), Is.EqualTo(Privacy.Friends));
			Assert.That(Privacy.FromJson("friends_of_friends"), Is.EqualTo(Privacy.FriendsOfFriends));
			Assert.That(Privacy.FromJson("friends_of_friends_only"), Is.EqualTo(Privacy.FriendsOfFriendsOnly));
			Assert.That(Privacy.FromJson("nobody"), Is.EqualTo(Privacy.Nobody));
			Assert.That(Privacy.FromJson("only_me"), Is.EqualTo(Privacy.OnlyMe));
		}

		[Test]
        public void RelativeTypeTest()
        {
			// get test
			Assert.That(RelativeType.Sibling.ToString(), Is.EqualTo("sibling"));
			Assert.That(RelativeType.Parent.ToString(), Is.EqualTo("parent"));
			Assert.That(RelativeType.Child.ToString(), Is.EqualTo("child"));
			Assert.That(RelativeType.Grandparent.ToString(), Is.EqualTo("grandparent"));
			Assert.That(RelativeType.Grandchild.ToString(), Is.EqualTo("grandchild"));
			// parse test
			Assert.That(RelativeType.FromJson("sibling"), Is.EqualTo(RelativeType.Sibling));
			Assert.That(RelativeType.FromJson("parent"), Is.EqualTo(RelativeType.Parent));
			Assert.That(RelativeType.FromJson("child"), Is.EqualTo(RelativeType.Child));
			Assert.That(RelativeType.FromJson("grandparent"), Is.EqualTo(RelativeType.Grandparent));
			Assert.That(RelativeType.FromJson("grandchild"), Is.EqualTo(RelativeType.Grandchild));
		}

		[Test]
        public void ReportTypeTest()
        {
			// get test
			Assert.That(ReportType.Porn.ToString(), Is.EqualTo("porn"));
			Assert.That(ReportType.Spam.ToString(), Is.EqualTo("spam"));
			Assert.That(ReportType.Insult.ToString(), Is.EqualTo("insult"));
			Assert.That(ReportType.Advertisment.ToString(), Is.EqualTo("advertisment"));
			// parse test
			Assert.That(ReportType.FromJson("porn"), Is.EqualTo(ReportType.Porn));
			Assert.That(ReportType.FromJson("spam"), Is.EqualTo(ReportType.Spam));
			Assert.That(ReportType.FromJson("insult"), Is.EqualTo(ReportType.Insult));
			Assert.That(ReportType.FromJson("advertisment"), Is.EqualTo(ReportType.Advertisment));
		}

		[Test]
        public void ServicesTest()
        {
			// get test
			Assert.That(Services.Email.ToString(), Is.EqualTo("email"));
			Assert.That(Services.Phone.ToString(), Is.EqualTo("phone"));
			Assert.That(Services.Twitter.ToString(), Is.EqualTo("twitter"));
			Assert.That(Services.Facebook.ToString(), Is.EqualTo("facebook"));
			Assert.That(Services.Odnoklassniki.ToString(), Is.EqualTo("odnoklassniki"));
			Assert.That(Services.Instagram.ToString(), Is.EqualTo("instagram"));
			Assert.That(Services.Google.ToString(), Is.EqualTo("google"));
			// parse test
			Assert.That(Services.FromJson("email"), Is.EqualTo(Services.Email));
			Assert.That(Services.FromJson("phone"), Is.EqualTo(Services.Phone));
			Assert.That(Services.FromJson("twitter"), Is.EqualTo(Services.Twitter));
			Assert.That(Services.FromJson("facebook"), Is.EqualTo(Services.Facebook));
			Assert.That(Services.FromJson("odnoklassniki"), Is.EqualTo(Services.Odnoklassniki));
			Assert.That(Services.FromJson("instagram"), Is.EqualTo(Services.Instagram));
			Assert.That(Services.FromJson("google"), Is.EqualTo(Services.Google));
		}

		[Test]
        public void UserSectionTest()
        {
			// get test
			Assert.That(UserSection.Friends.ToString(), Is.EqualTo("friends"));
			Assert.That(UserSection.Subscriptions.ToString(), Is.EqualTo("subscriptions"));
			// parse test
			Assert.That(UserSection.FromJson("friends"), Is.EqualTo(UserSection.Friends));
			Assert.That(UserSection.FromJson("subscriptions"), Is.EqualTo(UserSection.Subscriptions));
		}

		[Test]
        public void VideoCatalogItemTypeTest()
        {
			// get test
			Assert.That(VideoCatalogItemType.Video.ToString(), Is.EqualTo("video"));
			Assert.That(VideoCatalogItemType.Album.ToString(), Is.EqualTo("album"));
			// parse test
			Assert.That(VideoCatalogItemType.FromJson("video"), Is.EqualTo(VideoCatalogItemType.Video));
			Assert.That(VideoCatalogItemType.FromJson("album"), Is.EqualTo(VideoCatalogItemType.Album));
		}

		[Test]
        public void VideoCatalogTypeTest()
        {
			// get test
			Assert.That(VideoCatalogType.Channel.ToString(), Is.EqualTo("channel"));
			Assert.That(VideoCatalogType.Category.ToString(), Is.EqualTo("category"));
			// parse test
			Assert.That(VideoCatalogType.FromJson("channel"), Is.EqualTo(VideoCatalogType.Channel));
			Assert.That(VideoCatalogType.FromJson("category"), Is.EqualTo(VideoCatalogType.Category));
		}

		[Test]
        public void WallFilterTest()
        {
			// get test
			Assert.That(WallFilter.Owner.ToString(), Is.EqualTo("owner"));
			Assert.That(WallFilter.Others.ToString(), Is.EqualTo("others"));
			Assert.That(WallFilter.All.ToString(), Is.EqualTo("all"));
			Assert.That(WallFilter.Suggests.ToString(), Is.EqualTo("suggests"));
			Assert.That(WallFilter.Postponed.ToString(), Is.EqualTo("postponed"));
			// parse test
			Assert.That(WallFilter.FromJson("owner"), Is.EqualTo(WallFilter.Owner));
			Assert.That(WallFilter.FromJson("others"), Is.EqualTo(WallFilter.Others));
			Assert.That(WallFilter.FromJson("all"), Is.EqualTo(WallFilter.All));
			Assert.That(WallFilter.FromJson("suggests"), Is.EqualTo(WallFilter.Suggests));
			Assert.That(WallFilter.FromJson("postponed"), Is.EqualTo(WallFilter.Postponed));
		}

	}
}


text:
@interface TLUserHelper : NSObject

@property (nonatomic, strong) TLUser *user;

@property (nonatomic, strong, readonly) NSString *userID;

+ (TLUserHelper *) sharedHelper;

@end


text:
<!doctype html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="./../assets/css/combined.css">
	<link rel="shortcut icon" href="./../favicon.ico" />

	<title>Request - Classes - FuelPHP Documentation</title>

					FuelPHP, a PHP 5.3 Framework
					Documentation

				<form id="google_search">

						<input type="submit" name="search_submit" id="search_submit" value="search" />
						<input type="text" value="" id="search_input" name="search_input" />

				</form>

			table of contents

Request Class

The Request class processes URI requests. It is used by Fuel in index.php to process the users URI request, and you need it to generate requests in an HMVC context.

forge($uri = null, $route = true)

The forge method returns a new request object.

						Static
						Yes

						Parameters

									Param
									Default
									Description

									$uri

null

									The URI being requested. If this parameter is not present, the URI class will be used to detect the URI.

									$route

true

									If true, the URI passed or detected will be processed by the routing class. If no route is present, a 404 will be generated. If you request a non-public URI, set this to false.

						Returns
						Fuel\Core\Request Object

						Example

// create the request object for the admin controller, login method
$request = Request::forge('admin/login');

// note that this only creates the object, it does not execute the request!

execute()

The execute method executes a request and stores the resulting response in the request object to be used later.

						Static
						No

						Parameters
						No

						Returns
						Fuel\Core\Request Object

						Example

// create and execute the request object for the admin controller, login method
$request = Request::forge('admin/login')->execute();

response()

The response method fetches the response object of the executed request.

						Static
						No

						Parameters
						No

						Returns
						Fuel\Core\Response Object

						Example

// execute the request, fetch the response, and display it
$response = Request::forge('admin/login')->execute()->response();
echo $response;

// The Request object contains a __toString() method as an alternative way to fetch the output
$output = Request::forge('admin/login')->execute();
echo $output;

params()

Returns an array of all named parameters in the route that triggered this request.

						Static
						No

						Parameters
						No

						Returns
						array

						Example

// get the list of named parameters
$params = Request::active()->params();

get_method()

Gets the request method.

						Static
						No

						Parameters
						none

						Returns
						Request method

						Example

// Set the request method on a forged request
$method = Request::main()->get_method();

set_method($method)

Sets the request method.

						Static
						No

						Parameters

									Param
									Default
									Description

									$method
									string, required
									The name of the parameter to be returned. This must be exactly the same as defined in the route.

						Returns
						current instance

						Example

// Set the request method on a forged request
$params = Request::forge('some/route')->set_method('POST');

param($param, $default = null)

Returns a specific named parameter in the route that triggered this request, of the default if the parameter is not found.

						Static
						No

						Parameters

									Param
									Default
									Description

									$param
									string, required
									The name of the parameter to be returned. This must be exactly the same as defined in the route.

									$default

null

									value to be returned if the named parameter requested is not defined.

						Returns
						mixed

						Example

// get a specific named parameter called 'name'
$param = Request::active()->param('name', 'none');

The routing section explains how named paramaters can be defined in a route.

parent()

The Request that created this Request.

						Static
						No

						Parameters
						No

						Returns
						Fuel\Core\Request Object or null when it's the main request

						Example

// get the parent of the current active Request
$parent = Request::active()->parent();

children()

The Request objects that were created during this Request.

						Static
						No

						Parameters
						No

						Returns
						Array of Fuel\Core\Request Objects

						Example

// get the Requests that were created during the main Request
$children = Request::main()->children();

show_404($return = false)

The show_404 method will display or return the application's 404 page. If none is configured in your config routes.php, the Fuel default 404 page will be used instead. If the configured 404 route is incorrect, an error will be thrown.

This function is deprecated in 1.1 in favour of HttpNotFoundException.

						Static
						Yes

						Parameters

									Param
									Default
									Description

									$return

false

									If false, the result will be echoed out. If true, it will be returned.

						Returns
						If $return is false, the method will exit. If not, it will return the html of the 404 page configured.

						Example

Request::show_404();

main()

The main method returns the main Request instance (the one created by the initial
					page request).

						Static
						Yes

						Parameters
						No

						Returns
						Fuel\Core\Request Object, or false if no main request instance exists.

						Example

$main = Request::main();

This is the first executed Request instance, not necessarily the root parent of the
					current Request. That might be the case for example if the main Request 404s and you create a new
					Request after that (which is what happens in the _404_ route).

active()

The active method returns the currently active Request instance.

						Static
						Yes

						Parameters
						No

						Returns
						Fuel\Core\Request Object, or false if no active request instance exists.

						Example

$active = Request::active();

add_path($path, $prefix = false)

The add_path method allows you to add a search path to the current request instance. The search paths are used by Finder::search() to locate files within your application.

						Static
						No

						Parameters

									Param
									Default
									Description

									$path
									required
									Path to be added to the list of Request local search paths

									$prefix

false

									If false, the path will be appended to the search path. If true, it will be prepended.

						Returns
						void

						Example

// add the applications myfiles folder to the search path of the active request instance
Request::active()->add_path(APPPATH.'myfiles'.DS);

get_paths()

The get_paths method returns the defined list of search paths.

						Static
						No

						Parameters
						No

						Returns
						void

						Example

// get the defined search paths of the active request instance
$paths = Request::active()->get_paths();

				© FuelPHP Development Team 2010-2012 - FuelPHP is released under the MIT license.


text:
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace Core2D.Views.Docking.Views;

public class DashboardMenuView : UserControl
{
    public DashboardMenuView()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }
}


text:
package gov.nih.nci.cacis.transform;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * @author bpickeral
 * @since Sep 2, 2011
 */
public class XSLTTransformer {

    /**
     * Transformer using XSLT.
     */
    private final Transformer transformer;

    /**
     * Constructor
     *
     * @param transformer xslt transformer
     */
    public XSLTTransformer(Transformer transformer) {
        this.transformer = transformer;
    }

    /**
     * Transform XML to RDF
     *
     * @param params the set of parameters to pass to the transformation, may be null
     * @param in XML input stream
     * @param out XML output stream
     * @throws TransformerException exception
     */
    public void transform(Map<String, String> params, InputStream in, OutputStream out) throws TransformerException {
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }
        transformer.transform(new StreamSource(in), new StreamResult(out));
    }
}


text:
package armmysql_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mysql/armmysql"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/mysql/resource-manager/Microsoft.DBforMySQL/stable/2017-12-01/examples/CheckNameAvailability.json
func ExampleCheckNameAvailabilityClient_Execute() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armmysql.NewCheckNameAvailabilityClient("ffffffff-ffff-ffff-ffff-ffffffffffff", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Execute(ctx,
		armmysql.NameAvailabilityRequest{
			Name: to.Ptr("name1"),
			Type: to.Ptr("Microsoft.DBforMySQL"),
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}


text:
import {indentCommit} from '../util/indent-commit';

// Generic
import {Changelog} from '../updaters/changelog';

// RubyYoshi
import {VersionRB} from '../updaters/ruby/version-rb';
import {BaseStrategy, BuildUpdatesOptions, BaseStrategyOptions} from './base';
import {ConventionalCommit, Commit} from '../commit';
import {Update} from '../update';
import {readFileSync} from 'fs';
import {resolve} from 'path';
import {Release} from '../release';
import {TagName} from '../util/tag-name';
import {Version} from '../version';

const CHANGELOG_SECTIONS = [
  {type: 'feat', section: 'Features'},
  {type: 'fix', section: 'Bug Fixes'},
  {type: 'perf', section: 'Performance Improvements'},
  {type: 'revert', section: 'Reverts'},
  {type: 'docs', section: 'Documentation'},
  {type: 'style', section: 'Styles', hidden: true},
  {type: 'chore', section: 'Miscellaneous Chores', hidden: true},
  {type: 'refactor', section: 'Code Refactoring', hidden: true},
  {type: 'test', section: 'Tests', hidden: true},
  {type: 'build', section: 'Build System', hidden: true},
  {type: 'ci', section: 'Continuous Integration', hidden: true},
];

export class RubyYoshi extends BaseStrategy {
  readonly versionFile: string;
  constructor(options: BaseStrategyOptions) {
    super({
      ...options,
      changelogSections: CHANGELOG_SECTIONS,
      commitPartial: readFileSync(
        resolve(__dirname, '../../../templates/commit.hbs'),
        'utf8'
      ),
      headerPartial: readFileSync(
        resolve(__dirname, '../../../templates/header.hbs'),
        'utf8'
      ),
      mainTemplate: readFileSync(
        resolve(__dirname, '../../../templates/template.hbs'),
        'utf8'
      ),
      tagSeparator: '/',
    });
    this.versionFile = options.versionFile ?? '';
  }

  protected async buildUpdates(
    options: BuildUpdatesOptions
  ): Promise<Update[]> {
    const updates: Update[] = [];
    const version = options.newVersion;

    updates.push({
      path: this.addPath(this.changelogPath),
      createIfMissing: true,
      updater: new Changelog({
        version,
        changelogEntry: options.changelogEntry,
      }),
    });

    const versionFile: string = this.versionFile
      ? this.versionFile
      : `lib/${(this.component || '').replace(/-/g, '/')}/version.rb`;
    updates.push({
      path: this.addPath(versionFile),
      createIfMissing: false,
      updater: new VersionRB({
        version,
      }),
    });
    return updates;
  }

  protected async postProcessCommits(
    commits: ConventionalCommit[]
  ): Promise<ConventionalCommit[]> {
    commits.forEach(commit => {
      commit.message = indentCommit(commit);
    });
    return commits;
  }

  protected async buildReleaseNotes(
    conventionalCommits: ConventionalCommit[],
    newVersion: Version,
    newVersionTag: TagName,
    latestRelease?: Release,
    commits?: Commit[]
  ): Promise<string> {
    const releaseNotes = await super.buildReleaseNotes(
      conventionalCommits,
      newVersion,
      newVersionTag,
      latestRelease,
      commits
    );
    return (
      releaseNotes
        // Remove links in version title line and standardize on h3
        .replace(/^###? \[([\d.]+)\]\([^)]*\)/gm, '### $1')
        // Remove bolded scope from change lines
        .replace(/^\* \*\*[\w-]+:\*\* /gm, '* ')
        // Remove PR and commit links from pull request title suffixes
        .replace(/(\(\[(\w+)\]\(https:\/\/github\.com\/[^)]*\)\))+\s*$/gm, '')
        // Standardize on h4 for change type subheaders
        .replace(/^### (Features|Bug Fixes|Documentation)$/gm, '#### $1')
        // Collapse 2 or more blank lines
        .replace(/\n{3,}/g, '\n\n')
    );
  }
}


text:
@interface SKStackManager () <NSURLConnectionDelegate>

@property (strong, nonatomic) NSMutableData *URLData;
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSArray *stacks;

@end

@implementation SKStackManager

@synthesize currentStack=_currentStack;

+ (SKStackManager *)sharedStackManager
{
    static SKStackManager *SharedStackManager = nil;
    if (!SharedStackManager) {
        SharedStackManager = [[SKStackManager alloc] init];
    }
    return SharedStackManager;
}

+ (NSString *)hostString
{
    return [SKStackManager sharedStackManager].currentStack.URLString;
}

- (void)reloadStacks
{
    [self.connection cancel];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://stackotron-discover.herokuapp.com/v1/apps/%@/stacks", self.appId]]];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (NSString *)userDefaultsStorageKey
{
    return [NSString stringWithFormat:@"Stacks-CurrentStack-%@", self.appId];
}

- (void)setCurrentStack:(SKStack *)currentStack
{
    _currentStack = currentStack;
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:currentStack] forKey:[self userDefaultsStorageKey]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (SKStack *)currentStack
{
    // TODO: We should have some sort of logic to load a default stack, if none is set
    if (!_currentStack) {
        _currentStack = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:[self userDefaultsStorageKey]]];
    }
    return _currentStack;
}

#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.URLData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.URLData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error = nil;
    NSArray *stackDictionaryArray = [NSJSONSerialization JSONObjectWithData:self.URLData options:0 error:&error];
    if (error) {
        [self.delegate stackManager:self didError:error];
    } else {
        NSMutableArray *stacks = [[NSMutableArray alloc] init];
        for (NSDictionary *stackDictionary in stackDictionaryArray) {
            SKStack *stack = [[SKStack alloc] initWithJSONDictionary:stackDictionary];
            [stacks addObject:stack];
        }
        self.stacks = [NSArray arrayWithArray:stacks];
        [self.delegate stackManager:self didLoadStacks:self.stacks];
    }
}

@end


text:
namespace kaldi {
namespace nnet2 {

int32 IndexOfSoftmaxLayer(const Nnet &nnet) {
  int32 index = -1, nc = nnet.NumComponents();
  for (int32 c = 0; c < nc; c++) {
    const Component *component = &(nnet.GetComponent(c));
    if (dynamic_cast<const SoftmaxComponent *>(component) != NULL) {
      if (index != -1)
        return -1;  // >1 softmax components.
      else
        index = c;
    }
  }
  return index;
}

void InsertComponents(
    const Nnet &src_nnet,
    int32 c_to_insert,  // component-index before which to insert.
    Nnet *dest_nnet) {
  KALDI_ASSERT(c_to_insert >= 0 && c_to_insert <= dest_nnet->NumComponents());
  int32 c_tot = dest_nnet->NumComponents() + src_nnet.NumComponents();
  std::vector<Component *> components(c_tot);
  for (int32 c = 0; c < c_to_insert; c++)
    components[c] = dest_nnet->GetComponent(c).Copy();
  for (int32 c = 0; c < src_nnet.NumComponents(); c++)
    components[c + c_to_insert] = src_nnet.GetComponent(c).Copy();
  for (int32 c = c_to_insert; c < dest_nnet->NumComponents(); c++)
    components[c + src_nnet.NumComponents()] =
        dest_nnet->GetComponent(c).Copy();
  // Re-initialize "dest_nnet" from the resulting list of components.

  // The Init method will take ownership of the pointers in the vector:
  dest_nnet->Init(&components);
}

void ReplaceLastComponents(const Nnet &src_nnet, int32 num_to_remove,
                           Nnet *dest_nnet) {
  KALDI_ASSERT(num_to_remove >= 0 &&
               num_to_remove <= dest_nnet->NumComponents());
  int32 c_orig = dest_nnet->NumComponents() - num_to_remove;

  std::vector<Component *> components;
  for (int32 c = 0; c < c_orig; c++)
    components.push_back(dest_nnet->GetComponent(c).Copy());
  for (int32 c = 0; c < src_nnet.NumComponents(); c++)
    components.push_back(src_nnet.GetComponent(c).Copy());

  // Re-initialize "dest_nnet" from the resulting list of components.
  // The Init method will take ownership of the pointers in the vector:
  dest_nnet->Init(&components);
}

}  // namespace nnet2
}  // namespace kaldi


text:
Collection of various examples/utilities for Spark ROOT.

## Metrics Listener
Simple Metrics Listener that extends SparkListener. All the jobs are collected in a buffer and dumped into json at the application's end.
Directory/Filename of the metrics output are configurable (see below the conf options)

```
source for MetricsListener is located here: src/main/scala/org/dianahep/sparkrootapplications/metrics
sources for BenchMarksApp are here: src/main/scala/org/dianahep/sparkrootapplications/benchmarks

./spark-submit  --packages org.diana-hep:spark-root_2.11:0.1.7,org.diana-hep:histogrammar-sparksql_2.11:1.0.3,org.json4s:json4s-native_2.11:3.2.11  --class "org.dianahep.sparkrootapplications.benchmarks.AODPublicBenchmarkApp"  --conf spark.extraListeners="org.dianahep.sparkrootapplications.metrics.MetricsListener" --conf spark.executorEnv.pathToMetrics=/Users/vk/software/diana-hep/intel/metrics --conf spark.executorEnv.metricsFileName=test.json /Users/vk/software/diana-hep/spark-root-applications/target/scala-2.11/spark-root-applications_2.11-0.0.1.jar  file:/Users/vk/software/diana-hep/test_data/0029E804-C77C-E011-BA94-00215E22239A.root  /Users/vk/software/diana-hep/test_data/benchmarks/test 1 5
```

## Example Applications
- ReductionExample App
- AODPublicExample App
- Bacon/Higgs Example Apps


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CompilerServer
{
    /// <summary>
    /// This class is responsible for processing a request from a client of the compiler server.
    /// </summary>
    internal sealed class ClientConnectionHandler
    {
        internal ICompilerServerHost CompilerServerHost { get; }

        internal ClientConnectionHandler(ICompilerServerHost compilerServerHost)
        {
            CompilerServerHost = compilerServerHost;
        }

        /// <summary>
        /// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped
        /// in a <see cref="CompletionReason.RequestError"/>
        /// </summary>
        internal async Task<CompletionData> ProcessAsync(
            Task<IClientConnection> clientConnectionTask,
            bool allowCompilationRequests = true,
            CancellationToken cancellationToken = default)
        {
            try
            {
                return await ProcessCore().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                CompilerServerLogger.LogException(ex, $"Error processing request for client");
                return CompletionData.RequestError;
            }

            async Task<CompletionData> ProcessCore()
            {
                using var clientConnection = await clientConnectionTask.ConfigureAwait(false);
                var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false);

                if (request.ProtocolVersion != BuildProtocolConstants.ProtocolVersion)
                {
                    return await WriteBuildResponseAsync(
                        clientConnection,
                        new MismatchedVersionBuildResponse(),
                        CompletionData.RequestError,
                        cancellationToken).ConfigureAwait(false);
                }

                if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase))
                {
                    return await WriteBuildResponseAsync(
                        clientConnection,
                        new IncorrectHashBuildResponse(),
                        CompletionData.RequestError,
                        cancellationToken).ConfigureAwait(false);
                }

                if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown)
                {
                    return await WriteBuildResponseAsync(
                        clientConnection,
                        new ShutdownBuildResponse(Process.GetCurrentProcess().Id),
                        new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true),
                        cancellationToken).ConfigureAwait(false);
                }

                if (!allowCompilationRequests)
                {
                    return await WriteBuildResponseAsync(
                        clientConnection,
                        new RejectedBuildResponse("Compilation not allowed at this time"),
                        CompletionData.RequestCompleted,
                        cancellationToken).ConfigureAwait(false);
                }

                if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable())
                {
                    return await WriteBuildResponseAsync(
                        clientConnection,
                        new RejectedBuildResponse("Not enough resources to accept connection"),
                        CompletionData.RequestError,
                        cancellationToken).ConfigureAwait(false);
                }

                return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false);
            }
        }

        private static async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken)
        {
            var message = response switch
            {
                RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {clientConnection.LoggingIdentifier}",
                _ => $"Writing {response.Type} response for {clientConnection.LoggingIdentifier}"
            };
            CompilerServerLogger.Log(message);
            await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false);
            return completionData;
        }

        private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken)
        {
            // Need to wait for the compilation and client disconnection in parallel. If the client
            // suddenly disconnects we need to cancel the compilation that is occurring. It could be the
            // client hit Ctrl-C due to a run away analyzer.
            var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token);
            await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false);

            try
            {
                if (compilationTask.IsCompleted)
                {
                    BuildResponse response;
                    CompletionData completionData;
                    try
                    {
                        response = await compilationTask.ConfigureAwait(false);
                        completionData = response switch
                        {
                            // Once there is an analyzer inconsistency the assembly load space is polluted. The
                            // request is an error.
                            AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError,
                            _ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request))
                        };
                    }
                    catch (Exception ex)
                    {
                        // The compilation task should never throw. If it does we need to assume that the compiler is
                        // in a bad state and need to issue a RequestError
                        CompilerServerLogger.LogException(ex, $"Exception running compilation for {clientConnection.LoggingIdentifier}");
                        response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}");
                        completionData = CompletionData.RequestError;
                    }

                    return await WriteBuildResponseAsync(
                        clientConnection,
                        response,
                        completionData,
                        cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    return CompletionData.RequestError;
                }
            }
            finally
            {
                buildCancellationTokenSource.Cancel();
            }

            static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken)
            {
                Func<BuildResponse> func = () =>
                {
                    var request = BuildProtocolUtil.GetRunRequest(buildRequest);
                    var response = compilerServerHost.RunCompilation(request, cancellationToken);
                    return response;
                };

                var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning);
                task.Start();
                return task;
            }
        }

        /// <summary>
        /// Check the request arguments for a new keep alive time. If one is present,
        /// set the server timer to the new time.
        /// </summary>
        private static TimeSpan? CheckForNewKeepAlive(BuildRequest request)
        {
            TimeSpan? timeout = null;
            foreach (var arg in request.Arguments)
            {
                if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive)
                {
                    int result;
                    // If the value is not a valid integer for any reason,
                    // ignore it and continue with the current timeout. The client
                    // is responsible for validating the argument.
                    if (int.TryParse(arg.Value, out result))
                    {
                        // Keep alive times are specified in seconds
                        timeout = TimeSpan.FromSeconds(result);
                    }
                }
            }

            return timeout;
        }
    }
}


text:
//
//  DDMTTSessionEntity.h
//  IOSDuoduo
//
//  Created by 独嘉 on 14-6-5.
//  Copyright (c) 2014年 dujia. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "IMBaseDefine.pb.h"
@class MTTUserEntity,MTTGroupEntity;
//typedef enum
//{
//    SESSIONTYPE_SINGLE = 1,          //单个用户会话
//    SESSIONTYPE_TEMP_GROUP = 2,           //群会话
//    SESSIONTYPE_GROUP =3
//}SessionType;

@interface MTTSessionEntity : NSObject
@property (nonatomic,retain)NSString* sessionID;
@property (nonatomic,assign)SessionType sessionType;
@property (nonatomic,readonly)NSString* name;
@property(assign)NSInteger unReadMsgCount;
@property (assign)NSUInteger timeInterval;
@property(nonatomic,strong,readonly)NSString* orginId;
@property(assign)BOOL isShield;
@property(assign)BOOL isFixedTop;
@property(strong)NSString *lastMsg;
@property(assign)NSInteger lastMsgID;
@property(strong)NSString *avatar;
-(NSArray*)sessionUsers;
/**
 *  创建一个session,只需赋值sessionID和Type即可
 *
 *  @param sessionID 会话ID,群组传入groupid,p2p传入对方的userid
 *  @param type      会话的类型
 *
 *  @return
 */
- (id)initWithSessionID:(NSString*)sessionID type:(SessionType)type;
- (id)initWithSessionID:(NSString*)sessionID SessionName:(NSString *)name type:(SessionType)type;
- (id)initWithSessionIDByUser:(MTTUserEntity*)user;
- (id)initWithSessionIDByGroup:(MTTGroupEntity*)group;
- (void)updateUpdateTime:(NSUInteger)date;
-(NSString *)getSessionGroupID;
-(void)setSessionName:(NSString *)theName;
-(BOOL)isGroup;
-(id)dicToGroup:(NSDictionary *)dic;
-(void)setSessionUser:(NSArray *)array;
@end


text:
import * as gulp from 'gulp';
import stripDebug = require('gulp-strip-debug');

// Example taken from https://www.npmjs.com/package/gulp-strip-debug
gulp.task('default', function () {
	return gulp.src('src/app.js')
		.pipe(stripDebug())
		.pipe(gulp.dest('dist'));
});