text:
package com.github.fabito.gaeskeletons.infrastructure.web;

import com.google.api.server.spi.SystemServiceServlet;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class DaggerSystemServiceServlet<C> extends SystemServiceServlet {

    private static final Logger logger = Logger.getLogger(DaggerSystemServiceServlet.class.getName());

    private Class<C> clazz;
    private Map<Class, Method> cache;

    public DaggerSystemServiceServlet(Class<C> clazz) {
        super();
        this.clazz = clazz;
        this.cache = buildCache();
    }

    @Override
    protected <T> T createService(Class<T> serviceClass) {
        final T service = super.createService(serviceClass);
        try {
            inject(app(), service);
        } catch (InvocationTargetException | IllegalAccessException e) {
            logger.log(Level.SEVERE, "Error resolving dependencies", e);
            throw new RuntimeException(String.format("Cannot invoke method inject for type %s", serviceClass.getName()));
        }
        return service;
    }

    protected C app() {
        return clazz.cast(this.getServletContext().getAttribute("FooApp"));
    }

    protected Map<Class, Method> buildCache() {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Map<Class, Method> cache = Maps.newHashMap();
        for (Method m : clazz.getDeclaredMethods()) {
            Class[] types = m.getParameterTypes();
            if ("inject".equals(m.getName()) && types.length == 1) {
                cache.put(types[0], m);
            }
        }
        logger.log(Level.FINE, "Time to build injector cache: {0}", stopwatch);
        return cache;
    }

    // Use for injecting targets of any type.
    private void inject(C component, Object target) throws InvocationTargetException, IllegalAccessException {
        Method m = cache.get(target.getClass());
        if (m != null) {
            m.invoke(component, target);
        }
    }
}


text:
<?php
namespace Procure\Infrastructure\Persistence\Reporting\Filter;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class PrGrReportSqlFilter extends AbstractProcureAppSqlFilter
{

    public $vendorId;

    public $warehouseId;

    public $isActive;

    public $isRowActive;

    public $fromDate;

    public $toDate;

    public $docStatus;

    public function __toString()
    {
        $f = ("PrGrReportFilter_%s_%s_%s_%s_%s_%s_%s_%s");
        $t = \sprintf($f, $this->getCompanyId(), $this->getVendorId(), $this->getIsActive(), $this->getIsRowActive(), $this->getDocStatus(), $this->getFromDate(), $this->getToDate(), $this->getWarehouseId());
        return $t;
    }

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

    /**
     *
     * @param mixed $vendorId
     */
    public function setVendorId($vendorId)
    {
        $this->vendorId = $vendorId;
    }

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

    /**
     *
     * @param mixed $isActive
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
    }

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

    /**
     *
     * @param mixed $fromDate
     */
    public function setFromDate($fromDate)
    {
        $this->fromDate = $fromDate;
    }

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

    /**
     *
     * @param mixed $toDate
     */
    public function setToDate($toDate)
    {
        $this->toDate = $toDate;
    }

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

    /**
     *
     * @param mixed $docStatus
     */
    public function setDocStatus($docStatus)
    {
        $this->docStatus = $docStatus;
    }

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

    /**
     *
     * @param mixed $isRowActive
     */
    public function setIsRowActive($isRowActive)
    {
        $this->isRowActive = $isRowActive;
    }

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

