text:
"""
sentry.testutils.cases
~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

from __future__ import absolute_import

__all__ = (
    'TestCase', 'TransactionTestCase', 'APITestCase', 'AuthProviderTestCase',
    'RuleTestCase', 'PermissionTestCase', 'PluginTestCase'
)

import base64
import os.path
import urllib

from django.conf import settings
from django.contrib.auth import login
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.http import HttpRequest
from django.test import TestCase, TransactionTestCase
from django.utils.importlib import import_module
from exam import before, Exam
from nydus.db import create_cluster
from rest_framework.test import APITestCase as BaseAPITestCase

from sentry import auth
from sentry.auth.providers.dummy import DummyProvider
from sentry.constants import MODULE_ROOT
from sentry.models import GroupMeta, OrganizationMemberType, ProjectOption
from sentry.plugins import plugins
from sentry.rules import EventState
from sentry.utils import json

from .fixtures import Fixtures
from .helpers import AuthProvider, Feature, get_auth_header

def create_redis_conn():
    options = {
        'engine': 'nydus.db.backends.redis.Redis',
    }
    options.update(settings.SENTRY_REDIS_OPTIONS)

    return create_cluster(options)

_redis_conn = create_redis_conn()

def flush_redis():
    _redis_conn.flushdb()

class BaseTestCase(Fixtures, Exam):
    urls = 'tests.sentry.web.urls'

    def assertRequiresAuthentication(self, path, method='GET'):
        resp = getattr(self.client, method.lower())(path)
        assert resp.status_code == 302
        assert resp['Location'].startswith('http://testserver' + reverse('sentry-login'))

    @before
    def setup_session(self):
        engine = import_module(settings.SESSION_ENGINE)

        session = engine.SessionStore()
        session.save()

        self.session = session

    def feature(self, name, active=True):
        """
        >>> with self.feature('feature:name')
        >>>     # ...
        """
        return Feature(name, active)

    def auth_provider(self, name, cls):
        """
        >>> with self.auth_provider('name', Provider)
        >>>     # ...
        """
        return AuthProvider(name, cls)

    def save_session(self):
        self.session.save()

        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }

        session_cookie = settings.SESSION_COOKIE_NAME
        self.client.cookies[session_cookie] = self.session.session_key
        self.client.cookies[session_cookie].update(cookie_data)

    def login_as(self, user):
        user.backend = settings.AUTHENTICATION_BACKENDS[0]

        request = HttpRequest()
        request.session = self.session

        login(request, user)
        request.user = user

        # Save the session values.
        self.save_session()

    def load_fixture(self, filepath):
        filepath = os.path.join(
            MODULE_ROOT,
            'tests',
            'fixtures',
            filepath,
        )
        with open(filepath, 'rb') as fp:
            return fp.read()

    def _pre_setup(self):
        super(BaseTestCase, self)._pre_setup()

        cache.clear()
        ProjectOption.objects.clear_local_cache()
        GroupMeta.objects.clear_local_cache()

    def _post_teardown(self):
        super(BaseTestCase, self)._post_teardown()

        flush_redis()

    def _makeMessage(self, data):
        return json.dumps(data)

    def _makePostMessage(self, data):
        return base64.b64encode(self._makeMessage(data))

    def _postWithHeader(self, data, key=None, secret=None):
        if key is None:
            key = self.projectkey.public_key
            secret = self.projectkey.secret_key

        message = self._makePostMessage(data)
        with self.settings(CELERY_ALWAYS_EAGER=True):
            resp = self.client.post(
                reverse('sentry-api-store'), message,
                content_type='application/octet-stream',
                HTTP_X_SENTRY_AUTH=get_auth_header('_postWithHeader', key, secret),
            )
        return resp

    def _getWithReferer(self, data, key=None, referer='getsentry.com', protocol='4'):
        if key is None:
            key = self.projectkey.public_key

        headers = {}
        if referer is not None:
            headers['HTTP_REFERER'] = referer

        message = self._makeMessage(data)
        qs = {
            'sentry_version': protocol,
            'sentry_client': 'raven-js/lol',
            'sentry_key': key,
            'sentry_data': message,
        }
        with self.settings(CELERY_ALWAYS_EAGER=True):
            resp = self.client.get(
                '%s?%s' % (reverse('sentry-api-store', args=(self.project.pk,)), urllib.urlencode(qs)),
                **headers
            )
        return resp

    _postWithSignature = _postWithHeader
    _postWithNewSignature = _postWithHeader

class TestCase(BaseTestCase, TestCase):
    pass

class TransactionTestCase(BaseTestCase, TransactionTestCase):
    pass

class APITestCase(BaseTestCase, BaseAPITestCase):
    pass

class AuthProviderTestCase(TestCase):
    provider = DummyProvider
    provider_name = 'dummy'

    def setUp(self):
        super(AuthProviderTestCase, self).setUp()
        auth.register(self.provider_name, self.provider)
        self.addCleanup(auth.unregister, self.provider_name, self.provider)

class RuleTestCase(TestCase):
    rule_cls = None

    def get_event(self):
        return self.event

    def get_rule(self, data=None):
        return self.rule_cls(
            project=self.project,
            data=data or {},
        )

    def get_state(self, **kwargs):
        kwargs.setdefault('is_new', True)
        kwargs.setdefault('is_regression', True)
        kwargs.setdefault('is_sample', True)
        kwargs.setdefault('rule_is_active', False)
        kwargs.setdefault('rule_last_active', None)
        return EventState(**kwargs)

    def assertPasses(self, rule, event=None, **kwargs):
        if event is None:
            event = self.event
        state = self.get_state(**kwargs)
        assert rule.passes(event, state) is True

    def assertDoesNotPass(self, rule, event=None, **kwargs):
        if event is None:
            event = self.event
        state = self.get_state(**kwargs)
        assert rule.passes(event, state) is False

class PermissionTestCase(TestCase):
    def setUp(self):
        super(PermissionTestCase, self).setUp()
        self.owner = self.create_user()
        self.organization = self.create_organization(owner=self.owner)
        self.team = self.create_team(organization=self.organization)

    def assert_can_access(self, user, path, method='GET'):
        self.login_as(user)
        resp = getattr(self.client, method.lower())(path)
        assert resp.status_code >= 200 and resp.status_code < 300

    def assert_cannot_access(self, user, path, method='GET'):
        self.login_as(user)
        resp = getattr(self.client, method.lower())(path)
        assert resp.status_code >= 300

    def assert_team_member_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
        )

        self.assert_can_access(user, path)

    def assert_org_member_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
        )

        self.assert_can_access(user, path)

    def assert_teamless_member_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
        )

        self.assert_can_access(user, path)

    def assert_team_member_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
        )

        self.assert_cannot_access(user, path)

    def assert_org_member_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
        )

        self.assert_cannot_access(user, path)

    def assert_teamless_member_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
        )

        self.assert_cannot_access(user, path)

    def assert_team_admin_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_can_access(user, path)

    def assert_org_admin_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_can_access(user, path)

    def assert_teamless_admin_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_can_access(user, path)

    def assert_team_admin_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_cannot_access(user, path)

    def assert_org_admin_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_cannot_access(user, path)

    def assert_teamless_admin_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
            type=OrganizationMemberType.ADMIN,
        )

        self.assert_cannot_access(user, path)

    def assert_team_owner_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
            type=OrganizationMemberType.OWNER,
        )

        self.assert_can_access(user, path)

    def assert_org_owner_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
            type=OrganizationMemberType.OWNER,
        )

        self.assert_can_access(user, path)

    def assert_teamless_owner_can_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
            type=OrganizationMemberType.OWNER,
        )

        self.assert_can_access(user, path)

    def assert_team_owner_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False, teams=[self.team],
            type=OrganizationMemberType.OWNER,
        )

        self.assert_cannot_access(user, path)

    def assert_org_owner_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=True,
            type=OrganizationMemberType.OWNER,
        )

        self.assert_cannot_access(user, path)

    def assert_teamless_owner_cannot_access(self, path):
        user = self.create_user()
        self.create_member(
            user=user, organization=self.organization,
            has_global_access=False,
            type=OrganizationMemberType.OWNER,
        )

        self.assert_cannot_access(user, path)

    def assert_non_member_cannot_access(self, path):
        user = self.create_user()
        self.assert_cannot_access(user, path)

class PluginTestCase(TestCase):
    plugin = None

    def setUp(self):
        super(PluginTestCase, self).setUp()
        plugins.register(self.plugin)
        self.addCleanup(plugins.unregister, self.plugin)


text:
package org.eclipse.californium.core.network.serialization;

import static org.eclipse.californium.core.coap.CoAP.MessageFormat.CODE_BITS;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.EMPTY_CODE;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.MESSAGE_ID_BITS;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.PAYLOAD_MARKER;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.REQUEST_CODE_LOWER_BOUND;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.REQUEST_CODE_UPPER_BOUNT;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.RESPONSE_CODE_LOWER_BOUND;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.RESPONSE_CODE_UPPER_BOUND;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.TOKEN_LENGTH_BITS;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.TYPE_BITS;
import static org.eclipse.californium.core.coap.CoAP.MessageFormat.VERSION_BITS;

import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.EmptyMessage;
import org.eclipse.californium.core.coap.Message;
import org.eclipse.californium.core.coap.Option;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.coap.CoAP.Code;
import org.eclipse.californium.core.coap.CoAP.ResponseCode;
import org.eclipse.californium.core.coap.CoAP.Type;

/**
 * The DataParser parses incoming byte arrays to messages.
 */
public class DataParser {

	private DatagramReader reader;

	private int version;
	private int type;
	private int tokenlength;
	private int code;
	private int mid;

	public DataParser(byte[] bytes) {
		setBytes(bytes);
	}

	public void setBytes(byte[] bytes) {
		this.reader = new DatagramReader(bytes);
		this.version = reader.read(VERSION_BITS);
		this.type = reader.read(TYPE_BITS);
		this.tokenlength = reader.read(TOKEN_LENGTH_BITS);
		this.code = reader.read(CODE_BITS);
		this.mid = reader.read(MESSAGE_ID_BITS);
	}

	public boolean isWellFormed() {
		return version == CoAP.VERSION;
	}

	public int getVersion() {
		return version;
	}

	public int getMID() {
		return mid;
	}

	public boolean isReply() {
		return type > Type.NON.value;
	}

	public boolean isRequest() {
		return code >= REQUEST_CODE_LOWER_BOUND &&
				code <= REQUEST_CODE_UPPER_BOUNT;
	}

	public boolean isResponse() {
		return code >= RESPONSE_CODE_LOWER_BOUND &&
				code <= RESPONSE_CODE_UPPER_BOUND;
	}

	public boolean isEmpty() {
		return code == EMPTY_CODE;
	}

	public Request parseRequest() {
		assert(isRequest());
		Request request = new Request(Code.valueOf(code));
		parseMessage(request);
		return request;
	}

	public Response parseResponse() {
		assert(isResponse());
		Response response = new Response(ResponseCode.valueOf(code));
		parseMessage(response);
		return response;
	}

	public EmptyMessage parseEmptyMessage() {
		assert(!isRequest() && !isResponse());
		EmptyMessage message = new EmptyMessage(Type.valueOf(type));
		parseMessage(message);
		return message;
	}

	private void parseMessage(Message message) {
		message.setType(Type.valueOf(type));
		message.setMID(mid);

		if (tokenlength>0) {
			message.setToken(reader.readBytes(tokenlength));
		} else {
			message.setToken(new byte[0]);
		}

		int currentOption = 0;
		byte nextByte = 0;
		while(reader.bytesAvailable()) {
			nextByte = reader.readNextByte();
			if (nextByte != PAYLOAD_MARKER) {
				// the first 4 bits of the byte represent the option delta
				int optionDeltaNibble = (0xF0 & nextByte) >> 4;
				currentOption += readOptionValueFromNibble(optionDeltaNibble);

				// the second 4 bits represent the option length
				int optionLengthNibble = (0x0F & nextByte);
				int optionLength = readOptionValueFromNibble(optionLengthNibble);

				// read option
				Option option = new Option(currentOption);
				option.setValue(reader.readBytes(optionLength));

				// add option to message
				message.getOptions().addOption(option);
			} else break;
		}

		if (nextByte == PAYLOAD_MARKER) {
			// the presence of a marker followed by a zero-length payload must be processed as a message format error
			if (!reader.bytesAvailable())
				throw new IllegalStateException();

			// get payload
			message.setPayload(reader.readBytesLeft());
		} else {
			message.setPayload(new byte[0]); // or null?
		}
	}

	/**
	 * Calculates the value used in the extended option fields as specified in
	 * RFC 7252, Section 3.1
	 *
	 * @param nibble
	 *            the 4-bit option header value.
	 * @param datagram
	 *            the datagram.
	 * @return the value calculated from the nibble and the extended option
	 *         value.
	 */
	private int readOptionValueFromNibble(int nibble) {
		if (nibble <= 12) {
			return nibble;
		} else if (nibble == 13) {
			return reader.read(8) + 13;
		} else if (nibble == 14) {
			return reader.read(16) + 269;
		} else {
			throw new IllegalArgumentException("Unsupported option delta "+nibble);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { createStore, combineReducers, applyMiddleware, compose } from "redux";

import StoreMixin from "#SRC/js/mixins/StoreMixin";
import pluginsList from "#PLUGINS";

import {
  APPLICATION,
  PLUGIN_LOAD_TIMEOUT,
} from "#SRC/js/constants/PluginConstants";
import { APP_STORE_CHANGE } from "../constants/EventTypes";
import ActionsPubSub from "./middleware/ActionsPubSub";
import AppReducer from "./AppReducer";
import AppHooks from "./AppHooks";
import Config from "../config/Config";
import HooksMod from "./Hooks";
import Loader from "./Loader";

const hooks = HooksMod();
const initialState = {};
const middleware = [ActionsPubSub.pub];
const PLUGIN_ENV_CACHE = [];
const REGISTERED_ACTIONS = {};
const existingFluxStores = {};

const constants = {
  APPLICATION,
  APP_STORE_CHANGE,
};

const reducers = {
  [APPLICATION]: AppReducer,
};

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

/**
 * Add reducer to Store (only available in test mode so we can test plugins
 * that rely on State)
 * @param {String} pluginID - Plugin ID
 * @param  {Function} reducer - A reducer
 */
const __addReducer = (pluginID, reducer) => {
  addPluginReducer(reducer, pluginID);
  replaceStoreReducers();
};

// Create Redux Store
export const Store = createStore(
  combineReducers(reducers),
  initialState,
  composeEnhancers(applyMiddleware(...middleware))
);

/**
 * Bootstraps plugins and adds new reducers to Store.
 *
 * @param {Object} pluginsConfig - Plugin configuration
 */
const initialize = (pluginsConfig) => {
  Object.keys(pluginsConfig).forEach((pluginID) => {
    // Make sure plugin is bundled
    if (!(pluginID in pluginsList)) {
      if (Config.environment === "development") {
        console.warn(`Plugin ${pluginID} not available in bundle`);
      }

      return;
    }

    // Bootstrap if plugin enabled
    if (pluginsConfig[pluginID] && pluginsConfig[pluginID].enabled) {
      bootstrapPlugin(pluginID, pluginsList[pluginID], pluginsConfig[pluginID]);
    }
  });

  replaceStoreReducers();

  // Allows plugins to do things before the application ever renders
  const promises = hooks.applyFilter("pluginsLoadedCheck", []);
  let pluginsLoaded = false;

  Promise.all(promises).then(() => {
    pluginsLoaded = true;
    hooks.doAction("pluginsConfigured");
  });

  window.setTimeout(() => {
    if (!pluginsLoaded) {
      if (process.env.NODE_ENV === "development") {
        console.warn("Failed to load plugins.");
      }
    }
  }, PLUGIN_LOAD_TIMEOUT);
};

/**
 * Builds Actions API for registerActions and getActions.
 * Get Actions automatically instantiates actions module with
 * the requesting Plugin's SDK so dispatch is bound to the requesting Plugin.
 * @param  {PluginSDK} SDK - PluginSDK
 * @return {Object}     - API for registering/requesting actions
 */
const getActionsAPI = (SDK) => ({
  registerActions(actions, name) {
    if (SDK.pluginID in REGISTERED_ACTIONS) {
      throw new Error(`${SDK.pluginID} already has registered actions.`);
    }
    // Allow Application to name it's actions. Plugins have actions
    // registered under their pluginID
    if (SDK.pluginID !== APPLICATION) {
      name = SDK.pluginID;
    }
    REGISTERED_ACTIONS[name] = actions;
  },

  getActions(name, defaultValue) {
    if (!name || typeof name !== "string") {
      throw new Error(`Name not valid. Passed in ${name}`);
    }
    // Return Actions instantiated with SDK.
    // Actions will now use Plugin's own dispatch
    if (!REGISTERED_ACTIONS[name]) {
      if (defaultValue !== undefined) {
        return defaultValue;
      }
      throw Error(
        `No registered actions for ${name}. Make sure plugin is loaded or actions are registered`
      );
    }

    return REGISTERED_ACTIONS[name];
  },
});

/**
 * Create a flux store that exposes events to components. This store
 * does not support set methods. It provides an abstraction for handling
 * state changes in the OmniStore.
 * @param  {Object} definition - Store definition
 * @return {Object}            - Created store
 */
const addStoreConfig = (definition) => {
  if (definition) {
    if (!definition.storeID) {
      throw new Error("Must define a valid storeID to expose events");
    }
    if (definition.storeID in existingFluxStores) {
      throw new Error(`Store with ID ${definition.storeID} already exists.`);
    }
    existingFluxStores[definition.storeID] = definition;
    // Register events with StoreMixin. Only import this as needed
    // because its presence will degrade test performance.
    StoreMixin.store_configure(existingFluxStores);
  }

  return definition;
};

/**
 * Return a slice of the State
 * @param  {String} root - root of the slice to return
 * @return {Function}      Returns state at root
 */
const getStateRootedAt = (root) => () => Store.getState()[root];

/**
 * Extends the PluginSDK
 * @param  {PluginSDK} SDK - SDK to extend
 * @param  {Object} obj  - Key value pairs to be added to SDK
 */
const extendSDK = (SDK, obj) => {
  Object.keys(obj).forEach((methodName) => {
    SDK[methodName] = obj[methodName].bind(SDK);
  });
};

/**
 * Builds SDK for pluginID
 * @param  {String} pluginID - ID for plugin
 * @param  {Object} config   - Config
 * @return {PluginSDK}       - SDK for plugins
 */
const getSDK = (pluginID, config) => {
  if (pluginID in PLUGIN_ENV_CACHE) {
    return PLUGIN_ENV_CACHE[pluginID];
  }

  let StoreAPI = Store;

  if (pluginID !== APPLICATION) {
    // Limit access for Plugins
    StoreAPI = {
      subscribe: Store.subscribe.bind(Store),
      getState: Store.getState.bind(Store),
      getOwnState: getStateRootedAt(pluginID),
      getAppState: getStateRootedAt(APPLICATION),
    };
  }

  const SDK = {
    addStoreConfig,
    constants,
    onDispatch,
    pluginID,
    config: config || {},
    dispatch: Store.dispatch,
    Hooks: hooks,
    Store: StoreAPI,
    initialize,

    // helpers for testing
    __getSDK: getSDK,
    __addReducer,
  };

  extendSDK(SDK, getActionsAPI(SDK));

  PLUGIN_ENV_CACHE[pluginID] = SDK;

  return SDK;
};

/**
 * Bootstraps a plugin
 *
 * @param  {String} pluginID   Plugin's pluginID from config
 * @param  {Module} plugin Plugin module or path to entry point within plugins directory
 * @param  {Object} config Plugin configuration
 */
const bootstrapPlugin = (pluginID, plugin, config) => {
  // Inject Application key constant and configOptions if specified
  const SDK = getSDK(pluginID, config);

  const pluginReducer = plugin(SDK);

  // If plugin exported a reducer, add it to the reducers object
  if (pluginReducer) {
    addPluginReducer(pluginReducer, pluginID);
  }
};

/**
 * Adds a plugin's reducer to the reducers Object
 *
 * @param {Function} reducer    Reducer function to manage plugins state in Store
 * @param {String} pluginID     Plugin's ID
 */
const addPluginReducer = (reducer, pluginID) => {
  if (typeof reducer !== "function") {
    throw new Error(`Reducer for ${pluginID} must be a function`);
  }
  reducers[pluginID] = reducer;
};

/**
 * Replace reducers in Store
 */
const replaceStoreReducers = () => {
  // Replace all store reducers now that we have all plugin reducers
  Store.replaceReducer(combineReducers(reducers));
};

/**
 * Register a callback to be invoked for every dispatched action
 * @param  {Function} callback - Function invoked with action as argument for all dispatched Actions.
 * @returns {Function} - unsubscribe
 */
const onDispatch = (
  callback // Add ability to react to actions outside of a reducer.
) =>
  // This will most likely be deprecated at some point but for now it gives
  // us backwards compatibility with much of our existing dispatcher code
  ActionsPubSub.sub(callback);

// Subscribe to Store config change and call initialize with
// new plugin configuration
const unSubscribe = Store.subscribe(() => {
  const configStore = Store.getState()[APPLICATION].config;
  if (configStore && configStore.config && configStore.config.uiConfiguration) {
    // unsubscribe once we have the config
    unSubscribe();
    initialize(configStore.config.uiConfiguration.plugins);
  }
});

// Lets get an SDK for the Application
const ApplicationSDK = getSDK(APPLICATION, Config);
// Register our Actions
AppHooks.initialize(ApplicationSDK);

export default ApplicationSDK;
export const Hooks = ApplicationSDK.Hooks;


text:
abstract class A {
  private void condition(boolean flag) {
    return flag ? foo()<caret> : bar();
  }

  abstract B foo();
  abstract C bar();

  interface B {}
  interface C extends B {}

}


text:
package com.chinatelecom.myctu.upnsa.core.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Utility class for Json
 * User: snowway
 * Date: 11/2/13
 * Time: 10:30 PM
 */
public class JsonUtils {

    /**
     * 将JSONObject对象转换成Map
     *
     * @param object
     * @return
     * @throws JSONException
     */
    public static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap();
        Iterator keys = object.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, fromJson(object.get(key)));
        }
        return map;
    }

    /**
     * 将JSONArray对象转换成List
     * @param array
     * @return
     * @throws JSONException
     */
    public static List toList(JSONArray array) throws JSONException {
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++) {
            list.add(fromJson(array.get(i)));
        }
        return list;
    }

    private static Object fromJson(Object json) throws JSONException {
        if (json instanceof JSONObject) {
            return toMap((JSONObject) json);
        } else if (json instanceof JSONArray) {
            return toList((JSONArray) json);
        } else {
            return json;
        }
    }
}


text:
* [BUGFIX] Fix [RangeError: Maximum call stack size exceeded] error in PubSub hook
* [ENHANCEMENT] Support layout for Ractive template engine

### 0.11.0

* [ENHANCEMENT] Allow hooks to be installed in node_modules and dynamic changing of hook name
* [ENHANCEMENT] Pull out the `sockets` hook to its own repository
* [ENHANCEMENT] Allow hooks to have individual timeouts, and a global `sails.config.hookTimeout`
* [ENHANCEMENT] Pull out `sails.io`.js to its own generator
* [UPGRADE] Update `sails.io.js` for the latest version of the sockets hook
* [UPGRADE] Upgrade from Socket.IO 0.9.17 to 1.2.1
* [FEATURE] Add `restPrefix` setting in addition to `prefix` setting for blueprints for finer control
* [ENHANCEMENT] Support partials and layout with Handlebars for the `backend` generator
* [BUGFIX] Blueprint creation returns 201 status code instead of 200
* [BUGFIX] `ractive.toHTML()` replaces `ractive.renderHTML()` for Ractive template engine
* [BUGFIX] Fix arguments for publishAdd, publishRemove and publishUpdate
* [ENHANCEMENT] Enable views hook for all methods
* [BUGFIX] Resolve depreciation warnings
* [BUGFIX] Fix dependency for npm 2.0.0
* [BUGFIX] Fix Grunt launching when it's a peer dep
* [ENHANCEMENT] Upgrade express and skipper because of security vulnerabilities
* [BUGFIX] Fix Sails crashes if Redis goes down [#2277](https://github.com/balderdashy/sails/pull/2277)
* [BUGFIX] Fix crash when using sessionless requests over WebSockets [#2107](https://github.com/balderdashy/sails/pull/2107)
* [ENHANCEMENT] Checking npm-version on install
* [ENHANCEMENT] Updated "skipAssets" regex to ignore query string

### 0.10.5

* [ENHANCEMENT] Updated `waterline` to `~0.10.9`
* [ENHANCEMENT] Added new `routesDisabled` option for CSRF [#2121](https://github.com/balderdashy/sails/pull/2121)
* [ENHANCEMENT] Refactoring and cleanup.
* [ENHANCEMENT] Switched from `express3-handlebars` to `express-handlebars`
* [BUGFIX] Add missing require for async module [#2101](https://github.com/balderdashy/sails/pull/2101)


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'UserNotices.notice_cattype'
        db.add_column('myuw_mobile_usernotices', 'notice_cattype',
                      self.gf('django.db.models.fields.CharField')(max_length=256, null=True, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'UserNotices.notice_cattype'
        db.delete_column('myuw_mobile_usernotices', 'notice_cattype')

    models = {
        'myuw.building': {
            'Meta': {'object_name': 'Building', 'db_table': "'myuw_mobile_building'"},
            'code': ('django.db.models.fields.CharField', [], {'max_length': '6', 'db_index': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latititude': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
            'longitude': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
        },
        u'myuw.categorylinks': {
            'Meta': {'object_name': 'CategoryLinks', 'db_table': "'myuw_mobile_categorylinks'"},
            'campus': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True'}),
            'category_id': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            'category_name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'new_tab': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'sub_category': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
            'url': ('django.db.models.fields.CharField', [], {'max_length': '150'})
        },
        u'myuw.coursecolor': {
            'Meta': {'object_name': 'CourseColor', 'db_table': "'myuw_mobile_coursecolor'"},
            'color_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
            'course_number': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
            'curriculum_abbr': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {}),
            'quarter': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}),
            'regid': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
            'section_id': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
            'year': ('django.db.models.fields.PositiveSmallIntegerField', [], {'db_index': 'True'})
        },
        u'myuw.seenregistration': {
            'Meta': {'object_name': 'SeenRegistration', 'db_table': "'myuw_mobile_seenregistration'"},
            'first_seen_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'quarter': ('django.db.models.fields.CharField', [], {'max_length': '10', 'db_index': 'True'}),
            'summer_term': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['myuw.User']", 'on_delete': 'models.PROTECT'}),
            'year': ('django.db.models.fields.PositiveSmallIntegerField', [], {'db_index': 'True'})
        },
        u'myuw.studentaccountsbalances': {
            'Meta': {'object_name': 'StudentAccountsBalances', 'db_table': "'myuw_mobile_studentaccountsbalances'"},
            'asof_datetime': ('django.db.models.fields.DateTimeField', [], {}),
            'employee_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '10', 'null': 'True', 'blank': 'True'}),
            'husky_card': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '6', 'decimal_places': '2'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_am': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'residence_hall_dining': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '7', 'decimal_places': '2', 'blank': 'True'}),
            'student_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10', 'db_index': 'True'})
        },
        u'myuw.tuitiondate': {
            'Meta': {'object_name': 'TuitionDate', 'db_table': "'myuw_mobile_tuitiondate'"},
            'date': ('django.db.models.fields.DateField', [], {}),
            'date_stored': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['myuw.User']", 'unique': 'True', 'on_delete': 'models.PROTECT'})
        },
        u'myuw.user': {
            'Meta': {'object_name': 'User', 'db_table': "'myuw_mobile_user'"},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_visit': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2015, 9, 5, 0, 0)'}),
            'uwnetid': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '16'}),
            'uwregid': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True', 'db_index': 'True'})
        },
        u'myuw.usermigrationpreference': {
            'Meta': {'object_name': 'UserMigrationPreference'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'use_legacy_site': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'})
        },
        u'myuw.usernotices': {
            'Meta': {'unique_together': "(('notice_hash', 'user'),)", 'object_name': 'UserNotices', 'db_table': "'myuw_mobile_usernotices'"},
            'first_viewed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'marked_read': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'notice_cattype': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
            'notice_hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['myuw.User']", 'on_delete': 'models.PROTECT'})
        }
    }

    complete_apps = ['myuw']


text:
const cleanDatabase = require('./clean_database');
const createPosts = require('./create_posts');
const createPost = require('./create_post');
const getPostById = require('./get_post_by_id');

module.exports = {
  cleanDatabase,
  createPosts,
  createPost,
  getPostById,
};


text:
package org.locationtech.geowave.core.store.query.aggregate;

import java.math.BigDecimal;
import java.nio.ByteBuffer;
import org.locationtech.geowave.core.index.VarintUtils;
import org.locationtech.geowave.core.store.api.Aggregation;
import org.locationtech.geowave.core.store.api.DataTypeAdapter;

/**
 * Base aggregation class for performing math operations on numeric attributes. It uses BigDecimal
 * due to it being the most precise numeric attribute possible.
 */
public abstract class FieldMathAggregation<T> implements
    Aggregation<FieldNameParam, BigDecimal, T> {
  private FieldNameParam fieldNameParam;
  private BigDecimal value = null;

  public FieldMathAggregation() {
    this(null);
  }

  public FieldMathAggregation(final FieldNameParam fieldNameParam) {
    super();
    this.fieldNameParam = fieldNameParam;
  }

  @Override
  public FieldNameParam getParameters() {
    return fieldNameParam;
  }

  @Override
  public void setParameters(final FieldNameParam fieldNameParam) {
    this.fieldNameParam = fieldNameParam;
  }

  @Override
  public BigDecimal getResult() {
    return value;
  }

  @Override
  public BigDecimal merge(final BigDecimal result1, final BigDecimal result2) {
    return agg(result1, result2);
  }

  @Override
  public byte[] resultToBinary(BigDecimal result) {
    return VarintUtils.writeBigDecimal(result);
  }

  @Override
  public BigDecimal resultFromBinary(byte[] binary) {
    return VarintUtils.readBigDecimal(ByteBuffer.wrap(binary));
  }

  @Override
  public void clearResult() {
    value = null;
  }

  @Override
  public void aggregate(final DataTypeAdapter<T> adapter, T entry) {
    Object o;
    if ((fieldNameParam != null) && !fieldNameParam.isEmpty()) {
      o = adapter.getFieldValue(entry, fieldNameParam.getFieldName());
      if (o instanceof Number) {
        value = agg(value, new BigDecimal(o.toString()));
      }
    }
  }

  protected abstract BigDecimal agg(final BigDecimal a, final BigDecimal b);

}


text:
main_page::main_page(QWidget *parent, QWidget * context) :
    QWidget(parent),
    ui(new Ui::main_page)
{
    ui->setupUi(parent);
    xiamiapi::IGenericArray *recommend_list;
    this->context = context;
    auto api = ((MainWindow *)(context))->api;
    api->GetRecommendCollection(&recommend_list);
    std::vector<CarouselCollectionModelObject> list_data;
    for (uint64_t i = 0; i < recommend_list->length(); ++i)
    {
        xiamiapi::IXiamiCollectionInfo* info;
        recommend_list->get_element(i)->QueryInterface(recommend_list->ElementIID(), (void **)&info);
        std::string logo = info->get_logo();
        // logo.replace(logo.rfind("_1"), 2, "_5");
        list_data.push_back(CarouselCollectionModelObject{info->get_list_id(), logo.c_str(), info->get_collect_name()});
        info->Release();
    }
    recommend_list->Release();
    QQuickView *view = new QQuickView();

    CarouselCollectionListViewModel * model = new CarouselCollectionListViewModel(parent);
    model->setItem(std::move(list_data));

    QQmlContext* ctxt = view->rootContext();
    ctxt->setContextProperty("collectionModel", model);

    api->GetRecommendPlaylist(&recommend_list);
    std::vector<CarouselCollectionModelObject> playlist_data;
    for (uint64_t i = 0; i < recommend_list->length(); ++i)
    {
        xiamiapi::IXiamiPlaylistInfo* info;
        recommend_list->get_element(i)->QueryInterface(recommend_list->ElementIID(), (void **)&info);
        std::string logo = info->get_album_logo();
        logo.replace(logo.rfind("_1"), 2, "_5");
        playlist_data.push_back(CarouselCollectionModelObject{info->get_album_id(), logo.c_str(), info->get_album_name()});
        info->Release();
    }
    CarouselCollectionListViewModel * album_model = new CarouselCollectionListViewModel(parent);
    album_model->setItem(std::move(playlist_data));
    ctxt->setContextProperty("albumModel", album_model);

    view->setSource(QUrl("qrc:/carousel.qml"));
    QWidget *container = QWidget::createWindowContainer(view, this);
    QObject *item = view->rootObject();
    connect(item, SIGNAL(albumClicked(int)), this, SLOT(playAlbum(int)));
    connect(item, SIGNAL(collectionClicked(int)), this, SLOT(playCollection(int)));
    ui->horizontalLayout->addWidget(container);
}

main_page::~main_page()
{
    delete ui;
}

void main_page::playCollection(int collectionId)
{
    xiamiapi::IGenericArray * list;
    auto api = ((MainWindow *)(context))->api;
    api->GetCollectionPlaylist(collectionId, &list);
    QVector<SongInfo> playlist;
    for (uint64_t i = 0; i < list->length(); ++i)
    {
        xiamiapi::IXiamiPlaylistInfo * info;
        list->get_element(i)->QueryInterface(list->ElementIID(), (void **)&info);
        playlist.append(SongInfo(info->get_song_id(), info->get_title(), info->get_artist(), info->get_location()));
        info->Release();
    }
    list->Release();
    ((MainWindow *)(context))->play(std::move(playlist));
}

void main_page::playAlbum(int albumId)
{
    xiamiapi::IGenericArray * list;
    auto api = ((MainWindow *)(context))->api;
    api->GetAlbumPlaylist(albumId, &list);
    QVector<SongInfo> playlist;
    auto length = list->length();
    for (uint64_t i = 0; i < length; ++i)
    {
        xiamiapi::IXiamiPlaylistInfo * info;
        list->get_element(i)->QueryInterface(list->ElementIID(), (void **)&info);
        playlist.append(SongInfo(info->get_song_id(), info->get_title(), info->get_artist(), info->get_location()));
        info->Release();
    }
    list->Release();
    ((MainWindow *)(context))->play(std::move(playlist));
}

void main_page::loadImage(QPushButton* &button, FileDownloader* downloader)
{
    QPixmap buttonImage;
    buttonImage.loadFromData(downloader->downloadedData());
    QIcon icon(buttonImage);
    button->setIcon(icon);
    downloader->deleteLater();
}


text:
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Route | curriculum-inventory-reports', function(hooks) {
  setupTest(hooks);

  test('it exists', function(assert) {
    let route = this.owner.lookup('route:curriculum-inventory-reports');
    assert.ok(route);
  });
});


text:
<?php

namespace Sunspikes\Amadeus\Command;

use Sunspikes\Amadeus\AmadeusClientException;
use Sunspikes\Amadeus\AmadeusCommandInterface;
use Sunspikes\Amadeus\AmadeusSoapClient;

/**
 * Class AbstractAmadeusCommand
 *
 * @package Sunspikes\Amadeus\Command
 */
abstract class AbstractAmadeusCommand implements AmadeusCommandInterface
{
    /** @var AmadeusSoapClient */
    private $amadeusSoapClient;

    /**
     * @param AmadeusSoapClient $amadeusSoapClient
     */
    public function setAmadeusSoapClient(AmadeusSoapClient $amadeusSoapClient)
    {
        $this->amadeusSoapClient = $amadeusSoapClient;
    }

    /**
     * @return AmadeusSoapClient
     */
    public function getAmadeusSoapClient()
    {
        return $this->amadeusSoapClient;
    }

    /**
     * @throws AmadeusClientException
     */
    public function execute()
    {
        if (null === $this->amadeusSoapClient) {
            throw new AmadeusClientException("Error: Set the AmadeusSoapClient");
        }

        $this->amadeusSoapClient->execute(
            $this->getName(),
            $this->getParameters()
        );
    }
}


text:
class MemoryController():
    """Represents a computer system's memory controller."""

    def power_on(self):
        """Powers on this memory controller."""
        print("MemoryController.power_on()")


