text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/util/packed/Packed8ThreeBlocks.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneUtilPackedPacked8ThreeBlocks")
#ifdef RESTRICT_OrgApacheLuceneUtilPackedPacked8ThreeBlocks
#define INCLUDE_ALL_OrgApacheLuceneUtilPackedPacked8ThreeBlocks 0
#else
#define INCLUDE_ALL_OrgApacheLuceneUtilPackedPacked8ThreeBlocks 1
#endif
#undef RESTRICT_OrgApacheLuceneUtilPackedPacked8ThreeBlocks

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneUtilPackedPacked8ThreeBlocks_) && (INCLUDE_ALL_OrgApacheLuceneUtilPackedPacked8ThreeBlocks || defined(INCLUDE_OrgApacheLuceneUtilPackedPacked8ThreeBlocks))
#define OrgApacheLuceneUtilPackedPacked8ThreeBlocks_

#define RESTRICT_OrgApacheLuceneUtilPackedPackedInts 1
#define INCLUDE_OrgApacheLuceneUtilPackedPackedInts_MutableImpl 1
#include "org/apache/lucene/util/packed/PackedInts.h"

@class IOSByteArray;
@class IOSLongArray;
@class OrgApacheLuceneStoreDataInput;

/*!
 @brief Packs integers into 3 bytes (24 bits per value).
 */
@interface OrgApacheLuceneUtilPackedPacked8ThreeBlocks : OrgApacheLuceneUtilPackedPackedInts_MutableImpl {
 @public
  IOSByteArray *blocks_;
}
@property (readonly, class) jint MAX_SIZE NS_SWIFT_NAME(MAX_SIZE);

#pragma mark Public

- (void)clear;

- (void)fillWithInt:(jint)fromIndex
            withInt:(jint)toIndex
           withLong:(jlong)val;

- (jlong)getWithInt:(jint)index;

- (jint)getWithInt:(jint)index
     withLongArray:(IOSLongArray *)arr
           withInt:(jint)off
           withInt:(jint)len;

- (jlong)ramBytesUsed;

- (void)setWithInt:(jint)index
          withLong:(jlong)value;

- (jint)setWithInt:(jint)index
     withLongArray:(IOSLongArray *)arr
           withInt:(jint)off
           withInt:(jint)len;

- (NSString *)description;

#pragma mark Package-Private

- (instancetype __nonnull)initPackagePrivateWithInt:(jint)valueCount;

- (instancetype __nonnull)initPackagePrivateWithInt:(jint)packedIntsVersion
                  withOrgApacheLuceneStoreDataInput:(OrgApacheLuceneStoreDataInput *)inArg
                                            withInt:(jint)valueCount;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)initWithInt:(jint)arg0
                              withInt:(jint)arg1 NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneUtilPackedPacked8ThreeBlocks)

J2OBJC_FIELD_SETTER(OrgApacheLuceneUtilPackedPacked8ThreeBlocks, blocks_, IOSByteArray *)

inline jint OrgApacheLuceneUtilPackedPacked8ThreeBlocks_get_MAX_SIZE(void);
#define OrgApacheLuceneUtilPackedPacked8ThreeBlocks_MAX_SIZE 715827882
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheLuceneUtilPackedPacked8ThreeBlocks, MAX_SIZE, jint)

FOUNDATION_EXPORT void OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_(OrgApacheLuceneUtilPackedPacked8ThreeBlocks *self, jint valueCount);

FOUNDATION_EXPORT OrgApacheLuceneUtilPackedPacked8ThreeBlocks *new_OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_(jint valueCount) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneUtilPackedPacked8ThreeBlocks *create_OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_(jint valueCount);

FOUNDATION_EXPORT void OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_withOrgApacheLuceneStoreDataInput_withInt_(OrgApacheLuceneUtilPackedPacked8ThreeBlocks *self, jint packedIntsVersion, OrgApacheLuceneStoreDataInput *inArg, jint valueCount);

FOUNDATION_EXPORT OrgApacheLuceneUtilPackedPacked8ThreeBlocks *new_OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_withOrgApacheLuceneStoreDataInput_withInt_(jint packedIntsVersion, OrgApacheLuceneStoreDataInput *inArg, jint valueCount) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneUtilPackedPacked8ThreeBlocks *create_OrgApacheLuceneUtilPackedPacked8ThreeBlocks_initPackagePrivateWithInt_withOrgApacheLuceneStoreDataInput_withInt_(jint packedIntsVersion, OrgApacheLuceneStoreDataInput *inArg, jint valueCount);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneUtilPackedPacked8ThreeBlocks)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneUtilPackedPacked8ThreeBlocks")


text:
/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ember-experiments',
    podModulePrefix: 'ember-experiments/pods',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    firebase: 'https://rx-ember-experiments.firebaseio.com/',
    torii: {
      sessionServiceName: 'session'
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV.contentSecurityPolicy = {
      'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com",
      'script-src': "'self' 'unsafe-inline'",
      'font-src': "'self' http://fonts.gstatic.com https://maxcdn.bootstrapcdn.com",
      'style-src': "'self' 'unsafe-inline' http://fonts.googleapis.com https://maxcdn.bootstrapcdn.com"
    };
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.baseURL = '/ember-experiments';
    ENV.locationType = 'hash';
    ENV.googleAnalytics = {
      webPropertyId: 'UA-19631381-7'
    };
  }

  return ENV;
};

redpajama_set_name: RedPajamaGithub


text:
namespace peloton {
namespace bridge {

class raw_column_info {
 public:
  raw_column_info(ValueType column_type, oid_t column_length,
                  std::string column_name, bool is_inlined,
                  std::vector<raw_constraint_info> raw_constraints)
      : column_type(column_type),
        column_length(column_length),
        column_name(column_name),
        is_inlined(is_inlined),
        raw_constraints(raw_constraints) {}

  catalog::Column CreateColumn(void) const;

  std::string GetColName() const { return column_name; }

 private:
  ValueType column_type;

  size_t column_length;

  std::string column_name;

  bool is_inlined;

  // Constraint information
  std::vector<raw_constraint_info> raw_constraints;
};

}  // namespace bridge
}  // namespace peloton


text:
layout: post
title: "django-grappelli,非常漂亮的admin界面"
tags: [Django]
---
想必你一定觉得django的admin界面丑爆了吧,没关系,我们有很好的app可以完美替代原来的界面,grappelli这样一个非常漂亮的admin管理界面

    **A jazzy skin for the Django admin interface**.

    Grappelli is a grid-based alternative/extension to the `Django <http://www.djangoproject.com>`_ administration interface.

    Code
    ----

    https://github.com/sehmaschine/django-grappelli

    Website
    -------

    http://www.grappelliproject.com

    Documentation
    -------------

    http://readthedocs.org/docs/django-grappelli/

    Releases
    --------

    **Grappelli is always developed against the latest stable Django release and is NOT tested with Djangos trunk.**

    * Grappelli 2.6.2 (October 17th, 2014): Compatible with Django 1.7
    * Grappelli 2.5.5 (October 17th, 2014): Compatible with Django 1.6
    * Grappelli 2.4.11 (October 17th, 2014): Compatible with Django 1.4/1.5

    Current development branches:

    * Grappelli 2.6.3 (Development version for Django 1.7, see branch dev/2.6.x)
    * Grappelli 2.5.6 (Development version for Django 1.6, see branch Stable/2.5.x)
    * Grappelli 2.4.12 (Development version for Django 1.4/1.5, see branch Stable/2.4.x)

    Older versions are availabe at GitHub, but are not supported anymore.
    Support for 2.4.x and 2.5.x is limited to security issues and very important bugfixes.

从这上面的介绍,我们可以知道,对于django 1.4,我们应该选择 Grappelli 2.4.12

#安装
###安装方法一:

把版本切换到2.4,直接从github上clone,下载到本地目录后直接运行

    python setup.py install

###安装方法二:

使用pip 安装,后面指定安装的版本

    pip install django-grappelli==2.4

#配置
然后,在settings.py里把grappelli添加到INSTALLED_APPS,并且要在django.contrib.admin之前,这样grappelli会接管admin

    INSTALLED_APPS = (
    'grappelli',
    'django.contrib.admin',
)

再然后在你的站点url.py里增加,不是app的url.py

    urlpatterns = patterns('',
    (r'^grappelli/', include('grappelli.urls')), # grappelli URLS
    (r'^admin/',  include(admin.site.urls)), # admin site
)

确保STATICFILES_FINDERS里面AppDirectoriesFinder是第一个

    STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
)

在TEMPLATE_CONTEXT_PROCESSORS增加request context processor,这样就可以找到你定义好的模版

	TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "django.core.context_processors.request",
)

然后收集媒体数据文件

    python manage.py collectstatic

#测试
运行

    python manage.py runserver <IP-address>:8000

测试地址,这样Grappelli会替代你默认的管理界面

    <IP-address>:8000/admin/

几个界面截图

#参考网址

https://github.com/sehmaschine/django-grappelli/

http://django-grappelli.readthedocs.org/

http://grappelliproject.com/


text:
![Alt text](pong-solo-start-screen.png)

### In-Game
![Alt text](pong-solo-during.png)


text:
#include <utility>
#include <stdio.h>
#include <iostream>

#include <muduo/base/Logging.h>
#include <muduo/base/TimeZone.h>
#include <muduo/base/AsyncLogging.h>

#include "BfcpService.h"
#include "BFCPService.nsmap"

extern char *basename( char *path );

using namespace muduo;

int kRollSize = 500 * 1000 * 1000;

muduo::AsyncLogging* g_asyncLog = NULL;
void asyncOutput(const char* msg, int len)
{
  g_asyncLog->append(msg, len);
}

int http_get(struct soap *soap);

int main(int argc, char* argv[])
{
  int port = 0;
  if (argc < 2)
  {
    fprintf(stderr, "Usage: bfcp_service_soap <port>\n");
    return 0;
  }
  else
  {
    port = atoi(argv[1]);
    if (!port)
    {
      fprintf(stderr, "Usage: bfcp_service_soap <port>\n");
      return 0;
    }
  }

  sys_coredump_set(true);

  Logger::setLogLevel(Logger::kTRACE);
  Logger::setTimeZone(muduo::TimeZone(8*3600, "CST"));

  char name[256];
  strncpy(name, argv[0], 256);
  muduo::AsyncLogging log(::basename(name), kRollSize);
  log.start();
  g_asyncLog = &log;
  muduo::Logger::setOutput(asyncOutput);

  LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();

  BfcpService service(SOAP_C_UTFSTRING | SOAP_IO_KEEPALIVE);
  service.send_timeout = 20;
  service.recv_timeout = 20;
  service.connect_timeout = 5;
  service.accept_timeout = 5;

  /* run iterative server on port until fatal error */
  service.fget = http_get;
  if (service.run(port))
  {
    char buf[1024];
    service.soap_sprint_fault(buf, sizeof buf);
    buf[sizeof(buf)-1] = '\0';
    LOG_ERROR << buf;
  }

  return 0;
}