    /**
     *
     * @param mixed $warehouseId
     */
    public function setWarehouseId($warehouseId)
    {
        $this->warehouseId = $warehouseId;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var searchData=
[
  ['kamishibaiapplication_0',['KamishibaiApplication',['../class_kamishibai_application.html',1,'']]],
  ['kamishibaiapplicationbuilder_1',['KamishibaiApplicationBuilder',['../class_kamishibai_application_builder.html',1,'']]]
];


text:
<?php
/**
 * This file is part of the vardius/user-bundle package.
 *
 * Created by Rafał Lorenz <vardius@gmail.com>.
 */

namespace Vardius\Bundle\UserBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Vardius\Bundle\UserBundle\Entity\User;

/**
 * RegisterEvent
 *
 * @author Rafał Lorenz <vardius@gmail.com>
 */
class RegisterEvent extends Event
{
    /** @var User */
    protected $user;

    /**
     * @param User $user
     */
    function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * @return User
     */
    public function getUser()
    {
        return $this->user;
    }

}


text:
package migrations_test

import (
	"crypto/rand"
	"database/sql"
	"fmt"
	"strings"
	"time"

	"code.cloudfoundry.org/bbs/db/sqldb/helpers"
	"code.cloudfoundry.org/bbs/encryption"
	"code.cloudfoundry.org/bbs/migration"
	"code.cloudfoundry.org/bbs/test_helpers"
	"code.cloudfoundry.org/bbs/test_helpers/sqlrunner"
	"code.cloudfoundry.org/clock/fakeclock"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"

	_ "github.com/go-sql-driver/mysql"

	"testing"
)

var (
	flavor string

	rawSQLDB   *sql.DB
	sqlProcess ifrit.Process
	sqlRunner  sqlrunner.SQLRunner

	cryptor   encryption.Cryptor
	fakeClock *fakeclock.FakeClock
	logger    *lagertest.TestLogger
)

func TestMigrations(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Migrations Suite")
}

var _ = BeforeSuite(func() {
	logger = lagertest.NewTestLogger("test")

	dbName := fmt.Sprintf("diego_%d", GinkgoParallelNode())
	sqlRunner = test_helpers.NewSQLRunner(dbName)
	sqlProcess = ginkgomon.Invoke(sqlRunner)

	// mysql must be set up on localhost as described in the CONTRIBUTING.md doc
	// in diego-release.
	var err error
	rawSQLDB, err = helpers.Connect(logger, sqlRunner.DriverName(), sqlRunner.ConnectionString(), "", false)
	Expect(err).NotTo(HaveOccurred())
	Expect(rawSQLDB.Ping()).NotTo(HaveOccurred())

	flavor = sqlRunner.DriverName()

	encryptionKey, err := encryption.NewKey("label", "passphrase")
	Expect(err).NotTo(HaveOccurred())
	keyManager, err := encryption.NewKeyManager(encryptionKey, nil)
	Expect(err).NotTo(HaveOccurred())
	cryptor = encryption.NewCryptor(keyManager, rand.Reader)

	fakeClock = fakeclock.NewFakeClock(time.Now())
})

var _ = AfterSuite(func() {
	Expect(rawSQLDB.Close()).NotTo(HaveOccurred())
	ginkgomon.Kill(sqlProcess, 5*time.Second)
})

var _ = BeforeEach(func() {
	sqlRunner.Reset()
})

func listTableNames(db *sql.DB) []string {
	var rows *sql.Rows
	var err error
	switch flavor {
	case "mysql":
		rows, err = db.Query("SHOW TABLES")
	case "postgres":
		rows, err = db.Query("SELECT tablename FROM pg_catalog.pg_tables;")
	default:
		Expect(flavor).To(Equal("not supported"))
	}
	Expect(err).NotTo(HaveOccurred())
	defer rows.Close()

	var tableNames []string
	for rows.Next() {
		var name string
		Expect(rows.Scan(&name)).To(Succeed())
		if strings.HasPrefix(name, "pg_") || strings.HasPrefix(name, "sql_") {
			continue
		}
		tableNames = append(tableNames, name)
	}
	Expect(rows.Err()).To(Succeed())
	return tableNames
}

func getTableSchema(db *sql.DB, tableName string) []*sql.ColumnType {
	rows, err := db.Query("SELECT * FROM " + tableName)
	Expect(err).NotTo(HaveOccurred())
	columnTypes, err := rows.ColumnTypes()
	Expect(err).NotTo(HaveOccurred())
	rows.Close()
	return columnTypes
}

func getAllSchemas(db *sql.DB) ([]string, map[string][]*sql.ColumnType) {
	tableNames := listTableNames(db)
	allSchemas := make(map[string][]*sql.ColumnType)
	for _, table := range tableNames {
		allSchemas[table] = getTableSchema(db, table)
	}
	return tableNames, allSchemas
}

func dumpTableData(db *sql.DB, name string) [][][]byte {
	rows, err := db.Query("SELECT * FROM " + name)
	Expect(err).NotTo(HaveOccurred())
	defer rows.Close()

	cols, err := rows.Columns()
	Expect(err).NotTo(HaveOccurred())

	var all [][][]byte // row | col | data
	for rows.Next() {
		row := make([][]byte, len(cols))
		// create an interface slice pointing to
		// the values stored in byte slice row.
		p := make([]interface{}, len(row))
		for i := range row {
			p[i] = &row[i]
		}
		Expect(rows.Scan(p...)).To(Succeed())
		all = append(all, row)
	}
	Expect(rows.Err()).To(Succeed())

	return all
}

func testIdempotency(db *sql.DB, mig migration.Migration, logger lager.Logger) {
	Expect(mig.Up(logger)).To(Succeed())

	tableNamesBefore, allSchemasBefore := getAllSchemas(db)

	dataBefore := make(map[string][][][]byte)
	for _, name := range tableNamesBefore {
		dataBefore[name] = dumpTableData(db, name)
	}

	// some migrations will not apply a second time, but we still want
	// to make sure the data was not changed.
	mig.Up(logger)

	tableNamesAfter, allSchemasAfter := getAllSchemas(db)

	dataAfter := make(map[string][][][]byte)
	for _, name := range tableNamesAfter {
		dataAfter[name] = dumpTableData(db, name)
	}

	Expect(tableNamesBefore).To(Equal(tableNamesAfter))
	Expect(allSchemasBefore).To(Equal(allSchemasAfter))
	Expect(dataBefore).To(Equal(dataAfter))
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
MemberDirectory::Application.initialize!


text:
(function() {
	'use strict';

	module1.service('module1Service', ['$http', '$q', module1Service]);

	function module1Service($http, $q) {
		var foo;

		function getFoo() {
			return foo;
		}

		function setFoo(value) {
			foo = value;
		}

		function getUsers() {
			return $q(function(resolve, reject) {
				$http.get('api/users').success(function(response) {
					resolve(response);
				}).error(function(err) {
					reject(err);
				});
			});
		}

		return {
			getFoo: getFoo,
			setFoo: setFoo,
			getUsers: getUsers
		};
	}
})();


text:
Dir["#{Rails.root}/lib/ruby_ext/*.rb"].each { |file| require file }

# Used for rails extensions.
# Dir["#{Rails.root}/lib/rails_ext/*.rb"].each { |file| require file }


text:
package ca.corefacility.bioinformatics.irida.config.conditions;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * A {@link Condition} for testing if the current platform is a Windows
 * platform.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 *
 */
public class WindowsPlatformCondition implements Condition {

	/**
	 * Returns true if the current platform is Windows-based.
	 *
	 * @return true if the current platform is Windows-based.
	 */
	public static boolean isWindows() {
		return System.getProperty("os.name").toLowerCase().contains("win");
	}

	@Override
	public boolean matches(ConditionContext context,
			AnnotatedTypeMetadata metadata) {
		return isWindows();
	}

}


text:
package net.sf.cglib.transform.impl;

/**
 *
 * @author  baliuka
 */
public interface PersistenceCapable {

    void setPersistenceManager(Object manager);

    Object getPersistenceManager();
}


text:
using OmniSharp;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("OmniSharp" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.Host" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.MSBuild" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.Roslyn" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.Roslyn.CSharp" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.DotNetTest.Tests" + OmniSharpPublicKey.Key)]
[assembly: InternalsVisibleTo("OmniSharp.Tests" + OmniSharpPublicKey.Key)]


text:
/**
 Author: Mahdi Jaberzadeh Ansari
 Email: mahdijaberzadehansari@yahoo.co.uk
 Library: ImageSliderRibbonJS
 Description: By using this library you can create image slider ribbons like Flash.
 Licence: MIT Licence
 Version 1.0.5
 Date: 26 Sep 2016
 call this method like this:
 ImageSliderRibbonJS('ImageSliderWraperDivId','SliderIconsClassName');
 */
// JavaScript Document
var ImageSliderRibbonJS = function(ImageSliderRibbonDivId, ElementsClass) {
	'use strict';
	var parentImageSliderRibbonDivDOM = document.getElementById(ImageSliderRibbonDivId);
	if (!parentImageSliderRibbonDivDOM)
		throw 'The Image Slider Bar Wrapper couldn\'t be found.';
	if (!window['ImageSliderRibbonJS_' + ImageSliderRibbonDivId])
		window['ImageSliderRibbonJS_' + ImageSliderRibbonDivId] = new MJZ_ImageSliderRibbon(parentImageSliderRibbonDivDOM, ElementsClass);

	function MJZ_ImageSliderRibbon(parentImageSliderRibbonDivDOM, ElementsClass) {
		'use strict';
		var _this = this;
		// function definition area
		this.setStyle = function(element, elementStyle) {
			if (typeof(element) == 'string')
				element = document.createElement(element);
			for (var key in elementStyle) {
				element.style[key] = elementStyle[key];
			}
			return element;
		};
		//
		this.zoomImage = function(imageObj, zoomPercent, zindex) {
			zoomPercent = parseInt(zoomPercent);
			imageObj.PreWidth = imageObj.offsetWidth;
			if (zoomPercent < 0 || zoomPercent > 100)
				return;
			_this.setStyle(imageObj, {
				height: zoomPercent + '%',
				top: ((100 - zoomPercent) / 2) + '%',
				zIndex: zindex
			});
			if (_this.items[0] != imageObj) {
				imageObj.Left = Math.ceil(imageObj.xPos - imageObj.offsetWidth / 2);
				_this.setStyle(imageObj, {
					left: imageObj.Left + 'px'
				});
			}
		};
		//
		this.transition = function(direction) //direction = -1 : Left to right; direction = 1 : Right to Left
		{
			if (direction == -1 && _this.items.length > 1) {
				if (_this.items[0].Left >= _this.StartPoint)
					return;
			} else if (direction == 1 && _this.items.length > 1) {
				if (_this.items[_this.items.length - 1].offsetLeft + _this.items[_this.items.length - 1].offsetWidth <= _this.EndPoint - 10)
					return;
			}
			for (var _i = 0; _i < _this.items.length; _i++) {
				_this.items[_i].Left = parseInt(_this.items[_i].offsetLeft);
				if (direction == 1) {
					_this.items[_i].Left--;
					_this.items[_i].xPos--;
				} else if (direction == -1) {
					_this.items[_i].Left++;
					_this.items[_i].xPos++;
				}
				_this.setStyle(_this.items[_i], {
					left: _this.items[_i].Left + 'px'
				});
			}
		};
		this.IntervalId = null;
		this.setStyle(parentImageSliderRibbonDivDOM, {
			position: 'relative',
			overflow: 'hidden',
			cursor: 'default'
		});
		// There is a transparent div at the left end of the ribbon that when mouse hover on that moves the images to right
		var leftButton = this.setStyle('div', {
			position: 'absolute',
			left: '0',
			top: '0',
			backgroundColor: 'transparent',
			width: '40px',
			height: '100%',
			zIndex: '101'
		});
		parentImageSliderRibbonDivDOM.appendChild(leftButton);
		leftButton.onmouseover = function() {
			clearInterval(_this.IntervalId);
			var __this = _this;
			_this.IntervalId = setInterval(function() {
				__this.transition(-1);
			}, 20);
		};
		leftButton.onmouseout = function() {
			clearInterval(_this.IntervalId);
		};
		// There is a transparent div at the right end of the ribbon that when mouse hover on that moves the images to left
		var reightButton = this.setStyle('div', {
			position: 'absolute',
			right: '0',
			top: '0',
			backgroundColor: 'transparent',
			width: '40px',
			height: '100%',
			zIndex: '101'
		});
		parentImageSliderRibbonDivDOM.appendChild(reightButton);
		reightButton.onmouseover = function() {
			clearInterval(_this.IntervalId);
			var __this = _this;
			_this.IntervalId = setInterval(function() {
				__this.transition(+1);
			}, 20);
		}
		reightButton.onmouseout = function() {
			clearInterval(_this.IntervalId);
		}
		this.StartPoint = 50;
		this.EndPoint = reightButton.offsetLeft;
		this.gap = 6;
		this.items = [];
		var ISRJS_Elements = parentImageSliderRibbonDivDOM.getElementsByTagName('*');
		for (var _i = 0; _i < ISRJS_Elements.length; _i++) {
			if (ISRJS_Elements[_i].className) {
				if (ISRJS_Elements[_i].className.match(ElementsClass)) {
					this.items.push(ISRJS_Elements[_i]);
					this.items[this.items.length - 1].Left = this.StartPoint;
					if (this.items.length > 1) {
						this.items[this.items.length - 1].Left = this.items[this.items.length - 2].Left + this.items[this.items.length - 2].offsetWidth + this.gap;
					}
					this.setStyle(ISRJS_Elements[_i], {
						height: '50%',
						position: 'absolute',
						zIndex: '99',
						top: '25%',
						left: this.items[this.items.length - 1].Left + 'px',
						visibility: 'visible'
					});
					this.items[this.items.length - 1].xPos = Math.ceil(this.items[this.items.length - 1].offsetLeft + this.items[this.items.length - 1].offsetWidth / 2);
					ISRJS_Elements[_i].onmouseover = function() {
						if (typeof this.STID == 'undefined')
							this.STID = new Array();
						for (var _j = 0; _j < this.STID.length; _j++)
							clearTimeout(this.STID[_j]);
						var __this = this;
						this.STID[0] = setTimeout(function() {
							_this.zoomImage(__this, 90, 100);
						}, 100);
						this.STID[1] = setTimeout(function() {
							_this.zoomImage(__this, 80, 100);
						}, 300);
						this.STID[2] = setTimeout(function() {
							_this.zoomImage(__this, 87.5, 100);
						}, 500);
						this.STID[3] = setTimeout(function() {
							_this.zoomImage(__this, 82.5, 100);
						}, 700);
						this.STID[4] = setTimeout(function() {
							_this.zoomImage(__this, 85, 100);
						}, 900);
					}
					ISRJS_Elements[_i].onmouseout = function() {
						if (typeof this.STID == 'undefined')
							this.STID = new Array();
						for (var _j = 0; _j < this.STID.length; _j++)
							clearTimeout(this.STID[_j]);
						var __this = this;
						this.STID[0] = setTimeout(function() {
							_this.zoomImage(__this, 45, 99);
						}, 100);
						this.STID[1] = setTimeout(function() {
							_this.zoomImage(__this, 55, 99);
						}, 300);
						this.STID[2] = setTimeout(function() {
							_this.zoomImage(__this, 47.5, 99);
						}, 500);
						this.STID[3] = setTimeout(function() {
							_this.zoomImage(__this, 52.5, 99);
						}, 700);
						this.STID[4] = setTimeout(function() {
							_this.zoomImage(__this, 50, 99);
						}, 900);
					}
				}
			}
		}
		// This function detects the direction of the pointer movment and based on that it move the pictures to left or right
		parentImageSliderRibbonDivDOM.onmousemove = function(event) {
			if (typeof _this.PreClientX == 'undefined')
				_this.PreClientX = event.clientX;
			if (event.clientX > _this.PreClientX)
				_this.transition(1);
			else if (event.clientX < _this.PreClientX)
				_this.transition(-1);
			_this.PreClientX = event.clientX;
		}
	}
};


text:
#include <st_static_component_loader.h>
#include <omx_video_scheduler_component.h>

/** @brief The library entry point. It must have the same name for each
  * library of the components loaded by the ST static component loader.
  *
  * This function fills the version, the component name and if existing also the roles
  * and the specific names for each role. This base function is only an explanation.
  * For each library it must be implemented, and it must fill data of any component
  * in the library.
  *
  * @param stComponents pointer to an array of components descriptors.If NULL, the
  * function will return only the number of components contained in the library
  *
  * @return number of components contained in the library
*/
int omx_component_library_Setup(stLoaderComponentType **stComponents) {
	int i;
	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s \n",__func__);

	if (stComponents == NULL) {
		DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s \n",__func__);
		return 1; // Return Number of Components - one for fbdev sink component
	}

	stComponents[0]->componentVersion.s.nVersionMajor = 1;
	stComponents[0]->componentVersion.s.nVersionMinor = 1;
	stComponents[0]->componentVersion.s.nRevision = 1;
	stComponents[0]->componentVersion.s.nStep = 1;

	stComponents[0]->name = calloc(1, OMX_MAX_STRINGNAME_SIZE);
	if (stComponents[0]->name == NULL) {
		return OMX_ErrorInsufficientResources;
	}
	strcpy(stComponents[0]->name, "OMX.st.video.scheduler");
	stComponents[0]->name_specific_length = 1;
	stComponents[0]->constructor =  omx_video_scheduler_component_Constructor;

	stComponents[0]->name_specific = calloc(stComponents[0]->name_specific_length,sizeof(char *));
	stComponents[0]->role_specific = calloc(stComponents[0]->name_specific_length,sizeof(char *));

	for(i=0;i<stComponents[0]->name_specific_length;i++) {
		stComponents[0]->name_specific[i] = calloc(1, OMX_MAX_STRINGNAME_SIZE);
		if (stComponents[0]->name_specific[i] == NULL) {
			return OMX_ErrorInsufficientResources;
		}
	}
	for(i=0;i<stComponents[0]->name_specific_length;i++) {
		stComponents[0]->role_specific[i] = calloc(1, OMX_MAX_STRINGNAME_SIZE);
		if (stComponents[0]->role_specific[i] == NULL) {
			return OMX_ErrorInsufficientResources;
		}
	}

	strcpy(stComponents[0]->name_specific[0], "OMX.st.video.scheduler");
	strcpy(stComponents[0]->role_specific[0], "video.scheduler");

	stComponents[0]->nqualitylevels = VIDEOSCHED_QUALITY_LEVELS;
	stComponents[0]->multiResourceLevel = malloc(stComponents[1]->nqualitylevels * sizeof(multiResourceDescriptor *));
	for (i=0; i<stComponents[0]->nqualitylevels; i++) {
		stComponents[0]->multiResourceLevel[i] = malloc(sizeof(multiResourceDescriptor));
		stComponents[0]->multiResourceLevel[i]->CPUResourceRequested = videoSchedQualityLevels[i * 2];
		stComponents[0]->multiResourceLevel[i]->MemoryResourceRequested = videoSchedQualityLevels[i * 2 + 1];
	}
	DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s \n",__func__);
	return 1;
}


text:
Mykeysound
==========
Mykeysound is an openframeworks application that you can use to play sounds with the keyboard.

It shows a virtual keyboard on screen. If you click on a key with your mouse you can assign a sound to it, and then when you press the key on the keyboard it will play the assigned sound.

You can use it with Makey-Makey to play sounds with physical objects.

OpenFrameworks 0.7.4.

of_v0.7.4_win_cb_release


text:
package org.jkiss.dbeaver.runtime.utils;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;

/**
 * Script utility.
 * Generates target database script as a result of utility work
 */
public interface DBUScriptUtility extends DBUUtility {

    String generateScript(DBRProgressMonitor monitor)
        throws DBException;

}


text:
#include "third_party/gpus/cuda/extras/CUPTI/include/cupti.h"
#include "third_party/gpus/cuda/include/cuda.h"
#include "tensorflow/tsl/platform/dso_loader.h"
#include "tensorflow/tsl/platform/env.h"

// Implements the CUPTI API by forwarding to CUPTI loaded from the DSO.

namespace {
// Returns DSO handle or null if loading the DSO fails.
void* GetDsoHandle() {
#if defined(PLATFORM_GOOGLE) && (CUDA_VERSION > 10000)
  return nullptr;
#else
  static auto handle = []() -> void* {
    auto handle_or = tsl::internal::DsoLoader::GetCuptiDsoHandle();
    if (!handle_or.ok()) return nullptr;
    return handle_or.value();
  }();
  return handle;
#endif
}

template <typename T>
T LoadSymbol(const char* symbol_name) {
  void* symbol = nullptr;
  if (auto handle = GetDsoHandle()) {
    tsl::Env::Default()
        ->GetSymbolFromLibrary(handle, symbol_name, &symbol)
        .IgnoreError();
  }
  return reinterpret_cast<T>(symbol);
}

CUptiResult GetSymbolNotFoundError() { return CUPTI_ERROR_UNKNOWN; }
}  // namespace

// For now we only need one stub implementation. We will need to generate
// a new file when CUPTI breaks backwards compatibility (has not been the case
// for quite a while) or if we want to use functionality introduced in a new
// version.
//
// Calling a function that is not yet available in the loaded CUPTI version will
// return CUPTI_ERROR_UNKNOWN.
#include "tensorflow/tsl/cuda/cupti_10_0.inc"


text:
namespace pno
{
//=========================== Forward Declarations =============================

class DaqDevice;

//=================================== Actuator =================================
class Actuator : public Accessible
{
public :  //======================== Public ======================

  Actuator(const LuaTable&);
  DaqDevice& daq() const { return *_daq; }

private : //======================= Private ======================

  DaqDevice* _daq;
};

//=================================== Pulser ===================================
class Pulser : public Actuator
{
public :  //======================== Public ======================

  Pulser(const LuaTable&);
  ~Pulser() { stop(); }

  void start() const;
  void stop() const;
  bool status() const;

private : //======================= Private ======================

  // Path to pin
  std::string _pin;

  // PWM configuration
  PwmConfig _config;
};

}
#endif


text:
local Perplexity, parent = torch.class("dp.Perplexity", "dp.Feedback")
Perplexity.isPerplexity = true

function Perplexity:__init(config)
   config = config or {}
   assert(torch.type(config) == 'table' and not config[1],
      "Constructor requires key-value arguments")
   local args, name = xlua.unpack(
      {config},
      'Perplexity',
      'Computes perplexity for language models',
      {arg='name', type='string', default='perplexity',
       help='name identifying Feedback in reports'}
   )
   config.name = name
   parent.__init(self, config)
   self._nll = 0
end

function Perplexity:setup(config)
   parent.setup(self, config)
   self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end

-- exponential of the mean NLL
function Perplexity:perplexity()
   -- divide by number of elements in sequence
   return torch.exp(self._nll / self._n_sample)
end

function Perplexity:doneEpoch(report)
   if self._n_sample > 0 and self._verbose then
      print(self._id:toString().." perplexity = "..self:perplexity())
   end
end

function Perplexity:add(batch, output, report)
   assert(torch.isTypeOf(batch, 'dp.Batch'), "First argument should be dp.Batch")
   -- table outputs are expected of recurrent neural networks
   if torch.type(output) == 'table' then
      -- targets aren't a table
      local targets = batch:targets():forward('bt')
      self._n_sample = self._n_sample + targets:nElement()
      local sum = 0
      for i=1,#output do
         local target = targets:select(2,i)
         local act = output[i]
         if not (torch.isTypeOf(act, 'torch.FloatTensor') or torch.isTypeOf(act, 'torch.DoubleTensor')) then
            self._act = self._act or torch.FloatTensor()
            self._act:resize(act:size()):copy(act)
            act = self._act
         end
         if act:dim() == 2 then
            -- assume output originates from LogSoftMax
            for i=1,target:size(1) do
               sum = sum + act[i][target[i]]
            end
         else
            -- assume output originates from SoftMaxTree (which is loglikelihood)
            sum = sum + act:view(-1):sum()
         end
      end
      self._nll = self._nll - sum
   else
      self._n_sample = self._n_sample + batch:nSample()
      local act = output
      if not (torch.isTypeOf(act, 'torch.FloatTensor') or torch.isTypeOf(act, 'torch.DoubleTensor')) then
         self._act = self._act or torch.FloatTensor()
         self._act:resize(act:size()):copy(act)
         act = self._act
      end
      if output:dim() == 2 then
         -- assume output originates from LogSoftMax
         local targets = batch:targets():forward('b')
         local sum = 0
         for i=1,targets:size(1) do
            sum = sum + act[i][targets[i]]
         end
         self._nll = self._nll - sum
      else
         -- assume output originates from SoftMaxTree (which is loglikelihood)
         -- accumulate the sum of negative log likelihoods
         self._nll = self._nll - act:view(-1):sum()
      end
   end
end

function Perplexity:_reset()
   self._nll = 0
end

function Perplexity:report()
   return {
      [self:name()] = {
         ppl = self._n_sample > 0 and self:perplexity() or 0
      },
      n_sample = self._n_sample
   }
end


text:
KISSY.add('sammy/object', function(S, Sammy){
  var _escapeHTML = function(s) {
    return String(s).replace(/&(?!\w+;)/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
  }

  var SammyObject = function(obj){
    return S.mix(this, obj || {})
  }

  S.extend(SammyObject, {
    // Escape HTML in string, use in templates to prevent script injection.
    // Also aliased as `h()`
    escapeHTML: _escapeHTML,
    h: _escapeHTML,

    // Returns a copy of the object with Functions removed.
    toHash: function() {
      var json = {}
      S.each(this, function(v,k) {
        if (!S.isFunction(v)) {
          json[k] = v
        }
      })
      return json
    },

    // Renders a simple HTML version of this Objects attributes.
    // Does not render functions.
    // For example. Given this Sammy.Object:
    //
    //     var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
    //     s.toHTML()
    //     //=> 'first_name Sammy
last_name Davis Jr.
'
    //
    toHTML: function() {
      var display = ""
      S.each(this, function(v, k) {
        if (!S.isFunction(v)) {
          display += "" + k + " " + v + "
"
        }
      })
      return display
    },

    // Returns an array of keys for this object. If `attributes_only`
    // is true will not return keys that map to a `function()`
    keys: function(attributes_only) {
      var keys = []
      for (var property in this) {
        if (!S.isFunction(this[property]) || !attributes_only) {
          keys.push(property)
        }
      }
      return keys
    },

    // Checks if the object has a value at `key` and that the value is not empty
    has: function(key) {
      return this[key] && S.trim(this[key].toString()) !== ''
    },

    // convenience method to join as many arguments as you want
    // by the first argument - useful for making paths
    join: function() {
      var args = S.makeArray(arguments)
      var delimiter = args.shift()
      return args.join(delimiter)
    },

    // Shortcut to Sammy.log
    log: function() {
      Sammy.log.apply(Sammy, arguments)
    },

    // Returns a string representation of this object.
    // if `include_functions` is true, it will also toString() the
    // methods of this object. By default only prints the attributes.
    toString: function(include_functions) {
      var s = []
      S.each(this, function(v, k) {
        if (!S.isFunction(v) || include_functions) {
          s.push('"' + k + '": ' + v.toString())
        }
      });
      return "Sammy.Object: {" + s.join(',') + "}"
    }

  })

  Sammy.Object = SammyObject

  return SammyObject

}, {
  requires: ['sammy/base']
})


text:
package zap

import (
	"fmt"
	"io"

	"go.uber.org/zap/zapcore"

	"go.uber.org/multierr"
)

// Open is a high-level wrapper that takes a variadic number of URLs, opens or
// creates each of the specified resources, and combines them into a locked
// WriteSyncer. It also returns any error encountered and a function to close
// any opened files.
//
// Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a
// scheme and URLs with the "file" scheme. Third-party code may register
// factories for other schemes using RegisterSink.
//
// URLs with the "file" scheme must use absolute paths on the local
// filesystem. No user, password, port, fragments, or query parameters are
// allowed, and the hostname must be empty or "localhost".
//
// Since it's common to write logs to the local filesystem, URLs without a
// scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without
// a scheme, the special paths "stdout" and "stderr" are interpreted as
// os.Stdout and os.Stderr. When specified without a scheme, relative file
// paths also work.
func Open(paths ...string) (zapcore.WriteSyncer, func(), error) {
	writers, close, err := open(paths)
	if err != nil {
		return nil, nil, err
	}

	writer := CombineWriteSyncers(writers...)
	return writer, close, nil
}

func open(paths []string) ([]zapcore.WriteSyncer, func(), error) {
	writers := make([]zapcore.WriteSyncer, 0, len(paths))
	closers := make([]io.Closer, 0, len(paths))
	close := func() {
		for _, c := range closers {
			c.Close()
		}
	}

	var openErr error
	for _, path := range paths {
		sink, err := _sinkRegistry.newSink(path)
		if err != nil {
			openErr = multierr.Append(openErr, fmt.Errorf("open sink %q: %w", path, err))
			continue
		}
		writers = append(writers, sink)
		closers = append(closers, sink)
	}
	if openErr != nil {
		close()
		return nil, nil, openErr
	}

	return writers, close, nil
}

// CombineWriteSyncers is a utility that combines multiple WriteSyncers into a
// single, locked WriteSyncer. If no inputs are supplied, it returns a no-op
// WriteSyncer.
//
// It's provided purely as a convenience; the result is no different from
// using zapcore.NewMultiWriteSyncer and zapcore.Lock individually.
func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer {
	if len(writers) == 0 {
		return zapcore.AddSync(io.Discard)
	}
	return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...))
}


text:
package de.slisson.mps.editor.aec.demolang.editor;

/*Generated by MPS */

import jetbrains.mps.nodeEditor.AbstractCellProvider;
import jetbrains.mps.smodel.SNode;
import jetbrains.mps.nodeEditor.cells.EditorCell;
import jetbrains.mps.nodeEditor.EditorContext;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import jetbrains.mps.lang.editor.cellProviders.PropertyCellProvider;
import jetbrains.mps.smodel.IOperationContext;
import jetbrains.mps.nodeEditor.EditorManager;

public class ConceptA_Properties extends AbstractCellProvider {
  public ConceptA_Properties(SNode node) {
    super(node);
  }

  public EditorCell createEditorCell(EditorContext editorContext) {
    return this.createEditorCell(editorContext, this.getSNode());
  }

  public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
    return this.createCollection_qlz1v0_a(editorContext, node);
  }

  private EditorCell createCollection_qlz1v0_a(EditorContext editorContext, SNode node) {
    EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node);
    editorCell.setCellId("Collection_qlz1v0_a");
    editorCell.addEditorCell(this.createConstant_qlz1v0_a0(editorContext, node));
    editorCell.addEditorCell(this.createProperty_qlz1v0_b0(editorContext, node));
    return editorCell;
  }

  private EditorCell createConstant_qlz1v0_a0(EditorContext editorContext, SNode node) {
    EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "ConceptA_Properties");
    editorCell.setCellId("Constant_qlz1v0_a0");
    editorCell.setDefaultText("");
    return editorCell;
  }

