text:
import datetime
import json
import os
import re
import uuid

from concurrent.futures import ThreadPoolExecutor

import tornado
import tornado.options
from tornado.log import app_log
from tornado.web import RequestHandler, HTTPError, RedirectHandler

from tornado import gen, web

import dockworker
import spawnpool

class BaseHandler(RequestHandler):
    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.render("error/404.html", status_code = status_code)
        else:
            self.render("error/500.html", status_code = status_code)

    def prepare(self):
        if self.allow_origin:
            self.set_header("Access-Control-Allow-Origin", self.allow_origin)
        if self.expose_headers:
            self.set_header("Access-Control-Expose-Headers", self.expose_headers)
        if self.max_age:
            self.set_header("Access-Control-Max-Age", self.max_age)
        if self.allow_credentials:
            self.set_header("Access-Control-Allow-Credentials", self.allow_credentials)
        if self.allow_methods:
            self.set_header("Access-Control-Allow-Methods", self.allow_methods)
        if self.allow_headers:
            self.set_header("Access-Control-Allow-Headers", self.allow_headers)

    @property
    def allow_origin(self):
        return self.settings['allow_origin']

    @property
    def expose_headers(self):
        return self.settings['expose_headers']

    @property
    def max_age(self):
        return self.settings['max_age']

    @property
    def allow_credentials(self):
        return self.settings['allow_credentials']

    @property
    def allow_methods(self):
        return self.settings['allow_methods']

    @property
    def allow_headers(self):
        return self.settings['allow_headers']

class LoadingHandler(BaseHandler):
    def get(self, path=None):
        self.render("loading.html", path=path)

class APIStatsHandler(BaseHandler):
    def get(self):
        '''Returns some statistics/metadata about the tmpnb server'''
        self.set_header("Content-Type", 'application/json')
        response = {
                'available': len(self.pool.available),
                'capacity': self.pool.capacity,
                'version': '0.1.0',
                'container_image': self.pool.container_config.image,
        }
        self.write(response)

    @property
    def pool(self):
        return self.settings['pool']

class InfoHandler(BaseHandler):
    def get(self):
        self.render("stats.html")

    @property
    def pool(self):
        return self.settings['pool']

class SpawnHandler(BaseHandler):

    @gen.coroutine
    def get(self, path=None):
        '''Spawns a brand new server'''
        try:
            if path is None:
                # No path. Assign a prelaunched container from the pool and redirect to it.
                # Append self.redirect_uri to the redirect target.
                container_path = self.pool.acquire().path
                app_log.info("Allocated [%s] from the pool.", container_path)

                url = "/{}/{}".format(container_path, self.redirect_uri)
            else:
                # Split /user/{some_user}/long/url/path and acquire {some_user}
                path_parts = path.lstrip('/').split('/', 2)
                user = path_parts[1]

                # Scrap a container from the pool and replace it with an ad-hoc replacement.
                # This takes longer, but is necessary to support ad-hoc containers
                yield self.pool.adhoc(user)

                url = path

            app_log.debug("Redirecting [%s] -> [%s].", self.request.path, url)
            self.redirect(url, permanent=False)
        except spawnpool.EmptyPoolError:
            app_log.warning("The container pool is empty!")
            self.render("full.html", cull_period=self.cull_period)

    @property
    def pool(self):
        return self.settings['pool']

    @property
    def cull_period(self):
        return self.settings['cull_period']

    @property
    def redirect_uri(self):
        return self.settings['redirect_uri']

class APISpawnHandler(BaseHandler):

    @gen.coroutine
    def post(self):
        '''Spawns a brand new server programatically'''
        try:
            url = self.pool.acquire().path
            app_log.info("Allocated [%s] from the pool.", url)
            app_log.debug("Responding with container url [%s].", url)
            self.write({'url': url})
        except spawnpool.EmptyPoolError:
            app_log.warning("The container pool is empty!")
            self.write({'status': 'full'})

    @property
    def pool(self):
        return self.settings['pool']

def main():
    tornado.options.define('cull_period', default=600,
        help="Interval (s) for culling idle containers."
    )
    tornado.options.define('cull_timeout', default=3600,
        help="Timeout (s) for culling idle containers."
    )
    tornado.options.define('container_ip', default='127.0.0.1',
        help="IP address for containers to bind to"
    )
    tornado.options.define('container_port', default='8888',
        help="Port for containers to bind to"
    )

    command_default = (
        'ipython notebook --no-browser'
        ' --port {port} --ip=0.0.0.0'
        ' --NotebookApp.base_url=/{base_path}'
    )

    tornado.options.define('command', default=command_default,
        help="command to run when booting the image. A placeholder for base_path should be provided."
    )
    tornado.options.define('port', default=9999,
        help="port for the main server to listen on"
    )
    tornado.options.define('ip', default=None,
        help="ip for the main server to listen on [default: all interfaces]"
    )
    tornado.options.define('max_dock_workers', default=2,
        help="Maximum number of docker workers"
    )
    tornado.options.define('mem_limit', default="512m",
        help="Limit on Memory, per container"
    )
    tornado.options.define('cpu_shares', default=None,
        help="Limit CPU shares, per container"
    )
    tornado.options.define('image', default="jupyter/minimal",
        help="Docker container to spawn for new users. Must be on the system already"
    )
    tornado.options.define('docker_version', default="auto",
        help="Version of the Docker API to use"
    )
    tornado.options.define('redirect_uri', default="/tree",
        help="URI to redirect users to upon initial notebook launch"
    )
    tornado.options.define('pool_size', default=10,
        help="Capacity for containers on this system. Will be prelaunched at startup."
    )
    tornado.options.define('pool_name', default=None,
        help="Container name fragment used to identity containers that belong to this instance."
    )
    tornado.options.define('static_files', default=None,
        help="Static files to extract from the initial container launch"
    )
    tornado.options.define('allow_origin', default=None,
        help="Set the Access-Control-Allow-Origin header. Use '*' to allow any origin to access."
    )
    tornado.options.define('expose_headers', default=None,
            help="Sets the Access-Control-Expose-Headers header."
    )
    tornado.options.define('max_age', default=None,
        help="Sets the Access-Control-Max-Age header."
    )
    tornado.options.define('allow_credentials', default=None,
        help="Sets the Access-Control-Allow-Credentials header."
    )
    tornado.options.define('allow_methods', default=None,
        help="Sets the Access-Control-Allow-Methods header."
    )
    tornado.options.define('allow_headers', default=None,
        help="Sets the Access-Control-Allow-Headers header."
    )
    tornado.options.define('assert_hostname', default=False,
        help="Verify hostname of Docker daemon."
    )

    tornado.options.parse_command_line()
    opts = tornado.options.options

    handlers = [
        (r"/", LoadingHandler),
        (r"/spawn/?(/user/\w+(?:/.*)?)?", SpawnHandler),
        (r"/api/spawn/", APISpawnHandler),
        (r"/(user/\w+)(?:/.*)?", LoadingHandler),
        (r"/api/stats", APIStatsHandler),
        (r"/stats", RedirectHandler, {"url": "/api/stats"}),
        (r"/info", InfoHandler)
    ]

    proxy_token = os.environ['CONFIGPROXY_AUTH_TOKEN']
    proxy_endpoint = os.environ.get('CONFIGPROXY_ENDPOINT', "http://127.0.0.1:8001")
    docker_host = os.environ.get('DOCKER_HOST', 'unix://var/run/docker.sock')

    max_age = datetime.timedelta(seconds=opts.cull_timeout)
    pool_name = opts.pool_name
    if pool_name is None:
        # Derive a valid container name from the image name by default.
        pool_name = re.sub('[^a-zA-Z0_.-]+', '', opts.image.split(':')[0])

    container_config = dockworker.ContainerConfig(
        image=opts.image,
        command=opts.command,
        mem_limit=opts.mem_limit,
        cpu_shares=opts.cpu_shares,
        container_ip=opts.container_ip,
        container_port=opts.container_port,
    )

    spawner = dockworker.DockerSpawner(docker_host,
                                       timeout=30,
                                       version=opts.docker_version,
                                       max_workers=opts.max_dock_workers,
                                       assert_hostname=opts.assert_hostname,
    )

    static_path = os.path.join(os.path.dirname(__file__), "static")

    pool = spawnpool.SpawnPool(proxy_endpoint=proxy_endpoint,
                               proxy_token=proxy_token,
                               spawner=spawner,
                               container_config=container_config,
                               capacity=opts.pool_size,
                               max_age=max_age,
                               static_files=opts.static_files,
                               static_dump_path=static_path,
                               pool_name=pool_name,
    )

    ioloop = tornado.ioloop.IOLoop().instance()

    settings = dict(
        default_handler_class=BaseHandler,
        static_path=static_path,
        cookie_secret=uuid.uuid4(),
        xsrf_cookies=False,
        debug=True,
        cull_period=opts.cull_period,
        allow_origin=opts.allow_origin,
        expose_headers=opts.expose_headers,
        max_age=opts.max_age,
        allow_credentials=opts.allow_credentials,
        allow_methods=opts.allow_methods,
        allow_headers=opts.allow_headers,
        spawner=spawner,
        pool=pool,
        autoescape=None,
        proxy_token=proxy_token,
        template_path=os.path.join(os.path.dirname(__file__), 'templates'),
        proxy_endpoint=proxy_endpoint,
        redirect_uri=opts.redirect_uri.lstrip('/'),
    )

    # Synchronously cull any existing, inactive containers, and pre-launch a set number of
    # containers, ready to serve.
    ioloop.run_sync(pool.heartbeat)

    if(opts.static_files):
        ioloop.run_sync(pool.copy_static)

    # Periodically execute a heartbeat function to cull used containers and regenerated failed
    # ones, self-healing the cluster.
    cull_ms = opts.cull_period * 1e3
    app_log.info("Culling containers unused for %i seconds every %i seconds.",
                 opts.cull_timeout,
                 opts.cull_period)
    culler = tornado.ioloop.PeriodicCallback(pool.heartbeat, cull_ms)
    culler.start()

    app_log.info("Listening on {}:{}".format(opts.ip or '*', opts.port))
    application = tornado.web.Application(handlers, **settings)
    application.listen(opts.port, opts.ip)
    ioloop.start()

if __name__ == "__main__":
    main()


text:
CURRENT=$(cd $(dirname $0) && pwd)
source ~vagrant/android-common.sh

echo "Waiting for emulator to start..."

bootanim=""
failcounter=0
until [[ "$bootanim" =~ "stopped" ]]; do
   bootanim=`adb -e shell getprop init.svc.bootanim 2>&1`
   if [[ "$bootanim" =~ "not found" ]]; then
      let "failcounter += 1"
      if [[ $failcounter -gt 3 ]]; then
        echo "  Failed to start emulator"
        exit 1
      fi
   fi
   sleep 1