text:
usage       'set <field> <value> <file> [<file>...]'
summary     'set a field value'
description <<-EOS
Set a frontmatter field value on a set of files.
EOS

module Forematter::Commands
  class Set < Forematter::CommandRunner
    include Forematter::Arguments::FieldValueFiles

    def run
      files.each do |file|
        file[field] = value
        file.write
      end
    end

    protected

    def value
      val = super
      YAML.load(val)
    rescue Psych::SyntaxError
      val
    end
  end
end

runner Forematter::Commands::Set


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Skew X</title>
    <link rel="stylesheet" href="../include/style.css">

    <canvas id="canvas" width="400" height="400"></canvas>
    Move mouse left or right on canvas element.

      Return to Animation Menu


text:
package simpleserver.nbt;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipNBTFile extends NBTFile {
  public GZipNBTFile(String filename) throws Exception {
    super(new GZIPInputStream(new FileInputStream(filename)));
  }

  public GZipNBTFile(InputStream in) throws Exception {
    super(new GZIPInputStream(in));
  }

  public GZipNBTFile() {
    super();
  }

  @Override
  protected OutputStream getOutputStream(String filename) throws FileNotFoundException, IOException {
    return new GZIPOutputStream(new FileOutputStream(filename));
  }
}


text:
import numpy as np
from theano.gof import Variable
from theano import tensor as T