  private EditorCell createProperty_qlz1v0_b0(EditorContext editorContext, SNode node) {
    CellProviderWithRole provider = new PropertyCellProvider(node, editorContext);
    provider.setRole("propA1");
    provider.setNoTargetText("<no propA1>");
    EditorCell editorCell;
    editorCell = provider.createEditorCell(editorContext);
    editorCell.setCellId("property_propA1");
    editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
    SNode attributeConcept = provider.getRoleAttribute();
    Class attributeKind = provider.getRoleAttributeClass();
    if (attributeConcept != null) {
      IOperationContext opContext = editorContext.getOperationContext();
      EditorManager manager = EditorManager.getInstanceFromContext(opContext);
      return manager.createRoleAttributeCell(editorContext, attributeConcept, attributeKind, editorCell);
    } else
    return editorCell;
  }
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'sangha_accessibility'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sangha_accessibility

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
require 'spec_helper'

describe DynamicsCRM::XML::QueryExpression do

  describe 'initialization' do
    subject {
      DynamicsCRM::XML::QueryExpression.new('opportunity')
    }

    context "generate empty QueryExpression fragment" do
      it { expect(subject.to_xml).to include("<b:ColumnSet ") }
      it { expect(subject.to_xml).to include("<b:Criteria>") }
      it { expect(subject.to_xml).to include("<b:Conditions />") }
      it { expect(subject.to_xml).to include("<b:AllColumns>true</b:AllColumns>") }
      it { expect(subject.to_xml).to include("<b:Distinct>false</b:Distinct>") }
      it { expect(subject.to_xml).to include("<b:EntityName>opportunity</b:EntityName>") }
      it { expect(subject.to_xml).to include("<b:FilterOperator>And</b:FilterOperator>").or(include("<b:FilterOperator>Or</b:FilterOperator>")) }
    end
  end

