Based on https://github.com/NanoHttpd/nanohttpd/issues/232#issuecomment-180254564
334436
private static void __serveStream(HttpServletRequest request, HttpServletResponse response, InputStream is, String path, String mime, int bufferSize, long lastModified) throws IOException {
        Map<String, String> reqHeaders = __getRequestHeaderMap(request);

        String queryString = request.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        // Calculate etag
        String etag = Integer.toHexString((path + lastModified + queryString + is.available()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;

        String range = reqHeaders.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');

                if (minus > 0) {
                    startFrom = __parseLong(range.substring(0, minus), 0);
                    endAt = __parseLong(range.substring(minus + 1), -1);
                }
            }
        }

        response.addHeader("Accept-Ranges", "bytes");

        // Change return code and add Content-Range header when skipping is requested
        long fileLen = is.available();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                response.setContentType("text/plain");
                response.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                response.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }

                long newLen = endAt - startFrom + 1;

                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;

                is.skip(startFrom);

                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + dataLen);
                response.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                response.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(reqHeaders.get("if-none-match"))) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setContentType(mime);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + fileLen);
                response.addHeader("ETag", etag);
            }
        }

    }
833998
function fetchCollectionAttributeHTTPInput( $collection, $collectionAttribute, $http, $base, $contentObjectAttribute )
    {
        $multioptionValue = $http->postVariable( $base . "_data_multioption_value_" . $contentObjectAttribute->attribute( "id" ) );
        $collectionAttribute->setAttribute( 'data_int', $multioptionValue );
        return true;
    }
368964
function getCommentsList(comments) {
  if (!comments.body || !comments.headers) return;

  let pageInfo = getPage(comments.headers.link);
  let pageList = [];

  comments.body.forEach((item) => {
    pageList.push(getComments(item));
  });

  return {
    page: pageInfo,
    list: pageList
  }
}
641440
function eventTargetPatch(_global, api) {
    var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
    var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'
        .split(',');
    var EVENT_TARGET = 'EventTarget';
    var apis = [];
    var isWtf = _global['wtf'];
    var WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
    if (isWtf) {
        // Workaround for: https://github.com/google/tracing-framework/issues/555
        apis = WTF_ISSUE_555_ARRAY.map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);
    }
    else if (_global[EVENT_TARGET]) {
        apis.push(EVENT_TARGET);
    }
    else {
        // Note: EventTarget is not available in all browsers,
        // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
        apis = NO_EVENT_TARGET;
    }
    var isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
    var isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
    var ieOrEdge = isIEOrEdge();
    var ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
    var FUNCTION_WRAPPER = '[object FunctionWrapper]';
    var BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
    //  predefine all __zone_symbol__ + eventName + true/false string
    for (var i = 0; i < eventNames.length; i++) {
        var eventName = eventNames[i];
        var falseEventName = eventName + FALSE_STR;
        var trueEventName = eventName + TRUE_STR;
        var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
        var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
        zoneSymbolEventNames[eventName] = {};
        zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
        zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
    }
    //  predefine all task.source string
    for (var i = 0; i < WTF_ISSUE_555.length; i++) {
        var target = WTF_ISSUE_555_ARRAY[i];
        var targets = globalSources[target] = {};
        for (var j = 0; j < eventNames.length; j++) {
            var eventName = eventNames[j];
            targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
        }
    }
    var checkIEAndCrossContext = function (nativeDelegate, delegate, target, args) {
        if (!isDisableIECheck && ieOrEdge) {
            if (isEnableCrossContextCheck) {
                try {
                    var testString = delegate.toString();
                    if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
                        nativeDelegate.apply(target, args);
                        return false;
                    }
                }
                catch (error) {
                    nativeDelegate.apply(target, args);
                    return false;
                }
            }
            else {
                var testString = delegate.toString();
                if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
                    nativeDelegate.apply(target, args);
                    return false;
                }
            }
        }
        else if (isEnableCrossContextCheck) {
            try {
                delegate.toString();
            }
            catch (error) {
                nativeDelegate.apply(target, args);
                return false;
            }
        }
        return true;
    };
    var apiTypes = [];
    for (var i = 0; i < apis.length; i++) {
        var type = _global[apis[i]];
        apiTypes.push(type && type.prototype);
    }
    patchEventTarget(_global, apiTypes, { validateHandler: checkIEAndCrossContext });
    api.patchEventTarget = patchEventTarget;
    return true;
}
1287125
def ajax_required(func):
    # taken from djangosnippets.org
    
    def wrap(request, *args, **kwargs):
        if not request.is_ajax():
            return HttpResponseBadRequest
        return func(request, *args, **kwargs)
    wrap.__doc__ = func.__doc__
    wrap.__name__ = func.__name__
    return wrap