int http_get(struct soap * soap)
{
  FILE *fd = NULL;
  char *s = strchr(soap->path, '?');
  if (!s || strcmp(s, "?wsdl"))
    return SOAP_GET_METHOD;
  fd = fopen("BFCPService.wsdl", "rb"); // open WSDL file to copy
  if (!fd)
    return 404; // return HTTP not found error
  soap->http_content = "text/xml"; // HTTP header with text/xml content
  soap_response(soap, SOAP_FILE);
  for (;;)
  {
    size_t r = fread(soap->tmpbuf, 1, sizeof(soap->tmpbuf), fd);
    if (!r)
      break;
    if (soap_send_raw(soap, soap->tmpbuf, r))
      break; // can't send, but little we can do about that
  }
  fclose(fd);
  soap_end_send(soap);
  return SOAP_OK;
}


text:
"use strict";
/**
 * Parses an SMD and provides methods to read information from it for working with RESTful services.
 * Uses the format defined by Kris Zyp and utilized by Dojo for RPC stores
 */
define([
    "./declare",
    "./ServiceDescriptorReader",
    "./log",
    "./util",
    "./AmdResolver"
], function (
    declare,
    ServiceDescriptorReader,
    logger,
    Util,
    AmdResolver
) {

    var util = new Util(),
        module = declare(ServiceDescriptorReader, {
            /**
             * Constructor requires a JSONSchema-compliant SMD file in Zyp format.
             */
            constructor: function (schema, refResolver) {

                logger.debug("Creating reader for schema", schema);

                if (!refResolver) {
                    refResolver = new AmdResolver({path: "", altSeparator: "\\.", synchronous: true}).resolver;
                }

                this.smd = schema;

                //finds all $ref instances and replaces with the actual object
                //similar to dojox.json.ref.resolveJson, but doesn't get hung up on circular references
                //TODO: should we assume all schemas have been resolved prior, and remove this step?
                function resolveRef(subobj, parent, parentKey) {
                    if (!subobj.resolved) {
                        Object.keys(subobj).forEach(function (key) {
                            var Ref, value = subobj[key];
                            if (key === "$ref") {
                                logger.debug("Resolving $ref: " + value);
                                Ref = refResolver(value);
                                value = typeof Ref === 'function' ? new Ref() : Ref;
                                if (!util.isUndefined(value) && !value.resolved) {
                                    subobj.resolved = true;
                                    resolveRef(value, subobj, key);
                                }
                                parent[parentKey] = value;
                            } else if (typeof value === "object") {
                                resolveRef(value, subobj, key);
                            }
                        });
                    }
                }

                function getExtendedProperties(obj, props) {
                    var parent = (obj && obj["extends"]), propsObj = [], items = [], itemProps;

                    if (typeof parent !== "undefined") {

                        items = util.isArray(parent) ? parent : [parent]; //can be multiple-inheritance

                        items.forEach(function (item) {
                            itemProps = item.properties || {};
                            Object.keys(itemProps).forEach(function (key) {
                                var value = item.properties[key];
                                if (key !== "__parent") {
                                    propsObj.push({
                                        parentId: item.id,
                                        key: key,
                                        value: value
                                    });
                                }
                            });

                        }, this); // jshint ignore:line

                        props.push(propsObj);
                        props = getExtendedProperties(parent, props);
                    }

                    return props;

                }

                //looks in JSONSchema objects for "extends" and copies properties to children
            function resolveExtensions(schema) {

                var xprops, props;

                xprops = getExtendedProperties(schema, []);

                //unwind the property stack so that the earliest gets inheritance link
                schema.properties = schema.properties || {};
                function copyprop(item) { //util to get around jslint complaints about doing this directly in loop
                    schema.properties[item.key] = item.val;
                }

                while (xprops.length > 0) {
                    props = xprops.pop();
                    props.forEach(copyprop);
                }
            }

            // mix-in parameters for extended schemas
            function resolveExtendedParameters(obj) {

                // assume all references are resolved, just copy parameters down the
                // inheritence chain. If I am derived check base first.
                if (obj["extends"]) {
                    resolveExtendedParameters(obj["extends"]);
                    obj.parameters = obj.parameters || [];
                    obj.parameters = obj.parameters.concat(obj["extends"].parameters);
                }
            }

            //copies properties from parent as defaults, as well as extensions for params
            function resolveProperties(schema) {

                logger.debug("Resolving sub-properties for " + schema.id);

                // resolve inherited global parameters
                resolveExtendedParameters(schema);

                Object.keys(schema.services || {}).forEach(function (key) {
                    var value = schema.services[key];
                    //value.target = value.target ? schema.target + value.target : schema.target; //TODO: should this build concat paths? that is currently handled in getServiceUrl function
                    value.returns = value.returns || schema.returns;
                    value.transport = value.transport || schema.transport;
                    value.contentType = value.contentType || schema.contentType;
                    value.envelope = value.envelope || schema.envelope || "URL";
                    value.description = value.description || "";

                    if (value.returns) {
                        resolveExtensions(value.returns);
                    }

                    if (value.parameters) {
                        value.parameters.forEach(function (item) {
                            item.envelope = item.envelope || value.envelope;
                            item.description = item.description || "";
                        });
                    }

                    var ext = value["extends"];

                    if (ext) {

                        //resolution hasn't been completed or extends object isn't proper JSONSchema
                        if (!ext.id) {
                            throw new Error("Parent schema for method [" + key + "] in schema " + schema.id + " is invalid.");
                        }

                        //TODO: resolveExtensions for params object properties? not really needed yet (the name is fine for now...)
                        if (!value.parameters) {
                            value.parameters = ext.parameters;
                        } else {
                            value.parameters = value.parameters.concat(ext.parameters);
                        }
                    }
                });

                if (!schema.tag) {
                    schema.tag = {};
                }
                schema.tag.resolved = true;
                schema.resolvedProperties = true;
            }

            //if a schema has already been resolved, don't do it again - we can get into endless recursion
            if (!schema.resolved) {
                resolveRef(schema, null, null);
                schema.resolved = true;
            }

            //only resolve these once, or else our concats will be a problem
            if (!schema.resolvedProperties) {
                resolveProperties(schema);
            }

            var hash = {};

            //index params array by name for lookup
            hash.parameters = {};
            this.getMethodNames().forEach(function (methodName) {
                var service = this.smd.services[methodName];
                if (service.parameters) {
                    service.parameters.forEach(function (parameter) {
                        hash[methodName + "-" + parameter.name] = parameter;
                    });
                }
            }, this);

            this.findParameter = function (methodName, parameterName) {
                return hash[methodName + "-" + parameterName];
            };

        },

        /**
         * Returns the identifier of the schema this reader operates on.
         */
        getSchemaId: function () {
            return this.smd.id; //TODO: the property name here can be configurable, we may want to support that.
        },

        /**
         * Gets the root target property for the service.
         */
        getRootPath: function () {
            return this.smd.target;
        },

        /**
         * Gets the jsonp callback property for the service.
         */
        getJsonpCallbackParameter: function () {
            return this.smd.jsonpCallbackParameter;
        },

        /**
         * Gets the transport property for the service.
         */
        getTransport: function () {
            return this.smd.transport;
        },

        /**
         * Gets a list of the service method names defined by the SMD.
         */
        getMethodNames: function () {
            var names = [];

            Object.keys(this.smd.services || {}).forEach(function (serviceName) {
                names.push(serviceName);
            });

            return names;
        },

        /**
         * Gets list of service methods in the SMD. These are the actual schema objects.
         */
        getMethods: function () {
            var services = [], smdServices = this.smd.services;

            Object.keys(smdServices || []).forEach(function (serviceName) {
                services.push(smdServices[serviceName]);
            });

            return services;
        },

        /**
         * Gets a specific service method object by name.
         * TODO: exception if service doesn't exist
         */
        getMethod: function (methodName) {
            var method = this.smd.services[methodName];
            if (!method) {
                throw new Error("no such method");
            }
            return method;
        },

        /**
         * Gets a list of parameter names for a specified service.
         */
        getParameterNames: function (methodName) {
            var names = [], params = this.getParameters(methodName);

            params.forEach(function (param) {
                names.push(param.name);
            });

            return names;
        },

        /**
         * Gets a list of parameters for a specified service. These are the actual objects.
         */
        getParameters: function (methodName) {
            var parameters = this.smd.parameters || [];

            parameters = parameters.concat(this.smd.services[methodName].parameters || []);

            return parameters;
        },

        /**
         * Indicates whether the specified argument on a service method is required or not.
         */
        isArgumentRequired: function (methodName, argName) {
            var required = this.findParameter(methodName, argName).required;
            //default is false, so if "required" is undefined, return false anyway
            if (required) {
                return true;
            }
            return false;
        },

        /**
         * For the specified service, map the args object to the target + parameters to
         * get a full, functional URL.
         */
        getServiceUrl: function (methodName, args) {

            var service = this.smd.services[methodName],
                basePath = this.getRootPath(),
                url,
                parameters = this.enumerateParameters(service);

            //if no service target, it sits at the root
            url = basePath + (service.target ? "/" + service.target : "");

            //replace path params where required
            url = this.replacePathParamsInUrl(url, parameters.PATH, args);

            //add any query params
            url = this.addQueryParamsToUrl(url, parameters.URL, args);

            return url;

        },

        getMethodTransport: function (methodName) {
            return this.smd.services[methodName].transport;
        },

        getMethodTimeout: function (methodName) {
            return this.smd.services[methodName].timeout;
        },

        getAndValidateArgument: function (param, args) {
            args = args || {};
            var arg = typeof args[param.name] !== "undefined" ? args[param.name] : param["default"];

            if (typeof arg === "undefined" && (param.required === true || param.optional === false)) {
                throw new Error("Missing required param for service call: " + param.name);
            }

            return arg;
        },

        replacePathParamsInUrl: function (url, params, args) {

            var index, length, param, arg;

            for (index = 0, length = params.length; index < length; index += 1) {

                param = params[index];
                arg = this.getAndValidateArgument(param, args);

                if (typeof arg !== "undefined") {
                    url = url.replace("{" + param.name + "}", encodeURIComponent(arg));
                }
            }

            return url;

        },

        addQueryParamsToUrl: function (url, params, args) {

            var index, length, queryString = "", param, arg, substring, firstParam = true;

            for (index = 0, length = params.length; index < length; index += 1) {

                param = params[index];
                arg = this.getAndValidateArgument(param, args);

                if (typeof arg !== "undefined") {

                    substring = param.name + "=" + encodeURIComponent(arg);

                    if (firstParam) {
                        firstParam = false;
                        queryString += "?" + substring;
                    } else {
                        queryString += "&" + substring;
                    }

                }
            }

            url += queryString;

            return url;

        },

        /**
         * Returns the param list mapped by envelope (URL, PATH, ENTITY)
         */
        enumerateParameters: function (service) {

            var index, length, parameters = this.smd.parameters, param,
                svcParameters = service.parameters || [],
                params = {
                    PATH: [], //args in URL path
                    URL: [], //args in query string
                    JSON: [], //JSON in POST/PUT body
                    ENTITY: [] //custom POST/PUT entity body (e.g., multi-part)
                };

            parameters = parameters ? parameters.concat(svcParameters) : svcParameters;

            if (parameters) {
                for (index = 0, length = parameters.length; index < length; index += 1) {
                    param = parameters[index];
                    params[param.envelope].push(param);
                }
            }

            return params;

        },

        /**
         * Returns the schema associted with the service method's response.
         * @param methodName - the service method to return a schema for.
         * @return the response schema
         */
        getResponseSchema: function (methodName) {
            return this.smd.services[methodName].returns;
        },

        /**
         * Returns the parameter associated with the payload of a request if there is one.
         * @param methodName - the service method to return a payload schema for.
         * @return the payload parameter or undefined
         */
        getRequestPayloadParam: function (methodName) {
            var params = this.getParameters(methodName),
                ret;
            params.forEach(function (param) {
                if (param && (param.envelope === 'JSON' ||
                        param.envelope === 'ENTITY')) {
                    ret = param;
                }
            });
            return ret;
        },

        /**
         * Returns the schema associated with the payload of a request if there is one.
         * @param methodName - the service method to return a payload schema for.
         * @return a model schema or undefined if there is no payload.
         */
        getRequestSchema: function (methodName) {
            var param = this.getRequestPayloadParam(methodName),
                ret = param && param.type;
            return ret;
        },

        /**
         * Returns the name of the primary payload object.
         * @param methodName - the service method to return a payload schema for.
         * If the "payload" field is not defined on the method, check the service root.
         */
        getResponsePayloadName: function (methodName) {

            var smd = this.smd,
                method = smd.services[methodName],
                payloadName = (method && method.payload) || smd.payload;

            return payloadName;
        },

        /**
         * Returns the name of the primary payload object.
         * @param methodName - the service method to return a payload schema for.
         */
        getRequestPayloadName: function (methodName) {

            var param = this.getRequestPayloadParam(methodName),
                payloadName = param && param.payload;

            return payloadName;
        },

        /**
         * Returns whether the primary payload is a list, by checking for "array" type on the SMD.
         * Defaults to false if return type is JSONSchema "null" primitive type.
         */
        isListResponse: function (methodName) {
            var response = this.getResponseSchema(methodName),
                payloadName = this.getResponsePayloadName(methodName),
                isList = false;

            if (response.type !== "null") {
                if ((payloadName && response.properties[payloadName] && response.properties[payloadName].type === "array") ||
                        (response.type && response.type === "array")) {
                    isList = true;
                }
            }

            return isList;
        }

    });

    return module;
});