  describe 'Criteria' do
    subject {
      query = DynamicsCRM::XML::QueryExpression.new('opportunity')
      query.criteria = DynamicsCRM::XML::Criteria.new([["name", "Equal", "Test Opp"]])
      query
    }

    context "generate QueryExpression fragment" do
      it { expect(subject.to_xml).to include("<b:ColumnSet ") }
      it { expect(subject.to_xml).to include("<b:ConditionExpression") }
      it { expect(subject.to_xml).to include("AttributeName>name</") }
      it { expect(subject.to_xml).to include("Operator>Equal</") }
      it { expect(subject.to_xml).to include('<d:anyType i:type="s:string" xmlns:s="http://www.w3.org/2001/XMLSchema">Test Opp</d:anyType>') }
      it { expect(subject.to_xml).to include("<b:AllColumns>true</b:AllColumns>") }
      it { expect(subject.to_xml).to include("<b:Distinct>false</b:Distinct>") }
      it { expect(subject.to_xml).to include("<b:EntityName>opportunity</b:EntityName>") }
      it { expect(subject.to_xml).to include("<b:FilterOperator>And</b:FilterOperator>").or(include("<b:FilterOperator>Or</b:FilterOperator>")) }
    end
  end

  describe 'PageInfo' do
    subject {
      query = DynamicsCRM::XML::QueryExpression.new('account')
      query.columns = %w(accountid name)
      query.criteria.add_condition('name', 'NotEqual', 'Test Account')
      query.page_info = DynamicsCRM::XML::PageInfo.new(count: 5, page_number: 2, return_total_record_count: true)
      query
    }