def arg_to_softmax(prob):
    """
    Oh no! Someone has passed you the probability output,
    "prob", of a softmax function, and you want the unnormalized
    log probability--the argument to the softmax.

    Verify that prob really is the output of a softmax. Raise a
    TypeError if it is not.

    If it is, return the argument to the softmax.
    """

    if not isinstance(prob, Variable):
        raise TypeError()

    if prob.owner is None:
        raise TypeError()

    owner = prob.owner

    if not isinstance(owner.op, T.nnet.Softmax):
        raise TypeError()

    rval, = owner.inputs

    return rval

if __name__ == "__main__":
    x = np.ones((5, 4))
    try:
        arg_to_softmax(x)
        raise Exception("You should have raised an error.")
    except TypeError:
        pass

    x = T.matrix()
    try:
        arg_to_softmax(x)
        raise Exception("You should have raised an error.")
    except TypeError:
        pass

    y = T.nnet.sigmoid(x)
    try:
        arg_to_softmax(y)
        raise Exception("You should have raised an error.")
    except TypeError:
        pass

    y = T.nnet.softmax(x)
    rval = arg_to_softmax(y)
    assert rval is x

    print "SUCCESS!"


text:
declare module 'node-susanin/methods' {
  interface Methods {
    GET: symbol;
    PUT: symbol;
    POST: symbol;
    DELETE: symbol;
    HEAD: symbol;
    CONNECT: symbol;
    OPTIONS: symbol;
    TRACE: symbol;
    PATCH: symbol;
  }