text:
package com.netflix.recipes.rss.server;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rx.Observable;
import rx.Observable.OnSubscribe;

import com.google.gson.Gson;
import com.google.inject.Inject;
import com.netflix.karyon.transport.http.SimpleUriRouter;
import com.netflix.recipes.rss.manager.RSSManager;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpMethod;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import io.reactivex.netty.protocol.http.server.RequestHandler;

public class RssRouter implements RequestHandler<ByteBuf, ByteBuf> {

	private final SimpleUriRouter<ByteBuf, ByteBuf> delegate;

	private static final Logger log = LoggerFactory.getLogger(RssRouter.class);

	@Inject
	public RssRouter(RSSManager rssManager) {
		delegate = new SimpleUriRouter<ByteBuf, ByteBuf>();

		/*
		 * Deleagate for reading subscriptions from store
		 */
		delegate.addUriRegex(".middletier.rss.user.*$", (request, response) -> {
			log.info("Request Started: " + Thread.currentThread().getName());
			String user = StringUtils.substringAfterLast(request.getPath(), "/");

			if (request.getHttpMethod() == HttpMethod.GET) {
				return getSubscriptions(user, rssManager, response);
			} else if (request.getHttpMethod() == HttpMethod.POST) {
				String url = request.getQueryParameters().get("url").get(0);
				return addSubscription(user, url, rssManager, response);
			}

			return Observable.empty();
		});

		/*
		 * A fast delegate to test if the server can serve other requests, while busy with heavy IO request
		 */
		delegate.addUriRegex(".middletier.rss.hello.*$", (request, response) -> {
			return Observable.<Void>create((OnSubscribe<Void>) subscriber -> {
				response.writeStringAndFlush("Hello World");
				subscriber.onCompleted();
			});

		});
	}

	private Observable<Void> addSubscription(String user,
      String url, RSSManager rssManager, HttpServerResponse<ByteBuf> response) {
		try {
	    return rssManager.addSubscription(user, url);
    } catch (Exception e) {
    	log.error("Error adding url subscription for {}", user, e);
    }
		return Observable.empty();
  }

	private Observable<Void> getSubscriptions(String user, RSSManager rssManager, HttpServerResponse<ByteBuf> response) {
		/*
		 * this is assumed to be a long lasting I/O. If it is not subscribed on the Schedulers.io(), it will block
		 * the only thread of the server for the time of the IO operation.
		 */
		Observable<List<String>> subscriptions = rssManager.getSubscriptions(user);
		log.info("Request Done: " + Thread.currentThread().getName());

		return Observable.<Void>create((OnSubscribe<Void>) subscriber -> {
			subscriptions.subscribe(urls -> {
				log.info("Request Writing response: " + Thread.currentThread().getName());
				Gson gson = new Gson();
				response.writeStringAndFlush(gson.toJson(urls));
			}, Throwable::printStackTrace, () -> {
				response.close(true);
				subscriber.onCompleted();
			});
		});

	}

	@Override
	public Observable<Void> handle(HttpServerRequest<ByteBuf> request,
	    HttpServerResponse<ByteBuf> response) {
		return delegate.handle(request, response);
	}

}


text:
module Graphics.Rendering.OpenGL.Raw.ARB.BaseInstance (
  -- * Functions
  glDrawArraysInstancedBaseInstance,
  glDrawElementsInstancedBaseInstance,
  glDrawElementsInstancedBaseVertexBaseInstance
) where

import Graphics.Rendering.OpenGL.Raw.Functions


text:
package org.apache.flink.streaming.connectors.elasticsearch;

import org.elasticsearch.action.ActionRequest;

/**
 * Users add multiple {@link ActionRequest ActionRequests} to a {@link RequestIndexer} to prepare
 * them for sending to an Elasticsearch cluster.
 */
public interface RequestIndexer {

	/**
	 * Add multiple {@link ActionRequest} to the indexer to prepare for sending requests to Elasticsearch.
	 *
	 * @param actionRequests The multiple {@link ActionRequest} to add.
	 */
	void add(ActionRequest... actionRequests);
}


text:
/*
 * ip/ip6_pg: IP v4 packet-generator interface
 *
 * Copyright (c) 2008 Eliot Dresselhaus
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <vnet/ip/ip.h>
#include <vnet/pg/pg.h>

static void
ip6_pg_edit_function (pg_main_t * pg,
		      pg_stream_t * s,
		      pg_edit_group_t * g,
		      u32 * packets,
		      u32 n_packets)
{
  vlib_main_t * vm = pg->vlib_main;
  u32 ip_header_offset = g->start_byte_offset;

  while (n_packets >= 2)
    {
      u32 pi0, pi1;
      vlib_buffer_t * p0, * p1;
      ip6_header_t * ip0, * ip1;

      pi0 = packets[0];
      pi1 = packets[1];
      p0 = vlib_get_buffer (vm, pi0);
      p1 = vlib_get_buffer (vm, pi1);
      n_packets -= 2;
      packets += 2;

      ip0 = (void *) (p0->data + ip_header_offset);
      ip1 = (void *) (p1->data + ip_header_offset);

      ip0->payload_length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, p0) - ip_header_offset - sizeof (ip0[0]));
      ip1->payload_length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, p1) - ip_header_offset - sizeof (ip1[0]));
    }

  while (n_packets >= 1)
    {
      u32 pi0;
      vlib_buffer_t * p0;
      ip6_header_t * ip0;

      pi0 = packets[0];
      p0 = vlib_get_buffer (vm, pi0);
      n_packets -= 1;
      packets += 1;

      ip0 = (void *) (p0->data + ip_header_offset);

      ip0->payload_length = clib_host_to_net_u16 (vlib_buffer_length_in_chain (vm, p0) - ip_header_offset - sizeof (ip0[0]));
    }
}

typedef struct {
  pg_edit_t ip_version;
  pg_edit_t traffic_class;
  pg_edit_t flow_label;
  pg_edit_t payload_length;
  pg_edit_t protocol;
  pg_edit_t hop_limit;
  pg_edit_t src_address, dst_address;
} pg_ip6_header_t;

static inline void
pg_ip6_header_init (pg_ip6_header_t * p)
{
  /* Initialize fields that are not bit fields in the IP header. */
#define _(f) pg_edit_init (&p->f, ip6_header_t, f);
  _ (payload_length);
  _ (hop_limit);
  _ (protocol);
  _ (src_address);
  _ (dst_address);
#undef _

  /* Initialize bit fields. */
  pg_edit_init_bitfield (&p->ip_version, ip6_header_t,
			 ip_version_traffic_class_and_flow_label,
			 28, 4);
  pg_edit_init_bitfield (&p->traffic_class, ip6_header_t,
			 ip_version_traffic_class_and_flow_label,
			 20, 8);
  pg_edit_init_bitfield (&p->flow_label, ip6_header_t,
			 ip_version_traffic_class_and_flow_label,
			 0, 20);
}

