text:
#ifndef ANIMATION_H
#define ANIMATION_H
#include <mgl2/fltk.h>
#include <mgl2/mgl.h>
#include <mgl2/type.h>
#include <vector>
#include <unistd.h>
#include <string>
#include <iostream>
#include <thread>
#include <mutex>
#include "cont_data.h"
/*-------------------------------------------------------------------------
Author: Joey Allen
Created/last Modified: 10/5/14

Description:
The class animation controls the internal mechanisms of displaying and controlling
the speed of animation.
---------------------------------------------------------------------------*/
class Animation
{
	protected:
		mglFLTK* gr;
		cont_data* calculator;
		void Run();
		bool animation_paused;
		int points;  //The amount of point to calculate.
	private:
		int speed; //The speed of the animation
			   //**specificationf or speed not yet defined.
		//SIGNALS
		//If set to true, then animation will start/resume/continue
		//If set to false, animation will stall/pause until animation_paused is
		//set to 1.
		bool animation_begin;
		//If set to false, then animation has not started.
		//This function will be set to 1 when ToggleAnimation is started for hte
		//first time.
		void beginAnimation(); //Begin animation will begin the calculation.
		void UpdatePointers(int t, mglData* &, mglData* & , mglData* & );
		//Internal Method used for updating memory for drawing.  Should never
		//Be called or used by functions other than beginAnimation();
	public:
		 Animation(std::string = "PDE SOLVER", int s = 1, int p = 5000);
		~Animation();

	//	virtual void calculation(){}  //I don't know what to do right here.
		//Theoretically this will be the method that controls the calculation
		//Basic High-level animation controls.
//		virtual void calculation(int t, mglData* x, mglData * y, mglData * z, int n){}
		virtual void calculation(){}
		void toggleAnimation(); //Toggles animation from paused to resuming.
					//First call to toggle will begin the animation.
		//Getters
		int getSpeed(){return(speed);}
		int getPoints(){return(points);}
		//Setters
		int setCalculator(cont_data *aCalculator){calculator = aCalculator;}
		void RunThread();
		void setSpeed(int s){speed = s;}
		void setPoints(int p){points = p;}
		void update();
		void drawDots(mglData * , mglData* , mglData* , mglData*);
		void rotate(int arg1, int arg2);
};

#endif //ANIMATION_H


text:
// scalastyle:off println
package org.apache.spark.examples

import java.util.Random

import org.apache.spark.sql.SparkSession

/**
 * Usage: GroupByTest [numMappers] [numKVPairs] [KeySize] [numReducers]
 */
object SkewedGroupByTest {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession
      .builder
      .appName("GroupBy Test")
      .getOrCreate()

    val numMappers = if (args.length > 0) args(0).toInt else 2
    var numKVPairs = if (args.length > 1) args(1).toInt else 1000
    val valSize = if (args.length > 2) args(2).toInt else 1000
    val numReducers = if (args.length > 3) args(3).toInt else numMappers

    val pairs1 = spark.sparkContext.parallelize(0 until numMappers, numMappers).flatMap { p =>
      val ranGen = new Random

      // map output sizes linearly increase from the 1st to the last
      numKVPairs = (1.0 * (p + 1) / numMappers * numKVPairs).toInt

      val arr1 = new Array[(Int, Array[Byte])](numKVPairs)
      for (i <- 0 until numKVPairs) {
        val byteArr = new Array[Byte](valSize)
        ranGen.nextBytes(byteArr)
        arr1(i) = (ranGen.nextInt(Int.MaxValue), byteArr)
      }
      arr1
    }.cache()
    // Enforce that everything has been calculated and in cache
    pairs1.count()

    println(pairs1.groupByKey(numReducers).count())

    spark.stop()
  }
}
// scalastyle:on println

redpajama_set_name: RedPajamaGithub


text:
package server.msg;

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

import server.SimpleConstants;
import server.userauth.SimpleUser;

/**
 *
Query for a data value. Some data values require a user identity for
 * access.

 *
 *
The request data object is defined as:
 * {@code
 * data = {
 *   "#mandatory" : [ "key" ],
 *   "key" : "string"
 * }} where:
 *

 *
{@code key} is the data key identifying the value.

 *

 *
 * @author Wesley Miaw <wmiaw@netflix.com>
 */
public class SimpleQueryRequest extends SimpleRequest {
    /** JSON key key. */
    private static final String KEY_KEY = "key";

    /**
     *
Create a new query request.

     *
     * @param identity requesting entity identity.
     * @param user requesting user. May be null.
     * @param data the request data.
     * @throws SimpleRequestParseException if there is an error parsing the
     *         request data.
     */
    public SimpleQueryRequest(final String identity, final SimpleUser user, final JSONObject data) throws SimpleRequestParseException {
        super(Type.QUERY, identity, user);
        try {
            key = data.getString(KEY_KEY);
        } catch (final JSONException e) {
            throw new SimpleRequestParseException("Error parsing query request: " + data.toString() + ".", e);
        }
    }

    /**
     * @return the data key.
     */
    public String getKey() {
        return key;
    }

    /* (non-Javadoc)
     * @see server.msg.SimpleRequest#getData()
     */
    @Override
    public JSONObject getData() {
        final JSONObject jo = new JSONObject();
        jo.put(KEY_KEY, key);
        return jo;
    }

    /* (non-Javadoc)
     * @see server.msg.SimpleRequest#execute()
     */
    @Override
    public SimpleRespondMessageContext execute() throws SimpleRequestUserException, SimpleRequestExecutionException {
        // Pull requesting user.
        final SimpleUser user = getUser();
        final String username = (user != null) ? user.toString() : null;

        // Identify the requested data.
        for (final String[] data : SimpleConstants.QUERY_DATA) {
            if (data[1].equals(key)) {
                final String response;
                if (data[0] != null && !data[0].equals(username))
                    throw new SimpleRequestUserException("Error: access restricted to user " + data[0] + ".");
                else
                    response = data[2];
                return new SimpleRespondMessageContext(getIdentity(), true, response);
            }
        }

        // Data key not found.
        throw new SimpleRequestExecutionException("Error: no data found for key " + key + ".");
    }

    /** Data key. */
    private final String key;
}


text:
using System;
using System.Text;

using Extemory.MemoryEdits;

namespace Extemory
{
    public static class IntegerExtensions
    {
        #region int

        /// <summary>
        /// Read a struct type from an unmanaged pointer.
        /// </summary>
        /// <typeparam name="T">Struct type to read</typeparam>
        /// <param name="addr">Pointer address to read from</param>
        /// <returns></returns>
        public static T Read<T>(this int addr) where T : struct
        {
            return new IntPtr(addr).Read<T>();
        }

        /// <summary>
        /// Write a structure to unmanaged memory
        /// </summary>
        /// <typeparam name="T">Struct type to write</typeparam>
        /// <param name="addr">Address to write to</param>
        /// <param name="data">Struct data to write</param>
        public static void Write<T>(this int addr, T data) where T : struct
        {
            new IntPtr(addr).Write(data);
        }

        /// <summary>
        /// Read an array of integral types (int, float, byte, etc) from unmanaged memory.
        /// </summary>
        /// <typeparam name="T">Integral type to read. Must be struct, but not all structs are supported (only those supported by Marshal.Copy</typeparam>
        /// <param name="addr">Address to read array from</param>
        /// <param name="size">Size of the array to read (number of elements)</param>
        /// <returns></returns>
        public static T[] ReadArray<T>(this int addr, int size) where T : struct
        {
            return new IntPtr(addr).ReadArray<T>(size);
        }

        /// <summary>
        /// Write an array of integral types (int, float, byte, etc) to unmanaged memory.
        /// </summary>
        /// <typeparam name="T">Integral type to write. Must be struct, but not all structs are supported (only those supported by Marshal.Copy</typeparam>
        /// <param name="addr">Address to write array to</param>
        /// <param name="data">Array data to write</param>
        public static void WriteArray<T>(this int addr, T[] data) where T : struct
        {
            new IntPtr(addr).WriteArray(data);
        }

        public static string ReadString(this int addr, Encoding encoding)
        {
            return new IntPtr(addr).ReadString(encoding);
        }

        public static void WriteString(this int addr, string value, Encoding encoding)
        {
            new IntPtr(addr).WriteString(value, encoding);
        }

        public static IntPtr VTable(this int addr, int index)
        {
            return new IntPtr(addr).VTable(index);
        }

        public static T ToDelegate<T>(this int addr) where T : class
        {
            return new IntPtr(addr).ToDelegate<T>();
        }

        public static Detour<T> DetourWith<T>(this int addr, T del) where T : class
        {
            return new IntPtr(addr).DetourWith(del);
        }

        #endregion

        #region uint