  const methods: Methods;

  export default methods;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<ProgressBar
		android:id="@+id/progress"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		style="?android:progressBarStyleHorizontal"
		android:layout_alignParentTop="true"
		android:indeterminate="true"/>

	<android.support.v7.widget.RecyclerView
		android:id="@+id/app_grid"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:scrollbars="vertical"/>

	<com.shamanland.fab.FloatingActionButton
		android:id="@+id/fab"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignParentBottom="true"
		android:layout_alignParentRight="true"
		android:layout_alignParentEnd="true"
		android:layout_marginRight="16dp"
		android:layout_marginBottom="16dp"
		android:src="@drawable/ic_search_dark"/>
</RelativeLayout>


text:
Accessibility - EXPLORER [Micro Badge]
===================================================

Goals:
------

- You have done some exploration in the accessibility subject field
- You have applied this exploration to a practical result, and shared it back with the community

Intro
-----

> "Man cannot discover new oceans unless he has the courage to lose sight of the shore." ― André Gide

Gain the spirit of exploration. Use that big brain of yours to go find something new, different and awesome in the realm of accessibility! When you're done, pay it forward by sharing your discovery.

Suggested Assignment(s)
---------------------

Choose one in accessibility:

1) Discover a new & helpful tool
  - [ ] Explore & discover the tool (hasn't been covered in your required micro-badges yet)
  - [ ] Demonstrate the tool
  - [ ] Add the tool to the appropriate micro-badge curriculum

2) Discover a new & helpful technique
  - [ ] Explore & discover the technique (hasn't been covered in your required micro-badges yet)
  - [ ] Demonstrate the technique
  - [ ] Add the technique to the appropriate micro-badge curriculum

3) Discover a new & richly helpful information resource
  - [ ] Explore & discover the resource (hasn't been covered in your required micro-badges yet)
  - [ ] Demonstrate the info resource, and something helpful you found in it
  - [ ] Add the info resource to the appropriate micro-badge curriculum

4) Write a micro-badge about a new and helpful topic
  - [ ] Explore & discover a topic that hasn't been covered by any other badges yet
  - [ ] Propose and get go-ahead to make an awesome micro-badge about your sub-topic
  - [ ] The micro-badge must be as complete as the other active required ones
  - [ ] Contribute to actively support and maintain the micro-badge's contents

Suggested Study
---------------

### Web
- Go out and explore!

-----

  *Is this badge missing something? Submit a PR and review it with a master in this category*


text:
Algorithme KSVD - Projet de Séminaire de Statistiques

Auteurs: Marion Vichery, Sylvain Puyravaud et Paul Minder

Ce dépôt Github correspond au projet de séminaire de
statistiques réalisé à l'ENSAE en 2015 par les trois auteurs.
L'objectif est de comprendre et d'implémenter l'algorithme
K-SVD. Le projet s'articule en deux grandes parties:
- une première partie théorique, où nous exposons le
  le fonctionnemenent et le contexte d'apparition de
  l'algorithme, ainsi que certaines de ces applications.
- une seconde partie, plus pratique, où nous implémentons
  l'algorithme et l'utilisons pour débruiter une image.

La première partie est entièrement comprise dans le rapport,
disponible en PDF sur le dépôt Github. Nous exposons également
les principaux résultats de la seconde dans le rapport mais,
s'agissant essentiellement de code, elle gagne à être lue
en parallèle avec les autres fichiers présents sur ce dépôt.


text:
layout: segmentation-tool
title: Circle Scissors Tool
toolName: CircleScissors
toolType: segmentation
customButtons: segmentationStrategiesButtons.html
---

{% include tool-simple-code-snippet.md %}

🚧 Under Construction 🚧


text:
import { Key, CSSProperties, MouseEvent, TouchEvent } from 'react';

export interface RangerOptions {
    values: number[];
    min: number;
    max: number;
    stepSize: number;
    steps?: number[];
    tickSize?: number;
    ticks?: number[];
    onChange?: (values: number[]) => void;
    onDrag?: (values: number[]) => void;
    interpolator?: {
        getPercentageForValue: (val: number, min: number, max: number) => number;
        getValueForClientX: (clientX: number, trackDims: object, min: number, max: number) => number;
    };
}