uword
unformat_pg_ip6_header (unformat_input_t * input, va_list * args)
{
  pg_stream_t * s = va_arg (*args, pg_stream_t *);
  pg_ip6_header_t * p;
  u32 group_index;

  p = pg_create_edit_group (s, sizeof (p[0]), sizeof (ip6_header_t),
			    &group_index);
  pg_ip6_header_init (p);

  /* Defaults. */
  pg_edit_set_fixed (&p->ip_version, 6);
  pg_edit_set_fixed (&p->traffic_class, 0);
  pg_edit_set_fixed (&p->flow_label, 0);
  pg_edit_set_fixed (&p->hop_limit, 64);

  p->payload_length.type = PG_EDIT_UNSPECIFIED;

  if (! unformat (input, "%U: %U -> %U",
		  unformat_pg_edit,
		    unformat_ip_protocol, &p->protocol,
		  unformat_pg_edit,
		    unformat_ip6_address, &p->src_address,
		  unformat_pg_edit,
		    unformat_ip6_address, &p->dst_address))
    goto error;

  /* Parse options. */
  while (1)
    {
      if (unformat (input, "version %U",
		    unformat_pg_edit,
		    unformat_pg_number, &p->ip_version))
	;

      else if (unformat (input, "traffic-class %U",
			 unformat_pg_edit,
			 unformat_pg_number, &p->traffic_class))
	;

      else if (unformat (input, "length %U",
			 unformat_pg_edit,
			 unformat_pg_number, &p->payload_length))
	;

      else if (unformat (input, "hop-limit %U",
			 unformat_pg_edit,
			 unformat_pg_number, &p->hop_limit))
	;

      /* Can't parse input: try next protocol level. */
      else
	break;
    }

  {
    ip_main_t * im = &ip_main;
    ip_protocol_t protocol;
    ip_protocol_info_t * pi;

    pi = 0;
    if (p->protocol.type == PG_EDIT_FIXED)
      {
	protocol = pg_edit_get_value (&p->protocol, PG_EDIT_LO);
	pi = ip_get_protocol_info (im, protocol);
      }

    if (pi && pi->unformat_pg_edit
	&& unformat_user (input, pi->unformat_pg_edit, s))
      ;

    else if (! unformat_user (input, unformat_pg_payload, s))
      goto error;

    if (p->payload_length.type == PG_EDIT_UNSPECIFIED
	&& s->min_packet_bytes == s->max_packet_bytes
	&& group_index + 1 < vec_len (s->edit_groups))
      {
	pg_edit_set_fixed (&p->payload_length,
			   pg_edit_group_n_bytes (s, group_index) - sizeof (ip6_header_t));
      }

    p = pg_get_edit_group (s, group_index);
    if (p->payload_length.type == PG_EDIT_UNSPECIFIED)
      {
	pg_edit_group_t * g = pg_stream_get_group (s, group_index);
	g->edit_function = ip6_pg_edit_function;
      }

    return 1;
  }

 error:
  /* Free up any edits we may have added. */
  pg_free_edit_group (s);
  return 0;
}


text:
//
//  bot.js
//  examples
//
//  Created by Stephen Birarda on 2/20/14.
//  Modified by Philip on 3/3/14
//  Copyright 2014 High Fidelity, Inc.
//
//  This is an example script that demonstrates an NPC avatar.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//

function getRandomFloat(min, max) {
    return Math.random() * (max - min) + min;
}

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function printVector(string, vector) {
    print(string + " " + vector.x + ", " + vector.y + ", " + vector.z);
}

var CHANCE_OF_MOVING = 0.005;
var CHANCE_OF_SOUND = 0.005;
var CHANCE_OF_HEAD_TURNING = 0.05;
var CHANCE_OF_BIG_MOVE = 0.1;
var CHANCE_OF_WAVING = 0.009;

var shouldReceiveVoxels = true;
var VOXEL_FPS = 60.0;
var lastVoxelQueryTime = 0.0;

var isMoving = false;
var isTurningHead = false;
var isPlayingAudio = false;
var isWaving = false;
var waveFrequency = 0.0;
var waveAmplitude = 0.0;

var X_MIN = 5.0;
var X_MAX = 15.0;
var Z_MIN = 5.0;
var Z_MAX = 15.0;
var Y_PELVIS = 1.0;
var SPINE_JOINT_NUMBER = 13;
var SHOULDER_JOINT_NUMBER = 17;
var ELBOW_JOINT_NUMBER = 18;
var JOINT_R_HIP = 1;
var JOINT_R_KNEE = 2;

var MOVE_RANGE_SMALL = 0.5;
var MOVE_RANGE_BIG = Math.max(X_MAX - X_MIN, Z_MAX - Z_MIN) / 2.0;
var TURN_RANGE = 70.0;
var STOP_TOLERANCE = 0.05;
var MOVE_RATE = 0.05;
var TURN_RATE = 0.15;
var PITCH_RATE = 0.20;
var PITCH_RANGE = 30.0;

var firstPosition = { x: getRandomFloat(X_MIN, X_MAX), y: Y_PELVIS, z: getRandomFloat(Z_MIN, Z_MAX) };
var targetPosition =  { x: 0, y: 0, z: 0 };
var targetDirection = { x: 0, y: 0, z: 0, w: 0 };
var currentDirection = { x: 0, y: 0, z: 0, w: 0 };
var targetHeadPitch = 0.0;

var walkFrequency = 5.0;
var walkAmplitude = 45.0;

var cumulativeTime = 0.0;

var sounds = [];
loadSounds();

function clamp(val, min, max){
    return Math.max(min, Math.min(max, val))
}

//  Play a random sound from a list of conversational audio clips
var AVERAGE_AUDIO_LENGTH = 8000;
function playRandomSound() {
  if (!Agent.isPlayingAvatarSound) {
    var whichSound = Math.floor((Math.random() * sounds.length) % sounds.length);
    Agent.playAvatarSound(sounds[whichSound]);
  }
}

// pick an integer between 1 and 20 for the face model for this bot
botNumber = getRandomInt(1, 100);

if (botNumber <= 20) {
  newFaceFilePrefix = "bot" + botNumber;
  newBodyFilePrefix = "defaultAvatar_body"
} else {
  if (botNumber <= 40) {
    newFaceFilePrefix = "superhero";
  } else if (botNumber <= 60) {
    newFaceFilePrefix = "amber";
  } else if (botNumber <= 80) {
    newFaceFilePrefix = "ron";
  } else {
    newFaceFilePrefix = "angie";
  }

  newBodyFilePrefix = "bot" + botNumber;
}

// set the face model fst using the bot number
// there is no need to change the body model - we're using the default
Avatar.faceModelURL = "https://s3-us-west-1.amazonaws.com/highfidelity-public/meshes/" + newFaceFilePrefix + ".fst";
Avatar.skeletonModelURL = "https://s3-us-west-1.amazonaws.com/highfidelity-public/meshes/" + newBodyFilePrefix + ".fst";
Avatar.billboardURL = "https://s3-us-west-1.amazonaws.com/highfidelity-public/meshes/billboards/bot" + botNumber + ".png";

Agent.isAvatar = true;
Agent.isListeningToAudioStream = true;

// change the avatar's position to the random one
Avatar.position = firstPosition;
printVector("New bot, position = ", Avatar.position);

function stopWaving() {
  isWaving = false;
  Avatar.clearJointData(SHOULDER_JOINT_NUMBER);
  Avatar.clearJointData(ELBOW_JOINT_NUMBER);
  Avatar.clearJointData(SPINE_JOINT_NUMBER);
}

function keepWalking() {
      Avatar.setJointData(JOINT_R_HIP, Quat.fromPitchYawRollDegrees(walkAmplitude * Math.sin(cumulativeTime * walkFrequency), 0.0, 0.0));
      Avatar.setJointData(JOINT_R_KNEE, Quat.fromPitchYawRollDegrees(walkAmplitude * Math.sin(cumulativeTime * walkFrequency), 0.0, 0.0));
}

function stopWalking() {
  Avatar.clearJointData(JOINT_R_HIP);
  Avatar.clearJointData(JOINT_R_KNEE);
}

function updateBehavior(deltaTime) {

  cumulativeTime += deltaTime;

  //  Hack - right now you need to set the avatar position a bit after the avatar is made to make sure it's there.

  if (CHANCE_OF_MOVING == 0.000) {
      Avatar.position = firstPosition;
  }

  if (shouldReceiveVoxels && ((cumulativeTime - lastVoxelQueryTime) > (1.0 / VOXEL_FPS))) {
    VoxelViewer.setPosition(Avatar.position);
    VoxelViewer.setOrientation(Avatar.orientation);
    VoxelViewer.queryOctree();
    lastVoxelQueryTime = cumulativeTime;
    /*
    if (Math.random() < (1.0 / VOXEL_FPS)) {
      print("Voxels in view = " + VoxelViewer.getOctreeElementsCount());
    }*/
  }

  if (!isWaving && (Math.random() < CHANCE_OF_WAVING)) {
    isWaving = true;
    waveFrequency = 3.0 + Math.random() * 5.0;
    waveAmplitude = 5.0 + Math.random() * 60.0;
    Script.setTimeout(stopWaving, 1000 + Math.random() * 2000);
    Avatar.setJointData(ELBOW_JOINT_NUMBER, Quat.fromPitchYawRollDegrees(0.0, 45, 0.0));    //  Initially turn the palm outward
  } else if (isWaving) {
    Avatar.setJointData(SHOULDER_JOINT_NUMBER, Quat.fromPitchYawRollDegrees(0.0, 0.0,  60 + waveAmplitude * Math.sin((cumulativeTime - 0.25) * waveFrequency)));
    Avatar.setJointData(ELBOW_JOINT_NUMBER, Quat.fromPitchYawRollDegrees(0.0, 0.0,  25 + waveAmplitude/2.0 * Math.sin(cumulativeTime * 1.2 * waveFrequency)));
    Avatar.setJointData(SPINE_JOINT_NUMBER, Quat.fromPitchYawRollDegrees(0.0, 0.0,  60 + waveAmplitude/4.0 * Math.sin(cumulativeTime * waveFrequency)));

  }

  if (Math.random() < CHANCE_OF_SOUND) {
    playRandomSound();
  }

  if (!isTurningHead && (Math.random() < CHANCE_OF_HEAD_TURNING)) {
    targetHeadPitch = getRandomFloat(-PITCH_RANGE, PITCH_RANGE);
    isTurningHead = true;
  } else {
    Avatar.headPitch = Avatar.headPitch + (targetHeadPitch - Avatar.headPitch) * PITCH_RATE;
    if (Math.abs(Avatar.headPitch - targetHeadPitch) < STOP_TOLERANCE) {
      isTurningHead = false;
    }
  }
  if (!isMoving && (Math.random() < CHANCE_OF_MOVING)) {
    // Set new target location
    targetDirection = Quat.multiply(Avatar.orientation, Quat.angleAxis(getRandomFloat(-TURN_RANGE, TURN_RANGE), { x:0, y:1, z:0 }));
    var front = Quat.getFront(targetDirection);
    if (Math.random() < CHANCE_OF_BIG_MOVE) {
        targetPosition = Vec3.sum(Avatar.position, Vec3.multiply(front, getRandomFloat(0.0, MOVE_RANGE_BIG)));
    } else {
        targetPosition = Vec3.sum(Avatar.position, Vec3.multiply(front, getRandomFloat(0.0, MOVE_RANGE_SMALL)));
    }
    targetPosition.x = clamp(targetPosition.x, X_MIN, X_MAX);
    targetPosition.z = clamp(targetPosition.z, Z_MIN, Z_MAX);
    targetPosition.y = Y_PELVIS;

    isMoving = true;
  } else if (isMoving) {
    keepWalking();
    Avatar.position = Vec3.sum(Avatar.position, Vec3.multiply(Vec3.subtract(targetPosition, Avatar.position), MOVE_RATE));
    Avatar.orientation = Quat.mix(Avatar.orientation, targetDirection, TURN_RATE);
    if (Vec3.length(Vec3.subtract(Avatar.position, targetPosition)) < STOP_TOLERANCE) {
       isMoving = false;
       stopWalking();
    }
  }
}