    context "generate empty QueryExpression fragment" do
      it { expect(subject.to_xml).to include('<b:ColumnSet ') }
      it { expect(subject.to_xml).to include('<b:ConditionExpression') }
      it { expect(subject.to_xml).to include('AttributeName>name</') }
      it { expect(subject.to_xml).to include('Operator>NotEqual</') }
      it { expect(subject.to_xml).to include('<d:anyType i:type="s:string" xmlns:s="http://www.w3.org/2001/XMLSchema">Test Account</d:anyType>') }
      it { expect(subject.to_xml).to include('<b:AllColumns>false</b:AllColumns>') }
      it { expect(subject.to_xml).to include('<b:Columns') }
      it { expect(subject.to_xml).to include('<b:EntityName>account</b:EntityName>') }
      it { expect(subject.to_xml).to include('<b:PageInfo>') }
      it { expect(subject.to_xml).to include('<b:Count>5</b:Count>') }
      it { expect(subject.to_xml).to include('<b:PageNumber>2</b:PageNumber>') }
      it { expect(subject.to_xml).to include('<b:ReturnTotalRecordCount>true</b:ReturnTotalRecordCount>') }
    end
  end
end


text:
<!-- options file don't change unless you know what you are doing -->
<?php
/*The default database is mysql but it can be changed by editing this file*/
// Database connection info
$dbcs = "";
$dbuser = "";
$dbpass = "";
?>


text:
import Parsley from '../parsley';

Parsley.addMessages('ms', {
  dateiso:  "Nilai hendaklah berbentuk tarikh yang sah (YYYY-MM-DD).",
  minwords: "Ayat terlalu pendek. Ianya perlu sekurang-kurangnya %s patah perkataan.",
  maxwords: "Ayat terlalu panjang. Ianya tidak boleh melebihi %s patah perkataan.",
  words:    "Panjang ayat tidak sah. Jumlah perkataan adalah diantara %s hingga %s patah perkataan.",
  gt:       "Nilai lebih besar diperlukan.",
  gte:      "Nilai hendaklah lebih besar atau sama.",
  lt:       "Nilai lebih kecil diperlukan.",
  lte:      "Nilai hendaklah lebih kecil atau sama."
});


text:
var koa     = require('koa');
var sockjs  = require('sockjs');
var http    = require('http');
var fs      = require('fs');
var path    = require('path');

// 1. Echo sockjs server
var sockjs_opts = {sockjs_url: "http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"};
var sockjs_echo = sockjs.createServer(sockjs_opts);
sockjs_echo.on('connection', function(conn) {
    conn.on('data', function(message) {
        conn.write(message);
    });
});

// 2. koa server
var app = koa();

app.use(function *() {
    var filePath = __dirname + '/index.html';
    this.type = path.extname(filePath);
    this.body = fs.createReadStream(filePath);
});

var server = http.createServer(app.callback());
sockjs_echo.installHandlers(server, {prefix:'/echo'});

server.listen(9999, '0.0.0.0');
console.log(' [*] Listening on 0.0.0.0:9999' );


text:
if [ "$EUID" -ne 0 ]
  then echo "Please run as root/sudo"
  exit
fi

source config.sh

apt-get remove --purge apache2 ssl-cert -y
apt-get remove apache2-common -y
rm -rf /var/www/html/daytona

apt-get remove --purge libapache2-mod-php7.0 php7.0 php7.0-common php7.0-mcrypt php7.0-zip php7.0-mysqlnd php-common -y

apt-get remove --purge mysql-server mysql-client mysql-common -y

apt-get autoremove -y
apt-get autoclean -y
rm -rf /var/lib/mysql /etc/mysql

# Kill scheduler and agent
ps -ef | grep sar | awk '{print $2}' > pidfile
ps -ef | grep agent.py | awk '{print $2}' >> pidfile
ps -ef | grep iostat | awk '{print $2}' >> pidfile
ps -ef | grep scheduler.py | awk '{print $2}' >> pidfile

for i in `cat pidfile`
do
        kill -9 $i
done

rm -rf ${daytona_install_dir}/Scheduler+Agent
rm -rf $daytona_data_dir
rm -rf /var/www/html/daytona
rm -rf ${daytona_install_dir}/ExecScripts
rm -rf ${daytona_install_dir}/daytona_agent_root
rm -f pidfile
rm -rf ${daytona_install_dir}/config.sh
rm -rf ${daytona_install_dir}/daytona_backup.sh
rm -rf ${daytona_install_dir}/daytona_restore.sh
rm -rf ${daytona_install_dir}/cron-backup.sh


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/spanner/v1/transaction.proto

package com.google.spanner.v1;

public interface TransactionOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.spanner.v1.Transaction)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * `id` may be used to identify the transaction in subsequent
   * [Read][google.spanner.v1.Spanner.Read],
   * [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql],
   * [Commit][google.spanner.v1.Spanner.Commit], or
   * [Rollback][google.spanner.v1.Spanner.Rollback] calls.
   * Single-use read-only transactions do not have IDs, because
   * single-use transactions do not support multiple requests.
   *

   *
   * bytes id = 1;
   */
  com.google.protobuf.ByteString getId();

  /**
   *
   *
   *

   * For snapshot read-only transactions, the read timestamp chosen
   * for the transaction. Not returned by default: see
   * [TransactionOptions.ReadOnly.return_read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.return_read_timestamp].
   * A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds.
   * Example: `"2014-10-02T15:01:23.045123456Z"`.
   *

   *
   * .google.protobuf.Timestamp read_timestamp = 2;
   */
  boolean hasReadTimestamp();
  /**
   *
   *
   *

   * For snapshot read-only transactions, the read timestamp chosen
   * for the transaction. Not returned by default: see
   * [TransactionOptions.ReadOnly.return_read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.return_read_timestamp].
   * A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds.
   * Example: `"2014-10-02T15:01:23.045123456Z"`.
   *

   *
   * .google.protobuf.Timestamp read_timestamp = 2;
   */
  com.google.protobuf.Timestamp getReadTimestamp();
  /**
   *
   *
   *

   * For snapshot read-only transactions, the read timestamp chosen
   * for the transaction. Not returned by default: see
   * [TransactionOptions.ReadOnly.return_read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.return_read_timestamp].
   * A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds.
   * Example: `"2014-10-02T15:01:23.045123456Z"`.
   *

   *
   * .google.protobuf.Timestamp read_timestamp = 2;
   */
  com.google.protobuf.TimestampOrBuilder getReadTimestampOrBuilder();
}


text:
'use strict';

/**
 * Simple request module
 */
var rq = {
  /**
   * Builds a URI-encoded query string from an object
   * @param {Object} form Formatted `{field: value}`
   * @returns {String} Concatenated and URI endoded string of paramenters
   */
  encodeForm: function encodeForm() {
    var form = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    return Object.keys(form).map(function (key) {
      return [key, form[key]].map(encodeURIComponent).join('=');
    }).join('&');
  },
  /**
   * Simple GET request to url, returns a promise
   * @param {String} url
   * @param {Object} form Form data appended to url as form encoded query strings
   * @returns {Promise} Response body (parsed as JSON if application/json content-type detected)
   */
  get: function get(url, form) {
    return new Promise(function (resolve, reject) {
      var xhr = new window.XMLHttpRequest();
      form = rq.encodeForm(form);
      xhr.open('get', url + '?' + form, true);
      xhr.responseType = 'json';

      xhr.onload = function () {
        if (xhr.status === 200 || xhr.status === 304) {
          resolve(xhr.response);
        } else {
          reject(new Error(xhr.status));
        }
      };
      xhr.onerror = function () {
        return reject(new Error('XMLHttpRequest Error: ' + xhr.statusText));
      };
      xhr.send();
    });
  },
  /**
   * Simple POST request to url, returns a promise
   * @param {String} url
   * @param {Object} form Form data appended to url as form encoded query strings
   * @returns {Promise} Response body (parsed as JSON if application/json content-type detected)
   */
  post: function post(url, form) {
    return new Promise(function (resolve, reject) {
      var xhr = new window.XMLHttpRequest();
      form = rq.encodeForm(form);
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhr.setRequestHeader('Content-length', form.length);
      xhr.setRequestHeader('Connection', 'close');

      xhr.onload = function () {
        if (xhr.status === 200 || xhr.status === 304) {
          resolve(xhr.response);
        } else {
          reject(new Error(xhr.status));
        }
      };
      xhr.onerror = function () {
        return reject(new Error('XMLHttpRequest Error: ' + xhr.statusText));
      };

      xhr.send(form);
    });
  }
};

module.exports = rq;


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

#include "common/globals.h"
#include "vendors/OceanOptics/protocols/obp/exchanges/OBPGetConsecutiveSampleCountExchange.h"
#include "vendors/OceanOptics/protocols/obp/hints/OBPControlHint.h"
#include "vendors/OceanOptics/protocols/obp/constants/OBPMessageTypes.h"
#include <vector>

using namespace seabreeze;
using namespace seabreeze::oceanBinaryProtocol;
using namespace std;

OBPGetConsecutiveSampleCountExchange::OBPGetConsecutiveSampleCountExchange() {
    this->hints->push_back(new OBPControlHint());
    this->messageType = OBPMessageTypes::OBP_GET_BACK_TO_BACK_SAMPLE_COUNT;
	this->payload.resize(0);
}

OBPGetConsecutiveSampleCountExchange::~OBPGetConsecutiveSampleCountExchange() {

}

unsigned int OBPGetConsecutiveSampleCountExchange::queryConsecutiveSampleCount(
        TransferHelper *helper) {

    unsigned int consecutiveSampleCount;
    vector<unsigned char> *result;

    result = this->queryDevice(helper);
    if(NULL == result || result->size() < sizeof(unsigned int)) {
        throw ProtocolException("Got a short read when querying consecutive sample count.");
    }

	// cast of a byte pointer(data) to an unsigned integer pointer which is dereferenced
	consecutiveSampleCount = *(unsigned int *)(&(*result)[0]);

    delete result;

    return consecutiveSampleCount;
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/breadcrumbs/breadcrumb_manager_tab_helper.h"

#include "base/strings/stringprintf.h"
#include "chrome/browser/breadcrumbs/breadcrumb_manager_keyed_service_factory.h"
#include "chrome/common/webui_url_constants.h"
#include "components/breadcrumbs/core/breadcrumb_manager_keyed_service.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "url/gurl.h"

namespace {

bool IsNtpUrl(const GURL& url) {
  const std::string origin = url.DeprecatedGetOriginAsURL().spec();
  return origin == chrome::kChromeUINewTabURL ||
         origin == chrome::kChromeUINewTabPageURL ||
         origin == chrome::kChromeUINewTabPageThirdPartyURL;
}

}  // namespace

BreadcrumbManagerTabHelper::BreadcrumbManagerTabHelper(
    content::WebContents* web_contents)
    : breadcrumbs::BreadcrumbManagerTabHelper(
          infobars::ContentInfoBarManager::FromWebContents(web_contents)),
      content::WebContentsObserver(web_contents),
      content::WebContentsUserData<BreadcrumbManagerTabHelper>(*web_contents) {}

BreadcrumbManagerTabHelper::~BreadcrumbManagerTabHelper() = default;

void BreadcrumbManagerTabHelper::PlatformLogEvent(const std::string& event) {
  BreadcrumbManagerKeyedServiceFactory::GetForBrowserContext(
      GetWebContents().GetBrowserContext())
      ->AddEvent(event);
}

void BreadcrumbManagerTabHelper::DidStartNavigation(
    content::NavigationHandle* navigation_handle) {
  LogDidStartNavigation(navigation_handle->GetNavigationId(),
                        navigation_handle->GetURL(),
                        IsNtpUrl(navigation_handle->GetURL()),
                        navigation_handle->IsRendererInitiated(),
                        navigation_handle->HasUserGesture(),
                        navigation_handle->GetPageTransition());
}

void BreadcrumbManagerTabHelper::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  LogDidFinishNavigation(navigation_handle->GetNavigationId(),
                         navigation_handle->IsDownload(),
                         navigation_handle->GetNetErrorCode());
}