done

redpajama_set_name: RedPajamaGithub


text:
using System;
using Serilog;

namespace AutofacSerilogIntegration.Tests.SourceContext.Scenarios
{
    class AcceptsLogViaCtor : IAcceptsLogViaCtor
    {
        readonly ILogger _log;

        public AcceptsLogViaCtor(ILogger log)
        {
            _log = log ?? throw new ArgumentNullException(nameof(log));
        }

        public void CreateLog()
        {
            _log.Information("Hello!");
        }
    }

    interface IAcceptsLogViaCtor : ILogScenario
    {
    }
}


text:
export class ToUnderscore {
  static setMapping(mapping) {
    mapping.forProperty('id').primary().increments().field({ name: 'underscore_id' });
    mapping.field('camelCaseToUnderscore', { type: 'string', size: 20 });
    mapping.field('PascalToUnderscore', { type: 'integer' });
    mapping.field('already_underscore', { type: 'boolean' });
    mapping.field('customName', { type: 'string', name: 'customColumnName' });
    mapping.field('camelCaseAnd_underscore', { type: 'boolean' });
  }
}


text:
die() {
    echo >&2 "$*"
    exit 1
}

containsElement () {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}

# make_freddy --
#
#     Creates the freddy module containing commands: dance,study
#
make_freddy() {
    [ $# = 1 ] || { echo "usage: make_freddy <dir>"; return 1; }
    moddir=$1
    mkdir -p $moddir/freddy
    cat > $moddir/freddy/metadata <<EOF
NAME=freddy
DESCRIPTION="A dancer in a red beret and matching suspenders"
SHELL=${SHELL}
EOF
    # freddy:dance
    mkdir -p $moddir/freddy/commands/dance
    cat > $moddir/freddy/commands/dance/metadata <<EOF
NAME=dance
DESCRIPTION="tell freddy to dance"
OPTIONS="jumps"
EOF
    cat > $moddir/freddy/commands/dance/script <<EOF
#!/usr/bin/env bash
source  $moddir/freddy/commands/dance/options.sh || exit 2
echo "jumps (\$JUMPS)"
EOF
    # Make this script executable.
    chmod +x  $moddir/freddy/commands/dance/script
    # freddy:dance [-j|--jumps <>]
    mkdir -p  $moddir/freddy/options/jumps
    cat > $moddir/freddy/options/jumps/metadata <<EOF
NAME=jumps
DESCRIPTION="jump #num times"
REQUIRED=false
DEFAULT=3
LONG=jumps
SHORT=j
ARGUMENTS=true
EOF
    # freddy:dance options parser
    cat > $moddir/freddy/commands/dance/options.sh <<EOF
rerun_option_usage() {
    echo "\$USAGE" >&2 ; return 2 ;
}
rerun_option_check() {
    [ "\$1" -lt 2 ] && rerun_option_usage
}

while [ "\$#" -gt 0 ]; do
    OPT="\$1"
    case "\$OPT" in
          -j|--jumps) JUMPS="\$2" ; shift ;;
        # unknown option
        -?)
            rerun_option_usage
            ;;
        # end of options, just arguments left
        *)
          break
    esac
    shift
done
# Set defaultable options
[ -z "\$JUMPS" ] && JUMPS="3"
#
return 0
EOF
    # freddy:study
    mkdir -p $moddir/freddy/commands/study
    cat > $moddir/freddy/commands/study/metadata <<EOF
NAME=study
DESCRIPTION="tell freddy to study"
OPTIONS="subject"
EOF
    cat > $moddir/freddy/commands/study/script <<EOF
#!/usr/bin/env bash
source  $moddir/freddy/commands/study/options.sh || exit 2
echo "studying (\$SUBJECT)"
EOF
    # freddy:study [-s|--subject <>]
    mkdir -p  $moddir/freddy/options/subject
    cat > $moddir/freddy/options/subject/metadata <<EOF
NAME=subject
DESCRIPTION="subject to study"
REQUIRED=false
DEFAULT=math
LONG=subject
SHORT=s
ARGUMENTS=true
EOF
    # freddy:study option parser
    cat > $moddir/freddy/commands/study/options.sh <<EOF
rerun_option_usage() {
    echo "\$USAGE" >&2 ; return 2 ;
}
rerun_option_check() {
    [ "\$1" -lt 2 ] && rerun_option_usage
}

while [ "\$#" -gt 0 ]; do
    OPT="\$1"
    case "\$OPT" in
          -s|--subject) SUBJECT="\$2" ; shift ;;
        # unknown option
        -?)
            rerun_option_usage
            ;;
        # end of options, just arguments left
        *)
          break
    esac
    shift
done
# Set defaultable options
[ -z "\$SUBJECT" ] && SUBJECT="math"
#
return 0
EOF
    # Done
}


text: Alpine build of openresty, for minimalism


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe RSpec::Padrino do
  it "can be included" do
    expect { include RSpec::Padrino }.not_to raise_error
  end

  it "includes RSpec::Padrino::* automatically" do
    module Foo
      include RSpec::Padrino
    end
    expect(Foo).to be_include(RSpec::Padrino::Methods)
    expect(Foo).to be_include(RSpec::Padrino::Matchers)
  end
end


text:
import { decode } from "jwt-simple";
import { SessionToken } from "gearworks";
import { autorun, observable, action, computed } from "mobx";

const AUTH_STORAGE_NAME = "gearworks-auth";

export class AuthStore {
    constructor() {
        this.token = localStorage.getItem(AUTH_STORAGE_NAME) || "";

        if (this.token) {
            this.session = decode(this.token, undefined, true);
        }

        autorun("AuthStore-autorun", (runner) => {
            // Persist the auth changes to localstorage
            localStorage.setItem(AUTH_STORAGE_NAME, this.token);
        });
    }

    @observable token: string;

    @observable session: SessionToken;

    @computed get sessionIsInvalid() {
        return !this.token || !this.session || (this.session.exp * 1000 < Date.now());
    }

    @action login(token: string) {
        this.session = decode(token, undefined, true);

        this.token = token;
    }

    @action logout() {
        this.session = {} as any;
        this.token = "";
    }
}

const store = new AuthStore();

export default store;


text:
'use strict'

const nodeThree = require('../shared/node-three/index')
nodeThree.loadInternal('examples/js/loaders/OBJLoader.js')
nodeThree.loadInternal('examples/js/loaders/MTLLoader.js')
const Promise = require('bluebird')
const Canvas = require('canvas')
const THREE = nodeThree.THREE

// actual THREE library
module.exports.THREE = THREE

// some trick to get all pixel information
THREE.Material.prototype.toImageData = function () {
  if (!this.$$imageData) {
    if (!this.map || !this.map.image) {
      throw new Error('Unsupported material for image data retrieval!')
    }
    const image = this.map.image
    const canvas = new Canvas(image.width, image.height)
    const context = canvas.getContext('2d')
    context.drawImage(image, 0, 0)
    this.$$imageData = context.getImageData(0, 0, image.width, image.height)
  }
  return this.$$imageData
}

// Loads an OBJ file by file name
module.exports.loadOBJ = function (url) {
  return new Promise(function (resolve, reject) {
    const onError = reject
    const onLoad = resolve
    const onProgress = null
    const lastIndex = Math.max(url.lastIndexOf('/'), url.lastIndexOf('\\')) + 1
    const baseUrl = url.substr(0, lastIndex)
    const loader = new THREE.XHRLoader()
    loader.load(url, function (text) {
      const lines = text.split('\n').map(line => line.trim())
      const mtlRegex = /^mtllib (.*)$/
      const mtlLibs = lines.filter(function (line) {
        return mtlRegex.test(line)
      })
      if (mtlLibs.length !== 1) {
        onError(new Error('Exactly one material library expected!'))
        return
      }
      const mtlUrl = mtlRegex.exec(mtlLibs[0])[1]
      const mtlLoader = new THREE.MTLLoader()
      mtlLoader.setPath(baseUrl)
      mtlLoader.setCrossOrigin()
      mtlLoader.load(mtlUrl, function (materials) {
        materials.preload()
        nodeThree.awaitLoadingManager(materials)
          .then(() => {
            let objLoader = new THREE.OBJLoader()
            objLoader.setMaterials(materials)
            objLoader.load(url, onLoad, onProgress, onError)
          }, onError)
      }, onProgress, onError)
    }, onProgress, onError)
  }).then(nodeThree.awaitLoadingManager)
}

// load a texture into a material
module.exports.loadTexture = function (url) {
  return new Promise(function (resolve, reject) {
    const loader = new THREE.TextureLoader()
    loader.load(url, resolve, null, reject)
  }).then(function (texture) {
    return new THREE.MeshLambertMaterial({
      map: texture
    })
  })
}


text:
package com.renren.infra.xweb.service;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.renren.infra.xweb.entity.Test;
import com.renren.infra.xweb.repository.TestMybatisDao;

@Component
@Transactional
public class TestService {

    @Autowired
    private TestMybatisDao testDao;

    /**
     * 创建分页查询.
     *
     * @param filterParams
     * @param pageNumber
     * @param pageSize
     * @param sortType
     * @return Page<Test>
     */
    public Page<Test> getTest(Map<String, Object> filterParams, int pageNumber, int pageSize) {

        List<Test> tests = testDao.find(filterParams, buildRowBounds(pageNumber, pageSize));
        int totalnum = testDao.findTotalNum(filterParams);

        return new PageImpl<Test>(tests, new PageRequest(pageNumber - 1, pageSize), totalnum);
    }

    /**
     * 查找所有的Test.
     *
     * @return List<Test>
     */
    public List<Test> getAllTest() {
        return testDao.findAll();
    }

    /**
     * 创建分页请求.
     *
     * @param pageNumber
     * @param pageSize
     * @return RowBounds
     */
    private RowBounds buildRowBounds(int pageNumber, int pageSize) {
        return new RowBounds((pageNumber - 1) * pageSize, pageSize);
    }

    /**
     * 保存Test.
     *
     * @param newTest
     */
    public void saveTest(Test newTest) {
        if (newTest.getId() != null) {
            testDao.update(newTest);
        } else {
            testDao.insert(newTest);
        }
    }

    /**
     * 增加一组Test
     *
     * @param testList
     */
    public void saveBatchTest(List<Test> testList) {
        testDao.insertBatch(testList);
    }

    /**
     * 根据id获取Test
     *
     * @param id
     * @return Test
     */
    public Test getTest(Long id) {
        return testDao.getTestById(id.intValue());
    }