Script.update.connect(updateBehavior);

function loadSounds() {
  var sound_filenames = ["AB1.raw", "Anchorman2.raw", "B1.raw", "B1.raw", "Bale1.raw", "Bandcamp.raw",
    "Big1.raw", "Big2.raw", "Brian1.raw", "Buster1.raw", "CES1.raw", "CES2.raw", "CES3.raw", "CES4.raw",
    "Carrie1.raw", "Carrie3.raw", "Charlotte1.raw", "EN1.raw", "EN2.raw", "EN3.raw", "Eugene1.raw", "Francesco1.raw",
    "Italian1.raw", "Japanese1.raw", "Leigh1.raw", "Lucille1.raw", "Lucille2.raw", "MeanGirls.raw", "Murray2.raw",
    "Nigel1.raw", "PennyLane.raw", "Pitt1.raw", "Ricardo.raw", "SN.raw", "Sake1.raw", "Samantha1.raw", "Samantha2.raw",
    "Spicoli1.raw", "Supernatural.raw", "Swearengen1.raw", "TheDude.raw", "Tony.raw", "Triumph1.raw", "Uma1.raw",
    "Walken1.raw", "Walken2.raw", "Z1.raw", "Z2.raw"
  ];

  var SOUND_BASE_URL = "https://s3-us-west-1.amazonaws.com/highfidelity-public/sounds/Cocktail+Party+Snippets/Raws/";

  for (var i = 0; i < sound_filenames.length; i++) {
      sounds.push(new Sound(SOUND_BASE_URL + sound_filenames[i]));
  }
}


text:
package com.balonbal.slybot.util.sites.twitch;

import java.util.ArrayList;
import java.util.HashMap;

public class TwitchSubscription {

    boolean active;
    String name;
    ArrayList<String> subscribers;
    String channel;

    protected HashMap<String, Object> streamData;

    public TwitchSubscription(String name, String channel, String ... subscribers) {
        this.name = name;
        this.channel = channel;
        active = false;

        this.subscribers = new ArrayList<>();

        for (String sub: subscribers) {
            this.subscribers.add(sub);
        }
    }

    public TwitchSubscription(String name, String channel, ArrayList<String> subscribers) {
        this.name = name;
        this.channel = channel;
        this.subscribers = subscribers;
    }