        public static T Read<T>(this uint addr) where T : struct
        {
            return new IntPtr(addr).Read<T>();
        }

        public static void Write<T>(this uint addr, T data) where T : struct
        {
            new IntPtr(addr).Write(data);
        }

        public static T[] ReadArray<T>(this uint addr, int size) where T : struct
        {
            return new IntPtr(addr).ReadArray<T>(size);
        }

        public static void WriteArray<T>(this uint addr, T[] data) where T : struct
        {
            new IntPtr(addr).WriteArray(data);
        }

        public static string ReadString(this uint addr, Encoding encoding)
        {
            return new IntPtr(addr).ReadString(encoding);
        }

        public static void WriteString(this uint addr, string value, Encoding encoding)
        {
            new IntPtr(addr).WriteString(value, encoding);
        }

        public static IntPtr VTable(this uint addr, int index)
        {
            return new IntPtr(addr).VTable(index);
        }

        public static T ToDelegate<T>(this uint addr) where T : class
        {
            return new IntPtr(addr).ToDelegate<T>();
        }

        public static Detour<T> DetourWith<T>(this uint addr, T del) where T : class
        {
            return new IntPtr(addr).DetourWith(del);
        }

        #endregion

        #region long

        public static T Read<T>(this long addr) where T : struct
        {
            return new IntPtr(addr).Read<T>();
        }

        public static void Write<T>(this long addr, T data) where T : struct
        {
            new IntPtr(addr).Write(data);
        }

        public static T[] ReadArray<T>(this long addr, int size) where T : struct
        {
            return new IntPtr(addr).ReadArray<T>(size);
        }

        public static void WriteArray<T>(this long addr, T[] data) where T : struct
        {
            new IntPtr(addr).WriteArray(data);
        }

        public static string ReadString(this long addr, Encoding encoding)
        {
            return new IntPtr(addr).ReadString(encoding);
        }

        public static void WriteString(this long addr, string value, Encoding encoding)
        {
            new IntPtr(addr).WriteString(value, encoding);
        }

        public static IntPtr VTable(this long addr, int index)
        {
            return new IntPtr(addr).VTable(index);
        }

        public static T ToDelegate<T>(this long addr) where T : class
        {
            return new IntPtr(addr).ToDelegate<T>();
        }

        public static Detour<T> DetourWith<T>(this long addr, T del) where T : class
        {
            return new IntPtr(addr).DetourWith(del);
        }

        #endregion
    }
}


text:
/*eslint no-console: 0 */
/*eslint no-process-env: 0 */

const os = require('os')
const path = require('path')
const spawn = require('child_process').spawn
const spawnSync = require('child_process').spawnSync
const npm = /^win/.test(os.platform()) ? 'npm.cmd' : 'npm'

const requiredList = [
  'trailpack',
  'trailpack-router',
  'trailpack-repl',
  'trailpack-winston',
  'trailpack-hapi'
]

const optionalList = [
  'trailpack-waterline',
  'trailpack-knex',
  'trailpack-footprints',
  'trailpack-express',
  'trailpack-webpack',
  'trailpack-bootstrap',
  'trailpack-autoreload'
]

module.exports = {

  getTrailpackList () {
    let list
    if (process.env.REQUIRED_TESTS) {
      list = requiredList
    }
    else if (process.env.OPTIONAL_TESTS) {
      list = optionalList
    }
    else {
      console.log('REQUIRED_TESTS and OPTIONAL_TESTS not set. Running all tests.')
      list = requiredList.concat(optionalList)
    }

    return list.map(name => {
      return {
        clone_url: `https://github.com/trailsjs/${name}.git`,
        name: name
      }
    })
  },

  cloneTrailpacks (repos) {
    return Promise.all(repos.map(repo => {
      return new Promise((resolve, reject) => {
        console.log('>> git clone', repo.clone_url)
        const proc = spawn('git', [ 'clone', repo.clone_url ])

        proc.on('close', resolve)
        proc.on('error', reject)
      })
    }))
  },

  npmInstallTrailpacks (repos) {
    return Promise.all(repos.map(repo => {
      const wd = path.resolve(process.cwd(), repo.name)
      return new Promise((resolve, reject) => {
        console.log('>> npm install', repo.name)
        const proc = spawnSync(npm, [ 'install', '--no-progress', '-q', '--force' ], {
          cwd: wd,
          stdio: [
            'ignore',
            'ignore',
            process.stderr
          ]
        })
        resolve(proc.status)
      }).then(() => {
        return new Promise((resolve, reject) => {
          console.log('>> npm link trails')
          const proc = spawnSync(npm, [ 'link', 'trails', '--force' ], {
            cwd: wd,
            stdio: [
              'ignore',
              process.stdout,
              process.stderr
            ]
          })
          resolve(proc.status)
        })
      })
    }))
  },

  checkNodeSecurity (repos) {
    return new Promise((resolve, reject) => {
      const proc = spawn(npm, [ 'install', '-g', 'nsp', '--force' ], {
        stdio: [
          'ignore',
          process.stdout,
          process.stderr
        ]
      })
      proc.on('close', resolve)
      proc.on('error', reject)
    }).then(() => {
      return Promise.all(repos.map(repo => {
        return new Promise((resolve, reject) => {
          const wd = path.resolve(process.cwd(), repo.name)
          console.log('>> checking security of', repo.name)
          const proc = spawn('nsp', [ 'check', '--output', 'summary' ], {
            cwd: wd,
            stdio: [
              'ignore',
              process.stdout,
              process.stderr
            ]
          })
          proc.on('close', resolve)
          proc.on('error', reject)
        })
      }))
    })
  },

  npmTestTrailpacks (repos) {
    return repos.map(repo => {
      const wd = path.resolve(process.cwd(), repo.name)
      const proc = spawnSync(npm, [ 'test' ], {
        cwd: wd,
        stdio: [
          'ignore',
          process.stdout,
          process.stderr
        ]
      })

      return proc.status
    })
  }
}


text:
package xworker.web.angular;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class FileManagerActions {
	public static void httpDo(ActionContext actionContext) throws ServletException, IOException{
		Thing self = actionContext.getObject("self");

		AngularFileManagerServlet af = (AngularFileManagerServlet) self.getData("AngularFileManagerServlet");
		if(af == null){
			af = new AngularFileManagerServlet((String) self.doAction("getBaseUrl", actionContext), (HttpServlet) actionContext.getObject("servlet"));
			self.setData("AngularFileManagerServlet", af);
		}

		String method = actionContext.getObject("requestMethod");
		HttpServletRequest request = actionContext.getObject("request");
		HttpServletResponse response = actionContext.getObject("response");

		if("POST".equals(method)){
			af.doPost(request, response);
		}else{
			af.doGet(request, response);
		}
	}

}


text:
class ExternsChecker(object):
  _UPDATE_MESSAGE = """To update the externs, run:
 src/ $ python tools/json_schema_compiler/compiler.py\
 %s --root=. --generator=externs > %s"""

  def __init__(self, input_api, output_api, api_pairs):
    self._input_api = input_api
    self._output_api = output_api
    self._api_pairs = api_pairs

    for path in api_pairs.keys() + api_pairs.values():
      if not input_api.os_path.exists(path):
        raise OSError('Path Not Found: %s' % path)

  def RunChecks(self):
    bad_files = []
    affected = [f.AbsoluteLocalPath() for f in self._input_api.AffectedFiles()]
    for path in affected:
      pair = self._api_pairs.get(path)
      if pair != None and pair not in affected:
        bad_files.append({'source': path, 'extern': pair})
    results = []
    if bad_files:
      replacements = (('<source_file>', '<output_file>') if len(bad_files) > 1
          else (bad_files[0]['source'], bad_files[0]['extern']))
      long_text = self._UPDATE_MESSAGE % replacements
      results.append(self._output_api.PresubmitPromptWarning(
          str('Found updated extension api files without updated extern files. '
              'Please update the extern files.'),
          [f['source'] for f in bad_files],
          long_text))
    return results


text:
These are provided as stl files which can be opened by probably all 3D printer software.

## Laser cutting files (.ai)
These are provided in Adobe Illustrator format (.ai). Inkscape is recommneded to open these or Adobe Illustrator CS2 is now avaialble as free software although its very old.

## Simulation Files (.xml.gz)
The simulation files are gun-zipped xml files and have the extension .xml.gz - they are used in the Acoustic Field Simulator software which is also in this repository.

