text:
<?php

class ErrorController extends Zend_Controller_Action
{

    public function errorAction()
    {

        $this->getResponse()->clearBody();

        $errors = $this->_getParam('error_handler');

        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
            return;
        }

        $code = $errors->exception->getCode();
        if(!$code) {
            switch ($errors->type) {
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                    $code = 404;
                    break;
                default:
                    $code = 500;
                    break;
            }

        }

        // 400  Bad Request
        // 401  Authorization Required
        // 402  Payment Required (not used yet)
        // 403  Forbidden
        // 404  Not Found
        // 405  Method Not Allowed
        // 406  Not Acceptable (encoding)
        // 407  Proxy Authentication Required
        // 408  Request Timed Out
        // 409  Conflicting Request
        // 410  Gone
        // 411  Content Length Required
        // 412  Precondition Failed
        // 413  Request Entity Too Long
        // 414  Request URI Too Long
        // 415  Unsupported Media Type
        // Server Errors
        // 500  Internal Server Error
        // 501  Not Implemented
        // 502  Bad Gateway
        // 503  Service Unavailable
        // 504  Gateway Timeout
        // 505  HTTP Version Not Supported
        $this->view->errorCode = $code;
        switch ($code) {
            case 401:
                $this->getResponse()->setHttpResponseCode(401);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Brak dostępu';
                break;

            case 404:
                $this->getResponse()->setHttpResponseCode(404);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Strona nie istnieje';
                break;

            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Błąd strony ' . ($code);
                break;
        }

        // Log exception, if logger available
        $log = $this->_getLog();
        if (is_a($log, 'Zend_Log')) {
            $log->log($this->view->message, $priority, $errors->exception);
            $log->log('Message : ' . $errors->exception->getMessage(), $priority);
            if(APPLICATION_ENV != 'production') {
                // log extra info\
                $log->log( 'Error Details : ' . PHP_EOL
                         . 'Request Parameters : ' . var_export($errors->request->getParams(), true) . PHP_EOL
                         . 'Stack Trace : ' . PHP_EOL . $errors->exception->getTraceAsString()
                         , $priority);

            }
        }

        $this->view->request   = $errors->request;
    }

    public function noauthAction()
    {

    }

    private function _getLog()
    {
        if (!Zend_Registry::isRegistered('log')) {
            return false;
        }
        $log = Zend_Registry::get('log');
        return $log;
    }

}


text:
import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform

if sys.version_info >= (3, 3):
    import importlib.machinery
    def _extension_suffixes():
        return importlib.machinery.EXTENSION_SUFFIXES[:]
else:
    import imp
    def _extension_suffixes():
        return [suffix for suffix, _, type in imp.get_suffixes()
                if type == imp.C_EXTENSION]

if sys.version_info >= (3,):
    NativeIO = io.StringIO
else:
    class NativeIO(io.BytesIO):
        def write(self, s):
            if isinstance(s, unicode):
                s = s.encode('ascii')
            super(NativeIO, self).write(s)

def _hack_at_distutils():
    # Windows-only workaround for some configurations: see
    # https://bugs.python.org/issue23246 (Python 2.7 with
    # a specific MS compiler suite download)
    if sys.platform == "win32":
        try:
            import setuptools    # for side-effects, patches distutils
        except ImportError:
            pass

class Verifier(object):

    def __init__(self, ffi, preamble, tmpdir=None, modulename=None,
                 ext_package=None, tag='', force_generic_engine=False,
                 source_extension='.c', flags=None, relative_to=None, **kwds):
        if ffi._parser._uses_new_feature:
            raise ffiplatform.VerificationError(
                "feature not supported with ffi.verify(), but only "
                "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,))
        self.ffi = ffi
        self.preamble = preamble
        if not modulename:
            flattened_kwds = ffiplatform.flatten(kwds)
        vengine_class = _locate_engine_class(ffi, force_generic_engine)
        self._vengine = vengine_class(self)
        self._vengine.patch_extension_kwds(kwds)
        self.flags = flags
        self.kwds = self.make_relative_to(kwds, relative_to)
        #
        if modulename:
            if tag:
                raise TypeError("can't specify both 'modulename' and 'tag'")
        else:
            key = '\x00'.join([sys.version[:3], __version_verifier_modules__,
                               preamble, flattened_kwds] +
                              ffi._cdefsources)
            if sys.version_info >= (3,):
                key = key.encode('utf-8')
            k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
            k1 = k1.lstrip('0x').rstrip('L')
            k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
            k2 = k2.lstrip('0').rstrip('L')
            modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key,
                                              k1, k2)
        suffix = _get_so_suffixes()[0]
        self.tmpdir = tmpdir or _caller_dir_pycache()
        self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension)
        self.modulefilename = os.path.join(self.tmpdir, modulename + suffix)
        self.ext_package = ext_package
        self._has_source = False
        self._has_module = False

    def write_source(self, file=None):
        """Write the C source code.  It is produced in 'self.sourcefilename',
        which can be tweaked beforehand."""
        with self.ffi._lock:
            if self._has_source and file is None:
                raise ffiplatform.VerificationError(
                    "source code already written")
            self._write_source(file)

    def compile_module(self):
        """Write the C source code (if not done already) and compile it.
        This produces a dynamic link library in 'self.modulefilename'."""
        with self.ffi._lock:
            if self._has_module:
                raise ffiplatform.VerificationError("module already compiled")
            if not self._has_source:
                self._write_source()
            self._compile_module()

    def load_library(self):
        """Get a C module from this Verifier instance.
        Returns an instance of a FFILibrary class that behaves like the
        objects returned by ffi.dlopen(), but that delegates all
        operations to the C module.  If necessary, the C code is written
        and compiled first.
        """
        with self.ffi._lock:
            if not self._has_module:
                self._locate_module()
                if not self._has_module:
                    if not self._has_source:
                        self._write_source()
                    self._compile_module()
            return self._load_library()

    def get_module_name(self):
        basename = os.path.basename(self.modulefilename)
        # kill both the .so extension and the other .'s, as introduced
        # by Python 3: 'basename.cpython-33m.so'
        basename = basename.split('.', 1)[0]
        # and the _d added in Python 2 debug builds --- but try to be
        # conservative and not kill a legitimate _d
        if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'):
            basename = basename[:-2]
        return basename

    def get_extension(self):
        _hack_at_distutils() # backward compatibility hack
        if not self._has_source:
            with self.ffi._lock:
                if not self._has_source:
                    self._write_source()
        sourcename = ffiplatform.maybe_relative_path(self.sourcefilename)
        modname = self.get_module_name()
        return ffiplatform.get_extension(sourcename, modname, **self.kwds)

    def generates_python_module(self):
        return self._vengine._gen_python_module

    def make_relative_to(self, kwds, relative_to):
        if relative_to and os.path.dirname(relative_to):
            dirname = os.path.dirname(relative_to)
            kwds = kwds.copy()
            for key in ffiplatform.LIST_OF_FILE_NAMES:
                if key in kwds:
                    lst = kwds[key]
                    if not isinstance(lst, (list, tuple)):
                        raise TypeError("keyword '%s' should be a list or tuple"
                                        % (key,))
                    lst = [os.path.join(dirname, fn) for fn in lst]
                    kwds[key] = lst
        return kwds

    # ----------

    def _locate_module(self):
        if not os.path.isfile(self.modulefilename):
            if self.ext_package:
                try:
                    pkg = __import__(self.ext_package, None, None, ['__doc__'])
                except ImportError:
                    return      # cannot import the package itself, give up
                    # (e.g. it might be called differently before installation)
                path = pkg.__path__
            else:
                path = None
            filename = self._vengine.find_module(self.get_module_name(), path,
                                                 _get_so_suffixes())
            if filename is None:
                return
            self.modulefilename = filename
        self._vengine.collect_types()
        self._has_module = True

    def _write_source_to(self, file):
        self._vengine._f = file
        try:
            self._vengine.write_source_to_f()
        finally:
            del self._vengine._f

    def _write_source(self, file=None):
        if file is not None:
            self._write_source_to(file)
        else:
            # Write our source file to an in memory file.
            f = NativeIO()
            self._write_source_to(f)
            source_data = f.getvalue()

            # Determine if this matches the current file
            if os.path.exists(self.sourcefilename):
                with open(self.sourcefilename, "r") as fp:
                    needs_written = not (fp.read() == source_data)
            else:
                needs_written = True

            # Actually write the file out if it doesn't match
            if needs_written:
                _ensure_dir(self.sourcefilename)
                with open(self.sourcefilename, "w") as fp:
                    fp.write(source_data)

            # Set this flag
            self._has_source = True

    def _compile_module(self):
        # compile this C source
        tmpdir = os.path.dirname(self.sourcefilename)
        outputfilename = ffiplatform.compile(tmpdir, self.get_extension())
        try:
            same = ffiplatform.samefile(outputfilename, self.modulefilename)
        except OSError:
            same = False
        if not same:
            _ensure_dir(self.modulefilename)
            shutil.move(outputfilename, self.modulefilename)
        self._has_module = True

    def _load_library(self):
        assert self._has_module
        if self.flags is not None:
            return self._vengine.load_library(self.flags)
        else:
            return self._vengine.load_library()

# ____________________________________________________________

_FORCE_GENERIC_ENGINE = False      # for tests