    /**
     * 根据id删除Test
     *
     * @param id
     */
    public void deleteTest(Long id) {
        testDao.deleteById(id.intValue());
    }

}


text:
namespace base {

class SingleThreadTaskRunner;

}  // namespace base

namespace content {

class ResourceDispatcher;
struct ResourceResponseInfo;

// PlzNavigate: Used to override parameters of the navigation request.
struct StreamOverrideParameters {
 public:
  // TODO(clamy): The browser should be made aware on destruction of this struct
  // that it can release its associated stream handle.
  GURL stream_url;
  ResourceResponseHead response;
};

class CONTENT_EXPORT WebURLLoaderImpl
    : public NON_EXPORTED_BASE(blink::WebURLLoader) {
 public:

  // Takes ownership of |web_task_runner|.
  WebURLLoaderImpl(ResourceDispatcher* resource_dispatcher,
                   scoped_ptr<blink::WebTaskRunner> web_task_runner);
  ~WebURLLoaderImpl() override;

  static void PopulateURLResponse(const GURL& url,
                                  const ResourceResponseInfo& info,
                                  blink::WebURLResponse* response,
                                  bool report_security_info);
  static void PopulateURLRequestForRedirect(
      const blink::WebURLRequest& request,
      const net::RedirectInfo& redirect_info,
      blink::WebReferrerPolicy referrer_policy,
      bool skip_service_worker,
      blink::WebURLRequest* new_request);

  // WebURLLoader methods:
  void loadSynchronously(
      const blink::WebURLRequest& request,
      blink::WebURLResponse& response,
      blink::WebURLError& error,
      blink::WebData& data) override;
  void loadAsynchronously(
      const blink::WebURLRequest& request,
      blink::WebURLLoaderClient* client) override;
  void cancel() override;
  void setDefersLoading(bool value) override;
  void didChangePriority(blink::WebURLRequest::Priority new_priority,
                         int intra_priority_value) override;
  void setLoadingTaskRunner(blink::WebTaskRunner* loading_task_runner) override;

 private:
  class Context;
  class RequestPeerImpl;
  scoped_refptr<Context> context_;

  DISALLOW_COPY_AND_ASSIGN(WebURLLoaderImpl);
};

}  // namespace content

#endif  // CONTENT_CHILD_WEB_URL_LOADER_IMPL_H_


text:
#ifndef ORG_EEROS_HAL_OUTPUT_HPP_
#define ORG_EEROS_HAL_OUTPUT_HPP_

#include <eeros/core/System.hpp>
#include <string>

namespace eeros {
namespace hal {

/**
 * Base class for all output classes
 */
class OutputInterface {
 public:
  virtual ~OutputInterface() { }
  virtual std::string getId() const = 0;
  virtual void* getLibHandle() = 0;
};

template <typename T>
class Output : public OutputInterface {
 public:
  explicit Output(std::string id, void* libHandle) : id(id), libHandle(libHandle) { }
  virtual ~Output() { }
  virtual inline std::string getId() const { return id; }
  virtual T get() = 0;
  virtual void set(T value) = 0;
  virtual void setTimestampSignalIn(uint64_t timestampNs) { return; }
  virtual void *getLibHandle() { return libHandle; }

  T safe;
 private:
  std::string id;
  void *libHandle;
};

}
}

#endif /* ORG_EEROS_HAL_OUTPUT_HPP_ */


text:
<?php
class Kwf_Assets_Dependency_Iterator_UniqueFilter extends RecursiveFilterIterator
{
    private $_processed = array();
    public function accept()
    {
        $cur = $this->current();
        if (!in_array($cur, $this->_processed, true)) {
            $this->_processed[] = $cur;
            return true;
        }
        return false;
    }

    public function getChildren()
    {
        $ret = new self($this->getInnerIterator()->getChildren());
        $ret->_processed = &$this->_processed;
        return $ret;
    }
}


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["platform", "mode"],
    _excluded2 = ["mode", "children", "subtitle", "indicator", "aside", "getRootRef", "multiline"];
import { createScopedElement } from "../../lib/jsxRuntime";
import { classNames } from "../../lib/classNames";
import { usePlatform } from "../../hooks/usePlatform";
import { hasReactNode, isPrimitiveReactNode } from "../../lib/utils";
import { Platform } from "../../lib/platform";
import { Headline } from "../Typography/Headline/Headline";
import { Caption } from "../Typography/Caption/Caption";
import { Title } from "../Typography/Title/Title";
import { Text } from "../Typography/Text/Text";
import { Subhead } from "../Typography/Subhead/Subhead";

var HeaderContent = function HeaderContent(_ref) {
  var platform = _ref.platform,
      mode = _ref.mode,
      restProps = _objectWithoutProperties(_ref, _excluded);

  if (platform === Platform.IOS) {
    switch (mode) {
      case "primary":
      case "tertiary":
        return createScopedElement(Title, _extends({
          weight: "1",
          level: "3"
        }, restProps));

      case "secondary":
        return createScopedElement(Caption, _extends({
          weight: "2",
          caps: true
        }, restProps));
    }
  }

  if (platform === Platform.VKCOM) {
    switch (mode) {
      case "primary":
        return createScopedElement(Headline, _extends({
          weight: "3"
        }, restProps));

      case "secondary":
      case "tertiary":
        return createScopedElement(Caption, restProps);
    }
  }

  switch (mode) {
    case "primary":
    case "tertiary":
      return createScopedElement(Headline, _extends({
        weight: "2"
      }, restProps));

    case "secondary":
      return createScopedElement(Caption, _extends({
        weight: "1",
        caps: true
      }, restProps));
  }

  return null;
};
/**
 * @see https://vkcom.github.io/VKUI/#/Header
 */

export var Header = function Header(_ref2) {
  var _ref2$mode = _ref2.mode,
      mode = _ref2$mode === void 0 ? "primary" : _ref2$mode,
      children = _ref2.children,
      subtitle = _ref2.subtitle,
      indicator = _ref2.indicator,
      aside = _ref2.aside,
      getRootRef = _ref2.getRootRef,
      multiline = _ref2.multiline,
      restProps = _objectWithoutProperties(_ref2, _excluded2);

  var platform = usePlatform();
  var AsideTypography = platform === Platform.VKCOM ? Subhead : Text;
  var SubtitleTypography = mode === "secondary" ? Subhead : Caption;
  return createScopedElement("header", _extends({}, restProps, {
    ref: getRootRef,
    vkuiClass: classNames("Header", platform === Platform.VKCOM && "Header--vkcom", platform === Platform.ANDROID && "Header--android", platform === Platform.IOS && "Header--ios", "Header--mode-".concat(mode), isPrimitiveReactNode(indicator) && "Header--pi")
  }), createScopedElement("div", {
    vkuiClass: "Header__main"
  }, createScopedElement(HeaderContent, {
    vkuiClass: "Header__content",
    Component: "span",
    mode: mode,
    platform: platform
  }, createScopedElement("span", {
    vkuiClass: classNames("Header__content-in", multiline && "Header__content-in--multiline")
  }, children), hasReactNode(indicator) && createScopedElement(Caption, {
    vkuiClass: "Header__indicator",
    weight: mode === "primary" || mode === "secondary" ? "1" : undefined
  }, indicator)), hasReactNode(subtitle) && createScopedElement(SubtitleTypography, {
    vkuiClass: "Header__subtitle",
    Component: "span"
  }, subtitle)), hasReactNode(aside) && createScopedElement(AsideTypography, {
    vkuiClass: "Header__aside",
    Component: "span"
  }, aside));
};
//# sourceMappingURL=Header.js.map


text:
<?php
App::uses('AppModel', 'Model');
/**
 * ClientContactDevice Model
 *
 * @property ClientContact $ClientContact
 * @property ClientDevice $ClientDevice
 */
class ClientContactDevice extends AppModel {

	//The Associations below have been created with all possible keys, those that are not needed can be removed

	public $displayField = 'client_device_id';
	public $useDbConfig = 'admin';
/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'ClientContact' => array(
			'className' => 'ClientContact',
			'foreignKey' => 'client_contact_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'ClientDevice' => array(
			'className' => 'ClientDevice',
			'foreignKey' => 'client_device_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
}


text:
package plp.orientadaObjetos1.declaracao.procedimento;

import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.orientadaObjetos1.excecao.declaracao.ClasseNaoDeclaradaException;
import plp.orientadaObjetos1.expressao.leftExpression.Id;
import plp.orientadaObjetos1.memoria.AmbienteCompilacaoOO1;
import plp.orientadaObjetos1.memoria.AmbienteExecucaoOO1;
import plp.orientadaObjetos1.util.Tipo;
/**
 * Classe que representa uma declaração de parâmetros.
 */
public class DecParametro {
    /**
     * Identificador declarado.
     */
    private Id id;
    /**
     * Tipo do identificador declarado.
     */
    private Tipo tipo;
    /**
     * Construtor.
     * @param id Identificador declarado.
     * @param tipo Tipo do identificador declarado.
     */
    public DecParametro(Id id, Tipo tipo){
        this.id = id;
        this.tipo = tipo;
    }
    /**
     * Obtém o identificador declarado.
     * @return o identificador.
     */
    public Id getId() {
        return id;
    }
    /**
     * Obtém o tipo do identifador declarado.
     * @return o tipo do identifador declarado.
     */
    public Tipo getTipo() {
        return tipo;
    }
    /**
     * Cria um mapeamento do identificador para o valor da expressão
     * desta declaração no AmbienteExecucao
     * @param ambiente o ambiente que contem o mapeamento entre identificadores
     *  e valores.
     * @return o ambiente modificado pela inicialização da variável.
     */
    public AmbienteExecucaoOO1 elabora(AmbienteExecucaoOO1 ambiente) {
        return ambiente;
    }
    /**
     * Verifica se a declaração está bem tipada, ou seja, se a
     * expressão de inicialização está bem tipada.
     * @param ambiente o ambiente que contem o mapeamento entre identificadores
     *  e seus tipos.
     * @return true se os tipos da declaração são válidos;
     *          false caso contrario.
     */
    public boolean checaTipo(AmbienteCompilacaoOO1 ambiente)throws ClasseNaoDeclaradaException {
        return tipo.eValido(ambiente);
    }

