repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
DailyGrind/Chain-Reaction
client/src/state/players/actions/creators.js
374
import action from 'src/state/action'; import t from './types'; export const nextPlayer = () => ({ type: t.GET_NEXT_PLAYER }); export const updateCurrentPlayer = current => action(t.SET_CURRENT_PLAYER, { current }); export const playerIsBot = () => action(t.PLAYER_IS_BOT, { isBot: true }); export const playerIsHuman = () => action(t.PLAYER_IS_HUMAN, { isBot: false });
mit
astrapi69/bundle-app-ui
src/main/java/io/github/astrapi69/bundle/app/spring/rest/HttpResponseExtensions.java
2100
package io.github.astrapi69.bundle.app.spring.rest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import com.fasterxml.jackson.core.JsonProcessingException; import io.github.astrapi69.json.JsonStringToObjectExtensions; import io.github.astrapi69.json.ObjectToJsonExtensions; public final class HttpResponseExtensions { private HttpResponseExtensions() { } public static <T> T readEntity(HttpResponse response, final Class<T> clazz) throws IOException { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String json = IOUtils.toString(rd); T object = null; if (StringUtils.isNotEmpty(json)) { object = JsonStringToObjectExtensions.toObject(json, clazz); } return object; } public static <T> List<T> readListEntity(HttpResponse response, final Class<T> clazz) throws IOException { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String json = IOUtils.toString(rd); List<T> object = null; if (StringUtils.isNotEmpty(json)) { object = JsonStringToObjectExtensions.toObjectList(json, clazz); } return object; } public static <T> StringEntity getStringEntity(T object) throws JsonProcessingException, UnsupportedEncodingException { String jsonString = ObjectToJsonExtensions.toJson(object); StringEntity input = new StringEntity(jsonString); input.setContentType("application/json"); return input; } public static <T> HttpPost newHttpPost(String url, T stringEntityObject) throws UnsupportedEncodingException, JsonProcessingException { HttpPost post = new HttpPost(url); StringEntity input = HttpResponseExtensions.getStringEntity(stringEntityObject); post.setEntity(input); return post; } }
mit
davidepedone/spring-social-sample
src/main/java/it/dpedone/social/controller/PostController.java
795
package it.dpedone.social.controller; import org.springframework.social.facebook.api.PagePostData; import org.springframework.social.facebook.api.impl.FacebookTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class PostController { @RequestMapping(value="/updatestatus",method=RequestMethod.GET) public String updateStatus(){ try{ PagePostData pagePost = new PagePostData("pageid"); pagePost.message("Test new message"); FacebookTemplate fb = new FacebookTemplate("accesstoken"); fb.pageOperations().post(pagePost); }catch(Exception e){ System.out.println(e.getMessage()); } return "update"; } }
mit
teoreteetik/api-snippets
rest/subaccounts/voice-example/subaccount-call.6.x.py
551
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account sub_account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" sub_auth_token = "your_auth_token" sub_account_client = Client(sub_account_sid, sub_auth_token) url = 'http://twimlets.com/message?' + \ 'Message%5B0%5D=Hello%20from%20your%20subaccount' # Make a call from your subaccount sub_account_client.api.account.calls.create( from_='+14158141829', to='+16518675309', url=url )
mit
nekikara/book
perfect_ruby.rb
433
#! /usr/bin/env ruby # coding: utf-8 ######### block ########## # 繰り返し以外に用いられるブロック def write_with_lock File.open 'time.txt', 'w' do |f| f.flock File::LOCK_EX yield f f.flock File::LOCK_UN end end write_with_lock do |f| f.puts.Time.now end ### キーワード引数 ### 仮引数の順序 ### alias: メソッドに別名を付ける # Karnel#pはデバッグ用 # NOT p.110~114
mit
OnlyD/Agenda_ILM
src/Agenda_ILM/EstadoBundle/DependencyInjection/Configuration.php
878
<?php namespace Agenda_ILM\EstadoBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('estado'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
mit
elliotcw/Journey
public/app/scripts/services/main.js
8445
'use strict'; angular.module('journey.services', []) .service('journeyService', function ($http) { this.getJourneyInfo = function (journeyOptions) { var params = { 'language': 'en', 'sessionID': 0, 'place_origin': 'London', 'type_origin': 'stop', 'name_origin': journeyOptions.origin, 'place_destination': 'London', 'type_destination': 'stop', 'name_destination': journeyOptions.destination, 'itdDate': journeyOptions.day, 'itdTime': journeyOptions.by }; return $http.get('/api/XML_TRIP_REQUEST2', {params: params}); }; this.getTubeStations = function () { return _.map([ 'Acton Central', 'Acton Town', 'Aldgate', 'Aldgate East', 'All Saints', 'Alperton', 'Amersham', 'Angel', 'Archway', 'Arnos Grove', 'Arsenal', 'Baker Street', 'Balham', 'Bank', 'Barbican', 'Barking', 'Barkingside', 'Barons Court', 'Bayswater', 'Beckton', 'Beckton Park', 'Becontree', 'Belsize Park', 'Bermondsey', 'Bethnal Green', 'Blackfriars', 'Blackhorse Road', 'Blackwall', 'Bond Street', 'Borough Station', 'Boston Manor', 'Bounds Green', 'Bow Church', 'Bow Road', 'Brent Cross', 'Brixton', 'Bromley-by-Bow', 'Brondesbury', 'Brondesbury Park', 'Buckhurst Hill', 'Burnt Oak', 'Caledonian Road', 'Caledonian Road & Barnsbury', 'Camden Road', 'Camden Town', 'Canada Water', 'Canary Wharf', 'Canning Town', 'Cannon Street', 'Canonbury', 'Canons Park', 'Chalfont & Latimer', 'Chalk Farm', 'Chancery Lane', 'Charing Cross', 'Chesham', 'Chigwell', 'Chiswick Park', 'Chorleywood', 'Clapham Common', 'Clapham North', 'Clapham South', 'Cockfosters?', 'Colindale', 'Colliers Wood', 'Covent Garden', 'Crossharbour And London Arena', 'Croxley', 'Custom House for ExCel', 'Cutty Sark', 'Cyprus', 'Dagenham East', 'Dagenham Heathway', 'Dalston Kingsland', 'Debden', 'Debtford Bridge', 'Devons Road', 'Dollis Hill', 'Ealing Broadway', 'Ealing Common', 'Earls Court', 'East Acton', 'East Finchley', 'East Ham', 'East India', 'East Putney', 'Eastcote', 'Edgware', 'Edgware Road', 'Elephant And Castle', 'Elm Park', 'Elverson Road', 'Embankment', 'Epping', 'Euston', 'Euston Square', 'Fairlop', 'Farringdon', 'Finchley', 'Finchley Road', 'Finchley Road And Frognal', 'Finsbury Park', 'Fulham Broadway', 'Gallions Reach', 'Gants Hill', 'Gloucester Road?', 'Golders Green', 'Goldhawk Road', 'Goodge Street', 'Gospel Oak', 'Grange Hill', 'Great Portland Street', 'Green Park', 'Greenford', 'Greenwich', 'Gunnersbury', 'Hackney Central', 'Hackney Wick', 'Hainault', 'Hammersmith', 'Hampstead Heath', 'Hampstead', 'Hanger Lane', 'Harlesden', 'Harrow And Wealdstone', 'Harrow on-the-Hill', 'Hatton Cross', 'Heathrow Terminal 4', 'Heathrow Terminals 1,2,3', 'Hendon Central', 'Heron Quays', 'High Barnet', 'High Street Kensington', 'Highbury & Islington', 'Highgate', 'Hillingdon', 'Holborn', 'Holland Park', 'Holloway Road', 'Homerton', 'Hornchurch', 'Hounslow Central', 'Hounslow East', 'Hounslow West', 'Hyde Park Corner', 'Ickenham', 'Island Gardens', 'Kennington', 'Kensal Green', 'Kensal Rise', 'Kensington (Olympia)', 'Kentish Town', 'Kentish Town West', 'Kenton', 'Kew Gardens', 'Kilburn', 'Kilburn Park', 'King\'s Cross St Pancras', 'Kingsbury ', 'Knightsbridge ', 'Ladbroke Grove ', 'Lambeth North ? ', 'Lancaster Gate ', 'Latimer Road ', 'Leicester Square ', 'Lewisham ', 'Leyton ', 'Leytonstone ', 'Limehouse ', 'Liverpool Street ', 'London Bridge ', 'Loughton ', 'Manor House ', 'Mansion House ', 'Marble Arch ', 'Marylebone ', 'Maida Vale ? ', 'Mile End ', 'Mill Hill East ', 'Monument ', 'Moor Park ', 'Moorgate ', 'Morden ', 'Mornington Crescent ', 'Mudchute ', 'Neasden ', 'New Cross Gate ', 'New Cross ', 'Newbury Park ', 'North Acton ', 'North Ealing ', 'North Greenwich ', 'North Harrow ', 'North Wembley ', 'North Woolwich ', 'Northfields ', 'Northolt ', 'Northwick Park ', 'Northwood ', 'Northwood Hills ', 'Notting Hill Gate ', 'Oakwood ', 'Old Street ', 'Osterley ', 'Oval', 'Oxford Circus ', 'Paddington ', 'Park Royal ', 'Parsons Green ', 'Perivale ', 'Picadilly Circus ', 'Pimlico ', 'Pinner ', 'Plaistow ', 'Poplar ', 'Preston Road ', 'Prince Regent ', 'Pudding Mill Lane ', 'Putney Bridge ', 'Queens Park ', 'Queensbury ', 'Queensway ', 'Ravenscourt Park ', 'Rayners Lane ', 'Redbridge ', 'Regent\'s Park', 'Richmond', 'Rickmansworth', 'Roding Valley', 'Rotherhithe', 'Royal Albert', 'Royal Oak', 'Royal Victoria', 'Ruislip', 'Ruislip Gardens', 'Ruislip Manor', 'Russel Square', 'Seven Sisters', 'Shadwell', 'Shepherd\'s Bush ? ', 'Shoreditch ', 'Silvertown ', 'Sloane Square ', 'Snaresbrook ', 'South Acton ', 'South Ealing ', 'South Harrow ', 'South Kensington ', 'South Kenton ', 'South Quay ', 'South Ruislip ', 'South Wimbledon ? ', 'South Woodford ', 'Southfields ', 'Southgate ', 'Southwark ', 'St.James\'s Park', 'St John\'s Wood', 'St Paul\'s', 'Stamford Brook', 'Stanmore', 'Stepney Green', 'Stockwell', 'Stonebridge Park', 'Stratford', 'Sudbury Hill', 'Sudbury Town', 'Surrey Quays', 'Swiss Cottage', 'Temple', 'Theydon Bois', 'Tooting Bec', 'Tooting Broadway', 'Tottenham Court Road', 'Tottenham Hale', 'Totteridge And Whetstone', 'Tower Gateway', 'Tower Hill', 'Tufnell Park', 'Turnham Green', 'Turnpike Lane', 'Upminster', 'Upminster Bridge', 'Upney', 'Upton Park', 'Uxbridge', 'Vauxhall', 'Victoria', 'Walthamstow Central', 'Wanstead', 'Wapping', 'Warren Street', 'Warwick Avenue', 'Waterloo', 'Watford', 'Wembley Central', 'Wembley Park', 'West Acton', 'West Brompton', 'West Finchley', 'West Ham', 'West Hampstead', 'West Harrow', 'West India Quay', 'West Kensington?', 'West Ruislip', 'Westbourne Park', 'Westferry', 'Westminster', 'White City', 'Whitechapel', 'Willesden Green', 'Willesden Junction', 'Wimbledon?', 'Wimbledon Park', 'Wood Green', 'Woodford', 'Woodside Park' ], function (station) { return { name: station }; }); }; });
mit
Tresint/worldherb
forum/applications/core/interface/ckeditor/ckeditor/plugins/ipscontextmenu/lang/th.js
84
CKEDITOR.plugins.setLang("ipscontextmenu","th",{options:"Context Menu Options"});
mit
shinji-yoshida/Lockables
src/Lockables/AndLockStatus.cs
790
using System; using UniRx; using System.Collections.Generic; using System.Linq; namespace Lockables { public class AndLockStatus : LockStatus { List<LockStatus> statuses = new List<LockStatus>(); bool locked; Subject<bool> lockUpdatedSubject = new Subject<bool>(); public void Add(LockStatus status) { statuses.Add (status); UpdateLockStatus (); status.OnLockUpdatedAsObservable ().Subscribe (_ => UpdateLockStatus ()); } void UpdateLockStatus () { var current = statuses.All (s => s.IsLocked ()); if (this.locked != current) { this.locked = current; lockUpdatedSubject.OnNext (current); } } public bool IsLocked () { return locked; } public IObservable<bool> OnLockUpdatedAsObservable () { return lockUpdatedSubject; } } }
mit
x0156/gh-stats
src/app/stats/traffic/traffic.component.ts
823
import { Component, OnInit,Input } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { StatsService } from 'app/services/stats.service'; @Component({ selector: 'app-traffic', templateUrl: './traffic.component.html', styleUrls: ['./traffic.component.css'] }) export class TrafficComponent implements OnInit { @Input() private config; public clone; public view; public timer = 30; constructor(private stats: StatsService) { } ngOnInit() { this.stats.getTraffic(this.config, 'clones') .subscribe((data) => this.clone = data); this.stats.getTraffic(this.config, 'views') .subscribe((data) => this.view = data); } public stringify(object: any): string { if (object) { return JSON.stringify(object); } else { return '!'; } } }
mit
cordoval/rollerworks-datagrid
tests/DatagridViewTest.php
6558
<?php /* * This file is part of the RollerworksDatagrid package. * * (c) Sebastiaan Stok <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Rollerworks\Component\Datagrid\Tests; use Rollerworks\Component\Datagrid\Column\ColumnInterface; use Rollerworks\Component\Datagrid\Column\HeaderView; use Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface; use Rollerworks\Component\Datagrid\DatagridInterface; use Rollerworks\Component\Datagrid\DatagridView; use Rollerworks\Component\Datagrid\DataRowset; use Rollerworks\Component\Datagrid\Tests\Fixtures\Entity; class DatagridViewTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $rowset; /** * @var DatagridView */ private $gridView; protected function setUp() { $type = $this->getMock(ResolvedColumnTypeInterface::class); $type->expects($this->any()) ->method('getName') ->will($this->returnValue('text')); $datagrid = $this->getMock(DatagridInterface::class); $column = $this->getMock(ColumnInterface::class); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $this->rowset = new DataRowset([ 'e1' => new Entity('entity1'), 'e2' => new Entity('entity2'), ]); $this->gridView = new DatagridView($datagrid, [$column], $this->rowset); $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface'); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $columnHeader = new HeaderView($column, $this->gridView, 'foo'); $column->expects($this->any()) ->method('getName') ->will($this->returnValue('foo')); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $this->gridView->setColumns([$columnHeader]); } public function testHasColumn() { $this->assertTrue($this->gridView->hasColumn('foo')); $this->assertFalse($this->gridView->hasColumn('bar')); $this->assertInstanceOf('Rollerworks\Component\Datagrid\Column\HeaderView', $this->gridView->getColumn('foo')); } public function testGetColumn() { $this->assertInstanceOf('Rollerworks\Component\Datagrid\Column\HeaderView', $this->gridView->getColumn('foo')); $this->setExpectedException('Rollerworks\Component\Datagrid\Exception\InvalidArgumentException'); $this->gridView->getColumn('bar'); } public function testAddColumn() { $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface'); $type->expects($this->any()) ->method('getName') ->will($this->returnValue('text')); $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface'); $column->expects($this->any()) ->method('getName') ->will($this->returnValue('bar')); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $columnHeader = new HeaderView($column, $this->gridView, 'bar'); $this->gridView->addColumn($columnHeader); $this->assertTrue($this->gridView->hasColumn('foo')); $this->assertTrue($this->gridView->hasColumn('bar')); $this->assertFalse($this->gridView->hasColumn('bla')); } public function testRemoveColumn() { $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface'); $type->expects($this->any()) ->method('getName') ->will($this->returnValue('text')); $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface'); $column->expects($this->any()) ->method('getName') ->will($this->returnValue('bar')); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $columnHeader = new HeaderView($column, $this->gridView, 'bar'); $this->gridView->addColumn($columnHeader); $this->gridView->removeColumn('foo'); $this->assertFalse($this->gridView->hasColumn('foo')); $this->assertTrue($this->gridView->hasColumn('bar')); } public function testClearColumns() { $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface'); $type->expects($this->any()) ->method('getName') ->will($this->returnValue('text')); $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface'); $column->expects($this->any()) ->method('getName') ->will($this->returnValue('bar')); $column->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); $columnHeader = new HeaderView($column, $this->gridView, 'bar'); $this->gridView->addColumn($columnHeader); $this->gridView->clearColumns(); $this->assertFalse($this->gridView->hasColumn('foo')); $this->assertFalse($this->gridView->hasColumn('bar')); } public function testGetCanGetVariablesWhenNoneWereSet() { $this->assertEquals([], $this->gridView->getVars()); $this->assertNull($this->gridView->getVar('foo')); $this->assertEquals('bar', $this->gridView->getVar('foo', 'bar')); } public function testGetGetVariablesWhenSet() { $this->gridView->setVar('foo', 'bar'); $this->gridView->setVar('name', 'test'); $this->gridView->setVar('empty', null); $this->assertEquals(['foo' => 'bar', 'name' => 'test', 'empty' => null], $this->gridView->getVars()); $this->assertEquals('bar', $this->gridView->getVar('foo')); $this->assertEquals('test', $this->gridView->getVar('name')); $this->assertEquals('test', $this->gridView->getVar('name')); $this->assertNull($this->gridView->getVar('bar')); // This ensures null values are checked properly. $this->assertNull($this->gridView->getVar('empty', 'overwrite')); } public function testCount() { $this->assertCount(2, $this->gridView); } }
mit
trademachines/ecd
spec/lambda/core/config-modifiers.spec.ts
4473
import { DecryptSecureValuesConfigModifier, EnvironmentFromHashConfigModifier, PortMappingFromStringConfigModifier } from '../../../src/lambda/core/config-modifiers'; describe('Config modifications', () => { describe('modify environment vars', () => { let envFromHashModifier; beforeEach(() => { envFromHashModifier = new EnvironmentFromHashConfigModifier(); }); it('modifies environments defined as plain object', (done) => { const config = { containerDefinitions: [ { environment: { foo: 'bar', bar: true, baz: 3.14 } } ] }; envFromHashModifier.modify(config) .then((conf) => { expect(conf.containerDefinitions[0].environment).toEqual([ { name: 'foo', value: 'bar' }, { name: 'bar', value: true }, { name: 'baz', value: 3.14 }, ]); }) .then(done) .catch(done.fail); }); it('does not modify environments defined as array', (done) => { const config = { containerDefinitions: [ { environment: [1, 2, 3] } ] }; envFromHashModifier.modify(config) .then((conf) => { expect(conf.containerDefinitions[0].environment).toEqual([1, 2, 3]); }) .then(done) .catch(done.fail); }); }); describe('modify port mappings', () => { let portsFromStringModifier; beforeEach(() => { portsFromStringModifier = new PortMappingFromStringConfigModifier(); }); it('modifies portMappings defined as strings', (done) => { const config = { containerDefinitions: [ { portMappings: ["80"] } ] }; portsFromStringModifier.modify(config) .then((conf) => { expect(conf.containerDefinitions[0].portMappings).toEqual([ { containerPort: 80, hostPort: 0 }, ]); }) .then(done) .catch(done.fail); }); it('modifies portMappings defined as single number', (done) => { const config = { containerDefinitions: [ { portMappings: [80] } ] }; portsFromStringModifier.modify(config) .then((conf) => { expect(conf.containerDefinitions[0].portMappings).toEqual([ { containerPort: 80, hostPort: 0 }, ]); }) .then(done) .catch(done.fail); }); it('modifies portMappings defined as string with fixed host port', (done) => { const config = { containerDefinitions: [ { portMappings: ["8080:80"] } ] }; portsFromStringModifier.modify(config) .then((conf) => { expect(conf.containerDefinitions[0].portMappings).toEqual([ { containerPort: 80, hostPort: 8080 }, ]); }) .then(done) .catch(done.fail); }); }); describe('decrypting secure values', () => { let decryptSecureValuesModifier; let kms; let kmsDecryptedValue; beforeEach(() => { kms = { decrypt: () => ({ promise: () => Promise.resolve({ Plaintext: new Buffer(kmsDecryptedValue) }) }) }; decryptSecureValuesModifier = new DecryptSecureValuesConfigModifier(kms); }); it('decrypts plain objects with one single key named \'secure\'', (done) => { kmsDecryptedValue = 'kms-decrypted'; const encryptedValue = { secure: 'encrypted' }; const json = { 'scalar': encryptedValue, 'array': ['one', 'two', encryptedValue], 'object': { 'scalar': encryptedValue, 'array': ['three', encryptedValue], 'nested': { 'scalar': encryptedValue } } }; decryptSecureValuesModifier.modify(json) .then(config => { expect(config).toEqual(jasmine.objectContaining({ 'scalar': kmsDecryptedValue, 'array': ['one', 'two', kmsDecryptedValue], 'object': { 'scalar': kmsDecryptedValue, 'array': ['three', kmsDecryptedValue], 'nested': { 'scalar': kmsDecryptedValue } } })); }) .then(done) .catch(done.fail); }); }); });
mit
maiha/ircbot
lib/ircbot/client/eventable.rb
471
module Ircbot class Client include Extlib::Hook class << self def event(name, &block) name = "on_#{name}".intern unless instance_methods.include?(name.to_s) define_method(name){|m|} end before name, &block end end # escape from nil black hole private def method_missing(name, *args) raise NameError, "undefined local variable or method `#{name}' for #{self}" end end end
mit
hardikhirapara91/java-se-core
002_Comments/Documentation/DocCommentDemo/src/main/java/com/hardik/javase/App.java
416
package com.hardik.javase; /** * Java Documentation Comment Example * * The documentation comment is used to create documentation API. To create * documentation API, you need to use javadoc tool. * * @author HARDIK HIRAPARA */ public class App { /** * This is main method of App class * * @param args */ public static void main(String[] args) { System.out.println("Multi Line Comment."); } }
mit
GalacticGlum/memescraper
src/googlememe_scraper.py
1674
from bs4 import BeautifulSoup import requests import urllib import time import json import link_shortener class GoogleMemeScraper(): def __init__(self): self.header = { 'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36" } self.baseUrl = "https://www.google.com/search?q={0}&source=lnms&tbm=isch" self.query_set = self.__load_queryset() self.scrape_event = [] def __scrape_query(self, query): if query == "": print ("GoogleMemeScraper::scape_query: query value was empty!") return query_url = self.baseUrl.format(query) page = BeautifulSoup(urllib.request.urlopen(urllib.request.Request(query_url, headers = self.header)), 'html.parser') links = [] for attribute in page.find_all("div", {"class" : "rg_meta"}): links.append(json.loads(attribute.text)["ou"]) if self.shorten_links: links = set(links) links = link_shortener.shorten_urls(links) for callback in self.scrape_event: callback(links) return links def start(self, sleepTime, shorten_links, queriesAmount = -1): scrapedLinks = [] self.shorten_links = shorten_links if queriesAmount == 0: return scrapedLinks if queriesAmount < 0: queriesAmount = len(self.query_set) for i in range(queriesAmount): scrapedLinks += self.__scrape_query(self.query_set[i]) time.sleep(sleepTime) return scrapedLinks def __load_queryset(self): with open('data/google_queryset.json') as file: contents = file.read() jsonobject = json.loads(contents) query_list = [] for query in jsonobject: query_list.append(urllib.parse.quote(query)) return query_list
mit
paulot/NodeVector
node-0.12.0/deps/v8/src/heap/spaces.cc
101579
// Copyright 2011 the V8 project 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 "src/v8.h" #include "src/base/platform/platform.h" #include "src/full-codegen.h" #include "src/heap/mark-compact.h" #include "src/macro-assembler.h" #include "src/msan.h" namespace v8 { namespace internal { // ---------------------------------------------------------------------------- // HeapObjectIterator HeapObjectIterator::HeapObjectIterator(PagedSpace* space) { // You can't actually iterate over the anchor page. It is not a real page, // just an anchor for the double linked page list. Initialize as if we have // reached the end of the anchor page, then the first iteration will move on // to the first page. Initialize(space, NULL, NULL, kAllPagesInSpace, NULL); } HeapObjectIterator::HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func) { // You can't actually iterate over the anchor page. It is not a real page, // just an anchor for the double linked page list. Initialize the current // address and end as NULL, then the first iteration will move on // to the first page. Initialize(space, NULL, NULL, kAllPagesInSpace, size_func); } HeapObjectIterator::HeapObjectIterator(Page* page, HeapObjectCallback size_func) { Space* owner = page->owner(); DCHECK(owner == page->heap()->old_pointer_space() || owner == page->heap()->old_data_space() || owner == page->heap()->map_space() || owner == page->heap()->cell_space() || owner == page->heap()->property_cell_space() || owner == page->heap()->code_space()); Initialize(reinterpret_cast<PagedSpace*>(owner), page->area_start(), page->area_end(), kOnePageOnly, size_func); DCHECK(page->WasSweptPrecisely() || (static_cast<PagedSpace*>(owner)->swept_precisely() && page->SweepingCompleted())); } void HeapObjectIterator::Initialize(PagedSpace* space, Address cur, Address end, HeapObjectIterator::PageMode mode, HeapObjectCallback size_f) { // Check that we actually can iterate this space. DCHECK(space->swept_precisely()); space_ = space; cur_addr_ = cur; cur_end_ = end; page_mode_ = mode; size_func_ = size_f; } // We have hit the end of the page and should advance to the next block of // objects. This happens at the end of the page. bool HeapObjectIterator::AdvanceToNextPage() { DCHECK(cur_addr_ == cur_end_); if (page_mode_ == kOnePageOnly) return false; Page* cur_page; if (cur_addr_ == NULL) { cur_page = space_->anchor(); } else { cur_page = Page::FromAddress(cur_addr_ - 1); DCHECK(cur_addr_ == cur_page->area_end()); } cur_page = cur_page->next_page(); if (cur_page == space_->anchor()) return false; cur_addr_ = cur_page->area_start(); cur_end_ = cur_page->area_end(); DCHECK(cur_page->WasSweptPrecisely() || (static_cast<PagedSpace*>(cur_page->owner())->swept_precisely() && cur_page->SweepingCompleted())); return true; } // ----------------------------------------------------------------------------- // CodeRange CodeRange::CodeRange(Isolate* isolate) : isolate_(isolate), code_range_(NULL), free_list_(0), allocation_list_(0), current_allocation_block_index_(0) {} bool CodeRange::SetUp(size_t requested) { DCHECK(code_range_ == NULL); if (requested == 0) { // When a target requires the code range feature, we put all code objects // in a kMaximalCodeRangeSize range of virtual address space, so that // they can call each other with near calls. if (kRequiresCodeRange) { requested = kMaximalCodeRangeSize; } else { return true; } } DCHECK(!kRequiresCodeRange || requested <= kMaximalCodeRangeSize); code_range_ = new base::VirtualMemory(requested); CHECK(code_range_ != NULL); if (!code_range_->IsReserved()) { delete code_range_; code_range_ = NULL; return false; } // We are sure that we have mapped a block of requested addresses. DCHECK(code_range_->size() == requested); LOG(isolate_, NewEvent("CodeRange", code_range_->address(), requested)); Address base = reinterpret_cast<Address>(code_range_->address()); Address aligned_base = RoundUp(reinterpret_cast<Address>(code_range_->address()), MemoryChunk::kAlignment); size_t size = code_range_->size() - (aligned_base - base); allocation_list_.Add(FreeBlock(aligned_base, size)); current_allocation_block_index_ = 0; return true; } int CodeRange::CompareFreeBlockAddress(const FreeBlock* left, const FreeBlock* right) { // The entire point of CodeRange is that the difference between two // addresses in the range can be represented as a signed 32-bit int, // so the cast is semantically correct. return static_cast<int>(left->start - right->start); } bool CodeRange::GetNextAllocationBlock(size_t requested) { for (current_allocation_block_index_++; current_allocation_block_index_ < allocation_list_.length(); current_allocation_block_index_++) { if (requested <= allocation_list_[current_allocation_block_index_].size) { return true; // Found a large enough allocation block. } } // Sort and merge the free blocks on the free list and the allocation list. free_list_.AddAll(allocation_list_); allocation_list_.Clear(); free_list_.Sort(&CompareFreeBlockAddress); for (int i = 0; i < free_list_.length();) { FreeBlock merged = free_list_[i]; i++; // Add adjacent free blocks to the current merged block. while (i < free_list_.length() && free_list_[i].start == merged.start + merged.size) { merged.size += free_list_[i].size; i++; } if (merged.size > 0) { allocation_list_.Add(merged); } } free_list_.Clear(); for (current_allocation_block_index_ = 0; current_allocation_block_index_ < allocation_list_.length(); current_allocation_block_index_++) { if (requested <= allocation_list_[current_allocation_block_index_].size) { return true; // Found a large enough allocation block. } } current_allocation_block_index_ = 0; // Code range is full or too fragmented. return false; } Address CodeRange::AllocateRawMemory(const size_t requested_size, const size_t commit_size, size_t* allocated) { DCHECK(commit_size <= requested_size); DCHECK(current_allocation_block_index_ < allocation_list_.length()); if (requested_size > allocation_list_[current_allocation_block_index_].size) { // Find an allocation block large enough. if (!GetNextAllocationBlock(requested_size)) return NULL; } // Commit the requested memory at the start of the current allocation block. size_t aligned_requested = RoundUp(requested_size, MemoryChunk::kAlignment); FreeBlock current = allocation_list_[current_allocation_block_index_]; if (aligned_requested >= (current.size - Page::kPageSize)) { // Don't leave a small free block, useless for a large object or chunk. *allocated = current.size; } else { *allocated = aligned_requested; } DCHECK(*allocated <= current.size); DCHECK(IsAddressAligned(current.start, MemoryChunk::kAlignment)); if (!isolate_->memory_allocator()->CommitExecutableMemory( code_range_, current.start, commit_size, *allocated)) { *allocated = 0; return NULL; } allocation_list_[current_allocation_block_index_].start += *allocated; allocation_list_[current_allocation_block_index_].size -= *allocated; if (*allocated == current.size) { // This block is used up, get the next one. if (!GetNextAllocationBlock(0)) return NULL; } return current.start; } bool CodeRange::CommitRawMemory(Address start, size_t length) { return isolate_->memory_allocator()->CommitMemory(start, length, EXECUTABLE); } bool CodeRange::UncommitRawMemory(Address start, size_t length) { return code_range_->Uncommit(start, length); } void CodeRange::FreeRawMemory(Address address, size_t length) { DCHECK(IsAddressAligned(address, MemoryChunk::kAlignment)); free_list_.Add(FreeBlock(address, length)); code_range_->Uncommit(address, length); } void CodeRange::TearDown() { delete code_range_; // Frees all memory in the virtual memory range. code_range_ = NULL; free_list_.Free(); allocation_list_.Free(); } // ----------------------------------------------------------------------------- // MemoryAllocator // MemoryAllocator::MemoryAllocator(Isolate* isolate) : isolate_(isolate), capacity_(0), capacity_executable_(0), size_(0), size_executable_(0), lowest_ever_allocated_(reinterpret_cast<void*>(-1)), highest_ever_allocated_(reinterpret_cast<void*>(0)) {} bool MemoryAllocator::SetUp(intptr_t capacity, intptr_t capacity_executable) { capacity_ = RoundUp(capacity, Page::kPageSize); capacity_executable_ = RoundUp(capacity_executable, Page::kPageSize); DCHECK_GE(capacity_, capacity_executable_); size_ = 0; size_executable_ = 0; return true; } void MemoryAllocator::TearDown() { // Check that spaces were torn down before MemoryAllocator. DCHECK(size_ == 0); // TODO(gc) this will be true again when we fix FreeMemory. // DCHECK(size_executable_ == 0); capacity_ = 0; capacity_executable_ = 0; } bool MemoryAllocator::CommitMemory(Address base, size_t size, Executability executable) { if (!base::VirtualMemory::CommitRegion(base, size, executable == EXECUTABLE)) { return false; } UpdateAllocatedSpaceLimits(base, base + size); return true; } void MemoryAllocator::FreeMemory(base::VirtualMemory* reservation, Executability executable) { // TODO(gc) make code_range part of memory allocator? DCHECK(reservation->IsReserved()); size_t size = reservation->size(); DCHECK(size_ >= size); size_ -= size; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); if (executable == EXECUTABLE) { DCHECK(size_executable_ >= size); size_executable_ -= size; } // Code which is part of the code-range does not have its own VirtualMemory. DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->contains( static_cast<Address>(reservation->address()))); DCHECK(executable == NOT_EXECUTABLE || isolate_->code_range() == NULL || !isolate_->code_range()->valid()); reservation->Release(); } void MemoryAllocator::FreeMemory(Address base, size_t size, Executability executable) { // TODO(gc) make code_range part of memory allocator? DCHECK(size_ >= size); size_ -= size; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); if (executable == EXECUTABLE) { DCHECK(size_executable_ >= size); size_executable_ -= size; } if (isolate_->code_range() != NULL && isolate_->code_range()->contains(static_cast<Address>(base))) { DCHECK(executable == EXECUTABLE); isolate_->code_range()->FreeRawMemory(base, size); } else { DCHECK(executable == NOT_EXECUTABLE || isolate_->code_range() == NULL || !isolate_->code_range()->valid()); bool result = base::VirtualMemory::ReleaseRegion(base, size); USE(result); DCHECK(result); } } Address MemoryAllocator::ReserveAlignedMemory(size_t size, size_t alignment, base::VirtualMemory* controller) { base::VirtualMemory reservation(size, alignment); if (!reservation.IsReserved()) return NULL; size_ += reservation.size(); Address base = RoundUp(static_cast<Address>(reservation.address()), alignment); controller->TakeControl(&reservation); return base; } Address MemoryAllocator::AllocateAlignedMemory( size_t reserve_size, size_t commit_size, size_t alignment, Executability executable, base::VirtualMemory* controller) { DCHECK(commit_size <= reserve_size); base::VirtualMemory reservation; Address base = ReserveAlignedMemory(reserve_size, alignment, &reservation); if (base == NULL) return NULL; if (executable == EXECUTABLE) { if (!CommitExecutableMemory(&reservation, base, commit_size, reserve_size)) { base = NULL; } } else { if (reservation.Commit(base, commit_size, false)) { UpdateAllocatedSpaceLimits(base, base + commit_size); } else { base = NULL; } } if (base == NULL) { // Failed to commit the body. Release the mapping and any partially // commited regions inside it. reservation.Release(); return NULL; } controller->TakeControl(&reservation); return base; } void Page::InitializeAsAnchor(PagedSpace* owner) { set_owner(owner); set_prev_page(this); set_next_page(this); } NewSpacePage* NewSpacePage::Initialize(Heap* heap, Address start, SemiSpace* semi_space) { Address area_start = start + NewSpacePage::kObjectStartOffset; Address area_end = start + Page::kPageSize; MemoryChunk* chunk = MemoryChunk::Initialize(heap, start, Page::kPageSize, area_start, area_end, NOT_EXECUTABLE, semi_space); chunk->set_next_chunk(NULL); chunk->set_prev_chunk(NULL); chunk->initialize_scan_on_scavenge(true); bool in_to_space = (semi_space->id() != kFromSpace); chunk->SetFlag(in_to_space ? MemoryChunk::IN_TO_SPACE : MemoryChunk::IN_FROM_SPACE); DCHECK(!chunk->IsFlagSet(in_to_space ? MemoryChunk::IN_FROM_SPACE : MemoryChunk::IN_TO_SPACE)); NewSpacePage* page = static_cast<NewSpacePage*>(chunk); heap->incremental_marking()->SetNewSpacePageFlags(page); return page; } void NewSpacePage::InitializeAsAnchor(SemiSpace* semi_space) { set_owner(semi_space); set_next_chunk(this); set_prev_chunk(this); // Flags marks this invalid page as not being in new-space. // All real new-space pages will be in new-space. SetFlags(0, ~0); } MemoryChunk* MemoryChunk::Initialize(Heap* heap, Address base, size_t size, Address area_start, Address area_end, Executability executable, Space* owner) { MemoryChunk* chunk = FromAddress(base); DCHECK(base == chunk->address()); chunk->heap_ = heap; chunk->size_ = size; chunk->area_start_ = area_start; chunk->area_end_ = area_end; chunk->flags_ = 0; chunk->set_owner(owner); chunk->InitializeReservedMemory(); chunk->slots_buffer_ = NULL; chunk->skip_list_ = NULL; chunk->write_barrier_counter_ = kWriteBarrierCounterGranularity; chunk->progress_bar_ = 0; chunk->high_water_mark_ = static_cast<int>(area_start - base); chunk->set_parallel_sweeping(SWEEPING_DONE); chunk->available_in_small_free_list_ = 0; chunk->available_in_medium_free_list_ = 0; chunk->available_in_large_free_list_ = 0; chunk->available_in_huge_free_list_ = 0; chunk->non_available_small_blocks_ = 0; chunk->ResetLiveBytes(); Bitmap::Clear(chunk); chunk->initialize_scan_on_scavenge(false); chunk->SetFlag(WAS_SWEPT_PRECISELY); DCHECK(OFFSET_OF(MemoryChunk, flags_) == kFlagsOffset); DCHECK(OFFSET_OF(MemoryChunk, live_byte_count_) == kLiveBytesOffset); if (executable == EXECUTABLE) { chunk->SetFlag(IS_EXECUTABLE); } if (owner == heap->old_data_space()) { chunk->SetFlag(CONTAINS_ONLY_DATA); } return chunk; } // Commit MemoryChunk area to the requested size. bool MemoryChunk::CommitArea(size_t requested) { size_t guard_size = IsFlagSet(IS_EXECUTABLE) ? MemoryAllocator::CodePageGuardSize() : 0; size_t header_size = area_start() - address() - guard_size; size_t commit_size = RoundUp(header_size + requested, base::OS::CommitPageSize()); size_t committed_size = RoundUp(header_size + (area_end() - area_start()), base::OS::CommitPageSize()); if (commit_size > committed_size) { // Commit size should be less or equal than the reserved size. DCHECK(commit_size <= size() - 2 * guard_size); // Append the committed area. Address start = address() + committed_size + guard_size; size_t length = commit_size - committed_size; if (reservation_.IsReserved()) { Executability executable = IsFlagSet(IS_EXECUTABLE) ? EXECUTABLE : NOT_EXECUTABLE; if (!heap()->isolate()->memory_allocator()->CommitMemory(start, length, executable)) { return false; } } else { CodeRange* code_range = heap_->isolate()->code_range(); DCHECK(code_range != NULL && code_range->valid() && IsFlagSet(IS_EXECUTABLE)); if (!code_range->CommitRawMemory(start, length)) return false; } if (Heap::ShouldZapGarbage()) { heap_->isolate()->memory_allocator()->ZapBlock(start, length); } } else if (commit_size < committed_size) { DCHECK(commit_size > 0); // Shrink the committed area. size_t length = committed_size - commit_size; Address start = address() + committed_size + guard_size - length; if (reservation_.IsReserved()) { if (!reservation_.Uncommit(start, length)) return false; } else { CodeRange* code_range = heap_->isolate()->code_range(); DCHECK(code_range != NULL && code_range->valid() && IsFlagSet(IS_EXECUTABLE)); if (!code_range->UncommitRawMemory(start, length)) return false; } } area_end_ = area_start_ + requested; return true; } void MemoryChunk::InsertAfter(MemoryChunk* other) { MemoryChunk* other_next = other->next_chunk(); set_next_chunk(other_next); set_prev_chunk(other); other_next->set_prev_chunk(this); other->set_next_chunk(this); } void MemoryChunk::Unlink() { MemoryChunk* next_element = next_chunk(); MemoryChunk* prev_element = prev_chunk(); next_element->set_prev_chunk(prev_element); prev_element->set_next_chunk(next_element); set_prev_chunk(NULL); set_next_chunk(NULL); } MemoryChunk* MemoryAllocator::AllocateChunk(intptr_t reserve_area_size, intptr_t commit_area_size, Executability executable, Space* owner) { DCHECK(commit_area_size <= reserve_area_size); size_t chunk_size; Heap* heap = isolate_->heap(); Address base = NULL; base::VirtualMemory reservation; Address area_start = NULL; Address area_end = NULL; // // MemoryChunk layout: // // Executable // +----------------------------+<- base aligned with MemoryChunk::kAlignment // | Header | // +----------------------------+<- base + CodePageGuardStartOffset // | Guard | // +----------------------------+<- area_start_ // | Area | // +----------------------------+<- area_end_ (area_start + commit_area_size) // | Committed but not used | // +----------------------------+<- aligned at OS page boundary // | Reserved but not committed | // +----------------------------+<- aligned at OS page boundary // | Guard | // +----------------------------+<- base + chunk_size // // Non-executable // +----------------------------+<- base aligned with MemoryChunk::kAlignment // | Header | // +----------------------------+<- area_start_ (base + kObjectStartOffset) // | Area | // +----------------------------+<- area_end_ (area_start + commit_area_size) // | Committed but not used | // +----------------------------+<- aligned at OS page boundary // | Reserved but not committed | // +----------------------------+<- base + chunk_size // if (executable == EXECUTABLE) { chunk_size = RoundUp(CodePageAreaStartOffset() + reserve_area_size, base::OS::CommitPageSize()) + CodePageGuardSize(); // Check executable memory limit. if (size_executable_ + chunk_size > capacity_executable_) { LOG(isolate_, StringEvent("MemoryAllocator::AllocateRawMemory", "V8 Executable Allocation capacity exceeded")); return NULL; } // Size of header (not executable) plus area (executable). size_t commit_size = RoundUp(CodePageGuardStartOffset() + commit_area_size, base::OS::CommitPageSize()); // Allocate executable memory either from code range or from the // OS. if (isolate_->code_range() != NULL && isolate_->code_range()->valid()) { base = isolate_->code_range()->AllocateRawMemory(chunk_size, commit_size, &chunk_size); DCHECK( IsAligned(reinterpret_cast<intptr_t>(base), MemoryChunk::kAlignment)); if (base == NULL) return NULL; size_ += chunk_size; // Update executable memory size. size_executable_ += chunk_size; } else { base = AllocateAlignedMemory(chunk_size, commit_size, MemoryChunk::kAlignment, executable, &reservation); if (base == NULL) return NULL; // Update executable memory size. size_executable_ += reservation.size(); } if (Heap::ShouldZapGarbage()) { ZapBlock(base, CodePageGuardStartOffset()); ZapBlock(base + CodePageAreaStartOffset(), commit_area_size); } area_start = base + CodePageAreaStartOffset(); area_end = area_start + commit_area_size; } else { chunk_size = RoundUp(MemoryChunk::kObjectStartOffset + reserve_area_size, base::OS::CommitPageSize()); size_t commit_size = RoundUp(MemoryChunk::kObjectStartOffset + commit_area_size, base::OS::CommitPageSize()); base = AllocateAlignedMemory(chunk_size, commit_size, MemoryChunk::kAlignment, executable, &reservation); if (base == NULL) return NULL; if (Heap::ShouldZapGarbage()) { ZapBlock(base, Page::kObjectStartOffset + commit_area_size); } area_start = base + Page::kObjectStartOffset; area_end = area_start + commit_area_size; } // Use chunk_size for statistics and callbacks because we assume that they // treat reserved but not-yet committed memory regions of chunks as allocated. isolate_->counters()->memory_allocated()->Increment( static_cast<int>(chunk_size)); LOG(isolate_, NewEvent("MemoryChunk", base, chunk_size)); if (owner != NULL) { ObjectSpace space = static_cast<ObjectSpace>(1 << owner->identity()); PerformAllocationCallback(space, kAllocationActionAllocate, chunk_size); } MemoryChunk* result = MemoryChunk::Initialize( heap, base, chunk_size, area_start, area_end, executable, owner); result->set_reserved_memory(&reservation); MSAN_MEMORY_IS_INITIALIZED_IN_JIT(base, chunk_size); return result; } void Page::ResetFreeListStatistics() { non_available_small_blocks_ = 0; available_in_small_free_list_ = 0; available_in_medium_free_list_ = 0; available_in_large_free_list_ = 0; available_in_huge_free_list_ = 0; } Page* MemoryAllocator::AllocatePage(intptr_t size, PagedSpace* owner, Executability executable) { MemoryChunk* chunk = AllocateChunk(size, size, executable, owner); if (chunk == NULL) return NULL; return Page::Initialize(isolate_->heap(), chunk, executable, owner); } LargePage* MemoryAllocator::AllocateLargePage(intptr_t object_size, Space* owner, Executability executable) { MemoryChunk* chunk = AllocateChunk(object_size, object_size, executable, owner); if (chunk == NULL) return NULL; return LargePage::Initialize(isolate_->heap(), chunk); } void MemoryAllocator::Free(MemoryChunk* chunk) { LOG(isolate_, DeleteEvent("MemoryChunk", chunk)); if (chunk->owner() != NULL) { ObjectSpace space = static_cast<ObjectSpace>(1 << chunk->owner()->identity()); PerformAllocationCallback(space, kAllocationActionFree, chunk->size()); } isolate_->heap()->RememberUnmappedPage(reinterpret_cast<Address>(chunk), chunk->IsEvacuationCandidate()); delete chunk->slots_buffer(); delete chunk->skip_list(); base::VirtualMemory* reservation = chunk->reserved_memory(); if (reservation->IsReserved()) { FreeMemory(reservation, chunk->executable()); } else { FreeMemory(chunk->address(), chunk->size(), chunk->executable()); } } bool MemoryAllocator::CommitBlock(Address start, size_t size, Executability executable) { if (!CommitMemory(start, size, executable)) return false; if (Heap::ShouldZapGarbage()) { ZapBlock(start, size); } isolate_->counters()->memory_allocated()->Increment(static_cast<int>(size)); return true; } bool MemoryAllocator::UncommitBlock(Address start, size_t size) { if (!base::VirtualMemory::UncommitRegion(start, size)) return false; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); return true; } void MemoryAllocator::ZapBlock(Address start, size_t size) { for (size_t s = 0; s + kPointerSize <= size; s += kPointerSize) { Memory::Address_at(start + s) = kZapValue; } } void MemoryAllocator::PerformAllocationCallback(ObjectSpace space, AllocationAction action, size_t size) { for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { MemoryAllocationCallbackRegistration registration = memory_allocation_callbacks_[i]; if ((registration.space & space) == space && (registration.action & action) == action) registration.callback(space, action, static_cast<int>(size)); } } bool MemoryAllocator::MemoryAllocationCallbackRegistered( MemoryAllocationCallback callback) { for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { if (memory_allocation_callbacks_[i].callback == callback) return true; } return false; } void MemoryAllocator::AddMemoryAllocationCallback( MemoryAllocationCallback callback, ObjectSpace space, AllocationAction action) { DCHECK(callback != NULL); MemoryAllocationCallbackRegistration registration(callback, space, action); DCHECK(!MemoryAllocator::MemoryAllocationCallbackRegistered(callback)); return memory_allocation_callbacks_.Add(registration); } void MemoryAllocator::RemoveMemoryAllocationCallback( MemoryAllocationCallback callback) { DCHECK(callback != NULL); for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { if (memory_allocation_callbacks_[i].callback == callback) { memory_allocation_callbacks_.Remove(i); return; } } UNREACHABLE(); } #ifdef DEBUG void MemoryAllocator::ReportStatistics() { float pct = static_cast<float>(capacity_ - size_) / capacity_; PrintF(" capacity: %" V8_PTR_PREFIX "d" ", used: %" V8_PTR_PREFIX "d" ", available: %%%d\n\n", capacity_, size_, static_cast<int>(pct * 100)); } #endif int MemoryAllocator::CodePageGuardStartOffset() { // We are guarding code pages: the first OS page after the header // will be protected as non-writable. return RoundUp(Page::kObjectStartOffset, base::OS::CommitPageSize()); } int MemoryAllocator::CodePageGuardSize() { return static_cast<int>(base::OS::CommitPageSize()); } int MemoryAllocator::CodePageAreaStartOffset() { // We are guarding code pages: the first OS page after the header // will be protected as non-writable. return CodePageGuardStartOffset() + CodePageGuardSize(); } int MemoryAllocator::CodePageAreaEndOffset() { // We are guarding code pages: the last OS page will be protected as // non-writable. return Page::kPageSize - static_cast<int>(base::OS::CommitPageSize()); } bool MemoryAllocator::CommitExecutableMemory(base::VirtualMemory* vm, Address start, size_t commit_size, size_t reserved_size) { // Commit page header (not executable). if (!vm->Commit(start, CodePageGuardStartOffset(), false)) { return false; } // Create guard page after the header. if (!vm->Guard(start + CodePageGuardStartOffset())) { return false; } // Commit page body (executable). if (!vm->Commit(start + CodePageAreaStartOffset(), commit_size - CodePageGuardStartOffset(), true)) { return false; } // Create guard page before the end. if (!vm->Guard(start + reserved_size - CodePageGuardSize())) { return false; } UpdateAllocatedSpaceLimits(start, start + CodePageAreaStartOffset() + commit_size - CodePageGuardStartOffset()); return true; } // ----------------------------------------------------------------------------- // MemoryChunk implementation void MemoryChunk::IncrementLiveBytesFromMutator(Address address, int by) { MemoryChunk* chunk = MemoryChunk::FromAddress(address); if (!chunk->InNewSpace() && !static_cast<Page*>(chunk)->WasSwept()) { static_cast<PagedSpace*>(chunk->owner())->IncrementUnsweptFreeBytes(-by); } chunk->IncrementLiveBytes(by); } // ----------------------------------------------------------------------------- // PagedSpace implementation PagedSpace::PagedSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id, Executability executable) : Space(heap, id, executable), free_list_(this), swept_precisely_(true), unswept_free_bytes_(0), end_of_unswept_pages_(NULL), emergency_memory_(NULL) { if (id == CODE_SPACE) { area_size_ = heap->isolate()->memory_allocator()->CodePageAreaSize(); } else { area_size_ = Page::kPageSize - Page::kObjectStartOffset; } max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize) * AreaSize(); accounting_stats_.Clear(); allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); anchor_.InitializeAsAnchor(this); } bool PagedSpace::SetUp() { return true; } bool PagedSpace::HasBeenSetUp() { return true; } void PagedSpace::TearDown() { PageIterator iterator(this); while (iterator.has_next()) { heap()->isolate()->memory_allocator()->Free(iterator.next()); } anchor_.set_next_page(&anchor_); anchor_.set_prev_page(&anchor_); accounting_stats_.Clear(); } size_t PagedSpace::CommittedPhysicalMemory() { if (!base::VirtualMemory::HasLazyCommits()) return CommittedMemory(); MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); size_t size = 0; PageIterator it(this); while (it.has_next()) { size += it.next()->CommittedPhysicalMemory(); } return size; } Object* PagedSpace::FindObject(Address addr) { // Note: this function can only be called on precisely swept spaces. DCHECK(!heap()->mark_compact_collector()->in_use()); if (!Contains(addr)) return Smi::FromInt(0); // Signaling not found. Page* p = Page::FromAddress(addr); HeapObjectIterator it(p, NULL); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { Address cur = obj->address(); Address next = cur + obj->Size(); if ((cur <= addr) && (addr < next)) return obj; } UNREACHABLE(); return Smi::FromInt(0); } bool PagedSpace::CanExpand() { DCHECK(max_capacity_ % AreaSize() == 0); if (Capacity() == max_capacity_) return false; DCHECK(Capacity() < max_capacity_); // Are we going to exceed capacity for this space? if ((Capacity() + Page::kPageSize) > max_capacity_) return false; return true; } bool PagedSpace::Expand() { if (!CanExpand()) return false; intptr_t size = AreaSize(); if (anchor_.next_page() == &anchor_) { size = SizeOfFirstPage(); } Page* p = heap()->isolate()->memory_allocator()->AllocatePage(size, this, executable()); if (p == NULL) return false; DCHECK(Capacity() <= max_capacity_); p->InsertAfter(anchor_.prev_page()); return true; } intptr_t PagedSpace::SizeOfFirstPage() { int size = 0; switch (identity()) { case OLD_POINTER_SPACE: size = 112 * kPointerSize * KB; break; case OLD_DATA_SPACE: size = 192 * KB; break; case MAP_SPACE: size = 16 * kPointerSize * KB; break; case CELL_SPACE: size = 16 * kPointerSize * KB; break; case PROPERTY_CELL_SPACE: size = 8 * kPointerSize * KB; break; case CODE_SPACE: { CodeRange* code_range = heap()->isolate()->code_range(); if (code_range != NULL && code_range->valid()) { // When code range exists, code pages are allocated in a special way // (from the reserved code range). That part of the code is not yet // upgraded to handle small pages. size = AreaSize(); } else { size = RoundUp(480 * KB * FullCodeGenerator::kBootCodeSizeMultiplier / 100, kPointerSize); } break; } default: UNREACHABLE(); } return Min(size, AreaSize()); } int PagedSpace::CountTotalPages() { PageIterator it(this); int count = 0; while (it.has_next()) { it.next(); count++; } return count; } void PagedSpace::ObtainFreeListStatistics(Page* page, SizeStats* sizes) { sizes->huge_size_ = page->available_in_huge_free_list(); sizes->small_size_ = page->available_in_small_free_list(); sizes->medium_size_ = page->available_in_medium_free_list(); sizes->large_size_ = page->available_in_large_free_list(); } void PagedSpace::ResetFreeListStatistics() { PageIterator page_iterator(this); while (page_iterator.has_next()) { Page* page = page_iterator.next(); page->ResetFreeListStatistics(); } } void PagedSpace::IncreaseCapacity(int size) { accounting_stats_.ExpandSpace(size); } void PagedSpace::ReleasePage(Page* page) { DCHECK(page->LiveBytes() == 0); DCHECK(AreaSize() == page->area_size()); if (page->WasSwept()) { intptr_t size = free_list_.EvictFreeListItems(page); accounting_stats_.AllocateBytes(size); DCHECK_EQ(AreaSize(), static_cast<int>(size)); } else { DecreaseUnsweptFreeBytes(page); } if (page->IsFlagSet(MemoryChunk::SCAN_ON_SCAVENGE)) { heap()->decrement_scan_on_scavenge_pages(); page->ClearFlag(MemoryChunk::SCAN_ON_SCAVENGE); } DCHECK(!free_list_.ContainsPageFreeListItems(page)); if (Page::FromAllocationTop(allocation_info_.top()) == page) { allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); } page->Unlink(); if (page->IsFlagSet(MemoryChunk::CONTAINS_ONLY_DATA)) { heap()->isolate()->memory_allocator()->Free(page); } else { heap()->QueueMemoryChunkForFree(page); } DCHECK(Capacity() > 0); accounting_stats_.ShrinkSpace(AreaSize()); } void PagedSpace::CreateEmergencyMemory() { emergency_memory_ = heap()->isolate()->memory_allocator()->AllocateChunk( AreaSize(), AreaSize(), executable(), this); } void PagedSpace::FreeEmergencyMemory() { Page* page = static_cast<Page*>(emergency_memory_); DCHECK(page->LiveBytes() == 0); DCHECK(AreaSize() == page->area_size()); DCHECK(!free_list_.ContainsPageFreeListItems(page)); heap()->isolate()->memory_allocator()->Free(page); emergency_memory_ = NULL; } void PagedSpace::UseEmergencyMemory() { Page* page = Page::Initialize(heap(), emergency_memory_, executable(), this); page->InsertAfter(anchor_.prev_page()); emergency_memory_ = NULL; } #ifdef DEBUG void PagedSpace::Print() {} #endif #ifdef VERIFY_HEAP void PagedSpace::Verify(ObjectVisitor* visitor) { // We can only iterate over the pages if they were swept precisely. if (!swept_precisely_) return; bool allocation_pointer_found_in_space = (allocation_info_.top() == allocation_info_.limit()); PageIterator page_iterator(this); while (page_iterator.has_next()) { Page* page = page_iterator.next(); CHECK(page->owner() == this); if (page == Page::FromAllocationTop(allocation_info_.top())) { allocation_pointer_found_in_space = true; } CHECK(page->WasSweptPrecisely()); HeapObjectIterator it(page, NULL); Address end_of_previous_object = page->area_start(); Address top = page->area_end(); int black_size = 0; for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) { CHECK(end_of_previous_object <= object->address()); // The first word should be a map, and we expect all map pointers to // be in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // Perform space-specific object verification. VerifyObject(object); // The object itself should look OK. object->ObjectVerify(); // All the interior pointers should be contained in the heap. int size = object->Size(); object->IterateBody(map->instance_type(), size, visitor); if (Marking::IsBlack(Marking::MarkBitFrom(object))) { black_size += size; } CHECK(object->address() + size <= top); end_of_previous_object = object->address() + size; } CHECK_LE(black_size, page->LiveBytes()); } CHECK(allocation_pointer_found_in_space); } #endif // VERIFY_HEAP // ----------------------------------------------------------------------------- // NewSpace implementation bool NewSpace::SetUp(int reserved_semispace_capacity, int maximum_semispace_capacity) { // Set up new space based on the preallocated memory block defined by // start and size. The provided space is divided into two semi-spaces. // To support fast containment testing in the new space, the size of // this chunk must be a power of two and it must be aligned to its size. int initial_semispace_capacity = heap()->InitialSemiSpaceSize(); size_t size = 2 * reserved_semispace_capacity; Address base = heap()->isolate()->memory_allocator()->ReserveAlignedMemory( size, size, &reservation_); if (base == NULL) return false; chunk_base_ = base; chunk_size_ = static_cast<uintptr_t>(size); LOG(heap()->isolate(), NewEvent("InitialChunk", chunk_base_, chunk_size_)); DCHECK(initial_semispace_capacity <= maximum_semispace_capacity); DCHECK(IsPowerOf2(maximum_semispace_capacity)); // Allocate and set up the histogram arrays if necessary. allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1); promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1); #define SET_NAME(name) \ allocated_histogram_[name].set_name(#name); \ promoted_histogram_[name].set_name(#name); INSTANCE_TYPE_LIST(SET_NAME) #undef SET_NAME DCHECK(reserved_semispace_capacity == heap()->ReservedSemiSpaceSize()); DCHECK(static_cast<intptr_t>(chunk_size_) >= 2 * heap()->ReservedSemiSpaceSize()); DCHECK(IsAddressAligned(chunk_base_, 2 * reserved_semispace_capacity, 0)); to_space_.SetUp(chunk_base_, initial_semispace_capacity, maximum_semispace_capacity); from_space_.SetUp(chunk_base_ + reserved_semispace_capacity, initial_semispace_capacity, maximum_semispace_capacity); if (!to_space_.Commit()) { return false; } DCHECK(!from_space_.is_committed()); // No need to use memory yet. start_ = chunk_base_; address_mask_ = ~(2 * reserved_semispace_capacity - 1); object_mask_ = address_mask_ | kHeapObjectTagMask; object_expected_ = reinterpret_cast<uintptr_t>(start_) | kHeapObjectTag; ResetAllocationInfo(); return true; } void NewSpace::TearDown() { if (allocated_histogram_) { DeleteArray(allocated_histogram_); allocated_histogram_ = NULL; } if (promoted_histogram_) { DeleteArray(promoted_histogram_); promoted_histogram_ = NULL; } start_ = NULL; allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); to_space_.TearDown(); from_space_.TearDown(); LOG(heap()->isolate(), DeleteEvent("InitialChunk", chunk_base_)); DCHECK(reservation_.IsReserved()); heap()->isolate()->memory_allocator()->FreeMemory(&reservation_, NOT_EXECUTABLE); chunk_base_ = NULL; chunk_size_ = 0; } void NewSpace::Flip() { SemiSpace::Swap(&from_space_, &to_space_); } void NewSpace::Grow() { // Double the semispace size but only up to maximum capacity. DCHECK(Capacity() < MaximumCapacity()); int new_capacity = Min(MaximumCapacity(), 2 * static_cast<int>(Capacity())); if (to_space_.GrowTo(new_capacity)) { // Only grow from space if we managed to grow to-space. if (!from_space_.GrowTo(new_capacity)) { // If we managed to grow to-space but couldn't grow from-space, // attempt to shrink to-space. if (!to_space_.ShrinkTo(from_space_.Capacity())) { // We are in an inconsistent state because we could not // commit/uncommit memory from new space. V8::FatalProcessOutOfMemory("Failed to grow new space."); } } } DCHECK_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::Shrink() { int new_capacity = Max(InitialCapacity(), 2 * SizeAsInt()); int rounded_new_capacity = RoundUp(new_capacity, Page::kPageSize); if (rounded_new_capacity < Capacity() && to_space_.ShrinkTo(rounded_new_capacity)) { // Only shrink from-space if we managed to shrink to-space. from_space_.Reset(); if (!from_space_.ShrinkTo(rounded_new_capacity)) { // If we managed to shrink to-space but couldn't shrink from // space, attempt to grow to-space again. if (!to_space_.GrowTo(from_space_.Capacity())) { // We are in an inconsistent state because we could not // commit/uncommit memory from new space. V8::FatalProcessOutOfMemory("Failed to shrink new space."); } } } DCHECK_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::UpdateAllocationInfo() { MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); allocation_info_.set_top(to_space_.page_low()); allocation_info_.set_limit(to_space_.page_high()); UpdateInlineAllocationLimit(0); DCHECK_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::ResetAllocationInfo() { to_space_.Reset(); UpdateAllocationInfo(); pages_used_ = 0; // Clear all mark-bits in the to-space. NewSpacePageIterator it(&to_space_); while (it.has_next()) { Bitmap::Clear(it.next()); } } void NewSpace::UpdateInlineAllocationLimit(int size_in_bytes) { if (heap()->inline_allocation_disabled()) { // Lowest limit when linear allocation was disabled. Address high = to_space_.page_high(); Address new_top = allocation_info_.top() + size_in_bytes; allocation_info_.set_limit(Min(new_top, high)); } else if (inline_allocation_limit_step() == 0) { // Normal limit is the end of the current page. allocation_info_.set_limit(to_space_.page_high()); } else { // Lower limit during incremental marking. Address high = to_space_.page_high(); Address new_top = allocation_info_.top() + size_in_bytes; Address new_limit = new_top + inline_allocation_limit_step_; allocation_info_.set_limit(Min(new_limit, high)); } DCHECK_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } bool NewSpace::AddFreshPage() { Address top = allocation_info_.top(); if (NewSpacePage::IsAtStart(top)) { // The current page is already empty. Don't try to make another. // We should only get here if someone asks to allocate more // than what can be stored in a single page. // TODO(gc): Change the limit on new-space allocation to prevent this // from happening (all such allocations should go directly to LOSpace). return false; } if (!to_space_.AdvancePage()) { // Failed to get a new page in to-space. return false; } // Clear remainder of current page. Address limit = NewSpacePage::FromLimit(top)->area_end(); if (heap()->gc_state() == Heap::SCAVENGE) { heap()->promotion_queue()->SetNewLimit(limit); heap()->promotion_queue()->ActivateGuardIfOnTheSamePage(); } int remaining_in_page = static_cast<int>(limit - top); heap()->CreateFillerObjectAt(top, remaining_in_page); pages_used_++; UpdateAllocationInfo(); return true; } AllocationResult NewSpace::SlowAllocateRaw(int size_in_bytes) { Address old_top = allocation_info_.top(); Address high = to_space_.page_high(); if (allocation_info_.limit() < high) { // Either the limit has been lowered because linear allocation was disabled // or because incremental marking wants to get a chance to do a step. Set // the new limit accordingly. Address new_top = old_top + size_in_bytes; int bytes_allocated = static_cast<int>(new_top - top_on_previous_step_); heap()->incremental_marking()->Step(bytes_allocated, IncrementalMarking::GC_VIA_STACK_GUARD); UpdateInlineAllocationLimit(size_in_bytes); top_on_previous_step_ = new_top; return AllocateRaw(size_in_bytes); } else if (AddFreshPage()) { // Switched to new page. Try allocating again. int bytes_allocated = static_cast<int>(old_top - top_on_previous_step_); heap()->incremental_marking()->Step(bytes_allocated, IncrementalMarking::GC_VIA_STACK_GUARD); top_on_previous_step_ = to_space_.page_low(); return AllocateRaw(size_in_bytes); } else { return AllocationResult::Retry(); } } #ifdef VERIFY_HEAP // We do not use the SemiSpaceIterator because verification doesn't assume // that it works (it depends on the invariants we are checking). void NewSpace::Verify() { // The allocation pointer should be in the space or at the very end. DCHECK_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); // There should be objects packed in from the low address up to the // allocation pointer. Address current = to_space_.first_page()->area_start(); CHECK_EQ(current, to_space_.space_start()); while (current != top()) { if (!NewSpacePage::IsAtEnd(current)) { // The allocation pointer should not be in the middle of an object. CHECK(!NewSpacePage::FromLimit(current)->ContainsLimit(top()) || current < top()); HeapObject* object = HeapObject::FromAddress(current); // The first word should be a map, and we expect all map pointers to // be in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // The object should not be code or a map. CHECK(!object->IsMap()); CHECK(!object->IsCode()); // The object itself should look OK. object->ObjectVerify(); // All the interior pointers should be contained in the heap. VerifyPointersVisitor visitor; int size = object->Size(); object->IterateBody(map->instance_type(), size, &visitor); current += size; } else { // At end of page, switch to next page. NewSpacePage* page = NewSpacePage::FromLimit(current)->next_page(); // Next page should be valid. CHECK(!page->is_anchor()); current = page->area_start(); } } // Check semi-spaces. CHECK_EQ(from_space_.id(), kFromSpace); CHECK_EQ(to_space_.id(), kToSpace); from_space_.Verify(); to_space_.Verify(); } #endif // ----------------------------------------------------------------------------- // SemiSpace implementation void SemiSpace::SetUp(Address start, int initial_capacity, int maximum_capacity) { // Creates a space in the young generation. The constructor does not // allocate memory from the OS. A SemiSpace is given a contiguous chunk of // memory of size 'capacity' when set up, and does not grow or shrink // otherwise. In the mark-compact collector, the memory region of the from // space is used as the marking stack. It requires contiguous memory // addresses. DCHECK(maximum_capacity >= Page::kPageSize); initial_capacity_ = RoundDown(initial_capacity, Page::kPageSize); capacity_ = initial_capacity; maximum_capacity_ = RoundDown(maximum_capacity, Page::kPageSize); maximum_committed_ = 0; committed_ = false; start_ = start; address_mask_ = ~(maximum_capacity - 1); object_mask_ = address_mask_ | kHeapObjectTagMask; object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag; age_mark_ = start_; } void SemiSpace::TearDown() { start_ = NULL; capacity_ = 0; } bool SemiSpace::Commit() { DCHECK(!is_committed()); int pages = capacity_ / Page::kPageSize; if (!heap()->isolate()->memory_allocator()->CommitBlock(start_, capacity_, executable())) { return false; } NewSpacePage* current = anchor(); for (int i = 0; i < pages; i++) { NewSpacePage* new_page = NewSpacePage::Initialize(heap(), start_ + i * Page::kPageSize, this); new_page->InsertAfter(current); current = new_page; } SetCapacity(capacity_); committed_ = true; Reset(); return true; } bool SemiSpace::Uncommit() { DCHECK(is_committed()); Address start = start_ + maximum_capacity_ - capacity_; if (!heap()->isolate()->memory_allocator()->UncommitBlock(start, capacity_)) { return false; } anchor()->set_next_page(anchor()); anchor()->set_prev_page(anchor()); committed_ = false; return true; } size_t SemiSpace::CommittedPhysicalMemory() { if (!is_committed()) return 0; size_t size = 0; NewSpacePageIterator it(this); while (it.has_next()) { size += it.next()->CommittedPhysicalMemory(); } return size; } bool SemiSpace::GrowTo(int new_capacity) { if (!is_committed()) { if (!Commit()) return false; } DCHECK((new_capacity & Page::kPageAlignmentMask) == 0); DCHECK(new_capacity <= maximum_capacity_); DCHECK(new_capacity > capacity_); int pages_before = capacity_ / Page::kPageSize; int pages_after = new_capacity / Page::kPageSize; size_t delta = new_capacity - capacity_; DCHECK(IsAligned(delta, base::OS::AllocateAlignment())); if (!heap()->isolate()->memory_allocator()->CommitBlock( start_ + capacity_, delta, executable())) { return false; } SetCapacity(new_capacity); NewSpacePage* last_page = anchor()->prev_page(); DCHECK(last_page != anchor()); for (int i = pages_before; i < pages_after; i++) { Address page_address = start_ + i * Page::kPageSize; NewSpacePage* new_page = NewSpacePage::Initialize(heap(), page_address, this); new_page->InsertAfter(last_page); Bitmap::Clear(new_page); // Duplicate the flags that was set on the old page. new_page->SetFlags(last_page->GetFlags(), NewSpacePage::kCopyOnFlipFlagsMask); last_page = new_page; } return true; } bool SemiSpace::ShrinkTo(int new_capacity) { DCHECK((new_capacity & Page::kPageAlignmentMask) == 0); DCHECK(new_capacity >= initial_capacity_); DCHECK(new_capacity < capacity_); if (is_committed()) { size_t delta = capacity_ - new_capacity; DCHECK(IsAligned(delta, base::OS::AllocateAlignment())); MemoryAllocator* allocator = heap()->isolate()->memory_allocator(); if (!allocator->UncommitBlock(start_ + new_capacity, delta)) { return false; } int pages_after = new_capacity / Page::kPageSize; NewSpacePage* new_last_page = NewSpacePage::FromAddress(start_ + (pages_after - 1) * Page::kPageSize); new_last_page->set_next_page(anchor()); anchor()->set_prev_page(new_last_page); DCHECK((current_page_ >= first_page()) && (current_page_ <= new_last_page)); } SetCapacity(new_capacity); return true; } void SemiSpace::FlipPages(intptr_t flags, intptr_t mask) { anchor_.set_owner(this); // Fixup back-pointers to anchor. Address of anchor changes // when we swap. anchor_.prev_page()->set_next_page(&anchor_); anchor_.next_page()->set_prev_page(&anchor_); bool becomes_to_space = (id_ == kFromSpace); id_ = becomes_to_space ? kToSpace : kFromSpace; NewSpacePage* page = anchor_.next_page(); while (page != &anchor_) { page->set_owner(this); page->SetFlags(flags, mask); if (becomes_to_space) { page->ClearFlag(MemoryChunk::IN_FROM_SPACE); page->SetFlag(MemoryChunk::IN_TO_SPACE); page->ClearFlag(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK); page->ResetLiveBytes(); } else { page->SetFlag(MemoryChunk::IN_FROM_SPACE); page->ClearFlag(MemoryChunk::IN_TO_SPACE); } DCHECK(page->IsFlagSet(MemoryChunk::SCAN_ON_SCAVENGE)); DCHECK(page->IsFlagSet(MemoryChunk::IN_TO_SPACE) || page->IsFlagSet(MemoryChunk::IN_FROM_SPACE)); page = page->next_page(); } } void SemiSpace::Reset() { DCHECK(anchor_.next_page() != &anchor_); current_page_ = anchor_.next_page(); } void SemiSpace::Swap(SemiSpace* from, SemiSpace* to) { // We won't be swapping semispaces without data in them. DCHECK(from->anchor_.next_page() != &from->anchor_); DCHECK(to->anchor_.next_page() != &to->anchor_); // Swap bits. SemiSpace tmp = *from; *from = *to; *to = tmp; // Fixup back-pointers to the page list anchor now that its address // has changed. // Swap to/from-space bits on pages. // Copy GC flags from old active space (from-space) to new (to-space). intptr_t flags = from->current_page()->GetFlags(); to->FlipPages(flags, NewSpacePage::kCopyOnFlipFlagsMask); from->FlipPages(0, 0); } void SemiSpace::SetCapacity(int new_capacity) { capacity_ = new_capacity; if (capacity_ > maximum_committed_) { maximum_committed_ = capacity_; } } void SemiSpace::set_age_mark(Address mark) { DCHECK(NewSpacePage::FromLimit(mark)->semi_space() == this); age_mark_ = mark; // Mark all pages up to the one containing mark. NewSpacePageIterator it(space_start(), mark); while (it.has_next()) { it.next()->SetFlag(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK); } } #ifdef DEBUG void SemiSpace::Print() {} #endif #ifdef VERIFY_HEAP void SemiSpace::Verify() { bool is_from_space = (id_ == kFromSpace); NewSpacePage* page = anchor_.next_page(); CHECK(anchor_.semi_space() == this); while (page != &anchor_) { CHECK(page->semi_space() == this); CHECK(page->InNewSpace()); CHECK(page->IsFlagSet(is_from_space ? MemoryChunk::IN_FROM_SPACE : MemoryChunk::IN_TO_SPACE)); CHECK(!page->IsFlagSet(is_from_space ? MemoryChunk::IN_TO_SPACE : MemoryChunk::IN_FROM_SPACE)); CHECK(page->IsFlagSet(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING)); if (!is_from_space) { // The pointers-from-here-are-interesting flag isn't updated dynamically // on from-space pages, so it might be out of sync with the marking state. if (page->heap()->incremental_marking()->IsMarking()) { CHECK(page->IsFlagSet(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING)); } else { CHECK( !page->IsFlagSet(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING)); } // TODO(gc): Check that the live_bytes_count_ field matches the // black marking on the page (if we make it match in new-space). } CHECK(page->IsFlagSet(MemoryChunk::SCAN_ON_SCAVENGE)); CHECK(page->prev_page()->next_page() == page); page = page->next_page(); } } #endif #ifdef DEBUG void SemiSpace::AssertValidRange(Address start, Address end) { // Addresses belong to same semi-space NewSpacePage* page = NewSpacePage::FromLimit(start); NewSpacePage* end_page = NewSpacePage::FromLimit(end); SemiSpace* space = page->semi_space(); CHECK_EQ(space, end_page->semi_space()); // Start address is before end address, either on same page, // or end address is on a later page in the linked list of // semi-space pages. if (page == end_page) { CHECK(start <= end); } else { while (page != end_page) { page = page->next_page(); CHECK_NE(page, space->anchor()); } } } #endif // ----------------------------------------------------------------------------- // SemiSpaceIterator implementation. SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) { Initialize(space->bottom(), space->top(), NULL); } SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func) { Initialize(space->bottom(), space->top(), size_func); } SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) { Initialize(start, space->top(), NULL); } SemiSpaceIterator::SemiSpaceIterator(Address from, Address to) { Initialize(from, to, NULL); } void SemiSpaceIterator::Initialize(Address start, Address end, HeapObjectCallback size_func) { SemiSpace::AssertValidRange(start, end); current_ = start; limit_ = end; size_func_ = size_func; } #ifdef DEBUG // heap_histograms is shared, always clear it before using it. static void ClearHistograms(Isolate* isolate) { // We reset the name each time, though it hasn't changed. #define DEF_TYPE_NAME(name) isolate->heap_histograms()[name].set_name(#name); INSTANCE_TYPE_LIST(DEF_TYPE_NAME) #undef DEF_TYPE_NAME #define CLEAR_HISTOGRAM(name) isolate->heap_histograms()[name].clear(); INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM) #undef CLEAR_HISTOGRAM isolate->js_spill_information()->Clear(); } static void ClearCodeKindStatistics(int* code_kind_statistics) { for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) { code_kind_statistics[i] = 0; } } static void ReportCodeKindStatistics(int* code_kind_statistics) { PrintF("\n Code kind histograms: \n"); for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) { if (code_kind_statistics[i] > 0) { PrintF(" %-20s: %10d bytes\n", Code::Kind2String(static_cast<Code::Kind>(i)), code_kind_statistics[i]); } } PrintF("\n"); } static int CollectHistogramInfo(HeapObject* obj) { Isolate* isolate = obj->GetIsolate(); InstanceType type = obj->map()->instance_type(); DCHECK(0 <= type && type <= LAST_TYPE); DCHECK(isolate->heap_histograms()[type].name() != NULL); isolate->heap_histograms()[type].increment_number(1); isolate->heap_histograms()[type].increment_bytes(obj->Size()); if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) { JSObject::cast(obj) ->IncrementSpillStatistics(isolate->js_spill_information()); } return obj->Size(); } static void ReportHistogram(Isolate* isolate, bool print_spill) { PrintF("\n Object Histogram:\n"); for (int i = 0; i <= LAST_TYPE; i++) { if (isolate->heap_histograms()[i].number() > 0) { PrintF(" %-34s%10d (%10d bytes)\n", isolate->heap_histograms()[i].name(), isolate->heap_histograms()[i].number(), isolate->heap_histograms()[i].bytes()); } } PrintF("\n"); // Summarize string types. int string_number = 0; int string_bytes = 0; #define INCREMENT(type, size, name, camel_name) \ string_number += isolate->heap_histograms()[type].number(); \ string_bytes += isolate->heap_histograms()[type].bytes(); STRING_TYPE_LIST(INCREMENT) #undef INCREMENT if (string_number > 0) { PrintF(" %-34s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number, string_bytes); } if (FLAG_collect_heap_spill_statistics && print_spill) { isolate->js_spill_information()->Print(); } } #endif // DEBUG // Support for statistics gathering for --heap-stats and --log-gc. void NewSpace::ClearHistograms() { for (int i = 0; i <= LAST_TYPE; i++) { allocated_histogram_[i].clear(); promoted_histogram_[i].clear(); } } // Because the copying collector does not touch garbage objects, we iterate // the new space before a collection to get a histogram of allocated objects. // This only happens when --log-gc flag is set. void NewSpace::CollectStatistics() { ClearHistograms(); SemiSpaceIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) RecordAllocation(obj); } static void DoReportStatistics(Isolate* isolate, HistogramInfo* info, const char* description) { LOG(isolate, HeapSampleBeginEvent("NewSpace", description)); // Lump all the string types together. int string_number = 0; int string_bytes = 0; #define INCREMENT(type, size, name, camel_name) \ string_number += info[type].number(); \ string_bytes += info[type].bytes(); STRING_TYPE_LIST(INCREMENT) #undef INCREMENT if (string_number > 0) { LOG(isolate, HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes)); } // Then do the other types. for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) { if (info[i].number() > 0) { LOG(isolate, HeapSampleItemEvent(info[i].name(), info[i].number(), info[i].bytes())); } } LOG(isolate, HeapSampleEndEvent("NewSpace", description)); } void NewSpace::ReportStatistics() { #ifdef DEBUG if (FLAG_heap_stats) { float pct = static_cast<float>(Available()) / Capacity(); PrintF(" capacity: %" V8_PTR_PREFIX "d" ", available: %" V8_PTR_PREFIX "d, %%%d\n", Capacity(), Available(), static_cast<int>(pct * 100)); PrintF("\n Object Histogram:\n"); for (int i = 0; i <= LAST_TYPE; i++) { if (allocated_histogram_[i].number() > 0) { PrintF(" %-34s%10d (%10d bytes)\n", allocated_histogram_[i].name(), allocated_histogram_[i].number(), allocated_histogram_[i].bytes()); } } PrintF("\n"); } #endif // DEBUG if (FLAG_log_gc) { Isolate* isolate = heap()->isolate(); DoReportStatistics(isolate, allocated_histogram_, "allocated"); DoReportStatistics(isolate, promoted_histogram_, "promoted"); } } void NewSpace::RecordAllocation(HeapObject* obj) { InstanceType type = obj->map()->instance_type(); DCHECK(0 <= type && type <= LAST_TYPE); allocated_histogram_[type].increment_number(1); allocated_histogram_[type].increment_bytes(obj->Size()); } void NewSpace::RecordPromotion(HeapObject* obj) { InstanceType type = obj->map()->instance_type(); DCHECK(0 <= type && type <= LAST_TYPE); promoted_histogram_[type].increment_number(1); promoted_histogram_[type].increment_bytes(obj->Size()); } size_t NewSpace::CommittedPhysicalMemory() { if (!base::VirtualMemory::HasLazyCommits()) return CommittedMemory(); MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); size_t size = to_space_.CommittedPhysicalMemory(); if (from_space_.is_committed()) { size += from_space_.CommittedPhysicalMemory(); } return size; } // ----------------------------------------------------------------------------- // Free lists for old object spaces implementation void FreeListNode::set_size(Heap* heap, int size_in_bytes) { DCHECK(size_in_bytes > 0); DCHECK(IsAligned(size_in_bytes, kPointerSize)); // We write a map and possibly size information to the block. If the block // is big enough to be a FreeSpace with at least one extra word (the next // pointer), we set its map to be the free space map and its size to an // appropriate array length for the desired size from HeapObject::Size(). // If the block is too small (eg, one or two words), to hold both a size // field and a next pointer, we give it a filler map that gives it the // correct size. if (size_in_bytes > FreeSpace::kHeaderSize) { // Can't use FreeSpace::cast because it fails during deserialization. // We have to set the size first with a release store before we store // the map because a concurrent store buffer scan on scavenge must not // observe a map with an invalid size. FreeSpace* this_as_free_space = reinterpret_cast<FreeSpace*>(this); this_as_free_space->nobarrier_set_size(size_in_bytes); synchronized_set_map_no_write_barrier(heap->raw_unchecked_free_space_map()); } else if (size_in_bytes == kPointerSize) { set_map_no_write_barrier(heap->raw_unchecked_one_pointer_filler_map()); } else if (size_in_bytes == 2 * kPointerSize) { set_map_no_write_barrier(heap->raw_unchecked_two_pointer_filler_map()); } else { UNREACHABLE(); } // We would like to DCHECK(Size() == size_in_bytes) but this would fail during // deserialization because the free space map is not done yet. } FreeListNode* FreeListNode::next() { DCHECK(IsFreeListNode(this)); if (map() == GetHeap()->raw_unchecked_free_space_map()) { DCHECK(map() == NULL || Size() >= kNextOffset + kPointerSize); return reinterpret_cast<FreeListNode*>( Memory::Address_at(address() + kNextOffset)); } else { return reinterpret_cast<FreeListNode*>( Memory::Address_at(address() + kPointerSize)); } } FreeListNode** FreeListNode::next_address() { DCHECK(IsFreeListNode(this)); if (map() == GetHeap()->raw_unchecked_free_space_map()) { DCHECK(Size() >= kNextOffset + kPointerSize); return reinterpret_cast<FreeListNode**>(address() + kNextOffset); } else { return reinterpret_cast<FreeListNode**>(address() + kPointerSize); } } void FreeListNode::set_next(FreeListNode* next) { DCHECK(IsFreeListNode(this)); // While we are booting the VM the free space map will actually be null. So // we have to make sure that we don't try to use it for anything at that // stage. if (map() == GetHeap()->raw_unchecked_free_space_map()) { DCHECK(map() == NULL || Size() >= kNextOffset + kPointerSize); base::NoBarrier_Store( reinterpret_cast<base::AtomicWord*>(address() + kNextOffset), reinterpret_cast<base::AtomicWord>(next)); } else { base::NoBarrier_Store( reinterpret_cast<base::AtomicWord*>(address() + kPointerSize), reinterpret_cast<base::AtomicWord>(next)); } } intptr_t FreeListCategory::Concatenate(FreeListCategory* category) { intptr_t free_bytes = 0; if (category->top() != NULL) { // This is safe (not going to deadlock) since Concatenate operations // are never performed on the same free lists at the same time in // reverse order. base::LockGuard<base::Mutex> target_lock_guard(mutex()); base::LockGuard<base::Mutex> source_lock_guard(category->mutex()); DCHECK(category->end_ != NULL); free_bytes = category->available(); if (end_ == NULL) { end_ = category->end(); } else { category->end()->set_next(top()); } set_top(category->top()); base::NoBarrier_Store(&top_, category->top_); available_ += category->available(); category->Reset(); } return free_bytes; } void FreeListCategory::Reset() { set_top(NULL); set_end(NULL); set_available(0); } intptr_t FreeListCategory::EvictFreeListItemsInList(Page* p) { int sum = 0; FreeListNode* t = top(); FreeListNode** n = &t; while (*n != NULL) { if (Page::FromAddress((*n)->address()) == p) { FreeSpace* free_space = reinterpret_cast<FreeSpace*>(*n); sum += free_space->Size(); *n = (*n)->next(); } else { n = (*n)->next_address(); } } set_top(t); if (top() == NULL) { set_end(NULL); } available_ -= sum; return sum; } bool FreeListCategory::ContainsPageFreeListItemsInList(Page* p) { FreeListNode* node = top(); while (node != NULL) { if (Page::FromAddress(node->address()) == p) return true; node = node->next(); } return false; } FreeListNode* FreeListCategory::PickNodeFromList(int* node_size) { FreeListNode* node = top(); if (node == NULL) return NULL; while (node != NULL && Page::FromAddress(node->address())->IsEvacuationCandidate()) { available_ -= reinterpret_cast<FreeSpace*>(node)->Size(); node = node->next(); } if (node != NULL) { set_top(node->next()); *node_size = reinterpret_cast<FreeSpace*>(node)->Size(); available_ -= *node_size; } else { set_top(NULL); } if (top() == NULL) { set_end(NULL); } return node; } FreeListNode* FreeListCategory::PickNodeFromList(int size_in_bytes, int* node_size) { FreeListNode* node = PickNodeFromList(node_size); if (node != NULL && *node_size < size_in_bytes) { Free(node, *node_size); *node_size = 0; return NULL; } return node; } void FreeListCategory::Free(FreeListNode* node, int size_in_bytes) { node->set_next(top()); set_top(node); if (end_ == NULL) { end_ = node; } available_ += size_in_bytes; } void FreeListCategory::RepairFreeList(Heap* heap) { FreeListNode* n = top(); while (n != NULL) { Map** map_location = reinterpret_cast<Map**>(n->address()); if (*map_location == NULL) { *map_location = heap->free_space_map(); } else { DCHECK(*map_location == heap->free_space_map()); } n = n->next(); } } FreeList::FreeList(PagedSpace* owner) : owner_(owner), heap_(owner->heap()) { Reset(); } intptr_t FreeList::Concatenate(FreeList* free_list) { intptr_t free_bytes = 0; free_bytes += small_list_.Concatenate(free_list->small_list()); free_bytes += medium_list_.Concatenate(free_list->medium_list()); free_bytes += large_list_.Concatenate(free_list->large_list()); free_bytes += huge_list_.Concatenate(free_list->huge_list()); return free_bytes; } void FreeList::Reset() { small_list_.Reset(); medium_list_.Reset(); large_list_.Reset(); huge_list_.Reset(); } int FreeList::Free(Address start, int size_in_bytes) { if (size_in_bytes == 0) return 0; FreeListNode* node = FreeListNode::FromAddress(start); node->set_size(heap_, size_in_bytes); Page* page = Page::FromAddress(start); // Early return to drop too-small blocks on the floor. if (size_in_bytes < kSmallListMin) { page->add_non_available_small_blocks(size_in_bytes); return size_in_bytes; } // Insert other blocks at the head of a free list of the appropriate // magnitude. if (size_in_bytes <= kSmallListMax) { small_list_.Free(node, size_in_bytes); page->add_available_in_small_free_list(size_in_bytes); } else if (size_in_bytes <= kMediumListMax) { medium_list_.Free(node, size_in_bytes); page->add_available_in_medium_free_list(size_in_bytes); } else if (size_in_bytes <= kLargeListMax) { large_list_.Free(node, size_in_bytes); page->add_available_in_large_free_list(size_in_bytes); } else { huge_list_.Free(node, size_in_bytes); page->add_available_in_huge_free_list(size_in_bytes); } DCHECK(IsVeryLong() || available() == SumFreeLists()); return 0; } FreeListNode* FreeList::FindNodeFor(int size_in_bytes, int* node_size) { FreeListNode* node = NULL; Page* page = NULL; if (size_in_bytes <= kSmallAllocationMax) { node = small_list_.PickNodeFromList(node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_small_free_list(-(*node_size)); DCHECK(IsVeryLong() || available() == SumFreeLists()); return node; } } if (size_in_bytes <= kMediumAllocationMax) { node = medium_list_.PickNodeFromList(node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_medium_free_list(-(*node_size)); DCHECK(IsVeryLong() || available() == SumFreeLists()); return node; } } if (size_in_bytes <= kLargeAllocationMax) { node = large_list_.PickNodeFromList(node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_large_free_list(-(*node_size)); DCHECK(IsVeryLong() || available() == SumFreeLists()); return node; } } int huge_list_available = huge_list_.available(); FreeListNode* top_node = huge_list_.top(); for (FreeListNode** cur = &top_node; *cur != NULL; cur = (*cur)->next_address()) { FreeListNode* cur_node = *cur; while (cur_node != NULL && Page::FromAddress(cur_node->address())->IsEvacuationCandidate()) { int size = reinterpret_cast<FreeSpace*>(cur_node)->Size(); huge_list_available -= size; page = Page::FromAddress(cur_node->address()); page->add_available_in_huge_free_list(-size); cur_node = cur_node->next(); } *cur = cur_node; if (cur_node == NULL) { huge_list_.set_end(NULL); break; } DCHECK((*cur)->map() == heap_->raw_unchecked_free_space_map()); FreeSpace* cur_as_free_space = reinterpret_cast<FreeSpace*>(*cur); int size = cur_as_free_space->Size(); if (size >= size_in_bytes) { // Large enough node found. Unlink it from the list. node = *cur; *cur = node->next(); *node_size = size; huge_list_available -= size; page = Page::FromAddress(node->address()); page->add_available_in_huge_free_list(-size); break; } } huge_list_.set_top(top_node); if (huge_list_.top() == NULL) { huge_list_.set_end(NULL); } huge_list_.set_available(huge_list_available); if (node != NULL) { DCHECK(IsVeryLong() || available() == SumFreeLists()); return node; } if (size_in_bytes <= kSmallListMax) { node = small_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_small_free_list(-(*node_size)); } } else if (size_in_bytes <= kMediumListMax) { node = medium_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_medium_free_list(-(*node_size)); } } else if (size_in_bytes <= kLargeListMax) { node = large_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { DCHECK(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_large_free_list(-(*node_size)); } } DCHECK(IsVeryLong() || available() == SumFreeLists()); return node; } // Allocation on the old space free list. If it succeeds then a new linear // allocation space has been set up with the top and limit of the space. If // the allocation fails then NULL is returned, and the caller can perform a GC // or allocate a new page before retrying. HeapObject* FreeList::Allocate(int size_in_bytes) { DCHECK(0 < size_in_bytes); DCHECK(size_in_bytes <= kMaxBlockSize); DCHECK(IsAligned(size_in_bytes, kPointerSize)); // Don't free list allocate if there is linear space available. DCHECK(owner_->limit() - owner_->top() < size_in_bytes); int old_linear_size = static_cast<int>(owner_->limit() - owner_->top()); // Mark the old linear allocation area with a free space map so it can be // skipped when scanning the heap. This also puts it back in the free list // if it is big enough. owner_->Free(owner_->top(), old_linear_size); owner_->heap()->incremental_marking()->OldSpaceStep(size_in_bytes - old_linear_size); int new_node_size = 0; FreeListNode* new_node = FindNodeFor(size_in_bytes, &new_node_size); if (new_node == NULL) { owner_->SetTopAndLimit(NULL, NULL); return NULL; } int bytes_left = new_node_size - size_in_bytes; DCHECK(bytes_left >= 0); #ifdef DEBUG for (int i = 0; i < size_in_bytes / kPointerSize; i++) { reinterpret_cast<Object**>(new_node->address())[i] = Smi::FromInt(kCodeZapValue); } #endif // The old-space-step might have finished sweeping and restarted marking. // Verify that it did not turn the page of the new node into an evacuation // candidate. DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(new_node)); const int kThreshold = IncrementalMarking::kAllocatedThreshold; // Memory in the linear allocation area is counted as allocated. We may free // a little of this again immediately - see below. owner_->Allocate(new_node_size); if (owner_->heap()->inline_allocation_disabled()) { // Keep the linear allocation area empty if requested to do so, just // return area back to the free list instead. owner_->Free(new_node->address() + size_in_bytes, bytes_left); DCHECK(owner_->top() == NULL && owner_->limit() == NULL); } else if (bytes_left > kThreshold && owner_->heap()->incremental_marking()->IsMarkingIncomplete() && FLAG_incremental_marking_steps) { int linear_size = owner_->RoundSizeDownToObjectAlignment(kThreshold); // We don't want to give too large linear areas to the allocator while // incremental marking is going on, because we won't check again whether // we want to do another increment until the linear area is used up. owner_->Free(new_node->address() + size_in_bytes + linear_size, new_node_size - size_in_bytes - linear_size); owner_->SetTopAndLimit(new_node->address() + size_in_bytes, new_node->address() + size_in_bytes + linear_size); } else if (bytes_left > 0) { // Normally we give the rest of the node to the allocator as its new // linear allocation area. owner_->SetTopAndLimit(new_node->address() + size_in_bytes, new_node->address() + new_node_size); } else { // TODO(gc) Try not freeing linear allocation region when bytes_left // are zero. owner_->SetTopAndLimit(NULL, NULL); } return new_node; } intptr_t FreeList::EvictFreeListItems(Page* p) { intptr_t sum = huge_list_.EvictFreeListItemsInList(p); p->set_available_in_huge_free_list(0); if (sum < p->area_size()) { sum += small_list_.EvictFreeListItemsInList(p) + medium_list_.EvictFreeListItemsInList(p) + large_list_.EvictFreeListItemsInList(p); p->set_available_in_small_free_list(0); p->set_available_in_medium_free_list(0); p->set_available_in_large_free_list(0); } return sum; } bool FreeList::ContainsPageFreeListItems(Page* p) { return huge_list_.EvictFreeListItemsInList(p) || small_list_.EvictFreeListItemsInList(p) || medium_list_.EvictFreeListItemsInList(p) || large_list_.EvictFreeListItemsInList(p); } void FreeList::RepairLists(Heap* heap) { small_list_.RepairFreeList(heap); medium_list_.RepairFreeList(heap); large_list_.RepairFreeList(heap); huge_list_.RepairFreeList(heap); } #ifdef DEBUG intptr_t FreeListCategory::SumFreeList() { intptr_t sum = 0; FreeListNode* cur = top(); while (cur != NULL) { DCHECK(cur->map() == cur->GetHeap()->raw_unchecked_free_space_map()); FreeSpace* cur_as_free_space = reinterpret_cast<FreeSpace*>(cur); sum += cur_as_free_space->nobarrier_size(); cur = cur->next(); } return sum; } static const int kVeryLongFreeList = 500; int FreeListCategory::FreeListLength() { int length = 0; FreeListNode* cur = top(); while (cur != NULL) { length++; cur = cur->next(); if (length == kVeryLongFreeList) return length; } return length; } bool FreeList::IsVeryLong() { if (small_list_.FreeListLength() == kVeryLongFreeList) return true; if (medium_list_.FreeListLength() == kVeryLongFreeList) return true; if (large_list_.FreeListLength() == kVeryLongFreeList) return true; if (huge_list_.FreeListLength() == kVeryLongFreeList) return true; return false; } // This can take a very long time because it is linear in the number of entries // on the free list, so it should not be called if FreeListLength returns // kVeryLongFreeList. intptr_t FreeList::SumFreeLists() { intptr_t sum = small_list_.SumFreeList(); sum += medium_list_.SumFreeList(); sum += large_list_.SumFreeList(); sum += huge_list_.SumFreeList(); return sum; } #endif // ----------------------------------------------------------------------------- // OldSpace implementation void PagedSpace::PrepareForMarkCompact() { // We don't have a linear allocation area while sweeping. It will be restored // on the first allocation after the sweep. EmptyAllocationInfo(); // This counter will be increased for pages which will be swept by the // sweeper threads. unswept_free_bytes_ = 0; // Clear the free list before a full GC---it will be rebuilt afterward. free_list_.Reset(); } intptr_t PagedSpace::SizeOfObjects() { DCHECK(heap()->mark_compact_collector()->sweeping_in_progress() || (unswept_free_bytes_ == 0)); return Size() - unswept_free_bytes_ - (limit() - top()); } // After we have booted, we have created a map which represents free space // on the heap. If there was already a free list then the elements on it // were created with the wrong FreeSpaceMap (normally NULL), so we need to // fix them. void PagedSpace::RepairFreeListsAfterBoot() { free_list_.RepairLists(heap()); } void PagedSpace::EvictEvacuationCandidatesFromFreeLists() { if (allocation_info_.top() >= allocation_info_.limit()) return; if (Page::FromAllocationTop(allocation_info_.top()) ->IsEvacuationCandidate()) { // Create filler object to keep page iterable if it was iterable. int remaining = static_cast<int>(allocation_info_.limit() - allocation_info_.top()); heap()->CreateFillerObjectAt(allocation_info_.top(), remaining); allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); } } HeapObject* PagedSpace::WaitForSweeperThreadsAndRetryAllocation( int size_in_bytes) { MarkCompactCollector* collector = heap()->mark_compact_collector(); if (collector->sweeping_in_progress()) { // Wait for the sweeper threads here and complete the sweeping phase. collector->EnsureSweepingCompleted(); // After waiting for the sweeper threads, there may be new free-list // entries. return free_list_.Allocate(size_in_bytes); } return NULL; } HeapObject* PagedSpace::SlowAllocateRaw(int size_in_bytes) { // Allocation in this space has failed. MarkCompactCollector* collector = heap()->mark_compact_collector(); // Sweeping is still in progress. if (collector->sweeping_in_progress()) { // First try to refill the free-list, concurrent sweeper threads // may have freed some objects in the meantime. collector->RefillFreeList(this); // Retry the free list allocation. HeapObject* object = free_list_.Allocate(size_in_bytes); if (object != NULL) return object; // If sweeping is still in progress try to sweep pages on the main thread. int free_chunk = collector->SweepInParallel(this, size_in_bytes); collector->RefillFreeList(this); if (free_chunk >= size_in_bytes) { HeapObject* object = free_list_.Allocate(size_in_bytes); // We should be able to allocate an object here since we just freed that // much memory. DCHECK(object != NULL); if (object != NULL) return object; } } // Free list allocation failed and there is no next page. Fail if we have // hit the old generation size limit that should cause a garbage // collection. if (!heap()->always_allocate() && heap()->OldGenerationAllocationLimitReached()) { // If sweeper threads are active, wait for them at that point and steal // elements form their free-lists. HeapObject* object = WaitForSweeperThreadsAndRetryAllocation(size_in_bytes); if (object != NULL) return object; } // Try to expand the space and allocate in the new next page. if (Expand()) { DCHECK(CountTotalPages() > 1 || size_in_bytes <= free_list_.available()); return free_list_.Allocate(size_in_bytes); } // If sweeper threads are active, wait for them at that point and steal // elements form their free-lists. Allocation may still fail their which // would indicate that there is not enough memory for the given allocation. return WaitForSweeperThreadsAndRetryAllocation(size_in_bytes); } #ifdef DEBUG void PagedSpace::ReportCodeStatistics(Isolate* isolate) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); ReportCodeKindStatistics(isolate->code_kind_statistics()); PrintF( "Code comment statistics (\" [ comment-txt : size/ " "count (average)\"):\n"); for (int i = 0; i <= CommentStatistic::kMaxComments; i++) { const CommentStatistic& cs = comments_statistics[i]; if (cs.size > 0) { PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count, cs.size / cs.count); } } PrintF("\n"); } void PagedSpace::ResetCodeStatistics(Isolate* isolate) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); ClearCodeKindStatistics(isolate->code_kind_statistics()); for (int i = 0; i < CommentStatistic::kMaxComments; i++) { comments_statistics[i].Clear(); } comments_statistics[CommentStatistic::kMaxComments].comment = "Unknown"; comments_statistics[CommentStatistic::kMaxComments].size = 0; comments_statistics[CommentStatistic::kMaxComments].count = 0; } // Adds comment to 'comment_statistics' table. Performance OK as long as // 'kMaxComments' is small static void EnterComment(Isolate* isolate, const char* comment, int delta) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); // Do not count empty comments if (delta <= 0) return; CommentStatistic* cs = &comments_statistics[CommentStatistic::kMaxComments]; // Search for a free or matching entry in 'comments_statistics': 'cs' // points to result. for (int i = 0; i < CommentStatistic::kMaxComments; i++) { if (comments_statistics[i].comment == NULL) { cs = &comments_statistics[i]; cs->comment = comment; break; } else if (strcmp(comments_statistics[i].comment, comment) == 0) { cs = &comments_statistics[i]; break; } } // Update entry for 'comment' cs->size += delta; cs->count += 1; } // Call for each nested comment start (start marked with '[ xxx', end marked // with ']'. RelocIterator 'it' must point to a comment reloc info. static void CollectCommentStatistics(Isolate* isolate, RelocIterator* it) { DCHECK(!it->done()); DCHECK(it->rinfo()->rmode() == RelocInfo::COMMENT); const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data()); if (tmp[0] != '[') { // Not a nested comment; skip return; } // Search for end of nested comment or a new nested comment const char* const comment_txt = reinterpret_cast<const char*>(it->rinfo()->data()); const byte* prev_pc = it->rinfo()->pc(); int flat_delta = 0; it->next(); while (true) { // All nested comments must be terminated properly, and therefore exit // from loop. DCHECK(!it->done()); if (it->rinfo()->rmode() == RelocInfo::COMMENT) { const char* const txt = reinterpret_cast<const char*>(it->rinfo()->data()); flat_delta += static_cast<int>(it->rinfo()->pc() - prev_pc); if (txt[0] == ']') break; // End of nested comment // A new comment CollectCommentStatistics(isolate, it); // Skip code that was covered with previous comment prev_pc = it->rinfo()->pc(); } it->next(); } EnterComment(isolate, comment_txt, flat_delta); } // Collects code size statistics: // - by code kind // - by code comment void PagedSpace::CollectCodeStatistics() { Isolate* isolate = heap()->isolate(); HeapObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) { if (obj->IsCode()) { Code* code = Code::cast(obj); isolate->code_kind_statistics()[code->kind()] += code->Size(); RelocIterator it(code); int delta = 0; const byte* prev_pc = code->instruction_start(); while (!it.done()) { if (it.rinfo()->rmode() == RelocInfo::COMMENT) { delta += static_cast<int>(it.rinfo()->pc() - prev_pc); CollectCommentStatistics(isolate, &it); prev_pc = it.rinfo()->pc(); } it.next(); } DCHECK(code->instruction_start() <= prev_pc && prev_pc <= code->instruction_end()); delta += static_cast<int>(code->instruction_end() - prev_pc); EnterComment(isolate, "NoComment", delta); } } } void PagedSpace::ReportStatistics() { int pct = static_cast<int>(Available() * 100 / Capacity()); PrintF(" capacity: %" V8_PTR_PREFIX "d" ", waste: %" V8_PTR_PREFIX "d" ", available: %" V8_PTR_PREFIX "d, %%%d\n", Capacity(), Waste(), Available(), pct); if (!swept_precisely_) return; ClearHistograms(heap()->isolate()); HeapObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) CollectHistogramInfo(obj); ReportHistogram(heap()->isolate(), true); } #endif // ----------------------------------------------------------------------------- // MapSpace implementation // TODO(mvstanton): this is weird...the compiler can't make a vtable unless // there is at least one non-inlined virtual function. I would prefer to hide // the VerifyObject definition behind VERIFY_HEAP. void MapSpace::VerifyObject(HeapObject* object) { CHECK(object->IsMap()); } // ----------------------------------------------------------------------------- // CellSpace and PropertyCellSpace implementation // TODO(mvstanton): this is weird...the compiler can't make a vtable unless // there is at least one non-inlined virtual function. I would prefer to hide // the VerifyObject definition behind VERIFY_HEAP. void CellSpace::VerifyObject(HeapObject* object) { CHECK(object->IsCell()); } void PropertyCellSpace::VerifyObject(HeapObject* object) { CHECK(object->IsPropertyCell()); } // ----------------------------------------------------------------------------- // LargeObjectIterator LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) { current_ = space->first_page_; size_func_ = NULL; } LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func) { current_ = space->first_page_; size_func_ = size_func; } HeapObject* LargeObjectIterator::Next() { if (current_ == NULL) return NULL; HeapObject* object = current_->GetObject(); current_ = current_->next_page(); return object; } // ----------------------------------------------------------------------------- // LargeObjectSpace static bool ComparePointers(void* key1, void* key2) { return key1 == key2; } LargeObjectSpace::LargeObjectSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id) : Space(heap, id, NOT_EXECUTABLE), // Managed on a per-allocation basis max_capacity_(max_capacity), first_page_(NULL), size_(0), page_count_(0), objects_size_(0), chunk_map_(ComparePointers, 1024) {} bool LargeObjectSpace::SetUp() { first_page_ = NULL; size_ = 0; maximum_committed_ = 0; page_count_ = 0; objects_size_ = 0; chunk_map_.Clear(); return true; } void LargeObjectSpace::TearDown() { while (first_page_ != NULL) { LargePage* page = first_page_; first_page_ = first_page_->next_page(); LOG(heap()->isolate(), DeleteEvent("LargeObjectChunk", page->address())); ObjectSpace space = static_cast<ObjectSpace>(1 << identity()); heap()->isolate()->memory_allocator()->PerformAllocationCallback( space, kAllocationActionFree, page->size()); heap()->isolate()->memory_allocator()->Free(page); } SetUp(); } AllocationResult LargeObjectSpace::AllocateRaw(int object_size, Executability executable) { // Check if we want to force a GC before growing the old space further. // If so, fail the allocation. if (!heap()->always_allocate() && heap()->OldGenerationAllocationLimitReached()) { return AllocationResult::Retry(identity()); } if (Size() + object_size > max_capacity_) { return AllocationResult::Retry(identity()); } LargePage* page = heap()->isolate()->memory_allocator()->AllocateLargePage( object_size, this, executable); if (page == NULL) return AllocationResult::Retry(identity()); DCHECK(page->area_size() >= object_size); size_ += static_cast<int>(page->size()); objects_size_ += object_size; page_count_++; page->set_next_page(first_page_); first_page_ = page; if (size_ > maximum_committed_) { maximum_committed_ = size_; } // Register all MemoryChunk::kAlignment-aligned chunks covered by // this large page in the chunk map. uintptr_t base = reinterpret_cast<uintptr_t>(page) / MemoryChunk::kAlignment; uintptr_t limit = base + (page->size() - 1) / MemoryChunk::kAlignment; for (uintptr_t key = base; key <= limit; key++) { HashMap::Entry* entry = chunk_map_.Lookup(reinterpret_cast<void*>(key), static_cast<uint32_t>(key), true); DCHECK(entry != NULL); entry->value = page; } HeapObject* object = page->GetObject(); if (Heap::ShouldZapGarbage()) { // Make the object consistent so the heap can be verified in OldSpaceStep. // We only need to do this in debug builds or if verify_heap is on. reinterpret_cast<Object**>(object->address())[0] = heap()->fixed_array_map(); reinterpret_cast<Object**>(object->address())[1] = Smi::FromInt(0); } heap()->incremental_marking()->OldSpaceStep(object_size); return object; } size_t LargeObjectSpace::CommittedPhysicalMemory() { if (!base::VirtualMemory::HasLazyCommits()) return CommittedMemory(); size_t size = 0; LargePage* current = first_page_; while (current != NULL) { size += current->CommittedPhysicalMemory(); current = current->next_page(); } return size; } // GC support Object* LargeObjectSpace::FindObject(Address a) { LargePage* page = FindPage(a); if (page != NULL) { return page->GetObject(); } return Smi::FromInt(0); // Signaling not found. } LargePage* LargeObjectSpace::FindPage(Address a) { uintptr_t key = reinterpret_cast<uintptr_t>(a) / MemoryChunk::kAlignment; HashMap::Entry* e = chunk_map_.Lookup(reinterpret_cast<void*>(key), static_cast<uint32_t>(key), false); if (e != NULL) { DCHECK(e->value != NULL); LargePage* page = reinterpret_cast<LargePage*>(e->value); DCHECK(page->is_valid()); if (page->Contains(a)) { return page; } } return NULL; } void LargeObjectSpace::FreeUnmarkedObjects() { LargePage* previous = NULL; LargePage* current = first_page_; while (current != NULL) { HeapObject* object = current->GetObject(); // Can this large page contain pointers to non-trivial objects. No other // pointer object is this big. bool is_pointer_object = object->IsFixedArray(); MarkBit mark_bit = Marking::MarkBitFrom(object); if (mark_bit.Get()) { mark_bit.Clear(); Page::FromAddress(object->address())->ResetProgressBar(); Page::FromAddress(object->address())->ResetLiveBytes(); previous = current; current = current->next_page(); } else { LargePage* page = current; // Cut the chunk out from the chunk list. current = current->next_page(); if (previous == NULL) { first_page_ = current; } else { previous->set_next_page(current); } // Free the chunk. heap()->mark_compact_collector()->ReportDeleteIfNeeded(object, heap()->isolate()); size_ -= static_cast<int>(page->size()); objects_size_ -= object->Size(); page_count_--; // Remove entries belonging to this page. // Use variable alignment to help pass length check (<= 80 characters) // of single line in tools/presubmit.py. const intptr_t alignment = MemoryChunk::kAlignment; uintptr_t base = reinterpret_cast<uintptr_t>(page) / alignment; uintptr_t limit = base + (page->size() - 1) / alignment; for (uintptr_t key = base; key <= limit; key++) { chunk_map_.Remove(reinterpret_cast<void*>(key), static_cast<uint32_t>(key)); } if (is_pointer_object) { heap()->QueueMemoryChunkForFree(page); } else { heap()->isolate()->memory_allocator()->Free(page); } } } heap()->FreeQueuedChunks(); } bool LargeObjectSpace::Contains(HeapObject* object) { Address address = object->address(); MemoryChunk* chunk = MemoryChunk::FromAddress(address); bool owned = (chunk->owner() == this); SLOW_DCHECK(!owned || FindObject(address)->IsHeapObject()); return owned; } #ifdef VERIFY_HEAP // We do not assume that the large object iterator works, because it depends // on the invariants we are checking during verification. void LargeObjectSpace::Verify() { for (LargePage* chunk = first_page_; chunk != NULL; chunk = chunk->next_page()) { // Each chunk contains an object that starts at the large object page's // object area start. HeapObject* object = chunk->GetObject(); Page* page = Page::FromAddress(object->address()); CHECK(object->address() == page->area_start()); // The first word should be a map, and we expect all map pointers to be // in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // We have only code, sequential strings, external strings // (sequential strings that have been morphed into external // strings), fixed arrays, byte arrays, and constant pool arrays in the // large object space. CHECK(object->IsCode() || object->IsSeqString() || object->IsExternalString() || object->IsFixedArray() || object->IsFixedDoubleArray() || object->IsByteArray() || object->IsConstantPoolArray()); // The object itself should look OK. object->ObjectVerify(); // Byte arrays and strings don't have interior pointers. if (object->IsCode()) { VerifyPointersVisitor code_visitor; object->IterateBody(map->instance_type(), object->Size(), &code_visitor); } else if (object->IsFixedArray()) { FixedArray* array = FixedArray::cast(object); for (int j = 0; j < array->length(); j++) { Object* element = array->get(j); if (element->IsHeapObject()) { HeapObject* element_object = HeapObject::cast(element); CHECK(heap()->Contains(element_object)); CHECK(element_object->map()->IsMap()); } } } } } #endif #ifdef DEBUG void LargeObjectSpace::Print() { OFStream os(stdout); LargeObjectIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { obj->Print(os); } } void LargeObjectSpace::ReportStatistics() { PrintF(" size: %" V8_PTR_PREFIX "d\n", size_); int num_objects = 0; ClearHistograms(heap()->isolate()); LargeObjectIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { num_objects++; CollectHistogramInfo(obj); } PrintF( " number of objects %d, " "size of objects %" V8_PTR_PREFIX "d\n", num_objects, objects_size_); if (num_objects > 0) ReportHistogram(heap()->isolate(), false); } void LargeObjectSpace::CollectCodeStatistics() { Isolate* isolate = heap()->isolate(); LargeObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) { if (obj->IsCode()) { Code* code = Code::cast(obj); isolate->code_kind_statistics()[code->kind()] += code->Size(); } } } void Page::Print() { // Make a best-effort to print the objects in the page. PrintF("Page@%p in %s\n", this->address(), AllocationSpaceName(this->owner()->identity())); printf(" --------------------------------------\n"); HeapObjectIterator objects(this, heap()->GcSafeSizeOfOldObjectFunction()); unsigned mark_size = 0; for (HeapObject* object = objects.Next(); object != NULL; object = objects.Next()) { bool is_marked = Marking::MarkBitFrom(object).Get(); PrintF(" %c ", (is_marked ? '!' : ' ')); // Indent a little. if (is_marked) { mark_size += heap()->GcSafeSizeOfOldObjectFunction()(object); } object->ShortPrint(); PrintF("\n"); } printf(" --------------------------------------\n"); printf(" Marked: %x, LiveCount: %x\n", mark_size, LiveBytes()); } #endif // DEBUG } } // namespace v8::internal
mit
powmedia/update-props
mongoose-plugin.js
348
/** * Plugin for Mongoose * * Usage: * schema.plugin(updatePropsPlugin); * ... * (From within a model method:) * this.updateProps(attrs, allowedKeys) */ var update = require('./index.js'); module.exports = function(schema) { schema.methods.updateProps = function(attrs, allowedKeys) { return update(this, attrs, allowedKeys); }; };
mit
SkillSmart/ConferenceManagementSystem
UserManagement/migrations/0011_auto_20170309_1206.py
3567
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-09 11:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('UserManagement', '0010_auto_20170305_2040'), ] operations = [ migrations.RemoveField( model_name='expertprofile', name='certifications', ), migrations.RemoveField( model_name='expertprofile', name='mediation_experience', ), migrations.RemoveField( model_name='expertprofile', name='negotiation_experience', ), migrations.RemoveField( model_name='expertprofile', name='slogan', ), migrations.RemoveField( model_name='studentprofile', name='awards', ), migrations.RemoveField( model_name='studentprofile', name='internships', ), migrations.RemoveField( model_name='studentprofile', name='mediation_courses', ), migrations.RemoveField( model_name='studentprofile', name='negotiation_courses', ), migrations.RemoveField( model_name='studentprofile', name='slogan', ), migrations.AddField( model_name='award', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.StudentProfile'), preserve_default=False, ), migrations.AddField( model_name='certification', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.ExpertProfile'), preserve_default=False, ), migrations.AddField( model_name='competition', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.StudentProfile'), preserve_default=False, ), migrations.AddField( model_name='course', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.StudentProfile'), preserve_default=False, ), migrations.AddField( model_name='internship', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.StudentProfile'), preserve_default=False, ), migrations.AddField( model_name='mediationexperience', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.ExpertProfile'), preserve_default=False, ), migrations.AddField( model_name='negotiationexperience', name='profile', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='UserManagement.ExpertProfile'), preserve_default=False, ), migrations.AddField( model_name='profile', name='slogan', field=models.CharField(default='', max_length=250, verbose_name='Your favorite quote up to 250 characters'), preserve_default=False, ), ]
mit
tapomayukh/projects_in_python
classification/Classification_with_HMM/Single_Contact_Classification/Variable_Stiffness_Variable_Velocity/HMM/with 0.8s/hmm_crossvalidation_force_10_states.py
27332
# Hidden Markov Model Implementation import pylab as pyl import numpy as np import matplotlib.pyplot as pp #from enthought.mayavi import mlab import scipy as scp import scipy.ndimage as ni import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import rospy #import hrl_lib.mayavi2_util as mu import hrl_lib.viz as hv import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu import pickle import ghmm import sys sys.path.insert(0, '/home/tapo/svn/robot1_data/usr/tapo/data_code/Classification/Data/Single_Contact_HMM/Variable_Stiffness_Variable_Velocity/') from data_variable_hshv2 import Fmat_original_hshv from data_variable_hslv2 import Fmat_original_hslv from data_variable_lshv2 import Fmat_original_lshv from data_variable_lslv2 import Fmat_original_lslv # Returns mu,sigma for 10 hidden-states from feature-vectors(123,35) for RF,SF,RM,SM models def feature_to_mu_sigma(fvec): index = 0 m,n = np.shape(fvec) #print m,n mu = np.matrix(np.zeros((10,1))) sigma = np.matrix(np.zeros((10,1))) DIVS = m/10 while (index < 10): m_init = index*DIVS temp_fvec = fvec[(m_init):(m_init+DIVS),0:] #if index == 1: #print temp_fvec mu[index] = scp.mean(temp_fvec) sigma[index] = scp.std(temp_fvec) index = index+1 return mu,sigma # Returns sequence given raw data def create_seq(fvec): m,n = np.shape(fvec) #print m,n seq = np.matrix(np.zeros((10,n))) DIVS = m/10 for i in range(n): index = 0 while (index < 10): m_init = index*DIVS temp_fvec = fvec[(m_init):(m_init+DIVS),i] #if index == 1: #print temp_fvec seq[index,i] = scp.mean(temp_fvec) index = index+1 return seq if __name__ == '__main__': # HMM - Implementation: F = ghmm.Float() # emission domain of this model # A - Transition Matrix A = [[0.1, 0.25, 0.15, 0.15, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05], [0.0, 0.1, 0.25, 0.25, 0.2, 0.1, 0.05, 0.05, 0.05, 0.05], [0.0, 0.0, 0.1, 0.25, 0.25, 0.2, 0.05, 0.05, 0.05, 0.05], [0.0, 0.0, 0.0, 0.1, 0.3, 0.30, 0.20, 0.1, 0.05, 0.05], [0.0, 0.0, 0.0, 0.0, 0.1, 0.30, 0.30, 0.20, 0.05, 0.05], [0.0, 0.0, 0.0, 0.0, 0.00, 0.1, 0.35, 0.30, 0.20, 0.05], [0.0, 0.0, 0.0, 0.0, 0.00, 0.00, 0.2, 0.30, 0.30, 0.20], [0.0, 0.0, 0.0, 0.0, 0.00, 0.00, 0.00, 0.2, 0.50, 0.30], [0.0, 0.0, 0.0, 0.0, 0.00, 0.00, 0.00, 0.00, 0.4, 0.60], [0.0, 0.0, 0.0, 0.0, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00]] # pi - initial probabilities per state pi = [0.1] * 10 # Confusion Matrix cmat = np.zeros((4,4)) ############################################################################################################################################# # HSHV as testing set and Rest as training set # Checking the Data-Matrix mu_rf_hshv,sigma_rf_hshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hslv[0:81,0:15], Fmat_original_lshv[0:81,0:15], Fmat_original_lslv[0:81,0:15])))) mu_rm_hshv,sigma_rm_hshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hslv[0:81,15:30], Fmat_original_lshv[0:81,15:16], Fmat_original_lslv[0:81,15:28])))) mu_sf_hshv,sigma_sf_hshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hslv[0:81,30:45], Fmat_original_lshv[0:81,16:23], Fmat_original_lslv[0:81,28:37])))) mu_sm_hshv,sigma_sm_hshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hslv[0:81,45:56], Fmat_original_lshv[0:81,23:32], Fmat_original_lslv[0:81,37:45])))) # B - Emission Matrix, parameters of emission distributions in pairs of (mu, sigma) B_rf_hshv = np.zeros((10,2)) B_rm_hshv = np.zeros((10,2)) B_sf_hshv = np.zeros((10,2)) B_sm_hshv = np.zeros((10,2)) for num_states in range(10): B_rf_hshv[num_states,0] = mu_rf_hshv[num_states] B_rf_hshv[num_states,1] = sigma_rf_hshv[num_states] B_rm_hshv[num_states,0] = mu_rm_hshv[num_states] B_rm_hshv[num_states,1] = sigma_rm_hshv[num_states] B_sf_hshv[num_states,0] = mu_sf_hshv[num_states] B_sf_hshv[num_states,1] = sigma_sf_hshv[num_states] B_sm_hshv[num_states,0] = mu_sm_hshv[num_states] B_sm_hshv[num_states,1] = sigma_sm_hshv[num_states] B_rf_hshv = B_rf_hshv.tolist() B_rm_hshv = B_rm_hshv.tolist() B_sf_hshv = B_sf_hshv.tolist() B_sm_hshv = B_sm_hshv.tolist() # generate RF, RM, SF, SM models from parameters model_rf_hshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rf_hshv, pi) # Will be Trained model_rm_hshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rm_hshv, pi) # Will be Trained model_sf_hshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sf_hshv, pi) # Will be Trained model_sm_hshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sm_hshv, pi) # Will be Trained # For Training total_seq_rf_hshv = np.matrix(np.column_stack((Fmat_original_hslv[0:81,0:15], Fmat_original_lshv[0:81,0:15], Fmat_original_lslv[0:81,0:15]))) total_seq_rm_hshv = np.matrix(np.column_stack((Fmat_original_hslv[0:81,15:30], Fmat_original_lshv[0:81,15:16], Fmat_original_lslv[0:81,15:28]))) total_seq_sf_hshv = np.matrix(np.column_stack((Fmat_original_hslv[0:81,30:45], Fmat_original_lshv[0:81,16:23], Fmat_original_lslv[0:81,28:37]))) total_seq_sm_hshv = np.matrix(np.column_stack((Fmat_original_hslv[0:81,45:56], Fmat_original_lshv[0:81,23:32], Fmat_original_lslv[0:81,37:45]))) train_seq_rf_hshv = (np.array(total_seq_rf_hshv).T).tolist() train_seq_rm_hshv = (np.array(total_seq_rm_hshv).T).tolist() train_seq_sf_hshv = (np.array(total_seq_sf_hshv).T).tolist() train_seq_sm_hshv = (np.array(total_seq_sm_hshv).T).tolist() #print train_seq_rf_hshv final_ts_rf_hshv = ghmm.SequenceSet(F,train_seq_rf_hshv) final_ts_rm_hshv = ghmm.SequenceSet(F,train_seq_rm_hshv) final_ts_sf_hshv = ghmm.SequenceSet(F,train_seq_sf_hshv) final_ts_sm_hshv = ghmm.SequenceSet(F,train_seq_sm_hshv) model_rf_hshv.baumWelch(final_ts_rf_hshv) model_rm_hshv.baumWelch(final_ts_rm_hshv) model_sf_hshv.baumWelch(final_ts_sf_hshv) model_sm_hshv.baumWelch(final_ts_sm_hshv) # For Testing total_seq_obj_hshv = Fmat_original_hshv[0:81,:] rf_hshv = np.matrix(np.zeros(np.size(total_seq_obj_hshv,1))) rm_hshv = np.matrix(np.zeros(np.size(total_seq_obj_hshv,1))) sf_hshv = np.matrix(np.zeros(np.size(total_seq_obj_hshv,1))) sm_hshv = np.matrix(np.zeros(np.size(total_seq_obj_hshv,1))) k = 0 while (k < np.size(total_seq_obj_hshv,1)): test_seq_obj_hshv = (np.array(total_seq_obj_hshv[0:81,k]).T).tolist() new_test_seq_obj_hshv = np.array(sum(test_seq_obj_hshv,[])) #print new_test_seq_obj_hshv ts_obj_hshv = new_test_seq_obj_hshv #print np.shape(ts_obj_hshv) final_ts_obj_hshv = ghmm.EmissionSequence(F,ts_obj_hshv.tolist()) # Find Viterbi Path path_rf_obj_hshv = model_rf_hshv.viterbi(final_ts_obj_hshv) path_rm_obj_hshv = model_rm_hshv.viterbi(final_ts_obj_hshv) path_sf_obj_hshv = model_sf_hshv.viterbi(final_ts_obj_hshv) path_sm_obj_hshv = model_sm_hshv.viterbi(final_ts_obj_hshv) obj_hshv = max(path_rf_obj_hshv[1],path_rm_obj_hshv[1],path_sf_obj_hshv[1],path_sm_obj_hshv[1]) if obj_hshv == path_rf_obj_hshv[1]: rf_hshv[0,k] = 1 elif obj_hshv == path_rm_obj_hshv[1]: rm_hshv[0,k] = 1 elif obj_hshv == path_sf_obj_hshv[1]: sf_hshv[0,k] = 1 else: sm_hshv[0,k] = 1 k = k+1 #print rf_hshv.T cmat[0][0] = cmat[0][0] + np.sum(rf_hshv[0,0:15]) cmat[0][1] = cmat[0][1] + np.sum(rf_hshv[0,15:15]) cmat[0][2] = cmat[0][2] + np.sum(rf_hshv[0,15:26]) cmat[0][3] = cmat[0][3] + np.sum(rf_hshv[0,26:33]) cmat[1][0] = cmat[1][0] + np.sum(rm_hshv[0,0:15]) cmat[1][1] = cmat[1][1] + np.sum(rm_hshv[0,15:15]) cmat[1][2] = cmat[1][2] + np.sum(rm_hshv[0,15:26]) cmat[1][3] = cmat[1][3] + np.sum(rm_hshv[0,26:33]) cmat[2][0] = cmat[2][0] + np.sum(sf_hshv[0,0:15]) cmat[2][1] = cmat[2][1] + np.sum(sf_hshv[0,15:15]) cmat[2][2] = cmat[2][2] + np.sum(sf_hshv[0,15:26]) cmat[2][3] = cmat[2][3] + np.sum(sf_hshv[0,26:33]) cmat[3][0] = cmat[3][0] + np.sum(sm_hshv[0,0:15]) cmat[3][1] = cmat[3][1] + np.sum(sm_hshv[0,15:15]) cmat[3][2] = cmat[3][2] + np.sum(sm_hshv[0,15:26]) cmat[3][3] = cmat[3][3] + np.sum(sm_hshv[0,26:33]) #print cmat ############################################################################################################################################# # HSLV as testing set and Rest as training set mu_rf_hslv,sigma_rf_hslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_lshv[0:81,0:15], Fmat_original_lslv[0:81,0:15])))) mu_rm_hslv,sigma_rm_hslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_lshv[0:81,15:16], Fmat_original_lslv[0:81,15:28])))) mu_sf_hslv,sigma_sf_hslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_lshv[0:81,16:23], Fmat_original_lslv[0:81,28:37])))) mu_sm_hslv,sigma_sm_hslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_lshv[0:81,23:32], Fmat_original_lslv[0:81,37:45])))) # B - Emission Matrix, parameters of emission distributions in pairs of (mu, sigma) B_rf_hslv = np.zeros((10,2)) B_rm_hslv = np.zeros((10,2)) B_sf_hslv = np.zeros((10,2)) B_sm_hslv = np.zeros((10,2)) for num_states in range(10): B_rf_hslv[num_states,0] = mu_rf_hslv[num_states] B_rf_hslv[num_states,1] = sigma_rf_hslv[num_states] B_rm_hslv[num_states,0] = mu_rm_hslv[num_states] B_rm_hslv[num_states,1] = sigma_rm_hslv[num_states] B_sf_hslv[num_states,0] = mu_sf_hslv[num_states] B_sf_hslv[num_states,1] = sigma_sf_hslv[num_states] B_sm_hslv[num_states,0] = mu_sm_hslv[num_states] B_sm_hslv[num_states,1] = sigma_sm_hslv[num_states] B_rf_hslv = B_rf_hslv.tolist() B_rm_hslv = B_rm_hslv.tolist() B_sf_hslv = B_sf_hslv.tolist() B_sm_hslv = B_sm_hslv.tolist() model_rf_hslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rf_hslv, pi) # Will be Trained model_rm_hslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rm_hslv, pi) # Will be Trained model_sf_hslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sf_hslv, pi) # Will be Trained model_sm_hslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sm_hslv, pi) # Will be Trained # For Training total_seq_rf_hslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_lshv[0:81,0:15], Fmat_original_lslv[0:81,0:15]))) total_seq_rm_hslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_lshv[0:81,15:16], Fmat_original_lslv[0:81,15:28]))) total_seq_sf_hslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_lshv[0:81,16:23], Fmat_original_lslv[0:81,28:37]))) total_seq_sm_hslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_lshv[0:81,23:32], Fmat_original_lslv[0:81,37:45]))) train_seq_rf_hslv = (np.array(total_seq_rf_hslv).T).tolist() train_seq_rm_hslv = (np.array(total_seq_rm_hslv).T).tolist() train_seq_sf_hslv = (np.array(total_seq_sf_hslv).T).tolist() train_seq_sm_hslv = (np.array(total_seq_sm_hslv).T).tolist() #print train_seq_rf_hslv final_ts_rf_hslv = ghmm.SequenceSet(F,train_seq_rf_hslv) final_ts_rm_hslv = ghmm.SequenceSet(F,train_seq_rm_hslv) final_ts_sf_hslv = ghmm.SequenceSet(F,train_seq_sf_hslv) final_ts_sm_hslv = ghmm.SequenceSet(F,train_seq_sm_hslv) model_rf_hslv.baumWelch(final_ts_rf_hslv) model_rm_hslv.baumWelch(final_ts_rm_hslv) model_sf_hslv.baumWelch(final_ts_sf_hslv) model_sm_hslv.baumWelch(final_ts_sm_hslv) # For Testing total_seq_obj_hslv = Fmat_original_hslv[0:81,:] rf_hslv = np.matrix(np.zeros(np.size(total_seq_obj_hslv,1))) rm_hslv = np.matrix(np.zeros(np.size(total_seq_obj_hslv,1))) sf_hslv = np.matrix(np.zeros(np.size(total_seq_obj_hslv,1))) sm_hslv = np.matrix(np.zeros(np.size(total_seq_obj_hslv,1))) k = 0 while (k < np.size(total_seq_obj_hslv,1)): test_seq_obj_hslv = (np.array(total_seq_obj_hslv[0:81,k]).T).tolist() new_test_seq_obj_hslv = np.array(sum(test_seq_obj_hslv,[])) #print new_test_seq_obj_hslv ts_obj_hslv = new_test_seq_obj_hslv #print np.shape(ts_obj_hslv) final_ts_obj_hslv = ghmm.EmissionSequence(F,ts_obj_hslv.tolist()) # Find Viterbi Path path_rf_obj_hslv = model_rf_hslv.viterbi(final_ts_obj_hslv) path_rm_obj_hslv = model_rm_hslv.viterbi(final_ts_obj_hslv) path_sf_obj_hslv = model_sf_hslv.viterbi(final_ts_obj_hslv) path_sm_obj_hslv = model_sm_hslv.viterbi(final_ts_obj_hslv) obj_hslv = max(path_rf_obj_hslv[1],path_rm_obj_hslv[1],path_sf_obj_hslv[1],path_sm_obj_hslv[1]) if obj_hslv == path_rf_obj_hslv[1]: rf_hslv[0,k] = 1 elif obj_hslv == path_rm_obj_hslv[1]: rm_hslv[0,k] = 1 elif obj_hslv == path_sf_obj_hslv[1]: sf_hslv[0,k] = 1 else: sm_hslv[0,k] = 1 k = k+1 #print rf_hslv.T cmat[0][0] = cmat[0][0] + np.sum(rf_hslv[0,0:15]) cmat[0][1] = cmat[0][1] + np.sum(rf_hslv[0,15:30]) cmat[0][2] = cmat[0][2] + np.sum(rf_hslv[0,30:45]) cmat[0][3] = cmat[0][3] + np.sum(rf_hslv[0,45:56]) cmat[1][0] = cmat[1][0] + np.sum(rm_hslv[0,0:15]) cmat[1][1] = cmat[1][1] + np.sum(rm_hslv[0,15:30]) cmat[1][2] = cmat[1][2] + np.sum(rm_hslv[0,30:45]) cmat[1][3] = cmat[1][3] + np.sum(rm_hslv[0,45:56]) cmat[2][0] = cmat[2][0] + np.sum(sf_hslv[0,0:15]) cmat[2][1] = cmat[2][1] + np.sum(sf_hslv[0,15:30]) cmat[2][2] = cmat[2][2] + np.sum(sf_hslv[0,30:45]) cmat[2][3] = cmat[2][3] + np.sum(sf_hslv[0,45:56]) cmat[3][0] = cmat[3][0] + np.sum(sm_hslv[0,0:15]) cmat[3][1] = cmat[3][1] + np.sum(sm_hslv[0,15:30]) cmat[3][2] = cmat[3][2] + np.sum(sm_hslv[0,30:45]) cmat[3][3] = cmat[3][3] + np.sum(sm_hslv[0,45:56]) #print cmat ############################################################################################################################################ # LSHV as testing set and Rest as training set mu_rf_lshv,sigma_rf_lshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_hslv[0:81,0:15], Fmat_original_lslv[0:81,0:15])))) mu_rm_lshv,sigma_rm_lshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_hslv[0:81,15:30], Fmat_original_lslv[0:81,15:28])))) mu_sf_lshv,sigma_sf_lshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_hslv[0:81,30:45], Fmat_original_lslv[0:81,28:37])))) mu_sm_lshv,sigma_sm_lshv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_hslv[0:81,45:56], Fmat_original_lslv[0:81,37:45])))) # B - Emission Matrix, parameters of emission distributions in pairs of (mu, sigma) B_rf_lshv = np.zeros((10,2)) B_rm_lshv = np.zeros((10,2)) B_sf_lshv = np.zeros((10,2)) B_sm_lshv = np.zeros((10,2)) for num_states in range(10): B_rf_lshv[num_states,0] = mu_rf_lshv[num_states] B_rf_lshv[num_states,1] = sigma_rf_lshv[num_states] B_rm_lshv[num_states,0] = mu_rm_lshv[num_states] B_rm_lshv[num_states,1] = sigma_rm_lshv[num_states] B_sf_lshv[num_states,0] = mu_sf_lshv[num_states] B_sf_lshv[num_states,1] = sigma_sf_lshv[num_states] B_sm_lshv[num_states,0] = mu_sm_lshv[num_states] B_sm_lshv[num_states,1] = sigma_sm_lshv[num_states] B_rf_lshv = B_rf_lshv.tolist() B_rm_lshv = B_rm_lshv.tolist() B_sf_lshv = B_sf_lshv.tolist() B_sm_lshv = B_sm_lshv.tolist() model_rf_lshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rf_lshv, pi) # Will be Trained model_rm_lshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rm_lshv, pi) # Will be Trained model_sf_lshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sf_lshv, pi) # Will be Trained model_sm_lshv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sm_lshv, pi) # Will be Trained # For Training total_seq_rf_lshv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_hslv[0:81,0:15], Fmat_original_lslv[0:81,0:15]))) total_seq_rm_lshv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_hslv[0:81,15:30], Fmat_original_lslv[0:81,15:28]))) total_seq_sf_lshv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_hslv[0:81,30:45], Fmat_original_lslv[0:81,28:37]))) total_seq_sm_lshv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_hslv[0:81,45:56], Fmat_original_lslv[0:81,37:45]))) train_seq_rf_lshv = (np.array(total_seq_rf_lshv).T).tolist() train_seq_rm_lshv = (np.array(total_seq_rm_lshv).T).tolist() train_seq_sf_lshv = (np.array(total_seq_sf_lshv).T).tolist() train_seq_sm_lshv = (np.array(total_seq_sm_lshv).T).tolist() #print train_seq_rf_lshv final_ts_rf_lshv = ghmm.SequenceSet(F,train_seq_rf_lshv) final_ts_rm_lshv = ghmm.SequenceSet(F,train_seq_rm_lshv) final_ts_sf_lshv = ghmm.SequenceSet(F,train_seq_sf_lshv) final_ts_sm_lshv = ghmm.SequenceSet(F,train_seq_sm_lshv) model_rf_lshv.baumWelch(final_ts_rf_lshv) model_rm_lshv.baumWelch(final_ts_rm_lshv) model_sf_lshv.baumWelch(final_ts_sf_lshv) model_sm_lshv.baumWelch(final_ts_sm_lshv) # For Testing total_seq_obj_lshv = Fmat_original_lshv[0:81,:] rf_lshv = np.matrix(np.zeros(np.size(total_seq_obj_lshv,1))) rm_lshv = np.matrix(np.zeros(np.size(total_seq_obj_lshv,1))) sf_lshv = np.matrix(np.zeros(np.size(total_seq_obj_lshv,1))) sm_lshv = np.matrix(np.zeros(np.size(total_seq_obj_lshv,1))) k = 0 while (k < np.size(total_seq_obj_lshv,1)): test_seq_obj_lshv = (np.array(total_seq_obj_lshv[0:81,k]).T).tolist() new_test_seq_obj_lshv = np.array(sum(test_seq_obj_lshv,[])) #print new_test_seq_obj_lshv ts_obj_lshv = new_test_seq_obj_lshv #print np.shape(ts_obj_lshv) final_ts_obj_lshv = ghmm.EmissionSequence(F,ts_obj_lshv.tolist()) # Find Viterbi Path path_rf_obj_lshv = model_rf_lshv.viterbi(final_ts_obj_lshv) path_rm_obj_lshv = model_rm_lshv.viterbi(final_ts_obj_lshv) path_sf_obj_lshv = model_sf_lshv.viterbi(final_ts_obj_lshv) path_sm_obj_lshv = model_sm_lshv.viterbi(final_ts_obj_lshv) obj_lshv = max(path_rf_obj_lshv[1],path_rm_obj_lshv[1],path_sf_obj_lshv[1],path_sm_obj_lshv[1]) if obj_lshv == path_rf_obj_lshv[1]: rf_lshv[0,k] = 1 elif obj_lshv == path_rm_obj_lshv[1]: rm_lshv[0,k] = 1 elif obj_lshv == path_sf_obj_lshv[1]: sf_lshv[0,k] = 1 else: sm_lshv[0,k] = 1 k = k+1 #print rf_lshv.T cmat[0][0] = cmat[0][0] + np.sum(rf_lshv[0,0:15]) cmat[0][1] = cmat[0][1] + np.sum(rf_lshv[0,15:16]) cmat[0][2] = cmat[0][2] + np.sum(rf_lshv[0,16:23]) cmat[0][3] = cmat[0][3] + np.sum(rf_lshv[0,23:32]) cmat[1][0] = cmat[1][0] + np.sum(rm_lshv[0,0:15]) cmat[1][1] = cmat[1][1] + np.sum(rm_lshv[0,15:16]) cmat[1][2] = cmat[1][2] + np.sum(rm_lshv[0,16:23]) cmat[1][3] = cmat[1][3] + np.sum(rm_lshv[0,23:32]) cmat[2][0] = cmat[2][0] + np.sum(sf_lshv[0,0:15]) cmat[2][1] = cmat[2][1] + np.sum(sf_lshv[0,15:16]) cmat[2][2] = cmat[2][2] + np.sum(sf_lshv[0,16:23]) cmat[2][3] = cmat[2][3] + np.sum(sf_lshv[0,23:32]) cmat[3][0] = cmat[3][0] + np.sum(sm_lshv[0,0:15]) cmat[3][1] = cmat[3][1] + np.sum(sm_lshv[0,15:16]) cmat[3][2] = cmat[3][2] + np.sum(sm_lshv[0,16:23]) cmat[3][3] = cmat[3][3] + np.sum(sm_lshv[0,23:32]) #print cmat ############################################################################################################################################# # LSLV as testing set and Rest as training set mu_rf_lslv,sigma_rf_lslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_hslv[0:81,0:15], Fmat_original_lshv[0:81,0:15])))) mu_rm_lslv,sigma_rm_lslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_hslv[0:81,15:30], Fmat_original_lshv[0:81,15:16])))) mu_sf_lslv,sigma_sf_lslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_hslv[0:81,30:45], Fmat_original_lshv[0:81,16:23])))) mu_sm_lslv,sigma_sm_lslv = feature_to_mu_sigma(np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_hslv[0:81,45:56], Fmat_original_lshv[0:81,23:32])))) # B - Emission Matrix, parameters of emission distributions in pairs of (mu, sigma) B_rf_lslv = np.zeros((10,2)) B_rm_lslv = np.zeros((10,2)) B_sf_lslv = np.zeros((10,2)) B_sm_lslv = np.zeros((10,2)) for num_states in range(10): B_rf_lslv[num_states,0] = mu_rf_lslv[num_states] B_rf_lslv[num_states,1] = sigma_rf_lslv[num_states] B_rm_lslv[num_states,0] = mu_rm_lslv[num_states] B_rm_lslv[num_states,1] = sigma_rm_lslv[num_states] B_sf_lslv[num_states,0] = mu_sf_lslv[num_states] B_sf_lslv[num_states,1] = sigma_sf_lslv[num_states] B_sm_lslv[num_states,0] = mu_sm_lslv[num_states] B_sm_lslv[num_states,1] = sigma_sm_lslv[num_states] B_rf_lslv = B_rf_lslv.tolist() B_rm_lslv = B_rm_lslv.tolist() B_sf_lslv = B_sf_lslv.tolist() B_sm_lslv = B_sm_lslv.tolist() model_rf_lslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rf_lslv, pi) # Will be Trained model_rm_lslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_rm_lslv, pi) # Will be Trained model_sf_lslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sf_lslv, pi) # Will be Trained model_sm_lslv = ghmm.HMMFromMatrices(F,ghmm.GaussianDistribution(F), A, B_sm_lslv, pi) # Will be Trained # For Training total_seq_rf_lslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,0:15], Fmat_original_hslv[0:81,0:15], Fmat_original_lshv[0:81,0:15]))) total_seq_rm_lslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:15], Fmat_original_hslv[0:81,15:30], Fmat_original_lshv[0:81,15:16]))) total_seq_sf_lslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,15:26], Fmat_original_hslv[0:81,30:45], Fmat_original_lshv[0:81,16:23]))) total_seq_sm_lslv = np.matrix(np.column_stack((Fmat_original_hshv[0:81,26:33], Fmat_original_hslv[0:81,45:56], Fmat_original_lshv[0:81,23:32]))) train_seq_rf_lslv = (np.array(total_seq_rf_lslv).T).tolist() train_seq_rm_lslv = (np.array(total_seq_rm_lslv).T).tolist() train_seq_sf_lslv = (np.array(total_seq_sf_lslv).T).tolist() train_seq_sm_lslv = (np.array(total_seq_sm_lslv).T).tolist() #print train_seq_rf_lslv final_ts_rf_lslv = ghmm.SequenceSet(F,train_seq_rf_lslv) final_ts_rm_lslv = ghmm.SequenceSet(F,train_seq_rm_lslv) final_ts_sf_lslv = ghmm.SequenceSet(F,train_seq_sf_lslv) final_ts_sm_lslv = ghmm.SequenceSet(F,train_seq_sm_lslv) model_rf_lslv.baumWelch(final_ts_rf_lslv) model_rm_lslv.baumWelch(final_ts_rm_lslv) model_sf_lslv.baumWelch(final_ts_sf_lslv) model_sm_lslv.baumWelch(final_ts_sm_lslv) # For Testing total_seq_obj_lslv = Fmat_original_lslv[0:81,:] rf_lslv = np.matrix(np.zeros(np.size(total_seq_obj_lslv,1))) rm_lslv = np.matrix(np.zeros(np.size(total_seq_obj_lslv,1))) sf_lslv = np.matrix(np.zeros(np.size(total_seq_obj_lslv,1))) sm_lslv = np.matrix(np.zeros(np.size(total_seq_obj_lslv,1))) k = 0 while (k < np.size(total_seq_obj_lslv,1)): test_seq_obj_lslv = (np.array(total_seq_obj_lslv[0:81,k]).T).tolist() new_test_seq_obj_lslv = np.array(sum(test_seq_obj_lslv,[])) #print new_test_seq_obj_lslv ts_obj_lslv = new_test_seq_obj_lslv #print np.shape(ts_obj_lslv) final_ts_obj_lslv = ghmm.EmissionSequence(F,ts_obj_lslv.tolist()) # Find Viterbi Path path_rf_obj_lslv = model_rf_lslv.viterbi(final_ts_obj_lslv) path_rm_obj_lslv = model_rm_lslv.viterbi(final_ts_obj_lslv) path_sf_obj_lslv = model_sf_lslv.viterbi(final_ts_obj_lslv) path_sm_obj_lslv = model_sm_lslv.viterbi(final_ts_obj_lslv) obj_lslv = max(path_rf_obj_lslv[1],path_rm_obj_lslv[1],path_sf_obj_lslv[1],path_sm_obj_lslv[1]) if obj_lslv == path_rf_obj_lslv[1]: rf_lslv[0,k] = 1 elif obj_lslv == path_rm_obj_lslv[1]: rm_lslv[0,k] = 1 elif obj_lslv == path_sf_obj_lslv[1]: sf_lslv[0,k] = 1 else: sm_lslv[0,k] = 1 k = k+1 #print rf_lslv.T cmat[0][0] = cmat[0][0] + np.sum(rf_lslv[0,0:15]) cmat[0][1] = cmat[0][1] + np.sum(rf_lslv[0,15:28]) cmat[0][2] = cmat[0][2] + np.sum(rf_lslv[0,28:37]) cmat[0][3] = cmat[0][3] + np.sum(rf_lslv[0,37:45]) cmat[1][0] = cmat[1][0] + np.sum(rm_lslv[0,0:15]) cmat[1][1] = cmat[1][1] + np.sum(rm_lslv[0,15:28]) cmat[1][2] = cmat[1][2] + np.sum(rm_lslv[0,28:37]) cmat[1][3] = cmat[1][3] + np.sum(rm_lslv[0,37:45]) cmat[2][0] = cmat[2][0] + np.sum(sf_lslv[0,0:15]) cmat[2][1] = cmat[2][1] + np.sum(sf_lslv[0,15:28]) cmat[2][2] = cmat[2][2] + np.sum(sf_lslv[0,28:37]) cmat[2][3] = cmat[2][3] + np.sum(sf_lslv[0,37:45]) cmat[3][0] = cmat[3][0] + np.sum(sm_lslv[0,0:15]) cmat[3][1] = cmat[3][1] + np.sum(sm_lslv[0,15:28]) cmat[3][2] = cmat[3][2] + np.sum(sm_lslv[0,28:37]) cmat[3][3] = cmat[3][3] + np.sum(sm_lslv[0,37:45]) #print cmat ############################################################################################################################################ # Plot Confusion Matrix Nlabels = 4 fig = pp.figure() ax = fig.add_subplot(111) figplot = ax.matshow(cmat, interpolation = 'nearest', origin = 'upper', extent=[0, Nlabels, 0, Nlabels]) ax.set_title('Performance of HMM Models') pp.xlabel("Targets") pp.ylabel("Predictions") ax.set_xticks([0.5,1.5,2.5,3.5]) ax.set_xticklabels(['Rigid-Fixed', 'Rigid-Movable', 'Soft-Fixed', 'Soft-Movable']) ax.set_yticks([3.5,2.5,1.5,0.5]) ax.set_yticklabels(['Rigid-Fixed', 'Rigid-Movable', 'Soft-Fixed', 'Soft-Movable']) figbar = fig.colorbar(figplot) i = 0 while (i < 4): j = 0 while (j < 4): pp.text(j+0.5,3.5-i,cmat[i][j]) j = j+1 i = i+1 pp.savefig('results_force_10_states.png') pp.show()
mit
jwlockhart/socialinsignificance
js/math.js
2807
/** * math functions used by the site. Almost all borrowed and slightly modified from other sources. */ /** * given the json descriptions for each group's distribution * generates data for plotting the probability density functions (bell curves) */ function gen_data(json, x){ var data = {}; //create a variable for each group, generate and save it's data for (var i = 0; i < json.group.length; i++){ data[json.group[i].name] = get_gaus_data(json.group[i].mean, json.group[i].stddiv, x); } return data; } /** * given all populations defined in the json file, returns the best xs to draw our curves */ function get_x(json){ //settings var points = 1000; var cutoff_deviations = 5; //internal variables var x = []; var tmp_first = []; var tmp_last = []; var tmp = 0; var first = 0; var last = 0; var step = 1; // a 0 here would cause infinite loops //find the ideal start and end for each series for (var i = 0; i < json.group.length; i++){ tmp = json.group[i].stddiv * cutoff_deviations; tmp_first.push(json.group[i].mean - tmp); tmp_last.push(json.group[i].mean + tmp); } //find the earliest start and latest end for all series, and make them ints first = Math.floor( Math.min.apply(null, tmp_first) ); last = Math.ceil( Math.max.apply(null, tmp_last) ); //find the step size to uniformly distribute out points over the range step = ( last - first ) / points; //populate an array of x values at which we want to display points for (var i = first; i < last; i += step){ x.push(i); } return x; } /** * produces data for a plotting the probability densitiy of a single gaussian distribution */ function get_gaus_data(mean, stddiv, x_vals){ var data = []; var y = 0; for (var i = 0; i < x_vals.length; i++){ y = pdf(i, mean, stddiv); point = { "x": i, "y": y }; data.push(point); } return data; } /** returns asample of interesting x values given two gaussian distributions * @depricated */ function get_x_vals(m1, sd1, m2, sd2){ var cutoff_deviations = 5; var points = 10000; var x = []; var first = m1 - (sd1 * cutoff_deviations); var tmp = m2 - (sd2 * cutoff_deviations); if (tmp < first){ first = tmp; } var last = m1 + (sd1 * cutoff_deviations); tmp = m2 + (sd2 * cutoff_deviations); if (tmp > last){ last = tmp; } var step = ( last - first ) / points; for (var i = first; i < last; i += step){ x.push(i); } return x; } // from https://github.com/errcw/gaussian/blob/master/lib/gaussian.js // probability density function function pdf(x, mean, stddiv) { var m = stddiv * Math.sqrt(2 * Math.PI); var e = Math.exp(-Math.pow(x - mean, 2) / (2 * (stddiv * stddiv))); return e / m; }
mit
todorm85/TelerikAcademy
Projects/VoiceShoppingList/VoiceShoppingList/app/src/main/java/com/telerik/academy/voiceshoppinglist/utilities/speech/MenuSpeechListener.java
2825
package com.telerik.academy.voiceshoppinglist.utilities.speech; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.speech.SpeechRecognizer; import android.widget.TextView; import android.widget.Toast; import com.telerik.academy.voiceshoppinglist.R; import com.telerik.academy.voiceshoppinglist.utilities.commands.MainMenuCommands; import com.telerik.academy.voiceshoppinglist.utilities.Constants; import com.telerik.academy.voiceshoppinglist.utilities.StringsSimilarityCalculator; import java.util.ArrayList; public class MenuSpeechListener extends BaseSpeechListener { public MenuSpeechListener(Activity activity, SpeechRecognizer speechRecognizer, Intent intent, Class intentClass) { super(activity, speechRecognizer, intent, intentClass); this.tag = MenuSpeechListener.class.getSimpleName(); } @Override protected boolean handleResults(ArrayList<String> data) { for (String commandString : data) { if (StringsSimilarityCalculator.calculateSimilarityCoefficient(Constants.ADD_SHOPPING_LIST_COMMAND, commandString) >= Constants.ACCEPTABLE_SIMILARITY_COEFFICIENT) { MainMenuCommands.navigateToAddNewShoppingListActivity(this.activity); this.commandsResult.setText(Constants.ADD_SHOPPING_LIST_COMMAND); return false; } else if (StringsSimilarityCalculator.calculateSimilarityCoefficient(Constants.STOP_LISTENING_COMMAND, commandString) >= Constants.ACCEPTABLE_SIMILARITY_COEFFICIENT) { this.speechRecognizer.destroy(); // Need to set speechRecognizer to null because the destroy() method doesn't work here. this.speechRecognizer = null; SpeechRecognitionHandler.stopListening(); this.commandsResult.setText(Constants.STOP_LISTENING_COMMAND); return false; } else if (StringsSimilarityCalculator.calculateSimilarityCoefficient(Constants.EXIT_APPLICATION_COMMAND, commandString) >= Constants.ACCEPTABLE_SIMILARITY_COEFFICIENT) { MainMenuCommands.exitApplication(this.activity); this.commandsResult.setText(Constants.EXIT_APPLICATION_COMMAND); return false; } } return true; } @Override protected SpeechRecognizer getSpeechRecognizer(Activity activity, Intent intent, Class intentClass) { return SpeechRecognizerFactory.createMenuSpeechRecognizer(this.activity, this.intent, this.intentClass); } @Override public void onReadyForSpeech(Bundle params) { Toast.makeText(this.activity, "Speak now!!!", Toast.LENGTH_SHORT).show(); super.onReadyForSpeech(params); } }
mit
scentuals-natural-organic-skincare/scentuals
.modman/seo_suite_ultimate/app/code/community/MageWorx/XSitemap/Block/Adminhtml/Xsitemap.php
642
<?php /** * MageWorx * MageWorx XSitemap Extension * * @category MageWorx * @package MageWorx_XSitemap * @copyright Copyright (c) 2015 MageWorx (http://www.mageworx.com/) */ class MageWorx_XSitemap_Block_Adminhtml_Xsitemap extends Mage_Adminhtml_Block_Widget_Grid_Container { public function __construct() { $this->_blockGroup = 'xsitemap'; $this->_controller = 'adminhtml_xsitemap'; $this->_headerText = Mage::helper('xsitemap')->__('Google Sitemap (Extended)'); $this->_addButtonLabel = Mage::helper('xsitemap')->__('Add Sitemap'); parent::__construct(); } }
mit
c910335/GHShop
view/artist.html.php
1420
<table class="table table-hover"> <thead> <tr> <th>#</th> <th>作者</th> </tr> </thead> <?php for($i = 0 ; isset($_['artist'][$i]) ; $i++): ?> <tr <?php if(! ($i % 2)) echo ' class="success"' ; ?>> <td> <div class="artistAnchor" id="<?php echo $_['artist'][$i]['Name'] ; ?>"><?php echo $i+1 ; ?></div> </td> <td onclick="location='.<?php echo $_['artist'][$i]['Name'] == $_GET['Artist'] ? '?Artist' : '?Artist=' . $_['artist'][$i]['Name'] ; echo '#' . $_['artist'][$i]['Name'] ; ?>'"><?php echo $_['artist'][$i]['Name'] ; ?></td> </tr> <?php if(isset($_['openArtist']) && $_['artist'][$i]['Name'] == $_['openArtist']): ?> <tr class="info"> <td colspan="2">作者簡介:</td> </tr> <tr class="active"> <td colspan="2"> <form action="ajax.php?modifyArtistIntroduction" id="artistIntroductionForm" method="post" style="margin-bottom: 0; margin-top: 0; width: 100%;" role="form"> <input type="number" name="modifyArtistId" value="<?php echo $_['artist'][$i]['Id'] ; ?>" hidden /> <div id="artistIntroduction" style="min-height: 22px; "><?php echo str_replace("\n", '<br>', $_['artist'][$i]['Introduction']) ; ?></div> </form> </td> </tr> </table> <?php include 'view/product.html.php' ; ?> <table class="table table-hover"> <?php endif ; ?> <?php endfor ; ?> </table>
mit
Qiyue-Lin/ecpim-mobile
src/js/code-behind/PrdOrCoSearchCodeBehind.js
5433
/** * Created by ceprei2598 on 2016/5/9. */ define(['text!../html/PrdOrCoSearchView.html','config', 'CompanyDetailViewCodeBehind', 'jquery', 'jquerymobile'], function (PrdOrCoSearch, config, CompanyDetailViewCodeBehind, $) { var PrdOrCoSearchCodeBehind = function () { var self = this; this.doSearchRouterHandler = function () { var searchType = $("#select-searchType").val(); //检索类型为产品 if(searchType == 1){ self.doProductSearchHandler(); //检索类型为公司 }else if(searchType == 2){ self.doCompanySearchHandler(); } }; this.doProductSearchHandler = function () { //清空上次搜索结果 $('#cont-searchResult').html(""); $.post(config.baseUrl + config.mainInfoAppSearch, { searchKey: $('#input-search').val() }, function (json) { var html = ""; for(var i = 0; i < json.data.length; i++){ var item = json.data[i]; html += '<li><a href="javascript:void(0)"><img src="img/ceprei.png"><h2>' + item.name + '</h2><p>' + item.companyName+ '</p></a></li>'; } $('#cont-searchResult').append(html); $('#cont-searchResult').listview("refresh"); $("#input-preSearchType").val("product"); $('#input-pageSize').val(15); $('#input-posStart').val(15); }, 'json'); }; this.doCompanySearchHandler = function () { //清空上次搜索结果 $('#cont-searchResult').html(""); $.post(config.baseUrl + config.codeCompanyAppSearch, { searchKey: $('#input-search').val() }, function (json) { var html = ""; for(var i = 0; i < json.data.length; i++){ var item = json.data[i]; html += '<li><a href="javascript:window.ecpimMobilePrdOrCoSearchModule.doRenderCompanyDetailView(\'' + item.code + '\')"><img src="img/ceprei.png"><h2>' + item.item + '</h2><p>' + item.itemEasy + '</p></a></li>'; } $('#cont-searchResult').append(html); $('#cont-searchResult').listview("refresh"); $("#input-preSearchType").val("company"); $('#input-pageSize').val(15); $('#input-posStart').val(15); }, 'json'); }; this.doLoadMoreTouchHandler = function () { var searchType = $("#select-searchType").val(); //检索类型为产品 if(searchType == 1){ self.doProductLoadMoreTouchHandler(); //检索类型为公司 }else if(searchType == 2){ self.doCompanyLoadMoreTouchHandler(); } }; this.doProductLoadMoreTouchHandler = function () { $.post(config.baseUrl + config.mainInfoAppSearch, { posStart: $('#input-posStart').val(), searchKey: $('#input-search').val() }, function (json) { var html = ""; for(var i = 0; i < json.data.length; i++){ var item = json.data[i]; html += '<li><a href="javascript:void(0)"><img src="img/ceprei.png"><h2>' + item.name + '</h2><p>' + item.companyName+ '</p></a></li>'; } $('#cont-searchResult').append(html); $('#cont-searchResult').listview("refresh"); $("#input-preSearchType").val("product"); $('#input-pageSize').val(15); $('#input-posStart').val(parseInt($('#input-pageSize').val()) + parseInt($('#input-posStart').val())); }, 'json'); }; this.doCompanyLoadMoreTouchHandler = function () { $.post(config.baseUrl + config.codeCompanyAppSearch, { posStart: $('#input-posStart').val(), searchKey: $('#input-search').val() }, function (json) { var html = ""; for(var i = 0; i < json.data.length; i++){ var item = json.data[i]; html += '<li><a href="javascript:window.ecpimMobilePrdOrCoSearchModule.doRenderCompanyDetailView(\'' + item.code + '\')"><img src="img/ceprei.png"><h2>' + item.item + '</h2><p>' + item.itemEasy + '</p></a></li>'; } $('#cont-searchResult').append(html); $('#cont-searchResult').listview("refresh"); $("#input-preSearchType").val("company"); $('#input-pageSize').val(15); $('#input-posStart').val(parseInt($('#input-pageSize').val()) + parseInt($('#input-posStart').val())); }, 'json'); }; this.doRenderCompanyDetailView = function (code) { new CompanyDetailViewCodeBehind(code); }; $(function () { $('#page-prdorcosearch').html(PrdOrCoSearch); $.mobile.changePage('#page-prdorcosearch'); $('#btn-search').on('click', self.doSearchRouterHandler); $('#btn-loadMore').on('click', self.doLoadMoreTouchHandler); window.ecpimMobilePrdOrCoSearchModule = self; }); }; return PrdOrCoSearchCodeBehind; });
mit
Laylan/E-sim
www/app/inbox/messages/writeMessage/write-message.controller.js
1960
(function () { 'use strict'; angular .module('write-message.module') .controller('WriteMessageController', WriteMessageController); WriteMessageController.$inject = ['$scope', '$ionicScrollDelegate', '$stateParams', 'Toast', 'WriteMessageData', 'MessagesData']; /* @ngInject */ function WriteMessageController($scope, $ionicScrollDelegate, $stateParams, Toast, WriteMessageData, MessagesData) { var vm = this; vm.property = 'WriteMessageController'; // variables vm.newMessageTitle = ''; vm.newMessage = ''; vm.receiverName = ''; vm.writeNewMessage = true; vm.showScrollTo = false; vm.position = $ionicScrollDelegate.getScrollPosition().top; // functions definitions vm.initPosition = initPosition; vm.scrollToTop = scrollToTop; vm.sendMessage = sendMessage; // init functions vm.initPosition(); vm.scrollToTop(); //////////////// if ($stateParams.receiver) { vm.receiverName = $stateParams.receiver; vm.newMessageTitle = 'Re: ' + $stateParams.title; MessagesData.fetchConversation($stateParams.receiverId, 1) .then(function FetchJobOffersSuccess(data) { //console.log(data); vm.prevMessages = data; }, function FetchJobOffersError(error) { Toast(error); console.log(error); }); vm.writeNewMessage = false; } function initPosition() { if (vm.position >= 250) { vm.showScrollTo = true; } else if (vm.position < 250) { vm.showScrollTo = false; } } function scrollToTop() { $ionicScrollDelegate.scrollTop(); } function sendMessage() { WriteMessageData.writeMessage(vm.newMessageTitle, vm.newMessage, vm.receiverName) .then(function Success() { vm.newMessageTitle = ''; vm.newMessage = ''; vm.receiverName = ''; }, function Error(msg) { Toast(msg); }); } } })();
mit
Azure/azure-sdk-for-java
sdk/appconfiguration/azure-spring-cloud-appconfiguration-config/src/test/java/com/azure/spring/cloud/config/stores/KeyVaultClientTest.java
7926
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.cloud.config.stores; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.azure.core.credential.TokenCredential; import com.azure.security.keyvault.secrets.SecretAsyncClient; import com.azure.security.keyvault.secrets.SecretClientBuilder; import com.azure.security.keyvault.secrets.models.KeyVaultSecret; import com.azure.spring.cloud.config.KeyVaultCredentialProvider; import com.azure.spring.cloud.config.KeyVaultSecretProvider; import com.azure.spring.cloud.config.properties.AppConfigurationProperties; import com.azure.spring.cloud.config.resource.AppConfigManagedIdentityProperties; import reactor.core.publisher.Mono; public class KeyVaultClientTest { static TokenCredential tokenCredential; private KeyVaultClient clientStore; @Mock private SecretClientBuilder builderMock; @Mock private SecretAsyncClient clientMock; @Mock private TokenCredential credentialMock; @Mock private Mono<KeyVaultSecret> monoSecret; private AppConfigurationProperties azureProperties; @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); } @AfterEach public void cleanup() throws Exception { MockitoAnnotations.openMocks(this).close(); } @Test public void multipleArguments() throws IOException, URISyntaxException { azureProperties = new AppConfigurationProperties(); AppConfigManagedIdentityProperties msiProps = new AppConfigManagedIdentityProperties(); msiProps.setClientId("testclientid"); azureProperties.setManagedIdentity(msiProps); String keyVaultUri = "https://keyvault.vault.azure.net/secrets/mySecret"; KeyVaultCredentialProvider provider = new KeyVaultCredentialProvider() { @Override public TokenCredential getKeyVaultCredential(String uri) { assertEquals("https://keyvault.vault.azure.net", uri); return credentialMock; } }; clientStore = new KeyVaultClient(azureProperties, new URI(keyVaultUri), provider, null, null); KeyVaultClient test = Mockito.spy(clientStore); Mockito.doReturn(builderMock).when(test).getBuilder(); Assertions.assertThrows(IllegalArgumentException.class, () -> test.build()); } @Test public void configProviderAuth() throws IOException, URISyntaxException { azureProperties = new AppConfigurationProperties(); AppConfigManagedIdentityProperties msiProps = null; azureProperties.setManagedIdentity(msiProps); String keyVaultUri = "https://keyvault.vault.azure.net/secrets/mySecret"; KeyVaultCredentialProvider provider = new KeyVaultCredentialProvider() { @Override public TokenCredential getKeyVaultCredential(String uri) { assertEquals("https://keyvault.vault.azure.net", uri); return credentialMock; } }; clientStore = new KeyVaultClient(azureProperties, new URI(keyVaultUri), provider, null, null); KeyVaultClient test = Mockito.spy(clientStore); Mockito.doReturn(builderMock).when(test).getBuilder(); when(builderMock.vaultUrl(Mockito.any())).thenReturn(builderMock); when(builderMock.buildAsyncClient()).thenReturn(clientMock); test.build(); when(clientMock.getSecret(Mockito.any(), Mockito.any())) .thenReturn(monoSecret); when(monoSecret.block(Mockito.any())).thenReturn(new KeyVaultSecret("", "")); assertNotNull(test.getSecret(new URI(keyVaultUri), 10)); assertEquals(test.getSecret(new URI(keyVaultUri), 10).getName(), ""); } @Test public void configClientIdAuth() throws IOException, URISyntaxException { azureProperties = new AppConfigurationProperties(); AppConfigManagedIdentityProperties msiProps = new AppConfigManagedIdentityProperties(); msiProps.setClientId("testClientId"); AppConfigManagedIdentityProperties test2 = Mockito.spy(msiProps); azureProperties.setManagedIdentity(test2); String keyVaultUri = "https://keyvault.vault.azure.net/secrets/mySecret"; clientStore = new KeyVaultClient(azureProperties, new URI(keyVaultUri), null, null, null); KeyVaultClient test = Mockito.spy(clientStore); Mockito.doReturn(builderMock).when(test).getBuilder(); when(builderMock.vaultUrl(Mockito.any())).thenReturn(builderMock); when(builderMock.buildAsyncClient()).thenReturn(clientMock); test.build(); when(clientMock.getSecret(Mockito.any(), Mockito.any())) .thenReturn(monoSecret); when(monoSecret.block(Mockito.any())).thenReturn(new KeyVaultSecret("", "")); assertNotNull(test.getSecret(new URI(keyVaultUri), 10)); assertEquals(test.getSecret(new URI(keyVaultUri), 10).getName(), ""); verify(test2, times(2)).getClientId(); } @Test public void systemAssignedCredentials() throws IOException, URISyntaxException { azureProperties = new AppConfigurationProperties(); AppConfigManagedIdentityProperties msiProps = new AppConfigManagedIdentityProperties(); msiProps.setClientId(""); AppConfigManagedIdentityProperties test2 = Mockito.spy(msiProps); azureProperties.setManagedIdentity(test2); String keyVaultUri = "https://keyvault.vault.azure.net/secrets/mySecret"; clientStore = new KeyVaultClient(azureProperties, new URI(keyVaultUri), null, null, null); KeyVaultClient test = Mockito.spy(clientStore); Mockito.doReturn(builderMock).when(test).getBuilder(); when(builderMock.vaultUrl(Mockito.any())).thenReturn(builderMock); when(builderMock.buildAsyncClient()).thenReturn(clientMock); test.build(); when(clientMock.getSecret(Mockito.any(), Mockito.any())) .thenReturn(monoSecret); when(monoSecret.block(Mockito.any())).thenReturn(new KeyVaultSecret("", "")); assertNotNull(test.getSecret(new URI(keyVaultUri), 10)); assertEquals(test.getSecret(new URI(keyVaultUri), 10).getName(), ""); verify(test2, times(1)).getClientId(); } @Test public void secretResolverTest() throws URISyntaxException { azureProperties = new AppConfigurationProperties(); String keyVaultUri = "https://keyvault.vault.azure.net/secrets/mySecret"; clientStore = new KeyVaultClient(azureProperties, new URI(keyVaultUri), null, null, new TestSecretResolver()); KeyVaultClient test = Mockito.spy(clientStore); Mockito.doReturn(builderMock).when(test).getBuilder(); when(builderMock.vaultUrl(Mockito.any())).thenReturn(builderMock); assertEquals("Test-Value", test.getSecret(new URI(keyVaultUri + "/testSecret"), 10).getValue()); assertEquals("Default-Secret", test.getSecret(new URI(keyVaultUri + "/testSecret2"), 10).getValue()); } class TestSecretResolver implements KeyVaultSecretProvider { @Override public String getSecret(String uri) { if (uri.endsWith("/testSecret")) { return "Test-Value"; } return "Default-Secret"; } } }
mit
crafn/clover
code/source/visual/armatureattachment_def.hpp
811
#ifndef CLOVER_VISUAL_ARMATUREATTACHMENT_DEF_HPP #define CLOVER_VISUAL_ARMATUREATTACHMENT_DEF_HPP #include "build.hpp" #include "util/objectnodetraits.hpp" #include "util/optional.hpp" #include "util/transform.hpp" #include "util/string.hpp" namespace clover { namespace visual { struct ArmatureAttachmentDef { using Transform= util::SrtTransform<real32, util::Quatf, util::Vec3f>; util::Str8 entityName; util::Str8 jointName; util::Optional<Transform> offset; }; } // visual namespace util { template <> struct ObjectNodeTraits<visual::ArmatureAttachmentDef>{ using Value= visual::ArmatureAttachmentDef; static util::ObjectNode serialized(const Value& value); static Value deserialized(const util::ObjectNode& ob); }; } // util } // clover #endif // CLOVER_VISUAL_ARMATUREATTACHMENT_DEF_HPP
mit
rocketnia/mvtron
src/main/groovy/com/rocketnia/mvtron/analyzer/ISceneDetector.java
190
// ISceneDetector.java // // Copyright 2009, 2010 Ross Angle package com.rocketnia.mvtron.analyzer; public interface ISceneDetector { public double measureDistance( int[] p, int[] n ); }
mit
GrUSP/opencfp
tests/Integration/Http/Controller/ForgotControllerTest.php
2391
<?php declare(strict_types=1); /** * Copyright (c) 2013-2019 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Test\Integration\Http\Controller; use OpenCFP\Domain\Services\AccountManagement; use OpenCFP\Test\Integration\TransactionalTestCase; use OpenCFP\Test\Integration\WebTestCase; final class ForgotControllerTest extends WebTestCase implements TransactionalTestCase { /** * @test */ public function sendResetDisplaysCorrectMessage() { $this->container->get(AccountManagement::class) ->create('[email protected]', 'some password'); $client = $this->createClient(); $form = $client->request('GET', '/forgot') ->selectButton('Reset Password') ->form(); $form->setValues(['forgot_form' => ['email' => '[email protected]']]); $client->followRedirects(); $client->submit($form); $this->assertContains( 'If your email was valid, we sent a link to reset your password to', $client->getResponse()->getContent() ); } /** * @test */ public function invalidResetFormTriggersErrorMessage() { $client = $this->createClient(); $form = $client->request('GET', '/forgot') ->selectButton('Reset Password') ->form(); $form->setValues(['forgot_form' => ['email' => 'INVALID']]); $client->followRedirects(); $client->submit($form); $this->assertContains( 'Please enter a properly formatted email address', $client->getResponse()->getContent() ); } /** * @test */ public function resetPasswordNotFindingUserCorrectlyDisplaysMessage() { $client = $this->createClient(); $form = $client->request('GET', '/forgot') ->selectButton('Reset Password') ->form(); $form->setValues(['forgot_form' => ['email' => '[email protected]']]); $client->followRedirects(); $client->submit($form); $this->assertContains( 'If your email was valid, we sent a link to reset your password to', $client->getResponse()->getContent() ); } }
mit
phpManufakturHeirs/kfEvent
Control/Backend/Subscribe.php
22892
<?php /** * Event * * @author Team phpManufaktur <[email protected]> * @link http://www.phpmanufaktur.info/de/kitframework/erweiterungen/event.php * @copyright 2013 Ralf Hertsch <[email protected]> * @license MIT License (MIT) http://www.opensource.org/licenses/MIT */ namespace phpManufaktur\Event\Control\Backend; use phpManufaktur\Event\Control\Backend\Backend; use Silex\Application; use phpManufaktur\Event\Data\Event\Subscription; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; use phpManufaktur\Event\Data\Event\EventSearch; use phpManufaktur\Event\Data\Event\Event as EventData; use phpManufaktur\Basic\Control\Pattern\Alert; use phpManufaktur\Contact\Data\Contact\Message; class Subscribe extends Backend { protected $EventSearch = null; protected $EventData = null; protected $SubscriptionData = null; protected function initialize(Application $app) { parent::initialize($app); $this->EventSearch = new EventSearch($app); $this->EventData = new EventData($app); $this->SubscriptionData = new Subscription($app); } /** * Get the search field for the Contact * */ protected function getSearchContactFormFields() { return $this->app['form.factory']->createBuilder('form') ->add('search_contact', 'text', array( )); } /** * Form: Select the contact * * @param array $contacts */ protected function getSelectContactFormFields($contacts=array()) { $select_contacts = array(); foreach ($contacts as $contact) { $select_contacts[$contact['contact_id']] = sprintf('%s [%s] %s %s %s', $contact['contact_name'], $contact['communication_email'], $contact['address_zip'], $contact['address_city'], $contact['address_street'] ); } return $this->app['form.factory']->createBuilder('form') ->add('contact_id', 'choice', array( 'choices' => $select_contacts, 'empty_value' => '- please select -', 'expanded' => false, 'required' => true, 'label' => 'Contact search' )); } /** * Get the search field for the Event * * @param array $data */ protected function getSearchEventFormFields($data=array()) { return $this->app['form.factory']->createBuilder('form', $data) ->add('contact_id', 'hidden', array( 'data' => isset($data['contact_id']) ? $data['contact_id'] : -1 )) ->add('search_event', 'text'); } /** * Get the final subscription form fields * * @param array $data */ protected function getSubscriptionFormFields($data=array()) { $event_array = array(); if (isset($data['events'])) { foreach ($data['events'] as $event) { $event_array[$event['event_id']] = sprintf('[%05d] %s - %s', $event['event_id'], date($this->app['translator']->trans('DATE_FORMAT'), strtotime($event['event_date_from'])), $event['description_title'] ); } } if (isset($data['contact_id'])) { $contact = $this->app['contact']->selectOverview($data['contact_id']); } return $this->app['form.factory']->createBuilder('form', $data) ->add('contact_id', 'hidden', array( 'data' => isset($data['contact_id']) ? $data['contact_id'] : -1 )) ->add('subscriber', 'text', array( 'data' => isset($contact['contact_name']) ? $contact['contact_name'] : '', 'disabled' => true, 'required' => false )) ->add('event_id', 'choice', array( 'choices' => isset($event_array) ? $event_array : null, 'empty_value' => '- please select -', 'label' => 'Select event' )) ->add('remark', 'textarea', array( 'data' => isset($data['remark']) ? $data['remark'] : '', 'required' => false )) ; } /** * Add the subscription to the database * * @param Application $app * @return string */ public function ControllerFinishSubscription(Application $app) { $this->initialize($app); $data = $this->app['request']->request->get('form'); if (!isset($data['contact_id']) || !isset($data['event_id'])) { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); $subRequest = Request::create('/admin/event/subscription/add/start', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } // handle the subscription if (false === ($event = $this->EventData->selectEvent($data['event_id']))) { throw new \Exception('The Event with the ID '.$data['event_id'].' does not exists!'); } $message_id = -1; if (isset($data['remark']) && !empty($data['remark'])) { // insert a new Message $message_id = $this->app['contact']->addMessage( $data['contact_id'], $event['description_title'], $data['remark'], 'Event', 'Subscription', $data['event_id'] ); } $data = array( 'event_id' => $data['event_id'], 'contact_id' => $data['contact_id'], 'message_id' => $message_id, 'subscription_participants' => 1, 'subscription_date' => date('Y-m-d H:i:s'), 'subscription_guid' => $this->app['utils']->createGUID(), 'subscription_status' => 'CONFIRMED' ); $this->SubscriptionData->insert($data); $this->setAlert('The subscription was successfull inserted.'); $subRequest = Request::create('/admin/event/subscription', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } /** * Check the submitted event search term and show a selection for a event * * @param Application $app * @return \Symfony\Component\HttpFoundation\Response */ public function ControllerSearchEvent(Application $app) { $this->initialize($app); $fields = $this->getSearchEventFormFields(); $form = $fields->getForm(); if ('POST' == $this->app['request']->getMethod()) { // the form was submitted, bind the request $form->bind($this->app['request']); if ($form->isValid()) { $data = $form->getData(); // check the term in event search if (false === ($events = $this->EventSearch->search($data['search_event']))) { // no hits for the search term $this->setAlert('No hits for the search term <i>%search%</i>!', array('%search%' => $data['search_event'])); $fields = $this->getSearchEventFormFields($data); $form = $fields->getForm(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/event.add.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView() )); } else { $data['events'] = $events; $fields = $this->getSubscriptionFormFields($data); $form = $fields->getForm(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/form.add.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView() )); } } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); $subRequest = Request::create('/admin/event/subscription/add/start', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); $subRequest = Request::create('/admin/event/subscription/add/start', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } } /** * Controller to add a selected contact and show the search field for an event * * @param Application $app * @return \Symfony\Component\HttpFoundation\Response */ public function ControllerAddContact(Application $app) { $this->initialize($app); $fields = $this->getSearchEventFormFields(); $form = $fields->getForm(); if ('POST' == $this->app['request']->getMethod()) { // the form was submitted, bind the request $form->bind($this->app['request']); if ($form->isValid()) { $data = $form->getData(); $fields = $this->getSearchEventFormFields($data); $form = $fields->getForm(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/event.add.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView() )); } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); $subRequest = Request::create('/admin/event/subscription/add/start', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); $subRequest = Request::create('/admin/event/subscription/add/start', 'GET', array('usage' => self::$usage)); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } } /** * Start Controller to subscribe a contact to an event * * @param Application $app */ public function ControllerAddSubscriptionStart(Application $app) { $this->initialize($app); $fields = $this->getSearchContactFormFields(); $form = $fields->getForm(); if ('POST' == $this->app['request']->getMethod()) { // the form was submitted, bind the request $form->bind($this->app['request']); if ($form->isValid()) { $data = $form->getData(); if (false === ($contacts = $app['contact']->searchContact($data['search_contact']))) { $this->setAlert('No hits for the search term <i>%search%</i>!', array('%search%' => $data['search_contact'])); } else { $fields = $this->getSelectContactFormFields($contacts); $form = $fields->getForm(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/contact.add.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView() )); } } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); } } else { // set the intro text $this->setAlert('Please search for the contact you want to subscribe to an event or add a new contact, if you are shure that the person does not exists in Contacts.'); } return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/start.add.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView() )); } /** * Show the list with the subscriptions * * @return string rendered dialog */ public function ControllerList(Application $app) { $this->initialize($app); $limit = ( isset(self::$config['event']['subscription']['limit']) && is_numeric(self::$config['event']['subscription']['limit']) ) ? self::$config['event']['subscription']['limit'] : 100 ; $days = ( isset(self::$config['event']['subscription']['add_days_to_event']) && is_numeric(self::$config['event']['subscription']['add_days_to_event']) ) ? self::$config['event']['subscription']['add_days_to_event'] : 30 ; $SubscriptionData = new Subscription($app); $subscriptions = $SubscriptionData->selectList($limit, $days); $sum = $SubscriptionData->countSubscriptions(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/list.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'subscriptions' => $subscriptions, 'alert' => $this->getAlert(), 'showing' => count($subscriptions), 'sum' => $sum, 'limit' => $limit, 'days' => $days )); } /** * Get the final subscription form fields * * @param array $data */ protected function getSubscriptionEditFields($data=array()) { $remark = ''; if (isset($data['subscription']['message_id']) && ($data['subscription']['message_id'] > 0)) { $MessageData = new Message($this->app); if (false === ($msg = $MessageData->select($data['subscription']['message_id']))) { throw new \Exception('Missing the message ID '.$data['subscription']['message_id']); } $remark = $msg['message_content']; } return $this->app['form.factory']->createBuilder('form', $data) ->add('subscription_id', 'hidden', array( 'data' => isset($data['subscription']['subscription_id']) ? $data['subscription']['subscription_id'] : -1 )) ->add('status', 'choice', array( 'expanded' => false, 'multiple' => false, 'choices' => array( 'PENDING' => $this->app['translator']->trans('Pending'), 'CONFIRMED' => $this->app['translator']->trans('Confirmed'), 'CANCELED' => $this->app['translator']->trans('Canceled'), 'LOCKED' => $this->app['translator']->trans('Locked') ), 'data' => isset($data['subscription']['subscription_status']) ? $data['subscription']['subscription_status'] : 'LOCKED' )) ->add('remark', 'textarea', array( 'data' => $remark, 'required' => false )) ; } public function ControllerEditSubscription(Application $app, $subscription_id) { $this->initialize($app); if (false === ($subscription = $this->SubscriptionData->select($subscription_id))) { $this->setAlert('The Subscription with the ID %subscription_id% does not exists!', array('%subscription_id%' => $subscription_id), Alert::ALERT_TYPE_DANGER); return $this->ControllerList($app); } if (false === ($contact = $this->app['contact']->selectOverview($subscription['contact_id']))) { $this->setAlert("The contact with the ID %contact_id% does not exists!", array('%contact_id%' => $subscription['contact_id']), Alert::ALERT_TYPE_DANGER); return $this->ControllerList($app); } if (false === ($event = $this->EventData->selectEvent($subscription['event_id'], false))) { $this->setAlert('The record with the ID %id% does not exists!', array('%id%' => $subscription['event_id']), Alert::ALERT_TYPE_DANGER); return $this->ControllerList($app); } $data = array( 'subscription' => $subscription, 'contact' => $contact, 'event' => $event ); $fields = $this->getSubscriptionEditFields($data); $form = $fields->getForm(); return $this->app['twig']->render($this->app['utils']->getTemplateFile( '@phpManufaktur/Event/Template', 'admin/edit.subscription.twig'), array( 'usage' => self::$usage, 'toolbar' => $this->getToolbar('subscription'), 'alert' => $this->getAlert(), 'form' => $form->createView(), 'data' => $data )); } public function ControllerCheckSubscription(Application $app) { $this->initialize($app); $fields = $this->getSubscriptionEditFields(); $form = $fields->getForm(); $form->bind($this->app['request']); if ($form->isValid()) { $data = $form->getData(); if (false === ($subscription = $this->SubscriptionData->select($data['subscription_id']))) { $this->setAlert('The Subscription with the ID %subscription_id% does not exists!', array('%subscription_id%' => $data['subscription_id']), Alert::ALERT_TYPE_DANGER); return $this->ControllerList($app); } $MessageData = new Message($this->app); $remark = ''; if ($subscription['message_id'] > 0) { if (false === ($msg = $MessageData->select($subscription['message_id']))) { throw new \Exception('Missing the message ID '.$subscription['message_id']); } $remark = $msg['message_content']; } if (($data['status'] != $subscription['subscription_status']) || ($data['remark'] != $remark)) { if ($subscription['message_id'] > 0) { // update the message record $MessageData->update(array('message_content' => $data['remark']), $subscription['message_id']); } else { // create a new message record if (false === ($event = $this->EventData->selectEvent($subscription['event_id'], false))) { $this->setAlert('The record with the ID %id% does not exists!', array('%id%' => $subscription['event_id']), Alert::ALERT_TYPE_DANGER); return $this->ControllerList($app); } $MessageData->insert(array( 'contact_id' => $subscription['contact_id'], 'application_name' => 'Event', 'application_marker_type' => 'Subscription', 'application_marker_id' => $subscription['event_id'], 'message_title' => isset($event['description_title']) ? $event['description_title'] : '', 'message_content' => strip_tags($data['remark']), 'message_date' => date('Y-m-d H:i:s')), $subscription['message_id']); } $this->SubscriptionData->update($data['subscription_id'], array( 'subscription_status' => $data['status'], 'message_id' => $subscription['message_id'] )); $this->setAlert('The subscription was successfull updated'); } } else { // general error (timeout, CSFR ...) $this->setAlert('The form is not valid, please check your input and try again!', array(), self::ALERT_TYPE_DANGER, true, array('form_errors' => $form->getErrorsAsString(), 'method' => __METHOD__, 'line' => __LINE__)); } return $this->ControllerList($app); } }
mit
JornWildt/ZimmerBot
ZimmerBot.Core/Utilities/StringTemplateErrorHandler.cs
790
using Antlr4.StringTemplate; using Antlr4.StringTemplate.Misc; using log4net; namespace ZimmerBot.Core.Utilities { // Avoid error output to console // - Especially relevant when allowing using of undefined attributes in templates. public class StringTemplateErrorHandler : ITemplateErrorListener { private static ILog Logger = LogManager.GetLogger(typeof(StringTemplateErrorHandler)); public void CompiletimeError(TemplateMessage msg) { Logger.Warn(msg); } public void InternalError(TemplateMessage msg) { Logger.Warn(msg); } public void IOError(TemplateMessage msg) { Logger.Warn(msg); } public void RuntimeError(TemplateMessage msg) { Logger.Warn(msg); } } }
mit
rockwotj/PieServer
test_scripts/get_test.py
1982
import re import socket HOST = '127.0.0.1' # The remote host PORT = 8080 # The same port as used by the server ### TEST HELPER METHODS ### def ormap(func, seq): result = False booleans = map(func, seq) for b in booleans: result = bool(b) or result return result def andmap(func, seq): result = True booleans = map(func, seq) for b in booleans: result = bool(b) and result return result ### START TESTS ### print '===BEGIN GET TEST 1 ===' print 'Testing HTTP v1.0 GET request' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) request = """GET / HTTP/1.0\r\n""" s.sendall(request) data = s.recv(4096) response_lines = data.split('\r\n') expected = 'HTTP/1.1 200 OK' print 'Expecting line 1 of response to be: ', expected print 'Got: ', response_lines[0] if expected == response_lines[0]: print 'PASSED TEST 1' else: print 'FAILED TEST 1' s.close() print '===BEGIN GET TEST 2 ===' print 'Testing HTTP v1.1 GET request' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) request = """GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n""" s.sendall(request) data = s.recv(4096) response_lines = data.split('\r\n') expected = 'HTTP/1.1 200 OK' print 'Expecting line 1 of response to be: ', expected print 'Got: ', response_lines[0] if expected == response_lines[0]: print 'PASSED TEST 2' else: print 'FAILED TEST 2' s.close() print '===BEGIN GET TEST 3 ===' print 'Testing HTTP v1.1 GET request' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) request = """GET /wilkin_loves_kid_rock.html HTTP/1.1\r\nHost: 127.0.0.1\r\n""" s.sendall(request) data = s.recv(4096) response_lines = data.split('\r\n') expected = 'HTTP/1.1 404 Not Found' print 'Expecting line 1 of response to be: ', expected print 'Got: ', response_lines[0] if expected == response_lines[0]: print 'PASSED TEST 3' else: print 'FAILED TEST 3' s.close()
mit
joekhoobyar/cardiac
spec/rails-3.2/app_root/config/environments/test.rb
449
CardiacTest::Application.configure do config.cache_classes = true config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" config.whiny_nils = true config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_dispatch.show_exceptions = false config.action_controller.allow_forgery_protection = false config.active_support.deprecation = :stderr end
mit
mikolalysenko/regl
www/gallery/tile.min.js.js
118006
(function e$$0(u,y,c){function f(e,m){if(!y[e]){if(!u[e]){var b="function"==typeof require&&require;if(!m&&b)return b(e,!0);if(h)return h(e,!0);b=Error("Cannot find module '"+e+"'");throw b.code="MODULE_NOT_FOUND",b;}b=y[e]={exports:{}};u[e][0].call(b.exports,function(b){var c=u[e][1][b];return f(c?c:b)},b,b.exports,e$$0,u,y,c)}return y[e].exports}for(var h="function"==typeof require&&require,w=0;w<c.length;w++)f(c[w]);return f})({1:[function(k,u,y){var c=k("../regl")(),f=k("mouse-change")();k("resl")({manifest:{map:{type:"text", src:"assets/map.json",parser:JSON.parse},tiles:{type:"image",src:"assets/tiles.png",parser:c.texture}},onDone:function(h){var w=h.map,e=c({frag:"\n precision mediump float;\n uniform sampler2D map, tiles;\n uniform vec2 mapSize, tileSize;\n varying vec2 uv;\n void main() {\n vec2 tileCoord = floor(255.0 * texture2D(map, floor(uv) / mapSize).ra);\n gl_FragColor = texture2D(tiles, (tileCoord + fract(uv)) / tileSize);\n }",vert:"\n precision mediump float;\n attribute vec2 position;\n uniform vec4 view;\n varying vec2 uv;\n void main() {\n uv = mix(view.xw, view.zy, 0.5 * (1.0 + position));\n gl_Position = vec4(position, 1, 1);\n }", depth:{enable:!1},uniforms:{tiles:h.tiles,tileSize:[16,16],map:c.texture(w),mapSize:[w[0].length,w.length],view:c.prop("view")},attributes:{position:[-1,-1,1,-1,-1,1,1,1,-1,1,1,-1]},count:6});c.frame(function(c){var b=c.viewportWidth,h=c.viewportHeight;c=w[0].length*f.x/b;var k=w.length*f.y/h,b=b/h*10;e({view:[c-.5*b,k-5,c+.5*b,k+5]})})}})},{"../regl":38,"mouse-change":35,resl:37}],2:[function(k,u,y){function c(){this.w=this.z=this.y=this.x=this.state=0;this.buffer=null;this.size=0;this.normalized= !1;this.type=5126;this.divisor=this.stride=this.offset=0}u.exports=function(f,h,w,e,m){f=w.maxAttributes;h=Array(f);for(w=0;w<f;++w)h[w]=new c;return{Record:c,scope:{},state:h}}},{}],3:[function(k,u,y){function c(b){return v[Object.prototype.toString.call(b)]|0}function f(b,c){for(var e=0;e<c.length;++e)b[e]=c[e]}function h(b,c,e,f,m,h,l){for(var a=0,d=0;d<e;++d)for(var w=0;w<f;++w)b[a++]=c[m*d+h*w+l]}var w=k("./util/check"),e=k("./util/is-typed-array"),m=k("./util/is-ndarray"),b=k("./util/values"), n=k("./util/pool");y=k("./util/flatten");var E=y.flatten,C=y.shape,v=k("./constants/arraytypes.json"),q=k("./constants/dtypes.json"),F=k("./constants/usage.json"),A=[];A[5120]=1;A[5122]=2;A[5124]=4;A[5121]=1;A[5123]=2;A[5125]=4;A[5126]=4;u.exports=function(k,v,p){function r(b){this.id=a++;this.buffer=k.createBuffer();this.type=b;this.usage=35044;this.byteLength=0;this.dimension=1;this.dtype=5121;this.persistentData=null;p.profile&&(this.stats={size:0})}function N(b,a,d){b.byteLength=a.byteLength; k.bufferData(b.type,a,d)}function I(b,a,d,l,q,r){b.usage=d;if(Array.isArray(a)){if(b.dtype=l||5126,0<a.length)if(Array.isArray(a[0])){q=C(a);for(var p=l=1;p<q.length;++p)l*=q[p];b.dimension=l;a=E(a,q,b.dtype);N(b,a,d);r?b.persistentData=a:n.freeType(a)}else"number"===typeof a[0]?(b.dimension=q,q=n.allocType(b.dtype,a.length),f(q,a),N(b,q,d),r?b.persistentData=q:n.freeType(q)):e(a[0])?(b.dimension=a[0].length,b.dtype=l||c(a[0])||5126,a=E(a,[a.length,a[0].length],b.dtype),N(b,a,d),r?b.persistentData= a:n.freeType(a)):w.raise("invalid buffer data")}else if(e(a))b.dtype=l||c(a),b.dimension=q,N(b,a,d),r&&(b.persistentData=new Uint8Array(new Uint8Array(a.buffer)));else if(m(a)){q=a.shape;var k=a.stride,p=a.offset,K=0,Q=0,v=0,I=0;1===q.length?(K=q[0],Q=1,v=k[0],I=0):2===q.length?(K=q[0],Q=q[1],v=k[0],I=k[1]):w.raise("invalid shape");b.dtype=l||c(a.data)||5126;b.dimension=Q;q=n.allocType(b.dtype,K*Q);h(q,a.data,K,Q,v,I,p);N(b,q,d);r?b.persistentData=q:n.freeType(q)}else w.raise("invalid buffer data")} function l(b){v.bufferCount--;var a=b.buffer;w(a,"buffer must not be deleted already");k.deleteBuffer(a);b.buffer=null;delete d[b.id]}var a=0,d={};r.prototype.bind=function(){k.bindBuffer(this.type,this.buffer)};r.prototype.destroy=function(){l(this)};var K=[];p.profile&&(v.getTotalBufferSize=function(){var b=0;Object.keys(d).forEach(function(a){b+=d[a].stats.size});return b});return{create:function(b,a,K,N){function H(b){var a=35044,d=null,c=0,f=0,l=1;Array.isArray(b)||e(b)||m(b)?d=b:"number"=== typeof b?c=b|0:b&&(w.type(b,"object","buffer arguments must be an object, a number or an array"),"data"in b&&(w(null===d||Array.isArray(d)||e(d)||m(d),"invalid data for buffer"),d=b.data),"usage"in b&&(w.parameter(b.usage,F,"invalid buffer usage"),a=F[b.usage]),"type"in b&&(w.parameter(b.type,q,"invalid buffer type"),f=q[b.type]),"dimension"in b&&(w.type(b.dimension,"number","invalid dimension"),l=b.dimension|0),"length"in b&&(w.nni(c,"buffer length must be a nonnegative integer"),c=b.length|0)); J.bind();d?I(J,d,a,f,l,N):(k.bufferData(J.type,c,a),J.dtype=f||5121,J.usage=a,J.dimension=l,J.byteLength=c);p.profile&&(J.stats.size=J.byteLength*A[J.dtype]);return H}function u(b,a){w(a+b.byteLength<=J.byteLength,"invalid buffer subdata call, buffer is too small. Can't write data of size "+b.byteLength+" starting from offset "+a+" to a buffer of size "+J.byteLength);k.bufferSubData(J.type,a,b)}v.bufferCount++;var J=new r(a);d[J.id]=J;K||H(b);H._reglType="buffer";H._buffer=J;H.subdata=function(b, a){var d=(a||0)|0,l;J.bind();if(Array.isArray(b)){if(0<b.length)if("number"===typeof b[0]){var q=n.allocType(J.dtype,b.length);f(q,b);u(q,d);n.freeType(q)}else Array.isArray(b[0])||e(b[0])?(l=C(b),q=E(b,l,J.dtype),u(q,d),n.freeType(q)):w.raise("invalid buffer data")}else if(e(b))u(b,d);else if(m(b)){l=b.shape;var V=b.stride,r=q=0,p=0,K=0;1===l.length?(q=l[0],r=1,p=V[0],K=0):2===l.length?(q=l[0],r=l[1],p=V[0],K=V[1]):w.raise("invalid shape");l=Array.isArray(b.data)?J.dtype:c(b.data);l=n.allocType(l, q*r);h(l,b.data,q,r,p,K,b.offset);u(l,d);n.freeType(l)}else w.raise("invalid data for buffer subdata");return H};p.profile&&(H.stats=J.stats);H.destroy=function(){l(J)};return H},createStream:function(b,a){var d=K.pop();d||(d=new r(b));d.bind();I(d,a,35040,0,1,!1);return d},destroyStream:function(b){K.push(b)},clear:function(){b(d).forEach(l);K.forEach(l)},getBuffer:function(b){return b&&b._buffer instanceof r?b._buffer:null},restore:function(){b(d).forEach(function(b){b.buffer=k.createBuffer();k.bindBuffer(b.type, b.buffer);k.bufferData(b.type,b.persistentData||b.byteLength,b.usage)})},_initBuffer:I}}},{"./constants/arraytypes.json":4,"./constants/dtypes.json":5,"./constants/usage.json":7,"./util/check":21,"./util/flatten":25,"./util/is-ndarray":27,"./util/is-typed-array":28,"./util/pool":30,"./util/values":33}],4:[function(k,u,y){u.exports={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123, "[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121}},{}],5:[function(k,u,y){u.exports={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,"float":5126,float32:5126}},{}],6:[function(k,u,y){u.exports={points:0,point:0,lines:1,line:1,"line loop":2,"line strip":3,triangles:4,triangle:4,"triangle strip":5,"triangle fan":6}},{}],7:[function(k,u,y){u.exports={"static":35044,dynamic:35048,stream:35040}},{}],8:[function(k,u,y){function c(b){return Array.isArray(b)|| C(b)||v(b)}function f(b){return b.sort(function(b,a){return"viewport"===b?-1:"viewport"===a?1:b<a?-1:1})}function h(b,a,d,c){this.thisDep=b;this.contextDep=a;this.propDep=d;this.append=c}function w(b){return b&&!(b.thisDep||b.contextDep||b.propDep)}function e(b){return new h(!1,!1,!1,b)}function m(b,a){var d=b.type;return 0===d?(d=b.data.length,new h(!0,1<=d,2<=d,a)):4===d?(d=b.data,new h(d.thisDep,d.contextDep,d.propDep,a)):new h(3===d,2===d,1===d,a)}var b=k("./util/check"),n=k("./util/codegen"), E=k("./util/loop"),C=k("./util/is-typed-array"),v=k("./util/is-ndarray"),q=k("./util/is-array-like"),F=k("./dynamic"),A=k("./constants/primitives.json"),B=k("./constants/dtypes.json"),G=["x","y","z","w"],p="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),r={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772, "one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},N="constant color, constant alpha;one minus constant color, constant alpha;constant color, one minus constant alpha;one minus constant color, one minus constant alpha;constant alpha, constant color;constant alpha, one minus constant color;one minus constant alpha, constant color;one minus constant alpha, one minus constant color".split(";"), I={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},l={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},a={frag:35632,vert:35633},d={cw:2304,ccw:2305},K=new h(!1,!1,!1,function(){});u.exports=function(k,v,C,u,H,ia,J,y,da,Q,M,ra,ka,oa,wa){function ba(b){return b.replace(".","_")}function S(b,a,g){var d=ba(b); Ga.push(b);pa[d]=x[d]=!!g;Aa[d]=a}function O(b,a,g){var d=ba(b);Ga.push(b);Array.isArray(g)?(x[d]=g.slice(),pa[d]=g.slice()):x[d]=pa[d]=g;Ba[d]=a}function Ca(){var a=n(),g=a.link,d=a.global;a.id=Qa++;a.batchId="0";var c=g(Oa),e=a.shared={props:"a0"};Object.keys(Oa).forEach(function(b){e[b]=d.def(c,".",b)});b.optional(function(){a.CHECK=g(b);a.commandStr=b.guessCommand();a.command=g(a.commandStr);a.assert=function(b,a,d){b("if(!(",a,"))",this.CHECK,".commandRaise(",g(d),",",this.command,");")};Ha.invalidBlendCombinations= N});var P=a.next={},l=a.current={};Object.keys(Ba).forEach(function(b){Array.isArray(x[b])&&(P[b]=d.def(e.next,".",b),l[b]=d.def(e.current,".",b))});var Ra=a.constants={};Object.keys(Ha).forEach(function(b){Ra[b]=d.def(JSON.stringify(Ha[b]))});a.invoke=function(b,d){switch(d.type){case 0:var L=["this",e.context,e.props,a.batchId];return b.def(g(d.data),".call(",L.slice(0,Math.max(d.data.length+1,4)),")");case 1:return b.def(e.props,d.data);case 2:return b.def(e.context,d.data);case 3:return b.def("this", d.data);case 4:return d.data.append(a,b),d.data.ref}};a.attribCache={};var L={};a.scopeAttrib=function(b){b=v.id(b);if(b in L)return L[b];var a=Q.scope[b];a||(a=Q.scope[b]=new sa);return L[b]=g(a)};return a}function ta(b){var a=b["static"];b=b.dynamic;var g;if("profile"in a){var d=!!a.profile;g=e(function(b,a){return d});g.enable=d}else if("profile"in b){var c=b.profile;g=m(c,function(b,a){return b.invoke(a,c)})}return g}function xa(a,g){var d=a["static"],c=a.dynamic;if("framebuffer"in d){var l=d.framebuffer; return l?(l=y.getFramebuffer(l),b.command(l,"invalid framebuffer object"),e(function(b,a){var g=b.link(l),d=b.shared;a.set(d.framebuffer,".next",g);d=d.context;a.set(d,".framebufferWidth",g+".width");a.set(d,".framebufferHeight",g+".height");return g})):e(function(b,a){var g=b.shared;a.set(g.framebuffer,".next","null");g=g.context;a.set(g,".framebufferWidth",g+".drawingBufferWidth");a.set(g,".framebufferHeight",g+".drawingBufferHeight");return"null"})}if("framebuffer"in c){var P=c.framebuffer;return m(P, function(a,g){var d=a.invoke(g,P),D=a.shared,X=D.framebuffer,t=g.def(X,".getFramebuffer(",d,")");b.optional(function(){a.assert(g,"!"+d+"||"+t,"invalid framebuffer object")});g.set(X,".next",t);D=D.context;g.set(D,".framebufferWidth",t+"?"+t+".width:"+D+".drawingBufferWidth");g.set(D,".framebufferHeight",t+"?"+t+".height:"+D+".drawingBufferHeight");return t})}return null}function ca(a,g,d){function c(a){if(a in e){var L=e[a];b.commandType(L,"object","invalid "+a,d.commandStr);var t=!0,X=L.x|0,l=L.y| 0,x,f;"width"in L?(x=L.width|0,b.command(0<=x,"invalid "+a,d.commandStr)):t=!1;"height"in L?(f=L.height|0,b.command(0<=f,"invalid "+a,d.commandStr)):t=!1;return new h(!t&&g&&g.thisDep,!t&&g&&g.contextDep,!t&&g&&g.propDep,function(b,a){var g=b.shared.context,d=x;"width"in L||(d=a.def(g,".","framebufferWidth","-",X));var t=f;"height"in L||(t=a.def(g,".","framebufferHeight","-",l));return[X,l,d,t]})}if(a in P){var q=P[a],t=m(q,function(g,d){var L=g.invoke(d,q);b.optional(function(){g.assert(d,L+"&&typeof "+ L+'==="object"',"invalid "+a)});var X=g.shared.context,t=d.def(L,".x|0"),D=d.def(L,".y|0"),c=d.def('"width" in ',L,"?",L,".width|0:","(",X,".","framebufferWidth","-",t,")"),e=d.def('"height" in ',L,"?",L,".height|0:","(",X,".","framebufferHeight","-",D,")");b.optional(function(){g.assert(d,c+">=0&&"+e+">=0","invalid "+a)});return[t,D,c,e]});g&&(t.thisDep=t.thisDep||g.thisDep,t.contextDep=t.contextDep||g.contextDep,t.propDep=t.propDep||g.propDep);return t}return g?new h(g.thisDep,g.contextDep,g.propDep, function(b,a){var g=b.shared.context;return[0,0,a.def(g,".","framebufferWidth"),a.def(g,".","framebufferHeight")]}):null}var e=a["static"],P=a.dynamic;if(a=c("viewport")){var l=a;a=new h(a.thisDep,a.contextDep,a.propDep,function(b,a){var g=l.append(b,a),d=b.shared.context;a.set(d,".viewportWidth",g[2]);a.set(d,".viewportHeight",g[3]);return g})}return{viewport:a,scissor_box:c("scissor.box")}}function ja(g){function d(g){if(g in c){var L=v.id(c[g]);b.optional(function(){M.shader(a[g],L,b.guessCommand())}); var t=e(function(){return L});t.id=L;return t}if(g in l){var X=l[g];return m(X,function(d,L){var t=d.invoke(L,X),D=L.def(d.shared.strings,".id(",t,")");b.optional(function(){L(d.shared.shader,".shader(",a[g],",",D,",",d.command,");")});return D})}return null}var c=g["static"],l=g.dynamic,x=d("frag"),P=d("vert"),f=null;w(x)&&w(P)?(f=M.program(P.id,x.id),g=e(function(b,a){return b.link(f)})):g=new h(x&&x.thisDep||P&&P.thisDep,x&&x.contextDep||P&&P.contextDep,x&&x.propDep||P&&P.propDep,function(a,g){var d= a.shared.shader,X;X=x?x.append(a,g):g.def(d,".","frag");var t;t=P?P.append(a,g):g.def(d,".","vert");var D=d+".program("+t+","+X;b.optional(function(){D+=","+a.command});return g.def(D+")")});return{frag:x,vert:P,progVar:g,program:f}}function la(a,g){function d(a,L){if(a in l){var t=l[a]|0;b.command(!L||0<=t,"invalid "+a,g.commandStr);return e(function(b,a){L&&(b.OFFSET=t);return t})}if(a in x){var X=x[a];return m(X,function(g,d){var t=g.invoke(d,X);L&&(g.OFFSET=t,b.optional(function(){g.assert(d, t+">=0","invalid "+a)}));return t})}return L&&P?e(function(b,a){b.OFFSET="0";return 0}):null}var l=a["static"],x=a.dynamic,P=function(){if("elements"in l){var a=l.elements;c(a)?a=ia.getElements(ia.create(a,!0)):a&&(a=ia.getElements(a),b.command(a,"invalid elements",g.commandStr));var d=e(function(b,g){if(a){var d=b.link(a);return b.ELEMENTS=d}return b.ELEMENTS=null});d.value=a;return d}if("elements"in x){var t=x.elements;return m(t,function(a,g){var d=a.shared,L=d.isBufferArgs,d=d.elements,D=a.invoke(g, t),c=g.def("null"),L=g.def(L,"(",D,")"),e=a.cond(L).then(c,"=",d,".createStream(",D,");")["else"](c,"=",d,".getElements(",D,");");b.optional(function(){a.assert(e["else"],"!"+D+"||"+c,"invalid elements")});g.entry(e);g.exit(a.cond(L).then(d,".destroyStream(",c,");"));return a.ELEMENTS=c})}return null}(),f=d("offset",!0);return{elements:P,primitive:function(){if("primitive"in l){var a=l.primitive;b.commandParameter(a,A,"invalid primitve",g.commandStr);return e(function(b,g){return A[a]})}if("primitive"in x){var d=x.primitive;return m(d,function(a,g){var t=a.constants.primTypes,D=a.invoke(g,d);b.optional(function(){a.assert(g,D+" in "+t,"invalid primitive, must be one of "+Object.keys(A))});return g.def(t,"[",D,"]")})}return P?w(P)?P.value?e(function(b,a){return a.def(b.ELEMENTS,".primType")}):e(function(){return 4}):new h(P.thisDep,P.contextDep,P.propDep,function(b,a){var g=b.ELEMENTS;return a.def(g,"?",g,".primType:",4)}):null}(),count:function(){if("count"in l){var a=l.count|0;b.command("number"=== typeof a&&0<=a,"invalid vertex count",g.commandStr);return e(function(){return a})}if("count"in x){var d=x.count;return m(d,function(a,g){var t=a.invoke(g,d);b.optional(function(){a.assert(g,"typeof "+t+'==="number"&&'+t+">=0&&"+t+"===("+t+"|0)","invalid vertex count")});return t})}if(P){if(w(P)){if(P)return f?new h(f.thisDep,f.contextDep,f.propDep,function(a,g){var d=g.def(a.ELEMENTS,".vertCount-",a.OFFSET);b.optional(function(){a.assert(g,d+">=0","invalid vertex offset/element buffer too small")}); return d}):e(function(b,a){return a.def(b.ELEMENTS,".vertCount")});var t=e(function(){return-1});b.optional(function(){t.MISSING=!0});return t}var X=new h(P.thisDep||f.thisDep,P.contextDep||f.contextDep,P.propDep||f.propDep,function(b,a){var g=b.ELEMENTS;return b.OFFSET?a.def(g,"?",g,".vertCount-",b.OFFSET,":-1"):a.def(g,"?",g,".vertCount:-1")});b.optional(function(){X.DYNAMIC=!0});return X}return null}(),instances:d("instances",!1),offset:f}}function ma(a,g){var c=a["static"],x=a.dynamic,f={};Ga.forEach(function(a){function t(b, g){if(a in c){var d=b(c[a]);f[h]=e(function(){return d})}else if(a in x){var D=x[a];f[h]=m(D,function(b,a){return g(b,a,b.invoke(a,D))})}}var h=ba(a);switch(a){case "cull.enable":case "blend.enable":case "dither":case "stencil.enable":case "depth.enable":case "scissor.enable":case "polygonOffset.enable":case "sample.alpha":case "sample.enable":case "depth.mask":return t(function(d){b.commandType(d,"boolean",a,g.commandStr);return d},function(g,d,t){b.optional(function(){g.assert(d,"typeof "+t+'==="boolean"', "invalid flag "+a,g.commandStr)});return t});case "depth.func":return t(function(d){b.commandParameter(d,I,"invalid "+a,g.commandStr);return I[d]},function(g,d,t){var c=g.constants.compareFuncs;b.optional(function(){g.assert(d,t+" in "+c,"invalid "+a+", must be one of "+Object.keys(I))});return d.def(c,"[",t,"]")});case "depth.range":return t(function(a){b.command(q(a)&&2===a.length&&"number"===typeof a[0]&&"number"===typeof a[1]&&a[0]<=a[1],"depth range is 2d array",g.commandStr);return a},function(a, g,d){b.optional(function(){a.assert(g,a.shared.isArrayLike+"("+d+")&&"+d+".length===2&&typeof "+d+'[0]==="number"&&typeof '+d+'[1]==="number"&&'+d+"[0]<="+d+"[1]","depth range must be a 2d array")});var t=g.def("+",d,"[0]"),c=g.def("+",d,"[1]");return[t,c]});case "blend.func":return t(function(a){b.commandType(a,"object","blend.func",g.commandStr);var d="srcRGB"in a?a.srcRGB:a.src,t="srcAlpha"in a?a.srcAlpha:a.src,c="dstRGB"in a?a.dstRGB:a.dst;a="dstAlpha"in a?a.dstAlpha:a.dst;b.commandParameter(d, r,h+".srcRGB",g.commandStr);b.commandParameter(t,r,h+".srcAlpha",g.commandStr);b.commandParameter(c,r,h+".dstRGB",g.commandStr);b.commandParameter(a,r,h+".dstAlpha",g.commandStr);b.command(-1===N.indexOf(d+", "+c),"unallowed blending combination (srcRGB, dstRGB) = ("+d+", "+c+")",g.commandStr);return[r[d],r[c],r[t],r[a]]},function(g,d,t){function c(e,l){var x=d.def('"',e,l,'" in ',t,"?",t,".",e,l,":",t,".",e);b.optional(function(){g.assert(d,x+" in "+D,"invalid "+a+"."+e+l+", must be one of "+Object.keys(r))}); return x}var D=g.constants.blendFuncs;b.optional(function(){g.assert(d,t+"&&typeof "+t+'==="object"',"invalid blend func, must be an object")});var e=c("src","RGB"),l=c("dst","RGB");b.optional(function(){g.assert(d,g.constants.invalidBlendCombinations+".indexOf("+e+'+", "+'+l+") === -1 ","unallowed blending combination for (srcRGB, dstRGB)")});var x=d.def(D,"[",e,"]"),f=d.def(D,"[",c("src","Alpha"),"]"),h=d.def(D,"[",l,"]"),m=d.def(D,"[",c("dst","Alpha"),"]");return[x,h,f,m]});case "blend.equation":return t(function(d){if("string"=== typeof d)return b.commandParameter(d,ea,"invalid "+a,g.commandStr),[ea[d],ea[d]];if("object"===typeof d)return b.commandParameter(d.rgb,ea,a+".rgb",g.commandStr),b.commandParameter(d.alpha,ea,a+".alpha",g.commandStr),[ea[d.rgb],ea[d.alpha]];b.commandRaise("invalid blend.equation",g.commandStr)},function(g,d,t){var c=g.constants.blendEquations,D=d.def(),e=d.def(),l=g.cond("typeof ",t,'==="string"');b.optional(function(){function b(a,d,t){g.assert(a,t+" in "+c,"invalid "+d+", must be one of "+Object.keys(ea))} b(l.then,a,t);g.assert(l["else"],t+"&&typeof "+t+'==="object"',"invalid "+a);b(l["else"],a+".rgb",t+".rgb");b(l["else"],a+".alpha",t+".alpha")});l.then(D,"=",e,"=",c,"[",t,"];");l["else"](D,"=",c,"[",t,".rgb];",e,"=",c,"[",t,".alpha];");d(l);return[D,e]});case "blend.color":return t(function(a){b.command(q(a)&&4===a.length,"blend.color must be a 4d array",g.commandStr);return E(4,function(b){return+a[b]})},function(a,g,d){b.optional(function(){a.assert(g,a.shared.isArrayLike+"("+d+")&&"+d+".length===4", "blend.color must be a 4d array")});return E(4,function(b){return g.def("+",d,"[",b,"]")})});case "stencil.mask":return t(function(a){b.commandType(a,"number",h,g.commandStr);return a|0},function(a,g,d){b.optional(function(){a.assert(g,"typeof "+d+'==="number"',"invalid stencil.mask")});return g.def(d,"|0")});case "stencil.func":return t(function(d){b.commandType(d,"object",h,g.commandStr);var t=d.cmp||"keep",c=d.ref||0;d="mask"in d?d.mask:-1;b.commandParameter(t,I,a+".cmp",g.commandStr);b.commandType(c, "number",a+".ref",g.commandStr);b.commandType(d,"number",a+".mask",g.commandStr);return[I[t],c,d]},function(a,g,d){var t=a.constants.compareFuncs;b.optional(function(){function b(){a.assert(g,Array.prototype.join.call(arguments,""),"invalid stencil.func")}b(d+"&&typeof ",d,'==="object"');b('!("cmp" in ',d,")||(",d,".cmp in ",t,")")});var c=g.def('"cmp" in ',d,"?",t,"[",d,".cmp]",":",7680),D=g.def(d,".ref|0"),e=g.def('"mask" in ',d,"?",d,".mask|0:-1");return[c,D,e]});case "stencil.opFront":case "stencil.opBack":return t(function(d){b.commandType(d, "object",h,g.commandStr);var t=d.fail||"keep",c=d.zfail||"keep";d=d.zpass||"keep";b.commandParameter(t,l,a+".fail",g.commandStr);b.commandParameter(c,l,a+".zfail",g.commandStr);b.commandParameter(d,l,a+".zpass",g.commandStr);return["stencil.opBack"===a?1029:1028,l[t],l[c],l[d]]},function(g,d,t){function c(e){b.optional(function(){g.assert(d,'!("'+e+'" in '+t+")||("+t+"."+e+" in "+D+")","invalid "+a+"."+e+", must be one of "+Object.keys(l))});return d.def('"',e,'" in ',t,"?",D,"[",t,".",e,"]:",7680)} var D=g.constants.stencilOps;b.optional(function(){g.assert(d,t+"&&typeof "+t+'==="object"',"invalid "+a)});return["stencil.opBack"===a?1029:1028,c("fail"),c("zfail"),c("zpass")]});case "polygonOffset.offset":return t(function(a){b.commandType(a,"object",h,g.commandStr);var d=a.factor|0;a=a.units|0;b.commandType(d,"number",h+".factor",g.commandStr);b.commandType(a,"number",h+".units",g.commandStr);return[d,a]},function(g,d,t){b.optional(function(){g.assert(d,t+"&&typeof "+t+'==="object"',"invalid "+ a)});var c=d.def(t,".factor|0"),D=d.def(t,".units|0");return[c,D]});case "cull.face":return t(function(a){var d=0;"front"===a?d=1028:"back"===a&&(d=1029);b.command(!!d,h,g.commandStr);return d},function(a,g,d){b.optional(function(){a.assert(g,d+'==="front"||'+d+'==="back"',"invalid cull.face")});return g.def(d,'==="front"?',1028,":",1029)});case "lineWidth":return t(function(a){b.command("number"===typeof a&&a>=u.lineWidthDims[0]&&a<=u.lineWidthDims[1],"invalid line width, must positive number between "+ u.lineWidthDims[0]+" and "+u.lineWidthDims[1],g.commandStr);return a},function(a,g,d){b.optional(function(){a.assert(g,"typeof "+d+'==="number"&&'+d+">="+u.lineWidthDims[0]+"&&"+d+"<="+u.lineWidthDims[1],"invalid line width")});return d});case "frontFace":return t(function(a){b.commandParameter(a,d,h,g.commandStr);return d[a]},function(a,g,d){b.optional(function(){a.assert(g,d+'==="cw"||'+d+'==="ccw"',"invalid frontFace, must be one of cw,ccw")});return g.def(d+'==="cw"?2304:2305')});case "colorMask":return t(function(a){b.command(q(a)&& 4===a.length,"color.mask must be length 4 array",g.commandStr);return a.map(function(a){return!!a})},function(a,g,d){b.optional(function(){a.assert(g,a.shared.isArrayLike+"("+d+")&&"+d+".length===4","invalid color.mask")});return E(4,function(a){return"!!"+d+"["+a+"]"})});case "sample.coverage":return t(function(a){b.command("object"===typeof a&&a,h,g.commandStr);var d="value"in a?a.value:1;a=!!a.invert;b.command("number"===typeof d&&0<=d&&1>=d,"sample.coverage.value must be a number between 0 and 1", g.commandStr);return[d,a]},function(a,g,d){b.optional(function(){a.assert(g,d+"&&typeof "+d+'==="object"',"invalid sample.coverage")});var t=g.def('"value" in ',d,"?+",d,".value:1"),c=g.def("!!",d,".invert");return[t,c]})}});return f}function na(a,g){var d=a["static"],c=a.dynamic,l={};Object.keys(d).forEach(function(a){var t=d[a],c;if("number"===typeof t||"boolean"===typeof t)c=e(function(){return t});else if("function"===typeof t){var x=t._reglType;"texture2d"===x||"textureCube"===x?c=e(function(a){return a.link(t)}): "framebuffer"===x||"framebufferCube"===x?(b.command(0<t.color.length,'missing color attachment for framebuffer sent to uniform "'+a+'"',g.commandStr),c=e(function(a){return a.link(t.color[0])})):b.commandRaise('invalid data for uniform "'+a+'"',g.commandStr)}else q(t)?c=e(function(g){return g.global.def("[",E(t.length,function(d){b.command("number"===typeof t[d]||"boolean"===typeof t[d],"invalid uniform "+a,g.commandStr);return t[d]}),"]")}):b.commandRaise('invalid or missing data for uniform "'+ a+'"',g.commandStr);c.value=t;l[a]=c});Object.keys(c).forEach(function(a){var b=c[a];l[a]=m(b,function(a,g){return a.invoke(g,b)})});return l}function qa(a,d){var l=a["static"],x=a.dynamic,f={};Object.keys(l).forEach(function(a){var t=l[a],x=v.id(a),h=new sa;if(c(t))h.state=1,h.buffer=H.getBuffer(H.create(t,34962,!1,!0)),h.type=0;else{var m=H.getBuffer(t);if(m)h.state=1,h.buffer=m,h.type=0;else if(b.command("object"===typeof t&&t,"invalid data for attribute "+a,d.commandStr),t.constant){var z=t.constant; h.buffer="null";h.state=2;"number"===typeof z?h.x=z:(b.command(q(z)&&0<z.length&&4>=z.length,"invalid constant for attribute "+a,d.commandStr),G.forEach(function(a,b){b<z.length&&(h[a]=z[b])}))}else{m=c(t.buffer)?H.getBuffer(H.create(t.buffer,34962,!1,!0)):H.getBuffer(t.buffer);b.command(!!m,'missing buffer for attribute "'+a+'"',d.commandStr);var w=t.offset|0;b.command(0<=w,'invalid offset for attribute "'+a+'"',d.commandStr);var r=t.stride|0;b.command(0<=r&&256>r,'invalid stride for attribute "'+ a+'", must be integer betweeen [0, 255]',d.commandStr);var p=t.size|0;b.command(!("size"in t)||0<p&&4>=p,'invalid size for attribute "'+a+'", must be 1,2,3,4',d.commandStr);var k=!!t.normalized,K=0;"type"in t&&(b.commandParameter(t.type,B,"invalid type for attribute "+a,d.commandStr),K=B[t.type]);var n=t.divisor|0;"divisor"in t&&(b.command(0===n||g,'cannot specify divisor for attribute "'+a+'", instancing not supported',d.commandStr),b.command(0<=n,'invalid divisor for attribute "'+a+'"',d.commandStr)); b.optional(function(){var g=d.commandStr,c="buffer offset divisor normalized type size stride".split(" ");Object.keys(t).forEach(function(d){b.command(0<=c.indexOf(d),'unknown parameter "'+d+'" for attribute pointer "'+a+'" (valid parameters are '+c+")",g)})});h.buffer=m;h.state=1;h.size=p;h.normalized=k;h.type=K||m.dtype;h.offset=w;h.stride=r;h.divisor=n}}f[a]=e(function(a,b){var d=a.attribCache;if(x in d)return d[x];var g={isStream:!1};Object.keys(h).forEach(function(a){g[a]=h[a]});h.buffer&&(g.buffer= a.link(h.buffer),g.type=g.type||g.buffer+".dtype");return d[x]=g})});Object.keys(x).forEach(function(a){var d=x[a];f[a]=m(d,function(g,t){function c(a){t(f[a],"=",e,".",a,"|0;")}var e=g.invoke(t,d),l=g.shared,D=l.isBufferArgs,x=l.buffer;b.optional(function(){g.assert(t,e+"&&(typeof "+e+'==="object"||typeof '+e+'==="function")&&('+D+"("+e+")||"+x+".getBuffer("+e+")||"+x+".getBuffer("+e+".buffer)||"+D+"("+e+'.buffer)||("constant" in '+e+"&&(typeof "+e+'.constant==="number"||'+l.isArrayLike+"("+e+".constant))))", 'invalid dynamic attribute "'+a+'"')});var f={isStream:t.def(!1)},h=new sa;h.state=1;Object.keys(h).forEach(function(a){f[a]=t.def(""+h[a])});var m=f.buffer,q=f.type;t("if(",D,"(",e,")){",f.isStream,"=true;",m,"=",x,".createStream(",34962,",",e,");",q,"=",m,".dtype;","}else{",m,"=",x,".getBuffer(",e,");","if(",m,"){",q,"=",m,".dtype;",'}else if("constant" in ',e,"){",f.state,"=",2,";","if(typeof "+e+'.constant === "number"){',f[G[0]],"=",e,".constant;",G.slice(1).map(function(a){return f[a]}).join("="), "=0;","}else{",G.map(function(a,b){return f[a]+"="+e+".constant.length>="+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{","if(",D,"(",e,".buffer)){",m,"=",x,".createStream(",34962,",",e,".buffer);","}else{",m,"=",x,".getBuffer(",e,".buffer);","}",q,'="type" in ',e,"?",l.glTypes,"[",e,".type]:",m,".dtype;",f.normalized,"=!!",e,".normalized;");c("size");c("offset");c("stride");c("divisor");t("}}");t.exit("if(",f.isStream,"){",x,".destroyStream(",m,");","}");return f})});return f}function ya(a){var b= a["static"],d=a.dynamic,g={};Object.keys(b).forEach(function(a){var d=b[a];g[a]=e(function(a,b){return"number"===typeof d||"boolean"===typeof d?""+d:a.link(d)})});Object.keys(d).forEach(function(a){var b=d[a];g[a]=m(b,function(a,d){return a.invoke(d,b)})});return g}function W(a,d,g,c,e){function l(a){var d=m[a];d&&(z[a]=d)}var x=a["static"],f=a.dynamic;b.optional(function(){function a(g){Object.keys(g).forEach(function(a){b.command(0<=d.indexOf(a),'unknown parameter "'+a+'"',e.commandStr)})}var d= "framebuffer vert frag elements primitive offset count instances profile".split(" ").concat(Ga);a(x);a(f)});var h=xa(a,e),m=ca(a,h,e),q=la(a,e),z=ma(a,e),w=ja(a,e);l("viewport");l(ba("scissor.box"));var r=0<Object.keys(z).length,h={framebuffer:h,draw:q,shader:w,state:z,dirty:r};h.profile=ta(a,e);h.uniforms=na(g,e);h.attributes=qa(d,e);h.context=ya(c,e);return h}function Z(a,d,b){var g=a.shared.context,c=a.scope();Object.keys(b).forEach(function(e){d.save(g,"."+e);c(g,".",e,"=",b[e].append(a,d),";")}); d(c)}function T(a,d,b,g){var c=a.shared,e=c.gl,l=c.framebuffer,x;z&&(x=d.def(c.extensions,".webgl_draw_buffers"));var f=a.constants,c=f.drawBuffer,f=f.backBuffer;a=b?b.append(a,d):d.def(l,".next");g||d("if(",a,"!==",l,".cur){");d("if(",a,"){",e,".bindFramebuffer(",36160,",",a,".framebuffer);");z&&d(x,".drawBuffersWEBGL(",c,"[",a,".colorAttachments.length]);");d("}else{",e,".bindFramebuffer(",36160,",null);");z&&d(x,".drawBuffersWEBGL(",f,");");d("}",l,".cur=",a,";");g||d("}")}function U(a,d,b){var g= a.shared,c=g.gl,e=a.current,l=a.next,f=g.current,h=g.next,m=a.cond(f,".dirty");Ga.forEach(function(d){d=ba(d);if(!(d in b.state)){var g,D;if(d in l){g=l[d];D=e[d];var q=E(x[d].length,function(a){return m.def(g,"[",a,"]")});m(a.cond(q.map(function(a,d){return a+"!=="+D+"["+d+"]"}).join("||")).then(c,".",Ba[d],"(",q,");",q.map(function(a,d){return D+"["+d+"]="+a}).join(";"),";"))}else g=m.def(h,".",d),q=a.cond(g,"!==",f,".",d),m(q),d in Aa?q(a.cond(g).then(c,".enable(",Aa[d],");")["else"](c,".disable(", Aa[d],");"),f,".",d,"=",g,";"):q(c,".",Ba[d],"(",g,");",f,".",d,"=",g,";")}});0===Object.keys(b.state).length&&m(f,".dirty=false;");d(m)}function R(a,d,g,b){var c=a.shared,e=a.current,l=c.current,x=c.gl;f(Object.keys(g)).forEach(function(c){var f=g[c];if(!b||b(f)){var h=f.append(a,d);if(Aa[c]){var m=Aa[c];w(f)?h?d(x,".enable(",m,");"):d(x,".disable(",m,");"):d(a.cond(h).then(x,".enable(",m,");")["else"](x,".disable(",m,");"));d(l,".",c,"=",h,";")}else if(q(h)){var z=e[c];d(x,".",Ba[c],"(",h,");", h.map(function(a,d){return z+"["+d+"]="+a}).join(";"),";")}else d(x,".",Ba[c],"(",h,");",l,".",c,"=",h,";")}})}function aa(a,d){g&&(a.instancing=d.def(a.shared.extensions,".angle_instanced_arrays"))}function fa(a,d,g,b,c){function e(){return"undefined"===typeof performance?"Date.now()":"performance.now()"}function l(a){r=d.def();a(r,"=",e(),";");"string"===typeof c?a(m,".count+=",c,";"):a(m,".count++;");oa&&(b?(p=d.def(),a(p,"=",z,".getNumPendingQueries();")):a(z,".beginQuery(",m,");"))}function x(a){a(m, ".cpuTime+=",e(),"-",r,";");oa&&(b?a(z,".pushScopeStats(",p,",",z,".getNumPendingQueries(),",m,");"):a(z,".endQuery();"))}function f(a){var g=d.def(q,".profile");d(q,".profile=",a,";");d.exit(q,".profile=",g,";")}var h=a.shared,m=a.stats,q=h.current,z=h.timer;g=g.profile;var r,p;if(g){if(w(g)){g.enable?(l(d),x(d.exit),f("true")):f("false");return}g=g.append(a,d);f(g)}else g=d.def(q,".profile");h=a.block();l(h);d("if(",g,"){",h,"}");a=a.block();x(a);d.exit("if(",g,"){",a,"}")}function za(a,d,c,e,l){function x(a){switch(a){case 35664:case 35667:case 35671:return 2; case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}function f(b,c,e){function l(){d("if(!",z,".buffer){",m,".enableVertexAttribArray(",q,");}");var b=e.type,x;x=e.size?d.def(e.size,"||",c):c;d("if(",z,".type!==",b,"||",z,".size!==",x,"||",p.map(function(a){return z+"."+a+"!=="+e[a]}).join("||"),"){",m,".bindBuffer(",34962,",",w,".buffer);",m,".vertexAttribPointer(",[q,x,b,e.normalized,e.stride,e.offset],");",z,".type=",b,";",z,".size=",x,";",p.map(function(a){return z+ "."+a+"="+e[a]+";"}).join(""),"}");g&&(b=e.divisor,d("if(",z,".divisor!==",b,"){",a.instancing,".vertexAttribDivisorANGLE(",[q,b],");",z,".divisor=",b,";}"))}function x(){d("if(",z,".buffer){",m,".disableVertexAttribArray(",q,");","}if(",G.map(function(a,d){return z+"."+a+"!=="+r[d]}).join("||"),"){",m,".vertexAttrib4f(",q,",",r,");",G.map(function(a,d){return z+"."+a+"="+r[d]+";"}).join(""),"}")}var m=h.gl,q=d.def(b,".location"),z=d.def(h.attributes,"[",q,"]");b=e.state;var w=e.buffer,r=[e.x,e.y, e.z,e.w],p=["buffer","normalized","offset","stride"];1===b?l():2===b?x():(d("if(",b,"===",1,"){"),l(),d("}else{"),x(),d("}"))}var h=a.shared;e.forEach(function(g){var e=g.name,h=c.attributes[e],m;if(h){if(!l(h))return;m=h.append(a,d)}else{if(!l(K))return;var q=a.scopeAttrib(e);b.optional(function(){a.assert(d,q+".state","missing attribute "+e)});m={};Object.keys(new sa).forEach(function(a){m[a]=d.def(q,".",a)})}f(a.link(g),x(g.info.type),m)})}function ha(a,d,g,c,e){for(var x=a.shared,l=x.gl,f,h=0;h< c.length;++h){var m=c[h],z=m.name,r=m.info.type,p=g.uniforms[z],m=a.link(m)+".location",k;if(p){if(!e(p))continue;if(w(p)){var n=p.value;b.command(null!==n&&"undefined"!==typeof n,'missing uniform "'+z+'"',a.commandStr);if(35678===r||35680===r)b.command("function"===typeof n&&(35678===r&&("texture2d"===n._reglType||"framebuffer"===n._reglType)||35680===r&&("textureCube"===n._reglType||"framebufferCube"===n._reglType)),"invalid texture for uniform "+z,a.commandStr),p=a.link(n._texture||n.color[0]._texture), d(l,".uniform1i(",m,",",p+".bind());"),d.exit(p,".unbind();");else if(35674===r||35675===r||35676===r){b.optional(function(){b.command(q(n),"invalid matrix for uniform "+z,a.commandStr);b.command(35674===r&&4===n.length||35675===r&&9===n.length||35676===r&&16===n.length,"invalid length for matrix uniform "+z,a.commandStr)});var p=a.global.def("new Float32Array(["+Array.prototype.slice.call(n)+"])"),Q=2;35675===r?Q=3:35676===r&&(Q=4);d(l,".uniformMatrix",Q,"fv(",m,",false,",p,");")}else{switch(r){case 5126:b.commandType(n, "number","uniform "+z,a.commandStr);f="1f";break;case 35664:b.command(q(n)&&2===n.length,"uniform "+z,a.commandStr);f="2f";break;case 35665:b.command(q(n)&&3===n.length,"uniform "+z,a.commandStr);f="3f";break;case 35666:b.command(q(n)&&4===n.length,"uniform "+z,a.commandStr);f="4f";break;case 35670:b.commandType(n,"boolean","uniform "+z,a.commandStr);f="1i";break;case 5124:b.commandType(n,"number","uniform "+z,a.commandStr);f="1i";break;case 35671:b.command(q(n)&&2===n.length,"uniform "+z,a.commandStr); f="2i";break;case 35667:b.command(q(n)&&2===n.length,"uniform "+z,a.commandStr);f="2i";break;case 35672:b.command(q(n)&&3===n.length,"uniform "+z,a.commandStr);f="3i";break;case 35668:b.command(q(n)&&3===n.length,"uniform "+z,a.commandStr);f="3i";break;case 35673:b.command(q(n)&&4===n.length,"uniform "+z,a.commandStr);f="4i";break;case 35669:b.command(q(n)&&4===n.length,"uniform "+z,a.commandStr),f="4i"}d(l,".uniform",f,"(",m,",",q(n)?Array.prototype.slice.call(n):n,");")}continue}else k=p.append(a, d)}else{if(!e(K))continue;k=d.def(x.uniforms,"[",v.id(z),"]")}35678===r?d("if(",k,"&&",k,'._reglType==="framebuffer"){',k,"=",k,".color[0];","}"):35680===r&&d("if(",k,"&&",k,'._reglType==="framebufferCube"){',k,"=",k,".color[0];","}");b.optional(function(){function g(b,c){a.assert(d,b,'bad data or missing for uniform "'+z+'". '+c)}function b(a){g("typeof "+k+'==="'+a+'"',"invalid type, expected "+a)}function c(d,b){g(x.isArrayLike+"("+k+")&&"+k+".length==="+d,"invalid vector, should have length "+ d,a.commandStr)}function e(d){g("typeof "+k+'==="function"&&'+k+'._reglType==="texture'+(3553===d?"2d":"Cube")+'"',"invalid texture type",a.commandStr)}switch(r){case 5124:b("number");break;case 35667:c(2,"number");break;case 35668:c(3,"number");break;case 35669:c(4,"number");break;case 5126:b("number");break;case 35664:c(2,"number");break;case 35665:c(3,"number");break;case 35666:c(4,"number");break;case 35670:b("boolean");break;case 35671:c(2,"boolean");break;case 35672:c(3,"boolean");break;case 35673:c(4, "boolean");break;case 35674:c(4,"number");break;case 35675:c(9,"number");break;case 35676:c(16,"number");break;case 35678:e(3553);break;case 35680:e(34067)}});p=1;switch(r){case 35678:case 35680:p=d.def(k,"._texture");d(l,".uniform1i(",m,",",p,".bind());");d.exit(p,".unbind();");continue;case 5124:case 35670:f="1i";break;case 35667:case 35671:f="2i";p=2;break;case 35668:case 35672:f="3i";p=3;break;case 35669:case 35673:f="4i";p=4;break;case 5126:f="1f";break;case 35664:f="2f";p=2;break;case 35665:f= "3f";p=3;break;case 35666:f="4f";p=4;break;case 35674:f="Matrix2fv";break;case 35675:f="Matrix3fv";break;case 35676:f="Matrix4fv"}d(l,".uniform",f,"(",m,",");if("M"===f.charAt(0)){var m=Math.pow(r-35674+2,2),pa=a.global.def("new Float32Array(",m,")");d("false,(Array.isArray(",k,")||",k," instanceof Float32Array)?",k,":(",E(m,function(a){return pa+"["+a+"]="+k+"["+a+"]"}),",",pa,")")}else 1<p?d(E(p,function(a){return k+"["+a+"]"})):d(k);d(");")}}function ua(a,d,c,e){function f(g){var b=q[g];return b? b.contextDep&&e.contextDynamic||b.propDep?b.append(a,c):b.append(a,d):d.def(z,".",g)}function l(){function a(){c(v,".drawElementsInstancedANGLE(",[r,k,Q,p+"<<(("+Q+"-5121)>>1)",K],");")}function d(){c(v,".drawArraysInstancedANGLE(",[r,p,k,K],");")}n?pa?a():(c("if(",n,"){"),a(),c("}else{"),d(),c("}")):d()}function x(){function a(){c(m+".drawElements("+[r,k,Q,p+"<<(("+Q+"-5121)>>1)"]+");")}function d(){c(m+".drawArrays("+[r,p,k]+");")}n?pa?a():(c("if(",n,"){"),a(),c("}else{"),d(),c("}")):d()}var h= a.shared,m=h.gl,z=h.draw,q=e.draw,n=function(){var g=q.elements,b=d;if(g){if(g.contextDep&&e.contextDynamic||g.propDep)b=c;g=g.append(a,b)}else g=b.def(z,".","elements");g&&b("if("+g+")"+m+".bindBuffer(34963,"+g+".buffer.buffer);");return g}(),r=f("primitive"),p=f("offset"),k=function(){var g=q.count,f,l=d;if(g){if(g.contextDep&&e.contextDynamic||g.propDep)l=c;f=g.append(a,l);b.optional(function(){g.MISSING&&a.assert(d,"false","missing vertex count");g.DYNAMIC&&a.assert(l,f+">=0","missing vertex count")})}else f= l.def(z,".","count"),b.optional(function(){a.assert(l,f+">=0","missing vertex count")});return f}();if("number"===typeof k){if(0===k)return}else c("if(",k,"){"),c.exit("}");var K,v;g&&(K=f("instances"),v=a.instancing);var Q=n+".type",pa=q.elements&&w(q.elements);g&&("number"!==typeof K||0<=K)?"string"===typeof K?(c("if(",K,">0){"),l(),c("}else if(",K,"<0){"),x(),c("}")):l():x()}function Da(a,d,c,e,f){var l=Ca();f=l.proc("body",f);b.optional(function(){l.commandStr=d.commandStr;l.command=l.link(d.commandStr)}); g&&(l.instancing=f.def(l.shared.extensions,".angle_instanced_arrays"));a(l,f,c,e);return l.compile().body}function Fa(a,d,g,b){aa(a,d);za(a,d,g,b.attributes,function(){return!0});ha(a,d,g,b.uniforms,function(){return!0});ua(a,d,d,g)}function Ia(a,d){var g=a.proc("draw",1);aa(a,g);Z(a,g,d.context);T(a,g,d.framebuffer);U(a,g,d);R(a,g,d.state);fa(a,g,d,!1,!0);var b=d.shader.progVar.append(a,g);g(a.shared.gl,".useProgram(",b,".program);");if(d.shader.program)Fa(a,g,d,d.shader.program);else{var c=a.global.def("{}"), e=g.def(b,".id"),f=g.def(c,"[",e,"]");g(a.cond(f).then(f,".call(this,a0);")["else"](f,"=",c,"[",e,"]=",a.link(function(g){return Da(Fa,a,d,g,1)}),"(",b,");",f,".call(this,a0);"))}0<Object.keys(d.state).length&&g(a.shared.current,".dirty=true;")}function Ea(a,d,g,b){function c(){return!0}a.batchId="a1";aa(a,d);za(a,d,g,b.attributes,c);ha(a,d,g,b.uniforms,c);ua(a,d,d,g)}function Ja(a,d,g,b){function c(a){return a.contextDep&&f||a.propDep}function e(a){return!c(a)}aa(a,d);var f=g.contextDep,l=d.def(), x=d.def();a.shared.props=x;a.batchId=l;var h=a.scope(),m=a.scope();d(h.entry,"for(",l,"=0;",l,"<","a1",";++",l,"){",x,"=","a0","[",l,"];",m,"}",h.exit);g.needsContext&&Z(a,m,g.context);g.needsFramebuffer&&T(a,m,g.framebuffer);R(a,m,g.state,c);g.profile&&c(g.profile)&&fa(a,m,g,!1,!0);b?(za(a,h,g,b.attributes,e),za(a,m,g,b.attributes,c),ha(a,h,g,b.uniforms,e),ha(a,m,g,b.uniforms,c),ua(a,h,m,g)):(d=a.global.def("{}"),b=g.shader.progVar.append(a,m),x=m.def(b,".id"),h=m.def(d,"[",x,"]"),m(a.shared.gl, ".useProgram(",b,".program);","if(!",h,"){",h,"=",d,"[",x,"]=",a.link(function(d){return Da(Ea,a,g,d,2)}),"(",b,");}",h,".call(this,a0[",l,"],",l,");"))}function Ka(a,d){function g(a){return a.contextDep&&c||a.propDep}var b=a.proc("batch",2);a.batchId="0";aa(a,b);var c=!1,e=!0;Object.keys(d.context).forEach(function(a){c=c||d.context[a].propDep});c||(Z(a,b,d.context),e=!1);var f=d.framebuffer,l=!1;f?(f.propDep?c=l=!0:f.contextDep&&c&&(l=!0),l||T(a,b,f)):T(a,b,null);d.state.viewport&&d.state.viewport.propDep&& (c=!0);U(a,b,d);R(a,b,d.state,function(a){return!g(a)});d.profile&&g(d.profile)||fa(a,b,d,!1,"a1");d.contextDep=c;d.needsContext=e;d.needsFramebuffer=l;e=d.shader.progVar;if(e.contextDep&&c||e.propDep)Ja(a,b,d,null);else if(e=e.append(a,b),b(a.shared.gl,".useProgram(",e,".program);"),d.shader.program)Ja(a,b,d,d.shader.program);else{var f=a.global.def("{}"),l=b.def(e,".id"),x=b.def(f,"[",l,"]");b(a.cond(x).then(x,".call(this,a0,a1);")["else"](x,"=",f,"[",l,"]=",a.link(function(g){return Da(Ja,a,d, g,2)}),"(",e,");",x,".call(this,a0,a1);"))}0<Object.keys(d.state).length&&b(a.shared.current,".dirty=true;")}function La(a,d){function g(e){var f=d.shader[e];f&&b.set(c.shader,"."+e,f.append(a,b))}var b=a.proc("scope",3);a.batchId="a2";var c=a.shared,e=c.current;Z(a,b,d.context);d.framebuffer&&d.framebuffer.append(a,b);f(Object.keys(d.state)).forEach(function(g){var e=d.state[g].append(a,b);q(e)?e.forEach(function(d,c){b.set(a.next[g],"["+c+"]",d)}):b.set(c.next,"."+g,e)});fa(a,b,d,!0,!0);["elements", "offset","count","instances","primitive"].forEach(function(g){var e=d.draw[g];e&&b.set(c.draw,"."+g,""+e.append(a,b))});Object.keys(d.uniforms).forEach(function(g){b.set(c.uniforms,"["+v.id(g)+"]",d.uniforms[g].append(a,b))});Object.keys(d.attributes).forEach(function(g){var c=d.attributes[g].append(a,b),e=a.scopeAttrib(g);Object.keys(new sa).forEach(function(a){b.set(e,"."+a,c[a])})});g("vert");g("frag");0<Object.keys(d.state).length&&(b(e,".dirty=true;"),b.exit(e,".dirty=true;"));b("a1(",a.shared.context, ",a0,",a.batchId,");")}function Pa(a){if("object"===typeof a&&!q(a)){for(var d=Object.keys(a),g=0;g<d.length;++g)if(F.isDynamic(a[d[g]]))return!0;return!1}}function va(a,d,g){function b(a,d){f.forEach(function(g){var b=c[g];F.isDynamic(b)&&(b=a.invoke(d,b),d(z,".",g,"=",b,";"))})}var c=d["static"][g];if(c&&Pa(c)){var e=a.global,f=Object.keys(c),l=!1,x=!1,h=!1,z=a.global.def("{}");f.forEach(function(d){var g=c[d];if(F.isDynamic(g))"function"===typeof g&&(g=c[d]=F.unbox(g)),d=m(g,null),l=l||d.thisDep, h=h||d.propDep,x=x||d.contextDep;else{e(z,".",d,"=");switch(typeof g){case "number":e(g);break;case "string":e('"',g,'"');break;case "object":Array.isArray(g)&&e("[",g.join(),"]");break;default:e(a.link(g))}e(";")}});d.dynamic[g]=new F.DynamicVariable(4,{thisDep:l,contextDep:x,propDep:h,ref:z,append:b});delete d["static"][g]}}var sa=Q.Record,ea={add:32774,subtract:32778,"reverse subtract":32779};C.ext_blend_minmax&&(ea.min=32775,ea.max=32776);var g=C.angle_instanced_arrays,z=C.webgl_draw_buffers, x={dirty:!0,profile:wa.profile},pa={},Ga=[],Aa={},Ba={};S("dither",3024);S("blend.enable",3042);O("blend.color","blendColor",[0,0,0,0]);O("blend.equation","blendEquationSeparate",[32774,32774]);O("blend.func","blendFuncSeparate",[1,0,1,0]);S("depth.enable",2929,!0);O("depth.func","depthFunc",513);O("depth.range","depthRange",[0,1]);O("depth.mask","depthMask",!0);O("colorMask","colorMask",[!0,!0,!0,!0]);S("cull.enable",2884);O("cull.face","cullFace",1029);O("frontFace","frontFace",2305);O("lineWidth", "lineWidth",1);S("polygonOffset.enable",32823);O("polygonOffset.offset","polygonOffset",[0,0]);S("sample.alpha",32926);S("sample.enable",32928);O("sample.coverage","sampleCoverage",[1,!1]);S("stencil.enable",2960);O("stencil.mask","stencilMask",-1);O("stencil.func","stencilFunc",[519,0,-1]);O("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]);O("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]);S("scissor.enable",3089);O("scissor.box","scissor",[0,0,k.drawingBufferWidth,k.drawingBufferHeight]); O("viewport","viewport",[0,0,k.drawingBufferWidth,k.drawingBufferHeight]);var Oa={gl:k,context:ka,strings:v,next:pa,current:x,draw:ra,elements:ia,buffer:H,shader:M,attributes:Q.state,uniforms:da,framebuffer:y,extensions:C,timer:oa,isBufferArgs:c},Ha={primTypes:A,compareFuncs:I,blendFuncs:r,blendEquations:ea,stencilOps:l,glTypes:B,orientationType:d};b.optional(function(){Oa.isArrayLike=q});z&&(Ha.backBuffer=[1029],Ha.drawBuffer=E(u.maxDrawbuffers,function(a){return 0===a?[0]:E(a,function(a){return 36064+ a})}));var Qa=0;return{next:pa,current:x,procs:function(){var a=Ca(),d=a.proc("poll"),g=a.proc("refresh"),b=a.block();d(b);g(b);var c=a.shared,e=c.gl,f=c.next,l=c.current;b(l,".dirty=false;");T(a,d);T(a,g,null,!0);var h=k.getExtension("angle_instanced_arrays"),m;h&&(m=a.link(h));for(var z=0;z<u.maxAttributes;++z){var n=g.def(c.attributes,"[",z,"]"),r=a.cond(n,".buffer");r.then(e,".enableVertexAttribArray(",z,");",e,".bindBuffer(",34962,",",n,".buffer.buffer);",e,".vertexAttribPointer(",z,",",n,".size,", n,".type,",n,".normalized,",n,".stride,",n,".offset);")["else"](e,".disableVertexAttribArray(",z,");",e,".vertexAttrib4f(",z,",",n,".x,",n,".y,",n,".z,",n,".w);",n,".buffer=null;");g(r);h&&g(m,".vertexAttribDivisorANGLE(",z,",",n,".divisor);")}Object.keys(Aa).forEach(function(c){var x=Aa[c],h=b.def(f,".",c),m=a.block();m("if(",h,"){",e,".enable(",x,")}else{",e,".disable(",x,")}",l,".",c,"=",h,";");g(m);d("if(",h,"!==",l,".",c,"){",m,"}")});Object.keys(Ba).forEach(function(c){var h=Ba[c],m=x[c],z, n,r=a.block();r(e,".",h,"(");q(m)?(h=m.length,z=a.global.def(f,".",c),n=a.global.def(l,".",c),r(E(h,function(a){return z+"["+a+"]"}),");",E(h,function(a){return n+"["+a+"]="+z+"["+a+"];"}).join("")),d("if(",E(h,function(a){return z+"["+a+"]!=="+n+"["+a+"]"}).join("||"),"){",r,"}")):(z=b.def(f,".",c),n=b.def(l,".",c),r(z,");",l,".",c,"=",z,";"),d("if(",z,"!==",n,"){",r,"}"));g(r)});return a.compile()}(),compile:function(a,d,g,b,c){var e=Ca();e.stats=e.link(c);Object.keys(d["static"]).forEach(function(a){va(e, d,a)});p.forEach(function(d){va(e,a,d)});g=W(a,d,g,b,e);Ia(e,g);La(e,g);Ka(e,g);return e.compile()}}}},{"./constants/dtypes.json":5,"./constants/primitives.json":6,"./dynamic":9,"./util/check":21,"./util/codegen":23,"./util/is-array-like":26,"./util/is-ndarray":27,"./util/is-typed-array":28,"./util/loop":29}],9:[function(k,u,y){function c(c,f){this.id=w++;this.type=c;this.data=f}function f(c){if(0===c.length)return[];var h=c.charAt(0),b=c.charAt(c.length-1);if(1<c.length&&h===b&&('"'===h||"'"===h))return['"'+ c.substr(1,c.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(h=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(c))return f(c.substr(0,h.index)).concat(f(h[1])).concat(f(c.substr(h.index+h[0].length)));h=c.split(".");if(1===h.length)return['"'+c.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];c=[];for(b=0;b<h.length;++b)c=c.concat(f(h[b]));return c}function h(c){return"["+f(c).join("][")+"]"}var w=0;u.exports={DynamicVariable:c,define:function(e,f){return new c(e,h(f+""))},isDynamic:function(e){return"function"=== typeof e&&!e._reglType||e instanceof c},unbox:function(e,f){return"function"===typeof e?new c(0,e):e},accessor:h}},{}],10:[function(k,u,y){var c=k("./util/check"),f=k("./util/is-typed-array"),h=k("./util/is-ndarray"),w=k("./util/values"),e=k("./constants/primitives.json"),m=k("./constants/usage.json");u.exports=function(b,n,k,C){function v(b){this.id=B++;A[this.id]=this;this.buffer=b;this.primType=4;this.type=this.vertCount=0}function q(e,m,q,l,a,d,p){e.buffer.bind();if(m){var w=p;p||f(m)&&(!h(m)|| f(m.data))||(w=n.oes_element_index_uint?5125:5123);k._initBuffer(e.buffer,m,q,w,3)}else b.bufferData(34963,d,q),e.buffer.dtype=w||5121,e.buffer.usage=q,e.buffer.dimension=3,e.buffer.byteLength=d;w=p;if(!p){switch(e.buffer.dtype){case 5121:case 5120:w=5121;break;case 5123:case 5122:w=5123;break;case 5125:case 5124:w=5125;break;default:c.raise("unsupported type for element array")}e.buffer.dtype=w}e.type=w;c(5125!==w||!!n.oes_element_index_uint,"32 bit element buffers not supported, enable oes_element_index_uint first"); m=a;0>m&&(m=e.buffer.byteLength,5123===w?m>>=1:5125===w&&(m>>=2));e.vertCount=m;m=l;0>l&&(m=4,l=e.buffer.dimension,1===l&&(m=0),2===l&&(m=1),3===l&&(m=4));e.primType=m}function u(b){C.elementsCount--;c(null!==b.buffer,"must not double destroy elements");delete A[b.id];b.buffer.destroy();b.buffer=null}var A={},B=0,G={uint8:5121,uint16:5123};n.oes_element_index_uint&&(G.uint32=5125);v.prototype.bind=function(){this.buffer.bind()};var p=[];return{create:function(b,n){function p(d){if(d)if("number"=== typeof d)l(d),a.primType=4,a.vertCount=d|0,a.type=5121;else{var b=null,n=35044,k=-1,w=-1,r=0,v=0;if(Array.isArray(d)||f(d)||h(d))b=d;else if(c.type(d,"object","invalid arguments for elements"),"data"in d&&(b=d.data,c(Array.isArray(b)||f(b)||h(b),"invalid data for element buffer")),"usage"in d&&(c.parameter(d.usage,m,"invalid element buffer usage"),n=m[d.usage]),"primitive"in d&&(c.parameter(d.primitive,e,"invalid element buffer primitive"),k=e[d.primitive]),"count"in d&&(c("number"===typeof d.count&& 0<=d.count,"invalid vertex count for elements"),w=d.count|0),"type"in d&&(c.parameter(d.type,G,"invalid buffer type"),v=G[d.type]),"length"in d)r=d.length|0;else if(r=w,5123===v||5122===v)r*=2;else if(5125===v||5124===v)r*=4;q(a,b,n,k,w,r,v)}else l(),a.primType=4,a.vertCount=0,a.type=5121;return p}var l=k.create(null,34963,!0),a=new v(l._buffer);C.elementsCount++;p(b);p._reglType="elements";p._elements=a;p.subdata=function(a,b){l.subdata(a,b);return p};p.destroy=function(){u(a)};return p},createStream:function(b){var c= p.pop();c||(c=new v(k.create(null,34963,!0,!1)._buffer));q(c,b,35040,-1,-1,0,0);return c},destroyStream:function(b){p.push(b)},getElements:function(b){return"function"===typeof b&&b._elements instanceof v?b._elements:null},clear:function(){w(A).forEach(u)}}}},{"./constants/primitives.json":6,"./constants/usage.json":7,"./util/check":21,"./util/is-ndarray":27,"./util/is-typed-array":28,"./util/values":33}],11:[function(k,u,y){var c=k("./util/check");u.exports=function(f,h){function k(b){c.type(b,"string", "extension name must be string");b=b.toLowerCase();var h;try{h=e[b]=f.getExtension(b)}catch(m){}return!!h}for(var e={},m=0;m<h.extensions.length;++m){var b=h.extensions[m];if(!k(b))return h.onDestroy(),h.onDone('"'+b+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),null}h.optionalExtensions.forEach(k);return{extensions:e,restore:function(){Object.keys(e).forEach(function(b){if(!k(b))throw Error("(regl): error restoring extension "+b);})}}}}, {"./util/check":21}],12:[function(k,u,y){var c=k("./util/check"),f=k("./util/values"),h=k("./util/extend"),w=[6408],e=[];e[6408]=4;var m=[];m[5121]=1;m[5126]=4;m[36193]=2;var b=[32854,32855,36194,35907,34842,34843,34836],n={36053:"complete",36054:"incomplete attachment",36057:"incomplete dimensions",36055:"incomplete, missing attachment",36061:"unsupported"};u.exports=function(k,u,v,q,F,A){function B(a,d,b){this.target=a;this.texture=d;this.renderbuffer=b;var c=a=0;d?(a=d.width,c=d.height):b&&(a= b.width,c=b.height);this.width=a;this.height=c}function G(a){a&&(a.texture&&a.texture._texture.decRef(),a.renderbuffer&&a.renderbuffer._renderbuffer.decRef())}function p(a,d,b){if(a){if(a.texture){a=a.texture._texture;var e=Math.max(1,a.height);c(Math.max(1,a.width)===d&&e===b,"inconsistent width/height for supplied texture")}else a=a.renderbuffer._renderbuffer,c(a.width===d&&a.height===b,"inconsistent width/height for renderbuffer");a.refCount+=1}}function r(a,d){d&&(d.texture?k.framebufferTexture2D(36160, a,d.target,d.texture._texture.texture,0):k.framebufferRenderbuffer(36160,a,36161,d.renderbuffer._renderbuffer.renderbuffer))}function N(a){var d=3553,b=null,e=null,f=a;"object"===typeof a&&(f=a.data,"target"in a&&(d=a.target|0));c.type(f,"function","invalid attachment data");a=f._reglType;"texture2d"===a?(b=f,c(3553===d)):"textureCube"===a?(b=f,c(34069<=d&&34075>d,"invalid cube map target")):"renderbuffer"===a?(e=f,d=36161):c.raise("invalid regl object for attachment");return new B(d,b,e)}function I(a, d,b,c,e){if(b)return a=q.create2D({width:a,height:d,format:c,type:e}),a._texture.refCount=0,new B(3553,a,null);a=F.create({width:a,height:d,format:c});a._renderbuffer.refCount=0;return new B(36161,null,a)}function l(a){return a&&(a.texture||a.renderbuffer)}function a(a,d,b){a&&(a.texture?a.texture.resize(d,b):a.renderbuffer&&a.renderbuffer.resize(d,b))}function d(){this.id=Y++;da[this.id]=this;this.framebuffer=k.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment= this.stencilAttachment=this.depthAttachment=null}function K(a){a.colorAttachments.forEach(G);G(a.depthAttachment);G(a.stencilAttachment);G(a.depthStencilAttachment)}function V(a){var d=a.framebuffer;c(d,"must not double destroy framebuffer");k.deleteFramebuffer(d);a.framebuffer=null;A.framebufferCount--;delete da[a.id]}function Ma(a){var d;k.bindFramebuffer(36160,a.framebuffer);var b=a.colorAttachments;for(d=0;d<b.length;++d)r(36064+d,b[d]);for(d=b.length;d<v.maxColorAttachments;++d)k.framebufferTexture2D(36160, 36064+d,3553,null,0);k.framebufferTexture2D(36160,33306,3553,null,0);k.framebufferTexture2D(36160,36096,3553,null,0);k.framebufferTexture2D(36160,36128,3553,null,0);r(36096,a.depthAttachment);r(36128,a.stencilAttachment);r(33306,a.depthStencilAttachment);a=k.checkFramebufferStatus(36160);36053!==a&&c.raise("framebuffer configuration not supported, status = "+n[a]);k.bindFramebuffer(36160,y.next);y.cur=y.next;k.getError()}function ga(f,q){function n(a,d){var f;c(y.next!==k,"can not update framebuffer which is currently in use"); var h=u.webgl_draw_buffers,q=0,r=0,V=!0,B=!0;f=null;var A=!0,E="rgba",F="uint8",G=1,ga=null,Q=null,M=null,da=!1;if("number"===typeof a)q=a|0,r=d|0||q;else if(a){c.type(a,"object","invalid arguments for framebuffer");"shape"in a?(r=a.shape,c(Array.isArray(r)&&2<=r.length,"invalid shape for framebuffer"),q=r[0],r=r[1]):("radius"in a&&(q=r=a.radius),"width"in a&&(q=a.width),"height"in a&&(r=a.height));if("color"in a||"colors"in a)f=a.color||a.colors,Array.isArray(f)&&c(1===f.length||h,"multiple render targets not supported"); if(!f){"colorCount"in a&&(G=a.colorCount|0,c(0<G,"invalid color buffer count"));"colorTexture"in a&&(A=!!a.colorTexture,E="rgba4");if("colorType"in a){F=a.colorType;if(A)c(u.oes_texture_float||!("float"===F||"float32"===F),"you must enable OES_texture_float in order to use floating point framebuffer objects"),c(u.oes_texture_half_float||!("half float"===F||"float16"===F),"you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects");else if("half float"===F||"float16"=== F)c(u.ext_color_buffer_half_float,"you must enable EXT_color_buffer_half_float to use 16-bit render buffers"),E="rgba16f";else if("float"===F||"float32"===F)c(u.webgl_color_buffer_float,"you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers"),E="rgba32f";c.oneOf(F,J,"invalid color type")}if("colorFormat"in a)if(E=a.colorFormat,0<=H.indexOf(E))A=!0;else if(0<=ia.indexOf(E))A=!1;else if(A)c.oneOf(a.colorFormat,H,"invalid color format for texture");else c.oneOf(a.colorFormat, ia,"invalid color format for renderbuffer")}if("depthTexture"in a||"depthStencilTexture"in a)da=!(!a.depthTexture&&!a.depthStencilTexture),c(!da||u.webgl_depth_texture,"webgl_depth_texture extension not supported");"depth"in a&&("boolean"===typeof a.depth?V=a.depth:(ga=a.depth,B=!1));"stencil"in a&&("boolean"===typeof a.stencil?B=a.stencil:(Q=a.stencil,V=!1));"depthStencil"in a&&("boolean"===typeof a.depthStencil?V=B=a.depthStencil:(M=a.depthStencil,B=V=!1))}else q=r=1;var Y=h=null,T=null,U=null; if(Array.isArray(f))h=f.map(N);else if(f)h=[N(f)];else for(h=Array(G),f=0;f<G;++f)h[f]=I(q,r,A,E,F);c(u.webgl_draw_buffers||1>=h.length,"you must enable the WEBGL_draw_buffers extension in order to use multiple color buffers.");c(h.length<=v.maxColorAttachments,"too many color attachments, not supported");q=q||h[0].width;r=r||h[0].height;ga?Y=N(ga):V&&!B&&(Y=I(q,r,da,"depth","uint32"));Q?T=N(Q):B&&!V&&(T=I(q,r,!1,"stencil","uint8"));M?U=N(M):!ga&&!Q&&B&&V&&(U=I(q,r,da,"depth stencil","depth stencil")); c(1>=!!ga+!!Q+!!M,"invalid framebuffer configuration, can specify exactly one depth/stencil attachment");V=null;for(f=0;f<h.length;++f)p(h[f],q,r),c(!h[f]||h[f].texture&&0<=w.indexOf(h[f].texture._texture.format)||h[f].renderbuffer&&0<=b.indexOf(h[f].renderbuffer._renderbuffer.format),"framebuffer color attachment "+f+" is invalid"),h[f]&&h[f].texture&&(B=e[h[f].texture._texture.format]*m[h[f].texture._texture.type],null===V?V=B:c(V===B,"all color attachments much have the same number of bits per pixel.")); p(Y,q,r);c(!Y||Y.texture&&6402===Y.texture._texture.format||Y.renderbuffer&&33189===Y.renderbuffer._renderbuffer.format,"invalid depth attachment for framebuffer object");p(T,q,r);c(!T||T.renderbuffer&&36168===T.renderbuffer._renderbuffer.format,"invalid stencil attachment for framebuffer object");p(U,q,r);c(!U||U.texture&&34041===U.texture._texture.format||U.renderbuffer&&34041===U.renderbuffer._renderbuffer.format,"invalid depth-stencil attachment for framebuffer object");K(k);k.width=q;k.height= r;k.colorAttachments=h;k.depthAttachment=Y;k.stencilAttachment=T;k.depthStencilAttachment=U;n.color=h.map(l);n.depth=l(Y);n.stencil=l(T);n.depthStencil=l(U);n.width=k.width;n.height=k.height;Ma(k);return n}var k=new d;A.framebufferCount++;n(f,q);return h(n,{resize:function(d,b){c(y.next!==k,"can not resize a framebuffer which is currently in use");var e=d|0,f=b|0||e;if(e===k.width&&f===k.height)return n;for(var h=k.colorAttachments,l=0;l<h.length;++l)a(h[l],e,f);a(k.depthAttachment,e,f);a(k.stencilAttachment, e,f);a(k.depthStencilAttachment,e,f);k.width=n.width=e;k.height=n.height=f;Ma(k);return n},_reglType:"framebuffer",_framebuffer:k,destroy:function(){V(k);K(k)},bind:function(a){y.setFBO({framebuffer:n},a)}})}var y={cur:null,next:null,dirty:!1,setFBO:null},H=["rgba"],ia=["rgba4","rgb565","rgb5 a1"];u.ext_srgb&&ia.push("srgba");u.ext_color_buffer_half_float&&ia.push("rgba16f","rgb16f");u.webgl_color_buffer_float&&ia.push("rgba32f");var J=["uint8"];u.oes_texture_half_float&&J.push("half float","float16"); u.oes_texture_float&&J.push("float","float32");var Y=0,da={};return h(y,{getFramebuffer:function(a){return"function"===typeof a&&"framebuffer"===a._reglType&&(a=a._framebuffer,a instanceof d)?a:null},create:ga,createCube:function(a){function d(a){var e;c(0>b.indexOf(y.next),"can not update framebuffer which is currently in use");var f=u.webgl_draw_buffers,l={color:null},m=0,k=null;e="rgba";var n="uint8",p=1;if("number"===typeof a)m=a|0;else if(a){c.type(a,"object","invalid arguments for framebuffer"); "shape"in a?(m=a.shape,c(Array.isArray(m)&&2<=m.length,"invalid shape for framebuffer"),c(m[0]===m[1],"cube framebuffer must be square"),m=m[0]):("radius"in a&&(m=a.radius|0),"width"in a?(m=a.width|0,"height"in a&&c(a.height===m,"must be square")):"height"in a&&(m=a.height|0));if("color"in a||"colors"in a)k=a.color||a.colors,Array.isArray(k)&&c(1===k.length||f,"multiple render targets not supported");k||("colorCount"in a&&(p=a.colorCount|0,c(0<p,"invalid color buffer count")),"colorType"in a&&(c.oneOf(a.colorType, J,"invalid color type"),n=a.colorType),"colorFormat"in a&&(e=a.colorFormat,c.oneOf(a.colorFormat,H,"invalid color format for texture")));"depth"in a&&(l.depth=a.depth);"stencil"in a&&(l.stencil=a.stencil);"depthStencil"in a&&(l.depthStencil=a.depthStencil)}else m=1;if(k)if(Array.isArray(k))for(a=[],e=0;e<k.length;++e)a[e]=k[e];else a=[k];else for(a=Array(p),k={radius:m,format:e,type:n},e=0;e<p;++e)a[e]=q.createCube(k);l.color=Array(a.length);for(e=0;e<a.length;++e)p=a[e],c("function"===typeof p&& "textureCube"===p._reglType,"invalid cube map"),m=m||p.width,c(p.width===m&&p.height===m,"invalid cube map shape"),l.color[e]={target:34069,data:a[e]};for(e=0;6>e;++e){for(p=0;p<a.length;++p)l.color[p].target=34069+e;0<e&&(l.depth=b[0].depth,l.stencil=b[0].stencil,l.depthStencil=b[0].depthStencil);if(b[e])b[e](l);else b[e]=ga(l)}return h(d,{width:m,height:m,color:a})}var b=Array(6);d(a);return h(d,{faces:b,resize:function(a){var e=a|0;c(0<e&&e<=v.maxCubeMapSize,"invalid radius for cube fbo");if(e=== d.width)return d;var f=d.color;for(a=0;a<f.length;++a)f[a].resize(e);for(a=0;6>a;++a)b[a].resize(e);d.width=d.height=e;return d},_reglType:"framebufferCube",destroy:function(){b.forEach(function(a){a.destroy()})}})},clear:function(){f(da).forEach(V)},restore:function(){f(da).forEach(function(a){a.framebuffer=k.createFramebuffer();Ma(a)})}})}},{"./util/check":21,"./util/extend":24,"./util/values":33}],13:[function(k,u,y){u.exports=function(c,f){var h=1;f.ext_texture_filter_anisotropic&&(h=c.getParameter(34047)); var k=1,e=1;f.webgl_draw_buffers&&(k=c.getParameter(34852),e=c.getParameter(36063));return{colorBits:[c.getParameter(3410),c.getParameter(3411),c.getParameter(3412),c.getParameter(3413)],depthBits:c.getParameter(3414),stencilBits:c.getParameter(3415),subpixelBits:c.getParameter(3408),extensions:Object.keys(f).filter(function(c){return!!f[c]}),maxAnisotropic:h,maxDrawbuffers:k,maxColorAttachments:e,pointSizeDims:c.getParameter(33901),lineWidthDims:c.getParameter(33902),maxViewportDims:c.getParameter(3386), maxCombinedTextureUnits:c.getParameter(35661),maxCubeMapSize:c.getParameter(34076),maxRenderbufferSize:c.getParameter(34024),maxTextureUnits:c.getParameter(34930),maxTextureSize:c.getParameter(3379),maxAttributes:c.getParameter(34921),maxVertexUniforms:c.getParameter(36347),maxVertexTextureUnits:c.getParameter(35660),maxVaryingVectors:c.getParameter(36348),maxFragmentUniforms:c.getParameter(36349),glsl:c.getParameter(35724),renderer:c.getParameter(7937),vendor:c.getParameter(7936),version:c.getParameter(7938)}}}, {}],14:[function(k,u,y){var c=k("./util/check"),f=k("./util/is-typed-array");u.exports=function(h,k,e,m,b,n){function u(v){var q;null===k.next?(c(b.preserveDrawingBuffer,'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer'),q=5121):(c(null!==k.next.colorAttachments[0].texture,"You cannot read from a renderbuffer"),q=k.next.colorAttachments[0].texture._texture.type,n.oes_texture_float?c(5121===q||5126===q,"Reading from a framebuffer is only allowed for the types 'uint8' and 'float'"): c(5121===q,"Reading from a framebuffer is only allowed for the type 'uint8'"));var F=0,A=0,B=m.framebufferWidth,E=m.framebufferHeight,p=null;f(v)?p=v:v&&(c.type(v,"object","invalid arguments to regl.read()"),F=v.x|0,A=v.y|0,c(0<=F&&F<m.framebufferWidth,"invalid x offset for regl.read"),c(0<=A&&A<m.framebufferHeight,"invalid y offset for regl.read"),B=(v.width||m.framebufferWidth-F)|0,E=(v.height||m.framebufferHeight-A)|0,p=v.data||null);p&&(5121===q?c(p instanceof Uint8Array,"buffer must be 'Uint8Array' when reading from a framebuffer of type 'uint8'"): 5126===q&&c(p instanceof Float32Array,"buffer must be 'Float32Array' when reading from a framebuffer of type 'float'"));c(0<B&&B+F<=m.framebufferWidth,"invalid width for read pixels");c(0<E&&E+A<=m.framebufferHeight,"invalid height for read pixels");e();v=B*E*4;p||(5121===q?p=new Uint8Array(v):5126===q&&(p=p||new Float32Array(v)));c.isTypedArray(p,"data buffer for regl.read() must be a typedarray");c(p.byteLength>=v,"data buffer for regl.read() too small");h.pixelStorei(3333,4);h.readPixels(F,A,B, E,6408,q,p);return p}function C(b){var c;k.setFBO({framebuffer:b.framebuffer},function(){c=u(b)});return c}return function(b){return b&&"framebuffer"in b?C(b):u(b)}}},{"./util/check":21,"./util/is-typed-array":28}],15:[function(k,u,y){var c=k("./util/check"),f=k("./util/values"),h=[];h[32854]=2;h[32855]=2;h[36194]=2;h[33189]=2;h[36168]=1;h[34041]=4;h[35907]=4;h[34836]=16;h[34842]=8;h[34843]=6;u.exports=function(k,e,m,b,n){function u(b){this.id=F++;this.refCount=1;this.renderbuffer=b;this.format=32854; this.height=this.width=0;n.profile&&(this.stats={size:0})}function C(e){var f=e.renderbuffer;c(f,"must not double destroy renderbuffer");k.bindRenderbuffer(36161,null);k.deleteRenderbuffer(f);e.renderbuffer=null;e.refCount=0;delete A[e.id];b.renderbufferCount--}var v={rgba4:32854,rgb565:36194,"rgb5 a1":32855,depth:33189,stencil:36168,"depth stencil":34041};e.ext_srgb&&(v.srgba=35907);e.ext_color_buffer_half_float&&(v.rgba16f=34842,v.rgb16f=34843);e.webgl_color_buffer_float&&(v.rgba32f=34836);var q= [];Object.keys(v).forEach(function(b){q[v[b]]=b});var F=0,A={};u.prototype.decRef=function(){0>=--this.refCount&&C(this)};n.profile&&(b.getTotalRenderbufferSize=function(){var b=0;Object.keys(A).forEach(function(c){b+=A[c].stats.size});return b});return{create:function(e,f){function p(b,e){var f=0,a=0,d=32854;"object"===typeof b&&b?("shape"in b?(a=b.shape,c(Array.isArray(a)&&2<=a.length,"invalid renderbuffer shape"),f=a[0]|0,a=a[1]|0):("radius"in b&&(f=a=b.radius|0),"width"in b&&(f=b.width|0),"height"in b&&(a=b.height|0)),"format"in b&&(c.parameter(b.format,v,"invalid renderbuffer format"),d=v[b.format])):"number"===typeof b?(f=b|0,a="number"===typeof e?e|0:f):b?c.raise("invalid arguments to renderbuffer constructor"):f=a=1;c(0<f&&0<a&&f<=m.maxRenderbufferSize&&a<=m.maxRenderbufferSize,"invalid renderbuffer size");if(f!==r.width||a!==r.height||d!==r.format)return p.width=r.width=f,p.height=r.height=a,r.format=d,k.bindRenderbuffer(36161,r.renderbuffer),k.renderbufferStorage(36161,d,f,a),n.profile&& (r.stats.size=h[r.format]*r.width*r.height),p.format=q[r.format],p}var r=new u(k.createRenderbuffer());A[r.id]=r;b.renderbufferCount++;p(e,f);p.resize=function(b,e){var f=b|0,a=e|0||f;if(f===r.width&&a===r.height)return p;c(0<f&&0<a&&f<=m.maxRenderbufferSize&&a<=m.maxRenderbufferSize,"invalid renderbuffer size");p.width=r.width=f;p.height=r.height=a;k.bindRenderbuffer(36161,r.renderbuffer);k.renderbufferStorage(36161,r.format,f,a);n.profile&&(r.stats.size=h[r.format]*r.width*r.height);return p};p._reglType= "renderbuffer";p._renderbuffer=r;n.profile&&(p.stats=r.stats);p.destroy=function(){r.decRef()};return p},clear:function(){f(A).forEach(C)},restore:function(){f(A).forEach(function(b){b.renderbuffer=k.createRenderbuffer();k.bindRenderbuffer(36161,b.renderbuffer);k.renderbufferStorage(36161,b.format,b.width,b.height)});k.bindRenderbuffer(36161,null)}}}},{"./util/check":21,"./util/values":33}],16:[function(k,u,y){var c=k("./util/check"),f=k("./util/values");u.exports=function(h,k,e,m){function b(b,c, e,f){this.name=b;this.id=c;this.location=e;this.info=f}function n(b,c){for(var e=0;e<b.length;++e)if(b[e].id===c.id){b[e].location=c.location;return}b.push(c)}function u(b,e,f){var m=35632===b?q:F,l=m[e];if(!l){var a=k.str(e),l=h.createShader(b);h.shaderSource(l,a);h.compileShader(l);c.shaderError(h,l,a,b,f);m[e]=l}return l}function C(b,c){this.id=G++;this.fragId=b;this.vertId=c;this.program=null;this.uniforms=[];this.attributes=[];m.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function v(e, f){var q,v;q=u(35632,e.fragId);v=u(35633,e.vertId);var l=e.program=h.createProgram();h.attachShader(l,q);h.attachShader(l,v);h.linkProgram(l);c.linkError(h,l,k.str(e.fragId),k.str(e.vertId),f);var a=h.getProgramParameter(l,35718);m.profile&&(e.stats.uniformsCount=a);var d=e.uniforms;for(q=0;q<a;++q)if(v=h.getActiveUniform(l,q))if(1<v.size)for(var K=0;K<v.size;++K){var V=v.name.replace("[0]","["+K+"]");n(d,new b(V,k.id(V),h.getUniformLocation(l,V),v))}else n(d,new b(v.name,k.id(v.name),h.getUniformLocation(l, v.name),v));a=h.getProgramParameter(l,35721);m.profile&&(e.stats.attributesCount=a);d=e.attributes;for(q=0;q<a;++q)(v=h.getActiveAttrib(l,q))&&n(d,new b(v.name,k.id(v.name),h.getAttribLocation(l,v.name),v))}var q={},F={},A={},B=[],G=0;m.profile&&(e.getMaxUniformsCount=function(){var b=0;B.forEach(function(c){c.stats.uniformsCount>b&&(b=c.stats.uniformsCount)});return b},e.getMaxAttributesCount=function(){var b=0;B.forEach(function(c){c.stats.attributesCount>b&&(b=c.stats.attributesCount)});return b}); return{clear:function(){var b=h.deleteShader.bind(h);f(q).forEach(b);q={};f(F).forEach(b);F={};B.forEach(function(b){h.deleteProgram(b.program)});B.length=0;A={};e.shaderCount=0},program:function(b,f,h){c.command(0<=b,"missing vertex shader",h);c.command(0<=f,"missing fragment shader",h);var m=A[f];m||(m=A[f]={});var l=m[b];l||(l=new C(f,b),e.shaderCount++,v(l,h),m[b]=l,B.push(l));return l},restore:function(){q={};F={};for(var b=0;b<B.length;++b)v(B[b])},shader:u,frag:-1,vert:-1}}},{"./util/check":21, "./util/values":33}],17:[function(k,u,y){u.exports=function(){return{bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0}}},{}],18:[function(k,u,y){u.exports=function(){var c={"":0},f=[""];return{id:function(h){var k=c[h];if(k)return k;k=c[h]=f.length;f.push(h);return k},str:function(c){return f[c]}}}},{}],19:[function(k,u,y){function c(a){return Array.isArray(a)&&(0===a.length||"number"===typeof a[0])}function f(a){return Array.isArray(a)&& 0!==a.length&&A(a[0])?!0:!1}function h(a){return Object.prototype.toString.call(a)}function w(a){if(!a)return!1;var b=h(a);return 0<=I.indexOf(b)?!0:c(a)||f(a)||v(a)}function e(a,b){36193===a.type?(a.data=F(b),q.freeType(b)):a.data=b}function m(b,c,e,f,h,m){b="undefined"!==typeof a[b]?a[b]:N[b]*l[c];m&&(b*=6);if(h){for(f=0;1<=e;)f+=b*e*e,e/=2;return f}return b*e*f}var b=k("./util/check"),n=k("./util/extend"),E=k("./util/values"),C=k("./util/is-typed-array"),v=k("./util/is-ndarray"),q=k("./util/pool"), F=k("./util/to-half-float"),A=k("./util/is-array-like"),B=k("./util/flatten");y=k("./constants/arraytypes.json");var G=k("./constants/arraytypes.json"),p=[9984,9986,9985,9987],r=[0,6409,6410,6407,6408],N={};N[6409]=N[6406]=N[6402]=1;N[34041]=N[6410]=2;N[6407]=N[35904]=3;N[6408]=N[35906]=4;var I=Object.keys(y).concat(["[object HTMLCanvasElement]","[object CanvasRenderingContext2D]","[object HTMLImageElement]","[object HTMLVideoElement]"]),l=[];l[5121]=1;l[5126]=4;l[36193]=2;l[5123]=2;l[5125]=4;var a= [];a[32854]=2;a[32855]=2;a[36194]=2;a[34041]=4;a[33776]=.5;a[33777]=.5;a[33778]=1;a[33779]=1;a[35986]=.5;a[35987]=1;a[34798]=1;a[35840]=.5;a[35841]=.25;a[35842]=.5;a[35843]=.25;a[36196]=.5;u.exports=function(a,l,k,u,ga,I,H){function y(){this.format=this.internalformat=6408;this.type=5121;this.flipY=this.premultiplyAlpha=this.compressed=!1;this.unpackAlignment=1;this.channels=this.height=this.width=this.colorSpace=0}function J(a,b){a.internalformat=b.internalformat;a.format=b.format;a.type=b.type; a.compressed=b.compressed;a.premultiplyAlpha=b.premultiplyAlpha;a.flipY=b.flipY;a.unpackAlignment=b.unpackAlignment;a.colorSpace=b.colorSpace;a.width=b.width;a.height=b.height;a.channels=b.channels}function Y(a,d){if("object"===typeof d&&d){"premultiplyAlpha"in d&&(b.type(d.premultiplyAlpha,"boolean","invalid premultiplyAlpha"),a.premultiplyAlpha=d.premultiplyAlpha);"flipY"in d&&(b.type(d.flipY,"boolean","invalid texture flip"),a.flipY=d.flipY);"alignment"in d&&(b.oneOf(d.alignment,[1,2,4,8],"invalid texture unpack alignment"), a.unpackAlignment=d.alignment);"colorSpace"in d&&(b.parameter(d.colorSpace,U,"invalid colorSpace"),a.colorSpace=U[d.colorSpace]);if("type"in d){var c=d.type;b(l.oes_texture_float||!("float"===c||"float32"===c),"you must enable the OES_texture_float extension in order to use floating point textures.");b(l.oes_texture_half_float||!("half float"===c||"float16"===c),"you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures.");b(l.webgl_depth_texture||!("uint16"=== c||"uint32"===c||"depth stencil"===c),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures.");b.parameter(c,R,"invalid texture type");a.type=R[c]}var e=a.width,f=a.height,h=a.channels,c=!1;"shape"in d?(b(Array.isArray(d.shape)&&2<=d.shape.length,"shape must be an array"),e=d.shape[0],f=d.shape[1],3===d.shape.length&&(h=d.shape[2],b(0<h&&4>=h,"invalid number of channels"),c=!0),b(0<=e&&e<=k.maxTextureSize,"invalid width"),b(0<=f&&f<=k.maxTextureSize,"invalid height")): ("radius"in d&&(e=f=d.radius,b(0<=e&&e<=k.maxTextureSize,"invalid radius")),"width"in d&&(e=d.width,b(0<=e&&e<=k.maxTextureSize,"invalid width")),"height"in d&&(f=d.height,b(0<=f&&f<=k.maxTextureSize,"invalid height")),"channels"in d&&(h=d.channels,b(0<h&&4>=h,"invalid number of channels"),c=!0));a.width=e|0;a.height=f|0;a.channels=h|0;e=!1;"format"in d&&(e=d.format,b(l.webgl_depth_texture||!("depth"===e||"depth stencil"===e),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."), b.parameter(e,aa,"invalid texture format"),f=a.internalformat=aa[e],a.format=Ja[f],e in R&&!("type"in d)&&(a.type=R[e]),e in fa&&(a.compressed=!0),e=!0);!c&&e?a.channels=N[a.format]:c&&!e?a.channels!==r[a.format]&&(a.format=a.internalformat=r[a.channels]):e&&c&&b(a.channels===N[a.format],"number of channels inconsistent with specified format")}}function da(b){a.pixelStorei(37440,b.flipY);a.pixelStorei(37441,b.premultiplyAlpha);a.pixelStorei(37443,b.colorSpace);a.pixelStorei(3317,b.unpackAlignment)} function Q(){y.call(this);this.yOffset=this.xOffset=0;this.data=null;this.needsFree=!1;this.element=null;this.needsCopy=!1}function M(a,d){var l=null;w(d)?l=d:d&&(b.type(d,"object","invalid pixel data type"),Y(a,d),"x"in d&&(a.xOffset=d.x|0),"y"in d&&(a.yOffset=d.y|0),w(d.data)&&(l=d.data));b(!a.compressed||l instanceof Uint8Array,"compressed texture data must be stored in a uint8array");if(d.copy){b(!l,"can not specify copy and data field for the same texture");var m=ga.viewportWidth,n=ga.viewportHeight; a.width=a.width||m-a.xOffset;a.height=a.height||n-a.yOffset;a.needsCopy=!0;b(0<=a.xOffset&&a.xOffset<m&&0<=a.yOffset&&a.yOffset<n&&0<a.width&&a.width<=m&&0<a.height&&a.height<=n,"copy texture read out of bounds")}else if(!l)a.width=a.width||1,a.height=a.height||1,a.channels=a.channels||4;else if(C(l))a.channels=a.channels||4,a.data=l,"type"in d||5121!==a.type||(a.type=G[Object.prototype.toString.call(l)]|0);else if(c(l)){a.channels=a.channels||4;m=l;n=m.length;switch(a.type){case 5121:case 5123:case 5125:case 5126:n= q.allocType(a.type,n);n.set(m);a.data=n;break;case 36193:a.data=F(m);break;default:b.raise("unsupported texture type, must specify a typed array")}a.alignment=1;a.needsFree=!0}else if(v(l)){m=l.data;Array.isArray(m)||5121!==a.type||(a.type=G[Object.prototype.toString.call(m)]|0);var n=l.shape,p=l.stride,u,K,E,H;3===n.length?(E=n[2],H=p[2]):(b(2===n.length,"invalid ndarray pixel data, must be 2 or 3D"),H=E=1);u=n[0];K=n[1];n=p[0];p=p[1];a.alignment=1;a.width=u;a.height=K;a.channels=E;a.format=a.internalformat= r[E];a.needsFree=!0;u=H;l=l.offset;E=a.width;H=a.height;K=a.channels;for(var t=q.allocType(36193===a.type?5126:a.type,E*H*K),D=0,J=0;J<H;++J)for(var I=0;I<E;++I)for(var y=0;y<K;++y)t[D++]=m[n*I+p*J+u*y+l];e(a,t)}else if("[object HTMLCanvasElement]"===h(l)||"[object CanvasRenderingContext2D]"===h(l))"[object HTMLCanvasElement]"===h(l)?a.element=l:a.element=l.canvas,a.width=a.element.width,a.height=a.element.height,a.channels=4;else if("[object HTMLImageElement]"===h(l))a.element=l,a.width=l.naturalWidth, a.height=l.naturalHeight,a.channels=4;else if("[object HTMLVideoElement]"===h(l))a.element=l,a.width=l.videoWidth,a.height=l.videoHeight,a.channels=4;else if(f(l)){m=a.width||l[0].length;n=a.height||l.length;p=a.channels;p=A(l[0][0])?p||l[0][0].length:p||1;u=B.shape(l);E=1;for(H=0;H<u.length;++H)E*=u[H];E=q.allocType(36193===a.type?5126:a.type,E);B.flatten(l,u,"",E);e(a,E);a.alignment=1;a.width=m;a.height=n;a.channels=p;a.format=a.internalformat=r[p];a.needsFree=!0}5126===a.type?b(0<=k.extensions.indexOf("oes_texture_float"), "oes_texture_float extension not enabled"):36193===a.type&&b(0<=k.extensions.indexOf("oes_texture_half_float"),"oes_texture_half_float extension not enabled")}function ra(b,c,e,f,l){var h=b.element,m=b.data,k=b.internalformat,q=b.format,n=b.type,t=b.width,p=b.height;da(b);h?a.texSubImage2D(c,l,e,f,q,n,h):b.compressed?a.compressedTexSubImage2D(c,l,e,f,k,t,p,m):b.needsCopy?(u(),a.copyTexSubImage2D(c,l,e,f,b.xOffset,b.yOffset,t,p)):a.texSubImage2D(c,l,e,f,t,p,q,n,m)}function ka(){return Ka.pop()||new Q} function oa(a){a.needsFree&&q.freeType(a.data);Q.call(a);Ka.push(a)}function wa(){y.call(this);this.genMipmaps=!1;this.mipmapHint=4352;this.mipmask=0;this.images=Array(16)}function ba(a,b,d){var c=a.images[0]=ka();a.mipmask=1;c.width=a.width=b;c.height=a.height=d;c.channels=a.channels=4}function S(a,d){var c=null;if(w(d))c=a.images[0]=ka(),J(c,a),M(c,d),a.mipmask=1;else if(Y(a,d),Array.isArray(d.mipmap))for(var e=d.mipmap,f=0;f<e.length;++f)c=a.images[f]=ka(),J(c,a),c.width>>=f,c.height>>=f,M(c,e[f]), a.mipmask|=1<<f;else c=a.images[0]=ka(),J(c,a),M(c,d),a.mipmask=1;J(a,a.images[0]);(a.compressed&&33776===a.internalformat||33777===a.internalformat||33778===a.internalformat||33779===a.internalformat)&&b(0===a.width%4&&0===a.height%4,"for compressed texture formats, mipmap level 0 must have width and height that are a multiple of 4")}function O(b,c){for(var e=b.images,f=0;f<e.length&&e[f];++f){var l=e[f],h=c,m=f,k=l.element,q=l.data,n=l.internalformat,t=l.format,p=l.type,r=l.width,v=l.height;da(l); k?a.texImage2D(h,m,t,t,p,k):l.compressed?a.compressedTexImage2D(h,m,n,r,v,0,q):l.needsCopy?(u(),a.copyTexImage2D(h,m,t,l.xOffset,l.yOffset,r,v,0)):a.texImage2D(h,m,t,r,v,0,t,p,q)}}function Ca(){var a=La.pop()||new wa;y.call(a);for(var b=a.mipmask=0;16>b;++b)a.images[b]=null;return a}function ta(a){for(var b=a.images,d=0;d<b.length;++d)b[d]&&oa(b[d]),b[d]=null;La.push(a)}function xa(){this.magFilter=this.minFilter=9728;this.wrapT=this.wrapS=33071;this.anisotropic=1;this.genMipmaps=!1;this.mipmapHint= 4352}function ca(a,d){if("min"in d){var c=d.min;b.parameter(c,T);a.minFilter=T[c];0<=p.indexOf(a.minFilter)&&(a.genMipmaps=!0)}"mag"in d&&(c=d.mag,b.parameter(c,Z),a.magFilter=Z[c]);var c=a.wrapS,e=a.wrapT;if("wrap"in d){var f=d.wrap;"string"===typeof f?(b.parameter(f,W),c=e=W[f]):Array.isArray(f)&&(b.parameter(f[0],W),b.parameter(f[1],W),c=W[f[0]],e=W[f[1]])}else"wrapS"in d&&(c=d.wrapS,b.parameter(c,W),c=W[c]),"wrapT"in d&&(e=d.wrapT,b.parameter(e,W),e=W[e]);a.wrapS=c;a.wrapT=e;"anisotropic"in d&& (c=d.anisotropic,b("number"===typeof c&&1<=c&&c<=k.maxAnisotropic,"aniso samples must be between 1 and "),a.anisotropic=d.anisotropic);if("mipmap"in d){c=!1;switch(typeof d.mipmap){case "string":b.parameter(d.mipmap,ya,"invalid mipmap hint");a.mipmapHint=ya[d.mipmap];c=a.genMipmaps=!0;break;case "boolean":c=a.genMipmaps=d.mipmap;break;case "object":b(Array.isArray(d.mipmap),"invalid mipmap type");a.genMipmaps=!1;c=!0;break;default:b.raise("invalid mipmap type")}!c||"min"in d||(a.minFilter=9984)}} function ja(b,c){a.texParameteri(c,10241,b.minFilter);a.texParameteri(c,10240,b.magFilter);a.texParameteri(c,10242,b.wrapS);a.texParameteri(c,10243,b.wrapT);l.ext_texture_filter_anisotropic&&a.texParameteri(c,34046,b.anisotropic);b.genMipmaps&&(a.hint(33170,b.mipmapHint),a.generateMipmap(c))}function la(b){y.call(this);this.mipmask=0;this.internalformat=6408;this.id=Pa++;this.refCount=1;this.target=b;this.texture=a.createTexture();this.unit=-1;this.bindCount=0;this.texInfo=new xa;H.profile&&(this.stats= {size:0})}function ma(b){a.activeTexture(33984);a.bindTexture(b.target,b.texture)}function na(){var b=ea[0];b?a.bindTexture(b.target,b.texture):a.bindTexture(3553,null)}function qa(c){var e=c.texture;b(e,"must not double destroy texture");var f=c.unit,l=c.target;0<=f&&(a.activeTexture(33984+f),a.bindTexture(l,null),ea[f]=null);a.deleteTexture(e);c.texture=null;c.params=null;c.pixels=null;c.refCount=0;delete va[c.id];I.textureCount--}var ya={"don't care":4352,"dont care":4352,nice:4354,fast:4353}, W={repeat:10497,clamp:33071,mirror:33648},Z={nearest:9728,linear:9729},T=n({mipmap:9987,"nearest mipmap nearest":9984,"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},Z),U={none:0,browser:37444},R={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},aa={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},fa={};l.ext_srgb&&(aa.srgb=35904,aa.srgba=35906);l.oes_texture_float&&(R.float32=R["float"]=5126); l.oes_texture_half_float&&(R.float16=R["half float"]=36193);l.webgl_depth_texture&&(n(aa,{depth:6402,"depth stencil":34041}),n(R,{uint16:5123,uint32:5125,"depth stencil":34042}));l.webgl_compressed_texture_s3tc&&n(fa,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779});l.webgl_compressed_texture_atc&&n(fa,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798});l.webgl_compressed_texture_pvrtc&&n(fa,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841, "rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843});l.webgl_compressed_texture_etc1&&(fa["rgb etc1"]=36196);var za=Array.prototype.slice.call(a.getParameter(34467));Object.keys(fa).forEach(function(a){var b=fa[a];0<=za.indexOf(b)&&(aa[a]=b)});var ha=Object.keys(aa);k.textureFormats=ha;var ua=[];Object.keys(aa).forEach(function(a){ua[aa[a]]=a});var Da=[];Object.keys(R).forEach(function(a){Da[R[a]]=a});var Fa=[];Object.keys(Z).forEach(function(a){Fa[Z[a]]=a});var Ia=[];Object.keys(T).forEach(function(a){Ia[T[a]]= a});var Ea=[];Object.keys(W).forEach(function(a){Ea[W[a]]=a});var Ja=ha.reduce(function(a,b){var d=aa[b];6409===d||6406===d||6409===d||6410===d||6402===d||34041===d?a[d]=d:32855===d||0<=b.indexOf("rgba")?a[d]=6408:a[d]=6407;return a},{}),Ka=[],La=[],Pa=0,va={},sa=k.maxTextureUnits,ea=Array(sa).map(function(){return null});n(la.prototype,{bind:function(){this.bindCount+=1;var c=this.unit;if(0>c){for(var e=0;e<sa;++e){var f=ea[e];if(f){if(0<f.bindCount)continue;f.unit=-1}ea[e]=this;c=e;break}c>=sa&& b.raise("insufficient number of texture units");H.profile&&I.maxTextureUnits<c+1&&(I.maxTextureUnits=c+1);this.unit=c;a.activeTexture(33984+c);a.bindTexture(this.target,this.texture)}return c},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&qa(this)}});H.profile&&(I.getTotalTextureSize=function(){var a=0;Object.keys(va).forEach(function(b){a+=va[b].stats.size});return a});return{create2D:function(c,e){function f(a,d){var c=l.texInfo;xa.call(c);var e=Ca();"number"===typeof a? "number"===typeof d?ba(e,a|0,d|0):ba(e,a|0,a|0):a?(b.type(a,"object","invalid arguments to regl.texture"),ca(c,a),S(e,a)):ba(e,1,1);c.genMipmaps&&(e.mipmask=(e.width<<1)-1);l.mipmask=e.mipmask;J(l,e);b.texture2D(c,e,k);l.internalformat=e.internalformat;f.width=e.width;f.height=e.height;ma(l);O(e,3553);ja(c,3553);na();ta(e);H.profile&&(l.stats.size=m(l.internalformat,l.type,e.width,e.height,c.genMipmaps,!1));f.format=ua[l.internalformat];f.type=Da[l.type];f.mag=Fa[c.magFilter];f.min=Ia[c.minFilter]; f.wrapS=Ea[c.wrapS];f.wrapT=Ea[c.wrapT];return f}var l=new la(3553);va[l.id]=l;I.textureCount++;f(c,e);f.subimage=function(a,d,c,e){b(!!a,"must specify image data");d|=0;c|=0;e|=0;var g=ka();J(g,l);g.width=0;g.height=0;M(g,a);g.width=g.width||(l.width>>e)-d;g.height=g.height||(l.height>>e)-c;b(l.type===g.type&&l.format===g.format&&l.internalformat===g.internalformat,"incompatible format for texture.subimage");b(0<=d&&0<=c&&d+g.width<=l.width&&c+g.height<=l.height,"texture.subimage write out of bounds"); b(l.mipmask&1<<e,"missing mipmap data");b(g.data||g.element||g.needsCopy,"missing image data");ma(l);ra(g,3553,d,c,e);na();oa(g);return f};f.resize=function(b,c){var e=b|0,g=c|0||e;if(e===l.width&&g===l.height)return f;f.width=l.width=e;f.height=l.height=g;ma(l);for(var h=0;l.mipmask>>h;++h)a.texImage2D(3553,h,l.format,e>>h,g>>h,0,l.format,l.type,null);na();H.profile&&(l.stats.size=m(l.internalformat,l.type,e,g,!1,!1));return f};f._reglType="texture2d";f._texture=l;H.profile&&(f.stats=l.stats);f.destroy= function(){l.decRef()};return f},createCube:function(c,e,f,l,h,q){function n(a,d,c,e,f,g){var l,h=p.texInfo;xa.call(h);for(l=0;6>l;++l)r[l]=Ca();if("number"!==typeof a&&a)if("object"===typeof a)if(d)S(r[0],a),S(r[1],d),S(r[2],c),S(r[3],e),S(r[4],f),S(r[5],g);else if(ca(h,a),Y(p,a),"faces"in a)for(a=a.faces,b(Array.isArray(a)&&6===a.length,"cube faces must be a length 6 array"),l=0;6>l;++l)b("object"===typeof a[l]&&!!a[l],"invalid input for cube map face"),J(r[l],p),S(r[l],a[l]);else for(l=0;6>l;++l)S(r[l], a);else b.raise("invalid arguments to cube map");else for(a=a|0||1,l=0;6>l;++l)ba(r[l],a,a);J(p,r[0]);p.mipmask=h.genMipmaps?(r[0].width<<1)-1:r[0].mipmask;b.textureCube(p,h,r,k);p.internalformat=r[0].internalformat;n.width=r[0].width;n.height=r[0].height;ma(p);for(l=0;6>l;++l)O(r[l],34069+l);ja(h,34067);na();H.profile&&(p.stats.size=m(p.internalformat,p.type,n.width,n.height,h.genMipmaps,!0));n.format=ua[p.internalformat];n.type=Da[p.type];n.mag=Fa[h.magFilter];n.min=Ia[h.minFilter];n.wrapS=Ea[h.wrapS]; n.wrapT=Ea[h.wrapT];for(l=0;6>l;++l)ta(r[l]);return n}var p=new la(34067);va[p.id]=p;I.cubeCount++;var r=Array(6);n(c,e,f,l,h,q);n.subimage=function(a,d,c,e,f){b(!!d,"must specify image data");b("number"===typeof a&&a===(a|0)&&0<=a&&6>a,"invalid face");c|=0;e|=0;f|=0;var g=ka();J(g,p);g.width=0;g.height=0;M(g,d);g.width=g.width||(p.width>>f)-c;g.height=g.height||(p.height>>f)-e;b(p.type===g.type&&p.format===g.format&&p.internalformat===g.internalformat,"incompatible format for texture.subimage"); b(0<=c&&0<=e&&c+g.width<=p.width&&e+g.height<=p.height,"texture.subimage write out of bounds");b(p.mipmask&1<<f,"missing mipmap data");b(g.data||g.element||g.needsCopy,"missing image data");ma(p);ra(g,34069+a,c,e,f);na();oa(g);return n};n.resize=function(b){b|=0;if(b!==p.width){n.width=p.width=b;n.height=p.height=b;ma(p);for(var c=0;6>c;++c)for(var e=0;p.mipmask>>e;++e)a.texImage2D(34069+c,e,p.format,b>>e,b>>e,0,p.format,p.type,null);na();H.profile&&(p.stats.size=m(p.internalformat,p.type,n.width, n.height,!1,!0));return n}};n._reglType="textureCube";n._texture=p;H.profile&&(n.stats=p.stats);n.destroy=function(){p.decRef()};return n},clear:function(){for(var b=0;b<sa;++b)a.activeTexture(33984+b),a.bindTexture(3553,null),ea[b]=null;E(va).forEach(qa);I.cubeCount=0;I.textureCount=0},getTexture:function(a){return null},restore:function(){E(va).forEach(function(b){b.texture=a.createTexture();a.bindTexture(b.target,b.texture);for(var c=0;32>c;++c)if(0!==(b.mipmask&1<<c))if(3553===b.target)a.texImage2D(3553, c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);else for(var e=0;6>e;++e)a.texImage2D(34069+e,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);ja(b.texInfo,b.target)})}}}},{"./constants/arraytypes.json":4,"./util/check":21,"./util/extend":24,"./util/flatten":25,"./util/is-array-like":26,"./util/is-ndarray":27,"./util/is-typed-array":28,"./util/pool":30,"./util/to-half-float":32,"./util/values":33}],20:[function(k,u,y){u.exports=function(c,f){function h(){this.endQueryIndex= this.startQueryIndex=-1;this.sum=0;this.stats=null}function k(b,c,e){var f=n.pop()||new h;f.startQueryIndex=b;f.endQueryIndex=c;f.sum=0;f.stats=e;u.push(f)}var e=f.ext_disjoint_timer_query;if(!e)return null;var m=[],b=[],n=[],u=[],C=[],v=[];return{beginQuery:function(c){var f=m.pop()||e.createQueryEXT();e.beginQueryEXT(35007,f);b.push(f);k(b.length-1,b.length,c)},endQuery:function(){e.endQueryEXT(35007)},pushScopeStats:k,update:function(){var c,f;c=b.length;if(0!==c){v.length=Math.max(v.length,c+ 1);C.length=Math.max(C.length,c+1);C[0]=0;var h=v[0]=0;for(f=c=0;f<b.length;++f){var k=b[f];e.getQueryObjectEXT(k,34919)?(h+=e.getQueryObjectEXT(k,34918),m.push(k)):b[c++]=k;C[f+1]=h;v[f+1]=c}b.length=c;for(f=c=0;f<u.length;++f){var h=u[f],w=h.startQueryIndex,k=h.endQueryIndex;h.sum+=C[k]-C[w];w=v[w];k=v[k];k===w?(h.stats.gpuTime+=h.sum/1E6,n.push(h)):(h.startQueryIndex=w,h.endQueryIndex=k,u[c++]=h)}u.length=c}},getNumPendingQueries:function(){return b.length},clear:function(){m.push.apply(m,b);for(var c= 0;c<m.length;c++)e.deleteQueryEXT(m[c]);b.length=0;m.length=0},restore:function(){b.length=0;m.length=0}}}},{}],21:[function(k,u,y){function c(a){return"undefined"!==typeof btoa?btoa(a):"base64:"+a}function f(a){a=Error("(regl) "+a);console.error(a);throw a;}function h(a,b){a||f(b)}function w(a){return a?": "+a:""}function e(a,b,c){0>b.indexOf(a)&&f("invalid value"+w(c)+". must be one of: "+b)}function m(a,b){for(a+="";a.length<b;)a=" "+a;return a}function b(){this.name="unknown";this.lines=[];this.index= {};this.hasErrors=!1}function n(a,b){this.number=a;this.line=b;this.errors=[]}function E(a,b,c){this.file=a;this.line=b;this.message=c}function C(){var a=Error(),a=(a.stack||a).toString(),b=/compileProcedure.*\n\s*at.*\((.*)\)/.exec(a);return b?b[1]:(a=/compileProcedure.*\n\s*at\s+(.*)(\n|$)/.exec(a))?a[1]:"unknown"}function v(){var a=Error(),a=(a.stack||a).toString(),b=/at REGLCommand.*\n\s+at.*\((.*)\)/.exec(a);return b?b[1]:(a=/at REGLCommand.*\n\s+at\s+(.*)\n/.exec(a))?a[1]:"unknown"}function q(a, d){var e=a.split("\n"),f=1,l=0,h={unknown:new b,0:new b};h.unknown.name=h[0].name=d||C();h.unknown.lines.push(new n(0,""));for(var m=0;m<e.length;++m){var k=e[m],q=/^\s*\#\s*(\w+)\s+(.+)\s*$/.exec(k);if(q)switch(q[1]){case "line":if(q=/(\d+)(\s+\d+)?/.exec(q[2]))f=q[1]|0,q[2]&&(l=q[2]|0,l in h||(h[l]=new b));break;case "define":if(q=/SHADER_NAME(_B64)?\s+(.*)$/.exec(q[2]))h[l].name=q[1]?c(q[2]):q[2]}h[l].lines.push(new n(f++,k))}Object.keys(h).forEach(function(a){var b=h[a];b.lines.forEach(function(a){b.index[a.number]= a})});return h}function F(a){var b=[];a.split("\n").forEach(function(a){if(!(5>a.length)){var c=/^ERROR\:\s+(\d+)\:(\d+)\:\s*(.*)$/.exec(a);c?b.push(new E(c[1]|0,c[2]|0,c[3].trim())):0<a.length&&b.push(new E("unknown",0,a))}});return b}function A(a,b){b.forEach(function(b){var d=a[b.file];if(d){var c=d.index[b.line];if(c){c.errors.push(b);d.hasErrors=!0;return}}a.unknown.hasErrors=!0;a.unknown.lines[0].errors.push(b)})}function B(a){a._commandRef=C()}function G(a,b){var c=v();f(a+" in command "+(b|| C())+("unknown"===c?"":" called from "+c))}function p(a,b,c,e){typeof a!==b&&G("invalid parameter type"+w(c)+". expected "+b+", got "+typeof a,e||C())}function r(a,b){return 32820===a||32819===a||33635===a?2:34042===a?4:l[a]*b}var N=k("./is-typed-array");k=k("./extend");var I="gl canvas container attributes pixelRatio extensions optionalExtensions profile onDone".split(" "),l={};l[5120]=l[5121]=1;l[5122]=l[5123]=l[36193]=l[33635]=l[32819]=l[32820]=2;l[5124]=l[5125]=l[5126]=l[34042]=4;u.exports=k(h, {optional:function(a){a()},raise:f,commandRaise:G,command:function(a,b,c){a||G(b,c||C())},parameter:function(a,b,c){a in b||f("unknown parameter ("+a+")"+w(c)+". possible values: "+Object.keys(b).join())},commandParameter:function(a,b,c,e){a in b||G("unknown parameter ("+a+")"+w(c)+". possible values: "+Object.keys(b).join(),e||C())},constructor:function(a){Object.keys(a).forEach(function(a){0>I.indexOf(a)&&f('invalid regl constructor argument "'+a+'". must be one of '+I)})},type:function(a,b,c){typeof a!== b&&f("invalid parameter type"+w(c)+". expected "+b+", got "+typeof a)},commandType:p,isTypedArray:function(a,b){N(a)||f("invalid parameter type"+w(b)+". must be a typed array")},nni:function(a,b){0<=a&&(a|0)===a||f("invalid parameter type, ("+a+")"+w(b)+". must be a nonnegative integer")},oneOf:e,shaderError:function(a,b,c,e,f){if(!a.getShaderParameter(b,a.COMPILE_STATUS)){b=a.getShaderInfoLog(b);a=e===a.FRAGMENT_SHADER?"fragment":"vertex";p(c,"string",a+" shader source must be a string",f);var l= q(c,f);c=F(b);A(l,c);Object.keys(l).forEach(function(a){function b(a,d){c.push(a);e.push(d||"")}var d=l[a];if(d.hasErrors){var c=[""],e=[""];b("file number "+a+": "+d.name+"\n","color:red;text-decoration:underline;font-weight:bold");d.lines.forEach(function(a){if(0<a.errors.length){b(m(a.number,4)+"| ","background-color:yellow; font-weight:bold");b(a.line+"\n","color:red; background-color:yellow; font-weight:bold");var d=0;a.errors.forEach(function(c){c=c.message;var e=/^\s*\'(.*)\'\s*\:\s*(.*)$/.exec(c); if(e){var f=e[1];c=e[2];switch(f){case "assign":f="="}d=Math.max(a.line.indexOf(f,d),0)}else d=0;b(m("| ",6));b(m("^^^",d+3)+"\n","font-weight:bold");b(m("| ",6));b(c+"\n","font-weight:bold")});b(m("| ",6)+"\n")}else b(m(a.number,4)+"| "),b(a.line+"\n","color:red")});"undefined"!==typeof document?(e[0]=c.join("%c"),console.log.apply(console,e)):console.log(c.join(""))}});h.raise("Error compiling "+a+" shader, "+l[0].name)}},linkError:function(a,b,c,e,f){a.getProgramParameter(b,a.LINK_STATUS)||(a= a.getProgramInfoLog(b),c=q(c,f),e='Error linking program with vertex shader, "'+q(e,f)[0].name+'", and fragment shader "'+c[0].name+'"',"undefined"!==typeof document?console.log("%c"+e+"\n%c"+a,"color:red;text-decoration:underline;font-weight:bold","color:red"):console.log(e+"\n"+a),h.raise(e))},callSite:v,saveCommandRef:B,saveDrawInfo:function(a,b,c,e){function f(a){return a?e.id(a):0}function l(a,b){Object.keys(b).forEach(function(b){a[e.id(b)]=!0})}B(a);a._fragId=f(a["static"].frag);a._vertId= f(a["static"].vert);var h=a._uniformSet={};l(h,b["static"]);l(h,b.dynamic);b=a._attributeSet={};l(b,c["static"]);l(b,c.dynamic);a._hasCount="count"in a["static"]||"count"in a.dynamic||"elements"in a["static"]||"elements"in a.dynamic},framebufferFormat:function(a,b,c){a.texture?e(a.texture._texture.internalformat,b,"unsupported texture format for attachment"):e(a.renderbuffer._renderbuffer.format,c,"unsupported renderbuffer format for attachment")},guessCommand:C,texture2D:function(a,b,c){var e=b.width, f=b.height,l=b.channels;h(0<e&&e<=c.maxTextureSize&&0<f&&f<=c.maxTextureSize,"invalid texture shape");33071===a.wrapS&&33071===a.wrapT||h(!(e&e-1)&&!!e&&!(f&f-1)&&!!f,"incompatible wrap mode for texture, both width and height must be power of 2");1===b.mipmask?1!==e&&1!==f&&h(9984!==a.minFilter&&9986!==a.minFilter&&9985!==a.minFilter&&9987!==a.minFilter,"min filter requires mipmap"):(h(!(e&e-1)&&!!e&&!(f&f-1)&&!!f,"texture must be a square power of 2 to support mipmapping"),h(b.mipmask===(e<<1)-1, "missing or incomplete mipmap data"));5126===b.type&&(0>c.extensions.indexOf("oes_texture_float_linear")&&h(9728===a.minFilter&&9728===a.magFilter,"filter not supported, must enable oes_texture_float_linear"),h(!a.genMipmaps,"mipmap generation not supported with float textures"));var m=b.images;for(c=0;16>c;++c)if(m[c]){var k=e>>c,n=f>>c;h(b.mipmask&1<<c,"missing mipmap data");var q=m[c];h(q.width===k&&q.height===n,"invalid shape for mip images");h(q.format===b.format&&q.internalformat===b.internalformat&& q.type===b.type,"incompatible type for mip image");q.compressed||q.data&&h(q.data.byteLength===k*n*Math.max(r(q.type,l),q.unpackAlignment),"invalid data for image, buffer size is inconsistent with image format")}else a.genMipmaps||h(0===(b.mipmask&1<<c),"extra mipmap data");b.compressed&&h(!a.genMipmaps,"mipmap generation for compressed images not supported")},textureCube:function(a,b,c,e){var f=a.width,l=a.height,m=a.channels;h(0<f&&f<=e.maxTextureSize&&0<l&&l<=e.maxTextureSize,"invalid texture shape"); h(f===l,"cube map must be square");h(33071===b.wrapS&&33071===b.wrapT,"wrap mode not supported by cube map");for(e=0;e<c.length;++e){var k=c[e];h(k.width===f&&k.height===l,"inconsistent cube map face shape");b.genMipmaps&&(h(!k.compressed,"can not generate mipmap for compressed textures"),h(1===k.mipmask,"can not specify mipmaps and generate mipmaps"));for(var n=k.images,q=0;16>q;++q){var p=n[q];if(p){var v=f>>q,w=l>>q;h(k.mipmask&1<<q,"missing mipmap data");h(p.width===v&&p.height===w,"invalid shape for mip images"); h(p.format===a.format&&p.internalformat===a.internalformat&&p.type===a.type,"incompatible type for mip image");p.compressed||p.data&&h(p.data.byteLength===v*w*Math.max(r(p.type,m),p.unpackAlignment),"invalid data for image, buffer size is inconsistent with image format")}}}}})},{"./extend":24,"./is-typed-array":28}],22:[function(k,u,y){u.exports="undefined"!==typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date}},{}],23:[function(k,u,y){function c(c){return Array.prototype.slice.call(c)} function f(f){return c(f).join("")}var h=k("./extend");u.exports=function(){function k(){var b=[],e=[];return h(function(){b.push.apply(b,c(arguments))},{def:function(){var f="v"+m++;e.push(f);0<arguments.length&&(b.push(f,"="),b.push.apply(b,c(arguments)),b.push(";"));return f},toString:function(){return f([0<e.length?"var "+e+";":"",f(b)])}})}function e(){function b(c,h){f(c,h,"=",e.def(c,h),";")}var e=k(),f=k(),m=e.toString,n=f.toString;return h(function(){e.apply(e,c(arguments))},{def:e.def,entry:e, exit:f,save:b,set:function(c,f,h){b(c,f);e(c,f,"=",h,";")},toString:function(){return m()+n()}})}var m=0,b=[],n=[],u=k(),C={};return{global:u,link:function(c){for(var e=0;e<n.length;++e)if(n[e]===c)return b[e];e="g"+m++;b.push(e);n.push(c);return e},block:k,proc:function(b,c){function m(){var b="a"+k.length;k.push(b);return b}var k=[];c=c||0;for(var n=0;n<c;++n)m();var n=e(),w=n.toString;return C[b]=h(n,{arg:m,toString:function(){return f(["function(",k.join(),"){",w(),"}"])}})},scope:e,cond:function(){var b= f(arguments),m=e(),k=e(),n=m.toString,w=k.toString;return h(m,{then:function(){m.apply(m,c(arguments));return this},"else":function(){k.apply(k,c(arguments));return this},toString:function(){var c=w();c&&(c="else{"+c+"}");return f(["if(",b,"){",n(),"}",c])}})},compile:function(){var c=['"use strict";',u,"return {"];Object.keys(C).forEach(function(b){c.push('"',b,'":',C[b].toString(),",")});c.push("}");var e=f(c).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null, b.concat(e)).apply(null,n)}}}},{"./extend":24}],24:[function(k,u,y){u.exports=function(c,f){for(var h=Object.keys(f),k=0;k<h.length;++k)c[h[k]]=f[h[k]];return c}},{}],25:[function(k,u,y){function c(c,e,f,b,h,k){for(var u=0;u<e;++u)for(var v=c[u],q=0;q<f;++q)for(var y=v[q],A=0;A<b;++A)h[k++]=y[A]}function f(h,e,m,b,k){for(var u=1,C=m+1;C<e.length;++C)u*=e[C];var v=e[m];if(4===e.length-m){var q=e[m+1],y=e[m+2];e=e[m+3];for(C=0;C<v;++C)c(h[C],q,y,e,b,k),k+=u}else for(C=0;C<v;++C)f(h[C],e,m+1,b,k),k+= u}var h=k("./pool");u.exports={shape:function(c){for(var e=[];c.length;c=c[0])e.push(c.length);return e},flatten:function(k,e,m,b){var n=1;if(e.length)for(var u=0;u<e.length;++u)n*=e[u];else n=0;m=b||h.allocType(m,n);switch(e.length){case 0:break;case 1:b=e[0];for(e=0;e<b;++e)m[e]=k[e];break;case 2:b=e[0];e=e[1];for(u=n=0;u<b;++u)for(var C=k[u],v=0;v<e;++v)m[n++]=C[v];break;case 3:c(k,e[0],e[1],e[2],m,0);break;default:f(k,e,0,m,0)}return m}}},{"./pool":30}],26:[function(k,u,y){var c=k("./is-typed-array"); u.exports=function(f){return Array.isArray(f)||c(f)}},{"./is-typed-array":28}],27:[function(k,u,y){var c=k("./is-typed-array");u.exports=function(f){return!!f&&"object"===typeof f&&Array.isArray(f.shape)&&Array.isArray(f.stride)&&"number"===typeof f.offset&&f.shape.length===f.stride.length&&(Array.isArray(f.data)||c(f.data))}},{"./is-typed-array":28}],28:[function(k,u,y){var c=k("../constants/arraytypes.json");u.exports=function(f){return Object.prototype.toString.call(f)in c}},{"../constants/arraytypes.json":4}], 29:[function(k,u,y){u.exports=function(c,f){for(var h=Array(c),k=0;k<c;++k)h[k]=f(k);return h}},{}],30:[function(k,u,y){function c(c){var f,b;f=(65535<c)<<4;c>>>=f;b=(255<c)<<3;c>>>=b;f|=b;b=(15<c)<<2;c>>>=b;f|=b;b=(3<c)<<1;return f|b|c>>>b>>1}function f(e){a:{for(var f=16;268435456>=f;f*=16)if(e<=f){e=f;break a}e=0}f=w[c(e)>>2];return 0<f.length?f.pop():new ArrayBuffer(e)}function h(e){w[c(e.byteLength)>>2].push(e)}var w=k("./loop")(8,function(){return[]});u.exports={alloc:f,free:h,allocType:function(c, h){var b=null;switch(c){case 5120:b=new Int8Array(f(h),0,h);break;case 5121:b=new Uint8Array(f(h),0,h);break;case 5122:b=new Int16Array(f(2*h),0,h);break;case 5123:b=new Uint16Array(f(2*h),0,h);break;case 5124:b=new Int32Array(f(4*h),0,h);break;case 5125:b=new Uint32Array(f(4*h),0,h);break;case 5126:b=new Float32Array(f(4*h),0,h);break;default:return null}return b.length!==h?b.subarray(0,h):b},freeType:function(c){h(c.buffer)}}},{"./loop":29}],31:[function(k,u,y){u.exports={next:"function"===typeof requestAnimationFrame? function(c){return requestAnimationFrame(c)}:function(c){return setTimeout(c,16)},cancel:"function"===typeof cancelAnimationFrame?function(c){return cancelAnimationFrame(c)}:clearTimeout}},{}],32:[function(k,u,y){var c=k("./pool"),f=new Float32Array(1),h=new Uint32Array(f.buffer);u.exports=function(k){for(var e=c.allocType(5123,k.length),m=0;m<k.length;++m)if(isNaN(k[m]))e[m]=65535;else if(Infinity===k[m])e[m]=31744;else if(-Infinity===k[m])e[m]=64512;else{f[0]=k[m];var b=h[0],n=b>>>31<<15,u=(b<< 1>>>24)-127,b=b>>13&1023;e[m]=-24>u?n:-14>u?n+(b+1024>>-14-u):15<u?n+31744:n+(u+15<<10)+b}return e}},{"./pool":30}],33:[function(k,u,y){u.exports=function(c){return Object.keys(c).map(function(f){return c[f]})}},{}],34:[function(k,u,y){function c(b,c,e){function f(){var c=window.innerWidth,k=window.innerHeight;b!==document.body&&(k=b.getBoundingClientRect(),c=k.right-k.left,k=k.bottom-k.top);h.width=e*c;h.height=e*k;m(h.style,{width:c+"px",height:k+"px"})}var h=document.createElement("canvas");m(h.style, {border:0,margin:0,padding:0,top:0,left:0});b.appendChild(h);b===document.body&&(h.style.position="absolute",m(b.style,{margin:0,padding:0}));window.addEventListener("resize",f,!1);f();return{canvas:h,onDestroy:function(){window.removeEventListener("resize",f);b.removeChild(h)}}}function f(b,c){function e(f){try{return b.getContext(f,c)}catch(h){return null}}return e("webgl")||e("experimental-webgl")||e("webgl-experimental")}function h(b){if("string"===typeof b)return b.split();e(Array.isArray(b), "invalid extension array");return b}function w(b){return"string"===typeof b?(e("undefined"!==typeof document,"not supported outside of DOM"),document.querySelector(b)):b}var e=k("./util/check"),m=k("./util/extend");u.exports=function(b){var k=b||{},m,u,v,q;b={};var y=[],A=[],B="undefined"===typeof window?1:window.devicePixelRatio,G=!1,p=function(b){b&&e.raise(b)},r=function(){};"string"===typeof k?(e("undefined"!==typeof document,"selector queries only supported in DOM enviroments"),m=document.querySelector(k), e(m,"invalid query string for element")):"object"===typeof k?"string"===typeof k.nodeName&&"function"===typeof k.appendChild&&"function"===typeof k.getBoundingClientRect?m=k:"function"===typeof k.drawArrays||"function"===typeof k.drawElements?(q=k,v=q.canvas):(e.constructor(k),"gl"in k?q=k.gl:"canvas"in k?v=w(k.canvas):"container"in k&&(u=w(k.container)),"attributes"in k&&(b=k.attributes,e.type(b,"object","invalid context attributes")),"extensions"in k&&(y=h(k.extensions)),"optionalExtensions"in k&& (A=h(k.optionalExtensions)),"onDone"in k&&(e.type(k.onDone,"function","invalid or missing onDone callback"),p=k.onDone),"profile"in k&&(G=!!k.profile),"pixelRatio"in k&&(B=+k.pixelRatio,e(0<B,"invalid pixel ratio"))):e.raise("invalid arguments to regl");m&&("canvas"===m.nodeName.toLowerCase()?v=m:u=m);if(!q){if(!v){e("undefined"!==typeof document,"must manually specify webgl context outside of DOM environments");m=c(u||document.body,p,B);if(!m)return null;v=m.canvas;r=m.onDestroy}q=f(v,b)}return q? {gl:q,canvas:v,container:u,extensions:y,optionalExtensions:A,pixelRatio:B,profile:G,onDone:p,onDestroy:r}:(r(),p("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}},{"./util/check":21,"./util/extend":24}],35:[function(k,u,y){u.exports=function(f,h){function k(b){var c=!1;"altKey"in b&&(c=c||b.altKey!==p.alt,p.alt=!!b.altKey);"shiftKey"in b&&(c=c||b.shiftKey!==p.shift,p.shift=!!b.shiftKey);"ctrlKey"in b&&(c=c||b.ctrlKey!==p.control,p.control=!!b.ctrlKey); "metaKey"in b&&(c=c||b.metaKey!==p.meta,p.meta=!!b.metaKey);return c}function e(b,e){var a=c.x(e),d=c.y(e);"buttons"in e&&(b=e.buttons|0);if(b!==A||a!==B||d!==G||k(e))A=b|0,B=a||0,G=d||0,h&&h(A,B,G,p)}function m(b){e(0,b)}function b(){if(A||B||G||p.shift||p.alt||p.meta||p.control)A=B=G=0,p.shift=p.alt=p.control=p.meta=!1,h&&h(0,0,0,p)}function n(b){k(b)&&h&&h(A,B,G,p)}function u(b){0===c.buttons(b)?e(0,b):e(A,b)}function y(b){e(A|c.buttons(b),b)}function v(b){e(A&~c.buttons(b),b)}function q(){r|| (r=!0,f.addEventListener("mousemove",u),f.addEventListener("mousedown",y),f.addEventListener("mouseup",v),f.addEventListener("mouseleave",m),f.addEventListener("mouseenter",m),f.addEventListener("mouseout",m),f.addEventListener("mouseover",m),f.addEventListener("blur",b),f.addEventListener("keyup",n),f.addEventListener("keydown",n),f.addEventListener("keypress",n),f!==window&&(window.addEventListener("blur",b),window.addEventListener("keyup",n),window.addEventListener("keydown",n),window.addEventListener("keypress", n)))}function F(){r&&(r=!1,f.removeEventListener("mousemove",u),f.removeEventListener("mousedown",y),f.removeEventListener("mouseup",v),f.removeEventListener("mouseleave",m),f.removeEventListener("mouseenter",m),f.removeEventListener("mouseout",m),f.removeEventListener("mouseover",m),f.removeEventListener("blur",b),f.removeEventListener("keyup",n),f.removeEventListener("keydown",n),f.removeEventListener("keypress",n),f!==window&&(window.removeEventListener("blur",b),window.removeEventListener("keyup", n),window.removeEventListener("keydown",n),window.removeEventListener("keypress",n)))}h||(h=f,f=window);var A=0,B=0,G=0,p={shift:!1,alt:!1,control:!1,meta:!1},r=!1;q();var N={element:f};Object.defineProperties(N,{enabled:{get:function(){return r},set:function(b){b?q():F},enumerable:!0},buttons:{get:function(){return A},enumerable:!0},x:{get:function(){return B},enumerable:!0},y:{get:function(){return G},enumerable:!0},mods:{get:function(){return p},enumerable:!0}});return N};var c=k("mouse-event")}, {"mouse-event":36}],36:[function(k,u,y){function c(c){return c.target||c.srcElement||window}y.buttons=function(c){if("object"===typeof c){if("buttons"in c)return c.buttons;if("which"in c){c=c.which;if(2===c)return 4;if(3===c)return 2;if(0<c)return 1<<c-1}else if("button"in c){c=c.button;if(1===c)return 4;if(2===c)return 2;if(0<=c)return 1<<c}}return 0};y.element=c;y.x=function(f){if("object"===typeof f){if("offsetX"in f)return f.offsetX;var h=c(f).getBoundingClientRect();return f.clientX-h.left}return 0}; y.y=function(f){if("object"===typeof f){if("offsetY"in f)return f.offsetY;var h=c(f).getBoundingClientRect();return f.clientY-h.top}return 0}},{}],37:[function(k,u,y){function c(b){throw Error("resl: "+b);}function f(b,e,f){Object.keys(b).forEach(function(b){0>e.indexOf(b)&&c('invalid parameter "'+b+'" in '+f)})}function h(b,c){this.state=0;this.ready=!1;this.progress=0;this.name=b;this.cancel=c}var w=["manifest","onDone","onProgress","onError"],e=["type","src","stream","credentials","parser"],m= ["onData","onDone"];u.exports=function(b){function k(e,a){if(e in b){var d=b[e];"function"!==typeof d&&c('invalid callback "'+e+'"');return d}return null}function u(b){function a(){if(!(2>k.readyState||1===n.state||-1===n.state)){if(200!==k.status)return v('error loading resource "'+b.name+'"');if(2<k.readyState&&0===n.state){var a;a="binary"===b.type?k.response:k.responseText;if(f.data)try{m=f.data(a)}catch(c){return v(c)}else m=a}if(3<k.readyState&&0===n.state){if(f.done)try{m=f.done()}catch(c){return v(c)}n.state= 1}p[d]=m;n.progress=.75*n.progress+.25;n.ready=b.stream&&!!m||1===n.state;q()}}var d=b.name,c=b.stream,e="binary"===b.type,f=b.parser,k=new XMLHttpRequest,m=null,n=new h(d,function(){1!==n.state&&-1!==n.state&&(k.onreadystatechange=null,k.abort(),n.state=-1)});k.onreadystatechange=c?a:function(){4===k.readyState&&a()};e&&(k.responseType="arraybuffer");b.credentials&&(k.withCredentials=!0);k.open("GET",b.src,!0);k.send();return n}function y(b,a){function d(){if(0===r.state)if(n.data)try{u=n.data(a)}catch(b){return v(b)}else u= a}function c(a){d();p[m]=u;r.progress=a.lengthComputable?Math.max(r.progress,a.loaded/a.total):.75*r.progress+.25;q(m)}function e(){d();if(0===r.state){if(n.done)try{u=n.done()}catch(a){return v(a)}r.state=1}r.progress=1;r.ready=!0;p[m]=u;k();q("finish "+m)}function f(){v('error loading asset "'+m+'"')}function k(){b.stream&&a.removeEventListener("progress",c);"image"===b.type?a.addEventListener("load",e):a.addEventListener("canplay",e);a.removeEventListener("error",f)}var m=b.name,n=b.parser,r=new h(m, function(){1!==r.state&&-1!==r.state&&(r.state=-1,k(),a.src="")}),u=a;b.stream&&a.addEventListener("progress",c);if("image"===b.type)a.addEventListener("load",e);else{var w=!1,A=!1;a.addEventListener("loadedmetadata",function(){A=!0;w&&e()});a.addEventListener("canplay",function(){w=!0;A&&e()})}a.addEventListener("error",f);a.crossOrigin=b.credentials?"use-credentials":"anonymous";a.src=b.src;return r}function v(b){-1!==r&&1!==r&&(r=-1,I.forEach(function(a){a.cancel()}),G?"string"===typeof b?G(Error("resl: "+ b)):G(b):console.error("resl error:",b))}function q(b){if(-1!==r&&1!==r){var a=0,c=0;I.forEach(function(b){b.ready&&(c+=1);a+=b.progress});c===I.length?(r=1,A(p)):B&&B(a/I.length,b)}}"object"===typeof b&&b||c("invalid or missing configuration");f(b,w,"config");var F=b.manifest;"object"===typeof F&&F||c("missing manifest");var A=k("onDone");A||c("missing onDone() callback");var B=k("onProgress"),G=k("onError"),p={},r=0,N={text:u,binary:function(b){return u(b)},image:function(b){return y(b,document.createElement("img"))}, video:function(b){return y(b,document.createElement("video"))},audio:function(b){return y(b,document.createElement("audio"))}},I=Object.keys(F).map(function(b){function a(a,b){if(a in d.parser){var e=d.parser[a];"function"!==typeof e&&c("invalid parser callback "+a+' for asset "'+a+'"');return e}return b}var d=F[b];"string"===typeof d?d={src:d}:"object"===typeof d&&d||c('invalid asset definition "'+b+'"');f(d,e,'asset "'+b+'"');var h={};"parser"in d&&("function"===typeof d.parser?h={data:d.parser}: "object"===typeof d.parser&&d.parser?(f(h,m,'parser for asset "'+b+'"'),"onData"in h||c('missing onData callback for parser in asset "'+b+'"'),h={data:a("onData"),done:a("onDone")}):c('invalid parser for asset "'+b+'"'));return{name:b,type:function(a,e,f){a in d&&(f=d[a]);0>e.indexOf(f)&&c("invalid "+a+' "'+f+'" for asset "'+b+'", possible values: '+e);return f}("type",Object.keys(N),"text"),stream:!!d.stream,credentials:!!d.credentials,src:function(a,e,f){a in d?f=d[a]:e&&c("missing "+a+' for asset "'+ b+'"');"string"!==typeof f&&c("invalid "+a+' for asset "'+b+'", must be a string');return f}("src",!0,""),parser:h}}).map(function(b){return N[b.type](b)});0===I.length&&setTimeout(function(){q("done")},1)}},{}],38:[function(k,u,y){function c(a,b){for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}var f=k("./lib/util/check"),h=k("./lib/util/extend"),w=k("./lib/dynamic"),e=k("./lib/util/raf"),m=k("./lib/util/clock"),b=k("./lib/strings"),n=k("./lib/webgl"),E=k("./lib/extension"),C=k("./lib/limits"), v=k("./lib/buffer"),q=k("./lib/elements"),F=k("./lib/texture"),A=k("./lib/renderbuffer"),B=k("./lib/framebuffer"),G=k("./lib/attribute"),p=k("./lib/shader"),r=k("./lib/read"),N=k("./lib/core"),I=k("./lib/stats"),l=k("./lib/timer");u.exports=function(a){function d(){if(0===R.length)O&&O.update(),ha=null;else{ha=e.next(d);Y();for(var a=R.length-1;0<=a;--a){var b=R[a];b&&b(ca,null,0)}M.flush();O&&O.update()}}function k(){!ha&&0<R.length&&(ha=e.next(d))}function u(){ha&&(e.cancel(d),ha=null)}function y(a){a.preventDefault(); ka=!0;u();aa.forEach(function(a){a()})}function ga(a){M.getError();ka=!1;oa.restore();na.restore();la.restore();qa.restore();ya.restore();W.restore();O&&O.restore();Z.procs.refresh();k();fa.forEach(function(a){a()})}function Na(a){function b(a){var c={},d={};Object.keys(a).forEach(function(b){var e=a[b];w.isDynamic(e)?d[b]=w.unbox(e,b):c[b]=e});return{dynamic:d,"static":c}}function c(a){for(;q.length<a;)q.push(null);return q}f(!!a,"invalid args to regl({...})");f.type(a,"object","invalid args to regl({...})"); var d=b(a.context||{}),e=b(a.uniforms||{}),k=b(a.attributes||{}),l=b(function(a){function b(a){if(a in c){var d=c[a];delete c[a];Object.keys(d).forEach(function(b){c[a+"."+b]=d[b]})}}var c=h({},a);delete c.uniforms;delete c.attributes;delete c.context;"stencil"in c&&c.stencil.op&&(c.stencil.opBack=c.stencil.opFront=c.stencil.op,delete c.stencil.op);b("blend");b("depth");b("cull");b("stencil");b("polygonOffset");b("scissor");b("sample");return c}(a));a={gpuTime:0,cpuTime:0,count:0};var d=Z.compile(l, k,e,d,a),m=d.draw,n=d.batch,p=d.scope,q=[];return h(function(a,b){var d;ka&&f.raise("context lost");if("function"===typeof a)return p.call(this,null,a,0);if("function"===typeof b)if("number"===typeof a)for(d=0;d<a;++d)p.call(this,null,b,d);else if(Array.isArray(a))for(d=0;d<a.length;++d)p.call(this,a[d],b,d);else return p.call(this,a,b,0);else if("number"===typeof a){if(0<a)return n.call(this,c(a|0),a|0)}else if(Array.isArray(a)){if(a.length)return n.call(this,a,a.length)}else return m.call(this, a)},{stats:a})}function H(a,b){var c=0;Z.procs.poll();var d=b.color;d&&(M.clearColor(+d[0]||0,+d[1]||0,+d[2]||0,+d[3]||0),c|=16384);"depth"in b&&(M.clearDepth(+b.depth),c|=256);"stencil"in b&&(M.clearStencil(b.stencil|0),c|=1024);f(!!c,"called regl.clear with no buffer specified");M.clear(c)}function ia(a){f.type(a,"function","regl.frame() callback must be a function");R.push(a);k();return{cancel:function(){function b(){var a=c(R,b);R[a]=R[R.length-1];--R.length;0>=R.length&&u()}var d=c(R,a);f(0<= d,"cannot cancel a frame twice");R[d]=b}}}function J(){var a=T.viewport,b=T.scissor_box;a[0]=a[1]=b[0]=b[1]=0;ca.viewportWidth=ca.framebufferWidth=ca.drawingBufferWidth=a[2]=b[2]=M.drawingBufferWidth;ca.viewportHeight=ca.framebufferHeight=ca.drawingBufferHeight=a[3]=b[3]=M.drawingBufferHeight}function Y(){ca.tick+=1;ca.time=Q();J();Z.procs.poll()}function da(){J();Z.procs.refresh();O&&O.update()}function Q(){return(m()-Ca)/1E3}a=n(a);if(!a)return null;var M=a.gl,ra=M.getContextAttributes(),ka=M.isContextLost(), oa=E(M,a);if(!oa)return null;var wa=b(),ba=I(),S=oa.extensions,O=l(M,S),Ca=m(),ta=M.drawingBufferWidth,xa=M.drawingBufferHeight,ca={tick:0,time:0,viewportWidth:ta,viewportHeight:xa,framebufferWidth:ta,framebufferHeight:xa,drawingBufferWidth:ta,drawingBufferHeight:xa,pixelRatio:a.pixelRatio},ja=C(M,S),la=v(M,ba,a),ma=q(M,S,la,ba),ta=G(M,S,ja,la,wa),na=p(M,wa,ba,a),qa=F(M,S,ja,function(){Z.procs.poll()},ca,ba,a),ya=A(M,S,ja,ba,a),W=B(M,S,ja,qa,ya,ba),Z=N(M,wa,S,ja,la,ma,qa,W,{},ta,na,{elements:null, primitive:4,count:-1,offset:0,instances:-1},ca,O,a),wa=r(M,W,Z.procs.poll,ca,ra,S),T=Z.next,U=M.canvas,R=[],aa=[],fa=[],za=[a.onDestroy],ha=null;U&&(U.addEventListener("webglcontextlost",y,!1),U.addEventListener("webglcontextrestored",ga,!1));var ua=W.setFBO=Na({framebuffer:w.define.call(null,1,"framebuffer")});da();ra=h(Na,{clear:function(a){f("object"===typeof a&&a,"regl.clear() takes an object as input");if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b= 0;6>b;++b)ua(h({framebuffer:a.framebuffer.faces[b]},a),H);else ua(a,H);else H(null,a)},prop:w.define.bind(null,1),context:w.define.bind(null,2),"this":w.define.bind(null,3),draw:Na({}),buffer:function(a){return la.create(a,34962,!1,!1)},elements:function(a){return ma.create(a,!1)},texture:qa.create2D,cube:qa.createCube,renderbuffer:ya.create,framebuffer:W.create,framebufferCube:W.createCube,attributes:ra,frame:ia,on:function(a,b){f.type(b,"function","listener callback must be a function");var c;switch(a){case "frame":return ia(b); case "lost":c=aa;break;case "restore":c=fa;break;case "destroy":c=za;break;default:f.raise("invalid event, must be one of frame,lost,restore,destroy")}c.push(b);return{cancel:function(){for(var a=0;a<c.length;++a)if(c[a]===b){c[a]=c[c.length-1];c.pop();break}}}},limits:ja,hasExtension:function(a){return 0<=ja.extensions.indexOf(a.toLowerCase())},read:wa,destroy:function(){R.length=0;u();U&&(U.removeEventListener("webglcontextlost",y),U.removeEventListener("webglcontextrestored",ga));na.clear();W.clear(); ya.clear();qa.clear();ma.clear();la.clear();O&&O.clear();za.forEach(function(a){a()})},_gl:M,_refresh:da,poll:function(){Y();O&&O.update()},now:Q,stats:ba});a.onDone(null,ra);return ra}},{"./lib/attribute":2,"./lib/buffer":3,"./lib/core":8,"./lib/dynamic":9,"./lib/elements":10,"./lib/extension":11,"./lib/framebuffer":12,"./lib/limits":13,"./lib/read":14,"./lib/renderbuffer":15,"./lib/shader":16,"./lib/stats":17,"./lib/strings":18,"./lib/texture":19,"./lib/timer":20,"./lib/util/check":21,"./lib/util/clock":22, "./lib/util/extend":24,"./lib/util/raf":31,"./lib/webgl":34}]},{},[1]);
mit
damianh/LimitsMiddleware
src/LimitsMiddleware.Tests/MaxUrlLengthTests.cs
1973
namespace LimitsMiddleware { using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Owin.Builder; using Owin; using Shouldly; using Xunit; public class MaxUrlLengthTests { [Fact] public async Task When_max_urlLength_is_20_and_a_url_with_length_18_should_be_served() { HttpClient client = CreateClient(20); HttpResponseMessage response = await client.GetAsync("http://example.com"); response.StatusCode.ShouldBe(HttpStatusCode.OK); } [Fact] public async Task When_max_urlLength_is_20_and_a_url_with_length_39_is_coming_it_should_be_rejected() { HttpClient client = CreateClient(20); HttpResponseMessage response = await client.GetAsync("http://example.com/example/example.html"); response.StatusCode.ShouldBe(HttpStatusCode.RequestUriTooLong); } [Fact] public async Task When_max_urlLength_is_30_and_a_url_with_escaped_length_42_but_unescaped_28_it_should_be_served() { HttpClient client = CreateClient(30); HttpResponseMessage response = await client.GetAsync("http://example.com?q=%48%49%50%51%52%53%54"); response.StatusCode.ShouldBe(HttpStatusCode.OK); } private static HttpClient CreateClient(int length) { var app = new AppBuilder(); app.MaxQueryStringLength(length) .MaxUrlLength(length) .Use((context, next) => { context.Response.StatusCode = 200; context.Response.ReasonPhrase = "OK"; return Task.FromResult(0); }); return new HttpClient(new OwinHttpMessageHandler(app.Build())) { BaseAddress = new Uri("http://example.com") }; } } }
mit
AlloyTeam/Nuclear
components/icon/esm/date-range.js
305
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M9 11H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2zm2-7h-1V2h-2v2H8V2H6v2H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V9h14v11z" }), 'DateRange');
mit
RedHatQE/mgmtsystem
wrapanapi/entities/__init__.py
568
""" wrapanapi.entities """ from .template import Template, TemplateMixin from .vm import Vm, VmState, VmMixin from .instance import Instance from .physical_container import PhysicalContainer from .stack import Stack, StackMixin from .server import Server, ServerState from .network import Network, NetworkMixin from .volume import Volume, VolumeMixin __all__ = [ 'Template', 'TemplateMixin', 'Vm', 'VmState', 'VmMixin', 'Instance', 'PhysicalContainer', 'Server', 'ServerState', 'Stack', 'StackMixin', 'Network', 'NetworkMixin', 'Volume', 'VolumeMixin' ]
mit
pocky/person
src/Black/Component/Person/Domain/Model/Person.php
2237
<?php namespace Black\Component\Person\Domain\Model; use Black\DDD\DDDinPHP\Domain\Model\Entity; use Email\EmailAddress; /** * Class Person */ class Person implements Entity { /** * @var PersonId */ protected $personId; /** * @var Name */ protected $name; /** * @var EmailAddress */ protected $email; /** * @var */ protected $gender; /** * @var */ protected $honorificPrefix; /** * @var */ protected $jobTitle; /** * @var */ protected $telephone; /** * @var */ protected $mobile; /** * @var */ protected $faxNumber; /** * @var */ protected $picture; /** * @param PersonId $personId * @param Name $name * @param EmailAddress $email */ public function __construct( PersonId $personId, Name $name, EmailAddress $email ) { $this->personId = $personId; $this->name = $name; $this->email = $email; } /** * @return PersonId */ public function getPersonId() { return $this->personId; } /** * @return Name */ public function getName() { return $this->name; } /** * @return EmailAddress */ public function getEmail() { return $this->email; } /** * @return mixed */ public function getGender() { return $this->gender; } /** * @return mixed */ public function getHonorificPrefix() { return $this->honorificPrefix; } /** * @return mixed */ public function getJobTitle() { return $this->jobTitle; } /** * @return mixed */ public function getTelephone() { return $this->telephone; } /** * @return mixed */ public function getMobile() { return $this->mobile; } /** * @return mixed */ public function getFaxNumber() { return $this->faxNumber; } /** * @return mixed */ public function getPicture() { return $this->picture; } }
mit
42wim/matterircd
config/config.go
595
package config import ( "fmt" "runtime" "strings" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) var Logger *logrus.Entry func LoadConfig(cfgfile string) (*viper.Viper, error) { v := viper.New() v.SetConfigFile(cfgfile) v.SetEnvPrefix("matterircd") v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) // use environment variables v.AutomaticEnv() if err := v.ReadInConfig(); err != nil { return nil, fmt.Errorf("error reading config file %s", err) } // reload config on file changes if runtime.GOOS != "illumos" { v.WatchConfig() } return v, nil }
mit
devacto/grobot
Godeps/_workspace/src/gopkg.in/olivere/elastic.v2/index.go
4547
// Copyright 2012-2015 Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "encoding/json" "fmt" "net/url" "github.com/devacto/grobot/Godeps/_workspace/src/gopkg.in/olivere/elastic.v2/uritemplates" ) // IndexResult is the result of indexing a document in Elasticsearch. type IndexResult struct { Index string `json:"_index"` Type string `json:"_type"` Id string `json:"_id"` Version int `json:"_version"` Created bool `json:"created"` } // IndexService adds documents to Elasticsearch. type IndexService struct { client *Client index string _type string id string routing string parent string opType string refresh *bool version *int64 versionType string timestamp string ttl string timeout string bodyString string bodyJson interface{} pretty bool } func NewIndexService(client *Client) *IndexService { builder := &IndexService{ client: client, } return builder } func (b *IndexService) Index(name string) *IndexService { b.index = name return b } func (b *IndexService) Type(_type string) *IndexService { b._type = _type return b } func (b *IndexService) Id(id string) *IndexService { b.id = id return b } func (b *IndexService) Routing(routing string) *IndexService { b.routing = routing return b } func (b *IndexService) Parent(parent string) *IndexService { b.parent = parent return b } // OpType is either "create" or "index" (the default). func (b *IndexService) OpType(opType string) *IndexService { b.opType = opType return b } func (b *IndexService) Refresh(refresh bool) *IndexService { b.refresh = &refresh return b } func (b *IndexService) Version(version int64) *IndexService { b.version = &version return b } // VersionType is either "internal" (default), "external", // "external_gt", "external_gte", or "force". // See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html#_version_types // for details. func (b *IndexService) VersionType(versionType string) *IndexService { b.versionType = versionType return b } func (b *IndexService) Timestamp(timestamp string) *IndexService { b.timestamp = timestamp return b } func (b *IndexService) TTL(ttl string) *IndexService { b.ttl = ttl return b } func (b *IndexService) Timeout(timeout string) *IndexService { b.timeout = timeout return b } func (b *IndexService) BodyString(body string) *IndexService { b.bodyString = body return b } func (b *IndexService) BodyJson(json interface{}) *IndexService { b.bodyJson = json return b } func (b *IndexService) Pretty(pretty bool) *IndexService { b.pretty = pretty return b } func (b *IndexService) Do() (*IndexResult, error) { // Build url var path, method string if b.id != "" { // Create document with manual id method = "PUT" path = "/{index}/{type}/{id}" } else { // Automatic ID generation // See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation method = "POST" path = "/{index}/{type}/" } path, err := uritemplates.Expand(path, map[string]string{ "index": b.index, "type": b._type, "id": b.id, }) if err != nil { return nil, err } // Parameters params := make(url.Values) if b.pretty { params.Set("pretty", "true") } if b.routing != "" { params.Set("routing", b.routing) } if b.parent != "" { params.Set("parent", b.parent) } if b.opType != "" { params.Set("op_type", b.opType) } if b.refresh != nil && *b.refresh { params.Set("refresh", "true") } if b.version != nil { params.Set("version", fmt.Sprintf("%d", *b.version)) } if b.versionType != "" { params.Set("version_type", b.versionType) } if b.timestamp != "" { params.Set("timestamp", b.timestamp) } if b.ttl != "" { params.Set("ttl", b.ttl) } if b.timeout != "" { params.Set("timeout", b.timeout) } /* routing string parent string opType string refresh *bool version *int64 versionType string timestamp string ttl string */ // Body var body interface{} if b.bodyJson != nil { body = b.bodyJson } else { body = b.bodyString } // Get response res, err := b.client.PerformRequest(method, path, params, body) if err != nil { return nil, err } // Return result ret := new(IndexResult) if err := json.Unmarshal(res.Body, ret); err != nil { return nil, err } return ret, nil }
mit
fran93/TresEnRayas
routes/bot.js
2241
//Router const express = require('express'); const router = express.Router(); exports.router = router; const Game = require('../models/game'); //sesiones const usersRouter = require('./users'); //Solo se le manda al usuario la vista del tablero, el resto se hace con socket.io router.get('/', usersRouter.ensureAuthenticated, function(req, res, next) { res.render('bot', { title: 'Tablero bot', user: req.user }); }); module.exports.socketio = function(io) { var games = {}; //namespace var nsp = io.of('/bot'); //Si se desconecta un usuario que se acabe la partida nsp.on('connection', function(socket){ //El cliente nos manda la posición a la que ha movido socket.on('next', function(json){ var state = games[socket.request.user].next(json.position, json.symbol); if(state==='next'){ //le mandamos la posición que a la que el bot ha movido socket.emit('next', games[socket.request.user].bot()); //comprobamos si ha ganado o no state = games[socket.request.user].nextBot(); }else{ //borrar el juego delete games[socket.request.user]; } //comprobar el tipo de final if(state!=='next'){ if(state==='o'){ socket.emit('end', 'o'); }else if(state==='x'){ socket.emit('end', 'x'); }else if(state==='tables'){ socket.emit('end', 'tables'); } } }); //Cuando el usuario quiere empezar un nuevo juego, creamos el objeto juego y lo guardamos en un hashmap, con el nombre de usuario como key socket.on('newGame', function(){ if(socket.request.user in games){ delete games[socket.request.user]; } games[socket.request.user] = new Game(socket.request.user); }); //Si el usuario se desconecta sin terminar la partida, borramos el juego socket.on('disconnect', function(){ if(socket.request.user in games) delete games[socket.request.user]; }); }); };
mit
justcarakas/forkcms
src/Modules/MediaGalleries/Domain/MediaGallery/StatusDBALType.php
316
<?php namespace ForkCMS\Modules\MediaGalleries\Domain\MediaGallery; use ForkCMS\Core\Domain\Doctrine\ValueObjectDBALType; use Stringable; final class StatusDBALType extends ValueObjectDBALType { protected function fromString(string $value): Stringable { return Status::fromString($value); } }
mit
mtils/xtype
src/XType/Casting/Contracts/TypeProvider.php
383
<?php namespace XType\Casting\Contracts; /** * A TypeProvider is a central place to store the types **/ interface TypeProvider { /** * Returns an object describing the type of $attribute of $modelClass * * @param string $modelClass * @param string $attribute * @return \XType\AbstractType **/ public function type($modelClass, $attribute); }
mit
fondbot/framework
tests/Unit/Templates/Keyboard/UrlButtonTest.php
658
<?php declare(strict_types=1); namespace FondBot\Tests\Unit\Templates\Keyboard; use FondBot\Tests\TestCase; use FondBot\Templates\Keyboard\UrlButton; class UrlButtonTest extends TestCase { public function test() { $label = $this->faker()->word; $url = $this->faker()->url; $parameters = ['foo' => 'bar']; $button = UrlButton::make($label, $url, $parameters); $this->assertSame('UrlButton', $button->getName()); $this->assertSame($label, $button->getLabel()); $this->assertSame($url, $button->getUrl()); $this->assertEquals(collect($parameters), $button->getParameters()); } }
mit
dbrugne/ftp-nanny
webpack.init.js
160
const host = window.location.host.split(':')[0]; __webpack_public_path__ = `http://${host}:8080/`; __webpack_require__.p = __webpack_public_path__ + 'bundles/';
mit
siddhartham/mangoapps
e2e/app.e2e-spec.ts
309
import { MangoappsPage } from './app.po'; describe('mangoapps App', () => { let page: MangoappsPage; beforeEach(() => { page = new MangoappsPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); });
mit
MeTooThanks/Perceptron
PerceptronOrGate.java
4204
import java.io.*; public class PerceptronOrGate { public static void main(String[] args) { OutputPerceptron output = new OutputPerceptron(); InputPerceptron input1 = new InputPerceptron(output, null); InputPerceptron input2 = new InputPerceptron(output, input1.getInputPerceptrons()); InputPerceptron[] inputs = input2.getInputPerceptrons(); BiasPerceptron bias = new BiasPerceptron(output); AdjustWeights weightAdjust = new AdjustWeights(0.001); double[] input1WeightDataSet = new double[20001]; double[] input2WeightDataSet = new double[20001]; double[] biasWeightDataSet = new double[20001]; double result = 0; double activation = 0; for (int i = 0; i <= 20000; i++) { double chance = Math.random(); if (chance < 0.25) { input1WeightDataSet[i] = input1.getWeight(); input2WeightDataSet[i] = input2.getWeight(); biasWeightDataSet[i] = bias.getWeight(); input1.send(0); input2.send(0); bias.send(); result = output.activate(); activation = output.getInput(); System.out.println("Iteration: " +i); System.out.println("Input Node 1: 0 \nInput Node 2: 0 \nOutput: " +result); System.out.println("Weight Node 1: " +input1.getWeight() +"\nWeight Node 2: " +input2.getWeight() +"\nWeight Bias: " +bias.getWeight() +"\n"); weightAdjust.learn(inputs, bias, result, 0); output.reset(); } else if (chance < 0.5 && chance >= 0.25) { input1WeightDataSet[i] = input1.getWeight(); input2WeightDataSet[i] = input2.getWeight(); biasWeightDataSet[i] = bias.getWeight(); input1.send(0); input2.send(1); bias.send(); result = output.activate(); activation = output.getInput(); System.out.println("Iteration: " +i); System.out.println("Input Node 1: 0 \nInput Node 2: 1 \nOutput: " +result); System.out.println("Weight Node 1: " +input1.getWeight() +"\nWeight Node 2: " +input2.getWeight() +"\nWeight Bias: " +bias.getWeight() +"\n"); weightAdjust.learn(inputs, bias, result, 1); output.reset(); } else if (chance < 0.75 && chance >= 0.5) { input1WeightDataSet[i] = input1.getWeight(); input2WeightDataSet[i] = input2.getWeight(); biasWeightDataSet[i] = bias.getWeight(); input1.send(1); input2.send(0); bias.send(); result = output.activate(); activation = output.getInput(); System.out.println("Iteration: " +i); System.out.println("Input Node 1: 1 \nInput Node 2: 0 \nOutput: " +result); System.out.println("Weight Node 1: " +input1.getWeight() +"\nWeight Node 2: " +input2.getWeight() +"\nWeight Bias: " +bias.getWeight() +"\n"); weightAdjust.learn(inputs, bias, result, 1); output.reset(); } else if (chance >= 0.75) { input1WeightDataSet[i] = input1.getWeight(); input2WeightDataSet[i] = input2.getWeight(); biasWeightDataSet[i] = bias.getWeight(); input1.send(1); input2.send(1); bias.send(); result = output.activate(); activation = output.getInput(); System.out.println("Iteration: " +i); System.out.println("Input Node 1: 1 \nInput Node 2: 1 \nOutput: " +result); System.out.println("Weight Node 1: " +input1.getWeight() +"\nWeight Node 2: " +input2.getWeight() +"\nWeight Bias: " +bias.getWeight() +"\n"); weightAdjust.learn(inputs, bias, result, 1); output.reset(); } } write("input1_weights.dat", input1WeightDataSet); write("input2_weights.dat", input2WeightDataSet); write("bias_weights.dat", biasWeightDataSet); } public static void write (String fileName, double[] x){ try { File file = new File(fileName); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < x.length; i++) { bw.write(String.valueOf(x[i])); bw.write(" "); } bw.flush(); bw.close(); System.out.println("Done writing " +fileName); } catch (IOException e) { e.printStackTrace(); } } }
mit
weshaggard/corefxlab
src/System.Text.Formatting/GenerateCompatibilityTests/Program.cs
7494
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; class Program { static Random random = new Random(1000); static void Main(string[] args) { GenerateNumericTypesTests(); GenerateTimeSpanTests(); } private static void GenerateTimeSpanTests() { var file = new StreamWriter(@"..\..\..\tests\TimeSpanFormattingTests.Generated.cs"); var writer = new CodeWriter(file); GenerateFileHeader(writer); GenerateCheck(writer, "TimeSpan"); GenerateTest(writer, "TimeSpan", 'G'); //GenerateTest(writer, "TimeSpan", 'g'); GenerateTest(writer, "TimeSpan", 'c'); GenerateFileFooter(file, writer); } private static void GenerateNumericTypesTests() { var file = new StreamWriter(@"..\..\..\tests\NumberFormattingTests.Generated.cs"); var writer = new CodeWriter(file); GenerateFileHeader(writer); GenerateNumericTypeTests(writer, "Byte", 5); GenerateNumericTypeTests(writer, "SByte", 5); GenerateNumericTypeTests(writer, "UInt16", 5); GenerateNumericTypeTests(writer, "Int16", 5); GenerateNumericTypeTests(writer, "UInt32", 5); GenerateNumericTypeTests(writer, "Int32", 5); GenerateNumericTypeTests(writer, "UInt64", 5); GenerateNumericTypeTests(writer, "Int64", 5); GenerateFileFooter(file, writer); } // TODO: all of the formats should work private static void GenerateNumericTypeTests(CodeWriter writer, string typeName, int maxPrecision = -1) { GenerateCheck(writer, typeName); //GenerateTest(writer, typeName, 'C', maxPrecision); GenerateTest(writer, typeName, 'D', maxPrecision); GenerateTest(writer, typeName, 'd', maxPrecision); //GenerateTest(writer, typeName, 'E', maxPrecision); //GenerateTest(writer, typeName, 'F', maxPrecision); GenerateTest(writer, typeName, 'G'); //GenerateTest(writer, typeName, 'g', maxPrecision); GenerateTest(writer, typeName, 'N', maxPrecision); //GenerateTest(writer, typeName, 'P', maxPrecision); //GenerateTest(writer, typeName, 'R', maxPrecision); GenerateTest(writer, typeName, 'X', maxPrecision); GenerateTest(writer, typeName, 'x', maxPrecision); } private static void GenerateCheck(CodeWriter writer, string typeName) { var helperName = "Check" + typeName; writer.WriteLine("public void {0}({1} value, string format)", helperName, typeName); writer.WriteLine("{"); writer.WriteLine(" var parsed = Format.Parse(format);"); writer.WriteLine(" var formatter = new StringFormatter();"); writer.WriteLine(" formatter.Append(value, parsed);"); writer.WriteLine(" var result = formatter.ToString();"); writer.WriteLine(" var clrResult = value.ToString(format, CultureInfo.InvariantCulture);"); writer.WriteLine(" Assert.Equal(clrResult, result);"); writer.WriteLine("}"); writer.WriteLine(""); } private static void GenerateTest(CodeWriter writer, string typeName, char format, int maxPrecision = -1) { writer.WriteLine("[Fact]"); var testName = typeName + "Format" + format; writer.WriteLine("public void {0}()", testName); writer.WriteLine("{"); writer.Indent++; var helperName = "Check" + typeName; GenerateSpecificFormatTests(writer, typeName, format.ToString(), helperName); if (maxPrecision > -1) { for (int precision = 0; precision <= maxPrecision; precision++) { GenerateSpecificFormatTests(writer, typeName, format.ToString() + precision.ToString(), helperName); } } writer.Indent--; writer.WriteLine("}"); writer.WriteLine(""); } private static void GenerateSpecificFormatTests(CodeWriter writer, string typeName, string format, string checkMethodName) { writer.WriteLine(""); writer.WriteLine("// format {0}", format); foreach (var testValue in GetTestValues(typeName)) { writer.WriteLine("{0}({1}, \"{2}\");", checkMethodName, testValue, format); } } private static IEnumerable<string> GetTestValues(string typeName) { int min = 0; int max = int.MaxValue; switch (typeName) { case "UInt32": case "UInt64": break; case "TimeSpan": case "Int32": case "Int64": min = int.MinValue; break; case "UInt16": max = ushort.MaxValue; break; case "Byte": max = byte.MaxValue; break; case "Int16": min = short.MinValue; max = short.MaxValue; break; case "SByte": min = sbyte.MinValue; max = sbyte.MaxValue; break; default: throw new NotImplementedException(); } yield return typeName + ".MinValue"; yield return typeName + ".MaxValue"; if (typeName != "TimeSpan") { yield return "0"; } if (typeName == "TimeSpan") { for (int test = 3; test <= 20; test++) { yield return String.Format("new {0}({1})", typeName, random.Next(min, max)); } } else { for (int test = 4; test <= 8; test++) { yield return random.Next(min, max).ToString(); } } } private static void GenerateFileHeader(CodeWriter writer) { writer.WriteLine("// Copyright (c) Microsoft. All rights reserved."); writer.WriteLine("// Licensed under the MIT license. See LICENSE file in the project root for full license information."); writer.WriteLine(""); writer.WriteLine("// THIS FILE IS AUTOGENERATED"); writer.WriteLine(""); writer.WriteLine("using System;"); writer.WriteLine("using System.Globalization;"); writer.WriteLine("using Xunit;"); writer.WriteLine(""); writer.WriteLine("namespace System.Text.Formatting.Tests"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("public partial class SystemTextFormattingTests"); writer.WriteLine("{"); writer.Indent++; } private static void GenerateFileFooter(StreamWriter file, CodeWriter writer) { writer.Indent--; writer.WriteLine("}"); // end of test type writer.Indent--; writer.WriteLine("}"); // namesapce file.Close(); } class CodeWriter { TextWriter _writer; public int Indent = 0; public CodeWriter(TextWriter writer) { _writer = writer; } internal void WriteLine(string text) { _writer.Write(new String(' ', Indent * 4)); _writer.WriteLine(text); } internal void WriteLine(string format, params object[] args) { WriteLine(String.Format(format, args)); } } }
mit
FubarDevelopment/FtpServer
samples/TestFtpServer.Shell/Commands/ExitCommandHandler.cs
1396
// <copyright file="ExitCommandHandler.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TestFtpServer.Shell.Commands { /// <summary> /// The <c>EXIT</c> command. /// </summary> public class ExitCommandHandler : IRootCommandInfo, IExecutableCommandInfo { private readonly IShellStatus _status; /// <summary> /// Initializes a new instance of the <see cref="ExitCommandHandler"/> class. /// </summary> /// <param name="status">The shell status.</param> public ExitCommandHandler( IShellStatus status) { _status = status; } /// <inheritdoc /> public string Name { get; } = "exit"; /// <inheritdoc /> public IReadOnlyCollection<string> AlternativeNames { get; } = new[] { "quit" }; /// <inheritdoc /> public IAsyncEnumerable<ICommandInfo> GetSubCommandsAsync(CancellationToken cancellationToken) => AsyncEnumerable.Empty<ICommandInfo>(); /// <inheritdoc /> public Task ExecuteAsync(CancellationToken cancellationToken) { _status.Closed = true; return Task.CompletedTask; } } }
mit
adrianbu/renderdoc
renderdoc/replay/replay_output.cpp
24153
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2016 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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/common.h" #include "maths/matrix.h" #include "serialise/string_utils.h" #include "replay_renderer.h" static uint64_t GetHandle(WindowingSystem system, void *data) { #if defined(RENDERDOC_PLATFORM_LINUX) if(system == eWindowingSystem_Xlib) { #if defined(RENDERDOC_WINDOWING_XLIB) return (uint64_t)((XlibWindowData *)data)->window; #else RDCERR("Xlib windowing system data passed in, but support is not compiled in"); #endif } if(system == eWindowingSystem_XCB) { #if defined(RENDERDOC_WINDOWING_XCB) return (uint64_t)((XCBWindowData *)data)->window; #else RDCERR("XCB windowing system data passed in, but support is not compiled in"); #endif } RDCERR("Unrecognised window system %d", system); return 0; #elif defined(RENDERDOC_PLATFORM_WIN32) RDCASSERT(system == eWindowingSystem_Win32); return (uint64_t)data; // HWND #elif defined(RENDERDOC_PLATFORM_ANDROID) RDCASSERT(system == eWindowingSystem_Android); return (uint64_t)data; // ANativeWindow * #else RDCFATAL("No windowing data defined for this platform! Must be implemented for replay outputs"); #endif } ReplayOutput::ReplayOutput(ReplayRenderer *parent, WindowingSystem system, void *data, OutputType type) { m_pRenderer = parent; m_MainOutput.dirty = true; m_OverlayDirty = true; m_ForceOverlayRefresh = false; m_pDevice = parent->GetDevice(); m_EventID = parent->m_EventID; m_OverlayResourceId = ResourceId(); RDCEraseEl(m_RenderData); m_PixelContext.outputID = 0; m_PixelContext.texture = ResourceId(); m_PixelContext.depthMode = false; m_ContextX = -1.0f; m_ContextY = -1.0f; m_Config.m_Type = type; if(system != eWindowingSystem_Unknown) m_MainOutput.outputID = m_pDevice->MakeOutputWindow(system, data, type == eOutputType_MeshDisplay); else m_MainOutput.outputID = 0; m_MainOutput.texture = ResourceId(); m_pDevice->GetOutputWindowDimensions(m_MainOutput.outputID, m_Width, m_Height); m_CustomShaderResourceId = ResourceId(); } ReplayOutput::~ReplayOutput() { m_pDevice->DestroyOutputWindow(m_MainOutput.outputID); m_pDevice->DestroyOutputWindow(m_PixelContext.outputID); m_CustomShaderResourceId = ResourceId(); ClearThumbnails(); } bool ReplayOutput::SetOutputConfig(const OutputConfig &o) { m_OverlayDirty = true; m_Config = o; m_MainOutput.dirty = true; return true; } bool ReplayOutput::SetTextureDisplay(const TextureDisplay &o) { if(o.overlay != m_RenderData.texDisplay.overlay) { if(m_RenderData.texDisplay.overlay == eTexOverlay_ClearBeforeDraw || m_RenderData.texDisplay.overlay == eTexOverlay_ClearBeforePass) { // by necessity these overlays modify the actual texture, not an // independent overlay texture. So if we disable them, we must // refresh the log. m_ForceOverlayRefresh = true; } m_OverlayDirty = true; } m_RenderData.texDisplay = o; m_MainOutput.dirty = true; return true; } bool ReplayOutput::SetMeshDisplay(const MeshDisplay &o) { if(o.showWholePass != m_RenderData.meshDisplay.showWholePass) m_OverlayDirty = true; m_RenderData.meshDisplay = o; m_MainOutput.dirty = true; return true; } void ReplayOutput::SetFrameEvent(int eventID) { m_EventID = eventID; m_OverlayDirty = true; m_MainOutput.dirty = true; for(size_t i = 0; i < m_Thumbnails.size(); i++) m_Thumbnails[i].dirty = true; RefreshOverlay(); } void ReplayOutput::RefreshOverlay() { FetchDrawcall *draw = m_pRenderer->GetDrawcallByEID(m_EventID); passEvents = m_pDevice->GetPassEvents(m_EventID); if(m_Config.m_Type == eOutputType_TexDisplay && m_RenderData.texDisplay.overlay != eTexOverlay_None) { if(draw && m_pDevice->IsRenderOutput(m_RenderData.texDisplay.texid)) { m_OverlayResourceId = m_pDevice->RenderOverlay( m_pDevice->GetLiveID(m_RenderData.texDisplay.texid), m_RenderData.texDisplay.typeHint, m_RenderData.texDisplay.overlay, m_EventID, passEvents); m_OverlayDirty = false; } } if(m_Config.m_Type == eOutputType_MeshDisplay && m_OverlayDirty) { m_OverlayDirty = false; if(draw == NULL || (draw->flags & eDraw_Drawcall) == 0) return; m_pDevice->InitPostVSBuffers(draw->eventID); if(m_RenderData.meshDisplay.showWholePass && !passEvents.empty()) { m_pDevice->InitPostVSBuffers(passEvents); m_pDevice->ReplayLog(m_EventID, eReplay_WithoutDraw); } } } bool ReplayOutput::ClearThumbnails() { for(size_t i = 0; i < m_Thumbnails.size(); i++) m_pDevice->DestroyOutputWindow(m_Thumbnails[i].outputID); m_Thumbnails.clear(); return true; } bool ReplayOutput::SetPixelContext(WindowingSystem system, void *data) { m_PixelContext.outputID = m_pDevice->MakeOutputWindow(system, data, false); m_PixelContext.texture = ResourceId(); m_PixelContext.depthMode = false; RDCASSERT(m_PixelContext.outputID > 0); return true; } bool ReplayOutput::AddThumbnail(WindowingSystem system, void *data, ResourceId texID, FormatComponentType typeHint) { OutputPair p; RDCASSERT(data); bool depthMode = false; for(size_t t = 0; t < m_pRenderer->m_Textures.size(); t++) { if(m_pRenderer->m_Textures[t].ID == texID) { depthMode = (m_pRenderer->m_Textures[t].creationFlags & eTextureCreate_DSV) > 0; depthMode |= (m_pRenderer->m_Textures[t].format.compType == eCompType_Depth); break; } } for(size_t i = 0; i < m_Thumbnails.size(); i++) { if(m_Thumbnails[i].wndHandle == GetHandle(system, data)) { m_Thumbnails[i].texture = texID; m_Thumbnails[i].depthMode = depthMode; m_Thumbnails[i].typeHint = typeHint; m_Thumbnails[i].dirty = true; return true; } } p.wndHandle = GetHandle(system, data); p.outputID = m_pDevice->MakeOutputWindow(system, data, false); p.texture = texID; p.depthMode = depthMode; p.typeHint = typeHint; p.dirty = true; RDCASSERT(p.outputID > 0); m_Thumbnails.push_back(p); return true; } bool ReplayOutput::PickPixel(ResourceId tex, bool customShader, uint32_t x, uint32_t y, uint32_t sliceFace, uint32_t mip, uint32_t sample, PixelValue *ret) { if(ret == NULL || tex == ResourceId()) return false; RDCEraseEl(ret->value_f); bool decodeRamp = false; FormatComponentType typeHint = m_RenderData.texDisplay.typeHint; if(customShader && m_RenderData.texDisplay.CustomShader != ResourceId() && m_CustomShaderResourceId != ResourceId()) { tex = m_CustomShaderResourceId; typeHint = eCompType_None; } if((m_RenderData.texDisplay.overlay == eTexOverlay_QuadOverdrawDraw || m_RenderData.texDisplay.overlay == eTexOverlay_QuadOverdrawPass) && m_OverlayResourceId != ResourceId()) { decodeRamp = true; tex = m_OverlayResourceId; typeHint = eCompType_None; } m_pDevice->PickPixel(m_pDevice->GetLiveID(tex), x, y, sliceFace, mip, sample, typeHint, ret->value_f); if(decodeRamp) { for(size_t c = 0; c < ARRAY_COUNT(overdrawRamp); c++) { if(fabs(ret->value_f[0] - overdrawRamp[c].x) < 0.00005f && fabs(ret->value_f[1] - overdrawRamp[c].y) < 0.00005f && fabs(ret->value_f[2] - overdrawRamp[c].z) < 0.00005f) { ret->value_i[0] = (int32_t)c; ret->value_i[1] = 0; ret->value_i[2] = 0; ret->value_i[3] = 0; break; } } } return true; } uint32_t ReplayOutput::PickVertex(uint32_t eventID, uint32_t x, uint32_t y) { FetchDrawcall *draw = m_pRenderer->GetDrawcallByEID(eventID); if(!draw) return ~0U; if(m_RenderData.meshDisplay.type == eMeshDataStage_Unknown) return ~0U; if((draw->flags & eDraw_Drawcall) == 0) return ~0U; MeshDisplay cfg = m_RenderData.meshDisplay; if(cfg.position.buf == ResourceId()) return ~0U; cfg.position.buf = m_pDevice->GetLiveID(cfg.position.buf); cfg.position.idxbuf = m_pDevice->GetLiveID(cfg.position.idxbuf); cfg.second.buf = m_pDevice->GetLiveID(cfg.second.buf); cfg.second.idxbuf = m_pDevice->GetLiveID(cfg.second.idxbuf); return m_pDevice->PickVertex(m_EventID, cfg, x, y); } bool ReplayOutput::SetPixelContextLocation(uint32_t x, uint32_t y) { m_ContextX = RDCMAX((float)x, 0.0f); m_ContextY = RDCMAX((float)y, 0.0f); DisplayContext(); return true; } void ReplayOutput::DisablePixelContext() { m_ContextX = -1.0f; m_ContextY = -1.0f; DisplayContext(); } void ReplayOutput::DisplayContext() { if(m_PixelContext.outputID == 0) return; float color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; m_pDevice->BindOutputWindow(m_PixelContext.outputID, false); if((m_Config.m_Type != eOutputType_TexDisplay) || (m_ContextX < 0.0f && m_ContextY < 0.0f) || (m_RenderData.texDisplay.texid == ResourceId())) { m_pDevice->RenderCheckerboard(Vec3f(0.81f, 0.81f, 0.81f), Vec3f(0.57f, 0.57f, 0.57f)); m_pDevice->FlipOutputWindow(m_PixelContext.outputID); return; } m_pDevice->ClearOutputWindowColour(m_PixelContext.outputID, color); TextureDisplay disp = m_RenderData.texDisplay; disp.rawoutput = false; disp.CustomShader = ResourceId(); if(m_RenderData.texDisplay.CustomShader != ResourceId()) disp.texid = m_CustomShaderResourceId; if((m_RenderData.texDisplay.overlay == eTexOverlay_QuadOverdrawDraw || m_RenderData.texDisplay.overlay == eTexOverlay_QuadOverdrawPass) && m_OverlayResourceId != ResourceId()) disp.texid = m_OverlayResourceId; const float contextZoom = 8.0f; disp.scale = contextZoom / float(1 << disp.mip); int32_t width = 0, height = 0; m_pDevice->GetOutputWindowDimensions(m_PixelContext.outputID, width, height); float w = (float)width; float h = (float)height; int x = (int)m_ContextX; int y = (int)m_ContextY; x >>= disp.mip; x <<= disp.mip; y >>= disp.mip; y <<= disp.mip; disp.offx = -(float)x * disp.scale; disp.offy = -(float)y * disp.scale; disp.offx += w / 2.0f; disp.offy += h / 2.0f; disp.texid = m_pDevice->GetLiveID(disp.texid); m_pDevice->RenderTexture(disp); m_pDevice->RenderHighlightBox(w, h, contextZoom); m_pDevice->FlipOutputWindow(m_PixelContext.outputID); } bool ReplayOutput::Display() { if(m_pDevice->CheckResizeOutputWindow(m_MainOutput.outputID)) { m_pDevice->GetOutputWindowDimensions(m_MainOutput.outputID, m_Width, m_Height); m_MainOutput.dirty = true; } for(size_t i = 0; i < m_Thumbnails.size(); i++) if(m_pDevice->CheckResizeOutputWindow(m_Thumbnails[i].outputID)) m_Thumbnails[i].dirty = true; for(size_t i = 0; i < m_Thumbnails.size(); i++) { if(!m_Thumbnails[i].dirty) { m_pDevice->BindOutputWindow(m_Thumbnails[i].outputID, false); m_pDevice->FlipOutputWindow(m_Thumbnails[i].outputID); continue; } if(!m_pDevice->IsOutputWindowVisible(m_Thumbnails[i].outputID)) continue; float color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; if(m_Thumbnails[i].texture == ResourceId()) { m_pDevice->BindOutputWindow(m_Thumbnails[i].outputID, false); color[0] = 0.4f; m_pDevice->ClearOutputWindowColour(m_Thumbnails[i].outputID, color); m_pDevice->RenderCheckerboard(Vec3f(0.6f, 0.6f, 0.7f), Vec3f(0.5f, 0.5f, 0.6f)); m_pDevice->FlipOutputWindow(m_Thumbnails[i].outputID); continue; } m_pDevice->BindOutputWindow(m_Thumbnails[i].outputID, false); m_pDevice->ClearOutputWindowColour(m_Thumbnails[i].outputID, color); TextureDisplay disp; disp.Red = disp.Green = disp.Blue = true; disp.Alpha = false; disp.HDRMul = -1.0f; disp.linearDisplayAsGamma = true; disp.FlipY = false; disp.mip = 0; disp.sampleIdx = ~0U; disp.CustomShader = ResourceId(); disp.texid = m_pDevice->GetLiveID(m_Thumbnails[i].texture); disp.typeHint = m_Thumbnails[i].typeHint; disp.scale = -1.0f; disp.rangemin = 0.0f; disp.rangemax = 1.0f; disp.sliceFace = 0; disp.offx = 0.0f; disp.offy = 0.0f; disp.rawoutput = false; disp.overlay = eTexOverlay_None; disp.lightBackgroundColour = disp.darkBackgroundColour = FloatVector(); if(m_Thumbnails[i].typeHint == eCompType_SNorm) disp.rangemin = -1.0f; if(m_Thumbnails[i].depthMode) disp.Green = disp.Blue = false; m_pDevice->RenderTexture(disp); m_pDevice->FlipOutputWindow(m_Thumbnails[i].outputID); m_Thumbnails[i].dirty = false; } if(m_pDevice->CheckResizeOutputWindow(m_PixelContext.outputID)) m_MainOutput.dirty = true; if(!m_MainOutput.dirty) { m_pDevice->BindOutputWindow(m_MainOutput.outputID, false); m_pDevice->FlipOutputWindow(m_MainOutput.outputID); m_pDevice->BindOutputWindow(m_PixelContext.outputID, false); m_pDevice->FlipOutputWindow(m_PixelContext.outputID); return true; } m_MainOutput.dirty = false; switch(m_Config.m_Type) { case eOutputType_MeshDisplay: DisplayMesh(); break; case eOutputType_TexDisplay: DisplayTex(); break; default: RDCERR("Unexpected display type! %d", m_Config.m_Type); break; } m_pDevice->FlipOutputWindow(m_MainOutput.outputID); DisplayContext(); return true; } void ReplayOutput::DisplayTex() { FetchDrawcall *draw = m_pRenderer->GetDrawcallByEID(m_EventID); if(m_MainOutput.outputID == 0) return; if(m_RenderData.texDisplay.texid == ResourceId()) { float color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; m_pDevice->BindOutputWindow(m_MainOutput.outputID, false); m_pDevice->ClearOutputWindowColour(m_MainOutput.outputID, color); return; } if(m_Width <= 0 || m_Height <= 0) return; TextureDisplay texDisplay = m_RenderData.texDisplay; texDisplay.rawoutput = false; texDisplay.texid = m_pDevice->GetLiveID(texDisplay.texid); if(m_RenderData.texDisplay.overlay != eTexOverlay_None && draw) { if(m_OverlayDirty) { m_pDevice->ReplayLog(m_EventID, eReplay_WithoutDraw); RefreshOverlay(); m_pDevice->ReplayLog(m_EventID, eReplay_OnlyDraw); } } else if(m_ForceOverlayRefresh) { m_ForceOverlayRefresh = false; m_pDevice->ReplayLog(m_EventID, eReplay_Full); } if(m_RenderData.texDisplay.CustomShader != ResourceId()) { m_CustomShaderResourceId = m_pDevice->ApplyCustomShader( m_RenderData.texDisplay.CustomShader, texDisplay.texid, texDisplay.mip, texDisplay.sliceFace, texDisplay.sampleIdx, texDisplay.typeHint); texDisplay.texid = m_pDevice->GetLiveID(m_CustomShaderResourceId); texDisplay.typeHint = eCompType_None; texDisplay.CustomShader = ResourceId(); texDisplay.sliceFace = 0; } float color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; m_pDevice->BindOutputWindow(m_MainOutput.outputID, false); m_pDevice->ClearOutputWindowColour(m_MainOutput.outputID, color); m_pDevice->RenderCheckerboard( Vec3f(texDisplay.lightBackgroundColour.x, texDisplay.lightBackgroundColour.y, texDisplay.lightBackgroundColour.z), Vec3f(texDisplay.darkBackgroundColour.x, texDisplay.darkBackgroundColour.y, texDisplay.darkBackgroundColour.z)); m_pDevice->RenderTexture(texDisplay); if(m_RenderData.texDisplay.overlay != eTexOverlay_None && draw && m_pDevice->IsRenderOutput(m_RenderData.texDisplay.texid) && m_RenderData.texDisplay.overlay != eTexOverlay_NaN && m_RenderData.texDisplay.overlay != eTexOverlay_Clipping) { RDCASSERT(m_OverlayResourceId != ResourceId()); texDisplay.texid = m_pDevice->GetLiveID(m_OverlayResourceId); texDisplay.Red = texDisplay.Green = texDisplay.Blue = texDisplay.Alpha = true; texDisplay.rawoutput = false; texDisplay.CustomShader = ResourceId(); texDisplay.scale = m_RenderData.texDisplay.scale; texDisplay.HDRMul = -1.0f; texDisplay.FlipY = m_RenderData.texDisplay.FlipY; texDisplay.rangemin = 0.0f; texDisplay.rangemax = 1.0f; m_pDevice->RenderTexture(texDisplay); } } void ReplayOutput::DisplayMesh() { FetchDrawcall *draw = m_pRenderer->GetDrawcallByEID(m_EventID); if(draw == NULL || m_MainOutput.outputID == 0 || m_Width <= 0 || m_Height <= 0 || (m_RenderData.meshDisplay.type == eMeshDataStage_Unknown) || (draw->flags & eDraw_Drawcall) == 0) { float color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; m_pDevice->BindOutputWindow(m_MainOutput.outputID, false); m_pDevice->ClearOutputWindowColour(m_MainOutput.outputID, color); m_pDevice->ClearOutputWindowDepth(m_MainOutput.outputID, 1.0f, 0); m_pDevice->RenderCheckerboard(Vec3f(0.81f, 0.81f, 0.81f), Vec3f(0.57f, 0.57f, 0.57f)); return; } if(draw && m_OverlayDirty) { m_pDevice->ReplayLog(m_EventID, eReplay_WithoutDraw); RefreshOverlay(); m_pDevice->ReplayLog(m_EventID, eReplay_OnlyDraw); } m_pDevice->BindOutputWindow(m_MainOutput.outputID, true); m_pDevice->ClearOutputWindowDepth(m_MainOutput.outputID, 1.0f, 0); m_pDevice->RenderCheckerboard(Vec3f(0.81f, 0.81f, 0.81f), Vec3f(0.57f, 0.57f, 0.57f)); m_pDevice->ClearOutputWindowDepth(m_MainOutput.outputID, 1.0f, 0); MeshDisplay mesh = m_RenderData.meshDisplay; mesh.position.buf = m_pDevice->GetLiveID(mesh.position.buf); mesh.position.idxbuf = m_pDevice->GetLiveID(mesh.position.idxbuf); mesh.second.buf = m_pDevice->GetLiveID(mesh.second.buf); mesh.second.idxbuf = m_pDevice->GetLiveID(mesh.second.idxbuf); vector<MeshFormat> secondaryDraws; // we choose a pallette here so that the colours stay consistent (i.e the // current draw is always the same colour), but also to indicate somewhat // the relationship - ie. instances are closer in colour than other draws // in the pass // very slightly dark red const FloatVector drawItself(0.06f, 0.0f, 0.0f, 1.0f); // more desaturated/lighter, but still reddish const FloatVector otherInstances(0.18f, 0.1f, 0.1f, 1.0f); // lighter grey with blue tinge to contrast from main/instance draws const FloatVector passDraws(0.2f, 0.2f, 0.25f, 1.0f); if(m_RenderData.meshDisplay.type != eMeshDataStage_VSIn) { for(size_t i = 0; m_RenderData.meshDisplay.showWholePass && i < passEvents.size(); i++) { FetchDrawcall *d = m_pRenderer->GetDrawcallByEID(passEvents[i]); if(d) { for(uint32_t inst = 0; inst < RDCMAX(1U, draw->numInstances); inst++) { // get the 'most final' stage MeshFormat fmt = m_pDevice->GetPostVSBuffers(passEvents[i], inst, eMeshDataStage_GSOut); if(fmt.buf == ResourceId()) fmt = m_pDevice->GetPostVSBuffers(passEvents[i], inst, eMeshDataStage_VSOut); fmt.meshColour = passDraws; // if unproject is marked, this output had a 'real' system position output if(fmt.unproject) secondaryDraws.push_back(fmt); } } } // draw previous instances in the current drawcall if(draw->flags & eDraw_Instanced) { uint32_t maxInst = 0; if(m_RenderData.meshDisplay.showPrevInstances) maxInst = RDCMAX(1U, m_RenderData.meshDisplay.curInstance); if(m_RenderData.meshDisplay.showAllInstances) maxInst = RDCMAX(1U, draw->numInstances); for(uint32_t inst = 0; inst < maxInst; inst++) { // get the 'most final' stage MeshFormat fmt = m_pDevice->GetPostVSBuffers(draw->eventID, inst, eMeshDataStage_GSOut); if(fmt.buf == ResourceId()) fmt = m_pDevice->GetPostVSBuffers(draw->eventID, inst, eMeshDataStage_VSOut); fmt.meshColour = otherInstances; // if unproject is marked, this output had a 'real' system position output if(fmt.unproject) secondaryDraws.push_back(fmt); } } } mesh.position.meshColour = drawItself; m_pDevice->RenderMesh(m_EventID, secondaryDraws, mesh); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_SetOutputConfig(ReplayOutput *output, const OutputConfig &o) { return output->SetOutputConfig(o); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_SetTextureDisplay(ReplayOutput *output, const TextureDisplay &o) { return output->SetTextureDisplay(o); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_SetMeshDisplay(ReplayOutput *output, const MeshDisplay &o) { return output->SetMeshDisplay(o); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_ClearThumbnails(ReplayOutput *output) { return output->ClearThumbnails(); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_AddThumbnail(ReplayOutput *output, WindowingSystem system, void *data, ResourceId texID, FormatComponentType typeHint) { return output->AddThumbnail(system, data, texID, typeHint); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_Display(ReplayOutput *output) { return output->Display(); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_SetPixelContext(ReplayOutput *output, WindowingSystem system, void *data) { return output->SetPixelContext(system, data); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_SetPixelContextLocation(ReplayOutput *output, uint32_t x, uint32_t y) { return output->SetPixelContextLocation(x, y); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayOutput_DisablePixelContext(ReplayOutput *output) { output->DisablePixelContext(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayOutput_GetCustomShaderTexID(ReplayOutput *output, ResourceId *id) { if(id) *id = output->GetCustomShaderTexID(); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayOutput_PickPixel( ReplayOutput *output, ResourceId texID, bool32 customShader, uint32_t x, uint32_t y, uint32_t sliceFace, uint32_t mip, uint32_t sample, PixelValue *val) { return output->PickPixel(texID, customShader != 0, x, y, sliceFace, mip, sample, val); } extern "C" RENDERDOC_API uint32_t RENDERDOC_CC ReplayOutput_PickVertex(ReplayOutput *output, uint32_t eventID, uint32_t x, uint32_t y) { return output->PickVertex(eventID, x, y); }
mit
wgertler/wgertler.github.io
MathJax-master/unpacked/localization/vi/MathML.js
3056
/************************************************************* * * MathJax/localization/vi/MathML.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("vi","MathML",{ version: "2.7.3", isLoaded: true, strings: { BadMglyph: "mglyph h\u1ECFng: %1", BadMglyphFont: "Ph\u00F4ng ch\u1EEF h\u1ECFng: %1", MathPlayer: "MathJax kh\u00F4ng th\u1EC3 thi\u1EBFt l\u1EADp MathPlayer.\n\nN\u1EBFu MathPlayer ch\u01B0a \u0111\u01B0\u1EE3c c\u00E0i \u0111\u1EB7t, b\u1EA1n c\u1EA7n ph\u1EA3i c\u00E0i \u0111\u1EB7t n\u00F3 tr\u01B0\u1EDBc ti\u00EAn.\nN\u1EBFu kh\u00F4ng, c\u00E1c t\u00F9y ch\u1ECDn b\u1EA3o m\u1EADt c\u1EE7a b\u1EA1n c\u00F3 th\u1EC3 ng\u0103n tr\u1EDF c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m c\u00E1c h\u1ED9p \u201CCh\u1EA1y \u0111i\u1EC1u khi\u1EC3n ActiveX\u201D v\u00E0 \u201CH\u00E0nh vi nh\u1ECB ph\u00E2n v\u00E0 k\u1ECBch b\u1EA3n\u201D.\n\nHi\u1EC7n t\u1EA1i b\u1EA1n s\u1EBD g\u1EB7p c\u00E1c th\u00F4ng b\u00E1o l\u1ED7i thay v\u00EC to\u00E1n h\u1ECDc \u0111\u01B0\u1EE3c k\u1EBFt xu\u1EA5t.", CantCreateXMLParser: "MathJax kh\u00F4ng th\u1EC3 t\u1EA1o ra b\u1ED9 ph\u00E2n t\u00EDch XML cho MathML. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m h\u1ED9p \u201CScript c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX \u0111\u01B0\u1EE3c \u0111\u00E1nh d\u1EA5u l\u00E0 an to\u00E0n\u201D.\n\nMathJax s\u1EBD kh\u00F4ng th\u1EC3 x\u1EED l\u00FD c\u00E1c ph\u01B0\u01A1ng tr\u00ECnh MathML.", UnknownNodeType: "Ki\u1EC3u n\u00FAt kh\u00F4ng r\u00F5: %1", UnexpectedTextNode: "N\u00FAt v\u0103n b\u1EA3n b\u1EA5t ng\u1EEB: %1", ErrorParsingMathML: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML", ParsingError: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML: %1", MathMLSingleElement: "MathML ph\u1EA3i ch\u1EC9 c\u00F3 m\u1ED9t ph\u1EA7n t\u1EED g\u1ED1c", MathMLRootElement: "Ph\u1EA7n t\u1EED g\u1ED1c c\u1EE7a MathML ph\u1EA3i l\u00E0 \u003Cmath\u003E, ch\u1EE9 kh\u00F4ng ph\u1EA3i %1" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathML.js");
mit
AILanguages/WebClients
PatTuring2016.MVC5Web/Models/ManageViewModels.cs
2667
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; namespace PatTuring2016.MVC5Web.Models { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } public class ManageLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationDescription> OtherLogins { get; set; } } public class FactorViewModel { public string Purpose { get; set; } } public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } public class VerifyPhoneNumberViewModel { [Required] [Display(Name = "Code")] public string Code { get; set; } [Required] [Phone] [Display(Name = "Phone Number")] public string PhoneNumber { get; set; } } public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } } }
mit
hitnoodle/Animu-Torrent-Checker
Classes/Models/Animu.cs
3104
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.IO; namespace AnimuTorrentChecker.Models { public class Animu { public string Title; public int Episode; // Assume max episode is 99 (two digits) public string Subber; public Animu() { this.Title = ""; this.Episode = -1; this.Subber = ""; } public Animu(string title, int episode, string subber) { this.Title = title; this.Episode = episode; this.Subber = subber; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.Subber); sb.Append(" "); sb.Append(this.Title); sb.Append(" "); string episode = (this.Episode < 10) ? "0" + this.Episode : this.Episode.ToString(); sb.Append(episode); return sb.ToString(); } public string FormattedString() { StringBuilder sb = new StringBuilder(); sb.Append("["); sb.Append(this.Subber); sb.Append("] "); sb.Append(this.Title); sb.Append(" - "); string episode = (this.Episode < 10) ? "0" + this.Episode : this.Episode.ToString(); sb.Append(episode); return sb.ToString(); } } public class AnimuSeries { public Animu[] AnimuData; public AnimuSeries() { AnimuData = new Animu[1]; AnimuData[0] = new Animu("Animu Title Here", 0, "Animu Subber Here"); } public void Save() { XmlSerializer serializer = new XmlSerializer(typeof(AnimuSeries)); TextWriter textWriter = new StreamWriter(@Settings.Instance.AnimeListPath); serializer.Serialize(textWriter, this); textWriter.Close(); } public void Load() { XmlSerializer deserializer = new XmlSerializer(typeof(AnimuSeries)); TextReader textReader = new StreamReader(@Settings.Instance.AnimeListPath); AnimuSeries loaded; loaded = (AnimuSeries)deserializer.Deserialize(textReader); textReader.Close(); this.AnimuData = loaded.AnimuData; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Anime List:"); sb.Append(" (updated every "); sb.Append(Settings.Instance.MinutesToUpdate); sb.Append(" minutes)\n"); foreach (Animu a in AnimuData) { sb.Append("\t"); sb.Append(a.Title); sb.Append(" "); sb.Append(a.Episode); sb.Append(" "); sb.Append(a.Subber); sb.Append("\n"); } return sb.ToString(); } } }
mit
muziyoshiz/admiral_stats
app/models/special_ship_master.rb
1509
# 特別デザインのカードに関するマスタデータ class SpecialShipMaster < ApplicationRecord belongs_to :ship_master, foreign_key: :book_no, primary_key: :book_no # 追加されたカードの図鑑 No. validates :book_no, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, } # 追加されたカードの図鑑内でのインデックス(0〜) # オリジナルイラストカードが今後も追加される可能性があるため、上限なしに設定する validates :card_index, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, }, uniqueness: { scope: [ :book_no ] } # 追加されたカードの改造レベルを表す数値 # 0 ならノーマル、1 なら改 validates :remodel_level, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, } # 追加されたカードのレアリティを表す数値 # 0: ノーマル相当 # 1: ホロ相当(運が上がる) # 2: 中破相当(運が上がり、装甲が下がる) validates :rarity, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 2, } end
mit
vgrem/phpSPO
src/SharePoint/Sharing/PermissionCollection.php
1145
<?php /** * Modified: 2019-10-12T20:10:10+00:00 API: 16.0.19402.12016 */ namespace Office365\SharePoint\Sharing; use Office365\Runtime\ClientValue; /** * This class * is returned when * Microsoft.SharePoint.Client.Sharing.SecurableObjectExtensions.GetSharingInformation * is called with the optional expand on permissionsInformation property. It * contains a collection of LinkInfo and PrincipalInfo objects of users/groups * that have access to the list item and also * the site administrators who have implicit access. */ class PermissionCollection extends ClientValue { /** * @var bool */ public $hasInheritedLinks; /** * Read/WriteThe List * of tokenized * sharing links with their LinkInfo objects. * @var array */ public $links; /** * Read/WriteThe List * of Principals with their roles on this list item. * @var array */ public $principals; /** * Read/WriteThe List * of Principals who are Site Admins. This property is returned only if the caller * is an Auditor. * @var array */ public $siteAdmins; }
mit
mattloper/opendr
opendr/test_camera.py
2453
#!/usr/bin/env python # encoding: utf-8 """ Author(s): Matthew Loper See LICENCE.txt for licensing and contact information. """ import unittest import numpy as np from .camera import * import chumpy as ch class TestCamera(unittest.TestCase): def get_cam_params(self): v_raw = np.sin(np.arange(900)).reshape((-1,3)) v_raw[:, 2] -= 2 rt = ch.zeros(3) t = ch.zeros(3) f = ch.array([500,500]) c = ch.array([320,240]) k = ch.zeros(5) cam_params = {'v': ch.Ch(v_raw), 'rt': rt, 't': t, 'f': f, 'c': c, 'k': k} return cam_params def test_project_points(self): self.project_points(ProjectPoints) self.project_points(ProjectPoints3D) def project_points(self, cls): cam_params = self.get_cam_params() for key, value in list(cam_params.items()): eps = (np.random.random(value.r.size)-.5) * 1e-5 pp_dist = cls(**cam_params) old_val = pp_dist.r.copy() old_dr = pp_dist.dr_wrt(value).dot(eps) tmp = cam_params[key].r.copy() tmp += eps.reshape(tmp.shape) cam_params[key] = ch.Ch(tmp) diff = ((cls(**cam_params).r - old_val)) raw_dr_diff = np.abs(old_dr.flatten() - diff.flatten()) med_diff = np.median(raw_dr_diff) max_diff = np.max(raw_dr_diff) #pct_diff = (100. * max_diff / np.mean(np.abs(old_val.flatten()))) # print 'testing for %s' % (key,) # print 'empirical' + str(diff.flatten()[:5]) # print 'predicted' + str(old_dr[:5]) # print 'med diff: %.2e' % (med_diff,) # print 'max diff: %.2e' % (max_diff,) #print 'pct diff: %.2e%%' % (pct_diff,) self.assertLess(med_diff, 1e-8) self.assertLess(max_diff, 5e-8) pp_dist = cls(**cam_params) # Test to make sure that depends_on is working for name in ('rt', 't', 'f', 'c', 'k'): aa = pp_dist.camera_mtx setattr(pp_dist, name, getattr(pp_dist, name).r + 1) bb = pp_dist.camera_mtx if name in ('f', 'c'): self.assertTrue(aa is not bb) else: self.assertTrue(aa is bb) if __name__ == '__main__': unittest.main()
mit
Porterbg/FileSystemASP
FileSystem/FileSystem.Models/Image.cs
415
using System; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; namespace FileSystem.Models { public class Image { [Key] public int Id { get; set; } public int Width { get; set; } public int Height { get; set; } } }
mit
chennqqi/goutils
consul.v2/app.go
5191
package consul import ( "errors" "fmt" "io/ioutil" "log" "net" "net/url" "os" "os/signal" "reflect" "strings" "github.com/chennqqi/goutils/closeevent" "github.com/chennqqi/goutils/utils" "github.com/chennqqi/goutils/yamlconfig" "gopkg.in/yaml.v2" ) type ConsulApp struct { *ConsulOperator } // load an conf file text form file(FQDN) // try consul first, if not exist, try local file func ReadTxt(c *ConsulOperator, file string) ([]byte, error) { if strings.HasPrefix(file, "consul://") { u, err := url.Parse(file) if c == nil { return nil, errors.New("consul not set") } else if err != nil { return nil, err } else { return c.Get(u.Path) } } else { return ioutil.ReadFile(file) } } // create a consul app with load cfg, using 127.0.0.1:8500 // cfg is required parameter, the cfg address // arg heathHost is must parameter, a health http address of app // arg consulUrl is an FQDN format string which contains consul host,port,configpath, if configpath is empty, // ${appname}.yml, config/${appname} will be tried to load in order func NewConsulAppWithCfg(cfg interface{}, consulUrl string) (*ConsulApp, error) { var capp ConsulApp if consulUrl == "" { consulUrl = "127.0.0.1:8500" } appinfo, err := ParseConsulUrl(consulUrl) if err != nil { return nil, err } appName := utils.ApplicationName() consulapi, err := NewConsulOp(consulUrl) if err != nil { return nil, err } consulapi.Fix() capp.ConsulOperator = consulapi //try /${APPNAME}.yml //try /config/${APPNAME}.yml //try /config/${APPNAME}.yml var names []string var defaultName string var confName = appinfo.Config if confName == "" { confName = fmt.Sprintf("%s.yml", appName) defaultName = confName names = append(names, confName) confName = appName names = append(names, confName) confName = fmt.Sprintf("config/%s.yml", appName) names = append(names, confName) confName = fmt.Sprintf("config/%s", confName) names = append(names, confName) } else { names = append(names, confName) defaultName = appinfo.Config } if err := consulapi.Ping(); err != nil { log.Println("[consul/app.go] ping consul failed, try local") var exist bool for i := 0; i < len(names); i++ { log.Printf("[consul/app.go] ping consul failed, try load %v", names[i]) err := yamlconfig.Load(cfg, names[i]) if err == nil { exist = true break } } if !exist { log.Printf("[consul/app.go] all try load failed, make default %v", defaultName) yamlconfig.Save(cfg, defaultName) return nil, ErrNotExist } } else { // consul is OK //try /config/${APPNAME}.yml var exist bool for i := 0; i < len(names); i++ { txt, err := consulapi.Get(names[i]) if err == nil { log.Printf("[consul/app.go] successfully get consul kv: %v", names[i]) err = yaml.Unmarshal(txt, cfg) if err != nil { return &capp, err } exist = true break } else { log.Printf("[consul/app.go] failed get consul kv(%v), error(%v)", names[i], err) } } if !exist { log.Printf("[consul/app.go] all try load failed, make default %v", defaultName) yamlconfig.Save(cfg, defaultName) return nil, ErrNotExist } } //post fix consul if cfg != nil { //health var healthHost string var health string { st := reflect.ValueOf(cfg).Elem() field := st.FieldByName("Health") if field.IsValid() { health = field.String() //health is an url if strings.HasPrefix(health, "tcp") { consulapi.CheckTCP = health consulapi.CheckHTTP = "" } else if strings.HasPrefix(health, "http") { consulapi.CheckHTTP = health consulapi.CheckTCP = "" } } } if health == "" { st := reflect.ValueOf(cfg).Elem() field := st.FieldByName("HealthHost") if field.IsValid() { healthHost = field.String() v := strings.Split(healthHost, ":") if len(v) > 1 { fmt.Sscanf(v[1], "%d", &consulapi.ServicePort) } fmt.Println("healthHost:", v, consulapi.ServicePort) if v[0] != "" && v[0] != "127.0.0.1" && v[0] != "##1" { ip := net.ParseIP(v[0]) if ip != nil { consulapi.ServiceIP = ip.String() } } } } } return &capp, nil } // create a consul app // arg heathHost is must parameter, a health http address of app // arg agent is option, if empty using default 127.0.0.1:8500 func NewConsulApp(consulUrl string) (*ConsulApp, error) { consulapi, err := NewConsulOp(consulUrl) if err != nil { return nil, err } return &ConsulApp{consulapi}, nil } // wait for main function return and register app to service to consul func (c *ConsulApp) Wait(stopcall func(os.Signal), signals ...os.Signal) { quitChan := make(chan os.Signal, 1) defer close(quitChan) if len(signals) > 0 { signal.Notify(quitChan, signals...) } else { closeevent.CloseNotify(quitChan) } c.RegisterService() sig := <-quitChan log.Println("[main:main] quit, recv signal ", sig) if stopcall != nil { stopcall(sig) } c.DeregisterService() }
mit
dmayhak/HyperSlackers.Localization
Localization/Attributes/MinValueAttribute.cs
3170
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using HyperSlackers.Localization.Extensions; namespace HyperSlackers.Localization { /// <summary> /// Validation attribute to specify a minimum value for a property. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public sealed class MinValueAttribute : ValidationAttribute { /// <summary> /// The minimum value. /// </summary> public object MinValue { get; set; } /// <summary> /// Prevents a default instance of the <see cref="MinValueAttribute"/> class from being created. /// </summary> private MinValueAttribute() { } /// <summary> /// Initializes a new instance of the <see cref="MinValueAttribute"/> class. /// </summary> /// <param name="minValue">The minimum value.</param> public MinValueAttribute(int minValue) { this.MinValue = minValue; } /// <summary> /// Initializes a new instance of the <see cref="MinValueAttribute"/> class. /// </summary> /// <param name="minValue">The minimum value.</param> public MinValueAttribute(double minValue) { this.MinValue = minValue; } /// <summary> /// Determines whether the specified value of the object is valid. /// </summary> /// <param name="value">The value of the object to validate.</param> /// <returns> /// true if the specified value is valid; otherwise, false. /// </returns> public override bool IsValid(object value) { try { if (this.MinValue is int) { return (int)value >= (int)this.MinValue; } else { return (double)value >= (double)this.MinValue; } } catch { return false; } } /// <summary> /// Applies formatting to an error message, based on the data field where the error occurred. /// </summary> /// <param name="name">The name to include in the formatted message.</param> /// <returns> /// An instance of the formatted error message. /// </returns> public override string FormatErrorMessage(string name) { string formatString = this.ErrorMessage; if (formatString.IsNullOrWhiteSpace()) { formatString = Helpers.GetResourceString(this.ErrorMessageResourceType, this.ErrorMessageResourceName); } if (formatString.IsNullOrWhiteSpace()) { formatString = "{0} must be at least {1}."; } return formatString.FormatWith(name, this.MinValue); } } }
mit
davidteoran/freecodecamp-projects
intermediate-algorithm-scripting/pig_latin.js
1231
/* Translate the provided string to pig latin. Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay". If a word begins with a vowel you just add "way" to the end. Input strings are guaranteed to be English words in all lowercase. */ function translatePigLatin(str) { const vowels = ["a", "e", "i", "o", "u"]; const consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "x", "z", "w", "y"]; const firstLetter = str.charAt(0); const secondLetter = str.charAt(1); let restOfTheWord; for(i = 0; i < vowels.length; i++) { if(vowels[i] === firstLetter) { str = str.concat("way"); } } for (i = 0; i < consonants.length; i++) { if(consonants[i] === firstLetter) { restOfTheWord = str.slice(1); str = restOfTheWord + firstLetter + "ay"; for (j = 0; j < consonants.length; j++) { if(str.charAt(0) === secondLetter && consonants[j] === secondLetter) { restOfTheWord = restOfTheWord.slice(1); str = restOfTheWord + firstLetter + secondLetter + "ay"; } } } } return str; } translatePigLatin("consonant");
mit
easybiblio/easybiblio
server/person.php
3958
<?php include_once '_header.mandatory.php'; $fmw->checkOperator(); include '_header.php'; ?> <h1><?= $t->__('db.person') ?></h1> <?php $id = $_GET['id']; if ($id != '') { $columns = $database->get("tb_person", "*", array("id" => $id)); } ?> <form class="form-horizontal" action="personSave.php" method="post" role="form"> <!-- ID --> <input type="hidden" name="id" value="<?= $columns['id'] ?>"> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.name') ?>:</label> <div class="col-sm-10"> <input type="text" name="name" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'name') ?> maxlength="120"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.address') ?>:</label> <div class="col-sm-10"> <input type="text" name="address" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'address') ?> maxlength="120"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.zipcode') ?>:</label> <div class="col-sm-10"> <input type="text" name="zipcode" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'zipcode') ?> maxlength="10"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.city') ?>:</label> <div class="col-sm-10"> <input type="text" name="city" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'city') ?> maxlength="45"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.phone1') ?>:</label> <div class="col-sm-10"> <input type="text" name="phone1" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'phone1') ?> maxlength="45"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.phone2') ?>:</label> <div class="col-sm-10"> <input type="text" name="phone2" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'phone2') ?> maxlength="45"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.email') ?>:</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" value=<?= $fmw->getPostOrArrayQuoted($columns, 'email') ?> maxlength="100"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.notes') ?>:</label> <div class="col-sm-10"> <textarea rows="6" cols="47" class="form-control" name="notes"><?= $fmw->escapeHtml($fmw->getPostOrArray($columns, 'notes')) ?></textarea> </div> </div> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.active') ?></label> <div class="col-sm-1"> <input type="checkbox" name="active" class="form-control" value='1' <?= $fmw->getPostOrArray($columns, 'active') == '1' ? 'checked' : '' ?> > </div> <p class="form-control-static"><?= $t->__('db.person.active_explanation') ?></p> </div> <?php if ($id != '') { ?> <div class="form-group"> <label class="control-label col-sm-2"><?= $t->__('db.person.date_creation') ?>:</label> <div class="col-sm-10"> <p class="form-control-static"><?= $fmw->getPostOrArray($columns, 'date_creation') ?></p> </div> </div> <?php } ?> <!-- Buttons --> <div class="form-group"> <label class="control-label col-sm-2">&nbsp;</label> <div class="col-sm-10"> <input type="submit" class="btn btn-default" name="Submit" value="<?= $t->__('button.save') ?>"> <input type="button" class="btn btn-default" value="<?= $t->__('button.cancel') ?>" onclick="window.location.href='personSearch.php'"> </div> </div> </form> <?php include '_footer.php' ?>
mit
kodefuguru/bungie
src/Bungie.Tests/Wrappers/AbstractMessage.cs
366
namespace Bungie.Tests.Wrappers { internal abstract class AbstractMessage<T> { public T Response { get; set; } public int ErrorCode { get; set; } public int ThrottleSeconds { get; set; } public string ErrorStatus { get; set; } public string Message { get; set; } public object MessageData { get; set; } } }
mit
nrvru/dummy-api-exercise
services/object_service.js
1466
var _ = require('lodash'); var fdb = require('../data/fake_db'); var rawObject; function getProperties(objects, cb){ var properties = []; _.forEach(objects, function(object){ _.forEach(object.properties, function(value, key){ properties.push(key); }); }); properties = _.uniq(properties); var embeddedObjects = []; fdb.findByName(properties, function(err, data){ _.forEach(objects, function(object){ _.forEach(object.properties, function(value, key){ object.properties[key] = _.find(data, function(d){ return d.name === key; }); var property = object.properties[key]; if(_.isNumber(value)){ property.value = value; } else { if(property.properties){ embeddedObjects.push(property); } } }); }); if(embeddedObjects.length > 0){ getProperties(embeddedObjects, cb); } else { cb(null, rawObject); } }); } function getObjectByNameUrl(objectNameUrl, cb){ fdb.findByNameUrl([objectNameUrl], function(err, data){ if(err || !data[0]) { cb(err || 'Object not found'); return; } rawObject = data[0]; getProperties([rawObject], cb); }) } module.exports.getObjectByNameUrl = getObjectByNameUrl;
mit
zachmargolis/interjectable
spec/interjectable/rspec_spec.rb
10983
# frozen_string_literal: true require 'spec_helper' class Klass extend Interjectable inject(:dependency) { :dependency } inject_static(:static_dependency) { :static_dependency } define_method(:foo) { :foo } end SubKlass = Class.new(Klass) SubSubKlass = Class.new(SubKlass) describe "RSpec test helper #test_inject" do let(:instance) { Klass.new } let(:subklass_instance) { SubKlass.new } before(:all) do Klass.static_dependency = :boom SubKlass.static_dependency = :boom1 SubSubKlass.static_dependency = :boom2 expect(Klass.static_dependency).to eq(:boom2) expect(SubKlass.static_dependency).to eq(:boom2) expect(SubSubKlass.static_dependency).to eq(:boom2) Klass.static_dependency = :static_dependency end after(:all) do # Sanity check after running the tests, verify #test_inject cleans up after itself instance = Klass.new expect(instance.dependency).to eq(:dependency) expect(instance.static_dependency).to eq(:static_dependency) expect(Klass.static_dependency).to eq(:static_dependency) subklass_instance = SubKlass.new expect(subklass_instance.dependency).to eq(:dependency) expect(subklass_instance.static_dependency).to eq(:static_dependency) expect(SubKlass.static_dependency).to eq(:static_dependency) subsubklass_instance = SubSubKlass.new expect(subsubklass_instance.dependency).to eq(:dependency) expect(subsubklass_instance.static_dependency).to eq(:static_dependency) expect(SubSubKlass.static_dependency).to eq(:static_dependency) Klass.static_dependency = :boom SubKlass.static_dependency = :boom1 SubSubKlass.static_dependency = :boom2 expect(Klass.static_dependency).to eq(:boom2) expect(SubKlass.static_dependency).to eq(:boom2) expect(SubSubKlass.static_dependency).to eq(:boom2) end context "isoloated context" do before(:all) do # Sanity check before running the tests instance = Klass.new expect(instance.dependency).to eq(:dependency) expect(instance.static_dependency).to eq(:static_dependency) expect(Klass.static_dependency).to eq(:static_dependency) subklass_instance = SubKlass.new expect(subklass_instance.dependency).to eq(:dependency) expect(subklass_instance.static_dependency).to eq(:static_dependency) expect(SubKlass.static_dependency).to eq(:static_dependency) Klass.test_inject(:dependency) { :unused_dependency } Klass.test_inject(:static_dependency) { :unused_overriden_static_dependency } end before do test_inject(Klass, :dependency, :another_unused_dependency) Klass.test_inject(:dependency) { foo } Klass.test_inject(:static_dependency) { :overriden_static_dependency } end it "sets the dependency" do expect(instance.dependency).to eq(:foo) expect(instance.static_dependency).to eq(:overriden_static_dependency) expect(Klass.static_dependency).to eq(:overriden_static_dependency) end it "still respects instance setters" do instance.dependency = :bar expect(instance.dependency).to eq(:bar) expect(Klass.new.dependency).to eq(:foo) end it "still respects static setters in the overriden test_injected context only" do instance.static_dependency = :bar expect(instance.static_dependency).to eq(:bar) expect(Klass.static_dependency).to eq(:bar) expect(SubKlass.static_dependency).to eq(:bar) expect(SubSubKlass.static_dependency).to eq(:bar) end it "errors if you inject a non static default into a static injection" do Klass.test_inject(:static_dependency) { foo } expect { instance.bad_dependency }.to raise_error(NameError) expect { Klass.bad_dependency }.to raise_error(NameError) end context "override dependency" do before(:all) do Klass.test_inject(:dependency) { :yet_another_unused_dependency } test_inject(Klass, :static_dependency, :unused_static_dependency) end before do Klass.test_inject(:dependency) { :override } Klass.test_inject(:static_dependency) { :double_overriden_static_dependency } end it "sets the dependency" do expect(instance.dependency).to eq(:override) expect(instance.static_dependency).to eq(:double_overriden_static_dependency) expect(Klass.static_dependency).to eq(:double_overriden_static_dependency) end it "sets the dependency again" do expect(instance.dependency).to eq(:override) expect(instance.static_dependency).to eq(:double_overriden_static_dependency) expect(Klass.static_dependency).to eq(:double_overriden_static_dependency) end context "in a subclass" do before do SubKlass.test_inject(:dependency) { :subklass_override } SubKlass.test_inject(:static_dependency) { :subklass_double_overriden_static_dependency } end it "sets the dependency" do expect(subklass_instance.dependency).to eq(:subklass_override) expect(subklass_instance.static_dependency).to eq(:subklass_double_overriden_static_dependency) expect(Klass.static_dependency).to eq(:double_overriden_static_dependency) end end context "in a context" do it "sets the dependency" do expect(instance.dependency).to eq(:override) expect(instance.static_dependency).to eq(:double_overriden_static_dependency) expect(Klass.static_dependency).to eq(:double_overriden_static_dependency) end it "sets the dependency again" do expect(instance.dependency).to eq(:override) expect(instance.static_dependency).to eq(:double_overriden_static_dependency) expect(Klass.static_dependency).to eq(:double_overriden_static_dependency) end end end end context "isoloated context: subclass inject" do before do SubKlass.test_inject(:dependency) { foo } end it "sets the dependency" do expect(subklass_instance.dependency).to eq(:foo) end context "subcontext" do it "sets the dependency" do expect(subklass_instance.dependency).to eq(:foo) end end end context "isoloated context: subclass before :all" do before(:all) do SubKlass.test_inject(:static_dependency) { :bar } SubKlass.test_inject(:static_dependency) { :zoo } test_inject(SubKlass, :static_dependency, :baz) end it "sets the static_dependency" do expect(SubKlass.static_dependency).to eq(:baz) end context "subcontext" do before(:all) do test_inject(SubKlass, :static_dependency, :goat) end it "sets the static_dependency" do expect(SubKlass.static_dependency).to eq(:goat) end end context "another subcontext" do it "sets the static_dependency" do expect(SubKlass.static_dependency).to eq(:baz) end end end context "rspec receive mocks" do before do instance_double(Object).tap do |fake_dependency| Klass.test_inject(:dependency) { fake_dependency } end instance_double(Object).tap do |fake_static_dependency| Klass.test_inject(:static_dependency) { fake_static_dependency } end end it "supports rspec mocks" do expect(instance.dependency).to receive(:to_s).and_return("house") expect(instance.dependency.to_s).to eq("house") expect(SubKlass.static_dependency).to receive(:to_s).and_return("boom") expect(SubKlass.static_dependency.to_s).to eq("boom") expect(subklass_instance.static_dependency).to receive(:to_s).and_return("not boom") expect(subklass_instance.static_dependency.to_s).to eq("not boom") end end describe "invalid arguments" do it "raises ArgumentError" do expect { Klass.test_inject(:dependency) }.to raise_error(ArgumentError) expect { Klass.test_inject { instance_double(Object) } }.to raise_error(ArgumentError) expect { Klass.test_inject(:bad_dependency) { 1 } }.to raise_error(ArgumentError) end end context "double subclass" do context "1" do it "sets the dependency" do calls = 0 Klass.test_inject(:dependency) { calls += 1; :baz } expect(Klass.new.dependency).to eq(:baz) subklass = SubKlass.new expect(subklass.dependency).to eq(:baz) expect(subklass.dependency).to eq(:baz) expect(SubSubKlass.new.dependency).to eq(:baz) expect(calls).to eq(3) end end context "2" do it "sets the dependency" do calls = 0 SubKlass.test_inject(:dependency) { calls += 1; :baz } expect(Klass.new.dependency).to eq(:dependency) subklass = SubKlass.new expect(subklass.dependency).to eq(:baz) expect(subklass.dependency).to eq(:baz) expect(SubSubKlass.new.dependency).to eq(:baz) expect(calls).to eq(2) end end context "3" do it "sets the dependency" do sub_klass_calls = 0 sub_sub_klass_calls = 0 SubKlass.test_inject(:dependency) { sub_klass_calls += 1; :bar } SubSubKlass.test_inject(:dependency) { sub_sub_klass_calls += 1; :baz } expect(Klass.new.dependency).to eq(:dependency) subklass = SubKlass.new expect(subklass.dependency).to eq(:bar) expect(subklass.dependency).to eq(:bar) expect(SubSubKlass.new.dependency).to eq(:baz) expect(sub_klass_calls).to eq(1) expect(sub_sub_klass_calls).to eq(1) end end end context "double subclass static" do context "1" do it "sets the dependency" do calls = 0 Klass.test_inject(:static_dependency) { calls += 1; :baz } expect(Klass.new.static_dependency).to eq(:baz) expect(SubKlass.new.static_dependency).to eq(:baz) expect(SubSubKlass.new.static_dependency).to eq(:baz) expect(calls).to eq(1) end end context "2" do it "sets the dependency" do calls = 0 SubKlass.test_inject(:static_dependency) { calls += 1; :baz } expect(Klass.new.static_dependency).to eq(:static_dependency) expect(SubKlass.new.static_dependency).to eq(:baz) expect(SubSubKlass.new.static_dependency).to eq(:baz) expect(calls).to eq(1) end end context "3" do it "sets the dependency" do sub_klass_calls = 0 sub_sub_klass_calls = 0 SubKlass.test_inject(:static_dependency) { sub_klass_calls += 1; :bar } SubSubKlass.test_inject(:static_dependency) { sub_sub_klass_calls += 1; :baz } expect(Klass.new.static_dependency).to eq(:static_dependency) expect(SubKlass.new.static_dependency).to eq(:bar) expect(SubSubKlass.new.static_dependency).to eq(:baz) expect(sub_klass_calls).to eq(1) expect(sub_sub_klass_calls).to eq(1) end end end end
mit
DavidHickman/ahps_alerts
setup.py
1690
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'Click>=6.0', 'feedparser', 'beautifulsoup4', ] setup_requirements = [ 'pytest-runner', ] test_requirements = [ 'pytest', ] setup( name='ahps_alerts', version='0.1.5', description="Retrieve NWS AHPS alerts", long_description=readme + '\n\n' + history, author="David Hickman", author_email='[email protected]', url='https://github.com/DavidHickman/ahps_alerts', packages=find_packages(include=['ahps_alerts']), entry_points={ 'console_scripts': [ 'ahps-alerts=ahps_alerts.cli:main' ] }, include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='ahps_alerts, National Weather Service, TNRIS, Texas', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, )
mit
SebastianoF/LabelsManager
examples/prototype_symmetrise_a_segmentation.py
2395
import os from os.path import join as jph import a_generate_phantoms_for_examples as gen from nilabels.agents.agents_controller import AgentsController as NiL from nilabels.definitions import root_dir # ---- GENERATE DATA ---- if not os.path.exists(jph(root_dir, 'data_examples', 'ellipsoids.nii.gz')): creation_list = {'Examples folder' : False, 'Punt e mes' : False, 'C' : False, 'Planetaruim' : False, 'Buckle ellipsoids' : True, 'Ellipsoids family' : False, 'Cubes in the sky' : False, 'Sandwich' : False, 'Four-folds' : False} gen.generate_figures(creation_list) # ---- PATH MANAGER ---- # input pfi_input_anatomy = jph(root_dir, 'data_examples', 'ellipsoids.nii.gz') pfi_input_segmentation = jph(root_dir, 'data_examples', 'ellipsoids_seg_half.nii.gz') pfo_output_folder = jph(root_dir, 'data_output') assert os.path.exists(pfi_input_anatomy), pfi_input_anatomy assert os.path.exists(pfi_input_segmentation), pfi_input_segmentation assert os.path.exists(pfo_output_folder), pfo_output_folder # output pfi_output_segmentation = jph(root_dir, 'data_examples', 'ellipsoids_seg_symmetrised.nii.gz') # ---- LABELS LIST ---- labels_central = [] labels_left = [1, 2, 3, 4, 5, 6] labels_right = [a + 10 for a in labels_left] labels_sym_left = labels_left + labels_central labels_sym_right = labels_right + labels_central # --- EXECUTE ---- lt = NiL() lt.symmetrize.symmetrise_with_registration(pfi_input_anatomy, pfi_input_segmentation, labels_sym_left, pfi_output_segmentation, results_folder_path=pfo_output_folder, list_labels_transformed=labels_sym_right, coord='z', reuse_registration=False) # --- SEE RESULTS ---- opener1 = 'itksnap -g {} -s {}'.format(pfi_input_anatomy, pfi_input_segmentation) opener2 = 'itksnap -g {} -s {}'.format(pfi_input_anatomy, pfi_output_segmentation) os.system(opener1) os.system(opener2)
mit
sly01/ojs
tests/functional/plugins/generic/lucene/FunctionalLucenePluginBaseTestCase.inc.php
4265
<?php /** * @file tests/functional/plugins/generic/lucene/FunctionalLucenePluginBaseTestCase.inc.php * * Copyright (c) 2000-2013 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @class FunctionalLucenePluginBaseTestCase * @ingroup tests_functional_plugins_generic_lucene * @see LucenePlugin * * @brief Integration/Functional test for the lucene plug-in * and its dependencies (base class with common functionality). */ import('lib.pkp.tests.WebTestCase'); class FunctionalLucenePluginBaseTestCase extends WebTestCase { protected $simpleSearchForm = '//form[@id="simpleSearchForm"]//'; // // Implement template methods from PKPTestCase // protected function tearDown() { parent::tearDown(); $pluginSettingsDao = DAORegistry::getDAO('PluginSettingsDAO'); /* @var $pluginSettingsDao PluginSettingsDAO */ $pluginSettingsDao->_getCache(0, 'luceneplugin')->flush(); } // // Protected helper methods // /** * Execute a simple search. * * @param $searchPhrase string * @param $searchField * @param $articles integer|array a list of article * ids that must appear in the result set * @param $notArticles integer|array a list of article * ids that must not appear in the result. Can be '*' * to exclude any additional result. * @param $locale string * @param $journal string the context path of the journal to test */ protected function simpleSearch($searchPhrase, $searchField = 'query', $articles = array(), $notArticles = array(), $locale = 'en_US', $journal = 'lucene-test') { // Translate scalars to arrays. if (!is_array($articles)) $articles = array($articles); if ($notArticles !== '*' && !is_array($notArticles)) $notArticles = array($notArticles); try { // Open the "lucene-test" journal home page. $testJournal = $this->baseUrl . '/index.php/' . $journal; $this->verifyAndOpen($testJournal); // Select the locale. $selectedValue = $this->getSelectedValue('name=locale'); if ($selectedValue != $locale) { $this->selectAndWait('name=locale', 'value=' . $locale); } // Hack to work around timing problems in phpunit 3.4... $this->waitForElementPresent($this->simpleSearchForm . 'input[@id="simpleQuery"]'); $this->waitForElementPresent('name=searchField'); // Enter the search phrase into the simple search field. $this->type($this->simpleSearchForm . 'input[@id="simpleQuery"]', $searchPhrase); // Select the search field. $this->select('name=searchField', 'value=' . $searchField); // Click the "Search" button. $this->clickAndWait($this->simpleSearchForm . 'input[@type="submit"]'); // Check whether the result set contains the // sample articles. foreach($articles as $id) { $this->assertElementPresent('//table[@class="listing"]//a[contains(@href, "index.php/lucene-test/article/view/' . $id . '")]'); } // Make sure that the result set does not contain // the articles in the "not article" list. if ($notArticles === '*') { } else { foreach($notArticles as $id) { $this->assertElementNotPresent('//table[@class="listing"]//a[contains(@href, "index.php/lucene-test/article/view/' . $id . '")]'); } } } catch(Exception $e) { throw $this->improveException($e, "example $searchPhrase ($locale)"); } } /** * Execute a simple search across journals. * * @param $searchTerm string */ protected function simpleSearchAcrossJournals($searchTerm, $locale = 'en_US') { // Open the test installation's home page. $homePage = $this->baseUrl . '/index.php'; $this->verifyAndOpen($homePage); // Select the locale. $selectedValue = $this->getSelectedValue('name=locale'); if ($selectedValue != $locale) { $this->selectAndWait('name=locale', 'value=' . $locale); } // Hack to work around timing problems in phpunit 3.4... $this->waitForElementPresent($this->simpleSearchForm . 'input[@id="simpleQuery"]'); $this->waitForElementPresent('name=searchField'); // Enter the search term into the simple search box. $this->type($this->simpleSearchForm . 'input[@id="simpleQuery"]', $searchTerm); // Click the "Search" button. $this->clickAndWait($this->simpleSearchForm . 'input[@type="submit"]'); } } ?>
mit
nano-byte/common
src/UnitTests/Dispatch/PerTypeDispatcherTest.cs
2046
// Copyright Bastian Eicher // Licensed under the MIT License namespace NanoByte.Common.Dispatch; /// <summary> /// Contains test methods for <see cref="PerTypeDispatcher{TBase,TResult}"/>. /// </summary> public class PerTypeDispatcherTest { private abstract class Base {} private class Sub1 : Base {} private class Sub2 : Base {} [Fact] public void TestDispatchAction() { var sub1Orig = new Sub1(); Sub1? sub1Dispatched = null; var sub2Orig = new Sub2(); Sub2? sub2Dispatched = null; var dispatcher = new PerTypeDispatcher<Base>(false) { (Sub1 sub1) => sub1Dispatched = sub1, (Sub2 sub2) => sub2Dispatched = sub2 }; dispatcher.Dispatch(sub1Orig); sub1Dispatched.Should().BeSameAs(sub1Orig); dispatcher.Dispatch(sub2Orig); sub2Dispatched.Should().BeSameAs(sub2Orig); } [Fact] public void TestDispatchActionExceptions() { new PerTypeDispatcher<Base>(false) {(Sub1 _) => {}} .Invoking(x => x.Dispatch(new Sub2())) .Should().Throw<KeyNotFoundException>(); new PerTypeDispatcher<Base>(true) {(Sub1 _) => {}} .Invoking(x => x.Dispatch(new Sub2())) .Should().NotThrow<KeyNotFoundException>(); } [Fact] public void TestDispatchFunc() { var sub1Orig = new Sub1(); var sub2Orig = new Sub2(); var dispatcher = new PerTypeDispatcher<Base, Base> { (Sub1 sub1) => sub1, (Sub2 sub2) => sub2 }; dispatcher.Dispatch(sub1Orig).Should().BeSameAs(sub1Orig); dispatcher.Dispatch(sub2Orig).Should().BeSameAs(sub2Orig); } [Fact] public void TestDispatchFuncExceptions() { new PerTypeDispatcher<Base, Base> {(Sub1 sub1) => sub1} .Invoking(x => x.Dispatch(new Sub2())) .Should().Throw<KeyNotFoundException>(); } }
mit
utarahman/berita
application/models/News.php
787
<?php class News extends CI_Model { public function tampil_data_news($kode) { if ($kode=='all'){ $hasil=$this->db->get('tabel_news'); }else{ $this->db->where('kode_news',$kode); $hasil=$this->db->get('tabel_news'); } return $hasil->result(); } public function simpan_data_news($data) { if ($data['mode']=='baru'){ unset($data['mode']); $hasil=$this->db->insert('tabel_news', $data); }else{ unset($data['mode']); $this->db->where('kode_buku',$data['news_id']); $hasil=$this->db->update('tabel_news', $data); } return $hasil; } public function hapus_data_news($kode) { $this->db->where('news_id', $kode); $hasil=$this->db->delete('tabel_news'); return $hasil; } } ?>
mit
drumminhands/drumminhands_photobooth
drumminhands_photobooth.py
13012
#!/usr/bin/env python # created by [email protected] # see instructions at http://www.drumminhands.com/2014/06/15/raspberry-pi-photo-booth/ import os import glob import time import traceback from time import sleep import RPi.GPIO as GPIO import picamera # http://picamera.readthedocs.org/en/release-1.4/install2.html import atexit import sys import socket import pygame from pygame.locals import QUIT, KEYDOWN, K_ESCAPE import pytumblr # https://github.com/tumblr/pytumblr import config # this is the config python file config.py from signal import alarm, signal, SIGALRM, SIGKILL ######################## ### Variables Config ### ######################## led_pin = 7 # LED btn_pin = 18 # pin for the start button total_pics = 4 # number of pics to be taken capture_delay = 1 # delay between pics prep_delay = 5 # number of seconds at step 1 as users prep to have photo taken gif_delay = 100 # How much time between frames in the animated gif restart_delay = 10 # how long to display finished message before beginning a new session test_server = 'www.google.com' # full frame of v1 camera is 2592x1944. Wide screen max is 2592,1555 # if you run into resource issues, try smaller, like 1920x1152. # or increase memory http://picamera.readthedocs.io/en/release-1.12/fov.html#hardware-limits high_res_w = 1296 # width of high res image, if taken high_res_h = 972 # height of high res image, if taken ############################# ### Variables that Change ### ############################# # Do not change these variables, as the code will change it anyway transform_x = config.monitor_w # how wide to scale the jpg when replaying transfrom_y = config.monitor_h # how high to scale the jpg when replaying offset_x = 0 # how far off to left corner to display photos offset_y = 0 # how far off to left corner to display photos replay_delay = 1 # how much to wait in-between showing pics on-screen after taking replay_cycles = 2 # how many times to show each photo on-screen after taking #################### ### Other Config ### #################### real_path = os.path.dirname(os.path.realpath(__file__)) # Setup the tumblr OAuth Client client = pytumblr.TumblrRestClient( config.consumer_key, config.consumer_secret, config.oath_token, config.oath_secret, ) # GPIO setup GPIO.setmode(GPIO.BOARD) GPIO.setup(led_pin,GPIO.OUT) # LED GPIO.setup(btn_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(led_pin,False) #for some reason the pin turns on at the beginning of the program. Why? # initialize pygame pygame.init() pygame.display.set_mode((config.monitor_w, config.monitor_h)) screen = pygame.display.get_surface() pygame.display.set_caption('Photo Booth Pics') pygame.mouse.set_visible(False) #hide the mouse cursor pygame.display.toggle_fullscreen() ################# ### Functions ### ################# # clean up running programs as needed when main program exits def cleanup(): print('Ended abruptly') pygame.quit() GPIO.cleanup() atexit.register(cleanup) # A function to handle keyboard/mouse/device input events def input(events): for event in events: # Hit the ESC key to quit the slideshow. if (event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE)): pygame.quit() #delete files in folder def clear_pics(channel): files = glob.glob(config.file_path + '*') for f in files: os.remove(f) #light the lights in series to show completed print "Deleted previous pics" for x in range(0, 3): #blink light GPIO.output(led_pin,True); sleep(0.25) GPIO.output(led_pin,False); sleep(0.25) # check if connected to the internet def is_connected(): try: # see if we can resolve the host name -- tells us if there is a DNS listening host = socket.gethostbyname(test_server) # connect to the host -- tells us if the host is actually # reachable s = socket.create_connection((host, 80), 2) return True except: pass return False # set variables to properly display the image on screen at right ratio def set_demensions(img_w, img_h): # Note this only works when in booting in desktop mode. # When running in terminal, the size is not correct (it displays small). Why? # connect to global vars global transform_y, transform_x, offset_y, offset_x # based on output screen resolution, calculate how to display ratio_h = (config.monitor_w * img_h) / img_w if (ratio_h < config.monitor_h): #Use horizontal black bars #print "horizontal black bars" transform_y = ratio_h transform_x = config.monitor_w offset_y = (config.monitor_h - ratio_h) / 2 offset_x = 0 elif (ratio_h > config.monitor_h): #Use vertical black bars #print "vertical black bars" transform_x = (config.monitor_h * img_w) / img_h transform_y = config.monitor_h offset_x = (config.monitor_w - transform_x) / 2 offset_y = 0 else: #No need for black bars as photo ratio equals screen ratio #print "no black bars" transform_x = config.monitor_w transform_y = config.monitor_h offset_y = offset_x = 0 # uncomment these lines to troubleshoot screen ratios # print str(img_w) + " x " + str(img_h) # print "ratio_h: "+ str(ratio_h) # print "transform_x: "+ str(transform_x) # print "transform_y: "+ str(transform_y) # print "offset_y: "+ str(offset_y) # print "offset_x: "+ str(offset_x) # display one image on screen def show_image(image_path): # clear the screen screen.fill( (0,0,0) ) # load the image img = pygame.image.load(image_path) img = img.convert() # set pixel dimensions based on image set_demensions(img.get_width(), img.get_height()) # rescale the image to fit the current display img = pygame.transform.scale(img, (transform_x,transfrom_y)) screen.blit(img,(offset_x,offset_y)) pygame.display.flip() # display a blank screen def clear_screen(): screen.fill( (0,0,0) ) pygame.display.flip() # display a group of images def display_pics(jpg_group): for i in range(0, replay_cycles): #show pics a few times for i in range(1, total_pics+1): #show each pic show_image(config.file_path + jpg_group + "-0" + str(i) + ".jpg") time.sleep(replay_delay) # pause # define the photo taking function for when the big button is pressed def start_photobooth(): input(pygame.event.get()) # press escape to exit pygame. Then press ctrl-c to exit python. ################################# Begin Step 1 ################################# print "Get Ready" GPIO.output(led_pin,False); show_image(real_path + "/instructions.png") sleep(prep_delay) # clear the screen clear_screen() camera = picamera.PiCamera() camera.vflip = False camera.hflip = True # flip for preview, showing users a mirror image camera.saturation = -100 # comment out this line if you want color images camera.iso = config.camera_iso pixel_width = 0 # local variable declaration pixel_height = 0 # local variable declaration if config.hi_res_pics: camera.resolution = (high_res_w, high_res_h) # set camera resolution to high res else: pixel_width = 500 # maximum width of animated gif on tumblr pixel_height = config.monitor_h * pixel_width // config.monitor_w camera.resolution = (pixel_width, pixel_height) # set camera resolution to low res ################################# Begin Step 2 ################################# print "Taking pics" now = time.strftime("%Y-%m-%d-%H-%M-%S") #get the current date and time for the start of the filename if config.capture_count_pics: try: # take the photos for i in range(1,total_pics+1): camera.hflip = True # preview a mirror image camera.start_preview(resolution=(config.monitor_w, config.monitor_h)) # start preview at low res but the right ratio time.sleep(2) #warm up camera GPIO.output(led_pin,True) #turn on the LED filename = config.file_path + now + '-0' + str(i) + '.jpg' camera.hflip = False # flip back when taking photo camera.capture(filename) print(filename) GPIO.output(led_pin,False) #turn off the LED camera.stop_preview() show_image(real_path + "/pose" + str(i) + ".png") time.sleep(capture_delay) # pause in-between shots clear_screen() if i == total_pics+1: break finally: camera.close() else: camera.start_preview(resolution=(config.monitor_w, config.monitor_h)) # start preview at low res but the right ratio time.sleep(2) #warm up camera try: #take the photos for i, filename in enumerate(camera.capture_continuous(config.file_path + now + '-' + '{counter:02d}.jpg')): GPIO.output(led_pin,True) #turn on the LED print(filename) time.sleep(capture_delay) # pause in-between shots GPIO.output(led_pin,False) #turn off the LED if i == total_pics-1: break finally: camera.stop_preview() camera.close() ########################### Begin Step 3 ################################# input(pygame.event.get()) # press escape to exit pygame. Then press ctrl-c to exit python. print "Creating an animated gif" if config.post_online: show_image(real_path + "/uploading.png") else: show_image(real_path + "/processing.png") if config.make_gifs: # make the gifs if config.hi_res_pics: # first make a small version of each image. Tumblr's max animated gif's are 500 pixels wide. for x in range(1, total_pics+1): #batch process all the images graphicsmagick = "gm convert -size 500x500 " + config.file_path + now + "-0" + str(x) + ".jpg -thumbnail 500x500 " + config.file_path + now + "-0" + str(x) + "-sm.jpg" os.system(graphicsmagick) #do the graphicsmagick action graphicsmagick = "gm convert -delay " + str(gif_delay) + " " + config.file_path + now + "*-sm.jpg " + config.file_path + now + ".gif" os.system(graphicsmagick) #make the .gif else: # make an animated gif with the low resolution images graphicsmagick = "gm convert -delay " + str(gif_delay) + " " + config.file_path + now + "*.jpg " + config.file_path + now + ".gif" os.system(graphicsmagick) #make the .gif if config.post_online: # turn off posting pics online in config.py connected = is_connected() #check to see if you have an internet connection if (connected==False): print "bad internet connection" while connected: if config.make_gifs: try: file_to_upload = config.file_path + now + ".gif" client.create_photo(config.tumblr_blog, state="published", tags=[config.tagsForTumblr], data=file_to_upload) break except ValueError: print "Oops. No internect connection. Upload later." try: #make a text file as a note to upload the .gif later file = open(config.file_path + now + "-FILENOTUPLOADED.txt",'w') # Trying to create a new file or open one file.close() except: print('Something went wrong. Could not write file.') sys.exit(0) # quit Python else: # upload jpgs instead try: # create an array and populate with file paths to our jpgs myJpgs=[0 for i in range(4)] for i in range(4): myJpgs[i]=config.file_path + now + "-0" + str(i+1) + ".jpg" client.create_photo(config.tumblr_blog, state="published", tags=[config.tagsForTumblr], format="markdown", data=myJpgs) break except ValueError: print "Oops. No internect connection. Upload later." try: #make a text file as a note to upload the .gif later file = open(config.file_path + now + "-FILENOTUPLOADED.txt",'w') # Trying to create a new file or open one file.close() except: print('Something went wrong. Could not write file.') sys.exit(0) # quit Python ########################### Begin Step 4 ################################# input(pygame.event.get()) # press escape to exit pygame. Then press ctrl-c to exit python. try: display_pics(now) except Exception, e: tb = sys.exc_info()[2] traceback.print_exception(e.__class__, e, tb) pygame.quit() print "Done" if config.post_online: show_image(real_path + "/finished.png") else: show_image(real_path + "/finished2.png") time.sleep(restart_delay) show_image(real_path + "/intro.png"); GPIO.output(led_pin,True) #turn on the LED #################### ### Main Program ### #################### ## clear the previously stored pics based on config settings if config.clear_on_startup: clear_pics(1) print "Photo booth app running..." for x in range(0, 5): #blink light to show the app is running GPIO.output(led_pin,True) sleep(0.25) GPIO.output(led_pin,False) sleep(0.25) show_image(real_path + "/intro.png"); while True: GPIO.output(led_pin,True); #turn on the light showing users they can push the button input(pygame.event.get()) # press escape to exit pygame. Then press ctrl-c to exit python. GPIO.wait_for_edge(btn_pin, GPIO.FALLING) time.sleep(config.debounce) #debounce start_photobooth()
mit
yemrekeskin/IdentityKey
IdentityKey/IdentityKey/Areas/Admin/AdminAreaRegistration.cs
568
using System.Web.Mvc; namespace IdentityKey.Areas.Admin { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
mit
DAddYE/lipsiadmin
lib/view/helpers/ext/store.rb
3606
module Lipsiadmin#:nodoc: module Ext#:nodoc: # Generate a new Ext.data.GroupingStore # # Examples: # # var store = new Ext.data.GroupingStore({ # reader: new Ext.data.JsonReader({ # id:'id', # totalProperty:'count', root:'results', # fields:[{ # name: "accounts.name" # },{ # name: "accounts.categories.name" # },{ # type: "date", # renderer: Ext.util.Format.dateRenderer(), # name: "accounts.date", # dateFormat: "c" # },{ # type: "date", # renderer: Ext.util.Format.dateTimeRenderer(), # name: "accounts.datetime", # dateFormat: "c" # } ]}), # proxy: new Ext.data.HttpProxy({ url:'/backend/accounts.json' }), # remoteSort: true # }); # # grid.store do |store| # store.url "/backend/accounts.json" # store.add "accounts.name" # store.add "accounts.categories.name" # store.add "accounts.date", :type => :date # store.add "accounts.datetime", :type => :datetime # end # class Store < Component def initialize(options={}, &block)#:nodoc: @fields = [] super("Ext.data.GroupingStore", options) remoteSort true if config[:remoteSort].blank? baseParams("_method" => "GET") if config[:baseParams].blank? yield self if block_given? end # The url for getting the json data def url(value) @url = value end # This add automatically fields from an array def fields(fields) fields.each { |options| add_field(nil, options) } end # Add fields to a Ext.data.JsonReader # # Examples: # # { # type: "date", # renderer: Ext.util.Format.dateTimeRenderer(), # name: "accounts.datetime", # dateFormat: "c" # } # # add "accounts.datetime", :type => :datetime # def add_field(name=nil, options={})#:nodoc: options[:name] = name if name case options[:type] when :date then options.merge!({ :type => "date", :dateFormat => "Y-m-d" }) when :time_to_date then options.merge!({ :type => "date", :dateFormat => "c" }) when :datetime then options.merge!({ :type => "date", :dateFormat => "c" }) end raise ComponentError, "You must provide a Name for all fields" if options[:name].blank? @fields << Configuration.new(options) end # Return the javascript for create a new Ext.data.GroupingStore def to_s raise ComponentError, "You must provide the correct var the store." if get_var.blank? raise ComponentError, "You must provide the url for get the store data." if @url.blank? && config[:proxy].blank? raise ComponentError, "You must provide some fields for get build store." if @fields.blank? config[:proxy] = default_proxy if config[:proxy].blank? config[:reader] = default_reader if config[:reader].blank? super end private def default_proxy "new Ext.data.HttpProxy(#{Configuration.new(:url => @url).to_s(2)})".to_l end def default_reader options = { :id => "id", :totalProperty => "count", :root => "results", :fields => ("["[email protected] { |i| i.to_s(3) }.join(",")+"]").to_l } "new Ext.data.JsonReader(#{Configuration.new(options).to_s(2)})".to_l end end end end
mit
tiramizoo/oxid-plugin
copy_this/modules/oxtiramizoo/application/controllers/admin/oxtiramizoo_category_tab.php
3546
<?php /** * This file is part of the oxTiramizoo OXID eShop plugin. * * LICENSE: This source file is subject to the MIT license that is available * through the world-wide-web at the following URI: * http://opensource.org/licenses/mit-license.php * * @category module * @package oxTiramizoo * @author Tiramizoo GmbH <[email protected]> * @copyright Tiramizoo GmbH * @license http://opensource.org/licenses/mit-license.php MIT License */ /** * Admin category extended tiramizoo parameters manager. * Collects and updates (on user submit) extended category properties ( such as * weight, dimensions, enable tiramizoo delivery). * Admin Menu: Administer Products -> Category -> Tiramizoo. * * @extend oxAdminDetails * @package oxTiramizoo */ class oxTiramizoo_Category_Tab extends oxAdminDetails { /** * @var oxTiramizoo_CategoryExtended */ protected $_oTiramizooCategoryExtended = null; /** * @var array */ protected $_aEffectiveData = null; /** * @var oxCategory */ protected $_oCategory = null; /** * Getter method, returns oxTiramizoo_CategoryExtended object * * @return oxTiramizoo_CategoryExtended */ public function getTiramizooCategoryExtended() { return $this->_oTiramizooCategoryExtended; } /** * Getter method, returns array with article effective data * * @return array */ public function getEffectiveData() { return $this->_aEffectiveData; } /** * Getter method, returns oxCategory object * * @return oxCategory */ public function getCategory() { return $this->_oCategory; } /** * Loads category extended object data, passes it to Smarty engine and returns * name of template file "oxTiramizoo_category_tab.tpl". * * @extend oxAdminDetails::render * * @return string */ public function render() { // @codeCoverageIgnoreStart if (!defined('OXID_PHP_UNIT')) { parent::render(); } // @codeCoverageIgnoreEnd $this->_oCategory = oxNew( 'oxcategory' ); $soxId = $this->getConfig()->getRequestParameter( "oxid"); $oCategory = oxNew('oxCategory'); $oCategory->load($soxId); $oTiramizooCategoryExtended = oxNew('oxTiramizoo_CategoryExtended'); $oTiramizooCategoryExtended->load($oTiramizooCategoryExtended->getIdByCategoryId($soxId)); $this->_oTiramizooCategoryExtended = $oTiramizooCategoryExtended; $oArticleInheritedData = oxNew('oxTiramizoo_ArticleInheritedData'); $this->_aEffectiveData= $oArticleInheritedData->getCategoryEffectiveData($oCategory, true); return "oxTiramizoo_category_tab.tpl"; } /** * Saves category extended tiramizoo parameters. * * @return void */ public function save() { $soxId = $this->getConfig()->getRequestParameter( "oxid"); $aParams = $this->getConfig()->getRequestParameter( "oxTiramizooCategoryExtended"); if ( $soxId != "-1" && isset( $soxId ) ) { $this->_oTiramizooCategoryExtended = oxNew('oxTiramizoo_CategoryExtended'); $this->_oTiramizooCategoryExtended->load($this->_oTiramizooCategoryExtended->getIdByCategoryId($soxId)); $aParams['oxcategoryid'] = $soxId; $this->_oTiramizooCategoryExtended->assign( $aParams ); $this->_oTiramizooCategoryExtended->save(); } } }
mit
KaberMohamed/Symfony2015
src/Qcm/SalleTpBundle/QcmSalleTpBundle.php
128
<?php namespace Qcm\SalleTpBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class QcmSalleTpBundle extends Bundle { }
mit
net7/Dyno
javascripts/dyno.jquery.js
8782
/// Copyright (c) 2010 Net7 SRL, <http://www.netseven.it/> /// This Software is released under the terms of the MIT License /// See LICENSE.TXT for the full text of the license. (function($) { $.fn.dyno = function(settings) { var rowPrototype = null; /// Sources found during rendering, used to display /// a "limit result to sources" link. var sources = null; /// Default configuration. var config = { uris: [], values: null, source: null, lang: 'en', timeout: 30000, callback: null, callback_error: null }; /// Used to check for timeout in bridge requests. var timer = null; /// Called before querying for values and drawing the table. function onLoadStart() { $(".dyno-onload-show").hide(); $(".dyno-onload-hide").show(); $(".dyno-attribute").hide(); } /// Called after the table has been drawn. function onLoadEnd() { $(".dyno-attribute").show(); $(".dyno-onload-show").show(); $(".dyno-onload-hide").hide(); } /// Added to the names field of the table, 'predicate' is the RDF id of the property, /// while _name_ is it's label. function drawPredicate(predicate) { if(!predicate) return ''; return ' [<a class="dyno-predicate" alt="'+predicate+'" href="'+predicate+'">?</a>] '; } /// Added to each value in the table, even when values are grouped by property name. /// This is the one value in config.uris this property value is really about. function drawSource(source) { if(!source) return ''; return ' [<a class="dyno-source" alt="'+source+'" href="'+source+'">source?</a>] '; } /// Called is a value is defined as an image, for HTML formatting. function drawImage(data, filter) { if(filter && data.source != filter) return ''; var image = '<a target="_blank" href="' + data.url + '">'; image += '<img width="50" height="50" src="'+data.url+'" alt="'+data.text+'" title="'+data.text+'"/>'; image += '</a>' + drawSource(data.source); return image; }; /// Called is a value is defined as a link, for HTML formatting. function drawLink(data, filter) { if(filter && data.source != filter) return ''; return '<a target="_blank" href="'+data.url+'">'+data.text+'</a>' + drawSource(data.source) + '<br/>'; }; /// Called is a value is defined as text (this is the default), for HTML formatting. function drawText(data, filter) { if(filter && data.source != filter) return ''; return data.text + drawSource(data.source) + '<br/>'; }; /// Clones the template extracted from the HTML, fills it with one row of data, and appends /// the result back to the HTML. function addRow(element, name, value, predicate) { var temp = $(rowPrototype).clone(); $(".dyno-name p", temp).html(name+drawPredicate(predicate)); $(".dyno-value p", temp).html(value); temp.appendTo(element); }; /// Draws the table. function draw(values, element, source) { if(!values) return false; if(!rowPrototype) rowPrototype = $(".dyno-attribute", element).first().detach(); if(!rowPrototype.html()) return false; $("#dyno-title h1", element).text(values['title']); for(var i in values.rows) { var row = values.rows[i]; if(typeof row.value == 'string') row.value = [row.value]; if(typeof row.source == 'string') row.source = [row.source]; if(row.type == 'image') { var image = ''; for(var j = 0; j < row.value.length; j++) image += drawImage(row.value[j], source); if(image) addRow(element, row.name, image, row.url); } else if(row.type == 'link') { var link = ''; for(var j = 0; j < row.value.length; j++) link += drawLink(row.value[j], source); if(link) addRow(element, row.name, link, row.url); } else { var text = ''; for(var j = 0; j < row.value.length; j++) text += drawText(row.value[j], source); if(text) addRow(element, row.name, text, row.url); } } /// Now, unless this is not the first time we load, /// look around the table for sources, so we can build /// the sources filter section. if(!sources && $("#dyno-sources-list")) { sources = []; $(".dyno-source").map(function() { if(!sources[$(this).attr("href")]) sources[$(this).attr("href")] = 1; }); $("#dyno-sources-list").append('<a class="dyno-load-source" href="#">All</a> '); for(var source in sources) $("#dyno-sources-list").append(' <a class="dyno-load-source" href="' + source + '">' + source + '</a> '); $(".dyno-load-source").live("click", function(e) { $(".dyno-attribute").remove(); var source = $(this).attr("href") != '#' ? $(this).attr("href") : null; draw(values, element, source); singleResultSlide(); return false; }); } onLoadEnd(); if(config.callback) config.callback(); return true; } /// Utility, custom url-encode function. The default JS ones are not exactly what we need. function urlEncode(url) { return escape(url).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40') } /// Rewrites the querystring for the request to the bridge for the human-readable format: <url>/<param1>/<param2> etc. function altQuerystring(uris) { for(i in uris) uris[i] = urlEncode(uris[i]); return config.source+"/"+uris.join(',')+"/"+urlEncode(config.lang); } function timeout() { var message = "Timeout, " + (config.timeout/1000) + " seconds have passed and still no response from the server."; error('timeout', message); clearTimeout(timer); } /// Error handling: calls config.callback_error if defined or goes with the default (an alert dialog). function error(id, message) { if(config.callback_error) config.callback_error(id, message); else alert(message); onLoadEnd(); return false; } /// Some jQuery magic to set configuration from the user and use defaults if needed. if(settings) $.extend(config, settings); /// The main function of the plugin /// This is how you create a jQuery plugin. return this.each(function() { onLoadStart(); if(config.values) return draw(config.values, $(this)); var uris = config.uris && config.uris.length ? config.uris : [$(this).attr("rdf:about")]; if(!uris || !uris.length) return error('no_uris', 'No uri(s) requested'); if(typeof uris == 'string') uris = [uris]; var request = (config.altQuerystring) ? altQuerystring(uris) : config.source; var params = (config.altQuerystring) ? {} : {urls: uris.join(','), lang: config.lang}; var element = $(this); /// jQuery sucks at this, so let's try to setup a simple timeout handler. timer = setTimeout(timeout, config.timeout); /// TODO: need to add a "connection timeout" error. if(config.jsonp) { $.getJSON(request+"?callback=?", params, function(data) { clearTimeout(timer); if(data.error) return error('response_error', data.error); draw(data, element); }); } else { $.get(request, params, function(data) { clearTimeout(timer); if(data.error) return error('response_error', data.error); draw(data, element); }, 'json'); } }); }; })(jQuery);
mit
LanternPowered/LanternServer
src/main/java/org/lanternpowered/server/data/io/UserIO.java
4955
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data.io; import org.lanternpowered.server.data.DataQueries; import org.lanternpowered.server.data.io.store.ObjectStore; import org.lanternpowered.server.data.io.store.ObjectStoreRegistry; import org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils; import org.lanternpowered.server.entity.player.AbstractPlayer; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.UUID; public final class UserIO { private final static Path SPONGE_PLAYER_DATA_FOLDER = Paths.get("data", "sponge"); private final static Path PLAYER_DATA_FOLDER = Paths.get("playerdata"); private final static Path STATISTICS_FOLDER = Paths.get("stats"); private final static DataQuery NAME = DataQuery.of("Name"); public static boolean exists(Path dataFolder, UUID uniqueId) { final String fileName = uniqueId.toString() + ".dat"; final Path dataFile = dataFolder.resolve(PLAYER_DATA_FOLDER).resolve(fileName); return Files.exists(dataFile); } public static Optional<String> loadName(Path dataFolder, UUID uniqueId) throws IOException { final Path path = dataFolder.resolve(SPONGE_PLAYER_DATA_FOLDER).resolve(uniqueId.toString() + ".dat"); if (Files.exists(path)) { return NbtStreamUtils.read(Files.newInputStream(path), true).getString(NAME); } return Optional.empty(); } public static void load(Path dataFolder, AbstractPlayer player) throws IOException { final String fileName = player.getUniqueId().toString() + ".dat"; // Search for the player data and load it Path dataFile = dataFolder.resolve(PLAYER_DATA_FOLDER).resolve(fileName); if (Files.exists(dataFile)) { final DataContainer dataContainer = NbtStreamUtils.read(Files.newInputStream(dataFile), true); // Load sponge data if present and attach it to the main data dataFile = dataFolder.resolve(SPONGE_PLAYER_DATA_FOLDER).resolve(fileName); if (Files.exists(dataFile)) { final DataContainer spongeDataContainer = NbtStreamUtils.read(Files.newInputStream(dataFile), true); dataContainer.set(DataQueries.EXTENDED_SPONGE_DATA, spongeDataContainer); } final ObjectStore<AbstractUser> objectStore = ObjectStoreRegistry.get().get(AbstractUser.class).get(); objectStore.deserialize(player, dataContainer); } final Path statisticsFile = dataFolder.resolve(STATISTICS_FOLDER).resolve(player.getUniqueId().toString() + ".json"); if (Files.exists(statisticsFile)) { player.getStatisticMap().load(statisticsFile); } } public static void save(Path dataFolder, AbstractPlayer player) throws IOException { final String fileName = player.getUniqueId().toString() + ".dat"; final DataContainer dataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED); final ObjectStore<AbstractUser> objectStore = ObjectStoreRegistry.get().get(AbstractUser.class).get(); objectStore.serialize(player, dataContainer); final Optional<DataView> optSpongeData = dataContainer.getView(DataQueries.EXTENDED_SPONGE_DATA); dataContainer.remove(DataQueries.EXTENDED_SPONGE_DATA); Path dataFolder0 = dataFolder.resolve(PLAYER_DATA_FOLDER); if (!Files.exists(dataFolder0)) { Files.createDirectories(dataFolder0); } Path dataFile = dataFolder0.resolve(fileName); NbtStreamUtils.write(dataContainer, Files.newOutputStream(dataFile), true); dataFolder0 = dataFolder.resolve(SPONGE_PLAYER_DATA_FOLDER); if (!Files.exists(dataFolder0)) { Files.createDirectories(dataFolder0); } dataFile = dataFolder0.resolve(fileName); if (optSpongeData.isPresent()) { final DataView spongeData = optSpongeData.get(); spongeData.set(NAME, player.getName()); NbtStreamUtils.write(spongeData, Files.newOutputStream(dataFile), true); } else { Files.deleteIfExists(dataFile); } final Path statisticsFile = dataFolder.resolve(STATISTICS_FOLDER).resolve(player.getUniqueId().toString() + ".json"); player.getStatisticMap().save(statisticsFile); } private UserIO() { } }
mit
gdott9/the_moderator
spec/the_moderator/moderation_model_spec.rb
1102
require 'spec_helper' describe TheModerator::ModerationModel do subject do page = Page.new(name: 'Name', content: 'Content') moderation = page.moderate(:name) page.save moderation end describe '#accept' do it 'accepts moderated data' do expect(subject.moderatable.name).to be_nil subject.accept expect(subject.moderatable.name).to eq('Name') expect(subject.destroyed?).to be true end end describe '#discard' do it 'discards moderated data' do expect(subject.moderatable.name).to be_nil subject.discard expect(subject.moderatable.name).to be_nil expect(subject.destroyed?).to be true end end describe '#preview' do it 'previews moderated data' do expect(subject.moderatable.name).to be_nil preview = subject.preview expect(preview.frozen?).to be true expect(preview.name).to eq('Name') end end describe '#include?' do it 'includes name' do expect(subject.include?(:name)).to be true expect(subject.include?(:content)).to be false end end end
mit
FacticiusVir/SharpVk
src/SharpVk/Interop/NVidia/Experimental/VkPhysicalDeviceGetGeneratedCommandsPropertiesDelegate.gen.cs
1637
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.Interop.NVidia.Experimental { /// <summary> /// /// </summary> public unsafe delegate void VkPhysicalDeviceGetGeneratedCommandsPropertiesDelegate(SharpVk.Interop.PhysicalDevice physicalDevice, SharpVk.Interop.NVidia.Experimental.DeviceGeneratedCommandsFeatures* features, SharpVk.Interop.NVidia.Experimental.DeviceGeneratedCommandsLimits* limits); }
mit
andreas-eberle/settlers-remake
jsettlers.logic/src/main/java/jsettlers/logic/movable/strategies/specialists/PioneerStrategy.java
4937
/******************************************************************************* * Copyright (c) 2015 - 2017 * * 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. *******************************************************************************/ package jsettlers.logic.movable.strategies.specialists; import jsettlers.common.map.shapes.HexGridArea; import jsettlers.common.material.ESearchType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableAction; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.movable.EGoInDirectionMode; import jsettlers.logic.movable.Movable; import jsettlers.logic.movable.MovableStrategy; /** * * @author Andreas Eberle * */ public final class PioneerStrategy extends MovableStrategy { private static final long serialVersionUID = 1L; private static final float ACTION1_DURATION = 1.2f; private EPioneerState state = EPioneerState.JOBLESS; private ShortPoint2D centerPos; public PioneerStrategy(Movable movable) { super(movable); } @Override protected void action() { switch (state) { case JOBLESS: return; case GOING_TO_POS: if (centerPos == null) { this.centerPos = movable.getPos(); } if (canWorkOnPos(movable.getPos())) { super.playAction(EMovableAction.ACTION1, ACTION1_DURATION); state = EPioneerState.WORKING_ON_POS; } else { findWorkablePosition(); } break; case WORKING_ON_POS: if (canWorkOnPos(movable.getPos())) { executeAction(movable.getPos()); } findWorkablePosition(); break; } } private void findWorkablePosition() { EDirection closeForeignTileDir = getCloseForeignTile(); if (closeForeignTileDir != null && super.goInDirection(closeForeignTileDir, EGoInDirectionMode.GO_IF_ALLOWED_AND_FREE)) { this.state = EPioneerState.GOING_TO_POS; return; } centerPos = null; ShortPoint2D pos = movable.getPos(); if (super.preSearchPath(true, pos.x, pos.y, (short) 30, ESearchType.UNENFORCED_FOREIGN_GROUND)) { super.followPresearchedPath(); this.state = EPioneerState.GOING_TO_POS; } else { this.state = EPioneerState.JOBLESS; } } private EDirection getCloseForeignTile() { EDirection[] bestNeighbourDir = new EDirection[1]; double[] bestNeighbourDistance = new double[] { Double.MAX_VALUE }; // distance from start point ShortPoint2D position = movable.getPos(); HexGridArea.stream(position.x, position.y, 1, 6) .filter((x, y) -> super.isValidPosition(x, y) && canWorkOnPos(x, y)) .forEach((x, y) -> { double distance = ShortPoint2D.getOnGridDist(x - centerPos.x, y - centerPos.y); if (distance < bestNeighbourDistance[0]) { bestNeighbourDistance[0] = distance; bestNeighbourDir[0] = EDirection.getApproxDirection(position.x, position.y, x, y); } }); return bestNeighbourDir[0]; } private void executeAction(ShortPoint2D pos) { super.getGrid().changePlayerAt(pos, movable.getPlayer()); } private boolean canWorkOnPos(int x, int y) { return super.fitsSearchType(x, y, ESearchType.UNENFORCED_FOREIGN_GROUND); } private boolean canWorkOnPos(ShortPoint2D pos) { return super.fitsSearchType(pos, ESearchType.UNENFORCED_FOREIGN_GROUND); } @Override protected void moveToPathSet(ShortPoint2D oldPosition, ShortPoint2D oldTargetPos, ShortPoint2D targetPos) { this.state = EPioneerState.GOING_TO_POS; centerPos = null; } @Override protected boolean canBeControlledByPlayer() { return true; } @Override protected void stopOrStartWorking(boolean stop) { if (stop) { state = EPioneerState.JOBLESS; } else { state = EPioneerState.GOING_TO_POS; } } @Override protected void pathAborted(ShortPoint2D pathTarget) { state = EPioneerState.JOBLESS; } /** * Internal state of a {@link PioneerStrategy}. * * @author Andreas Eberle * */ private static enum EPioneerState { JOBLESS, GOING_TO_POS, WORKING_ON_POS } }
mit
scottohara/tvmanager
cypress/support/series.ts
114
export const seriesName = "#seriesName"; export const nowShowing = "#nowShowing"; export const moveTo = "#moveTo";
mit
smoogipoo/osu
osu.Game/Rulesets/Edit/Checks/CheckAudioInVideo.cs
4140
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.IO; using osu.Game.IO.FileAbstraction; using osu.Game.Rulesets.Edit.Checks.Components; using osu.Game.Storyboards; using TagLib; using File = TagLib.File; namespace osu.Game.Rulesets.Edit.Checks { public class CheckAudioInVideo : ICheck { public CheckMetadata Metadata => new CheckMetadata(CheckCategory.Audio, "Audio track in video files"); public IEnumerable<IssueTemplate> PossibleTemplates => new IssueTemplate[] { new IssueTemplateHasAudioTrack(this), new IssueTemplateMissingFile(this), new IssueTemplateFileError(this) }; public IEnumerable<Issue> Run(BeatmapVerifierContext context) { var beatmapSet = context.Beatmap.BeatmapInfo.BeatmapSet; var videoPaths = new List<string>(); foreach (var layer in context.WorkingBeatmap.Storyboard.Layers) { foreach (var element in layer.Elements) { if (!(element is StoryboardVideo video)) continue; // Ensures we don't check the same video file multiple times in case of multiple elements using it. if (!videoPaths.Contains(video.Path)) videoPaths.Add(video.Path); } } foreach (string filename in videoPaths) { string storagePath = beatmapSet.GetPathForFile(filename); if (storagePath == null) { // There's an element in the storyboard that requires this resource, so it being missing is worth warning about. yield return new IssueTemplateMissingFile(this).Create(filename); continue; } Issue issue; try { // We use TagLib here for platform invariance; BASS cannot detect audio presence on Linux. using (Stream data = context.WorkingBeatmap.GetStream(storagePath)) using (File tagFile = File.Create(new StreamFileAbstraction(filename, data))) { if (tagFile.Properties.AudioChannels == 0) continue; } issue = new IssueTemplateHasAudioTrack(this).Create(filename); } catch (CorruptFileException) { issue = new IssueTemplateFileError(this).Create(filename, "Corrupt file"); } catch (UnsupportedFormatException) { issue = new IssueTemplateFileError(this).Create(filename, "Unsupported format"); } yield return issue; } } public class IssueTemplateHasAudioTrack : IssueTemplate { public IssueTemplateHasAudioTrack(ICheck check) : base(check, IssueType.Problem, "\"{0}\" has an audio track.") { } public Issue Create(string filename) => new Issue(this, filename); } public class IssueTemplateFileError : IssueTemplate { public IssueTemplateFileError(ICheck check) : base(check, IssueType.Error, "Could not check whether \"{0}\" has an audio track ({1}).") { } public Issue Create(string filename, string errorReason) => new Issue(this, filename, errorReason); } public class IssueTemplateMissingFile : IssueTemplate { public IssueTemplateMissingFile(ICheck check) : base(check, IssueType.Warning, "Could not check whether \"{0}\" has an audio track, because it is missing.") { } public Issue Create(string filename) => new Issue(this, filename); } } }
mit
reflectoring/coderadar
coderadar-vcs/src/test/java/io/reflectoring/coderadar/adapter/ComputeContributorAdapterTest.java
2800
package io.reflectoring.coderadar.adapter; import io.reflectoring.coderadar.domain.Contributor; import io.reflectoring.coderadar.domain.DateRange; import io.reflectoring.coderadar.vcs.adapter.ComputeContributorAdapter; import java.io.File; import java.io.IOException; import java.net.URL; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.apache.tomcat.util.http.fileupload.FileUtils; import org.assertj.core.api.Assertions; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; class ComputeContributorAdapterTest { private URL testRepoURL = this.getClass().getClassLoader().getResource("test-repository"); @TempDir public File folder; @BeforeEach public void setup() throws GitAPIException { Git git = Git.cloneRepository().setURI(testRepoURL.toString()).setDirectory(folder).call(); git.close(); } @Test void test() { ComputeContributorAdapter computeContributorAdapter = new ComputeContributorAdapter(); List<Contributor> contributors = computeContributorAdapter.computeContributors( folder.getAbsolutePath(), new ArrayList<>(), new DateRange().setStartDate(LocalDate.MIN).setEndDate(LocalDate.MAX)); Assertions.assertThat(contributors.size()).isEqualTo(2); Assertions.assertThat(contributors.get(0).getDisplayName()).isEqualTo("Krause"); Assertions.assertThat(contributors.get(0).getNames()).containsExactly("Krause"); Assertions.assertThat(contributors.get(0).getEmailAddresses()) .containsExactly("[email protected]"); Assertions.assertThat(contributors.get(1).getDisplayName()).isEqualTo("maximAtanasov"); Assertions.assertThat(contributors.get(1).getNames()).containsExactly("maximAtanasov"); Assertions.assertThat(contributors.get(1).getEmailAddresses()) .containsExactly("[email protected]"); } @Test void contributorsNotCommitedInDateRangeAreNotAddedTest() { ComputeContributorAdapter computeContributorAdapter = new ComputeContributorAdapter(); List<Contributor> contributors = computeContributorAdapter.computeContributors( folder.getAbsolutePath(), new ArrayList<>(), new DateRange() .setStartDate(LocalDate.of(2019, 8, 5)) .setEndDate(LocalDate.of(2019, 8, 12))); Assertions.assertThat(contributors.get(0).getDisplayName()).isEqualTo("maximAtanasov"); Assertions.assertThat(contributors.size()).isEqualTo(1); } @AfterEach public void tearDown() throws IOException { FileUtils.deleteDirectory(folder); } }
mit
cs169-bizworld/bizworld-app
app/models/classroom.rb
2121
class Classroom < ActiveRecord::Base belongs_to :teacher has_many :students attr_accessible :class_type, :end_date, :name, :program, :start_date, :link, :short_link validates_presence_of :teacher, :class_type, :name TEST_URLS = {'pre' => 'https://docs.google.com/forms/d/18fGk0NX-z_Slad4WvlpPQFAugEsRoyVqpcscx6o8cdM/viewform?', 'post' => 'https://docs.google.com/forms/d/1H7Wwbo8mTbnKpCwMr231ZjWixIUo6sHXm0M431vwHU0/viewform?'} def get_short_link(test_type) bitly = Bitly.client bitly.shorten(self.get_link(test_type)).short_url end def get_link(test_type) teacher = self.teacher params = { 'entry.1019834039' => teacher.name, 'entry.56447872' => teacher.city, 'entry.1968199897' => teacher.state, 'entry.1945527637' => self.id.to_s, 'entry.514626172' => teacher.id.to_s } Classroom.replace_space(TEST_URLS[test_type] + params.to_query) end def self.replace_space(line) if line != nil line.gsub /( |%20)/, '+' end end def create_students(student_names) valid_students = [] invalid_students = [] for student_name in student_names first_and_last = student_name.split(" ") if first_and_last.size < 2 invalid_students << student_name else valid_students << student_name first_name = first_and_last[0] last_name = first_and_last[1] self.students.create(:first_name => first_name, :last_name => last_name) end end return valid_students, invalid_students end def to_csv_score_overview CSV.generate do |csv| csv << ['First Name', 'Last Name', 'School Name', 'Teacher Name', 'City Name', 'State', 'Grade', 'Gender', 'Ethnicity', 'Pre-score', 'Post-score'] self.students.each do |student| csv << [student.first_name, student.last_name, student.school_name, student.teacher_name, student.city_name, student.state, student.grade, student.gender, student.ethnicity, student.get_survey_score('pre'), student.get_survey_score('post')] end end end end
mit
AmineEch/BrainCNN
brainNetCNN.py
3075
from __future__ import print_function, division import matplotlib.pyplot as plt plt.interactive(False) import tensorflow as tf import h5py from scipy.stats import pearsonr from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import Dense, Dropout, Flatten from keras.layers.advanced_activations import LeakyReLU from keras import optimizers, callbacks, regularizers, initializers from E2E_conv import * from utils import * from injury import ConnectomeInjury batch_size = 14 dropout = 0.5 momentum = 0.9 lr = 0.01 decay = 0.0005 noise_weight = 1 reg = regularizers.l2(decay) kernel_init = initializers.he_uniform() # Loading synthetic data injuryconnectome = ConnectomeInjury() x_train,y_train = injuryconnectome.generate_injury(n_samples=1000,noise_weight=noise_weight) x_valid,y_valid = injuryconnectome.generate_injury(n_samples=300,noise_weight=noise_weight) # ploting a sample #plt.imshow(x_train[0][0]) #plt.show() # reshaping data x_train = x_train.reshape(x_train.shape[0],x_train.shape[3],x_train.shape[2],x_train.shape[1]) x_valid = x_valid.reshape(x_valid.shape[0],x_valid.shape[3],x_valid.shape[2],x_valid.shape[1]) print(x_train) # Model architecture model = Sequential() model.add(E2E_conv(2,32,(2,90),kernel_regularizer=reg,input_shape=(90,90,1),input_dtype='float32',data_format="channels_last")) print("First layer output shape :"+str(model.output_shape)) model.add(LeakyReLU(alpha=0.33)) #print(model.output_shape) model.add(E2E_conv(2,32,(2,90),kernel_regularizer=reg,data_format="channels_last")) print(model.output_shape) model.add(LeakyReLU(alpha=0.33)) model.add(Convolution2D(64,(1,90),kernel_regularizer=reg,data_format="channels_last")) model.add(LeakyReLU(alpha=0.33)) model.add(Convolution2D(256,(90,1),kernel_regularizer=reg,data_format="channels_last")) model.add(LeakyReLU(alpha=0.33)) #print(model.output_shape) model.add(Dropout(0.5)) model.add(Dense(128,kernel_regularizer=reg,kernel_initializer=kernel_init)) #print(model.output_shape) model.add(LeakyReLU(alpha=0.33)) #print(model.output_shape) model.add(Dropout(0.5)) model.add(Dense(30,kernel_regularizer=reg,kernel_initializer=kernel_init)) model.add(LeakyReLU(alpha=0.33)) #print(model.output_shape) model.add(Dropout(0.5)) model.add(Dense(2,kernel_regularizer=reg,kernel_initializer=kernel_init)) model.add(Flatten()) model.add(LeakyReLU(alpha=0.33)) model.summary() #print(model.output_shape) opt = optimizers.SGD(momentum=momentum,nesterov=True,lr=lr) model.compile(optimizer=opt,loss='mean_squared_error',metrics=['mae']) csv_logger = callbacks.CSVLogger('BrainCNN.log') command = str(raw_input("Train or predict ? [t/p]")) if command == "t": print("Training for noise = "+str(noise_weight)) history=model.fit(x_train,y_train,nb_epoch=1000,verbose=1,callbacks=[csv_logger]) model.save_weights("Weights/BrainCNNWeights_noise_"+str(noise_weight)+".h5") else: print("[*] Predicting and printing results for the models trained :") get_results_from_models(model,noises = [0,0.0625,0.125,0.25])
mit
cccqcn/php
svnhook_async/update-ftp.php
7801
<?php //----------------------------- // ¸Ã°æ±¾ÎªÒì²½ÉÏ´«£¬¸ÃÎļþÓÐftpÉÏ´«Ê§°ÜÈÝ´í£¬½«±£´æºÃµÄsvn¸üмǼÉÏ´«µ½ftp //----------------------------- // ³õʼ»¯ÉèÖà //----------------------------- date_default_timezone_set('PRC'); require_once("post-commit-param.php"); $config = unserialize(file_get_contents(dirname(__FILE__)."/cache.ca")); if(!isset($config) || empty($config)) { $config = array("dataIndex"=>1,); } echo "ÉÏ´«µ½FTP·þÎñÆ÷"; $result = uploadSvnArray(); while($result == false) { echo "ÉÏ´«Öжϣ¬10Ãëºó¼ÌÐøÉÏ´«"; usleep(10000000); $result = uploadSvnArray(); } function uploadSvnArray() { global $SvnHookArrayTxt, $SvnHookTest; $arrayIndex = file_get_contents(dirname(__FILE__)."/arrayIndex.ca"); $ftp_array_txtfile="{$SvnHookArrayTxt}{$arrayIndex}.txt"; //Ö´ÐиüеÄÎļþ file_put_contents($SvnHookTest, "\r\n".$arrayIndex."\r\n".$ftp_array_txtfile); $arrayTxt = file_get_contents($ftp_array_txtfile); $array = explode("\r\n", $arrayTxt); $result = update_to_ftp($array); return $result; } function updateLog($str) { global $SvnHookData; $fh = fopen($SvnHookData, "w"); fwrite($fh, $str); fclose($fh); } /** * ÔÚFTP·þÎñÆ÷ÉÏ´´½¨Ä¿Â¼ * * @author terry39 */ function ftp_create_dir($path) { global $ftp; $dir=split("/", $path); $path=""; $ret = true; for ($i=0;$i<count($dir);$i++) { $path.="/".$dir[$i]; if(!@ftp_chdir($ftp,$path)) { @ftp_chdir($ftp,"/"); if(!@ftp_mkdir($ftp,$path)) { $ret=false; break; } } } return $ret; } /** * ɾ³ý FTP ÖÐÖ¸¶¨µÄĿ¼ * * @param resource $ftp_stream The link identifier of the FTP connection * @param string $directory The directory to delete * * @author terry39 */ function ftp_rmdirr($ftp_stream, $directory) { if (!is_resource($ftp_stream) || get_resource_type($ftp_stream) !== 'FTP Buffer') { return false; } // Init $i = 0; $files = array(); $folders = array(); $statusnext = false; $currentfolder = $directory; // Get raw file listing $list = ftp_rawlist($ftp_stream, $directory, true); foreach ($list as $current) { if (empty($current)) { $statusnext = true; continue; } if ($statusnext === true) { $currentfolder = substr($current, 0, -1); $statusnext = false; continue; } $split = preg_split('[ ]', $current, 9, PREG_SPLIT_NO_EMPTY); $entry = $split[8]; $isdir = ($split[0]{0} === 'd') ? true : false; // Skip pointers if ($entry === '.' || $entry === '..') { continue; } if ($isdir === true) { $folders[] = $currentfolder . '/' . $entry; } else { $files[] = $currentfolder . '/' . $entry; } } foreach ($files as $file) { ftp_delete($ftp_stream, $file); } rsort($folders); foreach ($folders as $folder) { ftp_rmdir($ftp_stream, $folder); } return ftp_rmdir($ftp_stream, $directory); } /** * °Ñ¸üе½µÄÎļþÁбíÉÏ´«µ½·þÎñÆ÷ÉÏ * * ¸üеÄͬʱ¼Ç¼¸üÐÂÈÕÖ¾£¬Èç¹ýÓÐÒ»¸öÎļþ»òÕßĿ¼¸üÐÂʧ°Ü£¬Ôò·µ»Ø´íÎó * * @param array $update_list * @return bool * * @author terry39 */ function update_to_ftp($update_list) { global $SvnHookArrayTxt, $argv, $ftp, $author_name, $TMP_UPDATE_DIR, $fileSize, $config, $isPasv, $ftp_ip, $ftp_port, $ftp_username , $ftp_pass, $log_name; $dataIndex = $config["dataIndex"]; $newstr = ""; $ftp_update_logfile="{$log_name}{$dataIndex}.log"; //Ö´ÐиüеÄÈÕÖ¾Îļþ if(file_exists($ftp_update_logfile)) { if(filesize($ftp_update_logfile) >= $fileSize ) {//´óС³¬¹ý10M,ÖØÐÂдÈÕÖ¾Îļþ $dataIndex++; $config["dataIndex"] = $dataIndex; $ftp_update_logfile="{$log_name}{$dataIndex}.log"; //ÖØÐÂÖ´ÐиüеÄÈÕÖ¾Îļþ $contnet = serialize($config); file_put_contents(dirname(__FILE__)."/cache.ca",$contnet); } } $ftp_root_dir = '/'; //·þÎñÆ÷ÉϵĵØÖ·Ô´Âë¶ÔÓ¦µÄÆðʼĿ¼ $log = ""; $log .= date('Y-m-d H:i:s') . " BEGIN UPDATE TO FTP\n"; # $ftp = ftp_connect('192.168.0.163','5000'); $ftp = ftp_connect($ftp_ip,$ftp_port); $ftp_login = ftp_login($ftp, $ftp_username, $ftp_pass); $result = true; $connectSuccess = false; if($ftp && $ftp_login){ $connectSuccess = true; $log .= date('Y-m-d H:i:s') . " Connected to FTP Server Success\n"; if($isPasv){ ftp_pasv($ftp, true); } $isBreaked = false; $total = count($update_list); $current = 0; foreach($update_list as $file_cmd){ $current++; if($isBreaked == true || $file_cmd == '' || substr($file_cmd, 0, 8) == 'Updating' || substr($file_cmd, 0, 6) == 'Update' || substr($file_cmd, 0, 6) == 'Finish') { if($file_cmd != '') { $newstr = $newstr."\r\n".$file_cmd; echo $file_cmd."(".$current."/".$total.")"."\n"; } continue; //ÕâÀïÓÐ×îºóÒ»ÐÐµÄ Update Reversion NNN ÒªºöÂÔ } $file_cmd = trim($file_cmd); $cmd = substr($file_cmd, 0, 1); $file = trim(substr($file_cmd, 1)); $log .= date('Y-m-d H:i:s') . " file_cmd: {$file_cmd} \n"; $from = $file; $file = substr($file, strlen($TMP_UPDATE_DIR) + 1); //È¥µô·¾¶ÖеĿªÍ· $TMP_UPDATE_DIR ·¾¶ $tempExplode = explode('/', $file); $tempArrayPop = array_pop($tempExplode); $filename = is_dir($from) ? null : $tempArrayPop; $to = $ftp_root_dir . str_replace("\\", "/", $file); //¼ÆËã³ö·¾¶²¢´´½¨FTPĿ¼ (Èç¹û²»´æÔڵϰ) $dir = is_dir($from) ? $to : dirname($to); if(!@ftp_chdir($ftp,$dir)){ $log .= date('Y-m-d H:i:s') . " FTP_MKD\t{$dir}\n"; echo "creatingdir ".$dir."\n"; ftp_create_dir($dir); //´´½¨Ä¿Â¼ } if(is_dir($from)) continue; $rrr = false; //¸üлò´´½¨Îļþ if($cmd == "U" || $cmd == "A"){ echo "uploading ".$file_cmd."\n"; $rrr = ftp_put($ftp, $to, $from, FTP_BINARY); $result = $result && $rrr; //¼Ç¼ÈÕÖ¾ $log .= date('Y-m-d H:i:s') . " FTP_PUT\t{$from}\t{$to}" . ($rrr ? "\tSUCCESS\n" : "\tFALSE\n"); if($rrr == false) {//Èç¹ûÉÏ´«Ê§°Ü£¬²»ÔÙ¼ÌÐøÉÏ´« $isBreaked = true; } //ɾ³ýÎļþ»òĿ¼ }else if($cmd == "D"){ //------------------------------- // ÕâÀïÒªÅжÏÄ¿±êÊÇĿ¼»¹ÊÇÎļþ //------------------------------- if(@ftp_chdir($ftp,$to)){ echo "removingdir ".$file_cmd."\n"; $rrr = ftp_rmdirr($ftp, $to); $log .= date('Y-m-d H:i:s') . " FTP_RMD\t{$to}" . ($rrr ? "\tSUCCESS\n" : "\tFALSE\n"); }else{ echo "deleting ".$file_cmd."\n"; $rrr = ftp_delete($ftp, $to); $rrr = true; $result = $result && $rrr; //¼Ç¼ÈÕÖ¾ $log .= date('Y-m-d H:i:s') . " FTP_DEL\t{$to}" . ($rrr ? "\tSUCCESS\n" : "\tFALSE\n"); } }else{ $log .= date('Y-m-d H:i:s') . " UNKNOWN CMD\t{$cmd}\n"; } echo ($rrr ? "\tSUCCESS" : "\tFALSE")."(".$current."/".$total.")\n"; if($rrr) { $newstr = $newstr."\r\nFinished ".$file_cmd; } else { $newstr = $newstr."\r\n".$file_cmd; } } }else{ $log .= date('Y-m-d H:i:s') . " Connected to FTP Server False\n"; $log .= date('Y-m-d H:i:s') . " UPDATE FALSE\n"; $log .= date('Y-m-d H:i:s') . " QUIT UPDATE\n\n"; //return false; } //¼Ç¼×îºóÒ»´Î¸üгɹ¦µÄ°æ±¾ if($result){ $log .= date('Y-m-d H:i:s') . " UPDATE SUCCESS\n"; }else{ $log .= date('Y-m-d H:i:s') . " UPDATE FALSE\n"; } $log .= date('Y-m-d H:i:s') . " END UPDATE\n\n"; $arrayIndex = file_get_contents(dirname(__FILE__)."/arrayIndex.ca"); $ftp_array_txtfile="{$SvnHookArrayTxt}{$arrayIndex}.txt"; //Ö´ÐиüеÄÎļþ file_put_contents($ftp_update_logfile, $log, FILE_APPEND); if($connectSuccess){ file_put_contents($ftp_array_txtfile, $newstr); } return $result; } ?>
mit
indus/gluex
src/test.ts
4953
'use strict'; declare var describe; declare var it; var expect = require('chai').expect; var fs = require('fs-extra'); var gluex = require('../index'); describe('#REGEX', function () { var REGEX = gluex.REGEX; it('should find HTML comment', function () { var ns = undefined; var file = `file.html`; var sel = undefined; var string = `<!-- @gluex ${file} -->`; var match = REGEX.exec(`</some>${string} <other>`); expect(match).to.not.be.undefined; expect(match[0]).to.equal(string); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); it('should find JS line comment', function () { var ns = undefined; var file = `file.js`; var sel = undefined; var string = `// @gluex ${file}`; var match = REGEX.exec(`var some;${string} var other;`); expect(match).to.not.be.undefined; expect(match[0].trim()).to.equal(string.trim()); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); it('should find JS block comment', function () { var ns = undefined; var file = `file.js`; var sel = undefined; var string = `/* @gluex ${file} */`; var match = REGEX.exec(`var some;${string} var other;`); expect(match).to.not.be.undefined; expect(match[0]).to.equal(string); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); it('should find HTML comment with namespace & selector', function () { var ns = "dev"; var file = `./test/file.html`; var sel = "#comp"; var string = `<!-- @gluex${ns ? ':' + ns : ''} ${file} ${sel ? '(' + sel + ')' : ''} -->`; var match = REGEX.exec(`</some>${string} <other>`); expect(match).to.not.be.undefined; expect(match[0]).to.equal(string); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); it('should find JS line comment with namespace & selector', function () { var ns = "dev"; var file = `./test/file.json`; var sel = ".prop"; var string = `// @gluex${ns ? ':' + ns : ''} ${file} ${sel ? '(' + sel + ')' : ''}`; var match = REGEX.exec(`var some;${string} var other;`); expect(match).to.not.be.undefined; expect(match[0].trim()).to.equal(string.trim()); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); it('should find JS block comment with namespace & selector', function () { var ns = "dev"; var file = `./test/file.json`; var sel = ".prop"; var string = `/* @gluex${ns ? ':' + ns : ''} ${file} ${sel ? '(' + sel + ')' : ''} */`; var match = REGEX.exec(`var some;${string} var other;`); expect(match).to.not.be.undefined; expect(match[0]).to.equal(string); expect(match[1]).to.equal(ns); expect(match[2]).to.equal(file); expect(match[3]).to.equal(sel); }); }) describe('#GLUEX', function () { it(`should glue example0`, function () { var input = `test/example0/index.html`, output = `test/example0/index_gluex.html`, test = `test/example0/index_test.html`; gluex(input, output); expect(fs.readFileSync(test, 'utf8')).to.equal(fs.readFileSync(output, 'utf8')); expect(fs.readFileSync(test, 'utf8')).to.equal(gluex(input)); }); it(`should glue example1`, function () { var input = `test/example1/index.html`, output = `test/example1/index_gluex.html`, test = `test/example1/index_test.html`; gluex(input, output); expect(fs.readFileSync(test, 'utf8')).to.equal(fs.readFileSync(output, 'utf8')); expect(fs.readFileSync(test, 'utf8')).to.equal(gluex(input)); }); it(`should glue example2`, function () { var input = `test/example2/index.html`, output = `test/example2/index_gluex.html`, test = `test/example2/index_test.html`; gluex(input, output); expect(fs.readFileSync(test, 'utf8')).to.equal(fs.readFileSync(output, 'utf8')); expect(fs.readFileSync(test, 'utf8')).to.equal(gluex(input)); }); it(`should glue example3`, function () { var input = `test/example3/index.html`, output = `test/example3/index_gluex.html`, test = `test/example3/index_test.html`; gluex(input, output,'dev'); expect(fs.readFileSync(test, 'utf8')).to.equal(fs.readFileSync(output, 'utf8')); expect(fs.readFileSync(test, 'utf8')).to.equal(gluex(input,null,'dev')); }); })
mit
PagerDuty/whazzup
spec/app_spec.rb
2621
ENV['RACK_ENV'] = 'test' require 'app' require 'rspec' require 'rack/test' describe 'Galera health check' do include Rack::Test::Methods def app Whazzup.new end def db_client @db_client ||= Mysql2::Client.new(Whazzup.connection_settings) end before do Whazzup.set(:wsrep_state_dir, 'spec/data/3_node_cluster_synced') Whazzup.set(:hostname, 'test.local') end it 'should require and initialize checkers, and make a first check' do Whazzup.set(:services, [:xdb]) expect_any_instance_of(Whazzup).to receive(:require_relative).with 'lib/checkers/galera_health_checker' service_checker_class = double expect(Whazzup::SERVICE_CHECKERS[:xdb]).to receive(:constantize) { service_checker_class } expect(service_checker_class).to receive(:new) health_checker = double expect(HealthChecker).to receive(:new).once { health_checker } expect(health_checker).to receive(:check).once app end it 'should be marked up if it is a a synced node' do get '/xdb' expect(last_response.status).to be(200) end it 'should be marked down if it is a donor node' do Whazzup.set(:wsrep_state_dir, 'spec/data/3_node_cluster_donor') get '/xdb' expect(last_response.status).to be(503) end it 'should be marked up if it is a donor node in a 2 node cluster' do Whazzup.set(:wsrep_state_dir, 'spec/data/2_node_cluster_donor') get '/xdb' expect(last_response.status).to be(200) end it 'should be marked down if the wsrep state files cannot be read' do Whazzup.set(:wsrep_state_dir, 'does/not/exist') get '/xdb' expect(last_response.status).to be(503) end it 'should be marked down if it is marked down in the database' do begin db_client.query("update state set available = 0 where host_name = 'test.local'") get '/xdb' expect(last_response.status).to be(503) ensure db_client.query("update state set available = 1 where host_name = 'test.local'") end end it 'should be marked down if no row is found for the desired host in the DB' do Whazzup.set(:hostname, 'does.not.exist') get '/xdb' expect(last_response.status).to be(503) end it 'should be marked down if there is trouble connecting to the database' do allow_any_instance_of(Mysql2::Client).to receive(:query).and_raise(Mysql2::Error, 'mocking connection failure') get '/xdb' expect(last_response.status).to be(503) end it 'should support the OPTIONS method for checking health (HAProxy default method)' do options '/xdb' expect(last_response.status).to be(200) end end
mit
CS2103JAN2017-W14-B4/main
src/test/java/seedu/ezdo/storage/XmlFileStorageTest.java
1057
package seedu.ezdo.storage; import java.io.File; import java.io.FileNotFoundException; import javax.xml.bind.JAXBException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import mockit.Mock; import mockit.MockUp; import mockit.integration.junit4.JMockit; import seedu.ezdo.commons.util.XmlUtil; //@@author A0139248X @RunWith(JMockit.class) public class XmlFileStorageTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void saveDataToFile_JAXBException_throwAssertionError() throws Exception { thrown.expect(AssertionError.class); File file = new File("omg"); XmlSerializableEzDo ezDo = new XmlSerializableEzDo(); new MockUp<XmlUtil>() { @Mock <T> void saveDataToFile(File file, T data) throws FileNotFoundException, JAXBException { throw new JAXBException("exception"); } }; XmlFileStorage.saveDataToFile(file, ezDo); } }
mit
cold-brew-coding/protagonist
src/v8_wrapper.cc
2148
#include "v8_wrapper.h" using namespace v8; using namespace protagonist; // Forward declarations static Local<Value> v8_wrap_null(); static Local<Value> v8_wrap_string(const std::string& value); static Local<Value> v8_wrap_number(double value); static Local<Value> v8_wrap_boolean(bool value); static Local<Value> v8_wrap_array(const sos::Base& value); static Local<Value> v8_wrap_object(const sos::Base& value); // Wrap interface Local<Value> protagonist::v8_wrap(const sos::Base& base) { switch (base.type) { case sos::Base::StringType: return v8_wrap_string(base.str); case sos::Base::NumberType: return v8_wrap_number(base.number); case sos::Base::BooleanType: return v8_wrap_boolean(base.boolean); case sos::Base::ArrayType: return v8_wrap_array(base); case sos::Base::ObjectType: return v8_wrap_object(base); case sos::Base::NullType: default: return v8_wrap_null(); } } Local<Value> v8_wrap_null() { return Nan::Null(); } Local<Value> v8_wrap_string(const std::string& value) { return Nan::New<String>(value.c_str()).ToLocalChecked(); } Local<Value> v8_wrap_number(double value) { return Nan::New<Number>(value); } Local<Value> v8_wrap_boolean(bool value) { return Nan::New<Boolean>(value); } Local<Value> v8_wrap_array(const sos::Base& value) { Local<Array> wrappedArray = Nan::New<Array>(); size_t i = 0; for (sos::Bases::const_iterator it = value.array().begin(); it != value.array().end(); ++i, ++it) { Local<Value> arrayElement = v8_wrap(*it); wrappedArray->Set(i, arrayElement); } return wrappedArray; } Local<Value> v8_wrap_object(const sos::Base& value) { Local<Object> wrappedObject = Nan::New<Object>(); size_t i = 0; for (sos::Keys::const_iterator it = value.keys.begin(); it != value.keys.end(); ++i, ++it) { Local<Value> propertyValue = v8_wrap(value.object().at(*it)); wrappedObject->Set(v8_wrap_string(*it), propertyValue); } return wrappedObject; }
mit
urasandesu/Prig.Samples
12.ThreeOrMoreOutRef/ThreeOrMoreOutRefTest/Properties/AssemblyInfo.cs
1418
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ThreeOrMoreOutRefTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ThreeOrMoreOutRefTest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5154cb02-b93b-4140-9bc3-e828ea520669")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
hecateball/mastodon4j
src/main/java/mastodon4j/entity/ClientCredential.java
1344
package mastodon4j.entity; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * @author hecateball */ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class ClientCredential implements Serializable { private static final long serialVersionUID = 9120028367155631262L; @XmlElement(name = "id") private long id; @XmlElement(name = "redirect_uri") private String redirectUri; @XmlElement(name = "client_id") private String clientId; @XmlElement(name = "client_secret") private String clientSecret; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } }
mit
umutozel/QueryableProjector
QueryableProjector.Tests/Model/Company.cs
168
namespace QueryableProjector.Tests.Model { public abstract class Company { public int Id { get; set; } public string Name { get; set; } } }
mit
aileisun/bubbleimg
bubbleimg/obsobj/test/test_obsobj.py
2121
# test_obsobj.py # ALS 2017/05/16 import pytest import os import shutil from ..obsobj import obsObj ra = 150.0547735 dec = 12.7073027 dir_obj = './testing/SDSSJ1000+1242/' dir_parent = './testing/' @pytest.fixture(scope="module", autouse=True) def setUp_tearDown(): """ rm ./testing/ and ./test2/ before and after testing""" # setup if os.path.isdir(dir_parent): shutil.rmtree(dir_parent) yield # tear down if os.path.isdir(dir_parent): shutil.rmtree(dir_parent) @pytest.fixture def obj_dirobj(): return obsObj(ra=ra, dec=dec, dir_obj = dir_obj) @pytest.fixture def obj_hscobj(): ra = 140.099341430207 dec = 0.580162492432517 dir_obj = './testing/SDSSJ0920+0034/' return obsObj(ra=ra, dec=dec, dir_obj=dir_obj) def test_obsObj_init_dir_obj(obj_dirobj): obj = obj_dirobj assert isinstance(obj, obsObj) assert obj.dir_obj == dir_obj assert hasattr(obj, 'ra') assert hasattr(obj, 'dir_obj') assert hasattr(obj, 'name') assert obj.name == obj.dir_obj.split('/')[-2] def test_obsObj_init_dir_parent(): obj = obsObj(ra=ra, dec=dec, dir_parent = dir_parent) assert isinstance(obj, obsObj) assert obj.dir_obj == dir_obj def test_obsObj_add_sdss(obj_dirobj): obj = obj_dirobj status = obj.add_sdss() assert status assert round(obj.sdss.ra, 4) == round(obj.ra, 4) assert round(obj.sdss.dec, 4) == round(obj.dec, 4) assert hasattr(obj.sdss, 'xid') assert hasattr(obj.sdss, 'photoobj') def test_obsObj_add_sdss_fail(): ra = 0. dec = -89. obj = obsObj(ra=ra, dec=dec, dir_parent = dir_parent) status = obj.add_sdss() assert status == False assert obj.sdss.status == False def test_obsObj_add_hsc(obj_hscobj): obj = obj_hscobj status = obj.add_hsc() assert status assert round(obj.hsc.ra, 2) == round(obj.ra, 2) assert round(obj.hsc.dec, 2) == round(obj.dec, 2) assert hasattr(obj.hsc, 'xid') assert hasattr(obj.hsc, 'tract') assert hasattr(obj.hsc, 'patch') def test_obsObj_add_hsc_fail(): ra = 0. dec = -89. obj = obsObj(ra=ra, dec=dec, dir_parent = dir_parent) status = obj.add_hsc() assert status == False assert obj.hsc.status == False
mit
kassisdion/Android-animated-toolbar
app/src/main/java/com/kassisdion/animatedToolbar/demo/activity/MainActivity.java
874
package com.kassisdion.animatedToolbar.demo.activity; import com.kassisdion.animatedToolbar.R; import com.kassisdion.animatedToolbar.demo.fragment.MainActivityFragment; import com.kassisdion.lib.toolbar.AnimatedToolbar; import android.os.Bundle; import butterknife.Bind; public class MainActivity extends BaseAppCompatActivity { @Bind(R.id.toolbar) AnimatedToolbar mToolbar; /* ** Life cycle */ @Override protected int getLayoutResource() { return R.layout.activity_main; } @Override protected void init(Bundle savedInstanceState) { setUpToolbar(); MainActivityFragment.load(getSupportFragmentManager(), false); } /* ** Utils */ private void setUpToolbar() { setSupportActionBar(mToolbar); } public AnimatedToolbar getToolbar() { return mToolbar; } }
mit
jonaseck2/staxtest
src/main/java/Demo.java
2404
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.util.Stack; import java.util.stream.Collectors; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; @SuppressWarnings("restriction") public class Demo { public static void main(String[] args) throws Exception { new Demo().split("src/main/resources/test.xml"); } private void split(String xmlResource) throws Exception { XMLEventFactory eventFactory = XMLEventFactory.newFactory(); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader reader = inputFactory .createXMLEventReader(new FileReader(xmlResource)); StartElement rootElement = reader.nextTag().asStartElement(); StartDocument startDocument = eventFactory.createStartDocument(); EndDocument endDocument = eventFactory.createEndDocument(); XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(out); eventWriter.add(startDocument); eventWriter.add(rootElement); FileOutputStream os = new FileOutputStream(new File("target/out.xml")); Stack<String> elementPath = new Stack<String>(); elementPath.push(getElementName(rootElement.getName())); while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); elementPath.push(getElementName(startElement.getName())); } else if (xmlEvent.isEndElement()) { elementPath.pop(); } eventWriter.add(xmlEvent); } eventWriter.add(endDocument); try { os.write(out.toByteArray()); } finally { os.close(); } } private static String getElementName(QName name) { StringBuilder builder = new StringBuilder(); if (name.getPrefix() != null) { builder.append(name.getPrefix()); builder.append(":"); } builder.append(name.getLocalPart()); return builder.toString(); } }
mit
Valpineware/ValpineCompiler
Src/Tests/.Ext/Graph.cpp
4384
#include "Graph.h" namespace ext { Statement* addStatement(Block &block, Statement *statement) { block.appendStatement(statement); return statement; } Preprocessor* addPreprocessor(Block &block, Preprocessor *preprocessor) { block.appendStatement(preprocessor); return preprocessor; } Class* addClass(Block &block, Class *cls) { block.appendStatement(cls); return cls; } ControlStructure* addControlStructure(Block &block, ControlStructure *controlStructure) { block.appendStatement(controlStructure); return controlStructure; } Expression* addExpression(Block &block, Expression *expression) { block.appendStatement(expression); return expression; } Function* addFunction(Block &block, Function *function) { block.appendStatement(function); return function; } Variable* addVariable(Block &block, Variable *variable) { block.appendStatement(variable); return variable; } void assertEqualBlock(const Block &expected, const Block &actual); void assertEqualStatement(Statement *expected, Statement *actual); void assertEqualPreprocessor(Preprocessor *expected, Preprocessor *actual) { Expect::EqStr(expected->verbatim(), actual->verbatim()); } void assertEqualClass(Class *expected, Class *actual) { Expect::EqStr(expected->id(), actual->id()); auto assertAccessIdPair = [](const Class::AccessIdPair &lhs, const Class::AccessIdPair &rhs) -> void { Expect::EqStr(lhs.id, rhs.id); Expect::Eq(lhs.accessType, rhs.accessType); }; assertSameLists<Class::AccessIdPair>(expected->superClasses(), actual->superClasses(), assertAccessIdPair); assertSameLists<Class::AccessIdPair>(expected->interfaces(), actual->interfaces(), assertAccessIdPair); assertSameLists<Class::Member*>(expected->members(), actual->members(), [](const Class::Member *lhs, const Class::Member *rhs) -> void { Assert::Eq(lhs->accessType, rhs->accessType); assertEqualStatement(lhs->statement, rhs->statement); }); } void assertEqualControlStructure(ControlStructure *expected, ControlStructure *actual) { Expect::EqStr(expected->name(), actual->name()); assertEqualBlock(expected->block(), actual->block()); } void assertEqualFunction(Function *expected, Function *actual) { Expect::EqStr(expected->id(), actual->id()); Expect::Eq(expected->returnType(), actual->returnType()); Expect::Eq(expected->parameters(), actual->parameters()); assertEqualBlock(expected->block(), actual->block()); } void assertEqualVariable(Variable *expected, Variable *actual) { Expect::EqStr(expected->id(), actual->id()); Expect::EqStr(expected->initExpression(), actual->initExpression()); } void assertEqualBlock(const Block &expected, const Block &actual) { assertEqualStatementLists(expected.statements(), actual.statements()); } void assertEqualStatementLists(const QList<Statement*> expected, const QList<Statement*> actual) { Assert::Eq(expected.count(), actual.count()); auto expectedIter = vc::makeIter(expected); auto actualIter = vc::makeIter(actual); while (expectedIter.hasNext()) { ext::assertEqualStatement(expectedIter.next(), actualIter.next()); } Assert::False(expectedIter.hasNext()); Assert::False(actualIter.hasNext()); } void assertEqualStatement(Statement *expected, Statement *actual) { Assert::NotNull(expected); Assert::NotNull(actual); Assert::Eq(typeid(*expected), typeid(*actual)); if (auto preprocessor = dynamic_cast<Preprocessor*>(expected)) assertEqualPreprocessor(preprocessor, dynamic_cast<Preprocessor*>(actual)); else if (auto cls = dynamic_cast<Class*>(expected)) assertEqualClass(cls, dynamic_cast<Class*>(actual)); else if (auto controlStructure = dynamic_cast<ControlStructure*>(expected)) assertEqualControlStructure(controlStructure, dynamic_cast<ControlStructure*>(actual)); else if (auto expression = dynamic_cast<Expression*>(expected)) assertEqualExpression(*expression, *dynamic_cast<Expression*>(actual)); else if (auto function = dynamic_cast<Function*>(expected)) assertEqualFunction(function, dynamic_cast<Function*>(actual)); else if (auto variable = dynamic_cast<Variable*>(expected)) assertEqualVariable(variable, dynamic_cast<Variable*>(expected)); else Expect::EqStr(expected->verbatim(), actual->verbatim()); } }
mit
dnna/petdate
src/PD/UserBundle/Wantlet/ORM/PointStr.php
890
<?php namespace PD\UserBundle\Wantlet\ORM; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\Lexer; /** * POINT_STR function for querying using Point objects as parameters * * Usage: POINT_STR(:param) where param should be mapped to $point where $point is \PD\UserBundle\Wantlet\ORM\Point * without any special typing provided (eg. so that it gets converted to string) */ class PointStr extends FunctionNode { private $arg; public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { return 'GeomFromText(' . $this->arg->dispatch($sqlWalker) . ')'; } public function parse(\Doctrine\ORM\Query\Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); $this->arg = $parser->ArithmeticPrimary(); $parser->match(Lexer::T_CLOSE_PARENTHESIS); } }
mit
martintito/desaeka
src/Jaxxes/RavenBundle/Entity/RavenBaremoAdulto.php
3425
<?php namespace Jaxxes\RavenBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * RavenBaremoAdulto * * @ORM\Table() * @ORM\Entity */ class RavenBaremoAdulto { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="edadMin", type="integer") */ private $edadMin; /** * @var integer * * @ORM\Column(name="edadMax", type="integer") */ private $edadMax; /** * @var integer * * @ORM\Column(name="pn", type="integer") */ private $pn; /** * @var integer * * @ORM\Column(name="rangoMin", type="integer") */ private $rangoMin; /** * @var integer * * @ORM\Column(name="rangoMax", type="integer") */ private $rangoMax; /** * @var integer * * @ORM\Column(name="percentil", type="integer") */ private $percentil; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set edadMin * * @param integer $edadMin * @return RavenBaremoAdulto */ public function setEdadMin($edadMin) { $this->edadMin = $edadMin; return $this; } /** * Get edadMin * * @return integer */ public function getEdadMin() { return $this->edadMin; } /** * Set edadMax * * @param integer $edadMin * @return RavenBaremoAdulto */ public function setEdadMax($edadMax) { $this->edadMax = $edadMax; return $this; } /** * Get edadMax * * @return integer */ public function getEdadMax() { return $this->edadMax; } /** * Set pn * * @param integer $pn * @return RavenBaremoAdulto */ public function setPn($pn) { $this->pn = $pn; return $this; } /** * Get pn * * @return integer */ public function getPn() { return $this->pn; } /** * Set rangoMin * * @param integer $rangoMin * @return RavenBaremoAdulto */ public function setRangoMin($rangoMin) { $this->rangoMin = $rangoMin; return $this; } /** * Get rangoMin * * @return integer */ public function getRangoMin() { return $this->rangoMin; } /** * Set rangoMax * * @param integer $rangoMax * @return RavenBaremoAdulto */ public function setRangoMax($rangoMax) { $this->rangoMax = $rangoMax; return $this; } /** * Get rangoMax * * @return integer */ public function getRangoMax() { return $this->rangoMax; } /** * Set percentil * * @param integer $percentil * @return RavenBaremoAdulto */ public function setPercentil($percentil) { $this->percentil = $percentil; return $this; } /** * Get percentil * * @return integer */ public function getPercentil() { return $this->percentil; } }
mit
mikeschinkel/learning-backbonejs-best-practices
js/src/layer-addition-form.js
773
/** * layer-addition-form.js - */ app.LayerAdditionForm = Backbone.View.extend({ viewType: "LayerAdditionForm", tagName: 'form', template: _.template(app.loadTemplate('layer-addition-form')), contentTypesSelect: false, layoutsSelect: false, addLayerButton: new app.AddLayerButton(), initialize: function(options) { this.contentTypesSelect = new app.ContentTypesSelect({ collection: app.contentTypes }); this.layoutsSelect = new app.LayoutsSelect({ collection: app.layouts }); this.addLayerButton = new app.AddLayerButton(); }, render: function() { this.setElement('#layer-addition-form'); this.$el.html(this.template()); this.contentTypesSelect.render(); this.layoutsSelect.render(); this.addLayerButton.render(); return this; } });
mit
ufhy/Formstone
src/js/equalize.js
4265
;(function ($, Formstone, undefined) { "use strict"; /** * @method private * @name resize * @description Handles window resize */ function resize(windowWidth) { Functions.iterate.call($Instances, resizeInstance); } /** * @method private * @name cacheInstances * @description Caches active instances */ function cacheInstances() { $Instances = $(Classes.element); } /** * @method private * @name construct * @description Builds instance. * @param data [object] "Instance Data" */ function construct(data) { data.maxWidth = (data.maxWidth === Infinity ? "100000px" : data.maxWidth); data.mq = "(min-width:" + data.minWidth + ") and (max-width:" + data.maxWidth + ")"; data.type = (data.property === "height") ? "outerHeight" : "outerWidth"; if (data.target) { if (!$.isArray(data.target)) { data.target = [ data.target ]; } } else { data.target = [ "> *" ]; } cacheInstances(); $.mediaquery("bind", data.rawGuid, data.mq, { enter: function() { enable.call(data.$el, data); }, leave: function() { disable.call(data.$el, data); } }); } /** * @method private * @name destruct * @description Tears down instance. * @param data [object] "Instance data" */ function destruct(data) { tearDown(data); $.mediaquery("unbind", data.rawGuid); cacheInstances(); } /** * @method private * @name resizeInstance * @description Handle window resize event * @param data [object] "Instance data" */ function resizeInstance(data) { if (data.data) { data = data.data; // normalize image resize events } if (data.enabled) { var value, check, $target; for (var i = 0; i < data.target.length; i++) { value = 0; check = 0; $target = data.$el.find( data.target[i] ); $target.css(data.property, ""); for (var j = 0; j < $target.length; j++) { check = $target.eq(j)[ data.type ](); if (check > value) { value = check; } } $target.css(data.property, value); } } } /** * @method * @name disable * @description Disables instance of plugin * @example $(".target").equalize("disable"); */ function disable(data) { if (data.enabled) { data.enabled = false; tearDown(data); } } /** * @method * @name enable * @description Enables instance of plugin * @example $(".target").equalize("enable"); */ function enable(data) { if (!data.enabled) { data.enabled = true; var $images = data.$el.find("img"); if ($images.length) { $images.on(Events.load, data, resizeInstance); } resizeInstance(data); } } /** * @method private * @name tearDown * @description Removes styling from elements * @param data [object] "Instance data" */ function tearDown(data) { for (var i = 0; i < data.target.length; i++) { data.$el.find( data.target[i] ).css(data.property, ""); } data.$el.find("img").off(Events.namespace); } /** * @plugin * @name Equalize * @description A jQuery plugin for equal dimensions. * @type widget * @dependency core.js * @dependency mediaquery.js */ var Plugin = Formstone.Plugin("equalize", { widget: true, priority: 5, /** * @options * @param maxWidth [string] <'Infinity'> "Width at which to auto-disable plugin" * @param minWidth [string] <'0'> "Width at which to auto-disable plugin" * @param property [string] <"height"> "Property to size; 'height' or 'width'" * @param target [string OR array] <null> "Target child selector(s); Defaults to direct descendants" */ defaults: { maxWidth : Infinity, minWidth : '0px', property : "height", target : null }, methods : { _construct : construct, _destruct : destruct, _resize : resize } }), // Localize References Classes = Plugin.classes, RawClasses = Classes.raw, Events = Plugin.events, Functions = Plugin.functions, $Instances = []; })(jQuery, Formstone);
mit