# Parts List
* 20-core ribbon cable [from UK Farnell](http://uk.farnell.com/3m/3302-20/ribbon-cable-20core-28awg-per/dp/1207420)
* 3-way pcb connector
  * uk rs-components 506-7014
* female molex connector
  * uk rs-components 323-7873
* 40khz 1cm diameter transducers
 * MURATA: uk rs-components 237-0799
* The murata transducers are a little bit pricey so here are some alternatives:
  * Manorshi Black 10mm - 0.34$ - MSO-P1040H07T [from alibaba](https://manorshi.en.alibaba.com)
  * Ningbo Black 10mm - 0.38$ - 'dog repeller' [from alibaba](FBULS1007P-T https://bestgroup.en.alibaba.com/product/987365133-800848321/dog_repeller_ultrasonic_transducer_40khz_black_plastic_ultrasonic_sensor_ultrasonic_depth_sensor.html)


text:
"""
    font.py -- Displays FPS in OpenGL using TrueType fonts.

    Copyright (c) 2002. Nelson Rush. All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
"""

from OpenGL.GL import *
from OpenGL.GLU import *

from pygame.locals import *
from pygame.display import *
from pygame.event import *
from pygame.key import *
from pygame.mouse import *
from pygame.font import *
from pygame.image import *
from pygame.time import *
from pygame import *
import sys

class Engine:
    def __init__(self,w,h):
        init()
        display.init()
        display.set_mode([w,h], DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE)
        self.initgl()
        self.resize(w,h)
        mouse.set_visible(0)
        self.w = w
        self.h = h
        font.init()
        if not font.get_init():
            print 'Could not render font.'
            sys.exit(0)
        self.font = font.Font('font.ttf',18)
        self.char = []
        for c in range(256):
            self.char.append(self.CreateCharacter(chr(c)))
        self.char = tuple(self.char)
        self.lw = self.char[ord('0')][1]
        self.lh = self.char[ord('0')][2]
        self.angle = 0.0
        self.frames = self.t = self.t_start = self.fps = 0

    def initgl(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClearDepth(1.0)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LEQUAL)
        glShadeModel(GL_SMOOTH)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

    def resize(self,w,h):
        if h == 0: h = 1
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(w) / float(h), 0.5, 150.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def CreateCharacter(self, s):
        try:
            letter_render = self.font.render(s, 1, (255,255,255), (0,0,0))
            letter = image.tostring(letter_render, 'RGBA', 1)
            letter_w, letter_h = letter_render.get_size()
        except:
            letter = None
            letter_w = 0
            letter_h = 0
        return (letter, letter_w, letter_h)

    def textView(self):
        glViewport(0,0,self.w,self.h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0.0, self.w - 1.0, 0.0, self.h - 1.0, -1.0, 1.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def Print(self,s,x,y):
        s = str(s)
        i = 0
        lx = 0
        length = len(s)
        self.textView()
        glPushMatrix()
        while i < length:
            glRasterPos2i(x + lx, y)
            ch = self.char[ ord( s[i] ) ]
            glDrawPixels(ch[1], ch[2], GL_RGBA, GL_UNSIGNED_BYTE, ch[0])
            lx += ch[1]
            i += 1
        glPopMatrix()

    def DrawFPS(self, x, y):
        self.t = time.get_ticks()
        self.frames += 1
        if self.t - self.t_start > 1000:
            self.fps = self.frames * 1000 / (self.t - self.t_start)
            self.t_start = self.t
            self.frames = 0
        self.Print(self.fps, x, y)

    def draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        self.resize(self.w,self.h)
        glTranslatef(0.0, 0.0, -6.0)
        glPushMatrix()
        glRotatef(self.angle, 0.0, 1.0, 0.0)
        glBegin(GL_TRIANGLES)
        glColor3f(0.0, 0.0, 1.0)
        glVertex3f(0.0, 1.0, 0.0)
        glVertex3f(-1.0, -1.0, 0.0)
        glVertex3f(1.0, -1.0, 0.0)
        glEnd()
        glPopMatrix()

        self.DrawFPS(self.w - (self.lw * 3), self.h - self.lh)

        self.angle += 1.0

    def run(self):
        while 1:
            e = event.poll()
            k = key.get_pressed()
            if e.type == KEYDOWN and e.key == K_ESCAPE: break
            self.draw()
            display.flip()

if __name__ == '__main__':
    engine = Engine(640,480)
    engine.run()
    font.quit()
    display.quit()


text:
import {Injectable, Inject, LOCALE_ID} from '@angular/core';
import {PlatformService} from './platform.service';
import {I18NService} from '../modules/i18n/services/i18n.service';

export interface Country {
	id: string;
	name: string;
	foi?: {
		url: string;
		name: string;
		search: string;
	};
	whistle?: Array<{
		url: string;
		name: string;
	}>;
}

@Injectable()
export class ConfigService {
	public config: ClientConfig;
	public country: Country;
	public absUrl: string = '';
	public locale: string;
	public contactmail = 'info@govtransparency.eu';
	public validMinYear: number = 2009;
	public validMaxYear: number = 2018;

	constructor(@Inject('opentender') externalConfig,
				@Inject('config') serverConfig,
				@Inject('absurl') externalAbsUrl,
				@Inject(LOCALE_ID) externalLocale,
				private platform: PlatformService,
				private i18n: I18NService) {
		this.locale = null;
		if (externalLocale) {
			this.locale = externalLocale.slice(0, 2).toLowerCase();
		}
		let config = externalConfig;
		if (!config && this.platform.isBrowser) {
			config = document['opentender'];
		}
		if (!this.platform.isBrowser && serverConfig) {
			config.config = serverConfig;
		}
		if (!platform.isBrowser) {
			this.absUrl = externalAbsUrl;
		}
		if (config) {
			this.config = config.config;
			this.country = config.country;
			if (this.locale !== 'en') {
				this.country.name = i18n.getPortalName(config.country.id, config.country.name);
			}
		} else {
			this.config = {backendUrl: null, version: 'unknown', devMode: true};
			this.country = {id: null, name: 'General'};
		}
	}

}


text:
int main() {
  Botan::PKCS11::Module module("C:\\pkcs11-middleware\\library.dll");
  // open write session to first slot with connected token
  std::vector<Botan::PKCS11::SlotId> slots = Botan::PKCS11::Slot::get_available_slots(module, true);
  Botan::PKCS11::Slot slot(module, slots.at(0));
  Botan::PKCS11::Session session(slot, false);

  // create an simple data object
  Botan::secure_vector<uint8_t> value = {0x00, 0x01, 0x02, 0x03};
  std::size_t id = 1337;
  std::string label = "test data object";

  // set properties of the new object
  Botan::PKCS11::DataObjectProperties data_obj_props;
  data_obj_props.set_label(label);
  data_obj_props.set_value(value);
  data_obj_props.set_token(true);
  data_obj_props.set_modifiable(true);
  std::vector<uint8_t> encoded_id;
  Botan::DER_Encoder(encoded_id).encode(id);
  data_obj_props.set_object_id(encoded_id);

  // create the object
  Botan::PKCS11::Object data_obj(session, data_obj_props);

  // get label of this object
  Botan::PKCS11::secure_string retrieved_label =
      data_obj.get_attribute_value(Botan::PKCS11::AttributeType::Label);

  // set a new label
  Botan::PKCS11::secure_string new_label = {'B', 'o', 't', 'a', 'n'};
  data_obj.set_attribute_value(Botan::PKCS11::AttributeType::Label, new_label);

  // copy the object
  Botan::PKCS11::AttributeContainer copy_attributes;
  copy_attributes.add_string(Botan::PKCS11::AttributeType::Label, "copied object");
  [[maybe_unused]] Botan::PKCS11::ObjectHandle copied_obj_handle = data_obj.copy(copy_attributes);

  // search for an object
  Botan::PKCS11::AttributeContainer search_template;
  search_template.add_string(Botan::PKCS11::AttributeType::Label, "Botan");
  auto found_objs =
      Botan::PKCS11::Object::search<Botan::PKCS11::Object>(session, search_template.attributes());

  // destroy the object
  data_obj.destroy();

  return 0;
}


text:
Pagination
==========

.. image:: https://travis-ci.org/alexandresalome/pagination.png?branch=master
   :alt: Build status
   :target: https://travis-ci.org/alexandresalome/pagination

**Requirements**: PHP 5.3

**DEPRECATED**: this library is deprecated. It is recommended to use pagerfanta.

Personal library used to paginate stuff.

Create a pager
--------------

To paginate something:

.. code-block:: php

    $pager = new Pager(new ArrayAdapter($array));

Pager object
------------

.. code-block:: php

    // Change position
    $pager->setOffset(30);
    $pager->setLimit(10);
    $pager->setPerPage(20);
    $pager->setPage(3);

    // Inspect
    $pager->getPageCount(); // can be zero
    $pager->getPage();
    $pager->getPerPage();
    $pager->getOffset();
    $pager->isFirstPage();
    $pager->isLastPage();

    foreach ($pager as $element) {
        echo $element;
    }

Create your own adapter
-----------------------

If you want to paginate something, just create an adapter for it:

.. code-block:: php

    interface AdapterInterface
    {
        public function get($offset, $limit);
        public function count();
    }

Adapters
--------

.. code-block:: php

    // Paginate an array
    $array = range(1, 1000);
    $pager = new Pager(new ArrayAdapter($array));

    // Paginate a git log
    $log = $repository->getLog(); // see gitonomy/gitlib
    $pager = new Pager(new GitlibLogAdapter($log));


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml

{# wf_updated_on: 2015-09-14 #}
{# wf_published_on: 2015-09-14 #}
{# wf_youtube_id: TLXmB2TZyZE #}

# Live on stage: building a WebRTC app {: .page-title }

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="TLXmB2TZyZE"
          data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>

Tim Panton builds a WebRTC application live on stage from scratch.

This session is from an afternoon of talks by WebRTC experts, including updates from Google, Mozilla and Microsoft. The event took place at the Google office in San Francisco. More details at http://krankygeek.com.


text:
@interface CMMediaCropEditor : NSObject

- (void)cutVideo:(NSString *)videoPath
        savePath:(NSString *)savePath
    startSeconds:(double)startSeconds
        duration:(double)duration
       timeScale:(int)timeScale
      renderSize:(CGSize)renderSize
      usingBlock:(void(^)(NSString *savePath, NSError *error))block;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Bjd;
using Bjd.Logs;
using Bjd.Mailbox;
using Bjd.Configurations;

namespace Bjd.SmtpServer
{
    class MlList:IDisposable {
        readonly List<Ml> _ar = new List<Ml>();
        public MlList(Kernel kernel,Server server,MailSave mailSave, List<string> domainList) {

            var optionMl = kernel.ListOption.Get("Ml");

            //メーリングストの一覧を取得する
            var dat = (Dat) optionMl.GetValue("mlList");
            if (dat != null){
                foreach (var o2 in dat){
                    if (!o2.Enable)
                        continue;
                    //メーリングリスト名の読込
                    var mlName = o2.ColumnValueList[0];
                    var op = kernel.ListOption.Get("Ml-" + mlName);
                    var logger = kernel.CreateLogger(mlName, (bool) op.GetValue("useDetailsLog"), server);
                    var mlOption = new MlOption(kernel,op);
                    //無効なメンバ指定の確認と警告
                    foreach (var d in mlOption.MemberList){
                        var mailAddress = new MailAddress(d.ColumnValueList[1]); //メールアドレス
                        if (mailAddress.User != "" && mailAddress.Domain != "")
                            continue;
                        if (logger != null){
                            logger.Set(LogKind.Error, null, 53, string.Format("{0}", d.ColumnValueList[1]));
                        }
                    }
                    if (mlOption.MemberList.Count == 0){
                        logger.Set(LogKind.Error, null, 57, string.Format("{0}", mlName));
                        continue;
                    }
                    var ml = new Ml(kernel, logger, mailSave, mlOption, mlName, domainList);
                    //MLの管理領域の初期化に失敗している場合は、追加しない
                    if (!ml.Status)
                        continue;
                    _ar.Add(ml);
                    if (logger != null)
                        logger.Set(LogKind.Normal, null, 44, mlName);
                }
            }

        }
        //終了処理
        public void Dispose() {
            foreach(var ml in _ar) {
                ml.Dispose();//終了処理
            }
        }
        //有効なメーリングリスト名かどうかの確認
        public bool IsUser(MailAddress mailAddress){
            return _ar.Any(ml => ml.IsUser(mailAddress));
        }

        //当該メーリングリストに処理を分岐する
        public bool Job(MlEnvelope mlEnvelope,Mail mail) {
            foreach(var ml in _ar) {
                if (ml.IsUser(mlEnvelope.To)) {
                    return ml.Job(mlEnvelope,mail);
                }
            }
            return false;
        }

    }
}


text:
namespace BigEgg.Tools.ConsoleExtension.Parameters.Logicals
{
    internal enum ProcessorType
    {
        ArgumentCheck = 0,
        TypeCheck = 1,
        Tokenize = 2,
        TokenCheck = 3,
        Version = 4,
        Help = 5,
        ExtractCommand = 6,
        CommandHelp = 7,
        TypeParse = 8
    }
}


text:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Object List Item - sap.m</title>

<script src="shared-config.js"></script>
<script src="../../../resources/sap-ui-core.js"
	id="sap-ui-bootstrap" data-sap-ui-libs="sap.m">
</script>

<script>

	jQuery.sap.require("sap.ui.core.IconPool");
	jQuery.sap.require("sap.m.ObjectAttribute");
	jQuery.sap.require("sap.m.ObjectStatus");

	var list = new sap.m.List("test_list", {
		headerText: "Object List Items"
	});

    var newMarkers = new sap.m.ObjectListItem({
        title: "New markers aggregation",
        number: "802",
        numberUnit: "Euro",
        numberState : sap.ui.core.ValueState.Success,
        attributes: [
            new sap.m.ObjectAttribute({text: "First Attribute."}),
            new sap.m.ObjectAttribute({text: "Second Attribute"})
        ],
        firstStatus: new sap.m.ObjectStatus({text: "Critical Status", state: "Error"}),
        markers: [
                     new sap.m.ObjectMarker({type: sap.m.ObjectMarkerType.Favorite}),
                     new sap.m.ObjectMarker({type: sap.m.ObjectMarkerType.Flagged}),
                     new sap.m.ObjectMarker({type: sap.m.ObjectMarkerType.Draft})
                 ]
    });
    list.addItem(newMarkers);

    var lockedItem = new sap.m.ObjectListItem({
        intro: "Optional Intro Text",
        title: "Sed ut perspiciatis, unde omnis iste natus",
        number: "802",
        numberUnit: "Euro",
        numberState : sap.ui.core.ValueState.Success,
        attributes: [
            new sap.m.ObjectAttribute({text: "First Attribute Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."}),
            new sap.m.ObjectAttribute({text: "Second Attribute"})
        ],
        firstStatus: new sap.m.ObjectStatus({text: "Critical Status", state: "Error"}),
        showMarkers: true,
        markFlagged: true,
        markFavorite: true,
        markLocked: true
    });
    list.addItem(lockedItem);

    var rtlTestItem = new sap.m.ObjectListItem({
        type: "Active",
        intro: "0882 13 14 15",
        icon: sap.ui.core.IconPool.getIconURI("inbox"),
        title: "0882 13 14 15",
        number: "0882 13 14 15",
        //numberUnit: "Euro",
        numberState : sap.ui.core.ValueState.Success,
        attributes: [ new sap.m.ObjectAttribute({text: "+359 04 05 06", textDirection: sap.ui.core.TextDirection.LTR })],
        firstStatus: new sap.m.ObjectStatus({text: "+359 04 05 06", state: "Success", textDirection: sap.ui.core.TextDirection.LTR }),
        secondStatus: new sap.m.ObjectStatus({title: "לִהְיוֹת לָכֶם לֵאלֹהִים",
            text: "+359 04 05 06", state: "Warning", textDirection: sap.ui.core.TextDirection.LTR }),
        showMarkers: true,
        markFlagged: true,
        markFavorite: true,
        titleTextDirection: sap.ui.core.TextDirection.LTR,
        introTextDirection: sap.ui.core.TextDirection.LTR,
        numberTextDirection: sap.ui.core.TextDirection.LTR
    });
    list.addItem(rtlTestItem);

	var listItemId = "worst_case";
	var worstCaseAttrs = new Array();
	worstCaseAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 1 attribute text 1", tooltip: "Attribute tip"}));
	worstCaseAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 2 attribute text 1"}));
	worstCaseAttrs.push(new sap.m.ObjectAttribute({text: "Seven_seven-seven-seven-seven-seven_sevens_even years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."}));

	var worstCase = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		icon: sap.ui.core.IconPool.getIconURI("inbox"),
		title: "Ñorst case item with all fields, large number, Ñagçyfox",
		number: "Ñ999999999",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Success,
		attributes: worstCaseAttrs,
		firstStatus: new sap.m.ObjectStatus({text: "Positive Ñagçyfox", state: "Success", tooltip: "Status tip"}),
		secondStatus: new sap.m.ObjectStatus({text: "Negative Ñagçyfox", state: "Error"}),
		showMarkers: true,
		markFlagged: true,
		markFavorite: true
	});
	list.addItem(worstCase);

	var longWordTitle = new sap.m.ObjectListItem({
		type: "Active",
		icon: sap.ui.core.IconPool.getIconURI("inbox"),
		title: "123456789012345678901234567890123456789012345678901234567890 This long word should be wrapped to another line",
		number: "Ñ999999999",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Success,
		attributes: [new sap.m.ObjectAttribute({text: "attribute text 1 attribute text 1", tooltip: "Attribute tip"})],
		firstStatus: new sap.m.ObjectStatus({text: "Positive Ñagçyfox", state: "Success", tooltip: "Status tip"}),
		showMarkers: true,
		markFlagged: true,
		markFavorite: true
	});
	list.addItem(longWordTitle);

	var longWordTitleNoNumber = new sap.m.ObjectListItem({
		type: "Active",
		icon: sap.ui.core.IconPool.getIconURI("inbox"),
		title: "123456789012345678901234567890123456789012345678901234567890 This long word should be wrapped to another line",
		attributes: [new sap.m.ObjectAttribute({text: "attribute text 1 attribute text 1", tooltip: "Attribute tip"})],
		firstStatus: new sap.m.ObjectStatus({text: "Positive Ñagçyfox", state: "Success", tooltip: "Status tip"}),
		showMarkers: true,
		markFlagged: true,
		markFavorite: true
	});
	list.addItem(longWordTitleNoNumber);

	var longWordTitleOnly = new sap.m.ObjectListItem({
		title: "123456789012345678901234567890123456789012345678901234567890 This long word should be wrapped to another line",
		attributes: [new sap.m.ObjectAttribute({text: "attribute text 1 attribute text 1", tooltip: "Attribute tip"})],
		firstStatus: new sap.m.ObjectStatus({text: "Positive Ñagçyfox", state: "Success", tooltip: "Status tip"}),
		showMarkers: true,
		markFlagged: true,
		markFavorite: true
	});
	list.addItem(longWordTitleOnly);

	var bestCase = new sap.m.ObjectListItem({
		type: "Active",
		title: "Best case item with minimal fields, medium number",
		number: "3.62449",
		numberState : sap.ui.core.ValueState.Success
	});
	list.addItem(bestCase);

	var withImgIcon = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		icon: "images/action.png",
		activeIcon: "images/action_pressed.png",
		title: "Using image instead of icon font",
		number: "103",
		numberUnit: "%",
		numberState : sap.ui.core.ValueState.Success
	});
	list.addItem(withImgIcon);

	var bestVariation1 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "Best case item with number unit, small number",
		number: "-900,000,000.01",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Error
	});
	list.addItem(bestVariation1);

	var bestVariation2 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "Best case item adding number unit",
		number: "3.6244",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Error
	});
	list.addItem(bestVariation2);

	var bestVariation3Attrs = new Array();
	bestVariation3Attrs.push(new sap.m.ObjectAttribute({text: "attribute text 1"}));
	bestVariation3Attrs.push(new sap.m.ObjectAttribute({text: "attribute text 2"}));
	bestVariation3Attrs.push(new sap.m.ObjectAttribute({text: "attribute text 3"}));
	var bestVariation3 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "Best case item adding attributes aggregation only",
		number: "3.6244",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Error,
		attributes: bestVariation3Attrs
	});
	list.addItem(bestVariation3);

	var bestVariation4 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "Best case item adding first and second status",
		number: "3.6244",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Success,
		firstStatus: new sap.m.ObjectStatus({text: "Status state warning", state: "Warning"}),
		secondStatus: new sap.m.ObjectStatus({text: "Status state none", state: "None"})
	});
	list.addItem(bestVariation4);

	var bestVariation5 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "Best case item adding second status only",
		number: "3.6244",
		numberUnit: "Euro",
		numberState : sap.ui.core.ValueState.Success,
		secondStatus: new sap.m.ObjectStatus({text: "Second status"})
	});
	list.addItem(bestVariation5);

	var moreThanThreeAttrs = new Array();
	moreThanThreeAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}));
	moreThanThreeAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 2"}));
	moreThanThreeAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 3"}));
	moreThanThreeAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 4"}));
	moreThanThreeAttrs.push(new sap.m.ObjectAttribute({text: "attribute text 5"}));

	function handlePress(oEvent) {
		if(!bestVariation6.getInfo()) {
			bestVariation6.setInfo("I am impressed.");
		} else {
			bestVariation6.setInfo(undefined);
		}
	}

	var bestVariation6 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "More than three attributes & press",
		number: "3.6244",
		numberUnit: "Euro",
		attributes: moreThanThreeAttrs,
		press: handlePress
	});
	list.addItem(bestVariation6);

	var bestVariation8 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "No attributes, second status only",
		number: "3.6244",
		numberUnit: "Euro",
		secondStatus: new sap.m.ObjectStatus({text: "Second status"})
	});
	list.addItem(bestVariation8);

	var bestVariation9 = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "No attributes, first status only",
		number: "3.6244",
		numberUnit: "Euro",
		firstStatus: new sap.m.ObjectStatus({text: "First status info", state: "Success"})
	});
	list.addItem(bestVariation9);

	var withFirstStatusIcon = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "First status using icon font",
		number: "3.62449",
		firstStatus: new sap.m.ObjectStatus({icon: sap.ui.core.IconPool.getIconURI("inbox")})
	});
	list.addItem(withFirstStatusIcon);

	var emptyAttributes = new Array();
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));

	var emptyAttributes = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "3 Attributes with empty string & no status",
		number: "9999999999",
		numberUnit: "Euro",
		attributes: emptyAttributes
	});
	list.addItem(emptyAttributes);

	emptyAttributes = new Array();
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));
	emptyAttributes.push(new sap.m.ObjectAttribute({text: ""}));

	var emptyAttributesFirstStatus = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "3 Attributes with empty string with first status",
		number: "9999999999",
		numberUnit: "Euro",
		attributes: emptyAttributes,
		firstStatus: new sap.m.ObjectStatus({text: "First status info"})
	});
	list.addItem(emptyAttributesFirstStatus);

	oneAttributeWithRestEmpty = new Array();
	oneAttributeWithRestEmpty.push(new sap.m.ObjectAttribute({text: "First attrib val"}));
	oneAttributeWithRestEmpty.push(new sap.m.ObjectAttribute({text: ""}));
	oneAttributeWithRestEmpty.push(new sap.m.ObjectAttribute({text: ""}));

	var firstAttributeFirstStatus = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "1 Attribute and 2 empty, first status",
		number: "9999999999",
		numberUnit: "Euro",
		attributes: oneAttributeWithRestEmpty,
		firstStatus: new sap.m.ObjectStatus({text: "First status info"})
	});
	list.addItem(firstAttributeFirstStatus);

	var withFirstStatusImage = new sap.m.ObjectListItem({
		type: "Active",
		intro: "On behalf of John Smith",
		title: "First status using image",
		number: "3.62449",
		firstStatus: new sap.m.ObjectStatus({icon: "images/favorite_24.png"})
	});
	list.addItem(withFirstStatusImage);

	var allMarkersShown = new sap.m.ObjectListItem({

		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "All possible markers shown initially, no attributes",
		number: "12",
		numberUnit: "Milo",
		showMarkers: true,
		markFlagged: true,
		markFavorite: true
	});
	list.addItem(allMarkersShown);

	var flagMarkerOnly = new sap.m.ObjectListItem({

		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "Flagged only",
		number: "12",
		numberUnit: "Milo",
		showMarkers: true,
		markFlagged: true
	});
	list.addItem(flagMarkerOnly);

	var favoriteMarkerOnly = new sap.m.ObjectListItem({

		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "Favorite only",
		number: "12",
		numberUnit: "Milo",
		showMarkers: true,
		markFavorite: true
	});
	list.addItem(favoriteMarkerOnly);

	var markersAndStatuses = new sap.m.ObjectListItem({

		type: "Active",
		intro: "On behalf of John Smith, Ñagçyfox",
		title: "Markers and statuses, no attributes",
		number: "12",
		numberUnit: "Milo",
		firstStatus: new sap.m.ObjectStatus({text: "First status info"}),
		secondStatus: new sap.m.ObjectStatus({text: "Second status info"}),
		showMarkers: true
	});
	list.addItem(markersAndStatuses);

	var app = new sap.m.App();
	var page = new sap.m.Page("testPage", {title: "Object List Item Test"});
	app.setInitialPage(page.getId());
	page.setEnableScrolling(true);
	app.addPage(page);
	page.addContent(list);

	page.addContent(new sap.m.CheckBox({
		text: "Show Markers",
		selected: markersAndStatuses.getShowMarkers(),
		select: function() {
			markersAndStatuses.setShowMarkers(this.getSelected());
		}
	}));

	page.addContent(new sap.m.Button({
		id: "flag-button",
		text: "Flag",
		press: function() {
			markersAndStatuses.setMarkFlagged(!markersAndStatuses.getMarkFlagged());
		}
	}));
	page.addContent(new sap.m.Button({
		id: "favorite-button",
		text: "Favorite",
		press: function() {
			markersAndStatuses.setMarkFavorite(!markersAndStatuses.getMarkFavorite());
		}
	}));
    page.addContent(new sap.m.Button({
        id: "locked-button",
        text: "Locked",
        press: function() {
            markersAndStatuses.setMarkLocked(!markersAndStatuses.getMarkLocked());
        }
    }));
	app.placeAt('body');