190499
function UTF8ArrToStr (aBytes) {

  var sView = "";

  for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
    nPart = aBytes[nIdx];
    sView += String.fromCharCode(
      nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
        /* (nPart - 252 << 32) is not possible in ECMAScript! So...: */
        (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
      : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
        (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
      : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
        (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
      : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
        (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
      : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
        (nPart - 192 << 6) + aBytes[++nIdx] - 128
      : /* nPart < 127 ? */ /* one byte */
        nPart
    );
  }

  return sView;

}
752532
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $actionRemoveSelected = false;
        if ( $http->hasPostVariable( 'CustomActionButton' ) )
        {
            $customActionArray = $http->postVariable( 'CustomActionButton' );

            if ( isset( $customActionArray[$contentObjectAttribute->attribute( "id" ) . '_remove_selected'] ) )
                if ( $customActionArray[$contentObjectAttribute->attribute( "id" ) . '_remove_selected'] == 'Remove selected' )
                    $actionRemoveSelected = true;
        }

        if ( $http->hasPostVariable( $base . "_data_author_id_" . $contentObjectAttribute->attribute( "id" ) ) )
        {
            $classAttribute = $contentObjectAttribute->contentClassAttribute();
            $idList = $http->postVariable( $base . "_data_author_id_" . $contentObjectAttribute->attribute( "id" ) );
            $nameList = $http->postVariable( $base . "_data_author_name_" . $contentObjectAttribute->attribute( "id" ) );
            $emailList = $http->postVariable( $base . "_data_author_email_" . $contentObjectAttribute->attribute( "id" ) );

            if ( $http->hasPostVariable( $base . "_data_author_remove_" . $contentObjectAttribute->attribute( "id" ) ) )
                $removeList = $http->postVariable( $base . "_data_author_remove_" . $contentObjectAttribute->attribute( "id" ) );
            else
                $removeList = array();

            if ( $contentObjectAttribute->validateIsRequired() )
            {
                if ( trim( $nameList[0] ) == "" )
                {
                    $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                         'At least one author is required.' ) );
                    return eZInputValidator::STATE_INVALID;
                }
            }
            if ( trim( $nameList[0] ) != "" )
            {
                for ( $i=0;$i<count( $idList );$i++ )
                {
                    if ( $actionRemoveSelected )
                        if ( in_array( $idList[$i], $removeList ) )
                            continue;

                    $name =  $nameList[$i];
                    $email =  $emailList[$i];
                    if ( trim( $name )== "" )
                    {
                        $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                             'The author name must be provided.' ) );
                        return eZInputValidator::STATE_INVALID;

                    }
                    $isValidate =  eZMail::validate( $email );
                    if ( ! $isValidate )
                    {
                        $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                             'The email address is not valid.' ) );
                        return eZInputValidator::STATE_INVALID;
                    }
                }
            }
        }
        else
        {
            if ( $contentObjectAttribute->validateIsRequired() )
            {
                $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                     'At least one author is required.' ) );
                return eZInputValidator::STATE_INVALID;
            }
        }
        return eZInputValidator::STATE_ACCEPTED;
    }