    /**
     * Cria um mapeamento do identificador para o tipo do parametro
     * desta declaração no AmbienteCompilacao
     *
     * @param ambiente o ambiente que contem o mapeamento entre identificador
     *  e seu tipo.
     * @return o ambiente modificado pela declaração do parametro.
     */
    public AmbienteCompilacaoOO1 declaraParametro(AmbienteCompilacaoOO1 ambiente)
        throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {

        ambiente.map(id, tipo);
        return ambiente;
    }
}


text:
/**
 * Handle configuration
 *
 * @class conf
 */
(function(){
	conf = {
		/** @property majorVersion */
		majorVersion: 4,
		/** @property minorVersion */
		minorVersion: 4,
		/** @property versionHasChanged */
		versionHasChanged: false,
		/**
		 * get all active mensen
		 *
		 * @method getURLs
		 * @return {Array} an Array of mensa names
		 */
		getSavedMensen: function(){
			try {
				return JSON.parse(data.get("urls")) || [];
			} catch (e) {
				return [];
			}
		},
		/**
		 * get all active mensen
		 *
		 * @method getURLs
		 * @return {Array} an Array of mensa names
		 */
		getSavedURLs : function(){
			return this.getSavedMensen().map(function(mensa){
				return urls.byId[mensa] ? urls.byId[mensa].name : mensa;
			});
		},
		/**
		 * get all known mensen
		 *
		 * @method getURLs
		 * @return {Array} an Array of mensa names
		 */
		getURLs: function(){
			return urls.mensen.map(function( item ){ return item.id; });
		},
		/**
		 * set active mensen
		 * @method setURLs
		 * @param {Array} urls ein Array an Mensennamen
		 * @return {Boolean} success
		 */
		setURLs : function(mensen){
			mensen = mensen.map(function(mensa){
				return urls.byName[mensa] ? urls.byName[mensa].id : mensa;
			});
			return data.save("urls", JSON.stringify(mensen));
		},
		/**
		 * Find out if app has been configured
		 *
		 * @method isConfigured
		 */
		isConfigured : function(){
			try{
				return typeof data.get("urls") === "string";
			} catch(e) {
				return false;
			}
		},
		/**
		 * Get a list of all mensa names and status
		 * depreciated, use storage.getMensaInfo
		 *
		 * @depreciated
		 * @method getMensaInfo
		 * @return {JSON} json
		 */
		getMensaInfo : function(){
			log( "conf.getMensaInfo is depreciated" );
			return storage.getMensaInfo();
		},
		/**
		 * Set setStudentPrices
		 *
		 * @method setStudentPrices
		 * @param {Boolean} state
		 * @return {Boolean} success
		 */
		setStudentPrices : function(state){
			return data.save("displayStudentPrices", state ? "1" : "0");
		},
		/**
		 * get displayStudentPrices
		 *
		 * @method displayStudentPrices
		 * @return {Boolean} state
		 */
		displayStudentPrices : function(){
			return data.get("displayStudentPrices") !== "0";
		}
	};

	// version has changed if majorversion or minorversion differ from
	// saved value and there is no saved menu (it could be a fresh install otherwise)
	if( data.get("menu") && parseInt(data.get("minorversion"), 10) !== conf.minorVersion ){
		conf.versionHasChanged = true;
	}

	// ☢ nuke all saved data if major version has changed
	if( data.get("menu") && parseInt(data.get("majorversion"), 10) !== conf.majorVersion ){
		conf.versionHasChanged = true;
		data.clear();
	}

	data.set("majorversion", conf.majorVersion);
	data.set("minorversion", conf.minorVersion);
})();


text:
class CreateHistories < ActiveRecord::Migration
  def change
    create_table :histories do |t|
      t.string :send_man
      t.string :receive_man
      t.text :content
      t.timestamps
    end
  end
end


text:
import { Routes, RouterModule } from '@angular/router';
import { Pages } from './pages.component';
import { ModuleWithProviders } from '@angular/core';
// noinspection TypeScriptValidateTypes

// export function loadChildren(path) { return System.import(path); };

export const routes: Routes = [
  {
    path: 'pages',
    component: Pages,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
      { path: 'parliament', loadChildren: './parliament/parliament.module#ParliamentModule' },
      { path: 'party', loadChildren: './party/party.module#PartyModule' },
      { path: 'politician',  loadChildren: './politician/politician.module#PoliticianModule' },
      { path: 'about', loadChildren: './about/about.module#AboutModule' },
    ],
  },
];

export const routing: ModuleWithProviders = RouterModule.forChild(routes);


text:
<?php

/*
 * This file is part of the Social Feed Util.
 *
 * (c) LaNetscouade <contact@lanetscouade.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Lns\SocialFeed\Client;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException as GuzzleRequestException;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use GuzzleHttp\HandlerStack;
use Lns\SocialFeed\Exception\RequestException;

/**
 * TwitterApiClient.
 */
class TwitterApiClient extends AbstractClient implements ClientInterface
{
    private $client;
    private $consumerKey;
    private $consumerSecret;

    /**
     * __construct.
     *
     * @param $consumerKey
     * @param $consumerSecret
     */
    public function __construct($consumerKey, $consumerSecret)
    {
        $this->consumerKey = $consumerKey;
        $this->consumerSecret = $consumerSecret;
    }

    /**
     * get.
     *
     * @param $path
     * @param array $options
     */
    public function get($path, array $options = array())
    {
        $client = $this->createGuzzleClient($this->consumerKey, $this->consumerSecret);

        $options['auth'] = 'oauth';

        try {
            return json_decode($client->get('/1.1'.$path, $options)->getBody(), true);
        } catch (GuzzleRequestException $e) {
            $message = $e->getMessage();

            if ($e->hasResponse()) {
                $responseData = json_decode($e->getResponse()->getBody(), true);

                $messageParts = array();

                foreach ($responseData['errors'] as $error) {
                    $messageParts[] = $error['message'];
                }

                $message = implode($messageParts, "\n");
            }

            throw new RequestException($message);
        }
    }

    /**
     * createGuzzleClient.
     *
     * @param $consumerKey
     * @param $consumerSecret
     */
    protected function createGuzzleClient($consumerKey, $consumerSecret)
    {
        $stack = HandlerStack::create();

        $middleware = new Oauth1([
            'consumer_key'    => $consumerKey,
            'consumer_secret' => $consumerSecret,
        ]);

        $stack->push($middleware);

        $client = new Client([
            'base_uri' => 'https://api.twitter.com/1.1/',
            'handler' => $stack
        ]);

        return $client;
    }
}


text:
<?xml version="1.0"?>
<FileList
  Identity = "MMP.PF.Win10.Advertising.XAML.SDK, Version=1.0"
  DisplayName = "Microsoft Player Framework Advertising Plugin"
  MinVSVersion = "14.0"
  AppliesTo = "WindowsAppContainer + (CSharp | VB | VisualC)"
  TargetPlatform="UAP"
  TargetPlatformMinVersion="10.0.0.0"
  TargetPlatformVersion="10.0.0.0"
  ReferenceManagerEnumeration = "Files">
	 <DependsOn Identity = "MMP.PF.Win10.XAML.SDK, Version=1.0"/>
</FileList>


text:
package net.sourceforge.plantuml.svek;

import net.sourceforge.plantuml.ugraphic.UGraphic;

public interface Untranslated extends IEntityImage {

	public void drawUntranslated(UGraphic ug, double minX, double minY);

}


text:
declare const LOCAL_HOST: string;
declare const HEROKU_HOST: string;
declare const HEROKU_PORT: string;
declare const DEBUG: boolean;


text:
class GameWidget;
struct EntityDataWidgets;

#include <vxLib/math/Vector.h>
#include <qtreewidget.h>

enum class EntityShapeType : u16;

namespace Editor
{
	enum class EntityType :u32 { Dynamic, Static, GravityArea, GravityWell, PlayerSpawn, Goal};

	class EntityBase : public QTreeWidgetItem
	{
	protected:
		GameWidget* m_gameWidget;
		EntityType m_type;

		virtual void updateShape() = 0;
		virtual void updateData() = 0;

	public:
		EntityBase(const QString &text, GameWidget* gameWidget, EntityType entityType)
			: QTreeWidgetItem(),
			m_gameWidget(gameWidget),
			m_type(entityType)
		{
			setText(0, text);
		}

		virtual ~EntityBase() {}

		virtual void setupUI(EntityDataWidgets* widgets) = 0;

		EntityType getEntityType() const { return m_type; }

		virtual EntityShapeType getShapeType() const = 0;
	};
}


text:
using Rosier.Glucose.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rosier.Glucose.Phone.ViewModels
{
    public class MeasurementViewModel : ViewModelBase
    {
        private Measurement model;

        public Measurement Model
        {
            get { return this.model; }
            set { this.model = value; NotifyPropertyChanged(); }
        }

        public MeasurementViewModel(Measurement model)
        {
            this.model = model;
        }

        public MeasurementViewModel()
        {
            this.model = new Measurement();
            this.model.DateTime = DateTime.Now;
        }

        public string TimeString
        {
            get { return this.model.DateTime.ToString("HH:mm"); }
        }
        public string DayString
        {
            get { return this.model.DateTime.ToString("ddd d"); }
        }

        public DateTime Date
        {
            get { return this.model.DateTime; }
            set
            {
                this.model.DateTime = value.Date.Add(this.model.DateTime.TimeOfDay);
                NotifyPropertyChanged();
            }
        }

        public DateTime Time
        {
            get { return this.model.DateTime; }
            set
            {
                this.model.DateTime = this.model.DateTime.Date.Add(value.TimeOfDay);
                NotifyPropertyChanged();
            }
        }

        public int GlucoseValue
        {
            get { return this.model.GlucoseValue; }
            set { this.model.GlucoseValue = value; NotifyPropertyChanged(); }
        }
        /// <summary>
        /// Amount of insuline units taken.
        /// </summary>
        public int InsulineUnits
        {
            get { return this.model.InsulineUnits; }
            set { this.model.InsulineUnits = value; NotifyPropertyChanged(); }
        }
        /// <summary>
        /// Free comments about the measurement.
        /// </summary>
        public string Comments
        {
            get { return this.model.Comments; }
            set { this.model.Comments = value; NotifyPropertyChanged(); }
        }
    }
}


text:
package org.thehecklers.entity;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by markheckler on 12/3/15.
 */
public class QuoteSourceTest {
    QuoteSource quoteSource = new QuoteSource();

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void testGetId() throws Exception {
        quoteSource.setId(1);
        assertTrue(quoteSource.getId() == 1);
    }

    @Test
    public void testSetId() throws Exception {
        quoteSource.setId(2);
        assertTrue(quoteSource.getId() == 2);
    }

    @Test
    public void testGetName() throws Exception {
        quoteSource.setName("Bob's Your Uncle");
        assertTrue(quoteSource.getName().equalsIgnoreCase("Bob's Your Uncle"));
    }

    @Test
    public void testSetName() throws Exception {
        quoteSource.setName("Sam Etne");
        assertTrue(quoteSource.getName().equalsIgnoreCase("Sam Etne"));
    }