</script>

</head>
<body id="body" class="sapUiBody">
</body>
</html>


text:
Selected price options:

<?php /* @var $OptionGroup mPriceOptionGroup */
if (!isset($setOptionGroups)) {
	$setOptionGroups = $c->getItemPriceOptions($prod->ProductId);
}
if (!empty($prod->PriceOptions) && !empty($setOptionGroups)) {
foreach ($prod->PriceOptions as $iKey => $OptionGroup) {
	$GroupName = null;
	$Options = array();

	$groupKey = str_replace(' ', '_', $OptionGroup->Name);
	if (isset($setOptionGroups[$groupKey])) {
		foreach ($OptionGroup->Options as $iOptionKey => $Option) {
			$setOptions = explode(',', $setOptionGroups [$groupKey]);
			$optionKey = $Option->Value;
			if (in_array($optionKey, $setOptions)) {
				$GroupName = $OptionGroup->Name;
				$Options[] = $Option->Name;
			}
		}
	}
	if  (!is_null($GroupName)) {
?>

<?php echo $GroupName ?>:  <?php echo implode (', ', $Options) ?>

<?php }
}
} else {
?>

 none

<?php
}
?>


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * Loader Class
 * 扩展的核心类
 * @author xiaobin zxbin.1990@gmail.com
 * @created 2016/7/2
 *
 * Loads views and files
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @author		ExpressionEngine Dev Team
 * @category	Loader
 * @link		http://codeigniter.com/user_guide/libraries/loader.html
 */