    public HashMap<String, Object> createMap() {
        HashMap<String, Object> map = new HashMap<>();

        map.put("name", name);
        map.put("subscribers", subscribers);
        map.put("channel", channel);

        return map;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public String getChannel() {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public ArrayList<String> getSubscribers() {
        return subscribers;
    }

    public void setSubscribers(ArrayList<String> subscribers) {
        this.subscribers = subscribers;
    }

    public HashMap<String, Object> getStreamData() {
        return streamData;
    }

    public void setStreamData(HashMap<String, Object> streamData) {
        this.streamData = streamData;
    }

    public boolean isSubscribed(String name) {
        return subscribers.contains(name);
    }

    public void unsubscribe(String name) {
        subscribers.remove(name);
    }

    public void subscribe(String subscriber) {
        subscribers.add(subscriber);
    }
}


text:
* `Source code @ GitHub <https://github.com/a25kk/tam.sitecontent>`_
* `Releases @ PyPI <http://pypi.python.org/pypi/tam.sitecontent>`_
* `Documentation @ ReadTheDocs <http://tamsitecontent.readthedocs.org>`_
* `Continuous Integration @ Travis-CI <http://travis-ci.org/a25kk/tam.sitecontent>`_

## How it works

This package provides a Plone addon as an installable Python egg package.

The generated Python package hold the necessary scaffold to add content types
via the 'contenttype' template and to add functionality.

In order to get productive you still need to generate a contenttype

```bash
$ cd tam.sitecontent/src/tam/sitecontent/
$ mrbob --config ~/.mrbob.ini -O example_type bobtemplates:contenttype

```

## Installation

To install `tam.sitecontent` you simply add ``tam.sitecontent``
to the list of eggs in your buildout, run buildout and restart Plone.
Then, install `tam.sitecontent` using the Add-ons control panel.


text:
module Mimsy
  module RPC
    class Return
      def initialize(channel)
        @return_refs = {}
        @channel = channel
        @gateway = Mimsy::AMQP::Incoming.new(channel, topology_options)
      end

      def run
        @gateway.subscribe(ack: true) do |delivery_info, metadata, payload|
          Mimsy::logger.info "got return message: #{payload}"

          begin
            answer = Mimsy::Request.new(payload)
            answer.validate!
          rescue Mimsy::Request::Error => e
            Mimsy.logger.error "answer parsing error: #{payload}"
            Mimsy.logger.error e
            return true
          end

          entry = find(answer.ref)

          if entry
            Mimsy::logger.info "found callback for return message #{answer.ref}"

            if Mimsy::Lifecycle.run_callback(@channel, answer, entry[:context], entry[:callback])
              @channel.ack(delivery_info.delivery_tag, false)
            else
              @channel.reject(delivery_info.delivery_tag)
            end

          else
            Mimsy::logger.error "callback for return message #{answer.ref} not found"
            @channel.ack(delivery_info.delivery_tag, false)
          end
        end
      end

      def run_sync
        answer = nil

        @gateway.subscribe(ack: true, block: true) do |delivery_info, metadata, payload|
          @channel.ack(delivery_info.delivery_tag, false)

          begin
            answer = Mimsy::Request.new(payload)
            answer.validate!
          rescue Mimsy::Request::Error => e
            Mimsy.logger.error "answer parsing error: #{payload}"
            Mimsy.logger.error e
            return true
          end

          delivery_info.consumer.cancel
        end

        answer
      end

      def register(ref, callback_context, &callback)
        @return_refs[ref] = {context: callback_context, callback: callback}
      end

      def find(ref)
        @return_refs[ref]
      end

      def topology_options
        @topology_options ||= {
          object_type: 'q',
          name: "#{Mimsy::application.service_name}-ret-#{Mimsy.uuid}",
          auto_delete: true
        }
      end

      def close
        @channel.close if @channel rescue Bunny::ChannelError
      end
    end
  end
end


text:
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

import logging
log = logging.getLogger(__name__)

import numpy as np

from ...utils import print_progress

from ..matrix import CostMatrix
from ..cost_function import AbstractCostFunction
from ..cost_function.brownian import BrownianLinkCostFunction
from ..cost_function.diagonal import DiagonalCostFunction
from ..cost_function.directed import BasicDirectedLinkCostFunction

from . import AbstractSolver

__all__ = []

class ByFrameSolver(AbstractSolver):
    """

    Parameters
    ----------
    trajs : :class:`pandas.DataFrame`
    cost_functions : list of list
    """
    def __init__(self, trajs, cost_functions, coords=['x', 'y', 'z']):

        super(self.__class__, self).__init__(trajs)

        self.t_in = 0
        self.t_out = 0

        self.coords = coords

        self.trajs.check_trajs_df_structure(index=['t_stamp', 'label'],
                                            columns=['t'] + coords)

        self.link_cf = cost_functions['link']
        self.check_cost_function_type(self.link_cf, AbstractCostFunction)

        self.birth_cf = cost_functions['birth']
        self.check_cost_function_type(self.birth_cf, AbstractCostFunction)

        self.death_cf = cost_functions['death']
        self.check_cost_function_type(self.death_cf, AbstractCostFunction)

        self.max_assigned_cost = self.death_cf.context['cost']

    @classmethod
    def for_brownian_motion(cls, trajs,
                            max_speed,
                            penalty=1.05,
                            coords=['x', 'y', 'z']):
        """

        Parameters
        ----------
        trajs : :class:`sktracker.trajectories.Trajectories`
        max_speed : float
            Maximum objects velocity
        penalty : float
        coords : list
            Which columns to choose in trajs when computing distances.

        Examples
        --------
        >>> true_trajs = Trajectories(data.brownian_trajectories_generator())
        >>>
        >>> # Remove labels
        >>> true_trajs.relabel(np.arange(len(true_trajs)))
        >>>
        >>> solver = ByFrameSolver.for_brownian_motion(true_trajs, max_speed=5, penalty=2.)
        >>> new_trajs = solver.track()
        2014:INFO:by_frame_solver: Initiating frame by frame tracking.
        2014:INFO:by_frame_solver: Frame by frame tracking done. 5 segments found (500 before).
        """
        guessed_cost = np.float(max_speed ** 2) * penalty
        diag_context = {'cost': guessed_cost}
        diag_params = {'penalty': penalty, 'coords': coords}

        link_cost_func = BrownianLinkCostFunction(parameters={'max_speed': max_speed,
                                                              'coords': coords})
        birth_cost_func = DiagonalCostFunction(context=diag_context,
                                               parameters=diag_params)
        death_cost_func = DiagonalCostFunction(context=diag_context,
                                               parameters=diag_params)

        cost_functions = {'link': link_cost_func,
                          'birth': birth_cost_func,
                          'death': death_cost_func}

        return cls(trajs, cost_functions, coords=coords)

    @classmethod
    def for_directed_motion(cls, trajs,
                            max_speed,
                            penalty=1.05,
                            past_traj_time=10,
                            smooth_factor=0,
                            interpolation_order=1,
                            coords=['x', 'y', 'z']):
        """Link objects according to their distance found in trajectories frame by frame.

        Parameters
        ----------
        trajs : :class:`sktracker.trajectories.Trajectories`
        max_speed : float
            Maximum objects velocity
        penalty : float
        past_traj_time : float
            Time during which the tracker can make a gap close. Above this time all gap
            close event will discarded.
        smooth_factor : float
            Smoothing condition used in :func:`scipy.interpolate.splrep`
        interpolation_order : int
            The order of the spline fit. See :func:`scipy.interpolate.splrep`
        coords : list
            Which columns to choose in trajs when computing distances.
        """

        parameters = {'max_speed': max_speed,
                      'past_traj_time': past_traj_time,
                      'smooth_factor': smooth_factor,
                      'interpolation_order': interpolation_order,
                      'coords': coords}

        guessed_cost = 20 * penalty
        diag_context = {'cost': guessed_cost}
        diag_params = {'penalty': penalty}
        link_context = {'trajs': trajs}

        link_cost_func = BasicDirectedLinkCostFunction(parameters=parameters,
                                                       context=link_context)

        birth_cost_func = DiagonalCostFunction(context=diag_context,
                                               parameters=diag_params)
        death_cost_func = DiagonalCostFunction(context=diag_context,
                                               parameters=diag_params)

        cost_functions = {'link': link_cost_func,
                          'birth': birth_cost_func,
                          'death': death_cost_func}

        return cls(trajs, cost_functions, coords=coords)

    @property
    def blocks_structure(self):
        return [[self.link_cf.mat, self.death_cf.mat],
                [self.birth_cf.mat, None]]

    @property
    def pos_in(self):
        return self.trajs.loc[self.t_in]

    @property
    def pos_out(self):
        return self.trajs.loc[self.t_out]

    def track(self, progress_bar=False, progress_bar_out=None):
        """

        Returns
        -------
        self.trajs : :class:`pandas.DataFrame`
        progress_bar : bool
            Display progress bar
        progress_bar_out : OutStream
            For testing purpose only
        """

        log.info('Initiating frame by frame tracking.')

        old_labels = self.trajs.index.get_level_values('label').values
        self.trajs['new_label'] = old_labels.astype(np.float)
        ts_in = self.trajs.t_stamps[:-1]
        ts_out = self.trajs.t_stamps[1:]

        n_labels_before = len(self.trajs.labels)

        n = len(ts_in)
        for i, (t_in, t_out) in enumerate(zip(ts_in, ts_out)):
            if progress_bar:
                progress = i / n * 100
                message = "t_in : {} | t_out {}".format(t_in, t_out)
                print_progress(progress, message=message, out=progress_bar_out)

            self.one_frame(t_in, t_out)

        if progress_bar:
            print_progress(-1)

        self.relabel_trajs()

        n_labels_after = len(self.trajs.labels)
        mess = 'Frame by frame tracking done. {} segments found ({} before).'
        log.info(mess.format(n_labels_after, n_labels_before))
        return self.trajs

    def one_frame(self, t_in, t_out):
        """

        Parameters
        ----------
        t_in : int
        t_out : int
        """

        self.t_in = t_in
        self.t_out = t_out

        pos_in = self.pos_in
        pos_out = self.pos_out

        self.link_cf.context['pos_in'] = pos_in
        self.link_cf.context['pos_out'] = pos_out
        self.link_cf.get_block()

        self.birth_cf.context['objects'] = pos_out
        self.birth_cf.get_block()

        self.death_cf.context['objects'] = pos_in
        self.death_cf.get_block()

        self.cm = CostMatrix(self.blocks_structure)
        self.cm.solve()
        self.assign()

    def assign(self):
        """
        """

        row_shapes, col_shapes = self.cm.get_shapes()
        last_in_link = row_shapes[0]
        last_out_link = col_shapes[0]

        new_labels_in = self.trajs.loc[self.t_in]['new_label'].values
        new_labels_out = np.arange(last_out_link)

        for idx_out, idx_in in enumerate(self.cm.out_links[:last_out_link]):
            if idx_in >= last_in_link:
                # new segment
                new_label = self.trajs['new_label'].max() + 1.
            else:
                # assignment
                new_label = new_labels_in[idx_in]
                self._update_max_assign_cost(self.cm.mat[idx_in, idx_out])

            new_labels_out[idx_out] = new_label
            self.trajs.loc[self.t_out, 'new_label'] = new_labels_out
            # The line below looks much slower than the two lines above
            # self.trajs.loc[self.t_out, 'new_label'].iloc[idx_out] = new_label

    def _update_max_assign_cost(self, cost):
        """
        """

        if cost > self.max_assigned_cost:
            self.max_assigned_cost = cost
            new_b_cost = self.max_assigned_cost * self.birth_cf.parameters['penalty']
            new_d_cost = self.max_assigned_cost * self.death_cf.parameters['penalty']
            self.birth_cf.context['cost'] = new_b_cost
            self.death_cf.context['cost'] = new_d_cost


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codility_lesson_6_4
{
    /// <summary>
    /// CODILITY: Lesson 6 - Sorting, Task 4 - NumberOfDiscIntersections
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: ydera00
 * Date: 12/8/16
 * Time: 1:26 PM
 */

namespace Giftcards\Encryption\Doctrine;

class FieldData
{
    protected $clearText;
    protected $cipherText;
    protected $profile;

    public function __construct($clearText, $cipherText, $profile)
    {
        $this->clearText = $clearText;
        $this->cipherText = $cipherText;
        $this->profile = $profile;
    }

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

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

    /**
     * @return null|string
     */
    public function getProfile()
    {
        return $this->profile;
    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("product", "0080_auto_20181214_0440")]

    operations = [
        migrations.AlterField(
            model_name="product",
            name="tax_rate",
            field=models.CharField(
                blank=True,
                choices=[
                    ("accommodation", "accommodation"),
                    ("admission to cultural events", "admission to cultural events"),
                    (
                        "admission to entertainment events",
                        "admission to entertainment events",
                    ),
                    ("admission to sporting events", "admission to sporting events"),
                    ("advertising", "advertising"),
                    ("agricultural supplies", "agricultural supplies"),
                    ("baby foodstuffs", "baby foodstuffs"),
                    ("bikes", "bikes"),
                    ("books", "books"),
                    ("childrens clothing", "childrens clothing"),
                    ("domestic fuel", "domestic fuel"),
                    ("domestic services", "domestic services"),
                    ("e-books", "e-books"),
                    ("foodstuffs", "foodstuffs"),
                    ("hotels", "hotels"),
                    ("medical", "medical"),
                    ("newspapers", "newspapers"),
                    ("passenger transport", "passenger transport"),
                    ("pharmaceuticals", "pharmaceuticals"),
                    ("property renovations", "property renovations"),
                    ("restaurants", "restaurants"),
                    ("social housing", "social housing"),
                    ("standard", "standard"),
                    ("water", "water"),
                ],
                default="standard",
                max_length=128,
            ),
        )
    ]


text:
package com.matija.easy;

public class CavityMap {

    // Complete the cavityMap function below.
    static String[] cavityMap(String[] grid) {
        String[] r = new String[grid.length];
        r[0] = grid[0];
        for (int i = 1; i<grid.length-1; i++) {
            char[] crs = grid[i].toCharArray();
            char[] chars = grid[i].toCharArray();
            for (int j = 1; j < grid[i].length()-1; j++) {
                int up = Integer.parseInt(String.valueOf(grid[i-1].charAt(j)));
                int left = Integer.parseInt(String.valueOf(chars[j-1]));
                int right = Integer.parseInt(String.valueOf(chars[j+1]));
                int down = Integer.parseInt(String.valueOf(grid[i+1].charAt(j)));

                int curr = Integer.parseInt(String.valueOf(chars[j]));
                int biggest = Math.max(up, Math.max(left, Math.max(right, down)));
                if (curr > biggest) {
                    crs[j]='X';
                }
            }
            r[i] = new String(crs);
        }
        r[grid.length-1] = grid[grid.length-1];
        return r;
    }

}


text:
from sqlalchemy import create_engine
import waldo.backend

def test_backend():
    assert waldo.backend.Base

def test_create_all():
    metadata = waldo.backend.Base.metadata
    metadata.bind = create_engine('sqlite://')
    metadata.create_all()


text:
package com.intellij.internal.psiView.formattingblocks;

import com.intellij.ui.treeStructure.SimpleTreeStructure;
import org.jetbrains.annotations.NotNull;

public class BlockTreeStructure extends SimpleTreeStructure {
  private BlockTreeNode myRoot;

  @NotNull
  @Override
  public BlockTreeNode getRootElement() {
    return myRoot;
  }

  public void setRoot(BlockTreeNode root) {
    myRoot = root;
  }
}


text:
Tutorial
--------

### Introduction

Linked lists are the best and simplest example of a dynamic data structure that uses pointers for its implementation.
However, understanding pointers is crucial to understanding how linked lists work, so if you've skipped the pointers
tutorial, you should go back and redo it. You must also be familiar with dynamic memory allocation and structures.

Essentially, linked lists function as an array that can grow and shrink as needed, from any point in the array.

Linked lists have a few advantages over arrays:

1. Items can be added or removed from the middle of the list
2. There is no need to define an initial size

However, linked lists also have a few disadvantages:

1. There is no "random" access - it is impossible to reach the nth item in the array without first iterating over
all items up until that item. This means we have to start from the beginning of the list and count how many times
we advance in the list until we get to the desired item.
2. Dynamic memory allocation and pointers are required, which complicates the code and increases the risk of
memory leaks and segment faults.
3. Linked lists have a much larger overhead over arrays, since linked list items are dynamically allocated (which
is less efficient in memory usage) and each item in the list also must store an additional pointer.

### What is a linked list?

A linked list is a set of dynamically allocated nodes, arranged in such a way that each node contains one value
and one pointer. The pointer always points to the next member of the list. If the pointer is NULL, then it is
the last node in the list.

A linked list is held using a local pointer variable which points to the first item of the list. If that pointer
is also NULL, then the list is considered to be empty.

        ------------------------------              ------------------------------
        |              |             |            \ |              |             |
        |     DATA     |     NEXT    |--------------|     DATA     |     NEXT    |
        |              |             |            / |              |             |
        ------------------------------              ------------------------------

Let's define a linked list node:

    typedef struct node {
        int val;
        struct node * next;
    } node_t;

Notice that we are defining the struct in a recursive manner, which is possible in C. Let's name our node type `node_t`.

Now we can use the nodes. Let's create a local variable which points to the first item of the list (called `head`).

    node_t * head = NULL;
    head = (node_t *) malloc(sizeof(node_t));
    if (head == NULL) {
        return 1;
    }

    head->val = 1;
    head->next = NULL;

We've just created the first variable in the list. We must set the value, and the next item to be empty, if we want
to finish populating the list. Notice that we should always check if malloc returned a NULL value or not.

To add a variable to the end of the list, we can just continue advancing to the next pointer:

    node_t * head = NULL;
    head = (node_t *) malloc(sizeof(node_t));
    head->val = 1;
    head->next = (node_t *) malloc(sizeof(node_t));
    head->next->val = 2;
    head->next->next = NULL;

This can go on and on, but what we should actually do is advance to the last item of the list, until the `next` variable
will be `NULL`.

### Iterating over a list

Let's build a function that prints out all the items of a list. To do this, we need to use a `current` pointer
that will keep track of the node we are currently printing. After printing the value of the node, we set the `current`
pointer to the next node, and print again, until we've reached the end of the list (the next node is NULL).

    void print_list(node_t * head) {
        node_t * current = head;

        while (current != NULL) {
            printf("%d\n", current->val);
            current = current->next;
        }
    }

### Adding an item to the end of the list

To iterate over all the members of the linked list, we use a pointer called `current`. We set it to start from the head
and then in each step, we advance the pointer to the next item in the list, until we reach the last item.

    void push(node_t * head, int val) {
        node_t * current = head;
        while (current->next != NULL) {
            current = current->next;
        }

        /* now we can add a new variable */
        current->next = (node_t *) malloc(sizeof(node_t));
        current->next->val = val;
        current->next->next = NULL;
    }

The best use cases for linked lists are stacks and queues, which we will now implement:

### Adding an item to the beginning of the list (pushing to the list)

To add to the beginning of the list, we will need to do the following:

1. Create a new item and set its value
2. Link the new item to point to the head of the list
3. Set the head of the list to be our new item

This will effectively create a new head to the list with a new value, and keep the rest of the list linked to it.

Since we use a function to do this operation, we want to be able to modify the head variable. To do this, we must
pass a pointer to the pointer variable (a double pointer) so we will be able to modify the pointer itself.

    void push(node_t ** head, int val) {
        node_t * new_node;
        new_node = (node_t *) malloc(sizeof(node_t));

        new_node->val = val;
        new_node->next = *head;
        *head = new_node;
    }

### Removing the first item (popping from the list)

To pop a variable, we will need to reverse this action:

1. Take the next item that the head points to and save it
2. Free the head item
3. Set the head to be the next item that we've stored on the side

Here is the code:

    int pop(node_t ** head) {
        int retval = -1;
        node_t * next_node = NULL;

        if (*head == NULL) {
            return -1;
        }

        next_node = (*head)->next;
        retval = (*head)->val;
        free(*head);
        *head = next_node;

        return retval;
    }

### Removing the last item of the list

Removing the last item from a list is very similar to adding it to the end of the list, but with one big exception -
since we have to change one item before the last item, we actually have to look two items ahead and see if the next
item is the last one in the list:

    int remove_last(node_t * head) {
        int retval = 0;
        /* if there is only one item in the list, remove it */
        if (head->next == NULL) {
            retval = head->val;
            free(head);
            return retval;
        }

        /* get to the second to last node in the list */
        node_t * current = head;
        while (current->next->next != NULL) {
            current = current->next;
        }

        /* now current points to the second to last item of the list, so let's remove current->next */
        retval = current->next->val;
        free(current->next);
        current->next = NULL;
        return retval;

    }

### Removing a specific item

To remove a specific item from the list, either by its index from the beginning of the list or by its value, we will
need to go over all the items, continuously looking ahead to find out if we've reached the node before the item
we wish to remove. This is because we need to change the location to where the previous node points to as well.

Here is the algorithm:

1. Iterate to the node before the node we wish to delete
2. Save the node we wish to delete in a temporary pointer
3. Set the previous node's next pointer to point to the node after the node we wish to delete
4. Delete the node using the temporary pointer

There are a few edge cases we need to take care of, so make sure you understand the code.

    int remove_by_index(node_t ** head, int n) {
        int i = 0;
        int retval = -1;
        node_t * current = *head;
        node_t * temp_node = NULL;

        if (n == 0) {
            return pop(head);
        }

        for (i = 0; i < n-1; i++) {
            if (current->next == NULL) {
                return -1;
            }
            current = current->next;
        }

        if (current->next == NULL) {
            return -1;
        }

        temp_node = current->next;
        retval = temp_node->val;
        current->next = temp_node->next;
        free(temp_node);

        return retval;

    }

Exercise
--------

You must implement the function `remove_by_value` which receives a double pointer to the head and removes the first
item in the list which has the value `val`.

Tutorial Code
-------------

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct node {
        int val;
        struct node * next;
    } node_t;

    void print_list(node_t * head) {
        node_t * current = head;

        while (current != NULL) {
            printf("%d\n", current->val);
            current = current->next;
        }
    }

    int pop(node_t ** head) {
        int retval = -1;
        node_t * next_node = NULL;

        if (*head == NULL) {
            return -1;
        }

        next_node = (*head)->next;
        retval = (*head)->val;
        free(*head);
        *head = next_node;

        return retval;
    }

    int remove_by_value(node_t ** head, int val) {
        /* TODO: fill in your code here */
    }

    int main() {

        node_t * test_list = (node_t *) malloc(sizeof(node_t));
        test_list->val = 1;
        test_list->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->val = 2;
        test_list->next->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->next->val = 3;
        test_list->next->next->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->next->next->val = 4;
        test_list->next->next->next->next = NULL;

        remove_by_value(&test_list, 3);

        print_list(test_list);
    }

Expected Output
---------------

    1
    2
    4

Solution
--------

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct node {
        int val;
        struct node * next;
    } node_t;

    void print_list(node_t * head) {
        node_t * current = head;

        while (current != NULL) {
            printf("%d\n", current->val);
            current = current->next;
        }
    }

    int pop(node_t ** head) {
        int retval = -1;
        node_t * next_node = NULL;

        if (*head == NULL) {
            return -1;
        }

        next_node = (*head)->next;
        retval = (*head)->val;
        free(*head);
        *head = next_node;

        return retval;
    }

    int remove_by_value(node_t ** head, int val) {
        node_t *previous, *current;

        if (*head == NULL) {
            return -1;
        }

        if ((*head)->val == val) {
            return pop(head);
        }

        previous = *head;
        current = (*head)->next;
        while (current) {
            if (current->val == val) {
                previous->next = current->next;
                free(current);
                return val;
            }

            previous = current;
            current  = current->next;
        }
        return -1;
    }

    void delete_list(node_t *head) {
        node_t  *current = head,
                *next = head;

        while (current) {
            next = current->next;
            free(current);
            current = next;
        }
    }

    int main(void) {
        node_t * test_list = (node_t *) malloc(sizeof(node_t));

        test_list->val = 1;
        test_list->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->val = 2;
        test_list->next->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->next->val = 3;
        test_list->next->next->next = (node_t *) malloc(sizeof(node_t));
        test_list->next->next->next->val = 4;
        test_list->next->next->next->next = NULL;

        remove_by_value(&test_list, 3);

        print_list(test_list);
        delete_list(test_list);

        return EXIT_SUCCESS;
    }


text:
// flow-typed signature: b959e537a8829a43b278d18dd432d5a9
// flow-typed version: <<STUB>>/@types/react_v16.0.19/flow_v0.59.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   '@types/react'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module '@types/react' {
  declare module.exports: any;
}


text:
/*

@Name:不落阁整站模板源码
@Author:Absolutely
@Site:http://www.lyblogs.cn

*/

layui.use(['element', 'jquery', 'form', 'layedit'], function () {
    var element = layui.element();
    var form = layui.form();
    var $ = layui.jquery;
    var layedit = layui.layedit;

    //评论和留言的编辑器
    var editIndex = layedit.build('remarkEditor', {
        height: 150,
        tool: ['face', '|', 'left', 'center', 'right', '|', 'link'],
    });
    //评论和留言的编辑器的验证
    layui.form().verify({
        content: function (value) {
            value = $.trim(layedit.getText(editIndex));
            if (value == "") return "自少得有一个字吧";
            layedit.sync(editIndex);
        }
    });

    //Hash地址的定位
    var layid = location.hash.replace(/^#tabIndex=/, '');
    if (layid == "") {
        element.tabChange('tabAbout', 1);
    }
    element.tabChange('tabAbout', layid);

    element.on('tab(tabAbout)', function (elem) {
        location.hash = 'tabIndex=' + $(this).attr('lay-id');
    });

    //监听留言提交
    form.on('submit(formLeaveMessage)', function (data) {
        var index = layer.load(1);
        //模拟留言提交
        setTimeout(function () {
            layer.close(index);
            var content = data.field.editorContent;
            var html = '

模拟留言

' + content + '

2017-03-18 18:09回复

<form class="layui-form"action="">
<textarea name="replyContent"lay-verify="replyContent"placeholder="请输入回复内容"class="layui-textarea"style="min-height:80px;"></textarea>

<button class="layui-btn layui-btn-mini"lay-submit="formReply"lay-filter="formReply">提交</button>
</form>

';
            $('.blog-comment').append(html);
            $('#remarkEditor').val('');
            editIndex = layui.layedit.build('remarkEditor', {
                height: 150,
                tool: ['face', '|', 'left', 'center', 'right', '|', 'link'],
            });
            layer.msg("留言成功", { icon: 1 });
        }, 500);
        return false;
    });

    //监听留言回复提交
    form.on('submit(formReply)', function (data) {
        var index = layer.load(1);
        //模拟留言回复
        setTimeout(function () {
            layer.close(index);
            var content = data.field.replyContent;
            var html = '

模拟回复' + content + '

2017-03-18 18:26

';
            $(data.form).find('textarea').val('');
            $(data.form).parent('.replycontainer').before(html).siblings('.comment-parent').children('p').children('a').click();
            layer.msg("回复成功", { icon: 1 });
        }, 500);
        return false;
    });
});
function btnReplyClick(elem) {
    var $ = layui.jquery;
    $(elem).parent('p').parent('.comment-parent').siblings('.replycontainer').toggleClass('layui-hide');
    if ($(elem).text() == '回复') {
        $(elem).text('收起')
    } else {
        $(elem).text('回复')
    }
}
systemTime();

function systemTime() {
    //获取系统时间。
    var dateTime = new Date();
    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hh = dateTime.getHours();
    var mm = dateTime.getMinutes();
    var ss = dateTime.getSeconds();

    //分秒时间是一位数字,在数字前补0。
    mm = extra(mm);
    ss = extra(ss);

    //将时间显示到ID为time的位置,时间格式形如:19:18:02
    document.getElementById("time").innerHTML = year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
    //每隔1000ms执行方法systemTime()。
    setTimeout("systemTime()", 1000);
}

//补位函数。
function extra(x) {
    //如果传入数字小于10,数字前补一位0。
    if (x < 10) {
        return "0" + x;
    }
    else {
        return x;
    }
}


text:
package com.navercorp.pinpoint.thrift.io;

import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;

/**
 * @author koo.taejin
 */
public final class CommandHeaderTBaseDeserializerFactory implements DeserializerFactory<HeaderTBaseDeserializer> {

    private final DeserializerFactory<HeaderTBaseDeserializer> factory;

    public CommandHeaderTBaseDeserializerFactory(String version) {
        TBaseLocator commandTbaseLocator = new TCommandRegistry(TCommandTypeVersion.getVersion(version));

        TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
        HeaderTBaseDeserializerFactory deserializerFactory = new HeaderTBaseDeserializerFactory(protocolFactory, commandTbaseLocator);

        this.factory = new ThreadLocalHeaderTBaseDeserializerFactory<HeaderTBaseDeserializer>(deserializerFactory);
    }

    @Override
    public HeaderTBaseDeserializer createDeserializer() {
        return this.factory.createDeserializer();
    }

}


text:
export const repeat = (str, times) => (new Array(times + 1)).join(str);

export const pad = (num, maxLength) => repeat('0', maxLength - num.toString().length) + num;

export const formatTime = time => `${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`;

// Use performance API if it's available in order to get better precision
export const timer =
(typeof performance !== 'undefined' && performance !== null) && typeof performance.now === 'function' ?
  performance :
  Date;


text:
package play.mvc;

import play.inject.Injector;
import play.libs.typedmap.TypedKey;
import play.mvc.Http.Context;
import play.mvc.Http.Request;

import javax.inject.Inject;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;

/**
 * Defines several security helpers.
 */
public class Security {

    public static final TypedKey<String> USERNAME = TypedKey.create("username");

    /**
     * Wraps the annotated action in an {@link AuthenticatedAction}.
     */
    @With(AuthenticatedAction.class)
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Authenticated {
        Class<? extends Authenticator> value() default Authenticator.class;
    }

    /**
     * Wraps another action, allowing only authenticated HTTP requests.
     *

     * The user name is retrieved from the session cookie, and added to the HTTP request's
     * username attribute.
     */
    public static class AuthenticatedAction extends Action<Authenticated> {

        private final Function<Authenticated, Authenticator> configurator;

        @Inject
        public AuthenticatedAction(Injector injector) {
            this(authenticated -> injector.instanceOf(authenticated.value()));
        }

        public AuthenticatedAction(Authenticator authenticator) {
            this(authenticated -> authenticator);
        }

        public AuthenticatedAction(Function<Authenticated, Authenticator> configurator) {
            this.configurator = configurator;
        }

        public CompletionStage<Result> call(final Context ctx) {
            Authenticator authenticator = configurator.apply(configuration);
            String username = authenticator.getUsername(ctx);
            if (username == null) {
                Result unauthorized = authenticator.onUnauthorized(ctx);
                return CompletableFuture.completedFuture(unauthorized);
            } else {
                Request usernameReq = ctx.request().addAttr(USERNAME, username);
                Context usernameCtx = ctx.withRequest(usernameReq);
                return delegate.call(usernameCtx);
            }
        }

    }

    /**
     * Handles authentication.
     */
    public static class Authenticator extends Results {

        /**
         * Retrieves the username from the HTTP context; the default is to read from the session cookie.
         *
         * @param ctx the current request context
         * @return null if the user is not authenticated.
         */
        public String getUsername(Context ctx) {
            return ctx.session().get("username");
        }

        /**
         * Generates an alternative result if the user is not authenticated; the default a simple '401 Not Authorized' page.
         *
         * @param ctx the current request context
         * @return a 401 Not Authorized result
         */
        public Result onUnauthorized(Context ctx) {
            return unauthorized(views.html.defaultpages.unauthorized.render());
        }

    }

}


text:
require "spec_helper"

feature "Adding applications in application form" do
  background do
    i_am_logged_in
    visit "/oauth/applications/new"
  end

  scenario "adding a valid app" do
    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"

    click_button "Submit"
    i_should_see "Application created"
    i_should_see "My Application"
  end

  scenario "adding invalid app" do
    click_button "Submit"
    i_should_see "Whoops! Check your form for possible errors"
  end

  scenario "adding app ignoring bad scope" do
    config_is_set("enforce_configured_scopes", false)

    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"
    fill_in "doorkeeper_application[scopes]", with: "blahblah"

    click_button "Submit"
    i_should_see "Application created"
    i_should_see "My Application"
  end

  scenario "adding app validating bad scope" do
    config_is_set("enforce_configured_scopes", true)

    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"
    fill_in "doorkeeper_application[scopes]", with: "blahblah"

    click_button "Submit"
    i_should_see "Whoops! Check your form for possible errors"
  end

  scenario "adding app validating scope, blank scope is accepted" do
    config_is_set("enforce_configured_scopes", true)

    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"
    fill_in "doorkeeper_application[scopes]", with: ""

    click_button "Submit"
    i_should_see "Application created"
    i_should_see "My Application"
  end

  scenario "adding app validating scope, multiple scopes configured" do
    config_is_set("enforce_configured_scopes", true)
    scopes = Doorkeeper::OAuth::Scopes.from_array(%w[read write admin])
    config_is_set("optional_scopes", scopes)

    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"
    fill_in "doorkeeper_application[scopes]", with: "read write"

    click_button "Submit"
    i_should_see "Application created"
    i_should_see "My Application"
  end

  scenario "adding app validating scope, bad scope with multiple scopes configured" do
    config_is_set("enforce_configured_scopes", true)
    scopes = Doorkeeper::OAuth::Scopes.from_array(%w[read write admin])
    config_is_set("optional_scopes", scopes)

    fill_in "doorkeeper_application[name]", with: "My Application"
    fill_in "doorkeeper_application[redirect_uri]",
            with: "https://example.com"
    fill_in "doorkeeper_application[scopes]", with: "read blah"

    click_button "Submit"
    i_should_see "Whoops! Check your form for possible errors"
    i_should_see Regexp.new(
      I18n.t("activerecord.errors.models.doorkeeper/application.attributes.scopes.not_match_configured"),
      true,
    )
  end

  context "with blank redirect URI" do
    scenario "adding app with blank redirect URI when configured flows requires redirect uri" do
      config_is_set("grant_flows", %w[authorization_code implicit client_credentials])

      fill_in "doorkeeper_application[name]", with: "My Application"
      fill_in "doorkeeper_application[redirect_uri]",
              with: ""

      click_button "Submit"
      i_should_see "Whoops! Check your form for possible errors"
    end

    scenario "adding app with blank redirect URI when configured flows without redirect uri" do
      config_is_set("grant_flows", %w[client_credentials password])

      # Visit it once again to consider grant flows
      visit "/oauth/applications/new"

      i_should_see I18n.t("doorkeeper.applications.help.blank_redirect_uri")

      fill_in "doorkeeper_application[name]", with: "My Application"
      fill_in "doorkeeper_application[redirect_uri]",
              with: ""

      click_button "Submit"
      i_should_see "Application created"
      i_should_see "My Application"
    end
  end
end

feature "Listing applications" do
  background do
    i_am_logged_in

    FactoryBot.create :application, name: "Oauth Dude"
    FactoryBot.create :application, name: "Awesome App"
  end

  scenario "application list" do
    visit "/oauth/applications"

    i_should_see "Awesome App"
    i_should_see "Oauth Dude"
  end
end

feature "Renders assets" do
  scenario "admin stylesheets" do
    visit "/assets/doorkeeper/admin/application.css"

    i_should_see "Bootstrap"
    i_should_see ".doorkeeper-admin"
  end

  scenario "application stylesheets" do
    visit "/assets/doorkeeper/application.css"

    i_should_see "Bootstrap"
    i_should_see "#oauth-permissions"
    i_should_see "#container"
  end
end

feature "Show application" do
  given :app do
    i_am_logged_in

    FactoryBot.create :application, name: "Just another oauth app"
  end

  scenario "visiting application page" do
    visit "/oauth/applications/#{app.id}"

    i_should_see "Just another oauth app"
  end
end

feature "Edit application" do
  let :app do
    FactoryBot.create :application, name: "OMG my app"
  end

  background do
    i_am_logged_in

    visit "/oauth/applications/#{app.id}/edit"
  end

  scenario "updating a valid app" do
    fill_in "doorkeeper_application[name]", with: "Serious app"
    click_button "Submit"

    i_should_see "Application updated"
    i_should_see "Serious app"
    i_should_not_see "OMG my app"
  end

  scenario "updating an invalid app" do
    fill_in "doorkeeper_application[name]", with: ""
    click_button "Submit"

    i_should_see "Whoops! Check your form for possible errors"
  end
end

feature "Remove application" do
  background do
    i_am_logged_in

    @app = FactoryBot.create :application
  end

  scenario "deleting an application from list" do
    visit "/oauth/applications"

    i_should_see @app.name

    within(:css, "tr#application_#{@app.id}") do
      click_button "Destroy"
    end

    i_should_see "Application deleted"
    i_should_not_see @app.name
  end

  scenario "deleting an application from show" do
    visit "/oauth/applications/#{@app.id}"
    click_button "Destroy"

    i_should_see "Application deleted"
  end
end

context "when admin authenticator block is default" do
  let(:app) { FactoryBot.create :application, name: "app" }

  feature "application list" do
    scenario "fails with forbidden" do
      visit "/oauth/applications"

      should_have_status 403
    end
  end

  feature "adding an app" do
    scenario "fails with forbidden" do
      visit "/oauth/applications/new"

      should_have_status 403
    end
  end

  feature "editing an app" do
    scenario "fails with forbidden" do
      visit "/oauth/applications/#{app.id}/edit"

      should_have_status 403
    end
  end
end


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\event;

defined('MOODLE_INTERNAL') || die();

/**
 * Course content deleted event class.
 *
 * @property-read array $other {
 *      Extra information about event.
 *
 *      - array options: list of options which were skipped while deleting course content.
 * }
 *
 * @package    core
 * @since      Moodle 2.6
 * @copyright  2013 Mark Nelson <markn@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class course_content_deleted extends base {

    /**
     * Initialise the event data.
     */
    protected function init() {
        $this->data['objecttable'] = 'course';
        $this->data['crud'] = 'd';
        $this->data['edulevel'] = self::LEVEL_TEACHING;
    }

    /**
     * Returns localised general event name.
     *
     * @return string
     */
    public static function get_name() {
        return get_string('eventcoursecontentdeleted');
    }

    /**
     * Returns non-localised description of what happened.
     *
     * @return string
     */
    public function get_description() {
        return "The user with id '$this->userid' deleted content from course with id '$this->courseid'.";
    }

    /**
     * Returns the name of the legacy event.
     *
     * @return string legacy event name
     */
    public static function get_legacy_eventname() {
        return 'course_content_removed';
    }

    /**
     * Returns the legacy event data.
     *
     * @return \stdClass the course the content was deleted from
     */
    protected function get_legacy_eventdata() {
        $course = $this->get_record_snapshot('course', $this->objectid);
        $course->context = $this->context;
        $course->options = $this->other['options'];

        return $course;
    }

    /**
     * Custom validation.
     *
     * @throws \coding_exception
     * @return void
     */
    protected function validate_data() {
        parent::validate_data();

        if (!isset($this->other['options'])) {
            throw new \coding_exception('The \'options\' value must be set in other.');
        }
    }
}


text:
package math

import (
	"testing"

	"github.com/cosiner/gohper/testing2"
)

func TestIndexDistance(t *testing.T) {
	tt := testing2.Wrap(t)
	index, indexUsed, remains := SegmentIndex([]int{2, 3}, 6)
	tt.Eq(-1, index)
	tt.Eq(0, indexUsed)
	tt.Eq(-1, remains)
}