    @Test
    public void testGetDescription() throws Exception {
        quoteSource.setDescription("Get description.");
        assertTrue(quoteSource.getDescription().equalsIgnoreCase("Get description."));
    }

    @Test
    public void testSetDescription() throws Exception {
        quoteSource.setDescription("Set description.");
        assertTrue(quoteSource.getDescription().equalsIgnoreCase("Set description."));
    }
}


text:
package tpe.Gruppe1_1.uebung04.aufgabe01;

import gdi.MakeItSimple;
import tpe.Gruppe1_1.uebung01.BTree;
import tpe.Gruppe1_1.uebung01.Node;
import tpe.Gruppe1_1.utils.Queue;
import tpe.Gruppe1_1.utils.QueueImpl;

import java.io.*;

import static gdi.MakeItSimple.*;

public class BTreeImplementation implements BTree, Serializable {

    Node root;
    int order;

    /**
     * Creates the BTree with the given order
     * @param order the order of the tree (can't be <= 0)
     */
    public BTreeImplementation(int order) {
        if(order <= 0)
            order = 1;

        this.order = order;
        root = new Node(order);
    }

    public static BTree cloneDeep(BTree otherTree) {
        String tree = otherTree.getElements();

        Object file = openOutputFile("the.tree");

        print(file, tree);

        closeOutputFile(file);

        BTree baum = new BTreeImplementation(otherTree.getOrder());
        baum.insert("the.tree");

        return baum;
    }

    @Override
    public boolean insert(Comparable o) {
        if (root.getKeys()[0] == null)
            return insert(root, 0, o);

        return root.getKeys()[0].getClass().getSuperclass() == o.getClass().getSuperclass() && insert(root, 0, o);
    }

    private boolean insert(Node node,int keyIndex, Comparable o) {
        // If our current element is null and it doesn't have children
        // we can insert the integer at the current index.
        // Otherwise the node has children and we try to insert it in the left child
        // of the current element.
        if(node.getKeys()[keyIndex] == null && node.getChildren()[keyIndex] == null) {
            // If our node is full and the new element is inserted we have to balance the tree
            if(node.insert(keyIndex, o))
                balance(node);
            return true;
        } else if(node.getKeys()[keyIndex] == null) {
            return insert(node.getChildren()[keyIndex], 0, o);
        }

        // Should the element already be in the node we return false to indicate that
        if(node.getKeys()[keyIndex].compareTo(o) == 0)
            return false;

        // If our current element is greater than the integer we want to insert
        // and it doesn't have children, we insert it at the current index and rebalance if needed
        // if it has children we recursively call insert on that child
        if(node.getKeys()[keyIndex].compareTo(o)>= 1) {
            if(node.getChildren()[keyIndex] == null) {
                if(node.insert(keyIndex, o))
                    balance(node);
                return true;
            } else {
                return insert(node.getChildren()[keyIndex], 0, o);
            }
        } else {
            // If the current element is less than the integer we want to insert
            // we recursively call insert on the current node with a higher index (+1)
            return insert(node, keyIndex + 1, o);
        }
    }

    private void balance(Node node) {
        Comparable median = node.getKeys()[order];
        int indexOfInserted = 0;
        Node newParent;
        boolean needsRebalancing = false;

        // If our current node is the root of the Tree
        // we create a new root and insert the median
        if(node == root) {
            Node newRoot = new Node(order);
            newRoot.insert(0, median);
            newParent = newRoot;
            root = newRoot;
        } else {
            Node curParent = node.getParent();
            int maxIndex = 0;

            // Here we look for the largest element that is still
            // smaller than our median in the parent,
            // that way we can insert the median at the right position
            for(int i = 0; i < order * 2; i++)
                if (curParent.getKeys()[i] != null && curParent.getKeys()[i].compareTo(median)<= -1)
                    maxIndex = i;

            // Should the current maximum Index still be larger than our median
            // we insert the median BEFORE that index
            // otherwise we insert it AFTER the maximum Index
            if(curParent.getKeys()[maxIndex].compareTo(median)>= 1) {
                needsRebalancing = curParent.insert(maxIndex, median);
                indexOfInserted = maxIndex;
            } else {
                needsRebalancing = curParent.insert(maxIndex + 1, median);
                indexOfInserted = maxIndex + 1;
            }

            newParent = node.getParent();
        }

        // Here we create the new children of the new balanced node
        // the left child has all the values smaller than our median
        Node childLeft = new Node(order, newParent);
        newParent.getChildren()[indexOfInserted] = childLeft;
        for (int i = 0; i < order; i++) {
            childLeft.insert(i, node.getKeys()[i]);
            // if the elements have children we need to reconnect them too
            childLeft.getChildren()[i] = node.getChildren()[i];
            // and also reparent them
            if(childLeft.getChildren()[i] != null)
                childLeft.getChildren()[i].setParent(childLeft);

            // if we're on the last index before the median we need
            // to reconnect the child of our median too
            if(i == order - 1) {
                childLeft.getChildren()[i + 1] = node.getChildren()[i + 1];
                if(childLeft.getChildren()[i] != null)
                    childLeft.getChildren()[i + 1].setParent(childLeft);
            }
        }

        // and the right child has all the values larger than our median
        Node childRight = new Node(order, newParent);
        newParent.getChildren()[indexOfInserted + 1] = childRight;
        for (int i = order + 1; i < node.getKeys().length; i++) {
            // tempIndex is just there to shorten the other lines
            int tempIndex = i - (order + 1);
            // if the elements have children we need to reconnect them too
            childRight.insert(tempIndex, node.getKeys()[i]);
            childRight.getChildren()[tempIndex] = node.getChildren()[i];

            if(childRight.getChildren()[tempIndex] != null)
                childRight.getChildren()[tempIndex].setParent(childRight);

            // if we're on the last index we need
            // to reconnect the child last too
            if(i == node.getKeys().length - 1) {
                childRight.getChildren()[tempIndex + 1] = node.getChildren()[i + 1];
                if(childRight.getChildren()[tempIndex] != null)
                    childRight.getChildren()[tempIndex + 1].setParent(childRight);
            }
        }

        if(needsRebalancing)
            balance(newParent);
    }

    @Override
    public boolean insert(String filename) {
        if(!isFilePresent(filename))
            return false;

        Object file = openInputFile(filename);

        // We loop through each number in the file and see if
        // it already is in the tree, if it's not already there we insert it
        while(!isEndOfInputFile(file)) {
            int currentNumber = readInt(file);
            if(!contains(currentNumber)) {
                insert(currentNumber);
            } else {
                closeInputFile(file);
                return false;
            }
        }

        closeInputFile(file);
        return true;
    }

    @Override
    public boolean contains(Comparable o) {
        if(root.getKeys()[0] == null)
            return false;
        else if(root.getKeys()[0].getClass().getSuperclass() != o.getClass().getSuperclass())
            return false;
        return contains(root, 0, o);
    }

    private boolean contains(Node node, int keyIndex, Comparable o) {
        if(node.getKeys()[keyIndex] == null)
            return node.getChildren()[keyIndex] != null && contains(node.getChildren()[keyIndex], 0, o);

        if(node.getKeys()[keyIndex].compareTo(o) == 0)
            return true;

        if(node.getKeys()[keyIndex].compareTo(o)>= 1)
            return node.getChildren()[keyIndex] != null && contains(node.getChildren()[keyIndex], 0, o);
//        else if (node.getKeys()[keyIndex].compareTo(o) <= -1 && node.getChildren()[keyIndex] != null)
//            return  contains(node.getChildren()[keyIndex], 0, o);
        else
            return contains(node, keyIndex + 1, o);
    }

    @Override
    public int size() {
        int size = 0;
        Queue queue = new QueueImpl();
        queue.enter(root);

        while(!queue.isEmpty()) {
            Node n = queue.leave();
            size += n.size();
            for(int i = 0; i < order * 2 + 1; i++) {
                if(n.getChildren()[i] != null)
                    queue.enter(n.getChildren()[i]);
            }
        }

        return size;
    }

    @Override
    public int height() {
        return isEmpty() ? 0 : height(root);
    }

    private int height(Node node) {
        int count = 1;
        if(node.getChildren()[0] == null)
            return count;
        else
            count += height(node.getChildren()[0]);
        return count;
    }

    @Override
    public Comparable getMax() {
        Node maxNode = getMax(root);

        if(maxNode == null)
            return -1;
        else
            return maxNode.getKeys()[maxNode.size() - 1];
    }

    private Node getMax(Node node) {
        if(node.getChildren()[node.size()] != null)
            return getMax(node.getChildren()[node.size()]);
        else
            return node.getKeys()[0] == null ? null : node;
    }

    @Override
    public Comparable getMin() {
        Node minNode = getMin(root);

        if(minNode == null)
            return -1;
        else
            return minNode.getKeys()[0];
    }

    private Node getMin(Node node) {
        // For the smallest element we only need to look through
        // the left children of our nodes and the leftmost element in a node
        if(node.getChildren()[0] == null)
            return node.getKeys()[0] == null ? null : node;
        else
            return getMin(node.getChildren()[0]);
    }

    @Override
    public boolean isEmpty() {
        return (root == null || root.size() == 0);
    }

    @Override
    public void addAll(BTree otherTree) {
        String tree = otherTree.getElements();

        Object file = openOutputFile("the.tree");

        print(file, tree);

        closeOutputFile(file);

        insert("the.tree");

    }

    public int getOrder() {
        return order;
    }

    @Override
    public void printInorder() {
        println(printInorder(root));
    }

    private String printInorder(Node node) {
        String output = "";
        if(node == null)
            return output;
        if(node.getChildren()[0] == null) {
            output += "<";
            for(int i = 0; i < order * 2; i++)
                output += node.getKeys()[i] == null ? "" : " " + node.getKeys()[i] + " ";
            output += ">";
            return output;
        } else {
            output += "[";
            for (int i = 0; i < order * 2 + 1; i++) {
                output += printInorder(node.getChildren()[i]);
                output += node.getKeys()[i] == null ? "" :" " +  node.getKeys()[i] + " ";
            }
            output += "]";
            return output;
        }
    }

    @Override
    public void printPostorder() {
        println(printPostorder(root));
    }

    private String printPostorder(Node node) {
        String output = "";
        if(node == null)
            return output;
        if(node.getChildren()[0] == null) {
            for(int i = 0; i < order * 2; i++)
                output += node.getKeys()[i] == null ? "" : node.getKeys()[i] + " ";
            return output;
        } else {
            for (int i = 0; i < order * 2 + 1; i++)
                output += printPostorder(node.getChildren()[i]);
            for(int i = 0; i < order * 2; i++)
                output += node.getKeys()[i] == null ? "" : node.getKeys()[i] + " ";
            return output;
        }
    }