class MY_Loader extends CI_Loader
{
    function __construct()
    {
        parent::__construct();
    }

	/**
	 * Model Loader
	 *
	 * Loads and instantiates models.
	 *
	 * @param	string	$model		Model name
	 * @param    para string  表名  new add
	 * @param	string	$name		An optional object name to assign to
	 * @param	bool	$db_conn	An optional database connection configuration to initialize
	 * @return	object
	 */
	public function model($model, $name = '', $para = '', $db_conn = FALSE)
	{
		if (empty($model))
		{
			return $this;
		}
		elseif (is_array($model))
		{
			foreach ($model as $key => $value)
			{
				is_int($key) ? $this->model($value, '', $db_conn) : $this->model($key, $value, $db_conn);
			}

			return $this;
		}

		$path = '';

		// Is the model in a sub-folder? If so, parse out the filename and path.
		if (($last_slash = strrpos($model, '/')) !== FALSE)
		{
			// The path is in front of the last slash
			$path = substr($model, 0, ++$last_slash);

			// And the model name behind it
			$model = substr($model, $last_slash);
		}

		if (empty($name))
		{
			$name = $model;
		}

		if (in_array($name, $this->_ci_models, TRUE))
		{
			return $this;
		}

		$CI =& get_instance();
		if (isset($CI->$name))
		{
			throw new RuntimeException('The model name you are loading is the name of a resource that is already being used: '.$name);
		}

		if ($db_conn !== FALSE && ! class_exists('CI_DB', FALSE))
		{
			if ($db_conn === TRUE)
			{
				$db_conn = '';
			}

			$this->database($db_conn, FALSE, TRUE);
		}

		// Note: All of the code under this condition used to be just:
		//
		//       load_class('Model', 'core');
		//
		//       However, load_class() instantiates classes
		//       to cache them for later use and that prevents
		//       MY_Model from being an abstract class and is
		//       sub-optimal otherwise anyway.
		if ( ! class_exists('CI_Model', FALSE))
		{
			$app_path = APPPATH.'core'.DIRECTORY_SEPARATOR;
			if (file_exists($app_path.'Model.php'))
			{
				require_once($app_path.'Model.php');
				if ( ! class_exists('CI_Model', FALSE))
				{
					throw new RuntimeException($app_path."Model.php exists, but doesn't declare class CI_Model");
				}
			}
			elseif ( ! class_exists('CI_Model', FALSE))
			{
				require_once(BASEPATH.'core'.DIRECTORY_SEPARATOR.'Model.php');
			}

			$class = config_item('subclass_prefix').'Model';
			if (file_exists($app_path.$class.'.php'))
			{
				require_once($app_path.$class.'.php');
				if ( ! class_exists($class, FALSE))
				{
					throw new RuntimeException($app_path.$class.".php exists, but doesn't declare class ".$class);
				}
			}
		}

		$model = ucfirst($model);
		if ( ! class_exists($model, FALSE))
		{
			foreach ($this->_ci_model_paths as $mod_path)
			{
				if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
				{
					continue;
				}

				require_once($mod_path.'models/'.$path.$model.'.php');
				if ( ! class_exists($model, FALSE))
				{
					throw new RuntimeException($mod_path."models/".$path.$model.".php exists, but doesn't declare class ".$model);
				}

				break;
			}

			if ( ! class_exists($model, FALSE))
			{
				throw new RuntimeException('Unable to locate the model you have specified: '.$model);
			}
		}
		elseif ( ! is_subclass_of($model, 'CI_Model'))
		{
			throw new RuntimeException("Class ".$model." already exists and doesn't extend CI_Model");
		}

		$this->_ci_models[] = $name;
        // /new add  xiaobin  s
        if($para == '')
        {
           $CI->$name = new $model();
        }
        else
        {
		   $CI->$name = new $model($para);
        }
        //  end
		return $this;
	}
}