def _locate_engine_class(ffi, force_generic_engine):
    if _FORCE_GENERIC_ENGINE:
        force_generic_engine = True
    if not force_generic_engine:
        if '__pypy__' in sys.builtin_module_names:
            force_generic_engine = True
        else:
            try:
                import _cffi_backend
            except ImportError:
                _cffi_backend = '?'
            if ffi._backend is not _cffi_backend:
                force_generic_engine = True
    if force_generic_engine:
        from . import vengine_gen
        return vengine_gen.VGenericEngine
    else:
        from . import vengine_cpy
        return vengine_cpy.VCPythonEngine

# ____________________________________________________________

_TMPDIR = None

def _caller_dir_pycache():
    if _TMPDIR:
        return _TMPDIR
    result = os.environ.get('CFFI_TMPDIR')
    if result:
        return result
    filename = sys._getframe(2).f_code.co_filename
    return os.path.abspath(os.path.join(os.path.dirname(filename),
                           '__pycache__'))

def set_tmpdir(dirname):
    """Set the temporary directory to use instead of __pycache__."""
    global _TMPDIR
    _TMPDIR = dirname

def cleanup_tmpdir(tmpdir=None, keep_so=False):
    """Clean up the temporary directory by removing all files in it
    called `_cffi_*.{c,so}` as well as the `build` subdirectory."""
    tmpdir = tmpdir or _caller_dir_pycache()
    try:
        filelist = os.listdir(tmpdir)
    except OSError:
        return
    if keep_so:
        suffix = '.c'   # only remove .c files
    else:
        suffix = _get_so_suffixes()[0].lower()
    for fn in filelist:
        if fn.lower().startswith('_cffi_') and (
                fn.lower().endswith(suffix) or fn.lower().endswith('.c')):
            try:
                os.unlink(os.path.join(tmpdir, fn))
            except OSError:
                pass
    clean_dir = [os.path.join(tmpdir, 'build')]
    for dir in clean_dir:
        try:
            for fn in os.listdir(dir):
                fn = os.path.join(dir, fn)
                if os.path.isdir(fn):
                    clean_dir.append(fn)
                else:
                    os.unlink(fn)
        except OSError:
            pass

def _get_so_suffixes():
    suffixes = _extension_suffixes()
    if not suffixes:
        # bah, no C_EXTENSION available.  Occurs on pypy without cpyext
        if sys.platform == 'win32':
            suffixes = [".pyd"]
        else:
            suffixes = [".so"]

    return suffixes

def _ensure_dir(filename):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError:
        pass

redpajama_set_name: RedPajamaGithub


text:
/**
 * @constructor
 * @extends {WebInspector.RequestContentView}
 * @param {WebInspector.NetworkRequest} request
 */
WebInspector.RequestPreviewView = function(request, responseView)
{
    WebInspector.RequestContentView.call(this, request);
    this._responseView = responseView;
}

WebInspector.RequestPreviewView.prototype = {
    contentLoaded: function()
    {
        if (!this.request.content) {
            if (!this._emptyView) {
                this._emptyView = this._createEmptyView();
                this._emptyView.show(this.element);
                this.innerView = this._emptyView;
            }
        } else {
            if (this._emptyView) {
                this._emptyView.detach();
                delete this._emptyView;
            }

            if (!this._previewView)
                this._previewView = this._createPreviewView();
            this._previewView.show(this.element);
            this.innerView = this._previewView;
        }
    },

    _createEmptyView: function()
    {
        return new WebInspector.EmptyView(WebInspector.UIString("This request has no preview available."));
    },

    _jsonView: function()
    {
        var parsedJSON = WebInspector.RequestJSONView.parseJSON(this.request.content);
        if (parsedJSON)
            return new WebInspector.RequestJSONView(this.request, parsedJSON);
    },

    _htmlView: function()
    {
        var dataURL = this.request.asDataURL();
        if (dataURL !== null)
            return new WebInspector.RequestHTMLView(this.request, dataURL);
    },

    _createPreviewView: function()
    {
        if (this.request.content) {
            if (this.request.mimeType === "application/json") {
                var jsonView = this._jsonView();
                if (jsonView)
                    return jsonView;
            }

            if (this.request.hasErrorStatusCode()) {
                var htmlView = this._htmlView();
                if (htmlView)
                    return htmlView;
            }

            if (this.request.type === WebInspector.resourceTypes.XHR) {
                var jsonView = this._jsonView();
                if (jsonView)
                    return jsonView;
            }

            if (this.request.type === WebInspector.resourceTypes.XHR && this.request.mimeType === "text/html") {
                var htmlView = this._htmlView();
                if (htmlView)
                    return htmlView;
            }
        }

        if (this._responseView.sourceView)
            return this._responseView.sourceView;

        if (this.request.type === WebInspector.resourceTypes.Other)
            return this._createEmptyView();

        return WebInspector.RequestView.nonSourceViewForRequest(this.request);
    },

    __proto__: WebInspector.RequestContentView.prototype
}


text:
package com.orhanobut.wasp;

public interface NetworkStack {

  void invokeRequest(RequestCreator requestCreator, InternalCallback<Response> waspCallback);

  Object invokeRequest(RequestCreator requestCreator) throws Exception;
}


text:
#pragma once

#include <kitBase/robotModel/robotParts/device.h>
#include <kitBase/kitBaseDeclSpec.h>

namespace kitBase {
namespace robotModel {
namespace robotParts {

/// Abstract sensor device which can be asked to provide readings. Signals with readings are defined in subclasses
/// since readings can have different types, like scalars for touch or range sensor, or vector for accelerometer.
/// Sensors can also work in "push" mode, providing values as soon as they are ready, in that case "read()" call is
/// ignored.
/// General workflow is to subscribe to "newData" and "failure" signals and call read().
class ROBOTS_KIT_BASE_EXPORT AbstractSensor : public Device
{
	Q_OBJECT
	Q_CLASSINFO("direction", "input")
	Q_PROPERTY(bool locked READ isLocked WRITE setLocked)

public:
	/// Constructor, takes device type info and port on which this sensor is configured.
	AbstractSensor(const DeviceInfo &info, const PortInfo &port);

	/// Ask sensor to provide new readings. Returns immediately. When reading is done, sensor emits "newData" signal
	/// with reading as a parameter.
	/// This call is ignored if sensor works in a "push" mode and always provides readings as soon as they are ready.
	/// If more than one call of "read" was made before sensor returned values, subsequent calls are ignored.
	virtual void read() = 0;

	/// Returns true if sensor state was locked for writing. That means that last obtained sensor value
	/// will not be refreshed until setLocked(true) will be called.
	bool isLocked() const;

	/// Locks or unlocks sensor state for writing. If true is passed last obtained sensor value will be frozen.
	/// If false values will be refreshed again. Ideologically lock must be removed before interpretation starts.
	void setLocked(bool locked);

signals:
	/// Emitted when sensor reading is failed for some reason. Note that it is possible that sensor will not emit any
	/// signal in case of a failure, so if "failure()" is emitted, the sensor is failed, but if not, sensor may be still
	/// preparing readings and it can take some time, or simply failed silently.
	void failure();

private:
	bool mIsLocked;
};

}
}
}


text:
package org.motechproject.tasks.contract.builder;