108516
def comment(request, template="generic/comments.html", extra_context=None):
    
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
    form = form_class(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)
974432
function filterJsDocComments(jsDocComments) {
  const swaggerJsDocComments = [];

  for (let i = 0; i < jsDocComments.length; i += 1) {
    const jsDocComment = jsDocComments[i];
    for (let j = 0; j < jsDocComment.tags.length; j += 1) {
      const tag = jsDocComment.tags[j];
      if (tag.title === 'swagger') {
        swaggerJsDocComments.push(jsYaml.safeLoad(tag.description));
      }
    }
  }

  return swaggerJsDocComments;
}
153585
function jsonp(req) {
    var sUrl = req.url,
        inData = req.data,
        callback = req.callback;
    if (!sUrl || typeof sUrl != 'string') throw new Error('invalid URL');
    if (inData && (typeof inData === 'undefined' ? 'undefined' : _typeof(inData)) != 'object') throw new Error('invalid input argument (data)');
    if (typeof callback != 'function') throw new Error('input argument (callback) should be a function');

    var id = newJsonPid_();
    if (sUrl.indexOf('?') > 0) sUrl += '&';else sUrl += '?';
    sUrl += 'callback=TRIGGER__%5B' + id + '%5D'; // encodeURIComponent('[' + id + ']')

    if (inData) {
      Object.keys(inData).forEach(function (sKey) {
        var item = inData[sKey];
        sUrl += '&' + sKey + '=' + encodeURIComponent(item + '');
      });
    }

    var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.async = 'async';
    if (req.scriptCharset) script.charset = req.scriptCharset;
    script.src = sUrl;
    script.onload = script.onreadystatechange = function () {
      if (!script.readyState || /loaded|complete/.test(script.readyState)) {
        script.onload = script.onreadystatechange = null; // handle memory leak in IE
        if (head && script.parentNode) // remove the script node
          head.removeChild(script);

        script = undefined; // dereference the script
        setTimeout(function () {
          var fn = window.TRIGGER__[id];
          if (fn) {
            delete window.TRIGGER__[id];
            if (req.notifyError) callback(null); // null means failed, fn not removed in TRIGGER__[id]() yet
          }
        }, 0);
      }
    };
    head.insertBefore(script, head.firstChild);

    window.TRIGGER__[id] = function (json) {
      var fn = window.TRIGGER__[id];
      if (fn) {
        delete window.TRIGGER__[id]; // unregist callback: TRIGGER__[xxx]
        callback(json);
      }
    };
  }
1247250
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $count = 0;
        $classAttribute = $contentObjectAttribute->contentClassAttribute();
        if ( $http->hasPostVariable( $base . "_data_option_id_" . $contentObjectAttribute->attribute( "id" ) ) )
        {
            $idList = $http->postVariable( $base . "_data_option_id_" . $contentObjectAttribute->attribute( "id" ) );
            $valueList = $http->postVariable( $base . "_data_option_value_" . $contentObjectAttribute->attribute( "id" ) );
            $dataName = $http->postVariable( $base . "_data_option_name_" . $contentObjectAttribute->attribute( "id" ) );

            if ( $http->hasPostVariable( $base . "_data_option_additional_price_" . $contentObjectAttribute->attribute( "id" ) ) )
                $optionAdditionalPriceList = $http->postVariable( $base . "_data_option_additional_price_" . $contentObjectAttribute->attribute( "id" ) );
            else
                $optionAdditionalPriceList = array();

            for ( $i = 0; $i < count( $valueList ); ++$i )
                if ( trim( $valueList[$i] ) <> '' )
                {
                    ++$count;
                    break;
                }
            if ( $contentObjectAttribute->validateIsRequired() and trim( $dataName ) == '' )
            {
                $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                     'NAME is required.' ) );
                return eZInputValidator::STATE_INVALID;
            }
            if ( $count != 0 )
            {
                for ( $i=0;$i<count( $idList );$i++ )
                {
                    $value =  $valueList[$i];
                    if ( trim( $value )== "" )
                    {
                        $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                             'The option value must be provided.' ) );
                        return eZInputValidator::STATE_INVALID;
                    }
                    if ( isset( $optionAdditionalPriceList[$i] ) &&
                         strlen( $optionAdditionalPriceList[$i] ) &&
                         !preg_match( "#^[-|+]?[0-9]+(\.){0,1}[0-9]{0,2}$#", $optionAdditionalPriceList[$i] ) )
                    {
                        $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                             'The Additional price value is not valid.' ) );
                        return eZInputValidator::STATE_INVALID;
                    }
                }
            }
        }
        if ( $contentObjectAttribute->validateIsRequired() and
             !$classAttribute->attribute( 'is_information_collector' ) )
        {
            if ( $count == 0 )
            {
                $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                     'At least one option is required.' ) );
                return eZInputValidator::STATE_INVALID;
            }
        }
        return eZInputValidator::STATE_ACCEPTED;
    }