text:
#include "common/rect.h"

#include <CUnit/CUnit.h>

/**
 * Test which verifies that guac_common_rect_extend() expands the given
 * rectangle as necessary to contain at least the given bounds.
 */
void test_rect__extend() {

    guac_common_rect max;
    guac_common_rect rect;

    guac_common_rect_init(&rect, 10, 10, 90, 90);
    guac_common_rect_init(&max, 0, 0, 100, 100);
    guac_common_rect_extend(&rect, &max);
    CU_ASSERT_EQUAL(0, rect.x);
    CU_ASSERT_EQUAL(0, rect.y);
    CU_ASSERT_EQUAL(100, rect.width);
    CU_ASSERT_EQUAL(100, rect.height);

}


text:
/// <reference path="../_definitions.ts" />

/**
* Phaser - Display - DynamicTexture
*
* A DynamicTexture can be thought of as a mini canvas into which you can draw anything.
* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so
* based on the contents of the texture at the time. This allows you to create powerful effects
* once and have them replicated across as many game objects as you like.
*/

module Phaser.Display {

    export class DynamicTexture {

        /**
         * DynamicTexture constructor
         * Create a new DynamicTexture.
         *
         * @param game {Phaser.Game} Current game instance.
         * @param width {number} Init width of this texture.
         * @param height {number} Init height of this texture.
         */
        constructor(game: Game, width: number, height: number) {

            this.game = game;
            this.type = Phaser.Types.DYNAMICTEXTURE;

            this.canvas = <HTMLCanvasElement> document.createElement('canvas');
            this.canvas.width = width;
            this.canvas.height = height;
            this.context = this.canvas.getContext('2d');

            this.css3 = new Phaser.Display.CSS3Filters(this.canvas);

            this.bounds = new Rectangle(0, 0, width, height);

        }

        /**
         * Reference to game.
         */
        public game: Phaser.Game;

        /**
         * The type of game object.
         */
        public type: number;

        private _sx: number = 0;
        private _sy: number = 0;
        private _sw: number = 0;
        private _sh: number = 0;
        private _dx: number = 0;
        private _dy: number = 0;
        private _dw: number = 0;
        private _dh: number = 0;

        //  Input / Output nodes?

        /**
         * Controls the CSS3 Filters applied to the textures canvas object.
         * Only really useful if you attach this canvas to the DOM.
         * @type {Phaser.Components.CSS3Filters}
         */
        public css3: Phaser.Display.CSS3Filters;

        /**
         * Bound of this texture with width and height info.
         * @type {Rectangle}
         */
        public bounds: Phaser.Rectangle;

        /**
         * This class is actually a wrapper of canvas.
         * @type {HTMLCanvasElement}
         */
        public canvas: HTMLCanvasElement;

        /**
         * Canvas context of this object.
         * @type {CanvasRenderingContext2D}
         */
        public context: CanvasRenderingContext2D;

        /**
         * You can set a globalCompositeOperation that will be applied before the render method is called on this Sprite.
         * This is useful if you wish to apply an effect like 'lighten'.
         * If this value is set it will call a canvas context save and restore before and after the render pass, so use it sparingly.
         * Set to null to disable.
         */
        public globalCompositeOperation: string = null;