void BreadcrumbManagerTabHelper::DidFinishLoad(
    content::RenderFrameHost* render_frame_host,
    const GURL& validated_url) {
  LogPageLoaded(IsNtpUrl(validated_url), validated_url,
                /*page_load_success=*/true,
                GetWebContents().GetContentsMimeType());
}

void BreadcrumbManagerTabHelper::DidFailLoad(
    content::RenderFrameHost* render_frame_host,
    const GURL& validated_url,
    int error_code) {
  LogPageLoaded(IsNtpUrl(validated_url), validated_url,
                /*page_load_success=*/false,
                GetWebContents().GetContentsMimeType());
}

void BreadcrumbManagerTabHelper::DidChangeVisibleSecurityState() {
  const auto visible_security_state =
      security_state::GetVisibleSecurityState(&GetWebContents());
  DCHECK(visible_security_state);

  // Note that mixed content is auto-upgraded to HTTPS in almost all cases on
  // desktop (the user has to specifically allow it on a per-site basis in
  // settings), so this is unlikely.
  const bool displayed_mixed_content =
      visible_security_state->displayed_mixed_content;

  security_state::SecurityLevel security_level =
      security_state::GetSecurityLevel(
          *visible_security_state,
          /*used_policy_installed_certificate=*/false);
  const bool security_style_authentication_broken =
      security_level == security_state::SecurityLevel::DANGEROUS;

  LogDidChangeVisibleSecurityState(displayed_mixed_content,
                                   security_style_authentication_broken);
}

void BreadcrumbManagerTabHelper::PrimaryMainFrameRenderProcessGone(
    base::TerminationStatus status) {
  LogRenderProcessGone();
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(BreadcrumbManagerTabHelper);


text:
tinymce.init({
    selector: 'textarea.tinymce',
    height: 300,
    theme: 'modern',
    plugins: [
        'advlist autolink lists link image charmap print preview hr anchor pagebreak',
        'searchreplace media wordcount visualblocks visualchars code fullscreen',
        'insertdatetime nonbreaking save table contextmenu directionality',
        'emoticons template paste textcolor colorpicker textpattern imagetools cakephp3media'
    ],
    toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link media',
    toolbar2: 'print preview | forecolor backcolor emoticons'
})


text:
package com.google.android.apps.muzei.event;

public class SwitchingPhotosStateChangedEvent {
    private boolean mSwitchingPhotos;
    private int mId;

    public SwitchingPhotosStateChangedEvent(int id, boolean switchingPhotos) {
        mId = id;
        mSwitchingPhotos = switchingPhotos;
    }

    public int getCurrentId() {
        return mId;
    }

    public boolean isSwitchingPhotos() {
        return mSwitchingPhotos;
    }
}


text:
import json
import os

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import config
from models import Company, Location

Base = declarative_base()
engine = create_engine(config.Config.SQLALCHEMY_DATABASE_URI)

DBSession = sessionmaker(bind=engine)
session = DBSession()

DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(
    os.path.abspath(__file__)
)), "data")

EXT = "json"

class Loader(object):

    def __init__(self, data_dir):
        self.data_dir = data_dir

    def traverse(self):
        for filename in os.listdir(self.data_dir):
            split = filename.split(".")
            if len(split) > 1 and split[-1] == EXT:
                yield os.path.join(self.data_dir, filename)

    def run(self):
        def save_obj(data):
            company = Company(
                cid=data['companyId'],
                logo=config.Static.LAGOU_WEBSITE + "/"
                     + data['coreInfo']['logo'],
                name=data['coreInfo']['companyName'],
                short_name=data['coreInfo']['companyShortName'],
                url=data['coreInfo']['companyUrl'],
                industry_field=data['baseInfo']['industryField'],
                size=data['baseInfo']['companySize'],
                city=data['baseInfo']['city'],
                finance_stage=data['baseInfo']['financeStage']
            )
            session.add(company)
            locations = []
            for item in data['location']:
                loc = Location(
                    company_id=data['companyId'],
                    brief_position=item['briefPosition'],
                    detail_position=item['detailPosition'],
                    longitude=item.get('longitude', ""),
                    latitude=item.get('latitude', "")
                )
                locations.append(loc)
            if locations:
                session.bulk_save_objects(locations)

        for path in self.traverse():
            with open(path) as f:
                try:
                    data = json.loads(f.read())
                    save_obj(data)
                except Exception, exp:
                    print "load %s encounters error %s" % (path, str(exp))
        session.commit()

if __name__ == '__main__':
    loader = Loader(DATA_DIR)
    loader.run()


text:
package account

import (
	"net/url"
	"strconv"

	stripe "github.com/stripe/stripe-go"
)

// Client is used to invoke /account APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

// New creates a new account.
func New(params *stripe.AccountParams) (*stripe.Account, error) {
	return getC().New(params)
}

func writeAccountParams(
	params *stripe.AccountParams, body *url.Values,
) {
	if len(params.Email) > 0 {
		body.Add("email", params.Email)
	}

	// Country.
	if len(params.Country) > 0 {
		body.Add("country", params.Country)
	}

	if len(params.DefaultCurrency) > 0 {
		body.Add("default_currency", params.DefaultCurrency)
	}

	if len(params.Statement) > 0 {
		body.Add("statement_descriptor", params.Statement)
	}

	if len(params.BusinessName) > 0 {
		body.Add("business_name", params.BusinessName)
	}

	if len(params.BusinessPrimaryColor) > 0 {
		body.Add("business_primary_color", params.BusinessPrimaryColor)
	}

	if len(params.BusinessUrl) > 0 {
		body.Add("business_url", params.BusinessUrl)
	}

	if len(params.SupportPhone) > 0 {
		body.Add("support_phone", params.SupportPhone)
	}

	if len(params.SupportEmail) > 0 {
		body.Add("support_email", params.SupportEmail)
	}

	if len(params.SupportUrl) > 0 {
		body.Add("support_url", params.SupportUrl)
	}

	if params.LegalEntity != nil {
		params.LegalEntity.AppendDetails(body)
	}

	if params.TransferSchedule != nil {
		params.TransferSchedule.AppendDetails(body)
	}

	if params.BankAccount != nil {
		params.BankAccount.AppendDetails(body)
	}
}

func (c Client) New(params *stripe.AccountParams) (*stripe.Account, error) {
	body := &url.Values{
		"managed": {strconv.FormatBool(params.Managed)},
	}

	writeAccountParams(params, body)

	if params.TOSAcceptance != nil {
		params.TOSAcceptance.AppendDetails(body)
	}

	params.AppendTo(body)

	acct := &stripe.Account{}
	err := c.B.Call("POST", "/accounts", c.Key, body, &params.Params, acct)

	return acct, err
}

// Get returns the details of an account.
func Get() (*stripe.Account, error) {
	return getC().Get()
}

func (c Client) Get() (*stripe.Account, error) {
	account := &stripe.Account{}
	err := c.B.Call("GET", "/account", c.Key, nil, nil, account)

	return account, err
}

// GetByID returns the details of your account.
func GetByID(id string, params *stripe.AccountParams) (*stripe.Account, error) {
	return getC().GetByID(id, params)
}

func (c Client) GetByID(id string, params *stripe.AccountParams) (*stripe.Account, error) {
	var body *url.Values
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &url.Values{}
		params.AppendTo(body)
	}

	account := &stripe.Account{}
	err := c.B.Call("GET", "/accounts/"+id, c.Key, body, commonParams, account)

	return account, err
}

// Update updates the details of an account.
func Update(id string, params *stripe.AccountParams) (*stripe.Account, error) {
	return getC().Update(id, params)
}

func (c Client) Update(id string, params *stripe.AccountParams) (*stripe.Account, error) {
	var body *url.Values
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &url.Values{}

		writeAccountParams(params, body)

		params.AppendTo(body)
	}

	acct := &stripe.Account{}
	err := c.B.Call("POST", "/accounts/"+id, c.Key, body, commonParams, acct)

	return acct, err
}

// List lists your accounts.
func List(params *stripe.AccountListParams) *Iter {
	return getC().List(params)
}