export interface TrackProps {
    key: Key;
    style: CSSProperties;
}
export interface TickProps  {
    key: Key;
    style: CSSProperties;
}
export interface SegmentProps  {
    key: Key;
    style: CSSProperties;
}
export interface HandleProps {
    key: Key;
    style: CSSProperties;
    onMouseDown: (event: MouseEvent) => void;
    onTouchStart: (event: TouchEvent) => void;
    tabIndex: number;
}

export interface RangerTick {
    value: number;
    getTickProps: <T>(props?: T) => T & TickProps;
}

export interface RangerSegment {
    value: number;
    getSegmentProps: <T>(props?: T) => T & SegmentProps;
}

export interface RangerHandle {
    value: number;
    active: boolean;
    getHandleProps: <T>(props?: T) => T & HandleProps;
}

export interface Ranger {
    getTrackProps: <T>(props?: T) => T & TrackProps;
    ticks: RangerTick[];
    segments: RangerSegment[];
    handles: RangerHandle[];
    activeHandleIndex: number | null;
}

export function useRanger(options: RangerOptions): Ranger;


text:
namespace NadekoBot.Core.Common
{
    public interface ISeria
    {
        byte[] Serialize<T>(T data);
        T Deserialize<T>(byte[] data);
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Aptroot, Diederich, Sérusiaux & Sipman, Biblthca Lichenol. 64: 204 (1997)

#### Original name
Tricharia verrucosa Sérus.

### Remarks
null


text:
package org.apache.spark.sql

import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSQLContext
import org.apache.spark.sql.types.StructType

class ExplainSuite extends QueryTest with SharedSQLContext {
  import testImplicits._

  /**
   * Runs the plan and makes sure the plans contains all of the keywords.
   */
  private def checkKeywordsExistsInExplain(df: DataFrame, keywords: String*): Unit = {
    val output = new java.io.ByteArrayOutputStream()
    Console.withOut(output) {
      df.explain(extended = true)
    }
    val normalizedOutput = output.toString.replaceAll("#\\d+", "#x")
    for (key <- keywords) {
      assert(normalizedOutput.contains(key))
    }
  }

  test("SPARK-23034 show rdd names in RDD scan nodes (Dataset)") {
    val rddWithName = spark.sparkContext.parallelize(Row(1, "abc") :: Nil).setName("testRdd")
    val df = spark.createDataFrame(rddWithName, StructType.fromDDL("c0 int, c1 string"))
    checkKeywordsExistsInExplain(df, keywords = "Scan ExistingRDD testRdd")
  }

  test("SPARK-23034 show rdd names in RDD scan nodes (DataFrame)") {
    val rddWithName = spark.sparkContext.parallelize(ExplainSingleData(1) :: Nil).setName("testRdd")
    val df = spark.createDataFrame(rddWithName)
    checkKeywordsExistsInExplain(df, keywords = "Scan testRdd")
  }

  test("SPARK-24850 InMemoryRelation string representation does not include cached plan") {
    val df = Seq(1).toDF("a").cache()
    checkKeywordsExistsInExplain(df,
      keywords = "InMemoryRelation", "StorageLevel(disk, memory, deserialized, 1 replicas)")
  }

  test("optimized plan should show the rewritten aggregate expression") {
    withTempView("test_agg") {
      sql(
        """
          |CREATE TEMPORARY VIEW test_agg AS SELECT * FROM VALUES
          |  (1, true), (1, false),
          |  (2, true),
          |  (3, false), (3, null),
          |  (4, null), (4, null),
          |  (5, null), (5, true), (5, false) AS test_agg(k, v)
        """.stripMargin)

      // simple explain of queries having every/some/any aggregates. Optimized
      // plan should show the rewritten aggregate expression.
      val df = sql("SELECT k, every(v), some(v), any(v) FROM test_agg GROUP BY k")
      checkKeywordsExistsInExplain(df,
        "Aggregate [k#x], [k#x, min(v#x) AS every(v)#x, max(v#x) AS some(v)#x, " +
          "max(v#x) AS any(v)#x]")
    }
  }

  test("explain inline tables cross-joins") {
    val df = sql(
      """
        |SELECT * FROM VALUES ('one', 1), ('three', null)
        |  CROSS JOIN VALUES ('one', 1), ('three', null)
      """.stripMargin)
    checkKeywordsExistsInExplain(df,
      "Join Cross",
      ":- LocalRelation [col1#x, col2#x]",
      "+- LocalRelation [col1#x, col2#x]")
  }

  test("explain table valued functions") {
    checkKeywordsExistsInExplain(sql("select * from RaNgE(2)"), "Range (0, 2, step=1, splits=None)")
    checkKeywordsExistsInExplain(sql("SELECT * FROM range(3) CROSS JOIN range(3)"),
      "Join Cross",
      ":- Range (0, 3, step=1, splits=None)",
      "+- Range (0, 3, step=1, splits=None)")
  }

  test("explain string functions") {
    // Check if catalyst combine nested `Concat`s
    val df1 = sql(
      """
        |SELECT (col1 || col2 || col3 || col4) col
        |  FROM (SELECT id col1, id col2, id col3, id col4 FROM range(10))
      """.stripMargin)
    checkKeywordsExistsInExplain(df1,
      "Project [concat(cast(id#xL as string), cast(id#xL as string), cast(id#xL as string)" +
        ", cast(id#xL as string)) AS col#x]")

    // Check if catalyst combine nested `Concat`s if concatBinaryAsString=false
    withSQLConf(SQLConf.CONCAT_BINARY_AS_STRING.key -> "false") {
      val df2 = sql(
        """
          |SELECT ((col1 || col2) || (col3 || col4)) col
          |FROM (
          |  SELECT
          |    string(id) col1,
          |    string(id + 1) col2,
          |    encode(string(id + 2), 'utf-8') col3,
          |    encode(string(id + 3), 'utf-8') col4
          |  FROM range(10)
          |)
        """.stripMargin)
      checkKeywordsExistsInExplain(df2,
        "Project [concat(cast(id#xL as string), cast((id#xL + 1) as string), " +
          "cast(encode(cast((id#xL + 2) as string), utf-8) as string), " +
          "cast(encode(cast((id#xL + 3) as string), utf-8) as string)) AS col#x]")

      val df3 = sql(
        """
          |SELECT (col1 || (col3 || col4)) col
          |FROM (
          |  SELECT
          |    string(id) col1,
          |    encode(string(id + 2), 'utf-8') col3,
          |    encode(string(id + 3), 'utf-8') col4
          |  FROM range(10)
          |)
        """.stripMargin)
      checkKeywordsExistsInExplain(df3,
        "Project [concat(cast(id#xL as string), " +
          "cast(encode(cast((id#xL + 2) as string), utf-8) as string), " +
          "cast(encode(cast((id#xL + 3) as string), utf-8) as string)) AS col#x]")
    }
  }

  test("check operator precedence") {
    // We follow Oracle operator precedence in the table below that lists the levels
    // of precedence among SQL operators from high to low:
    // ---------------------------------------------------------------------------------------
    // Operator                                          Operation
    // ---------------------------------------------------------------------------------------
    // +, -                                              identity, negation
    // *, /                                              multiplication, division
    // +, -, ||                                          addition, subtraction, concatenation
    // =, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN   comparison
    // NOT                                               exponentiation, logical negation
    // AND                                               conjunction
    // OR                                                disjunction
    // ---------------------------------------------------------------------------------------
    checkKeywordsExistsInExplain(sql("select 'a' || 1 + 2"),
      "Project [null AS (CAST(concat(a, CAST(1 AS STRING)) AS DOUBLE) + CAST(2 AS DOUBLE))#x]")
    checkKeywordsExistsInExplain(sql("select 1 - 2 || 'b'"),
      "Project [-1b AS concat(CAST((1 - 2) AS STRING), b)#x]")
    checkKeywordsExistsInExplain(sql("select 2 * 4  + 3 || 'b'"),
      "Project [11b AS concat(CAST(((2 * 4) + 3) AS STRING), b)#x]")
    checkKeywordsExistsInExplain(sql("select 3 + 1 || 'a' || 4 / 2"),
      "Project [4a2.0 AS concat(concat(CAST((3 + 1) AS STRING), a), " +
        "CAST((CAST(4 AS DOUBLE) / CAST(2 AS DOUBLE)) AS STRING))#x]")
    checkKeywordsExistsInExplain(sql("select 1 == 1 OR 'a' || 'b' ==  'ab'"),
      "Project [true AS ((1 = 1) OR (concat(a, b) = ab))#x]")
    checkKeywordsExistsInExplain(sql("select 'a' || 'c' == 'ac' AND 2 == 3"),
      "Project [false AS ((concat(a, c) = ac) AND (2 = 3))#x]")
  }