    @Override
    public void printPreorder() {
        println(printPreorder(root));
    }

    private String printPreorder(Node node) {
        String output = "";
        if(node == null)
            return output;
        if(node.getChildren()[0] == null) {
            for(int i = 0; i < order * 2; i++)
                output += node.getKeys()[i] == null ? "" : node.getKeys()[i] + " ";
            return output;
        } else {
            for(int i = 0; i < order * 2; i++)
                output += node.getKeys()[i] == null ? "" : node.getKeys()[i] + " ";
            for (int i = 0; i < order * 2 + 1; i++)
                output += printPreorder(node.getChildren()[i]);
            return output;
        }
    }

    @Override
    public void printLevelorder() {
        String output = "";
        Queue queue = new QueueImpl();
        queue.enter(root);

        while(!queue.isEmpty()) {
            Node n = queue.leave();
            for(int i = 0; i < order * 2; i++)
                output += n.getKeys()[i] == null ? "" : n.getKeys()[i] + " ";

            for(int i = 0; i < order * 2 + 1; i++) {
                if(n.getChildren()[i] != null)
                    queue.enter(n.getChildren()[i]);
            }
        }

        println(output);

    }

    public String getElements() {
        String output = "";
        Queue queue = new QueueImpl();
        queue.enter(root);

        while(!queue.isEmpty()) {
            Node n = queue.leave();
            for(int i = 0; i < order * 2; i++)
                output += n.getKeys()[i] == null ? "" : " " + n.getKeys()[i];

            for(int i = 0; i < order * 2 + 1; i++) {
                if(n.getChildren()[i] != null)
                    queue.enter(n.getChildren()[i]);
            }
        }

        return output;
    }

    private Node findObject(Node node, Comparable o) {
        if(node.getChildren()[0] == null) {
            for(int i = 0; i < node.size(); i++) {
                if(node.getKeys()[i].compareTo(o) == 0)
                    return node;
            }
            return null;
        }

        for(int i = 0; i < node.size(); i++) {
            if(node.getKeys()[i].compareTo(o) == 0)
                return node;
            if(node.getKeys()[i].compareTo(o) >= 1)
                return findObject(node.getChildren()[i], o);
            if(i == node.size() - 1)
                return findObject(node.getChildren()[i+1], o);
        }

        return null;
    }

    @Override
    public boolean remove(Comparable o) {
        // First we want to know if the object is in the tree (with contains(o))
        // then we find the node that contains that object and remove the object
        return contains(o) && remove(findObject(root, o), 0, o);
    }

    private boolean remove(Node node, int index, Comparable o) {
        // if our node is a leaf we can just remove the object
        // from the node and rebalance it if needed
        if(node.getChildren()[0] == null) {
            node.remove(o);
            if(node.size() < order)
                rebalance(node);
        } else {
            // in this case our node is not a leaf

            int seperatorIndex = 0;
            // first we find the index of our object that we want to remove
            for(int i = 0; i < node.size(); i++)
                if(node.getKeys()[i].compareTo(o) == 0)
                    seperatorIndex = i;

            // then we get the biggest element from the left subtree of our object
            Node maxNode = getMax(node.getChildren()[seperatorIndex]);
            // we replace our element with the biggest element from the left subtree
            node.getKeys()[seperatorIndex] = maxNode.getKeys()[maxNode.size() - 1];
            // and then we remove that element from the subtree
            maxNode.remove(maxNode.getKeys()[maxNode.size() - 1]);

            // in case our maxNode is now deficient we need to rebalance it
            if(maxNode.size() < order)
                rebalance(maxNode);
        }
        return true;
    }

    private void rebalance(Node node) {
        int rightParentIndex = 0;
        Node rightSibling = null, leftSibling = null;

        if(node.getParent() == null)
        	return;

        // first we get the index of the parent element (right from our node)
        for(int i = 0; i < node.getParent().size() + 1; i++) {
            if(node.getParent().getChildren()[i] == node ) {
                rightParentIndex = i;
            }
        }

        // here we get the siblings
        if(rightParentIndex < order + 1)
            rightSibling = node.getParent().getChildren()[rightParentIndex + 1];
        if(rightParentIndex > 0)
            leftSibling = node.getParent().getChildren()[rightParentIndex - 1];

        // should our node have a right sibling that we can remove one element from
        // we rotate the tree
        if(rightSibling != null && rightSibling.size() - 1 >= order) {
            rotate(node, rightSibling, rightParentIndex, 0, order - 1);
        }
        // same with our left sibling
        else if (leftSibling != null && leftSibling.size() - 1 >= order) {
            rotate(node, leftSibling, rightParentIndex - 1, leftSibling.size() - 1, 0);
        } else {
            // if we're not able to remove one element from one of the siblings
            // we have to merge with one of them
            if(leftSibling != null) {
                // we get the seperator and insert it into the left sibling
                Comparable seperator = node.getParent().getKeys()[rightParentIndex - 1];
                leftSibling.insert(order, seperator);

                // then we fill that left sibling with all the elements
                // that are still in our deficient node
                for(int i = 0; i < node.size(); i++)
                    leftSibling.insert(order + 1 + i, node.getKeys()[i]);

                // here we set the right child of our seperator
                // to the left child because after removing one element from
                // the node, all the children get shifted to the left, thus losing one element
                node.getParent().getChildren()[rightParentIndex] = leftSibling;
                node.getParent().remove(seperator);

                // should our parent be the root and not have any elements, our new root
                // is now  the left sibling
                if(node.getParent() == root && node.getParent().getKeys()[0] == null) {
                    if(node.getChildren()[0] != null)
                        leftSibling.getChildren()[leftSibling.size()] = node.getChildren()[0];
                    root = leftSibling;
                    leftSibling.setParent(null);
                } else if (node.getParent().size() < order) {
                    rebalance(node.getParent());
                }

            } else if (rightSibling != null) {
                // here we do the same as with the left sibling
                Comparable seperator = node.getParent().getKeys()[rightParentIndex];
                node.insert(order - 1, seperator);

                for(int i = 0; i < rightSibling.size(); i++)
                    node.insert(order + i, rightSibling.getKeys()[i]);

                node.getParent().getChildren()[rightParentIndex + 1] = node;
                node.getParent().remove(seperator);
                if(node.getParent() == root && node.getParent().getKeys()[0] == null) {
                    if (rightSibling.getChildren()[0] != null) {
                        node.getChildren()[node.size()] = rightSibling.getChildren()[0];
                    }
                    root = node;
                    node.setParent(null);
                } else if (node.getParent().size() < order) {
                    rebalance(node.getParent());
                }

            }
        }
    }

    private void rotate(Node deficientNode, Node nodeWithEnoughElements, int parentIndex, int keyIndexToTakeOut, int insertPosInDeficentNode) {
        deficientNode.insert(insertPosInDeficentNode, deficientNode.getParent().getKeys()[parentIndex]);
        deficientNode.getParent().getKeys()[parentIndex] = nodeWithEnoughElements.getKeys()[keyIndexToTakeOut];

        if(nodeWithEnoughElements.getChildren()[keyIndexToTakeOut] != null) {
        	if(deficientNode.getChildren()[insertPosInDeficentNode+1] == null) {
        		deficientNode.getChildren()[insertPosInDeficentNode+1] = new Node(order);
        		deficientNode.getChildren()[insertPosInDeficentNode+1].setParent(deficientNode);
        	}
        	for(int i = 0; i < nodeWithEnoughElements.getChildren()[keyIndexToTakeOut].size(); i++) {
        		deficientNode.getChildren()[insertPosInDeficentNode+1].insert(deficientNode.getChildren()[insertPosInDeficentNode+1].size(),
        				nodeWithEnoughElements.getChildren()[keyIndexToTakeOut].getKeys()[i]);
        	}
        }

        nodeWithEnoughElements.remove(nodeWithEnoughElements.getKeys()[keyIndexToTakeOut]);
    }