func (c Client) List(params *stripe.AccountListParams) *Iter {
	type accountList struct {
		stripe.ListMeta
		Values []*stripe.Account `json:"data"`
	}

	var body *url.Values
	var lp *stripe.ListParams

	if params != nil {
		body = &url.Values{}

		params.AppendTo(body)
		lp = &params.ListParams
	}

	return &Iter{stripe.GetIter(lp, body, func(b url.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &accountList{}
		err := c.B.Call("GET", "/accounts", c.Key, &b, nil, list)

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}

// Iter is an iterator for lists of Accounts.
// The embedded Iter carries methods with it;
// see its documentation for details.
type Iter struct {
	*stripe.Iter
}

// Account returns the most recent Account
// visited by a call to Next.
func (i *Iter) Account() *stripe.Account {
	return i.Current().(*stripe.Account)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}


text:
<?php

class FBMock_Utils {
  public static function mockClassNameFor(
      $class_name,
      array $interfaces,
      array $traits) {

    self::assertString($class_name);

    sort($interfaces);
    sort($traits);

    return sprintf(
      'FBMockFramework_%s_%s_%s',
      self::classNameForMock($class_name),
      implode('_', (array)str_replace('_', '__', $interfaces)),
      implode('_', (array)str_replace('_', '__', $traits))
    );
  }

  public static function isHHVM() {
    return defined('HPHP_VERSION');
  }

  public static function getInterfacesAndTraits(array $interfaces = array()) {
    $interfaces[] = 'FBMock_Mock';
    return array(
      $interfaces,
      FBMock_Config::get()->getMockTraits(),
    );
  }

  public static function enforce($invariant, $msg /* args */) {
    if (!$invariant) {
      self::assertString($msg);

      // TODO (#1913833): use FBMock_MockObjectException
      throw new Exception(vsprintf($msg, array_slice(func_get_args(), 2)));
    }
  }

  public static function assertString($str) {
    if (!is_string($str)) {
      throw new InvalidArgumentException(
        "String argument expected, ".gettype($str)." given"
      );
    }
  }

  public static function assertInt($int) {
    if (!is_int($int)) {
      throw new InvalidArgumentException(
        "Integer argument expected, ".gettype($int)." given"
      );
    }
  }

  public static function setDoubleImplementation($double, $impl) {
    $double->__implementation = $impl;
  }

  public static function getDoubleImplementation($double) {
    return $double->__implementation;
  }

  public static function classNameForMock($class_name) {
    // Remove namespace separators from class name as mocks are not namespaced.
    return str_replace('\\', '__NS__', $class_name);
  }
}


text:
export * from './toolbar-search.module';
export * from './toolbar-search.component';
export * from './toolbar-search-field.directive';
export * from './toolbar-search-button.directive';


text:
const got = require('got')

const errorHandling = require('./error-handling.js')

const osrs = require('./constants').osrs
const rs3 = require('./constants').rs3

const requestOptions = {family: 4}
// family: 4 is needed to avoid this weird error
// https://github.com/nodejs/node/issues/5436

module.exports = class Cml {
	constructor(game) {
		if (game === 'rs3') {
			this.game = 'rs3'
			this.skills = rs3.skills
			this.cmlURL = 'crystalmathlabs.com/tracker-rs3/api.php'
		} else {
			this.game = 'osrs'
			this.skills = osrs.skills
			this.cmlURL = 'crystalmathlabs.com/tracker/api.php'
		}
	}

	update(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=update&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)
					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	lastcheck(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=lastcheck&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const sec = parseInt(res.body)
						resolve({err, sec})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	lastchange(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=lastchange&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const sec = parseInt(res.body)
						resolve({err, sec})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	// see if user exists
	search(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=search&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const exists = (parseInt(res.body) !== 0)
						resolve({err, exists})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	recordsOfPlayer(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=recordsofplayer&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const records = {}
						const splitBody = res.body.split('\n')
						splitBody.pop()

						for (let i = 0; i < splitBody.length; i++) {
							const info = splitBody[i].split(',')
							records[this.skills[i]] = {
								day: parseFloat(info[0]),
								week: parseFloat(info[2]),
								month: parseFloat(info[4])
							}
						}

						resolve({err, records})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	previousName(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=previousname&player=${user}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const username = res.body
						resolve({err, username})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	track(user, time) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=trackehp&player=${user}&time=${time}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const stats = {}
						const splitBody = res.body.split('\n')
						stats.lastchanged = parseInt(splitBody[0])
						splitBody.shift()
						splitBody.pop()

						for (let i = 0; i < this.skills.length - 1; i++) {
							const skillInfo = splitBody[i].split(',')
							const afterLevel = this.convertXPtoLVL(parseInt(skillInfo[2]))
							const preLevel = this.convertXPtoLVL(parseInt(skillInfo[2]) - parseInt(skillInfo[0]))

							stats[this.skills[i]] = {
								xp: parseInt(skillInfo[2]),
								rank: parseInt(skillInfo[3]),
								xpGained: parseInt(skillInfo[0]),
								ranksGained: parseInt(skillInfo[1]), // negative ranksGained is good
								levelsGained: (afterLevel - preLevel),
								ehpGained: parseFloat(skillInfo[4])
							}

							stats.overall.levelsGained += (afterLevel - preLevel)
						}

						// .ehp looks a bit different
						const ehpInfo = splitBody[this.skills.length - 1].split(',')
						stats.ehp = {
							hours: parseFloat(ehpInfo[2]),
							ranksGained: parseInt(ehpInfo[1]),
							ehpGained: parseFloat(ehpInfo[0])
						}

						resolve({err, stats})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	compTotal(compID, skill) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=comptotal&competition=${compID}&skill=${skill}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const xp = parseInt(res.body)
						resolve({err, xp})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	compRankings(compID, skill) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=comprankings&competition=${compID}&skill=${skill}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const rankings = []
						const splitBody = res.body.split('\n')
						splitBody.pop()

						for (let i = 0; i < splitBody.length; i++) {
							const info = splitBody[i].split(',')
							if (skill === 'ehp') {
								rankings.push({
									username: info[0],
									startEHP: parseFloat(info[1]),
									currentEHP: parseFloat(info[2]),
									gainedEHP: parseFloat(info[3])
								})
							} else {
								rankings.push({
									username: info[0],
									startXP: parseFloat(info[1]),
									currentXP: parseFloat(info[2]),
									gainedXP: parseFloat(info[3])
								})
							}
						}

						resolve({err, rankings})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	records(skill, timeperiod, count = 30) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `
						${this.cmlURL}?type=records&timeperiod=${timeperiod}&skill=${skill}&count=${count}
					`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const records = []
						const splitBody = res.body.split('\n')
						splitBody.pop()

						for (const line of splitBody) {
							const info = line.split(',')

							if (skill === 'ehp') {
								records.push({
									username: info[0],
									hours: parseFloat(info[1])
								})
							} else {
								records.push({
									username: info[0],
									xp: parseFloat(info[1])
								})
							}
						}

						resolve({err, records})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	currentTop(skill, timeperiod) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `${this.cmlURL}?type=currenttop&timeperiod=${timeperiod}&skill=${skill}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const top = []
						const splitBody = res.body.split('\n')
						splitBody.pop()

						for (let i = 0; i < splitBody.length; i++) {
							const info = splitBody[i].split(',')
							top.push({
								username: info[0],
								gained: parseFloat(info[1])
							})
						}

						resolve({err, top})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	stats(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const url = `
						${this.cmlURL}?multiquery=[{"type": "stats", "player": "${user}"},
						{"type": "virtualhiscoresatplayer", "page": "timeplayed"}]
					`
					const res = await got(url, requestOptions)
					const err = errorHandling(res.body)

					if (!err) {
						const stats = {}
						const [normalStats, ehpStats] = res.body.split('~~')

						const normalStatsSplit = normalStats.split('\n')
						const overallInfo = normalStats.split(',')
						stats.overall = {
							level: 0,
							xp: parseInt(overallInfo[0].split('\n')[1]),
							rank: parseInt(overallInfo[1])
						}

						for (let i = 1; i < this.skills.length - 1; i++) {
							// i = 1 because stats.overall doesnt have level
							// skills.length - 1 because added ehp to osrs skills
							const skillInfo = normalStatsSplit[i + 1].split(',')
							const actualLevel = this.convertXPtoLVL(parseInt(skillInfo[0]), 99)

							stats[this.skills[i]] = {
								level: actualLevel,
								xp: parseInt(skillInfo[0]),
								rank: parseInt(skillInfo[1])
							}

							stats.overall.level += actualLevel
						}

						const ehpInfo = ehpStats.split(',')
						stats.ehp = {
							hours: parseFloat(ehpInfo[2]),
							rank: parseFloat(ehpInfo[0])
						}

						resolve({err, stats})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	ttm(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const multiquery = [
						{type: 'ttm', player: user},
						{type: 'ttmrank'}
					]
					const url = `${this.cmlURL}?multiquery=${JSON.stringify(multiquery)}`
					const res = await got(url, requestOptions)
					const err = errorHandling(res.body)

					if (!err) {
						const ttm = {}
						const splitBody = res.body.split('~~')
						ttm.hours = parseInt(splitBody[0])
						ttm.rank = parseInt(splitBody[1])

						resolve({err, ttm})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	virtualHiscores(user) {
		return new Promise(resolve => {
			;(async () => {
				try {
					const multiquery = [
						{type: 'virtualhiscoresatplayer', player: user, page: 'virtualtotal'},
						{page: 'recordsheld'},
						{page: 'frontpagecount'}
					]
					const url = `${this.cmlURL}?multiquery=${JSON.stringify(multiquery)}`
					const res = await got(url, requestOptions)

					const err = errorHandling(res.body)

					if (!err) {
						const vh = {}
						const splitBody = res.body.split('~~')

						vh.total = {
							level: parseInt(splitBody[0].split(',')[2]),
							rank: parseInt(splitBody[0].split(',')[0])
						}

						vh.recordsHeld = {
							held: parseInt(splitBody[1].split(',')[2]),
							rank: parseInt(splitBody[1].split(',')[0])
						}

						vh.frontpageCount = {
							count: parseInt(splitBody[2].split(',')[2]),
							rank: parseInt(splitBody[2].split(',')[0])
						}

						resolve({err, vh})
					}

					resolve({err})
				} catch (error) {
					resolve({err: error})
				}
			})()
		})
	}

	convertXPtoLVL(xp, cap = 99) {
		// very inefficient, couldnt reverse formula
		// for getting the lvl out of xp..(wish i was good at math)
		// shoutout to http://rsdo.net/rsdonline/guides/Experience%20formula.html
		let points = 0

		for (let lvl = 1; lvl <= cap; lvl++) {
			points += Math.floor(lvl + (300 * Math.pow(2, lvl / 7)))

			if (Math.floor(points / 4) >= xp + 1) {
				return lvl
			}
			// why xp + 1? I HAVE NO FUCKING CLUE
			// I HAVE NO CLUE AND ITS SO FUCKING WEIRD
			// but it works
		}

		return cap // needed if virtual level > 99
	}

	convertLVLtoXP(lvl) {
		let points = 0

		for (let i = 1; i < lvl; i++) {
			points += Math.floor(i + (300 * Math.pow(2, i / 7)))
		}

		return Math.floor(points / 4)
	}
}


text:
<!DOCTYPE HTML>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Savory — Free Website Template, Free HTML5 Template by GetTemplates.co</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="Free HTML5 Website Template by GetTemplates.co" />
	<meta name="keywords" content="free website templates, free html5, free template, free bootstrap, free website template, html5, css3, mobile first, responsive" />
	<meta name="author" content="GetTemplates.co" />

	<meta property="og:title" content=""/>
	<meta property="og:image" content=""/>
	<meta property="og:url" content=""/>
	<meta property="og:site_name" content=""/>
	<meta property="og:description" content=""/>
	<meta name="twitter:title" content="" />
	<meta name="twitter:image" content="" />
	<meta name="twitter:url" content="" />
	<meta name="twitter:card" content="" />

	<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">

	<link rel="stylesheet" href="css/animate.css">

	<link rel="stylesheet" href="css/icomoon.css">

	<link rel="stylesheet" href="css/themify-icons.css">

	<link rel="stylesheet" href="css/bootstrap.css">

	<link rel="stylesheet" href="css/magnific-popup.css">

	<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css">

	<link rel="stylesheet" href="css/owl.carousel.min.css">
	<link rel="stylesheet" href="css/owl.theme.default.min.css">

	<link rel="stylesheet" href="css/style.css">

Savory .

Menu

							Services

Food Catering

Wedding Celebration

Birthday's Celebration

Contact

Reservation

							Hand-crafted by GetTemplates.co

It's our pleasure to serve!

Our Services

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Happy People

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Creative Culinary

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Food Delivery

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Happy People

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Creative Culinary

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

Food Delivery

Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.

“ Their high quality of service makes me back over and over again!”

— John Doe, CEO of XYZ Co.

Subscribe

Be the first to know about the new templates.

					<form class="form-inline">

								Email
								<input type="email" class="form-control" id="email" placeholder="Your Email">

							<button type="submit" class="btn btn-default btn-block">Subscribe</button>

					</form>

Get In Touch

 +1 234 567 890

 info@GetTemplates.co

 Live Chat

Get Social

© 2016 Free HTML5. All Rights Reserved.
						More Templates 模板之家 - Collect from 网页模板


text:
/*
 * Extremely simplified version of the requireJS text plugin
 */

(function() {

var globalRequire = typeof require != "undefined" && require;

define(function (require, exports, module) {
    "use strict";

    exports.load = function (name, req, onLoad, config) {
        //Using special require.nodeRequire, something added by r.js.
        if (globalRequire && globalRequire.nodeRequire)
            onLoad(globalRequire.nodeRequire('fs').readFileSync(req.toUrl(name), 'utf8'));
        else
            require("../lib/net").get(req.toUrl(name), onLoad);
    };
});

})();


text:
<?php

namespace Backend\APIBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * Get all the books
     * @return array
     *
     * @View()
     * @Get("/home")
     */
    public function indexAction()
    {
        return $this->render('BackendAPIBundle:Default:index.html.twig');
    }
}


text:
package com.milaboratory.util;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;

public final class Bit2Array implements java.io.Serializable {
    private static final long serialVersionUID = 1L;

    byte[] data;
    int size;

    public Bit2Array(int length) {
        this.size = length;
        data = new byte[(length + 3) >> 2];
    }

    Bit2Array(int size, byte[] data) {
        //if (data.length != ((size + 3) >> 2))
        //    throw new IllegalArgumentException();
        this.size = size;
        this.data = data;
    }

    public int size() {
        return size;
    }

    public int get(int index) {
        return (data[index >> 2] >>> ((index & 3) << 1)) & 0x3;
    }

    public void set(int index, int value) {
        data[index >> 2] &= ~(0x3 << ((index & 3) << 1));
        data[index >> 2] |= (value & 0x3) << ((index & 3) << 1);
    }

    public Bit2Array clone() {
        return new Bit2Array(size, Arrays.copyOf(data, data.length));
    }

    public Bit2Array extend(int size) {
        if (size < this.size)
            throw new IllegalArgumentException();
        return new Bit2Array(size, Arrays.copyOf(data, (size + 3) >> 2));
    }

    public byte[] toByteArray() {
        byte[] data = new byte[size];
        for (int i = 0; i < size; ++i)
            data[i] = (byte) get(i);
        return data;
    }

    public void copyFrom(Bit2Array other, int otherOffset, int thisOffset, int length) {
        if (thisOffset < 0 || thisOffset + length > size ||
                otherOffset < 0 || otherOffset + length > other.size)
            throw new IndexOutOfBoundsException();

        //TODO optimize
        for (int i = 0; i < length; ++i)
            set(thisOffset + i, other.get(otherOffset + i));
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 47 * hash + Arrays.hashCode(this.data);
        hash = 47 * hash + this.size;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final Bit2Array other = (Bit2Array) obj;
        if (this.size != other.size)
            return false;
        if (!Arrays.equals(this.data, other.data))
            return false;
        return true;
    }

    //TODO optimize
    public Bit2Array getRange(int from, int to) {
        if (from < 0 || (from >= size && size != 0)
                || to < from || to > size)
            throw new IndexOutOfBoundsException("from=" + from + ", to=" + to);

        Bit2Array ret = new Bit2Array(to - from);
        int i = 0;
        for (int j = from; j < to; ++j, ++i)
            ret.set(i, get(j));
        return ret;
    }

    public void writeTo(DataOutput output) throws IOException {
        output.writeInt(size);
        output.write(data);
    }

    public static Bit2Array readFrom(DataInput input) throws IOException {
        int size = input.readInt();
        byte[] buf = new byte[(size + 3) >> 2];
        input.readFully(buf);
        return new Bit2Array(size, buf);
    }

    /*public static Bit2Array wrap(byte[] data, int size) {
        return new Bit2Array(size, data);
    }*/

    public static byte[] extractRawDataArray(Bit2Array array) {
        return array.data;
    }

    public static Bit2Array construct(int size, byte[] data) {
        return new Bit2Array(size, data);
    }
}


text:
package edu.isi.bmkeg.uimaBioC.bin.dev;

import java.io.File;

import org.apache.log4j.Logger;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.resource.metadata.TypeSystemDescription;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.uimafit.factory.AggregateBuilder;
import org.uimafit.factory.AnalysisEngineFactory;
import org.uimafit.factory.CollectionReaderFactory;
import org.uimafit.factory.TypeSystemDescriptionFactory;
import org.uimafit.pipeline.SimplePipeline;

import edu.isi.bmkeg.uimaBioC.uima.out.TabulateBioCAnnotationTypes;
import edu.isi.bmkeg.uimaBioC.uima.out.TabulateNestedBioCAnnotations;
import edu.isi.bmkeg.uimaBioC.uima.readers.BioCCollectionReader;

/**
 * This script runs through serialized JSON files from the model and converts
 * them to VPDMf KEfED models, including the data.
 *
 * @author Gully
 *
 */
public class S06_CountNestedAnnotations {

	public static class Options {

		@Option(name = "-inDir", usage = "Input Directory", required = true, metaVar = "IN-DIRECTORY")
		public File inDir;

		@Option(name = "-outFile", usage = "Output Directory", required = true, metaVar = "OUT-DIRECTORY")
		public File outFile;

		@Option(name = "-annType1", usage = "Output Format", required = true, metaVar = "XML/JSON")
		public String annType1;

		@Option(name = "-annType2", usage = "Output Format", required = true, metaVar = "XML/JSON")
		public String annType2;

	}

	private static Logger logger = Logger
			.getLogger(S06_CountNestedAnnotations.class);

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		Options options = new Options();

		CmdLineParser parser = new CmdLineParser(options);

		try {

			parser.parseArgument(args);

		} catch (CmdLineException e) {

			System.err.println(e.getMessage());
			System.err.print("Arguments: ");
			parser.printSingleLineUsage(System.err);
			System.err.println("\n\n Options: \n");
			parser.printUsage(System.err);
			System.exit(-1);

		}

		if (!options.outFile.getParentFile().exists())
			options.outFile.getParentFile().mkdirs();

		TypeSystemDescription typeSystem = TypeSystemDescriptionFactory
				.createTypeSystemDescription("bioc.TypeSystem");

		CollectionReader cr = CollectionReaderFactory.createCollectionReader(
				BioCCollectionReader.class, typeSystem,
				BioCCollectionReader.INPUT_DIRECTORY, options.inDir,
				BioCCollectionReader.PARAM_FORMAT, BioCCollectionReader.JSON);

		AggregateBuilder builder = new AggregateBuilder();

		builder.add(AnalysisEngineFactory.createPrimitiveDescription(
				TabulateNestedBioCAnnotations.class,
				TabulateNestedBioCAnnotations.PARAM_TITLE,
				options.inDir.getPath(),
				TabulateNestedBioCAnnotations.PARAM_OUTER_ANNOTATION_TYPE,
				options.annType1,
				TabulateNestedBioCAnnotations.PARAM_FILE_PATH,
				options.outFile.getPath(),
				TabulateNestedBioCAnnotations.PARAM_INNER_ANNOTATION_TYPE,
				options.annType2));

		SimplePipeline.runPipeline(cr, builder.createAggregateDescription());

	}

}