        /**
         * Get a color of a specific pixel.
         * @param x {number} X position of the pixel in this texture.
         * @param y {number} Y position of the pixel in this texture.
         * @return {number} A native color value integer (format: 0xRRGGBB)
         */
        public getPixel(x: number, y: number): number {

            //r = imageData.data[0];
            //g = imageData.data[1];
            //b = imageData.data[2];
            //a = imageData.data[3];
            var imageData = this.context.getImageData(x, y, 1, 1);

            return Phaser.ColorUtils.getColor(imageData.data[0], imageData.data[1], imageData.data[2]);

        }

        /**
         * Get a color of a specific pixel (including alpha value).
         * @param x {number} X position of the pixel in this texture.
         * @param y {number} Y position of the pixel in this texture.
         * @return  A native color value integer (format: 0xAARRGGBB)
         */
        public getPixel32(x: number, y: number) {

            var imageData = this.context.getImageData(x, y, 1, 1);

            return Phaser.ColorUtils.getColor32(imageData.data[3], imageData.data[0], imageData.data[1], imageData.data[2]);

        }

        /**
         * Get pixels in array in a specific Rectangle.
         * @param rect {Rectangle} The specific Rectangle.
         * @returns {array} CanvasPixelArray.
         */
        public getPixels(rect: Phaser.Rectangle) {

            return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);

        }

        /**
         * Set color of a specific pixel.
         * @param x {number} X position of the target pixel.
         * @param y {number} Y position of the target pixel.
         * @param color {number} Native integer with color value. (format: 0xRRGGBB)
         */
        public setPixel(x: number, y: number, color: string) {

            this.context.fillStyle = color;
            this.context.fillRect(x, y, 1, 1);

        }

        /**
         * Set color (with alpha) of a specific pixel.
         * @param x {number} X position of the target pixel.
         * @param y {number} Y position of the target pixel.
         * @param color {number} Native integer with color value. (format: 0xAARRGGBB)
         */
        public setPixel32(x: number, y: number, color: number) {

            this.context.fillStyle = color;
            this.context.fillRect(x, y, 1, 1);

        }

        /**
         * Set image data to a specific Rectangle.
         * @param rect {Rectangle} Target Rectangle.
         * @param input {object} Source image data.
         */
        public setPixels(rect: Phaser.Rectangle, input) {

            this.context.putImageData(input, rect.x, rect.y);

        }

        /**
         * Fill a given Rectangle with specific color.
         * @param rect {Rectangle} Target Rectangle you want to fill.
         * @param color {number} A native number with color value. (format: 0xRRGGBB)
         */
        public fillRect(rect: Phaser.Rectangle, color: number) {

            this.context.fillStyle = color;
            this.context.fillRect(rect.x, rect.y, rect.width, rect.height);

        }

        /**
         *
         */
        public pasteImage(key: string, frame: number = -1, destX: number = 0, destY: number = 0, destWidth: number = null, destHeight: number = null) {

            var texture = null;
            var frameData;

            this._sx = 0;
            this._sy = 0;
            this._dx = destX;
            this._dy = destY;

            //  TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot
            if (frame > -1)
            {
                //if (this.game.cache.isSpriteSheet(key))
                //{
                //    texture = this.game.cache.getImage(key);
                //this.animations.loadFrameData(this.game.cache.getFrameData(key));
                //}
            }
            else
            {
                texture = this.game.cache.getImage(key);
                this._sw = texture.width;
                this._sh = texture.height;
                this._dw = texture.width;
                this._dh = texture.height;
            }

            if (destWidth !== null)
            {
                this._dw = destWidth;
            }

            if (destHeight !== null)
            {
                this._dh = destHeight;
            }

            if (texture != null)
            {
                this.context.drawImage(
                    texture,        //  Source Image
                    this._sx,       //  Source X (location within the source image)
                    this._sy,       //  Source Y
                    this._sw,       //  Source Width
                    this._sh,       //  Source Height
                    this._dx,       //  Destination X (where on the canvas it'll be drawn)
                    this._dy,       //  Destination Y
                    this._dw,       //  Destination Width (always same as Source Width unless scaled)
                    this._dh        //  Destination Height (always same as Source Height unless scaled)
                );
            }

        }

        //  TODO - Add in support for: alphaBitmapData: BitmapData = null, alphaPoint: Point = null, mergeAlpha: bool = false
        /**
         * Copy pixel from another DynamicTexture to this texture.
         * @param sourceTexture {DynamicTexture} Source texture object.
         * @param sourceRect {Rectangle} The specific region Rectangle to be copied to this in the source.
         * @param destPoint {Point} Top-left point the target image data will be paste at.
         */
        public copyPixels(sourceTexture: Phaser.Display.DynamicTexture, sourceRect: Phaser.Rectangle, destPoint: Phaser.Point) {

            //  Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call
            if (Phaser.RectangleUtils.equals(sourceRect, this.bounds) == true)
            {
                this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y);
            }
            else
            {
                this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y);
            }

        }

        public add(sprite: Phaser.Sprite) {

            sprite.texture.canvas = this.canvas;
            sprite.texture.context = this.context;

        }

        /**
         * Given an array of Sprites it will update each of them so that their canvas/contexts reference this DynamicTexture
         * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites
         */
        public assignCanvasToGameObjects(objects) {

            for (var i = 0; i < objects.length; i++)
            {
                if (objects[i].texture)
                {
                    objects[i].texture.canvas = this.canvas;
                    objects[i].texture.context = this.context;
                }
            }

        }

        /**
         * Clear the whole canvas.
         */
        public clear() {

            this.context.clearRect(0, 0, this.bounds.width, this.bounds.height);

        }

        /**
        * Renders this DynamicTexture to the Stage at the given x/y coordinates
        *
        * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world)
        * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world)
        */
        public render(x: number = 0, y: number = 0) {

            if (this.globalCompositeOperation)
            {
                this.game.stage.context.save();
                this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation;
            }

            this.game.stage.context.drawImage(this.canvas, x, y);

            if (this.globalCompositeOperation)
            {
                this.game.stage.context.restore();
            }

        }

        public get width(): number {
            return this.bounds.width;
        }

        public get height(): number {
            return this.bounds.height;
        }

    }

}


text:
module FmCli
  class SetCurrentAccountingPeriodInteraction < FmCli::Interaction

    def run identifier
      begin
        accounting_period = ::SetCurrentAccountingPeriod.new(identifier).run
        io.print_success "Successfully changed current accounting period"
        io.print_blank_line
        io.print_accounting_period accounting_period
      rescue RecordNotFoundError
        io.print_failure "Couldn't find specified accounting period"
      end
    end
  end
end


text:
/*global HackerNews:true*/
HackerNews = {};


text:
package org.androidpn.client;