import org.junit.Test;
import org.motechproject.tasks.contract.ActionEventRequest;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class ActionEventRequestBuilderTest {

    private static final String SERVICE_METHOD = "service.method";
    private static final String SERVICE_INTERFACE = "service.interface";
    private static final String SUBJECT = "some-subject";

    @Test
    public void shouldTestSubjectAvailability() {
        TestActionEventRequestBuilder requestBuilder = new TestActionEventRequestBuilder();
        ActionEventRequest requestWithSubject = requestBuilder.setSubject(SUBJECT).createActionEventRequest();
        assertThat(requestWithSubject.hasSubject(), is(true));
        ActionEventRequest requestWithoutSubject = requestBuilder.setNullSubject().createActionEventRequest();
        assertThat(requestWithoutSubject.hasSubject(), is(false));
        ActionEventRequest requestWithEmptySubject = requestBuilder.setEmptySubject().createActionEventRequest();
        assertThat(requestWithEmptySubject.hasSubject(), is(false));
    }

    @Test
    public void shouldTestServiceAvailability() {
        TestActionEventRequestBuilder requestBuilder = new TestActionEventRequestBuilder();
        ActionEventRequest fullyFormedRequest = requestBuilder.setServiceInterface(SERVICE_INTERFACE).setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(fullyFormedRequest.hasService(), is(true));

        ActionEventRequest requestWithoutServiceInterface = requestBuilder.setNullServiceInterface().setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(requestWithoutServiceInterface.hasService(), is(false));
        ActionEventRequest requestWithEmptyServiceInterface = requestBuilder.setEmptyServiceInterface().setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(requestWithEmptyServiceInterface.hasService(), is(false));

        ActionEventRequest requestWithoutServiceMethod = requestBuilder.setServiceInterface(SERVICE_INTERFACE).setNullServiceMethod().createActionEventRequest();
        assertThat(requestWithoutServiceMethod.hasService(), is(false));
        ActionEventRequest requestWithEmptyServiceMethod = requestBuilder.setServiceInterface(SERVICE_INTERFACE).setEmptyServiceMethod().createActionEventRequest();
        assertThat(requestWithEmptyServiceMethod.hasService(), is(false));
    }

    @Test
    public void shouldConsiderRequestValidIfEitherSubjectOrServicePresent() {
        TestActionEventRequestBuilder requestBuilder = new TestActionEventRequestBuilder();

        ActionEventRequest fullyFormedRequest = requestBuilder.setSubject(SUBJECT).setServiceInterface(SERVICE_INTERFACE).setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(fullyFormedRequest.isValid(), is(true));

        ActionEventRequest requestWithSubjectButNotService = requestBuilder.setSubject(SUBJECT).setNullServiceInterface().setNullServiceMethod().createActionEventRequest();
        assertThat(requestWithSubjectButNotService.isValid(), is(true));

        ActionEventRequest requestWithoutSubjectButWithService = requestBuilder.setNullSubject().setServiceInterface(SERVICE_INTERFACE).setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(requestWithoutSubjectButWithService.isValid(), is(true));

        ActionEventRequest requestWithoutSubjectAndWithoutService = requestBuilder.setNullSubject().setNullServiceInterface().setNullServiceMethod().createActionEventRequest();
        assertThat(requestWithoutSubjectAndWithoutService.isValid(), is(false));

        ActionEventRequest requestWithoutSubjectAndWithServiceMethodOnly = requestBuilder.setNullSubject().setNullServiceInterface().setServiceMethod(SERVICE_METHOD).createActionEventRequest();
        assertThat(requestWithoutSubjectAndWithServiceMethodOnly.isValid(), is(false));

        ActionEventRequest requestWithoutSubjectAndWithServiceInterfaceOnly = requestBuilder.setNullSubject().setServiceInterface(SERVICE_INTERFACE).setNullServiceMethod().createActionEventRequest();
        assertThat(requestWithoutSubjectAndWithServiceInterfaceOnly.isValid(), is(false));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.wso2</groupId>
        <artifactId>connectedlap-component</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <version>1.0.0-SNAPSHOT</version>
    <artifactId>${project-base-package}.plugin</artifactId>
    <packaging>bundle</packaging>
    <name>${project-base-package}.plugin</name>
    <url>http://wso2.org</url>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${org.apache.felix.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
                        <Bundle-Name>${project-base-package}.plugin</Bundle-Name>
                        <Bundle-Version>1.0.0-SNAPSHOT</Bundle-Version>
                        <Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
                        <Private-Package>${project-base-package}.plugin.internal</Private-Package>
                        <Import-Package>
                            org.osgi.framework,
                            org.osgi.service.component,
                            org.apache.commons.logging,
                            javax.naming;resolution:=optional,
                            javax.sql;resolution:=optional,
                            org.wso2.carbon.device.mgt.common.*,
                            org.wso2.carbon.device.mgt.common,
                            org.wso2.carbon.device.mgt.iot.*,
                            org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
                            org.wso2.carbon.utils.*,
                            org.wso2.carbon.event.output.adapter.core,
                            org.wso2.carbon.event.output.adapter.core.exception,
                            org.wso2.carbon.base,
                            org.wso2.carbon.core.util,
                            org.wso2.carbon.context,
                            org.wso2.carbon.core,
                            org.apache.commons.codec.binary
                        </Import-Package>
                        <Export-Package>
                            !${project-base-package}.plugin.internal,
                            ${project-base-package}.plugin.*
                        </Export-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>commons-codec.wso2</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi.services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.devicemgt</groupId>
            <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.devicemgt</groupId>
            <artifactId>org.wso2.carbon.device.mgt.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.ndatasource.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.devicemgt</groupId>
            <artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.analytics-common</groupId>
            <artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
        </dependency>
    </dependencies>
</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Switch terminal into raw mode</title>

ncurses_qiflush

ncurses_refresh

Ncurses Functions

PHP Manual

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Switch terminal into raw mode

Description

   bool ncurses_raw
    ( void
   )

Warning
This function is
EXPERIMENTAL. The behaviour of this function, its name, and
surrounding documentation may change without notice in a future release of PHP.
This function should be used at your own risk.

   Places the terminal in raw mode. Raw mode is similar to cbreak mode, in
   that characters typed are immediately passed through to the user program.
   The differences that are that in raw mode, the interrupt, quit, suspend
   and flow control characters are all passed through uninterpreted, instead
   of generating a signal.

Return Values

   Returns TRUE if any error occurred, otherwise FALSE.

See Also

ncurses_noraw() - Switch terminal out of raw mode

ncurses_cbreak() - Switch off input buffering

ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_qiflush

ncurses_refresh

Ncurses Functions

PHP Manual


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Contr. Univ. Mich. Herb. 5: 33 (1941)

#### Original name
Psathyra multipedata Peck, 1905

### Remarks
null


text:
setopt always_to_end            # When complete from middle, move cursor
setopt append_history           # Append to history file, not overwrite it
setopt auto_cd                  # If a command is not in the hash table, and there exists an executable directory by that name, perform the cd command to that directory.
setopt complete_in_word         # Always auto complete, not just at the end
setopt extendedglob             # Extra filename generation features
setopt hist_ignore_dups         # Don't enter command in history if it is duplicate of previous command
setopt hist_find_no_dups        # Don't display duplicates when searching commands
setopt inc_append_history       # Append history item as soon as command is executed, rather than waiting until the shell is killed
setopt nobeep                   # Kill the fscking beep!
setopt nohup										# In general, we don't kill background jobs upon logging out
setopt prompt_subst             # parameter expansion, command substitution and arithmetic expansion is performed in prompts


text:
all :
	# Generate Parser
	bison -d calc.y
	mv calc.tab.c calc.tab.cc
	clang++ -g -std=c++14 -Wall -Wextra -Wpedantic -Wno-unused-function -c calc.tab.cc -o calc.y.o

	# Lexical analyser
	flex -o lex.yy.cc calc.lex
	clang++ -g -std=c++14 -Wall -Wextra -Wpedantic -Wno-unused-function -c lex.yy.cc -o calc.lex.o

	# Link
	clang++ -g -std=c++14 -Wall -Wextra -Wpedantic -o calc calc.lex.o calc.y.o -ll -lm

clean:
	rm -f calc calc.tab.h lex.yy.c calc.lex.o calc.tab.c calc.y.o calc.tab.cc calc.tab.hh lex.yy.cc

format:
	clang-format -style=file -i arbnumber.h calculate_funcs.h global.h helper_funcs.h parse_helper_funcs.h table.h


text:
package com.danielwestheide.kontextfrei

import scala.collection.immutable.Seq
import scala.reflect.ClassTag

private[kontextfrei] trait DCollectionConstructors[DCollection[_]] {
  def unit[A: ClassTag](as: Seq[A]): DCollection[A]
  def empty[A: ClassTag]: DCollection[A]
}


text:
package org.coursera.naptime.ari.graphql.schema

import com.linkedin.data.DataMap
import org.coursera.naptime.ari.graphql.SangriaGraphQlContext
import sangria.schema.Context

case class ParentContext(parentContext: Context[SangriaGraphQlContext, DataMap])


text:
package io.virtdata.libbasics.shared.from_long.to_int;

import io.virtdata.annotations.ThreadSafeMapper;

import java.util.function.LongToIntFunction;

@ThreadSafeMapper
public class Add implements LongToIntFunction {

    private final long addend;

    public Add(int addend) {
        this.addend = addend;
    }

    @Override
    public int applyAsInt(long value) {
        return (int) ((value + addend) % Integer.MAX_VALUE);
    }
}


text:
#ifndef __ASMARM_SETUP_H
#define __ASMARM_SETUP_H

#include <uapi/asm/setup.h>

#define __tag __used __attribute__((__section__(".taglist.init")))
#define __tagtable(tag, fn) \
static const struct tagtable __tagtable_##fn __tag = { tag, fn }

extern int arm_add_memory(u64 start, u64 size);
extern void early_print(const char *str, ...);
extern void dump_machine_table(void);

#endif


text:
CURRENT_COMMIT=`git rev-parse HEAD`

if [[ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == "false" ]]; then
echo "Starting to update gh-pages\n"

#copy data we're interested in to other place
cp -R dist $HOME/dist

#go to home and setup git
cd $HOME
git config --global user.email "travis@travis-ci.org"
git config --global user.name "Travis"

#using token clone gh-pages branch
git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages > /dev/null

	#go into directory and copy data we're interested in to that directory
cd gh-pages
cp -Rf $HOME/dist/* .

echo "Allow files with underscore https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/" > .nojekyll

echo "[View live](http://voorhoede.github.io/front-end-guide/)" > README.md

 #add, commit and push files
 git add -f .
 git commit -m "Travis build $TRAVIS_BUILD_NUMBER pushed to gh-pages"
 git push -fq origin gh-pages > /dev/null

 echo "Done updating gh-pages\n"
 else
 echo "Updating gh-pages skipped, because Travis is not notified from the master branch."
 fi;


text:
module Melt

  def self.included(base)
    @melt_builders = {}
  end

  def define_response(name, &block)
    @melt_builders[name.to_sym] = block
  end

  def melt
    Melt::Responder.new(self, @melt_builders)
  end

end


text:
class Task;
class WaitItem
{
public:
    WaitItem() : task(nullptr), next(nullptr) {}

    Task *task;
    WaitItem *next;
};

class Waitlist
{
    friend class WaitItem;
public:
    Waitlist() : head(nullptr), tail(nullptr) {}
    void enqueue();
    void dequeue();
    void abort();
    bool empty();

private:
    WaitItem *head;
    WaitItem *tail;
};


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package org.acre.lang.node;

import java.util.*;
import org.acre.lang.analysis.*;

public final class ADoubleType extends PType
{
    private TDouble _double_;

    public ADoubleType()
    {
    }

    public ADoubleType(
        TDouble _double_)
    {
        setDouble(_double_);

    }
    public Object clone()
    {
        return new ADoubleType(
            (TDouble) cloneNode(_double_));
    }

    public void apply(Switch sw)
    {
        ((Analysis) sw).caseADoubleType(this);
    }

    public TDouble getDouble()
    {
        return _double_;
    }

    public void setDouble(TDouble node)
    {
        if(_double_ != null)
        {
            _double_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        _double_ = node;
    }

    public String toString()
    {
        return ""
            + toString(_double_);
    }

    void removeChild(Node child)
    {
        if(_double_ == child)
        {
            _double_ = null;
            return;
        }

    }

    void replaceChild(Node oldChild, Node newChild)
    {
        if(_double_ == oldChild)
        {
            setDouble((TDouble) newChild);
            return;
        }

    }
}


text:
package xorm

import (
	"database/sql"
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"xorm.io/core"
)

func TestGetVar(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type GetVar struct {
		Id      int64  `xorm:"autoincr pk"`
		Msg     string `xorm:"varchar(255)"`
		Age     int
		Money   float32
		Created time.Time `xorm:"created"`
	}

	assert.NoError(t, testEngine.Sync2(new(GetVar)))

	var data = GetVar{
		Msg:   "hi",
		Age:   28,
		Money: 1.5,
	}
	_, err := testEngine.InsertOne(&data)
	assert.NoError(t, err)

	var msg string
	has, err := testEngine.Table("get_var").Cols("msg").Get(&msg)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, "hi", msg)

	var age int
	has, err = testEngine.Table("get_var").Cols("age").Get(&age)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, 28, age)

	var ageMax int
	has, err = testEngine.SQL("SELECT max(age) FROM "+testEngine.TableName("get_var", true)+" WHERE `id` = ?", data.Id).Get(&ageMax)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, 28, ageMax)

	var age2 int64
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age2)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age2)

	var age3 int8
	has, err = testEngine.Table("get_var").Cols("age").Get(&age3)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age3)

	var age4 int16
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age4)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age4)

	var age5 int32
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age5)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age5)

	var age6 int
	has, err = testEngine.Table("get_var").Cols("age").Get(&age6)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age6)

	var age7 int64
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age7)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age7)

	var age8 int8
	has, err = testEngine.Table("get_var").Cols("age").Get(&age8)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age8)

	var age9 int16
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age9)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age9)

	var age10 int32
	has, err = testEngine.Table("get_var").Cols("age").
		Where("age > ?", 20).
		And("age < ?", 30).
		Get(&age10)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.EqualValues(t, 28, age10)

	var id sql.NullInt64
	has, err = testEngine.Table("get_var").Cols("id").Get(&id)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, true, id.Valid)
	assert.EqualValues(t, data.Id, id.Int64)

	var msgNull sql.NullString
	has, err = testEngine.Table("get_var").Cols("msg").Get(&msgNull)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, true, msgNull.Valid)
	assert.EqualValues(t, data.Msg, msgNull.String)

	var nullMoney sql.NullFloat64
	has, err = testEngine.Table("get_var").Cols("money").Get(&nullMoney)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, true, nullMoney.Valid)
	assert.EqualValues(t, data.Money, nullMoney.Float64)

	var money float64
	has, err = testEngine.Table("get_var").Cols("money").Get(&money)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, "1.5", fmt.Sprintf("%.1f", money))

	var money2 float64
	if testEngine.Dialect().DBType() == core.MSSQL {
		has, err = testEngine.SQL("SELECT TOP 1 money FROM " + testEngine.TableName("get_var", true)).Get(&money2)
	} else {
		has, err = testEngine.SQL("SELECT money FROM " + testEngine.TableName("get_var", true) + " LIMIT 1").Get(&money2)
	}
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, "1.5", fmt.Sprintf("%.1f", money2))

	var money3 float64
	has, err = testEngine.SQL("SELECT money FROM " + testEngine.TableName("get_var", true) + " WHERE money > 20").Get(&money3)
	assert.NoError(t, err)
	assert.Equal(t, false, has)

	var valuesString = make(map[string]string)
	has, err = testEngine.Table("get_var").Get(&valuesString)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, 5, len(valuesString))
	assert.Equal(t, "1", valuesString["id"])
	assert.Equal(t, "hi", valuesString["msg"])
	assert.Equal(t, "28", valuesString["age"])
	assert.Equal(t, "1.5", valuesString["money"])

	// for mymysql driver, interface{} will be []byte, so ignore it currently
	if testEngine.Dialect().DriverName() != "mymysql" {
		var valuesInter = make(map[string]interface{})
		has, err = testEngine.Table("get_var").Where("id = ?", 1).Select("*").Get(&valuesInter)
		assert.NoError(t, err)
		assert.Equal(t, true, has)
		assert.Equal(t, 5, len(valuesInter))
		assert.EqualValues(t, 1, valuesInter["id"])
		assert.Equal(t, "hi", fmt.Sprintf("%s", valuesInter["msg"]))
		assert.EqualValues(t, 28, valuesInter["age"])
		assert.Equal(t, "1.5", fmt.Sprintf("%v", valuesInter["money"]))
	}

	var valuesSliceString = make([]string, 5)
	has, err = testEngine.Table("get_var").Get(&valuesSliceString)
	assert.NoError(t, err)
	assert.Equal(t, true, has)
	assert.Equal(t, "1", valuesSliceString[0])
	assert.Equal(t, "hi", valuesSliceString[1])
	assert.Equal(t, "28", valuesSliceString[2])
	assert.Equal(t, "1.5", valuesSliceString[3])

	var valuesSliceInter = make([]interface{}, 5)
	has, err = testEngine.Table("get_var").Get(&valuesSliceInter)
	assert.NoError(t, err)
	assert.Equal(t, true, has)

	v1, err := convertInt(valuesSliceInter[0])
	assert.NoError(t, err)
	assert.EqualValues(t, 1, v1)

	assert.Equal(t, "hi", fmt.Sprintf("%s", valuesSliceInter[1]))

	v3, err := convertInt(valuesSliceInter[2])
	assert.NoError(t, err)
	assert.EqualValues(t, 28, v3)

	v4, err := convertFloat(valuesSliceInter[3])
	assert.NoError(t, err)
	assert.Equal(t, "1.5", fmt.Sprintf("%v", v4))
}

func TestGetStruct(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type UserinfoGet struct {
		Uid   int `xorm:"pk autoincr"`
		IsMan bool
	}

	assert.NoError(t, testEngine.Sync2(new(UserinfoGet)))

	session := testEngine.NewSession()
	defer session.Close()

	var err error
	if testEngine.Dialect().DBType() == core.MSSQL {
		err = session.Begin()
		assert.NoError(t, err)
		_, err = session.Exec("SET IDENTITY_INSERT userinfo_get ON")
		assert.NoError(t, err)
	}
	cnt, err := session.Insert(&UserinfoGet{Uid: 2})
	assert.NoError(t, err)
	assert.EqualValues(t, 1, cnt)
	if testEngine.Dialect().DBType() == core.MSSQL {
		err = session.Commit()
		assert.NoError(t, err)
	}

	user := UserinfoGet{Uid: 2}
	has, err := testEngine.Get(&user)
	assert.NoError(t, err)
	assert.True(t, has)

	type NoIdUser struct {
		User   string `xorm:"unique"`
		Remain int64
		Total  int64
	}

	assert.NoError(t, testEngine.Sync2(&NoIdUser{}))

	userCol := testEngine.GetColumnMapper().Obj2Table("User")
	_, err = testEngine.Where("`"+userCol+"` = ?", "xlw").Delete(&NoIdUser{})
	assert.NoError(t, err)

	cnt, err = testEngine.Insert(&NoIdUser{"xlw", 20, 100})
	assert.NoError(t, err)
	assert.EqualValues(t, 1, cnt)

	noIdUser := new(NoIdUser)
	has, err = testEngine.Where("`"+userCol+"` = ?", "xlw").Get(noIdUser)
	assert.NoError(t, err)
	assert.True(t, has)
}

func TestGetSlice(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type UserinfoSlice struct {
		Uid   int `xorm:"pk autoincr"`
		IsMan bool
	}

	assertSync(t, new(UserinfoSlice))

	var users []UserinfoSlice
	has, err := testEngine.Get(&users)
	assert.False(t, has)
	assert.Error(t, err)
}

func TestGetError(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type GetError struct {
		Uid   int `xorm:"pk autoincr"`
		IsMan bool
	}

	assertSync(t, new(GetError))

	var info = new(GetError)
	has, err := testEngine.Get(&info)
	assert.False(t, has)
	assert.Error(t, err)

	has, err = testEngine.Get(info)
	assert.False(t, has)
	assert.NoError(t, err)
}

func TestJSONString(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type JsonString struct {
		Id      int64
		Content string `xorm:"json"`
	}
	type JsonJson struct {
		Id      int64
		Content []string `xorm:"json"`
	}

	assertSync(t, new(JsonJson))

	_, err := testEngine.Insert(&JsonJson{
		Content: []string{"1", "2"},
	})
	assert.NoError(t, err)

	var js JsonString
	has, err := testEngine.Table("json_json").Get(&js)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 1, js.Id)
	assert.EqualValues(t, `["1","2"]`, js.Content)

	var jss []JsonString
	err = testEngine.Table("json_json").Find(&jss)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, len(jss))
	assert.EqualValues(t, `["1","2"]`, jss[0].Content)
}

func TestGetActionMapping(t *testing.T) {
	assert.NoError(t, prepareEngine())

	type ActionMapping struct {
		ActionId    string `xorm:"pk"`
		ActionName  string `xorm:"index"`
		ScriptId    string `xorm:"unique"`
		RollbackId  string `xorm:"unique"`
		Env         string
		Tags        string
		Description string
		UpdateTime  time.Time `xorm:"updated"`
		DeleteTime  time.Time `xorm:"deleted"`
	}

	assertSync(t, new(ActionMapping))

	_, err := testEngine.Insert(&ActionMapping{
		ActionId: "1",
		ScriptId: "2",
	})
	assert.NoError(t, err)

	var valuesSlice = make([]string, 2)
	has, err := testEngine.Table(new(ActionMapping)).
		Cols("script_id", "rollback_id").
		ID("1").Get(&valuesSlice)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, "2", valuesSlice[0])
	assert.EqualValues(t, "", valuesSlice[1])
}

func TestGetStructId(t *testing.T) {
	type TestGetStruct struct {
		Id int64
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(TestGetStruct))

	_, err := testEngine.Insert(&TestGetStruct{})
	assert.NoError(t, err)
	_, err = testEngine.Insert(&TestGetStruct{})
	assert.NoError(t, err)

	type maxidst struct {
		Id int64
	}

	//var id int64
	var maxid maxidst
	sql := "select max(id) as id from " + testEngine.TableName(&TestGetStruct{}, true)
	has, err := testEngine.SQL(sql).Get(&maxid)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 2, maxid.Id)
}

func TestContextGet(t *testing.T) {
	type ContextGetStruct struct {
		Id   int64
		Name string
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(ContextGetStruct))

	_, err := testEngine.Insert(&ContextGetStruct{Name: "1"})
	assert.NoError(t, err)

	sess := testEngine.NewSession()
	defer sess.Close()

	context := NewMemoryContextCache()

	var c2 ContextGetStruct
	has, err := sess.ID(1).NoCache().ContextCache(context).Get(&c2)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 1, c2.Id)
	assert.EqualValues(t, "1", c2.Name)
	sql, args := sess.LastSQL()
	assert.True(t, len(sql) > 0)
	assert.True(t, len(args) > 0)

	var c3 ContextGetStruct
	has, err = sess.ID(1).NoCache().ContextCache(context).Get(&c3)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 1, c3.Id)
	assert.EqualValues(t, "1", c3.Name)
	sql, args = sess.LastSQL()
	assert.True(t, len(sql) == 0)
	assert.True(t, len(args) == 0)
}

func TestContextGet2(t *testing.T) {
	type ContextGetStruct2 struct {
		Id   int64
		Name string
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(ContextGetStruct2))

	_, err := testEngine.Insert(&ContextGetStruct2{Name: "1"})
	assert.NoError(t, err)

	context := NewMemoryContextCache()

	var c2 ContextGetStruct2
	has, err := testEngine.ID(1).NoCache().ContextCache(context).Get(&c2)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 1, c2.Id)
	assert.EqualValues(t, "1", c2.Name)

	var c3 ContextGetStruct2
	has, err = testEngine.ID(1).NoCache().ContextCache(context).Get(&c3)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 1, c3.Id)
	assert.EqualValues(t, "1", c3.Name)
}

type GetCustomTableInterface interface {
	TableName() string
}

type MyGetCustomTableImpletation struct {
	Id   int64  `json:"id"`
	Name string `json:"name"`
}

const getCustomTableName = "GetCustomTableInterface"

func (m *MyGetCustomTableImpletation) TableName() string {
	return getCustomTableName
}

func TestGetCustomTableInterface(t *testing.T) {
	assert.NoError(t, prepareEngine())
	assert.NoError(t, testEngine.Table(getCustomTableName).Sync2(new(MyGetCustomTableImpletation)))

	exist, err := testEngine.IsTableExist(getCustomTableName)
	assert.NoError(t, err)
	assert.True(t, exist)

	_, err = testEngine.Insert(&MyGetCustomTableImpletation{
		Name: "xlw",
	})
	assert.NoError(t, err)

	var c GetCustomTableInterface = new(MyGetCustomTableImpletation)
	has, err := testEngine.Get(c)
	assert.NoError(t, err)
	assert.True(t, has)
}

func TestGetNullVar(t *testing.T) {
	type TestGetNullVarStruct struct {
		Id   int64
		Name string
		Age  int
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(TestGetNullVarStruct))

	affected, err := testEngine.Exec("insert into " + testEngine.TableName(new(TestGetNullVarStruct), true) + " (name,age) values (null,null)")
	assert.NoError(t, err)
	a, _ := affected.RowsAffected()
	assert.EqualValues(t, 1, a)

	var name string
	has, err := testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("name").Get(&name)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, "", name)

	var age int
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age)

	var age2 int8
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age2)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age2)

	var age3 int16
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age3)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age3)

	var age4 int32
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age4)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age4)

	var age5 int64
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age5)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age5)

	var age6 uint
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age6)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age6)

	var age7 uint8
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age7)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age7)

	var age8 int16
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age8)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age8)

	var age9 int32
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age9)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age9)

	var age10 int64
	has, err = testEngine.Table(new(TestGetNullVarStruct)).Where("id = ?", 1).Cols("age").Get(&age10)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 0, age10)
}

func TestCustomTypes(t *testing.T) {
	type MyInt int
	type MyString string

	type TestCustomizeStruct struct {
		Id   int64
		Name MyString
		Age  MyInt
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(TestCustomizeStruct))

	var s = TestCustomizeStruct{
		Name: "test",
		Age:  32,
	}
	_, err := testEngine.Insert(&s)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, s.Id)

	var name MyString
	has, err := testEngine.Table(new(TestCustomizeStruct)).ID(s.Id).Cols("name").Get(&name)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, "test", name)

	var age MyInt
	has, err = testEngine.Table(new(TestCustomizeStruct)).ID(s.Id).Select("age").Get(&age)
	assert.NoError(t, err)
	assert.True(t, has)
	assert.EqualValues(t, 32, age)
}

func TestGetViaMapCond(t *testing.T) {
	type GetViaMapCond struct {
		Id       int64
		Platform int
		Index    int
	}

	assert.NoError(t, prepareEngine())
	assertSync(t, new(GetViaMapCond))

	var (
		r           GetViaMapCond
		platformStr = colMapper.Obj2Table("Platform")
		indexStr    = colMapper.Obj2Table("Index")
		query       = map[string]interface{}{
			platformStr: 1,
			indexStr:    1,
		}
	)

	has, err := testEngine.Where(query).Get(&r)
	assert.NoError(t, err)
	assert.False(t, has)
}


text:
package org.jetbrains.plugins.scala.lang.resolve.testAllResolve
package generated

class TestAllResolveComplexTest extends TestAllResolveTestBase {
  //This class was generated by build script, please don't change this
  override def folderPath: String = super.folderPath + "complex/"

  def testExistential(): Unit = doTest()
}


text:
layout: page
title: Benson - Walker Wedding
date: 2016-05-24
author: Virginia Mercer
tags: weekly links, java
status: published
summary: Suspendisse potenti. Nulla pellentesque mattis nibh ac egestas.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/11/2016
  endDate: 01/16/2016
  ctyhocn: CLUTVHX
  groupCode: BWW
published: true
---
Cras et orci non lectus blandit maximus. Donec dapibus est ex, bibendum consectetur arcu consequat aliquam. In imperdiet justo eget est sollicitudin, in elementum ex feugiat. Etiam et lectus venenatis, pellentesque justo sit amet, blandit metus. Nullam sagittis quam quis nibh elementum, et hendrerit lacus vehicula. Nam sem felis, scelerisque sed pretium eu, consequat non est. In faucibus malesuada nisl sit amet volutpat. Praesent laoreet dapibus pharetra. Donec laoreet, diam sit amet vehicula congue, urna nisl feugiat mi, vel viverra dolor odio vel augue. Nam auctor urna ac odio ullamcorper finibus.

1 Sed viverra mauris vestibulum volutpat semper
1 Nunc eu dui scelerisque, iaculis tellus sit amet, tempus ligula
1 Nam id neque pulvinar, consequat lacus at, tempor ligula.

Mauris id sapien sapien. Aenean nulla sem, ultrices eu varius molestie, aliquam vel lorem. Cras justo purus, egestas viverra eros at, fringilla congue ligula. Etiam sit amet nisi tincidunt, placerat leo quis, pellentesque magna. Curabitur metus nunc, egestas sit amet aliquam eget, mollis ac leo. Nunc placerat ornare eleifend. Ut tempor lacinia feugiat. Nullam vitae massa euismod, consequat mi sit amet, porta neque. Phasellus consequat nisl ut ipsum volutpat luctus. Fusce placerat bibendum lorem eget tempus.
Aliquam dapibus placerat malesuada. Maecenas quis dolor vitae turpis suscipit pretium. Sed cursus sollicitudin maximus. Quisque at quam ac odio imperdiet tempus sed ac ipsum. Praesent laoreet nisl ac libero imperdiet consectetur. Donec ac tempor erat, sit amet ornare velit. Morbi nec congue diam, a elementum quam. Vivamus ut fringilla eros. Integer ornare sem id pharetra luctus. Sed pharetra egestas placerat. In lacinia, urna et tempor blandit, arcu nisl rutrum orci, sed sodales ipsum enim et ipsum.


text:
from __future__ import unicode_literals
from django.db import migrations, models, transaction, connection
import json

def execute(apps, schema_editor):
    Chart = apps.get_model('grapher_admin', 'Chart')
    with transaction.atomic():
        for chart in Chart.objects.all():
            if chart.config['type'] == "ScatterPlot" or chart.config['type'] == "SlopeChart":
                properties = [d['property'] for d in chart.config['dimensions']]
                if not "color" in properties:
                    chart.config['dimensions'].append({ "variableId": 123, "property": "color" })
                if not "size" in properties:
                    chart.config['dimensions'].append({ "variableId": 72, "property": "size" })

            chart.save()

class Migration(migrations.Migration):

    dependencies = [
        ('grapher_admin', '0023_auto_20171212_2333'),
    ]

    operations = [
        migrations.RunPython(execute),
    ]


text:
<?php declare(strict_types=1);
/**
 * Camada de processamento e consulta ao banco de dados
 */

namespace App\Models;

use App\Models\ModelBase;
use App\Objetos\Usuario;
use App\Fabricas\FabricaUsuario;
use App\Views\RegistrarView;
use App\Database\DalUsuarios;
use App\Exceptions\FormException;
use App\Http\Sessao;
use App\Http\Resposta;
use App\Uteis\Uteis;
use App\Config\AppConfig;

final class RegistrarModel extends ModelBase {
	private const LOGIN_NAO_INFORMADO = 'É preciso informar o nome do usuário.';
	private const SENHA_NAO_INFORMADA = 'É preciso informar a senha do usuário.';
	private const LOGIN_JA_EXISTE = 'O nome de usuário informado não está disponível.';

	private const LOGIN_CHAR_INVALIDO = 'O nome do usuário contém carácteres inválidos.';
	private const LOGIN_TAM_INVALIDO = 'O nome do usuário precisa ter entre %m à %M carácteres.';

	private const SENHA_CHAR_INVALIDO = 'A senha do usuário contém carácteres inválidos.';
	private const SENHA_TAM_INVALIDO = 'A senha do usuário precisa ter entre %m à %M carácteres.';

	private const CONFIRMASENHA_INVALIDA = 'A confirmação de senha não condiz com a senha informada anteriormente.';

	private const REF_LOGIN = 0;
	private const REF_SENHA = 1;

	/**
	 * Retorna uma RegistrarView padrão
	 * @return RegistrarView
	 */
	public function __invoke() : RegistrarView {
		return new RegistrarView($this->getUsuarioLogado());
	}

	/**
	 * Efetua o registro de um usuário
	 *
	 * @param string|null $login
	 * @param string|null $senha
	 * @param string|null $confirmaSenha
	 * @return RegistrarView
	 */
	public function registrar(?string $login, ?string $senha, ?string $confirmaSenha) : RegistrarView {
		try {
			// Estágio 1

			$validador = new FormException();

			// Informou os campos?
			if ($login === null)
				$validador->adicionarErros(['login-erro' => self::LOGIN_NAO_INFORMADO]);

			if ($senha === null)
				$validador->adicionarErros(['senha-erro' => self::SENHA_NAO_INFORMADA]);

			if ($validador->ocorreuErro()) {
				throw $validador;
			} else {
				// Estágio 2
				// São válidos?

				if (self::contemCaracteresInvalidos($login))
					$validador->adicionarErros(['login-erro' => self::LOGIN_CHAR_INVALIDO]);

				if (!self::tamanhoValido(self::REF_LOGIN, $login)) {
					$validador->adicionarErros(
						['login-erro-2' => str_replace(
							['%m','%M'],
							[
								AppConfig::obter('Usuarios.NomeTamanhoMinimo'),
								AppConfig::obter('Usuarios.NomeTamanhoLimite')
							],
							self::LOGIN_TAM_INVALIDO
							)
						]
					);
				}

				if (self::contemCaracteresInvalidos($senha))
					$validador->adicionarErros(['senha-erro' => self::SENHA_CHAR_INVALIDO]);

				if (!self::tamanhoValido(self::REF_SENHA, $senha)) {
					$validador->adicionarErros(
						['senha-erro-2' => str_replace(
							['%m','%M'],
							[
								AppConfig::obter('Usuarios.SenhaTamanhoMinimo'),
								AppConfig::obter('Usuarios.SenhaTamanhoLimite')
							],
							self::SENHA_TAM_INVALIDO
							)
						]
					);
				}

				if ($senha !== $confirmaSenha)
					$validador->adicionarErros(['confirmasenha-erro' => self::CONFIRMASENHA_INVALIDA]);

				if ($validador->ocorreuErro()) {
					throw $validador;
				} else {
					// Estágio 3
					// Crie a conta

					$dal = new DalUsuarios($this->getConexao());
					$localUsuario = $dal->obterPeloNome($login);

					if ($localUsuario !== null)
						throw new RegistrarException(self::LOGIN_JA_EXISTE);

					$localUsuario = FabricaUsuario::criar($login, $senha);

					$dal->criar($localUsuario);

					Sessao::setUsuario($localUsuario);
					Resposta::appRedirecionar('home');
				}
			}
		} catch (FormException $e) {
			return new RegistrarView(
				$this->getUsuarioLogado(),
				$login,
				$e->obter('login-erro'),
				$e->obter('login-erro-2'),
				$senha,
				$e->obter('senha-erro'),
				$e->obter('senha-erro-2'),
				$confirmaSenha,
				$e->obter('confirmasenha-erro')
			);
		}
	}

	/**
	 * Retorna se determinada $str contêm carácteres inválidos
	 * @param  string $str
	 * @return bool
	 */
	private static function contemCaracteresInvalidos(string $str) : bool {
		return Uteis::contemCaracteresInvalidos($str);
	}

	/**
	 * Retorna se determinada $str de login ou senha tem o seu tamanho permitido
	 * @param  int    $tipo
	 * @param  string $str
	 * @return bool
	 */
	private static function tamanhoValido(int $tipo, string $str) : bool {
		$len = strlen($str);

		switch ($tipo) {
			case self::REF_LOGIN:
				return ($len >= AppConfig::obter('Usuarios.NomeTamanhoMinimo')
					&&
						$len <= AppConfig::obter('Usuarios.NomeTamanhoLimite'));
			case self::REF_SENHA:
				return ($len >= AppConfig::obter('Usuarios.SenhaTamanhoMinimo')
					&&
						$len <= AppConfig::obter('Usuarios.SenhaTamanhoLimite'));
			default:
				return false;
		}
	}
}

?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See the LICENSE file in the project root for license information.

using System;
using System.Runtime.Serialization;

namespace Mad2WordLib
{
    public class MadokoReaderException : Exception
    {
        public MadokoReaderException() : base() { }

        public MadokoReaderException(string message) : base(message) { }

        public MadokoReaderException(string message, Exception innerException) : base(message, innerException) { }

        public MadokoReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}


text:
struct AnyT {
  template<typename T>
  operator T();
};

void test_cvqual_ref(AnyT any) {
  const int &cir = any;
}

struct AnyThreeLevelPtr {
  template<typename T>
  operator T***() const
  {
    T x = 0;
    // FIXME: looks like we get this wrong, too!
    // x = 0; // will fail if T is deduced to a const type
           // (EDG and GCC get this wrong)
    return 0;
  }
};

struct X { };

void test_deduce_with_qual(AnyThreeLevelPtr a3) {
  int * const * const * const ip = a3;
}

struct AnyPtrMem {
  template<typename Class, typename T>
  operator T Class::*() const
  {
    T x = 0;
    // FIXME: looks like we get this wrong, too!
    // x = 0; // will fail if T is deduced to a const type.
           // (EDG and GCC get this wrong)
    return 0;
  }
};

void test_deduce_ptrmem_with_qual(AnyPtrMem apm) {
  const float X::* pm = apm;
}


text:
using System;

namespace StockCube
{
	public abstract class State<T> : IState<T>
	{
        protected T _id;
		protected IStateMachine<T> _stateMachine;

		protected T _nextStateId;
		protected T _backStateId;

		public T ID
		{
			get { return _id; }
		}

		public State(T id, IStateMachine<T> stateMachine)
		{
			this._id = id;
			this._stateMachine = stateMachine;
		}

        public abstract void Enter();
        public abstract void Update();
        public abstract void Exit();
	}
}


text:
local map = require("src.logic.rooms.map")

local gamestate = {}

local addEntity = function (self, entity)
  table.insert(self.entities, entity)
end

local update = function (self, dt)
  self.dt = dt
  self.map:update(self)
  for _, entity in ipairs(self.entities) do
    entity:update(self)
  end
  self.player:update(self)
  self.view:update(self)
end

local draw = function (self)
  self.map:draw(self.view)
  self.player:draw(self.view)
  for _, entity in ipairs(self.entities) do
    entity:draw(self.view)
  end
  if DEBUG then
    love.graphics.print(self.debugString)
  end
end

local keypressed = function (self, key)
  if key == 'z' then self.player:action1(self) end
end

gamestate.create = function (player, view)
  local inst = {}

  inst.entities = {}
  inst.player = player
  inst.map = map.create()
  inst.view = view
  inst.dt = 0
  inst.debugString = ""

  inst.addEntity = addEntity
  inst.update = update
  inst.draw = draw
  inst.keypressed = keypressed

  return inst
end

return gamestate


text:
[![Build Status](https://travis-ci.org/GDGMalaga/hackersweek3.svg?branch=develop)](https://travis-ci.org/GDGMalaga/hackersweek3)

![](https://raw.githubusercontent.com/ineedblood/hackersweek3/master/app/images/escudo.png)
## Hackers Week 3

### Install dependencies

#### Quick-start (for experienced users)

With Node.js installed, run the following one liner from the root of your Polymer Starter Kit download:

```sh
npm install -g gulp bower && npm install && bower install
```

#### Prerequisites (for everyone)

- Node.js, used to run JavaScript tools from the command line.
- npm, the node package manager, installed with Node.js and used to install Node.js packages.
- gulp, a Node.js-based build tool.
- bower, a Node.js-based package manager used to install front-end packages (like Polymer).

**To install dependencies:**

1)  Check your Node.js version.

```sh
node --version
```

The version should be at or above 0.12.x.

2)  If you don't have Node.js installed, or you have a lower version, go to [nodejs.org](https://nodejs.org) and click on the big green Install button.

3)  Install `gulp` and `bower` globally.

```sh
npm install -g gulp bower
```

This lets you run `gulp` and `bower` from the command line.

4)  Enter to the Hackers Week folder and Install local `npm` and `bower` dependencies.

```sh
 npm install && bower install
```

### Development workflow

#### Serve / watch

```sh
gulp serve
```

This outputs an IP address you can use to locally test and another that can be used on devices connected to your network.

#### Run tests

```sh
gulp test:local
```

#### Build & Vulcanize

```sh
gulp
```


text:
package domain_migration

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/que-go"
	"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2"
	"github.com/flynn/flynn/controller/client"
	ct "github.com/flynn/flynn/controller/types"
	"github.com/flynn/flynn/pkg/postgres"
	"github.com/flynn/flynn/pkg/tlscert"
	routerc "github.com/flynn/flynn/router/client"
	"github.com/flynn/flynn/router/types"
)

// limits the number of concurrent requests to the router
const maxActiveRouteUpdates = 5

type context struct {
	db     *postgres.DB
	client *controller.Client
	logger log15.Logger
}

type migration struct {
	db                 *postgres.DB
	client             *controller.Client
	rc                 routerc.Client
	logger             log15.Logger
	dm                 *ct.DomainMigration
	activeRouteUpdates chan struct{}
}

func JobHandler(db *postgres.DB, client *controller.Client, logger log15.Logger) func(*que.Job) error {
	return (&context{db, client, logger}).HandleDomainMigration
}

func (c *context) HandleDomainMigration(job *que.Job) (err error) {
	log := c.logger.New("fn", "HandleDomainMigration")
	log.Info("handling domain migration", "job_id", job.ID, "error_count", job.ErrorCount)

	var dm *ct.DomainMigration
	if err := json.Unmarshal(job.Args, &dm); err != nil {
		log.Error("error unmarshaling job", "err", err)
		return err
	}

	log = log.New("domain_migration", dm.ID)

	m := &migration{
		db:                 c.db,
		client:             c.client,
		rc:                 routerc.New(),
		logger:             log,
		dm:                 dm,
		activeRouteUpdates: make(chan struct{}, maxActiveRouteUpdates),
	}

	if err := m.db.QueryRow("SELECT old_domain, domain, old_tls_cert, tls_cert, created_at, finished_at FROM domain_migrations WHERE migration_id = $1", dm.ID).Scan(&dm.OldDomain, &dm.Domain, &dm.OldTLSCert, &dm.TLSCert, &dm.CreatedAt, &dm.FinishedAt); err != nil {
		log.Error("error fetching postgres record", "err", err)
		m.createEvent(err)
		return err
	}

	if dm.FinishedAt != nil {
		// Already done
		return nil
	}

	return m.Run()
}

func (m *migration) Run() error {
	log := m.logger
	dm := m.dm

	// Generate TLS Cert if not already present
	var cert *tlscert.Cert
	if dm.TLSCert == nil {
		var err error
		cert, err = m.generateTLSCert()
		if err != nil {
			log.Error("error generating TLS cert", "err", err)
			m.createEvent(err)
			return err
		}
		dm.TLSCert = cert
	}

	if err := m.maybeDeployController(); err != nil {
		log.Error("error deploying controller", "err", err)
		m.createEvent(err)
		return err
	}

	if err := m.maybeDeployRouter(); err != nil {
		log.Error("error deploying router", "err", err)
		m.createEvent(err)
		return err
	}

	if err := m.maybeDeployDashboard(); err != nil {
		log.Error("error deploying dashboard", "err", err)
		m.createEvent(err)
		return err
	}

	if err := m.createMissingRoutes(); err != nil {
		log.Error("error creating missing routes", "err", err)
		m.createEvent(err)
		return err
	}

	if err := m.db.QueryRow("UPDATE domain_migrations SET finished_at = now() RETURNING finished_at").Scan(&dm.FinishedAt); err != nil {
		log.Error("error setting finished_at", "err", err)
		m.createEvent(err)
		return err
	}

	log.Info("domain migration complete")

	m.createEvent(nil)

	return nil
}

func (m *migration) generateTLSCert() (*tlscert.Cert, error) {
	hosts := []string{
		m.dm.Domain,
		fmt.Sprintf("*.%s", m.dm.Domain),
	}
	cert, err := tlscert.Generate(hosts)
	if err != nil {
		return nil, err
	}
	if _, err := m.db.Query("UPDATE domain_migrations SET tls_cert = $1 WHERE migration_id = $2", cert, m.dm.ID); err != nil {
		return nil, err
	}
	return cert, nil
}

func dupRelease(release *ct.Release) *ct.Release {
	return &ct.Release{
		ArtifactID: release.ArtifactID,
		Env:        release.Env,
		Meta:       release.Meta,
		Processes:  release.Processes,
	}
}

func (m *migration) waitForDeployment(app string) error {
	list, err := m.client.DeploymentList(app)
	if err != nil || len(list) == 0 {
		return err
	}
	d := list[0]
	if d.Status != "pending" && d.Status != "running" {
		return nil
	}

	events := make(chan *ct.Event)
	stream, err := m.client.StreamEvents(controller.StreamEventsOptions{
		AppID:       d.AppID,
		ObjectID:    d.ID,
		ObjectTypes: []ct.EventType{ct.EventTypeDeployment},
	}, events)
	if err != nil {
		return err
	}
	defer stream.Close()

	log := m.logger.New("app.name", app, "deployment", d.ID)
	log.Info("waiting for deployment")

	timeout := time.After(2 * time.Minute)
	for {
		select {
		case event := <-events:
			var data *ct.DeploymentEvent
			if err := json.Unmarshal(event.Data, &data); err != nil {
				return err
			}
			if data.Status == "complete" {
				log.Info("deployment complete")
				return nil
			}
			if data.Status == "failed" {
				log.Error("deployment failed", "error", data.Error)
				return errors.New(data.Error)
			}
		case <-timeout:
			err := errors.New("timed out waiting for deployment")
			log.Error(err.Error())
			return err
		}
	}
}

func (m *migration) maybeDeployController() error {
	const appName = "controller"
	log := m.logger.New("app.name", appName)
	if err := m.waitForDeployment(appName); err != nil {
		return err
	}
	release, err := m.client.GetAppRelease(appName)
	if err != nil {
		log.Error("error fetching release", "error", err)
		return err
	}
	if release.Env["DEFAULT_ROUTE_DOMAIN"] != m.dm.OldDomain {
		log.Info("already migrated")
		return nil
	}
	release = dupRelease(release)
	release.Env["DEFAULT_ROUTE_DOMAIN"] = m.dm.Domain
	release.Env["CA_CERT"] = m.dm.TLSCert.CACert
	if err := m.client.CreateRelease(release); err != nil {
		log.Error("error creating release", "error", err)
		return err
	}
	if err := m.client.DeployAppRelease(appName, release.ID); err != nil {
		log.Error("error deploying release", "error", err)
		return err
	}
	return nil
}

func (m *migration) maybeDeployRouter() error {
	const appName = "router"
	log := m.logger.New("app.name", appName)
	if err := m.waitForDeployment(appName); err != nil {
		return err
	}
	release, err := m.client.GetAppRelease(appName)
	if err != nil {
		log.Error("error fetching release", "error", err)
		return err
	}
	if release.Env["TLSCERT"] != m.dm.OldTLSCert.Cert {
		log.Info("already migrated")
		return nil
	}
	release = dupRelease(release)
	release.Env["TLSCERT"] = m.dm.TLSCert.Cert
	release.Env["TLSKEY"] = m.dm.TLSCert.PrivateKey
	if err := m.client.CreateRelease(release); err != nil {
		log.Error("error creating release", "error", err)
		return err
	}
	if err := m.client.DeployAppRelease(appName, release.ID); err != nil {
		log.Error("error deploying release", "error", err)
		return err
	}
	return nil
}

func (m *migration) maybeDeployDashboard() error {
	const appName = "dashboard"
	log := m.logger.New("app.name", appName)
	if err := m.waitForDeployment(appName); err != nil {
		return err
	}
	release, err := m.client.GetAppRelease(appName)
	if err != nil {
		log.Error("error fetching release", "error", err)
		return err
	}
	if release.Env["DEFAULT_ROUTE_DOMAIN"] != m.dm.OldDomain {
		log.Info("already migrated")
		return nil
	}
	release = dupRelease(release)
	release.Env["CA_CERT"] = m.dm.TLSCert.CACert
	release.Env["DEFAULT_ROUTE_DOMAIN"] = m.dm.Domain
	release.Env["CONTROLLER_DOMAIN"] = fmt.Sprintf("controller.%s", m.dm.Domain)
	release.Env["URL"] = fmt.Sprintf("dashboard.%s", m.dm.Domain)
	if err := m.client.CreateRelease(release); err != nil {
		log.Error("error creating release", "error", err)
		return err
	}
	if err := m.client.DeployAppRelease(appName, release.ID); err != nil {
		log.Error("error deploying release", "error", err)
		return err
	}
	return nil
}

func (m *migration) createMissingRoutes() error {
	// Get list of all routes from router
	routes, err := m.rc.ListRoutes("")
	if err != nil {
		return err
	}

	apps, err := m.client.AppList()
	if err != nil {
		return err
	}

	// Index routes by appID
	appRoutes := make(map[string][]*router.Route, len(apps))
	for _, r := range routes {
		if !strings.HasPrefix(r.ParentRef, ct.RouteParentRefPrefix) {
			continue
		}
		appID := strings.TrimPrefix(r.ParentRef, ct.RouteParentRefPrefix)
		if appRoutes[appID] == nil {
			appRoutes[appID] = make([]*router.Route, 0, 1)
		}
		appRoutes[appID] = append(appRoutes[appID], r)
	}

	errChan := make(chan error, len(apps))
	createMissingRoutes := func(app *ct.App) {
		errChan <- m.appCreateMissingRoutes(app.ID, appRoutes[app.ID])
	}
	for _, app := range apps {
		go createMissingRoutes(app)
	}
	var returnErr error
	for range apps {
		if err := <-errChan; err != nil && returnErr == nil {
			returnErr = err
		}
	}
	return returnErr
}

func (m *migration) appCreateMissingRoutes(appID string, routes []*router.Route) error {
	if routes == nil {
		// There are no routes for this app
		return nil
	}
	m.activeRouteUpdates <- struct{}{}
	for _, route := range routes {
		if route.Type != "http" {
			continue
		}
		if strings.HasSuffix(route.Domain, m.dm.OldDomain) && route.TLSCert == m.dm.OldTLSCert.Cert {
			if err := m.appMaybeCreateRoute(appID, route, routes); err != nil {
				return err
			}
		}
	}
	<-m.activeRouteUpdates
	return nil
}

func (m *migration) appMaybeCreateRoute(appID string, oldRoute *router.Route, routes []*router.Route) error {
	prefix := strings.TrimSuffix(oldRoute.Domain, m.dm.OldDomain)
	for _, route := range routes {
		if strings.HasPrefix(route.Domain, prefix) && strings.HasSuffix(route.Domain, m.dm.Domain) {
			// Route already exists
			return nil
		}
	}
	route := &router.Route{
		Type:    "http",
		Domain:  strings.Join([]string{prefix, m.dm.Domain}, ""),
		Sticky:  oldRoute.Sticky,
		Service: oldRoute.Service,
	}
	if oldRoute.TLSCert == m.dm.OldTLSCert.Cert {
		route.TLSCert = m.dm.TLSCert.Cert
		route.TLSKey = m.dm.TLSCert.PrivateKey
	} else {
		route.TLSCert = oldRoute.TLSCert
		route.TLSKey = oldRoute.TLSKey
	}
	err := m.client.CreateRoute(appID, route)
	if err != nil && err.Error() == "conflict: Duplicate route" {
		return nil
	}
	return err
}

func (m *migration) createEvent(err error) error {
	e := ct.DomainMigrationEvent{DomainMigration: m.dm}
	if err != nil {
		e.Error = err.Error()
	}
	query := "INSERT INTO events (object_id, object_type, data) VALUES ($1, $2, $3)"
	return m.db.Exec(query, m.dm.ID, string(ct.EventTypeDomainMigration), e)
}


text:
"""iWorkflow® License (shared) module

REST URI
    ``http://localhost/mgmt/cm/shared/licensing/``

GUI Path
    ``Device Management --> License Management``

REST Kind
    N/A -- HTTP GET returns an error
"""

from f5.iworkflow.cm.shared.licensing.pools import Pools_s
from f5.iworkflow.resource import OrganizingCollection

class Licensing(OrganizingCollection):
    def __init__(self, shared):
        super(Licensing, self).__init__(shared)
        self._meta_data['allowed_lazy_attributes'] = [
            Pools_s
        ]


text:
"""
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License,
    or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    See the GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, see <http://www.gnu.org/licenses/>.

    @author: mkaay, RaNaN
"""

try:
    from json import loads
except ImportError:
    from simplejson import loads

from thread import start_new_thread
from pycurl import FORM_FILE, LOW_SPEED_TIME

from module.network.RequestFactory import getURL, getRequest
from module.network.HTTPRequest import BadHeader

from module.plugins.Hook import Hook

PYLOAD_KEY = "9f65e7f381c3af2b076ea680ae96b0b7"

class CaptchaTraderException(Exception):
    def __init__(self, err):
        self.err = err

    def getCode(self):
        return self.err

    def __str__(self):
        return "<CaptchaTraderException %s>" % self.err

    def __repr__(self):
        return "<CaptchaTraderException %s>" % self.err

class CaptchaTrader(Hook):
    __name__ = "CaptchaTrader"
    __version__ = "0.14"
    __description__ = """send captchas to captchatrader.com"""
    __config__ = [("activated", "bool", "Activated", True),
                  ("username", "str", "Username", ""),
                  ("force", "bool", "Force CT even if client is connected", False),
                  ("passkey", "password", "Password", ""),]
    __author_name__ = ("RaNaN")
    __author_mail__ = ("RaNaN@pyload.org")

    SUBMIT_URL = "http://api.captchatrader.com/submit"
    RESPOND_URL = "http://api.captchatrader.com/respond"
    GETCREDITS_URL = "http://api.captchatrader.com/get_credits/username:%(user)s/password:%(password)s/"

    def setup(self):
        self.info = {}

    def getCredits(self):
        json = getURL(CaptchaTrader.GETCREDITS_URL % {"user": self.getConfig("username"),
                                                           "password": self.getConfig("passkey")})
        response = loads(json)
        if response[0] < 0:
            raise CaptchaTraderException(response[1])
        else:
            self.logInfo(_("%s credits left") % response[1])
            self.info["credits"] = response[1]
            return response[1]

    def submit(self, captcha, captchaType="file", match=None):
        if not PYLOAD_KEY:
            raise CaptchaTraderException("No API Key Specified!")

        #if type(captcha) == str and captchaType == "file":
        #    raise CaptchaTraderException("Invalid Type")
        assert captchaType in ("file", "url-jpg", "url-jpeg", "url-png", "url-bmp")

        req = getRequest()

        #raise timeout threshold
        req.c.setopt(LOW_SPEED_TIME, 80)

        try:
            json = req.load(CaptchaTrader.SUBMIT_URL, post={"api_key": PYLOAD_KEY,
                                                           "username": self.getConfig("username"),
                                                           "password": self.getConfig("passkey"),
                                                           "value": (FORM_FILE, captcha),
                                                           "type": captchaType}, multipart=True)
        finally:
            req.close()

        response = loads(json)
        if response[0] < 0:
            raise CaptchaTraderException(response[1])

        ticket = response[0]
        result = response[1]
        self.logDebug("result %s : %s" % (ticket, result))

        return ticket, result

    def respond(self, ticket, success):
        try:
            json = getURL(CaptchaTrader.RESPOND_URL, post={"is_correct": 1 if success else 0,
                                                            "username": self.getConfig("username"),
                                                            "password": self.getConfig("passkey"),
                                                            "ticket": ticket})

            response = loads(json)
            if response[0] < 0:
                raise CaptchaTraderException(response[1])

        except BadHeader, e:
            self.logError(_("Could not send response."), str(e))

    def newCaptchaTask(self, task):
        if not task.isTextual():
            return False

        if not self.getConfig("username") or not self.getConfig("passkey"):
            return False

        if self.core.isClientConnected() and not self.getConfig("force"):
            return False

        if self.getCredits() > 10:
            task.handler.append(self)
            task.setWaiting(100)
            start_new_thread(self.processCaptcha, (task,))

        else:
            self.logInfo(_("Your CaptchaTrader Account has not enough credits"))

    def captchaCorrect(self, task):
        if "ticket" in task.data:
            ticket = task.data["ticket"]
            self.respond(ticket, True)

    def captchaInvalid(self, task):
        if "ticket" in task.data:
            ticket = task.data["ticket"]
            self.respond(ticket, False)

    def processCaptcha(self, task):
        c = task.captchaFile
        try:
            ticket, result = self.submit(c)
        except CaptchaTraderException, e:
            task.error = e.getCode()
            return

        task.data["ticket"] = ticket
        task.setResult(result)


text:
<?php

namespace Cyclear\GameBundle\Form;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RennerType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('naam')
            ->add('cqranking_id', null, array('required' => true, 'label' => 'CQ-id'))
            ->add('country', EntityType::class, array(
                'class' => 'CyclearGameBundle:Country',
                'query_builder' => function (\Doctrine\ORM\EntityRepository $e) {
                    return $e->createQueryBuilder('c')->orderBy('c.name');
                }))
            ->add('twitter', null, ['required' => false]);
    }

    public function getName()
    {
        return 'cyclear_gamebundle_rennertype';
    }
}