    /**
     * This method saves the tree to a file
     *
     * @param path The path (including filename) the tree will be saved to
     */
    public void saveTree(String path) {
        ObjectOutputStream stream = null;
        try {
            stream = new ObjectOutputStream(new FileOutputStream(path));
            stream.writeObject(this);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method loads a tree from a file
     * and returns that tree.
     * @param path The path to the file that contains the tree;
     * @return Returns the tree from the file
     * @throws FileNotFoundException
     */
    public static BTreeImplementation loadTree(String path) throws FileNotFoundException {
        ObjectInputStream stream = null;
        BTreeImplementation newTree = null;

        if (!MakeItSimple.isFilePresent(path))
            throw new FileNotFoundException(path + " could not be found!");

        try {
            stream = new ObjectInputStream(new FileInputStream(path));
            newTree = (BTreeImplementation) stream.readObject();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return newTree;
    }
}


text:
<?php declare(strict_types = 1);

namespace DrdPlus\Tables\Theurgist\Spells\Exceptions;

class UnknownProfile extends \LogicException implements Logic
{

}


text:
package org.junit.tests.validation;

import static org.junit.Assert.assertEquals;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;

public class ValidationTest {
    public static class WrongBeforeClass {
        @BeforeClass
        protected int a() {
            return 0;
        }
    }

    @Test
    public void initializationErrorIsOnCorrectClass() {
        assertEquals(WrongBeforeClass.class.getName(),
                Request.aClass(WrongBeforeClass.class).getRunner().getDescription().getDisplayName());
    }

    public static class NonStaticBeforeClass {
        @BeforeClass
        public void before() {
        }

        @Test
        public void hereBecauseEveryTestClassNeedsATest() {
        }
    }

    @Test
    public void nonStaticBeforeClass() {
        Result result = JUnitCore.runClasses(NonStaticBeforeClass.class);
        assertEquals("Method before() should be static", result.getFailures().get(0).getMessage());
    }
}


text:
<?php

namespace App\Factories;

use App\Config;
use App\Exceptions\InvalidConfiguration;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\Translator;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class TranslationFactory
{
    /** @var Config The applicaiton configuration */
    protected $config;

    /** @var CacheInterface The application cache */
    protected $cache;

    /** Create a new TranslationFactory object. */
    public function __construct(Config $config, CacheInterface $cache)
    {
        $this->config = $config;
        $this->cache = $cache;
    }

    /** Initialize and return the translation component. */
    public function __invoke(): TranslatorInterface
    {
        if (! in_array(
            $language = $this->config->get('language'),
            $translations = $this->translations())
        ) {
            throw InvalidConfiguration::fromConfig('language', $language);
        }

        $translator = new Translator($language);
        $translator->addLoader('yaml', new YamlFileLoader());

        foreach ($translations as $language) {
            $translator->addResource('yaml', sprintf(
                '%s/%s.yaml', $this->config->get('translations_path'), $language
            ), $language);
        }

        return $translator;
    }

    /** Get an array of available translation languages. */
    protected function translations(): array
    {
        return $this->cache->get('translations', function (): array {
            return array_values(array_map(function (SplFileInfo $file): string {
                return $file->getBasename('.yaml');
            }, iterator_to_array(
                Finder::create()->in($this->config->get('translations_path'))->name('*.yaml')
            )));
        });
    }
}


text:
package com.google.chat.bot.basic.async;

// [START async-bot]

import com.fasterxml.jackson.databind.JsonNode;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.chat.v1.HangoutsChat;
import com.google.api.services.chat.v1.model.Message;
import com.google.api.services.chat.v1.model.Thread;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.logging.Logger;

@SpringBootApplication
@RestController
public class Bot {
    static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
    private static final Logger logger = Logger.getLogger(Bot.class.getName());

    public static void main(String[] args) {
        SpringApplication.run(Bot.class, args);
    }

    /**
     * Handles a GET request to the /bot endpoint.
     *
     * @param event Event from chat.
     * @return Message
     */
    @PostMapping("/")
    public void onEvent(@RequestBody JsonNode event) throws IOException, GeneralSecurityException {
        String replyText = "";
        switch (event.at("/type").asText()) {
            case "ADDED_TO_SPACE":
                String spaceType = event.at("/space/type").asText();
                if ("ROOM".equals(spaceType)) {
                    String displayName = event.at("/space/displayName").asText();
                    replyText = String.format("Thanks for adding me to %s", displayName);
                } else {
                    String displayName = event.at("/user/displayName").asText();
                    replyText = String.format("Thanks for adding me to a DM, %s!", displayName);
                }
                break;
            case "MESSAGE":
                String message = event.at("/message/text").asText();
                replyText = String.format("Your message: %s", message);
                break;
            case "REMOVED_FROM_SPACE":
                String name = event.at("/space/name").asText();
                logger.info(String.format("Bot removed from %s", name));
                break;
            default:
                replyText = "Cannot determine event type";
                break;
        }

        // [START async-response]
        String spaceName = event.at("/space/name").asText();
        Message reply = new Message().setText(replyText);
        // If replying to a message, set thread name to keep conversation together
        if (event.has("message")) {
            String threadName = event.at("/message/thread/name").asText();
            Thread thread = new Thread().setName(threadName);
            reply.setThread(thread);
        }

        GoogleCredentials credentials = GoogleCredentials.fromStream(
                Bot.class.getResourceAsStream("/service-acct.json")
        ).createScoped(CHAT_SCOPE);
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
        HangoutsChat chatService = new HangoutsChat.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(),
                    JacksonFactory.getDefaultInstance(),
                    requestInitializer)
                .setApplicationName("basic-async-bot-java")
                .build();
        chatService.spaces().messages().create(spaceName, reply).execute();
        // [END async-response]
    }
}

// [END async-bot]


text: find_package(NotHere MODULE CONFIG CONFIGS NotHereConfig.cmake NO_DEFAULT_PATH)


text:
@implementation SampleAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	_window.rootViewController = _viewController;
	[_window makeKeyAndVisible];

	return YES;
}

@end


text:
<?php
/**
 * Config-file for navigation bar.
 *
 */
return [

    // Use for styling the menu
    'class' => 'navbar',

    // Here comes the menu strcture
    'items' => [

        // This is a menu item
        'home'  => [
            'text'  => '  Home',
            'url'   => $this->di->get('url')->create(''),
            'title' => 'Hem till Allspark'
        ],

        // This is a menu item
        'site-subs'  => [
            'text'  => '  Subs',
            'url'   => null,
            'title' => 'Här samlas alla moduler som tillkommer till projektet under kursens gång',

            // Here we add the submenu, with some menu items, as part of a existing menu item
            'submenu' => [

                'items' => [

                    // This is a menu item of the submenu
                    'item 0'  => [
                        'text'  => '  Dicegame',
                        'url'   => $this->di->get('url')->create('dicegame'),
                        'title' => 'Dicegame modul from early course'
                    ],

                    // This is a menu item of the submenu
                    'item 1'  => [
                        'text'  => '  Comments',
                        'url'   => $this->di->get('url')->create('comment'),
                        'title' => 'Modules for creating comments'
                    ],

                    // This is a menu item of the submenu
                    'item 2'  => [
                        'text'  => '  Theme',
                        'url'   => $this->di->get('url')->create('theme.php'),
                        'title' => 'Genomgång av olika tekniker gällande LESS'
                    ],
                ],
            ],
        ],

        // This is a menu item
        'redovisning' => [
            'text'  =>'  Presentation',
            'url'   => $this->di->get('url')->create('redovisning'),
            'title' => 'Här samlas alla redovisningstexter under kursen',
        ],

        // This is a menu item
        'source' => [
            'text'  =>'  Source',
            'url'   => $this->di->get('url')->create('source'),
            'title' => 'Källkoden för me-sidan'
        ],
    ],

    /**
     * Callback tracing the current selected menu item base on scriptname
     *
     */
    'callback' => function ($url) {
        if ($url == $this->di->get('request')->getCurrentUrl(false)) {
            return true;
        }
    },

    /**
     * Callback to check if current page is a decendant of the menuitem, this check applies for those
     * menuitems that has the setting 'mark-if-parent' set to true.
     *
     */
    'is_parent' => function ($parent) {
        $route = $this->di->get('request')->getRoute();
        return !substr_compare($parent, $route, 0, strlen($parent));
    },

   /**
     * Callback to create the url, if needed, else comment out.
     *
     */
   /*
    'create_url' => function ($url) {
        return $this->di->get('url')->create($url);
    },
    */
];


text:
package org.elasticsearch.xpack.core.enrich.action;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;
import java.util.Objects;

public class DeleteEnrichPolicyAction extends ActionType<AcknowledgedResponse> {

    public static final DeleteEnrichPolicyAction INSTANCE = new DeleteEnrichPolicyAction();
    public static final String NAME = "cluster:admin/xpack/enrich/delete";

    private DeleteEnrichPolicyAction() {
        super(NAME, AcknowledgedResponse::readFrom);
    }

    public static class Request extends MasterNodeRequest<DeleteEnrichPolicyAction.Request> {

        private final String name;

        public Request(String name) {
            this.name = Objects.requireNonNull(name, "name cannot be null");
        }

        public Request(StreamInput in) throws IOException {
            super(in);
            this.name = in.readString();
        }

        public String getName() {
            return name;
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            super.writeTo(out);
            out.writeString(name);
        }

        @Override
        public ActionRequestValidationException validate() {
            return null;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Request request = (Request) o;
            return name.equals(request.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name);
        }
    }
}


text:
package gov.hhs.fha.nhinc.admindistribution.nhin.proxy;

import gov.hhs.fha.nhinc.admindistribution.AdminDistributionAuditLogger;
import gov.hhs.fha.nhinc.admindistribution.AdminDistributionHelper;
import gov.hhs.fha.nhinc.admindistribution.AdminDistributionUtils;
import gov.hhs.fha.nhinc.admindistribution.aspect.EDXLDistributionEventDescriptionBuilder;
import gov.hhs.fha.nhinc.admindistribution.nhin.proxy.service.NhinAdminDistributionG0ServicePortDescriptor;
import gov.hhs.fha.nhinc.admindistribution.nhin.proxy.service.NhinAdminDistributionG1ServicePortDescriptor;
import gov.hhs.fha.nhinc.aspect.NwhinInvocationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AcknowledgementType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinadmindistribution.RespondingGatewayAdministrativeDistributionPortType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.GATEWAY_API_LEVEL;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
import oasis.names.tc.emergency.edxl.de._1.EDXLDistribution;

import org.apache.log4j.Logger;

/**
 *
 * @author dunnek
 */
public class NhinAdminDistributionProxyWebServiceSecuredImpl implements NhinAdminDistributionProxy {
    private static final Logger LOG = Logger.getLogger(NhinAdminDistributionProxyWebServiceSecuredImpl.class);
    private AdminDistributionAuditLogger adLogger = null;

    /**
     * @return AdminDistributionUtils instance.
     */
    protected AdminDistributionUtils getAdminDistributionUtils() {
        return AdminDistributionUtils.getInstance();
    }

    private AdminDistributionHelper getHelper() {
        return new AdminDistributionHelper();
    }

    /**
     * @return WebServiceProxyHelper instance.
     */
    protected WebServiceProxyHelper getWebServiceProxyHelper() {
        return new WebServiceProxyHelper();
    }

    /**
     * This method returns ServicePortDescriptor for AdminDist based on gateway apiLevel.
     *
     * @param apiLevel gateway apiLevel received (g0/g1).
     * @return NhinAdminDistributionPortDescriptor based on g0/g1 impl
     */
    public ServicePortDescriptor<RespondingGatewayAdministrativeDistributionPortType> getServicePortDescriptor(
            NhincConstants.GATEWAY_API_LEVEL apiLevel) {
        switch (apiLevel) {
        case LEVEL_g0:
            return new NhinAdminDistributionG0ServicePortDescriptor();
        default:
            return new NhinAdminDistributionG1ServicePortDescriptor();
        }
    }

    /**
     * This method returns CXFClient to implement AdminDist Secured Service.
     *
     * @param portDescriptor Comprises of
     * @param url target community url to send the message.
     * @param assertion Assertion received.
     * @return CXFClient to implement Secured Service.
     */
    protected CONNECTClient<RespondingGatewayAdministrativeDistributionPortType> getCONNECTClientSecured(
            ServicePortDescriptor<RespondingGatewayAdministrativeDistributionPortType> portDescriptor, String url,
            AssertionType assertion, String target, String serviceName) {

        return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, assertion, url, target,
                serviceName);
    }