import com.example.share.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Activity for displaying the notification details view.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class NotificationDetailsActivity extends Activity {

    private static final String LOGTAG = LogUtil
            .makeLogTag(NotificationDetailsActivity.class);

    private String callbackActivityPackageName;

    private String callbackActivityClassName;

    private View mArticleView;
	private ImageButton mBackImageButton;
	private TextView mArticleTitle;
	private TextView mArticleUserName;
	private TextView mArticleTime;
	private TextView mArticleContent;

	private String notificationId;
	private String notificationApiKey;
	private String notificationTitle;
	private String notificationMessage;
	private String notificationUri;

    public NotificationDetailsActivity() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sharedPrefs = this.getSharedPreferences(
                Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
        callbackActivityPackageName = sharedPrefs.getString(
                Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
        callbackActivityClassName = sharedPrefs.getString(
                Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");

        Intent intent = getIntent();
        notificationId = intent.getStringExtra(Constants.NOTIFICATION_ID);
        notificationApiKey = intent.getStringExtra(Constants.NOTIFICATION_API_KEY);
        notificationTitle = intent.getStringExtra(Constants.NOTIFICATION_TITLE);
        notificationMessage = intent.getStringExtra(Constants.NOTIFICATION_MESSAGE);
        notificationUri = intent.getStringExtra(Constants.NOTIFICATION_URI);

        Log.d(LOGTAG, "notificationId=" + notificationId);
        Log.d(LOGTAG, "notificationApiKey=" + notificationApiKey);
        Log.d(LOGTAG, "notificationTitle=" + notificationTitle);
        Log.d(LOGTAG, "notificationMessage=" + notificationMessage);
        Log.d(LOGTAG, "notificationUri=" + notificationUri);

        //        Display display = getWindowManager().getDefaultDisplay();
        //        View rootView;
        //        if (display.getWidth() > display.getHeight()) {
        //            rootView = null;
        //        } else {
        //            rootView = null;
        //        }

//        View rootView = createView(notificationTitle, notificationMessage,
//                notificationUri);
        View rootView = initViews();
        setContentView(rootView);
    }

    private View initViews() {
		// TODO Auto-generated method stub
    	mArticleView = LayoutInflater.from(this).inflate(
				R.layout.share_detail_article, null);
    	mArticleView.setPadding(0, 0, 0, 20);
		mArticleTitle = (TextView) mArticleView
				.findViewById(R.id.share_detail_article_title);
		mArticleUserName = (TextView) mArticleView
				.findViewById(R.id.share_detail_article_user_name);
		mArticleTime = (TextView) mArticleView
				.findViewById(R.id.share_detail_article_time);
		mArticleContent = (TextView) mArticleView
				.findViewById(R.id.share_detail_article_content);
		initEvents(mArticleView);
		return mArticleView;
	}

	private void initEvents(View view) {
		// TODO Auto-generated method stub
		mArticleTitle.setText(notificationTitle);
		mArticleUserName.setText("系统");
		mArticleTime.setText("刚刚");
		mArticleContent.setText(notificationMessage);
	}

//	private View createView(final String title, final String message,
//            final String uri) {
//
//        LinearLayout linearLayout = new LinearLayout(this);
//        linearLayout.setBackgroundColor(0xffeeeeee);
//        linearLayout.setOrientation(LinearLayout.VERTICAL);
//        linearLayout.setPadding(5, 5, 5, 5);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.FILL_PARENT,
//                LinearLayout.LayoutParams.FILL_PARENT);
//        linearLayout.setLayoutParams(layoutParams);
//
//        TextView textTitle = new TextView(this);
//        textTitle.setText(title);
//        textTitle.setTextSize(18);
//        // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
//        textTitle.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
//        textTitle.setTextColor(0xff000000);
//        textTitle.setGravity(Gravity.CENTER);
//
//        layoutParams = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.FILL_PARENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        layoutParams.setMargins(30, 30, 30, 0);
//        textTitle.setLayoutParams(layoutParams);
//        linearLayout.addView(textTitle);
//
//        TextView textDetails = new TextView(this);
//        textDetails.setText(message);
//        textDetails.setTextSize(14);
//        // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
//        textDetails.setTextColor(0xff333333);
//        textDetails.setGravity(Gravity.CENTER);
//
//        layoutParams = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.FILL_PARENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        layoutParams.setMargins(30, 10, 30, 20);
//        textDetails.setLayoutParams(layoutParams);
//        linearLayout.addView(textDetails);
//
//        Button okButton = new Button(this);
//        okButton.setText("Ok");
//        okButton.setWidth(100);
//
//        okButton.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View view) {
//                Intent intent;
//                if (uri != null
//                        && uri.length() > 0
//                        && (uri.startsWith("http:") || uri.startsWith("https:")
//                                || uri.startsWith("tel:") || uri
//                                .startsWith("geo:"))) {
//                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
//                } else {
//                    intent = new Intent().setClassName(
//                            callbackActivityPackageName,
//                            callbackActivityClassName);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                }
//
//                NotificationDetailsActivity.this.startActivity(intent);
//                NotificationDetailsActivity.this.finish();
//            }
//        });
//
//        LinearLayout innerLayout = new LinearLayout(this);
//        innerLayout.setGravity(Gravity.CENTER);
//        innerLayout.addView(okButton);
//
//        linearLayout.addView(innerLayout);
//
//        return linearLayout;
//    }

    //    protected void onPause() {
    //        super.onPause();
    //        finish();
    //    }
    //
    //    protected void onStop() {
    //        super.onStop();
    //        finish();
    //    }
    //
    //    protected void onSaveInstanceState(Bundle outState) {
    //        super.onSaveInstanceState(outState);
    //    }
    //
    //    protected void onNewIntent(Intent intent) {
    //        setIntent(intent);
    //    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/circle_item"
        android:drawable="@android:color/transparent" /> <!-- actual drawable set in code -->
</layer-list>


text:
module("wysihtml.dom.unwrap", {
  setup: function() {
    this.inner = "test
tes2
";
    this.container = document.createElement("div");
    this.containerInner = document.createElement("div");
    this.containerInner.innerHTML = this.inner;
    this.container.appendChild(this.containerInner);
  }
});

test("Basic test", function() {
  wysihtml.dom.unwrap(this.containerInner);
  equal(this.container.innerHTML, this.inner, "Unwrapping element works splendid.");
});


text:
void GeoJson::extractPoint(const rapidjson::Value& _in, Point& _out, const MapTile& _tile) {

    glm::dvec2 tmp = _tile.getProjection()->LonLatToMeters(glm::dvec2(_in[0].GetDouble(), _in[1].GetDouble()));
    _out.x = (tmp.x - _tile.getOrigin().x) * _tile.getInverseScale();
    _out.y = (tmp.y - _tile.getOrigin().y) * _tile.getInverseScale();

}

void GeoJson::extractLine(const rapidjson::Value& _in, Line& _out, const MapTile& _tile) {

    for (auto itr = _in.Begin(); itr != _in.End(); ++itr) {
        _out.emplace_back();
        extractPoint(*itr, _out.back(), _tile);
    }

}

void GeoJson::extractPoly(const rapidjson::Value& _in, Polygon& _out, const MapTile& _tile) {

    for (auto itr = _in.Begin(); itr != _in.End(); ++itr) {
        _out.emplace_back();
        extractLine(*itr, _out.back(), _tile);
    }

}

void GeoJson::extractFeature(const rapidjson::Value& _in, Feature& _out, const MapTile& _tile) {

    // Copy properties into tile data

    const rapidjson::Value& properties = _in["properties"];

    for (auto itr = properties.MemberBegin(); itr != properties.MemberEnd(); ++itr) {

        const auto& member = itr->name.GetString();

        const rapidjson::Value& prop = properties[member];

        // height and minheight need to be handled separately so that their dimensions are normalized
        if (strcmp(member, "height") == 0) {
            _out.props.numericProps[member] = prop.GetDouble() * _tile.getInverseScale();
            continue;
        }

        if (strcmp(member, "min_height") == 0) {
            _out.props.numericProps[member] = prop.GetDouble() * _tile.getInverseScale();
            continue;
        }

        if (prop.IsNumber()) {
            _out.props.numericProps[member] = prop.GetDouble();
        } else if (prop.IsString()) {
            _out.props.stringProps[member] = prop.GetString();
        }

    }

    // Copy geometry into tile data

    const rapidjson::Value& geometry = _in["geometry"];
    const rapidjson::Value& coords = geometry["coordinates"];
    const std::string& geometryType = geometry["type"].GetString();

    if (geometryType.compare("Point") == 0) {

        _out.geometryType = GeometryType::POINTS;
        _out.points.emplace_back();
        extractPoint(coords, _out.points.back(), _tile);

    } else if (geometryType.compare("MultiPoint") == 0) {

        _out.geometryType= GeometryType::POINTS;
        for (auto pointCoords = coords.Begin(); pointCoords != coords.End(); ++pointCoords) {
            _out.points.emplace_back();
            extractPoint(*pointCoords, _out.points.back(), _tile);
        }

    } else if (geometryType.compare("LineString") == 0) {
        _out.geometryType = GeometryType::LINES;
        _out.lines.emplace_back();
        extractLine(coords, _out.lines.back(), _tile);

    } else if (geometryType.compare("MultiLineString") == 0) {
        _out.geometryType = GeometryType::LINES;
        for (auto lineCoords = coords.Begin(); lineCoords != coords.End(); ++lineCoords) {
            _out.lines.emplace_back();
            extractLine(*lineCoords, _out.lines.back(), _tile);
        }

    } else if (geometryType.compare("Polygon") == 0) {

        _out.geometryType = GeometryType::POLYGONS;
        _out.polygons.emplace_back();
        extractPoly(coords, _out.polygons.back(), _tile);

    } else if (geometryType.compare("MultiPolygon") == 0) {

        _out.geometryType = GeometryType::POLYGONS;
        for (auto polyCoords = coords.Begin(); polyCoords != coords.End(); ++polyCoords) {
            _out.polygons.emplace_back();
            extractPoly(*polyCoords, _out.polygons.back(), _tile);
        }

    }

}

void GeoJson::extractLayer(const rapidjson::Value& _in, Layer& _out, const MapTile& _tile) {

    const auto& featureIter = _in.FindMember("features");

    if (featureIter == _in.MemberEnd()) {
        logMsg("ERROR: GeoJSON missing 'features' member\n");
        return;
    }

    const auto& features = featureIter->value;
    for (auto featureJson = features.Begin(); featureJson != features.End(); ++featureJson) {
        _out.features.emplace_back();
        extractFeature(*featureJson, _out.features.back(), _tile);
    }

}