1104079
function makeHttpRequest(next) {
  var start = Date.now();

  request({
    url: 'http://localhost:1337/upper',
    method: 'POST',
    headers: {
      'x-to-reverse': 'hi'
    },
    qs: {
      page: 13
    },
    body: 'goodbye-world'
  }, function(err, data, body) {
    var time = Date.now() - start;

    var filteredHeaders = _.pick(data.headers, 'x-reversed');
    console.log('FROM REQUEST');
    console.log('  status :', data.statusCode);
    console.log('  headers:', JSON.stringify(filteredHeaders));
    console.log('  body   :', body);
    console.log('  time   :', time);

    common.verify(function() {
      filteredHeaders.should.eql({ 'x-reversed': 'ih' });
      JSON.parse(body).should.eql({ data: 'GOODBYE-WORLD' });
      common.shouldBeDynamicallyTimed(time);
    });

    console.log();

    next();
  });
}
1091618
function fetchObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $enabledName = $base . '_ezcomcomments_enabled_' . $contentObjectAttribute->attribute( 'id' );
        $shownName = $base . '_ezcomcomments_shown_' . $contentObjectAttribute->attribute( 'id' );
        $enabledValue = -1;
        $shownValue = -1;
        if ( $http->hasPostVariable( $enabledName ) )
        {
            $enabledValue = 1;
        }
        if ( $http->hasPostVariable( $shownName ) )
        {
            $shownValue = 1;
        }
        $contentObjectAttribute->setAttribute( 'data_float', $shownValue );
        $contentObjectAttribute->setAttribute( 'data_int', $enabledValue );
        return true;
    }
181844
function pGetUrl(url, headers){
    //console.log(`\r\n发起远程请求(${Date()})：${url}\r\n`);
    if(!headers){
        headers = {};
    }
    headers['User-Agent'] = 'Request-Promise';
    return rp({
        uri: url,
        headers: headers,
        json: true // Automatically parses the JSON string in the response
    });
}
13681
function comment() {
    var ret = this.seq(
        this.stringf(";"),
        this.manyf(this.choicef(WSP, VCHAR)),
        CRLF);
    return new ast.Comment(ret[2]);
}
68750
function analyseComment(comment, callback) {
  var reg = /(@(require|async|require\.async)\s+)('[^']+'|"[^"]+"|[^\s;!@#%^&*()]+)/g;
  callback = callback || function(m, prefix, type, value) {
    type = type === 'require' ? type : 'async';

    return prefix + map[type].wrap(value);
  };

  return comment.replace(reg, callback).replace(/(?:@|#)\s+sourceMappingURL=([^\s]+)/g, function(_, value) {
    return '# sourceMappingURL=' + map.sourceMap.wrap(value);
  });
}
537049
function rants({
	sort = 'algo',
	limit = 50,
	skip = 0
} = {}) {
	const url = `${API}/devrant/rants`;
	const params = {
		app: 3,
		sort, limit, skip
	};

	return http
		.GET(url, params)
		.then(data => data.rants);
}