    /**
     * This method implements sendAlertMessage for AdminDist.
     *
     * @param body Emergency Message Distribution Element transaction messgae body.
     * @param assertion Assertion received.
     * @param target NhinTargetCommunity received.
     * @param apiLevel gateway apiLevel (g0/g1).
     */
    @Override
    @NwhinInvocationEvent(beforeBuilder = EDXLDistributionEventDescriptionBuilder.class, afterReturningBuilder = EDXLDistributionEventDescriptionBuilder.class, serviceType = "Admin Distribution", version = "")
    public void sendAlertMessage(EDXLDistribution body, AssertionType assertion, NhinTargetSystemType target,
            NhincConstants.GATEWAY_API_LEVEL apiLevel) {
        LOG.debug("begin sendAlertMessage");
        AdminDistributionHelper helper = getHelper();
        String url = helper.getUrl(target, NhincConstants.NHIN_ADMIN_DIST_SERVICE_NAME, apiLevel);

        if (NullChecker.isNotNullish(url)) {

            auditMessage(body, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, target);

            try {
                getAdminDistributionUtils().convertFileLocationToDataIfEnabled(body);

                ServicePortDescriptor<RespondingGatewayAdministrativeDistributionPortType> portDescriptor = getServicePortDescriptor(apiLevel);

                CONNECTClient<RespondingGatewayAdministrativeDistributionPortType> client = getCONNECTClientSecured(
                        portDescriptor, url, assertion, target.getHomeCommunity().getHomeCommunityId(),
                        NhincConstants.NHIN_ADMIN_DIST_SERVICE_NAME);
                if (apiLevel == GATEWAY_API_LEVEL.LEVEL_g1) {
                    client.enableMtom();
                }

                client.invokePort(RespondingGatewayAdministrativeDistributionPortType.class, "sendAlertMessage", body);
            } catch (Exception ex) {
                LOG.error("Failed to call the web service (" + NhincConstants.NHIN_ADMIN_DIST_SERVICE_NAME
                        + ").  An unexpected exception occurred.  " + "Exception: " + ex.getMessage(), ex);
            }
        } else {
            LOG.error("Failed to call the web service (" + NhincConstants.ADAPTER_ADMIN_DIST_SERVICE_NAME
                    + ").  The URL is null.");
        }
    }

    /**
     * This method audits the AdminDist Service at Nhin interface.
     *
     * @param message Emergency Message Distribution Element transaction message.
     * @param assertion Assertion received.
     * @param direction The direction can be eigther outbound or inbound.
     */
    protected void auditMessage(EDXLDistribution message, AssertionType assertion, String direction,
            NhinTargetSystemType target) {
        AcknowledgementType ack = getLogger().auditNhinAdminDist(message, assertion, direction, target,
                NhincConstants.AUDIT_LOG_NHIN_INTERFACE);
        if (ack != null) {
            LOG.debug("ack: " + ack.getMessage());
        }
    }

    /**
     * @return Nhin AdminDist audit logger.
     */
    protected AdminDistributionAuditLogger getLogger() {
        return (adLogger != null) ? adLogger : new AdminDistributionAuditLogger();
    }

}


text:
using UnityEngine;
 using System.Collections;

 public class ParticleSystemAutoDestroy : MonoBehaviour
 {
     private ParticleSystem ps;

     public void Start()
     {
         ps = GetComponent<ParticleSystem>();
     }

     public void Update()
     {
         if(ps)
         {
             if(!ps.IsAlive())
             {
                 Destroy(gameObject);
             }
         }
     }
 }


text:
title: FAQ / Troubleshooting
url: references/developer-app/troubleshoot-faq
github_url: https://github.com/phonegap/phonegap-docs/blob/master/docs/references/developer-app/10-troubleshoot-faq.html.md
layout: subpage
expand: dev-app
---

1. *Which plugins are supported by the PhoneGap Developer app?*

 The PhoneGap Developer App supports all of the PhoneGap core plugins as well as some other popular plugins to allow you to easily test with
 them in your app on a mobile device. Below is a list of supported plugins at the time of this writing however you can get the latest list at
 any time by checking the [GitHub repo](https://github.com/phonegap/phonegap-app-developer/tree/master/plugins).

  - [Battery Status](https://www.npmjs.com/package/cordova-plugin-battery-status)
  - [Bluetooth](http://evothings.com/doc/plugins/com.megster.cordova.bluetoothserial/index.html)
  - [Camera](https://www.npmjs.com/package/cordova-plugin-camera)
  - [Console](https://www.npmjs.com/package/cordova-plugin-console)
  - [Contacts](https://www.npmjs.com/package/cordova-plugin-contacts)
  - [Device Motion](https://www.npmjs.com/package/cordova-plugin-device-motion)
  - [Device Orientation](https://www.npmjs.com/package/cordova-plugin-device-orientation)
  - [Device](https://www.npmjs.com/package/cordova-plugin-device)
  - [Dialogs](https://www.npmjs.com/package/cordova-plugin-dialogs)
  - [Insomnia](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin)
  - [File](https://www.npmjs.com/package/cordova-plugin-file)
  - [File Transfer](https://www.npmjs.com/package/cordova-plugin-file-transfer)
  - [Geolocation](https://www.npmjs.com/package/cordova-plugin-geolocation)
  - [Globalization](https://www.npmjs.com/package/cordova-plugin-globalization)
  - [InAppBrowser](https://www.npmjs.com/package/cordova-plugin-inappbrowser)
  - [MediaCapture](https://www.npmjs.com/package/cordova-plugin-media-capture)
  - [Media](https://www.npmjs.com/package/cordova-plugin-media)
  - [Network Information](https://www.npmjs.com/package/cordova-plugin-network-information)
  - [Splash Screen](https://www.npmjs.com/package/cordova-plugin-splashscreen)
  - [Status Bar](https://www.npmjs.com/package/cordova-plugin-statusbar)
  - [Vibration](https://www.npmjs.com/package/cordova-plugin-vibration)
  - [Content Sync](https://www.npmjs.com/package/phonegap-plugin-contentsync)
  - [Adobe Mobile Services](https://github.com/Adobe-Marketing-Cloud/mobile-services)

If you're using a plugin in your project that is not shown in this list, it will not work with the PhoneGap Developer
 App out of the box. However, you can create your own [custom build of the PhoneGap Developer app](/references/developer-app/custom-build/ios)
 locally and include any other plugins there. We recommend always checking for the existence of any plugin in your code first before using it
 to avoid errors in testing in general.

2. *What is Autoreload?*

 Autoreload is a feature that will automatically refresh your previewed app
 when a file changes in the `www/` directory. This allows you to immediately
 preview your changes without four-finger tapping the devices screen. It's
 especially useful when previewing multiple devices at the same time.

 Autoreload is a developer feature that only works while connected to the
 PhoneGap CLI. If the CLI server stops, then autoreload will stop working.

 By default, autoreload is enabled. However, you can force it to be enabled
 or disabled with the following commands:

    ```
    $ phonegap serve --autoreload
    $ phonegap serve --no-autoreload
    ```

3. *How can I debug my apps remotely?*

  We are working on ways to make debugging easier with the PhoneGap Developer app, but for now there are two ways it can be done:
   1. Using [Weinre](https://www.npmjs.com/package/weinre)
   2. Running your own custom build of PhoneGap Developer App (as opposed to the app marketplace version)

 Check out the [debugging section](/references/developer-app/debugging) for more details.

4. *PhoneGap Developer App hangs on `DOWNLOADING...` for iOS*

 Currently if you enter the wrong IP address (or an invalid one) to connect to, it will hang on the DOWNLOADING phase and you will need to exit and
 restart the app to try again. See the [bug being tracked here](https://github.com/phonegap/phonegap-app-developer/issues/338) for more details.


text:
package com.juchao.upg.android.view;

import android.widget.LinearLayout;
import android.widget.PopupWindow;

/**
 * 创建一个弹出窗体,显示点检项目详细信息
 * @author xiao-jiang
 *
 */
public class PopupInspectionItemDetailUtil {

	private static final String TAG=PopupInspectionItemDetailUtil.class.getSimpleName();
	private PopupWindow popupWindow;
	private LinearLayout scanCode,plan,managementOrgNum,equipmentName,projectSeq,projectName,checkMethod,judgeMethod;

}


text:
package st.domain.ggviario.secret.items;

import android.view.View;
import android.widget.TextView;

import st.domain.ggviario.secret.R;
import st.domain.ggviario.secret.model.Client;
import st.zudamue.support.android.adapter.ItemDataSet;
import st.zudamue.support.android.adapter.ItemViewHolder;

/**
 *
 * Created by dchost on 06/02/17.
 */

public class ClientViewHolder extends ItemViewHolder {

    private CreditsClientDataSet dataSet;
    private TextView tvClientAvatar;
    private TextView tvClientName;
    private TextView tvClientSubInformation;
    private TextView tvClientAvatarSecond;
    private ItemCallback onClickcallback;

    public ClientViewHolder setOnClickCallback(ItemCallback onClickCallback ){
        this.onClickcallback = onClickCallback;
        return this;
    }

    public ClientViewHolder(View itemView) {
        super(itemView);
        this.tvClientAvatar = ( TextView ) this.itemView.findViewById( R.id.tv_client_avatar );
        this.tvClientName = ( TextView ) this.itemView.findViewById( R.id.tv_client_name );
        this.tvClientSubInformation = ( TextView ) this.itemView.findViewById( R.id.tv_client_info );
        this.tvClientAvatarSecond = ( TextView ) this.itemView.findViewById( R.id.tv_client_avatar_second );
        this.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callback( onClickcallback );
            }
        });
    }

    @Override
    public void onBind(ItemDataSet dataSet, int currentAdapterPosition, int totalDataSet) {
        this.dataSet = ( CreditsClientDataSet ) dataSet;
        this.tvClientAvatar.setText( this.dataSet.client.getAvatar() );
        this.tvClientName.setText( this.dataSet.client );
        this.tvClientSubInformation.setText( this.dataSet.client.getSubInformation() );
        this.tvClientAvatarSecond.setText( this.dataSet.getAvatarSecond() );
    }

    public static CreditsClientDataSet newInstance ( Client client, int totalCredits, int totalCreditsPay ) {
        return new CreditsClientDataSet(client, totalCredits, totalCreditsPay);
    }

    public static class CreditsClientDataSet implements ItemDataSet {

        private final Client client;
        private final int totalCreditsPay;
        private final int totalCredits;

        private CreditsClientDataSet ( Client client, int totalCredits, int totalCreditsPay ) {
            this.client = client;
            this.totalCredits = totalCredits;
            this.totalCreditsPay = totalCreditsPay;
        }

        @Override
        public int getLayoutId() {
            return R.layout._client_item;
        }

        public CharSequence getAvatarSecond() {
            return String.valueOf( this.totalCredits - this.totalCreditsPay );
        }

        public Client getClient() {
            return this.client;
        }
    }
}


text:
CREATE TABLE `ospos_modules` (
  `name_lang_key` varchar(255) NOT NULL,
  `desc_lang_key` varchar(255) NOT NULL,
  `sort` int(10) NOT NULL,
  `module_id` varchar(255) NOT NULL,
  PRIMARY KEY (`module_id`),
  UNIQUE KEY `desc_lang_key` (`desc_lang_key`),
  UNIQUE KEY `name_lang_key` (`name_lang_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8