  test("explain for these functions; use range to avoid constant folding") {
    val df = sql("select ifnull(id, 'x'), nullif(id, 'x'), nvl(id, 'x'), nvl2(id, 'x', 'y') " +
      "from range(2)")
    checkKeywordsExistsInExplain(df,
      "Project [coalesce(cast(id#xL as string), x) AS ifnull(`id`, 'x')#x, " +
        "id#xL AS nullif(`id`, 'x')#xL, coalesce(cast(id#xL as string), x) AS nvl(`id`, 'x')#x, " +
        "x AS nvl2(`id`, 'x', 'y')#x]")
  }
}

case class ExplainSingleData(id: Int)


text:
require "ar_find_in_batches_with_usefulness"

RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"
end


text:
<?php

/**
 * Class FunctionStrIreplaceTest
 * @link http://php.net/manual/en/function.str-ireplace.php
 */
class FunctionStrIreplaceTest extends PHPUnit_Framework_TestCase
{
    public function testFunctionStrIreplace()
    {
        $bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
        $this->assertEquals('<body text=black>', $bodytag);
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ch.halcyon.squareprogressbar.SquareProgressBar
        android:id="@+id/subi2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:paddingTop="20dp" >
    </ch.halcyon.squareprogressbar.SquareProgressBar>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/progressSeekBar"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/progressSeekBar"
        android:gravity="center_vertical"
        android:text="@string/progress"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <SeekBar
        android:id="@+id/progressSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/progressDisplay"
        android:layout_toRightOf="@+id/textView1"
        android:max="100"
        android:progress="25" />

    <TextView
        android:id="@+id/progressDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/progressSeekBar"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignRight="@+id/textView1"
        android:layout_alignTop="@+id/widthSeekBar"
        android:gravity="center_vertical"
        android:text="@string/width"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <SeekBar
        android:id="@+id/widthSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressSeekBar"
        android:layout_alignLeft="@+id/progressSeekBar"
        android:layout_alignParentRight="true"
        android:max="20"
        android:progress="8" />

</RelativeLayout>


text:
author: Matt Oswalt
comments: true
date: 2013-04-09 15:00:41+00:00
layout: post
slug: no-experience-is-irrelevant
title: No Experience is Irrelevant
wordpress_id: 3385
categories:
- Opinion
tags:
- experience
- kiclet
- skillset
---

So you've recently changed jobs, and you have a very extensive linux skillset. Your new job doesn't include or require this skillset. Does that mean that experience will not serve you in this new role?

Absolutely false. The most valuable thing these experiences give us is **perspective**. The ability to see things from a unique point of view makes you a unique and valuable addition to any team. This is a strong reason for my advocacy of the [Unified Skillset](https://keepingitclassless.net/2013/01/the-unified-skillset/).

I will say this - a great tactic when looking for a position is asking the hiring position how easy it is to fill multiple roles from a technical perspective. Some have the internal org structure that allows you to work on technical projects outside of the core skillset you may have been immediately hired for. This is a really good way to keep your blade sharp in multiple areas.

Will my 6 years of experience doing software development (I miss programming) _really_ have a direct impact on my ability to configure a Cisco switch? Likely not in the most direct sense, but it still provides a perspective that many others with the same Cisco skillset cannot have (This is all regardless of the growing trend of automation, and SDN). It is not up to us to judge the value of either our own or others' technical history and figure out if the skillsets match exactly, especially if you're in the position of looking for engineering talent on the market. Such a pursuit is relevant on the surface but will likely lead to a bad working relationship.

I'll leave you with some of the best advice I've ever received: Hire people, train engineers. Get comfortable with proactively looking for personalities that fit the culture of your own organization, rather than engineers that meet a technical need right away. You'll have much better luck with the former.


text:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="../schematron/schematron_result_for_eop.xsl"?>
<lmb:EarthObservation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:eop="http://www.opengis.net/eop/2.1" xmlns:lmb="http://www.opengis.net/lmb/2.1" xmlns:ows="http://www.opengis.net/ows/2.0" xmlns:swe="http://www.opengis.net/swe/1.0" xmlns:om="http://www.opengis.net/om/2.0" gml:id="lmb_example_1" xsi:schemaLocation="http://www.opengis.net/lmb/2.1 ../xsd/lmb.xsd">
	<om:phenomenonTime>
		<gml:TimePeriod gml:id="tp_2">
			<gml:beginPosition>2001-08-22T11:02:47.000</gml:beginPosition>
			<gml:endPosition>2001-08-22T11:02:47.999</gml:endPosition>
		</gml:TimePeriod>
	</om:phenomenonTime>
	<om:resultTime>
		<!-- repeat of archiving date? -->
		<gml:TimeInstant gml:id="archivingdate_1">
			<gml:timePosition>2001-08-22T11:02:47.999</gml:timePosition>
		</gml:TimeInstant>
	</om:resultTime>
	<om:procedure>
		<lmb:EarthObservationEquipment gml:id="eop_2">
			<eop:platform>
				<eop:Platform>
					<eop:shortName>DummyPlatform</eop:shortName>
					<eop:serialIdentifier>DummyP</eop:serialIdentifier>
				</eop:Platform>
			</eop:platform>
			<eop:instrument>
				<eop:Instrument>
					<eop:shortName>DummyLimbSoundingInstrument</eop:shortName>
					<eop:instrumentType/>
				</eop:Instrument>
			</eop:instrument>
			<lmb:acquisitionParameters>
				<eop:Acquisition>
					<eop:orbitNumber>12</eop:orbitNumber>
					<eop:lastOrbitNumber>12</eop:lastOrbitNumber>
					<eop:orbitDirection>ASCENDING</eop:orbitDirection>
					<eop:illuminationAzimuthAngle uom="deg">10</eop:illuminationAzimuthAngle>
					<eop:acrossTrackIncidenceAngle uom="deg">-14.0</eop:acrossTrackIncidenceAngle>
					<eop:alongTrackIncidenceAngle uom="deg">-13.9</eop:alongTrackIncidenceAngle>
					<eop:pitch uom="deg">0</eop:pitch>
					<eop:roll uom="deg">0</eop:roll>
					<eop:yaw uom="deg">0</eop:yaw>
				</eop:Acquisition>
			</lmb:acquisitionParameters>
			<lmb:sensor>
				<lmb:Sensor>
					<eop:sensorType>LIMB</eop:sensorType>
					<eop:operationalMode codeSpace="urn:eop:DUMMY:sensorMode">Mode5</eop:operationalMode>
					<eop:resolution uom="m">1.0</eop:resolution>
					<lmb:measurementType>ABSORPTION</lmb:measurementType>
				</lmb:Sensor>
			</lmb:sensor>
		</lmb:EarthObservationEquipment>
	</om:procedure>
	<om:observedProperty/>
	<om:featureOfInterest>
		<lmb:Footprint gml:id="fp1">
			<eop:multiExtentOf>
				<gml:MultiSurface gml:id="mask">
					<gml:surfaceMembers>
						<gml:Polygon gml:id="maskPolygon">
							<gml:exterior>
								<gml:LinearRing>
									<gml:posList>2.1025 43.516667 2.861667 43.381667 2.65 42.862778 1.896944 42.996389 2.1025 43.516667</gml:posList>
								</gml:LinearRing>
							</gml:exterior>
						</gml:Polygon>
					</gml:surfaceMembers>
				</gml:MultiSurface>
			</eop:multiExtentOf>
			<lmb:maximumAltitude uom="m">3500</lmb:maximumAltitude>
			<lmb:minimumAltitude uom="m">1500</lmb:minimumAltitude>
			<lmb:nominalTrack>
				<gml:MultiCurve gml:id="lmb_fpcurve1">
					<gml:curveMember>
						<gml:LineString gml:id="track1" srsName="EPSG:4326">
							<gml:coordinates>-60.11159,-49.394531 -22.355494,-19.863281
								51.777811,18.457031 78.611509,63.808594</gml:coordinates>
						</gml:LineString>
					</gml:curveMember>
				</gml:MultiCurve>
			</lmb:nominalTrack>
			<lmb:occultationPoints>
				<gml:MultiPoint gml:id="occ1" srsName="EPSG:4326">
					<gml:pointMember>
						<gml:Point gml:id="profile1">
							<gml:coordinates>-59.1823 -48.2336</gml:coordinates>
						</gml:Point>
					</gml:pointMember>
					<gml:pointMember>
						<gml:Point gml:id="profile2">
							<gml:coordinates>-30.2141 -23.4324 </gml:coordinates>
						</gml:Point>
					</gml:pointMember>
					<gml:pointMember>
						<gml:Point gml:id="profile3">
							<gml:coordinates>-23.3424 -18.7632</gml:coordinates>
						</gml:Point>
					</gml:pointMember>
				</gml:MultiPoint>
			</lmb:occultationPoints>
		</lmb:Footprint>
	</om:featureOfInterest>
	<om:result>
		<eop:EarthObservationResult gml:id="eor_2">
			<eop:browse>
				<eop:BrowseInformation>
					<eop:type>QUICKLOOK</eop:type>
					<eop:referenceSystemIdentifier codeSpace="EPSG">epsg:4326</eop:referenceSystemIdentifier>
					<eop:fileName>
						<ows:ServiceReference xlink:href="http://www.mybrowse.com/dummy">
							<ows:RequestMessage/>
						</ows:ServiceReference>
					</eop:fileName>
				</eop:BrowseInformation>
			</eop:browse>
			<eop:product>
				<eop:ProductInformation>
					<eop:fileName>
						<ows:ServiceReference xlink:href="">
							<ows:RequestMessage/>
						</ows:ServiceReference>
					</eop:fileName>
					<eop:timeliness>NRT</eop:timeliness>
				</eop:ProductInformation>
			</eop:product>
			<eop:mask>
				<eop:MaskInformation>
					<eop:type>CLOUD</eop:type>
					<eop:format>VECTOR</eop:format>
					<eop:fileName>
						<ows:ServiceReference xlink:href="http://www.mybrowse.com/dummy2">
							<ows:RequestMessage/>
						</ows:ServiceReference>
					</eop:fileName>
				</eop:MaskInformation>
			</eop:mask>
		</eop:EarthObservationResult>
	</om:result>
	<eop:metaDataProperty>
		<eop:EarthObservationMetaData>
			<eop:identifier>DS_PHR1A_20010822110247_TLS_PX_E123N45_0101_01234</eop:identifier>
			<eop:creationDate>2001-08-22T11:02:47.999</eop:creationDate>
			<eop:modificationDate>2001-08-22T11:02:47.999</eop:modificationDate>
			<eop:acquisitionType>NOMINAL</eop:acquisitionType>
			<eop:productType>TBD</eop:productType>
			<eop:status>ARCHIVED</eop:status>
			<eop:statusSubType>OFF-LINE</eop:statusSubType>
			<eop:downlinkedTo>
				<eop:DownlinkInformation>
					<eop:acquisitionStation codeSpace="urn:eop:PHR:stationCode">TLS</eop:acquisitionStation>
				</eop:DownlinkInformation>
			</eop:downlinkedTo>
			<eop:archivedIn>
				<eop:ArchivingInformation>
					<eop:archivingCenter codeSpace="urn:eop:PHR:stationCode">TLS</eop:archivingCenter>
					<eop:archivingDate>2001-08-22T11:02:47.999</eop:archivingDate>
				</eop:ArchivingInformation>
			</eop:archivedIn>
			<eop:productQualityDegradation uom="%">12</eop:productQualityDegradation>
			<eop:productQualityDegradationQuotationMode>AUTOMATIC</eop:productQualityDegradationQuotationMode>
			<eop:productQualityStatus>DEGRADED</eop:productQualityStatus>
			<eop:productQualityReportURL>http://www.xxx.xx/test.pdf</eop:productQualityReportURL>
			<eop:processing>
				<eop:ProcessingInformation>
					<eop:processingDate>2001-08-22T11:01:47</eop:processingDate>
					<eop:processingMode codeSpace="http://xxx.xxx.xx">NOMINAL</eop:processingMode>
				</eop:ProcessingInformation>
			</eop:processing>
			<eop:productGroupId>1515:56:4564:5646:6548:75748</eop:productGroupId>
		</eop:EarthObservationMetaData>
	</eop:metaDataProperty>
</lmb:EarthObservation>


text:
class CreatePeople < ActiveRecord::Migration
  def change
    create_table :people do |t|
      t.string :name
      t.boolean :programmer
      t.float :height
      t.timestamp :birthDate
      t.binary :avatar

      t.timestamps
    end
  end
end


text:
package com.tascape.qa.th.ios.comm;

/**
 *
 * @author linsong wang
 */
public interface JavaScriptServer {

    String retrieveJavaScript() throws InterruptedException;
}


text:
#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize button, name, result;

- (void)viewDidLoad {
    result.contentInset = UIEdgeInsetsMake(20.0, 20.0, 10.0, 10.0);
    [super viewDidLoad];
    button.hidden = YES;
    // Initialized cloud connection
    [FH initWithSuccess:^(FHResponse *response) {
        NSLog(@"initialized OK");
        button.hidden = NO;
    } AndFailure:^(FHResponse *response) {
        NSLog(@"initialize fail, %@", response.rawResponseAsString);
        if (response.parsedResponse) {
            result.text = [NSString stringWithFormat:@"init failed, %@",[response.parsedResponse objectForKey:@"msg"]];
        } else {
            result.text = @"Please fill in fhconfig.plist file.";
        }
    }];
}

- (IBAction)cloudCall:(id)sender {
    [name endEditing:YES];
    NSDictionary *args = [NSDictionary dictionaryWithObject:name.text forKey:@"hello"];
    FHCloudRequest *req = (FHCloudRequest *) [FH buildCloudRequest:@"/hello" WithMethod:@"POST" AndHeaders:nil AndArgs:args];

    [req execAsyncWithSuccess:^(FHResponse * res) {
        // Response
        NSLog(@"Response: %@", res.rawResponseAsString);
        result.text = [res.parsedResponse objectForKey:@"msg"];
    } AndFailure:^(FHResponse * res){
        // Errors
        NSLog(@"Failed to call. Response = %@", res.rawResponseAsString);
        result.text = res.rawResponseAsString;
    }];
}

// Mark - Dismiss keyboard
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [name endEditing:YES];
}

@end


text:
PROJECT_NAME := coap_client

EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/common_components/protocol_examples_common

include $(IDF_PATH)/make/project.mk


text:
using System;
using System.Collections.Generic;
using Penneo.Connector;
using Penneo.Mapping;
using RestSharp;

namespace Penneo
{
    /// <summary>
    /// Base class for all Penneo business entities
    /// </summary>
    public abstract class Entity
    {
        protected Entity()
        {
            InternalIdentifier = Guid.NewGuid();
        }

        /// <summary>
        /// The relative url (rest resource) of the entity type
        /// </summary>
        internal virtual string GetRelativeUrl(PenneoConnector con)
        {
            return con.ServiceLocator.GetInstance<RestResources>().GetResource(GetType(), Parent);
        }

        /// <summary>
        /// The entity type mapping
        /// </summary>
        internal IMapping GetMapping(PenneoConnector con)
        {
            return con.ServiceLocator.GetInstance<Mappings>().GetMapping(GetType());
        }

        /// <summary>
        /// The parent of the entity (if any)
        /// </summary>
        internal virtual Entity Parent
        {
            get { return null; }
        }

        /// <summary>
        /// Internal guid of the entity
        /// </summary>
        internal Guid InternalIdentifier { get; set; }

        /// <summary>
        /// The Id of the entity
        /// </summary>
        public int? Id { get; set; }

        /// <summary>
        /// Denotes if the entity is new (i.e. still unknown to Penneo)
        /// </summary>
        public bool IsNew
        {
            get { return !Id.HasValue; }
        }

        /// <summary>
        /// Get request data from the entity as a property->value dictionary
        /// </summary>
        public Dictionary<string, object> GetRequestData(PenneoConnector con)
        {
            var values = IsNew ? GetMapping(con).GetCreateValues(this) : GetMapping(con).GetUpdateValues(this);
            return values;
        }

        /// <summary>
        /// Persist the entity to the storage
        /// </summary>
        public bool Persist(PenneoConnector con)
        {
            con.Log((IsNew ? "Creating" : "Updating") + " " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information);
            var success = con.ApiConnector.WriteObject(this);
            if (!success)
            {
                con.Log((IsNew ? "Creating" : "Updating") + " " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") failed", LogSeverity.Information);
            }
            return success;
        }

        /// <summary>
        /// Delete the entity from the storage
        /// </summary>
        public void Delete(PenneoConnector con)
        {
            con.Log("Deleting " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information);
            if (!con.ApiConnector.DeleteObject(this))
            {
                throw new Exception("Penneo: Could not delete the " + GetType().Name);
            }
            Id = null;
        }

        /// <summary>
        /// Get the latest server result for the entity
        /// </summary>
        public ServerResult GetLatestServerResult(PenneoConnector con)
        {
            return con.ApiConnector.GetLatestEntityServerResult(this);
        }

        /// <summary>
        /// Link this entity with the given child in the storage
        /// </summary>
        protected bool LinkEntity(PenneoConnector con, Entity child)
        {
            con.Log("Linking " +
                      GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") TO " +
                      child.GetType().Name + " (" + (child.Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information);
            return con.ApiConnector.LinkEntity(this, child);
        }

        /// <summary>
        /// Unlink this entity with the given child in the storage
        /// </summary>
        protected bool UnlinkEntity(PenneoConnector con, Entity child)
        {
            con.Log("Unlinking " +
                      GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") TO " +
                      child.GetType().Name + " (" + (child.Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information);
            return con.ApiConnector.UnlinkEntity(this, child);
        }

        /// <summary>
        /// Get all entities linked with this entity in the storage
        /// </summary>
        protected QueryResult<T> GetLinkedEntities<T>(PenneoConnector con, string url = null)
            where T: Entity
        {
            return con.ApiConnector.GetLinkedEntities<T>(this, url);
        }

        /// <summary>
        /// Get entity linked with this entity based on url
        /// </summary>
        protected QuerySingleObjectResult<T> GetLinkedEntity<T>(PenneoConnector con, string url = null)
            where T: Entity
        {
            return con.ApiConnector.GetLinkedEntity<T>(this, url);
        }

        /// <summary>
        /// Find a specific linked entity
        /// </summary>
        protected T FindLinkedEntity<T>(PenneoConnector con, int id)
        {
            return con.ApiConnector.FindLinkedEntity<T>(this, id);
        }

        /// <summary>
        /// Get file assets with the given name for this entity
        /// </summary>
        protected byte[] GetFileAssets(PenneoConnector con, string assetName)
        {
            return con.ApiConnector.GetFileAssets(this, assetName);
        }

        /// <summary>
        /// Get text assets with the given name for this entity
        /// </summary>
        protected string GetTextAssets(PenneoConnector con, string assetName)
        {
            return con.ApiConnector.GetTextAssets(this, assetName);
        }

        protected T GetAsset<T>(PenneoConnector con, string assetName)
        {
            return con.ApiConnector.GetAsset<T>(this, assetName);
        }

        /// <summary>
        /// Get list of string asset with the given name for this entity
        /// </summary>
        protected IEnumerable<string> GetStringListAsset(PenneoConnector con, string assetName)
        {
            return con.ApiConnector.GetStringListAsset(this, assetName);
        }

        /// <summary>
        /// Perform the given action on this entity
        /// </summary>
        protected ServerResult PerformAction(PenneoConnector con, string action)
        {
            return con.ApiConnector.PerformAction(this, action);
        }

        protected ServerResult PerformComplexAction(
            PenneoConnector con,
            Method method,
            string action,
            Dictionary<string, object> data
        )
        {
            return con.ApiConnector.PerformComplexAction(this, method, action, data);
        }

        /// <summary>
        /// Do optional initialization when reading the entity from a source
        /// </summary>
        internal virtual void ReadInit()
        {
        }

        /// <summary>
        /// Return a string for debugging with both type and id
        /// </summary>
        public override string ToString()
        {
            return string.Format("{0} Id: {1}", GetType().Name, Id);
        }
    }
}


text:
package com.intel.icecp.core.modules;

import com.intel.icecp.core.Channel;
import com.intel.icecp.core.Module;
import com.intel.icecp.core.Module.StopReason;
import com.intel.icecp.core.messages.BytesMessage;
import com.intel.icecp.core.messages.ConfigurationMessage;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;

/**
 */
public interface Modules {

    /**
     * Retrieve a module from the list of loaded modules. Access is checked with ModulePermission("module-name").
     *
     * @param id the ID of the module instance to retrieve
     * @return the {@link Module} instance
     * @throws ModuleNotFoundException if the module has not yet been loaded
     */
    ModuleInstance get(long id) throws ModuleNotFoundException;

    /**
     * @return all module instances currently loaded on the system
     */
    Collection<ModuleInstance> getAll();

    /**
     * Retrieve an (assumed) JAR file and load only the modules matching the regular expression passed as
     * moduleNameRegex.
     * <p>
     * If module implementors need to run multiple instances of their module, call this method multiple times.
     *
     * @param moduleChannel a document channel returning the bytes of a JAR file
     * @param moduleNameRegex a unique name identifying the module inside the JAR, matches the name specified on the
     * module with {@link ModuleProperty}
     * @param configurationChannel a channel for retrieving configuration to load with the module
     * @return a future that resolves to a collection of all loaded module IDs
     */
    CompletableFuture<Collection<Long>> load(Channel<BytesMessage> moduleChannel, String moduleNameRegex, Channel<ConfigurationMessage> configurationChannel);

    /**
     * Start the module in the execution pool; any thread with access to the ModulePermission("module-name") can start
     * and stop the module.
     *
     * @param id the ID of the module instance to start
     * @return a future that completes once the module is started, the result will contain the passed ID
     */
    CompletableFuture<Long> start(long id);

    /**
     * Stop the module (assumes the module implements the stop() contract correctly). Any thread with access to the
     * ModulePermission("module-name") can start and stop the module. TODO is there a way to force this? Tried with
     * Future.cancel() but this only works if the module respects InterruptedExceptions (and sleeps).
     *
     * @param id the ID of the module instance to start
     * @param reason a {@link StopReason} describing why to stop the module
     * @return a future that completes once the module is stopped
     */
    CompletableFuture<Void> stop(long id, Module.StopReason reason);

    /**
     * Stop all modules
     *
     * @param reason a {@link StopReason} describing why to stop the modules
     * @return a future that completes once all modules are stopped
     */
    CompletableFuture<Void> stopAll(Module.StopReason reason);
}


text:
if (POLICY CMP0054)
  cmake_policy(SET CMP0054 NEW)
endif()

# Makes a C compliant preprocessor symbol
function(wn_make_preprocessor_symbol INPUT OUTPUT)
  string(MAKE_C_IDENTIFIER ${INPUT} SANITIZED_INPUT)
  string(TOUPPER ${SANITIZED_INPUT} SYMBOL)
  string(REGEX REPLACE "_+$" "" SYMBOL ${SYMBOL})

  set(${OUTPUT} ${SYMBOL} PARENT_SCOPE)
endfunction()


text:
var YCBCR_VERTEX_SHADER = require('./generated/YCbCr-vertex-shader.js');
var YCBCR_FRAGMENT_SHADER = require('./generated/YCbCr-fragment-shader.js');
var YCBCR_STRIPE_FRAGMENT_SHADER = require('./generated/YCbCr-stripe-fragment-shader.js');

/**
 * Warning: canvas must not have been used for 2d drawing prior!
 *
 * @param HTMLCanvasElement canvas
 * @constructor
 */
function WebGLFrameSink(canvas, videoInfo) {
	var self = this,
		gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'),
		debug = false; // swap this to enable more error checks, which can slow down rendering

	if (gl === null) {
		throw new Error('WebGL unavailable');
	}

	// GL!
	function checkError() {
		if (debug) {
			err = gl.getError();
			if (err !== 0) {
				throw new Error("GL error " + err);
			}
		}
	}

	function compileShader(type, source) {
		var shader = gl.createShader(type);
		gl.shaderSource(shader, source);
		gl.compileShader(shader);

		if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
			var err = gl.getShaderInfoLog(shader);
			gl.deleteShader(shader);
			throw new Error('GL shader compilation for ' + type + ' failed: ' + err);
		}

		return shader;
	}

	var vertexShader,
		fragmentShader,
		program,
		buffer,
		err;

	// In the world of GL there are no rectangles.
	// There are only triangles.
	// THERE IS NO SPOON.
	var rectangle = new Float32Array([
		// First triangle (top left, clockwise)
		-1.0, -1.0,
		+1.0, -1.0,
		-1.0, +1.0,

		// Second triangle (bottom right, clockwise)
		-1.0, +1.0,
		+1.0, -1.0,
		+1.0, +1.0
	]);

	var textures = {};
	function attachTexture(name, register, index, width, height, data) {
		var texture,
			texWidth = WebGLFrameSink.stripe ? (width / 4) : width,
			format = WebGLFrameSink.stripe ? gl.RGBA : gl.LUMINANCE,
			filter = WebGLFrameSink.stripe ? gl.NEAREST : gl.LINEAR;

		if (textures[name]) {
			// Reuse & update the existing texture
			texture = textures[name];
		} else {
			textures[name] = texture = gl.createTexture();
			checkError();

			gl.uniform1i(gl.getUniformLocation(program, name), index);
			checkError();
		}
		gl.activeTexture(register);
		checkError();
		gl.bindTexture(gl.TEXTURE_2D, texture);
		checkError();
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		checkError();
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		checkError();
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
		checkError();
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
		checkError();

		gl.texImage2D(
			gl.TEXTURE_2D,
			0, // mip level
			format, // internal format
			texWidth,
			height,
			0, // border
			format, // format
			gl.UNSIGNED_BYTE, //type
			data // data!
		);
		checkError();

		return texture;
	}

	function buildStripe(width, height) {
		var len = width * height,
			out = new Uint32Array(len);
		for (var i = 0; i < len; i += 4) {
			out[i    ] = 0x000000ff;
			out[i + 1] = 0x0000ff00;
			out[i + 2] = 0x00ff0000;
			out[i + 3] = 0xff000000;
		}
		return new Uint8Array(out.buffer);
	}

	function init(yCbCrBuffer) {
		vertexShader = compileShader(gl.VERTEX_SHADER, YCBCR_VERTEX_SHADER);
		if (WebGLFrameSink.stripe) {
			fragmentShader = compileShader(gl.FRAGMENT_SHADER, YCBCR_STRIPE_FRAGMENT_SHADER);
		} else {
			fragmentShader = compileShader(gl.FRAGMENT_SHADER, YCBCR_FRAGMENT_SHADER);
		}

		program = gl.createProgram();
		gl.attachShader(program, vertexShader);
		checkError();

		gl.attachShader(program, fragmentShader);
		checkError();

		gl.linkProgram(program);
		if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
			var err = gl.getProgramInfoLog(program);
			gl.deleteProgram(program);
			throw new Error('GL program linking failed: ' + err);
		}

		gl.useProgram(program);
		checkError();

		if (WebGLFrameSink.stripe) {
			attachTexture(
				'uStripeLuma',
				gl.TEXTURE3,
				3,
				yCbCrBuffer.strideY * 4,
				yCbCrBuffer.height,
				buildStripe(yCbCrBuffer.strideY, yCbCrBuffer.height)
			);
			checkError();

			attachTexture(
				'uStripeChroma',
				gl.TEXTURE4,
				4,
				yCbCrBuffer.strideCb * 4,
				yCbCrBuffer.height >> yCbCrBuffer.vdec,
				buildStripe(yCbCrBuffer.strideCb, yCbCrBuffer.height >> yCbCrBuffer.vdec)
			);
			checkError();
		}
	}

	self.drawFrame = function(yCbCrBuffer) {
		if (!program) {
			init(yCbCrBuffer);
		}

		// Set up the rectangle and draw it

		//
		// Set up geometry
		//

		buffer = gl.createBuffer();
		checkError();

		gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
		checkError();

		gl.bufferData(gl.ARRAY_BUFFER, rectangle, gl.STATIC_DRAW);
		checkError();

		var positionLocation = gl.getAttribLocation(program, 'aPosition');
		checkError();

		gl.enableVertexAttribArray(positionLocation);
		checkError();

		gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
		checkError();

		// Set up the texture geometry...
		function setupTexturePosition(varname, texWidth, texHeight) {
			// Warning: assumes that the stride for Cb and Cr is the same size in output pixels
			var textureX0 = videoInfo.picX / texWidth;
			var textureX1 = (videoInfo.picX + videoInfo.picWidth) / texWidth;
			var textureY0 = (videoInfo.picY + videoInfo.picHeight) / texHeight;
			var textureY1 = videoInfo.picY / texHeight;
			var textureRectangle = new Float32Array([
				textureX0, textureY0,
				textureX1, textureY0,
				textureX0, textureY1,
				textureX0, textureY1,
				textureX1, textureY0,
				textureX1, textureY1
			]);

			var texturePositionBuffer = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, texturePositionBuffer);
			checkError();

			gl.bufferData(gl.ARRAY_BUFFER, textureRectangle, gl.STATIC_DRAW);
			checkError();

			var texturePositionLocation = gl.getAttribLocation(program, varname);
			checkError();

			gl.enableVertexAttribArray(texturePositionLocation);
			checkError();

			gl.vertexAttribPointer(texturePositionLocation, 2, gl.FLOAT, false, 0, 0);
			checkError();
		}
		setupTexturePosition('aLumaPosition', yCbCrBuffer.strideY, yCbCrBuffer.height);
		setupTexturePosition('aChromaPosition', yCbCrBuffer.strideCb << yCbCrBuffer.hdec, yCbCrBuffer.height);

		// Create the textures...
		var textureY = attachTexture(
			'uTextureY',
			gl.TEXTURE0,
			0,
			yCbCrBuffer.strideY,
			yCbCrBuffer.height,
			yCbCrBuffer.bytesY
		);
		var textureCb = attachTexture(
			'uTextureCb',
			gl.TEXTURE1,
			1,
			yCbCrBuffer.strideCb,
			yCbCrBuffer.height >> yCbCrBuffer.vdec,
			yCbCrBuffer.bytesCb
		);
		var textureCr = attachTexture(
			'uTextureCr',
			gl.TEXTURE2,
			2,
			yCbCrBuffer.strideCr,
			yCbCrBuffer.height >> yCbCrBuffer.vdec,
			yCbCrBuffer.bytesCr
		);

		// Aaaaand draw stuff.
		gl.drawArrays(gl.TRIANGLES, 0, rectangle.length / 2);
		checkError();
	};

	self.clear = function() {
		gl.clearColor(0.0, 0.0, 0.0, 0.0);
		gl.clear(gl.COLOR_BUFFER_BIT);
	};

	// @fixme make the clearing work reliably
	self.clear();
	gl.viewport(0, 0, canvas.width, canvas.height);
	self.clear();

	return self;
}

// For Windows; luminance and alpha textures are ssllooww to upload,
// so we pack into RGBA and unpack in the shaders.
//
// This seems to affect all browsers on Windows, probably due to fun
// mismatches between GL and D3D.
WebGLFrameSink.stripe = (function() {
	if (navigator.userAgent.indexOf('Windows') !== -1) {
		return true;
	}
	return false;
})();

/**
 * Static function to check if WebGL will be available with appropriate features.
 *
 * @return boolean
 */
WebGLFrameSink.isAvailable = function() {
	var canvas = document.createElement('canvas'),
		gl;
	canvas.width = 1;
	canvas.height = 1;
	var options = {
		// Still dithering on whether to use this.
		// Recommend avoiding it, as it's overly conservative
		//failIfMajorPerformanceCaveat: true
	};
	try {
		gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options);
	} catch (e) {
		return false;
	}
	if (gl) {
		var register = gl.TEXTURE0,
			width = 4,
			height = 4,
			texture = gl.createTexture(),
			data = new Uint8Array(width * height),
			texWidth = WebGLFrameSink.stripe ? (width / 4) : width,
			format = WebGLFrameSink.stripe ? gl.RGBA : gl.LUMINANCE,
			filter = WebGLFrameSink.stripe ? gl.NEAREST : gl.LINEAR;

		gl.activeTexture(register);
		gl.bindTexture(gl.TEXTURE_2D, texture);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
		gl.texImage2D(
			gl.TEXTURE_2D,
			0, // mip level
			format, // internal format
			texWidth,
			height,
			0, // border
			format, // format
			gl.UNSIGNED_BYTE, //type
			data // data!
		);

		var err = gl.getError();
		if (err) {
			// Doesn't support luminance textures?
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
};

module.exports = WebGLFrameSink;


text:
/**
 * This file is generated with Kurento ktool-rom-processor.
 * Please don't edit. Changes should go to kms-interface-rom and
 * ktool-rom-processor templates.
 */
package org.kurento.client;

/**
 *
 * Statistics related to the peer connection.
 *
 **/
@org.kurento.client.internal.ModuleName ("kurento")
public class RTCPeerConnectionStats extends RTCStats {

/**
 *
 * Represents the number of unique datachannels opened.
 *
 **/
    private long dataChannelsOpened;
/**
 *
 * Represents the number of unique datachannels closed.
 *
 **/
    private long dataChannelsClosed;

/**
 *
 * Default private constructor of RTCPeerConnectionStats for serialization with Jackson
 *
 **/
			protected RTCPeerConnectionStats() {
				super();
			}

/**
 *
 * Create a RTCPeerConnectionStats
 *
 **/
    public RTCPeerConnectionStats(@org.kurento.client.internal.server.Param("id") String id, @org.kurento.client.internal.server.Param("type") org.kurento.client.StatsType type, @org.kurento.client.internal.server.Param("timestamp") double timestamp, @org.kurento.client.internal.server.Param("dataChannelsOpened") long dataChannelsOpened, @org.kurento.client.internal.server.Param("dataChannelsClosed") long dataChannelsClosed) {

	super(
id,
type,
timestamp);

        this.dataChannelsOpened = dataChannelsOpened;
        this.dataChannelsClosed = dataChannelsClosed;
    }

/**
 *
 * get Represents the number of unique datachannels opened.
 *
 **/
    public long getDataChannelsOpened(){
    	return dataChannelsOpened;
    }

/**
 *
 * set Represents the number of unique datachannels opened.
 *
 **/
    public void setDataChannelsOpened(long dataChannelsOpened){
    	this.dataChannelsOpened = dataChannelsOpened;
    }

/**
 *
 * get Represents the number of unique datachannels closed.
 *
 **/
    public long getDataChannelsClosed(){
    	return dataChannelsClosed;
    }

/**
 *
 * set Represents the number of unique datachannels closed.
 *
 **/
    public void setDataChannelsClosed(long dataChannelsClosed){
    	this.dataChannelsClosed = dataChannelsClosed;
    }

}