repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
bem/jsd | lib/jsdoc.js | 8452 | var Tags = require('./tags'),
parser = require('./parser'),
inherit = require('inherit');
/**
* API
* @param {Array} plugins
* @returns {Function}
*/
module.exports = function(plugins) {
var jsdoc = new JSDoc(plugins);
return function(str) {
return jsdoc.parse(str);
};
};
var JSDoc = inherit({
__constructor : function(plugins) {
this._tagParsers = {};
this._tagBuilders = [];
this._postprocessors = {};
plugins.forEach(this._registerPlugin, this);
},
_registerPlugin : function(plugin) {
(typeof plugin === 'string'? require(plugin) : plugin)(this);
return this;
},
registerParser : function(tagType, parseFn) {
if(Array.isArray(tagType)) {
tagType.forEach(
function(tagType) {
this.registerParser(tagType, parseFn);
},
this);
return this;
}
tagType = escapeKey(tagType);
this._tagParsers[tagType] = parseFn === Boolean || parseFn === String?
simpleParsers[parseFn.name] :
parseFn;
return this;
},
registerBuilder : function(tagType, builderFn) {
if(typeof tagType === 'function') {
builderFn = tagType;
tagType = null;
}
else if(Array.isArray(tagType)) {
tagType.forEach(
function(tagType) {
this.registerBuilder(tagType, builderFn);
},
this);
return this;
}
this._tagBuilders.push({ type : tagType, fn : builderFn });
return this;
},
registerPostprocessor : function(jsdocType, postprocessorFn) {
if(Array.isArray(jsdocType)) {
jsdocType.forEach(
function(jsdocType) {
this.registerPostprocessor(jsdocType, postprocessorFn);
},
this);
return this;
}
if(arguments.length === 1) {
postprocessorFn = jsdocType;
jsdocType = '';
}
jsdocType = escapeKey(jsdocType);
(this._postprocessors[jsdocType] || (this._postprocessors[jsdocType] = [])).push(postprocessorFn);
return this;
},
parse : function(source) {
var sourceTree = parser(source),
rootJsdocNode = { jsdocType : 'root' },
ctx = {},
_this = this,
errors = [];
sourceTree.iterate(
function(astNode, jsdocNode) {
var accJsdocNode = jsdocNode;
astNode.comments.forEach(function(commentAstNode) {
var iterationErrors = [];
accJsdocNode = _this._onIterate(ctx, commentAstNode, astNode, accJsdocNode, iterationErrors);
errors = errors.concat(iterationErrors.map(function(e) {
return _this._buildError(e, source, commentAstNode);
}));
});
return accJsdocNode;
},
rootJsdocNode);
this._postprocess(rootJsdocNode, ctx, errors);
if(errors.length) throw Error(errors.join('\n\n\n'));
return rootJsdocNode;
},
_onIterate : function(ctx, commentAstNode, astNode, jsdocNode, errors) {
var accJsdocNode = jsdocNode,
parentJsdocNode = jsdocNode,
tags = new Tags(this._parseJSDocComment(commentAstNode.value, errors));
this._tagBuilders.forEach(function(tagBuilder) {
if(!tagBuilder.type) {
// TODO: get rid of copy-paste
try {
var res = tagBuilder.fn.call(ctx, tags, accJsdocNode, parentJsdocNode, astNode);
typeof res !== 'undefined' && (accJsdocNode = res);
} catch(e) {
errors.push(e);
}
return;
}
tags.getTagsByType(tagBuilder.type).forEach(function(tag) {
// TODO: get rid of copy-paste
try {
var res = tagBuilder.fn.call(ctx, tag, accJsdocNode, parentJsdocNode, astNode);
typeof res !== 'undefined' && (accJsdocNode = res);
} catch(e) {
errors.push(e);
}
});
});
return accJsdocNode;
},
_parseJSDocComment : function(comment, errors) {
var tags = [],
lines = comment.replace(/^(\s*\*)?[\s\n]*|[\s\n]*$/g, '').split('\n'),
tag = { type : '', comment : '' };
lines.forEach(function(line, i) {
var matches = line.match(/^(?:\*|\s)*@(\w+)(?:\s+(.+?)\s*)?$/);
if(matches) {
tag.type && tags.push(this._parseTagComment(tag, errors));
tag.type = matches[1];
tag.comment = matches[2] || '';
} else {
i || (tag.type = 'description');
tag.comment += (tag.comment? '\n' : '') + line.replace(/^\s*\*\s?|\s*$/g, '');
}
}, this);
tags.push(this._parseTagComment(tag, errors));
return tags;
},
_parseTagComment : function(tag, errors) {
var parse = this._tagParsers[escapeKey(tag.type)],
comment = tag.comment.replace(/\n*$/g, ''),
res;
if(parse) {
try {
res = parse(comment);
} catch(e) {
errors.push(e);
}
} else {
errors.push(Error('Unsupported tag: ' + tag.type));
}
res || (res = { content : comment });
res.type = tag.type;
return res;
},
iterate : function(jsdocNode, cb, ctx) {
function iterate(jsdocNode) {
if(!jsdocNode) return;
jsdocNode.jsdocType && cb.call(ctx, jsdocNode);
for(var i in jsdocNode) {
if(jsdocNode.hasOwnProperty(i)) {
var prop = jsdocNode[i];
if(prop && typeof prop === 'object') {
Array.isArray(prop)?
prop.forEach(iterate) :
iterate(prop);
}
}
}
}
iterate(jsdocNode);
},
_postprocess : function(rootJsdocNode, ctx, errors) {
var _this = this,
processedJsdocNodes = [],
postprocessCb = function(jsdocNode) {
_this.iterate(jsdocNode, function(jsdocNode) {
if(!jsdocNode._postprocessed) {
jsdocNode._postprocessed = true;
processedJsdocNodes.push(jsdocNode);
try {
_this._postprocessByType(jsdocNode.jsdocType, jsdocNode, ctx, postprocessCb);
} catch(e) {
errors.push(e);
}
try {
_this._postprocessByType('', jsdocNode, ctx, postprocessCb);
} catch(e) {
errors.push(e);
}
}
});
};
postprocessCb(rootJsdocNode);
processedJsdocNodes.forEach(function(jsdocNode) {
delete jsdocNode._postprocessed;
});
},
_postprocessByType : function(jsdocType, jsdocNode, ctx, postprocessCb) {
var postprocessors = this._postprocessors[escapeKey(jsdocType)];
postprocessors && postprocessors.forEach(function(fn) {
fn.call(ctx, jsdocNode, postprocessCb);
});
},
_buildError : function(e, source, commentAstNode) {
var loc = commentAstNode.loc,
msg = 'Error: "' + e.message + '" while processing jsdoc comments started at line ' + loc.start.line;
return Error(
msg + '\n' +
new Array(msg.length + 1).join('-') + '\n' +
source.split('\n').slice(loc.start.line - 1, loc.end.line + 3).join('\n') + '\n' +
e.stack);
}
});
var simpleParsers = {
String : function(comment) {
return { content : comment.trim() };
},
Boolean : function(comment) {
return {};
}
};
function escapeKey(tagType) {
return '_' + tagType;
}
| mit |
Gendoria/command-queue | src/Gendoria/CommandQueue/Tests/Console/Command/RunWorkerCommandTest.php | 2669 | <?php
namespace Gendoria\CommandQueue\Tests\Console\Command;
use Gendoria\CommandQueue\Console\Command\RunWorkerCommand;
use Gendoria\CommandQueue\Worker\WorkerRunnerInterface;
use Gendoria\CommandQueue\Worker\WorkerRunnerManager;
use PHPUnit_Framework_TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* Test run worker command.
*
* @author Tomasz Struczyński <[email protected]>
*/
class RunWorkerCommandTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
$manager = new WorkerRunnerManager();
$runner = $this->getMockBuilder(WorkerRunnerInterface::class)->getMock();
$manager->addRunner('test', $runner);
$application = new Application();
$testedCommand = new RunWorkerCommand();
$testedCommand->setRunnerManager($manager);
$application->add($testedCommand);
$command = $application->find('cmq:worker:run');
$commandTester = new CommandTester($command);
$commandTester->execute(
array(
'name' => 'test',
)
);
}
public function testExecuteNoWorker()
{
$manager = new WorkerRunnerManager();
$runner = $this->getMockBuilder(WorkerRunnerInterface::class)->getMock();
$manager->addRunner('different', $runner);
$application = new Application();
$testedCommand = new RunWorkerCommand();
$testedCommand->setRunnerManager($manager);
$application->add($testedCommand);
$command = $application->find('cmq:worker:run');
$commandTester = new CommandTester($command);
$exitCode = $commandTester->execute(
array(
'name' => 'test',
)
);
$this->assertEquals(1, $exitCode);
$this->assertContains('Worker "test" not registered.', $commandTester->getDisplay());
$this->assertContains('different', $commandTester->getDisplay());
}
public function testExecuteNoManager()
{
$application = new Application();
$testedCommand = new RunWorkerCommand();
$application->add($testedCommand);
$command = $application->find('cmq:worker:run');
$commandTester = new CommandTester($command);
$exitCode = $commandTester->execute(
array(
'name' => 'test',
)
);
$this->assertEquals(1, $exitCode);
$this->assertContains('Runner manager not provided to command. Command is not correctly initialized.', $commandTester->getDisplay());
}
}
| mit |
skerit/alchemy | lib/class/error.js | 613 | /**
* The Error class
*
* @constructor
*
* @author Jelle De Loecker <[email protected]>
* @since 1.1.0
* @version 1.1.0
*/
const AlchemyError = Function.inherits('Develry.Error', 'Alchemy.Error', function Error(message) {
Error.super.call(this, message);
});
/**
* Return string interpretation of this error
*
* @author Jelle De Loecker <[email protected]>
* @since 1.1.0
* @version 1.1.0
*
* @return {String}
*/
AlchemyError.setMethod(function toString() {
let result = this.name + ' Error';
if (this.message) {
result += ': ' + this.message;
}
return result;
});
| mit |
pebble/pypkjs | pypkjs/timeline/colours.py | 1992 | from __future__ import absolute_import
__author__ = 'katharine'
PEBBLE_COLOURS = {
"black": 0b11000000,
"oxfordblue": 0b11000001,
"dukeblue": 0b11000010,
"blue": 0b11000011,
"darkgreen": 0b11000100,
"midnightgreen": 0b11000101,
"cobaltblue": 0b11000110,
"bluemoon": 0b11000111,
"islamicgreen": 0b11001000,
"jaegergreen": 0b11001001,
"tiffanyblue": 0b11001010,
"vividcerulean": 0b11001011,
"green": 0b11001100,
"malachite": 0b11001101,
"mediumspringgreen": 0b11001110,
"cyan": 0b11001111,
"bulgarianrose": 0b11010000,
"imperialpurple": 0b11010001,
"indigo": 0b11010010,
"electricultramarine": 0b11010011,
"armygreen": 0b11010100,
"darkgray": 0b11010101,
"liberty": 0b11010110,
"verylightblue": 0b11010111,
"kellygreen": 0b11011000,
"maygreen": 0b11011001,
"cadetblue": 0b11011010,
"pictonblue": 0b11011011,
"brightgreen": 0b11011100,
"screamingreen": 0b11011101,
"mediumaquamarine": 0b11011110,
"electricblue": 0b11011111,
"darkcandyapplered": 0b11100000,
"jazzberryjam": 0b11100001,
"purple": 0b11100010,
"vividviolet": 0b11100011,
"windsortan": 0b11100100,
"rosevale": 0b11100101,
"purpureus": 0b11100110,
"lavenderindigo": 0b11100111,
"limerick": 0b11101000,
"brass": 0b11101001,
"lightgray": 0b11101010,
"babyblueeyes": 0b11101011,
"springbud": 0b11101100,
"inchworm": 0b11101101,
"mintgreen": 0b11101110,
"celeste": 0b11101111,
"red": 0b11110000,
"folly": 0b11110001,
"fashionmagenta": 0b11110010,
"magenta": 0b11110011,
"orange": 0b11110100,
"sunsetorange": 0b11110101,
"brilliantrose": 0b11110110,
"shockingpink": 0b11110111,
"chromeyellow": 0b11111000,
"rajah": 0b11111001,
"melon": 0b11111010,
"richbrilliantlavender": 0b11111011,
"yellow": 0b11111100,
"icterine": 0b11111101,
"pastelyellow": 0b11111110,
"white": 0b11111111,
} | mit |
blindpenguin/orangelime | templates/page-full.php | 798 | <?php
/*
Template Name: Full Width
*/
get_header(); ?>
<?php get_template_part( 'parts/featured-image' ); ?>
<div class="row main-content">
<div class="small-12 large-12 columns" role="main">
<?php /* Start loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<article <?php post_class() ?> id="post-<?php the_ID(); ?>">
<header>
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content">
<?php the_content(); ?>
</div>
<footer>
<?php wp_link_pages( array('before' => '<nav id="page-nav"><p>' . __( 'Pages:', 'foundationpress' ), 'after' => '</p></nav>' ) ); ?>
<p><?php the_tags(); ?></p>
</footer>
<?php comments_template(); ?>
</article>
<?php endwhile; // End the loop ?>
</div>
</div>
<?php get_footer(); ?>
| mit |
mahendrahirpara/Organization-Architecture | Organization/Hotel720.Platform.Infrastructure/Data/IUnitOfWork.cs | 198 | using System;
namespace Hotel720.Platform.Infrastructure.Data
{
public interface IUnitOfWork : IDisposable
{
void BeginTransaction();
void Commit();
void Rollback();
}
}
| mit |
DaanVanYperen/arktrail | core/src/net/mostlyoriginal/game/system/ui/RouteSystem.java | 4455 | package net.mostlyoriginal.game.system.ui;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.managers.GroupManager;
import com.artemis.managers.TagManager;
import com.artemis.systems.EntityProcessingSystem;
import com.artemis.utils.ImmutableBag;
import com.badlogic.gdx.math.MathUtils;
import net.mostlyoriginal.api.component.basic.Pos;
import net.mostlyoriginal.api.component.graphics.Anim;
import net.mostlyoriginal.api.utils.EntityUtil;
import net.mostlyoriginal.game.G;
import net.mostlyoriginal.game.component.environment.RouteIndicator;
import net.mostlyoriginal.game.component.environment.RouteNode;
import net.mostlyoriginal.game.manager.EntityFactorySystem;
/**
* Plot system.
*
* @author Daan van Yperen
*/
@Wire
public class RouteSystem extends EntityProcessingSystem {
public static final int CHANCE_OF_ROUTE_BEING_NODE = 44;
public static final int DEFAULT_ROUTE_LENGTH = 24;
protected GroupManager groupManager;
protected EntityFactorySystem efs;
protected ComponentMapper<RouteNode> mRouteNode;
protected ComponentMapper<Anim> mAnim;
protected ComponentMapper<Pos> mPos;
protected ComponentMapper<RouteIndicator> mRouteIndicator;
private TagManager tagManager;
public RouteSystem() {
super(Aspect.getAspectForAll(RouteNode.class));
}
@Override
protected void initialize() {
super.initialize();
efs.createRouteIndicator();
createRoute(DEFAULT_ROUTE_LENGTH);
}
private void createRoute( int length ) {
deleteRoute();
// center our route.
int startX = (G.SCREEN_WIDTH / 2) - (length * 4);
for ( int i=0; i<length; i++ )
{
RouteNode.Action action =
( i==length-1 ) ? RouteNode.Action.FINISH :
( (i==0) || (MathUtils.random(0, 99) < CHANCE_OF_ROUTE_BEING_NODE) ) ? RouteNode.Action.EVENT : RouteNode.Action.SKIP;
efs.createRouteNode( startX + i * 8, G.SCREEN_HEIGHT - 16, action, i);
}
markVisitedUpTo(0);
}
/** Signal everything visited up to given step. */
public Entity markVisitedUpTo(int upToStep)
{
Entity atNode = null;
ImmutableBag<Entity> entities = groupManager.getEntities("route");
for (int i=0,s=entities.size();i<s; i++)
{
Entity node = entities.get(i);
if( mRouteNode.has(node) )
{
RouteNode routeNode = (RouteNode) mRouteNode.get(node);
routeNode.visited = ( routeNode.order <= upToStep );
// move indicator to active step.
if ( routeNode.order == upToStep )
{
atNode = node;
placeIndicatorAboveNode(node);
}
}
}
return atNode;
}
private void placeIndicatorAboveNode(Entity node) {
final Entity routeIndicator = getIndicator();
if ( routeIndicator != null && mPos.has(routeIndicator)) {
Pos indicatorPos = mPos.get(routeIndicator);
Pos nodePos = mPos.get(node);
indicatorPos.x = nodePos.x;
indicatorPos.y = nodePos.y + 5;
// keep track of our current location.
RouteIndicator indicator = mRouteIndicator.get(routeIndicator);
indicator.at = mRouteNode.get(node).order;
}
}
private Entity getIndicator() {
return tagManager.getEntity("routeindicator");
}
private void deleteRoute() {
EntityUtil.safeDeleteAll(groupManager.getEntities("route"));
}
@Override
protected void process(Entity e) {
RouteNode routeNode = mRouteNode.get(e);
Anim anim = mAnim.get(e);
// update nodes so they have the right appearance.
switch ( routeNode.action ) {
case SKIP:
anim.id = routeNode.visited ? "progress-bar-1" : "progress-bar-0";
break;
case EVENT:
case FINISH:
anim.id = routeNode.visited ? "progress-bubble-1" : "progress-bubble-0";
break;
}
}
/** go to next step in route. */
public Entity gotoNext() {
final Entity routeIndicator = getIndicator();
return markVisitedUpTo(mRouteIndicator.get(routeIndicator).at + 1);
}
}
| mit |
bheftye/CEEACCE | CEEACCE/src/gui/interfazdeusuario/CentradorDeVistas.java | 753 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gui.interfazdeusuario;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
/**
*
* @author brentheftye
*/
public class CentradorDeVistas {
private static CentradorDeVistas centradorDeVistas = new CentradorDeVistas();
private CentradorDeVistas(){}
public void centrarJFrame(JFrame vista){
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
vista.setLocation(dimension.width/2-vista.getSize().width/2, dimension.height/2-vista.getSize().height/2);
}
public static CentradorDeVistas getCentradorDeVistas(){
return centradorDeVistas;
}
}
| mit |
aliencube/yarm | src/Yarm.Functions/ResponseMessages.Designer.cs | 4414 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Yarm.Functions {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class ResponseMessages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ResponseMessages() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Yarm.Functions.ResponseMessages", typeof(ResponseMessages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Request payload content type is invalid.
/// </summary>
public static string InvalidRequestPayloadContentType {
get {
return ResourceManager.GetString("InvalidRequestPayloadContentType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Parameters cannot be found.
/// </summary>
public static string ParametersNotFound {
get {
return ResourceManager.GetString("ParametersNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Request payload is missing.
/// </summary>
public static string RequestPayloadNotFound {
get {
return ResourceManager.GetString("RequestPayloadNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resource cannot be found.
/// </summary>
public static string ResourceNotFound {
get {
return ResourceManager.GetString("ResourceNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ARM template cannot be found.
/// </summary>
public static string TemplateNotFound {
get {
return ResourceManager.GetString("TemplateNotFound", resourceCulture);
}
}
}
}
| mit |
kenyonduan/amazon-mws | src/main/java/com/amazonservices/mws/finances/model/ListFinancialEventGroupsResult.java | 5368 | /*******************************************************************************
* Copyright 2009-2017 Amazon Services. All Rights Reserved.
* 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://aws.amazon.com/apache2.0
* This file 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.
*******************************************************************************
* List Financial Event Groups Result
* API Version: 2015-05-01
* Library Version: 2017-07-26
* Generated: Tue Jul 25 12:48:56 UTC 2017
*/
package com.amazonservices.mws.finances.model;
import java.util.List;
import java.util.ArrayList;
import com.amazonservices.mws.client.*;
/**
* ListFinancialEventGroupsResult complex type.
*
* XML schema:
*
* <pre>
* <complexType name="ListFinancialEventGroupsResult">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="NextToken" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="FinancialEventGroupList" type="{http://mws.amazonservices.com/Finances/2015-05-01}FinancialEventGroup" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
public class ListFinancialEventGroupsResult extends AbstractMwsObject {
private String nextToken;
private List<FinancialEventGroup> financialEventGroupList;
/**
* Get the value of NextToken.
*
* @return The value of NextToken.
*/
public String getNextToken() {
return nextToken;
}
/**
* Set the value of NextToken.
*
* @param nextToken
* The new value to set.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* Check to see if NextToken is set.
*
* @return true if NextToken is set.
*/
public boolean isSetNextToken() {
return nextToken != null;
}
/**
* Set the value of NextToken, return this.
*
* @param nextToken
* The new value to set.
*
* @return This instance.
*/
public ListFinancialEventGroupsResult withNextToken(String nextToken) {
this.nextToken = nextToken;
return this;
}
/**
* Get the value of FinancialEventGroupList.
*
* @return The value of FinancialEventGroupList.
*/
public List<FinancialEventGroup> getFinancialEventGroupList() {
if (financialEventGroupList==null) {
financialEventGroupList = new ArrayList<FinancialEventGroup>();
}
return financialEventGroupList;
}
/**
* Set the value of FinancialEventGroupList.
*
* @param financialEventGroupList
* The new value to set.
*/
public void setFinancialEventGroupList(List<FinancialEventGroup> financialEventGroupList) {
this.financialEventGroupList = financialEventGroupList;
}
/**
* Clear FinancialEventGroupList.
*/
public void unsetFinancialEventGroupList() {
this.financialEventGroupList = null;
}
/**
* Check to see if FinancialEventGroupList is set.
*
* @return true if FinancialEventGroupList is set.
*/
public boolean isSetFinancialEventGroupList() {
return financialEventGroupList != null && !financialEventGroupList.isEmpty();
}
/**
* Add values for FinancialEventGroupList, return this.
*
* @param financialEventGroupList
* New values to add.
*
* @return This instance.
*/
public ListFinancialEventGroupsResult withFinancialEventGroupList(FinancialEventGroup... values) {
List<FinancialEventGroup> list = getFinancialEventGroupList();
for (FinancialEventGroup value : values) {
list.add(value);
}
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
nextToken = r.read("NextToken", String.class);
financialEventGroupList = r.readList("FinancialEventGroupList", "FinancialEventGroup", FinancialEventGroup.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.write("NextToken", nextToken);
w.writeList("FinancialEventGroupList", "FinancialEventGroup", financialEventGroupList);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("http://mws.amazonservices.com/Finances/2015-05-01", "ListFinancialEventGroupsResult",this);
}
/** Default constructor. */
public ListFinancialEventGroupsResult() {
super();
}
}
| mit |
rbobin/play-json-match | src/main/scala/com/github/rbobin/playjsonmatch/Patterns.scala | 3765 | package com.github.rbobin.playjsonmatch
import com.github.rbobin.playjsonmatch.Errors._
import com.github.rbobin.playjsonmatch.processors._
import com.github.rbobin.playjsonmatch.utils.StringUtils._
import com.github.rbobin.playjsonmatch.utils.{JsMatchException, StringUtils}
import play.api.libs.json.JsValue
import scala.util.matching.Regex
sealed trait MatchAttempt
sealed trait MatchResult extends MatchAttempt {
def processorName: String
}
case object MatchSkip extends MatchAttempt
case class MatchSuccess(override val processorName: String) extends MatchResult
case class MatchError(override val processorName: String, message: String) extends MatchResult
trait PatternProcessor {
val regex: Regex
val rationalNumberRegex = "(-?\\d*\\.{0,1}\\d+)"
def process(patternCandidate: String, maybeJsValue: Option[JsValue]): MatchAttempt
val processorName = this.getClass.getSimpleName
def fail(message: String) = MatchError(processorName, message)
def success = MatchSuccess(processorName)
def skip = MatchSkip
}
private[playjsonmatch] object Matcher {
val defaultProcessors: Seq[PatternProcessor] = Seq(AnyValueProcessor, MissingValueProcessor, BooleanProcessor,
NullProcessor, RegexProcessor, DateTimeProcessor, BoundedArrayProcessor, LowerBoundedArrayProcessor,
SimpleArrayProcessor, SizedArrayProcessor, UpperBoundedArrayProcessor, LowerBoundedNumberProcessor,
NumberInRangeProcessor, SimpleNumberProcessor, UpperBoundedNumberProcessor, BoundedObjectProcessor,
LowerBoundedObjectProcessor, SimpleObjectProcessor, SizedObjectProcessor, UpperBoundedObjectProcessor,
BoundedStringProcessor, LowerBoundedStringProcessor, SimpleStringProcessor, SizedStringProcessor,
UpperBoundedStringProcessor)
val splitCharacter = '|'
val emptyString = ""
val emptyErrors = Left(Nil)
type ErrorsOrSuccess = Either[List[MatchError], Unit]
def processPatterns(patternsString: String, maybeJsValue: Option[JsValue], path: JsPath): Errors =
try {
getMatchResults(patternsString, maybeJsValue) match {
case Left(errors) => matchErrors(errors, maybeJsValue, path)
case Right(_) => NO_ERRORS
}
} catch {
case e: JsMatchException =>
throw new JsMatchException(FailureMessages("errorAtPath", e.message, prettifyPath(path)))
}
private def getMatchResults(patternString: String, maybeJsValue: Option[JsValue]): ErrorsOrSuccess =
splitPatterns(patternString)
.map(processPattern(_, maybeJsValue))
.foldLeft[ErrorsOrSuccess](emptyErrors)(mergeMatchResults)
private def splitPatterns(patterns: String): List[String] =
patterns.split(splitCharacter)
.toList
.filterNot(_.isEmpty)
match {
case Nil => throw new JsMatchException(FailureMessages("noPatterns"))
case x => x
}
private def mergeMatchResults(errorsEitherSuccess: ErrorsOrSuccess, matchResult: MatchResult): ErrorsOrSuccess =
errorsEitherSuccess match {
case Left(errors) => matchResult match {
case _: MatchSuccess => Right()
case error: MatchError => Left(error :: errors)
}
case Right(_) => Right()
}
private def processPattern(pattern: String, maybeJsValue: Option[JsValue]): MatchResult =
filterSkipped(pattern, defaultProcessors.map(processor => processor.process(pattern, maybeJsValue)))
private def filterSkipped(pattern: String, results: Seq[MatchAttempt]): MatchResult =
results.filterNot(_ == MatchSkip) match {
case Nil => throw new JsMatchException(FailureMessages("noMatch", pattern))
case (x: MatchResult) :: Nil => x
case x: Seq[MatchResult] =>
throw new JsMatchException(FailureMessages("multipleMatch", pattern, x.map(_.processorName).mkString(",")))
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/analytics.js/2.3.18/analytics.js | 131 | version https://git-lfs.github.com/spec/v1
oid sha256:53c26f265964f25566839044d419ac436f49139940501973d6277ef458987a75
size 361085
| mit |
SimoNonnis/Gliffaes | single-offer.php | 1893 | <?php
/*
Template Name Posts: Single Offer
*/
?>
<?php get_header(); ?>
<div <?php post_class('clearfix'); ?> >
<div id="content-inner" role="main">
<section class="page-content page-sidebar sidebar-content clearfix">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="page-sidebar-inner page-text clearfix">
<?php get_template_part('partials/offers-sidebar'); ?>
<div class="page-sidebar-article">
<article class="clearfix post post-<?php the_ID(); ?>" role="article" itemscope itemtype="http://schema.org/BlogPosting">
<div class="post_inner">
<header class="post_header">
<h1 class="post_title" itemprop="headline"><?php the_title(); ?></h1>
</header>
<div class="single-post-big-img"><?php the_post_thumbnail('ignite-thumb-1700'); ?></div>
<section class="post_content" itemprop="articleBody">
<?php the_content(); ?>
</section>
</div>
<?php get_template_part('partials/social-sharing'); ?>
<div class="availab">
<div class="availab-inner">
<a class="border-radius" target="_blank" href="<?php the_field('book_this_offer_link'); ?>"><span>Book This Offer</span><i class=" icon-calendar"></i></a>
</div>
</div>
<a href="<?php echo get_permalink( 12 ); ?>"><< return to Offers</a>
</article>
</div>
</div><!-- end page-sidebar-inner -->
<?php endwhile; // end of the loop. ?>
<?php endif; ?>
</section><!-- end page-content -->
</div><!-- .content-inner -->
</div><!-- .content -->
<?php get_footer(); ?> | mit |
atsaki/lockgate | lg/lg.go | 1043 | package main
import (
"os"
"github.com/atsaki/lockgate"
"github.com/atsaki/lockgate/cli"
"github.com/atsaki/lockgate/command"
)
var (
app = cli.Application{
Name: "lg",
Help: "CLI for CloudStack",
Version: "0.0.1",
Flags: []cli.Flag{
cli.Flag{
Name: "profile",
Short: 'P',
Help: "Profile to connect CloudStack",
Type: cli.String,
},
cli.Flag{
Name: "no-header",
Short: 'H',
Help: "Show no header line",
Type: cli.Bool,
},
cli.Flag{
Name: "keys",
Short: 'k',
Help: "Keys for output",
Type: cli.String,
},
cli.Flag{
Name: "debug",
Help: "Show log messages for debug",
Type: cli.Bool,
},
},
Commands: []cli.Command{
command.Init,
command.API,
command.Firewallrule,
command.IP,
command.Network,
command.Nic,
command.Portforwardingrule,
command.ServiceOffering,
command.Sshkeypair,
command.Template,
command.VM,
command.Zone,
lockgate.Test,
},
}
)
func main() {
app.Run(os.Args[1:])
}
| mit |
g0rdan/g0rdan.MvvmCross.Plugins | source/Droid/g0rdan.MvvmCross.Plugin.DiskInfo.Droid/Resources/Resource.designer.cs | 1319 | #pragma warning disable 1591
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
[assembly: Android.Runtime.ResourceDesignerAttribute("g0rdan.MvvmCross.Plugin.DiskInfo.Droid.Resource", IsApplication=false)]
namespace g0rdan.MvvmCross.Plugin.DiskInfo.Droid
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class String
{
// aapt resource value: 0x7f020000
public static int library_name = 2130837504;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
| mit |
raltamirano/rant | Rant.Core/ScriptExecutionContexts/DefaultScriptExecutionContext.cs | 848 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rant.Common;
using System.Collections;
namespace Rant.Core.ScriptExecutionContexts
{
/// <summary>
/// Default script execution context. This script execution context is automatically initializated with a copy of the
/// container process' environment variables.
/// </summary>
public class DefaultScriptExecutionContext : AbstractScriptExecutionContext
{
public DefaultScriptExecutionContext()
: base()
{
IDictionary environment = Environment.GetEnvironmentVariables();
foreach (Object key in environment.Keys)
base.SetVariable<String>(key.ToString(), environment[key] != null ? environment[key].ToString() : null);
}
}
}
| mit |
38elements/feedhoos | feedhoos/finder/views/registered.py | 1905 | # coding: utf-8
import json
from django.http import HttpResponse
import feedparser
from feedhoos.finder.forms.feed import FeedForm
from feedhoos.finder.models.feed import FeedModel
from feedhoos.reader.models.bookmark import BookmarkModel
import datetime
import time
def execute(request):
feedform = FeedForm(request.POST)
result = {}
if feedform.is_valid():
feed_url = feedform.cleaned_data["url"]
try:
feed_model = FeedModel.objects.get(url=feed_url)
except FeedModel.DoesNotExist:
feed = feedparser.parse(feed_url, etag=None, modified=None)
if feed.status in [200, 301, 302]:
feed_model = FeedModel(
url=feed_url,
link=feed.feed.link,
title=feed.feed.title,
last_access=int(time.mktime(datetime.datetime.now().timetuple())),
etag=feed.etag if "etag" in feed else "",
modified=feed.modified if "modified" in feed else ""
)
feed_model.feed = feed
feed_model.save()
#feed_modelのidが必要
feed_model.add_entries()
# FIXME for personal
if not BookmarkModel.objects.filter(feed_id=feed_model.id).exists():
BookmarkModel(feed_id=feed_model.id).save()
result["msg"] = "ok"
result["feed"] = feed_model.dict
result["reading"] = feed_model.reading_dict
#Bookmarkはクライアントで生成
else:
result["msg"] = "status error"
else:
result["msg"] = "exist"
else:
result["msg"] = "validation_error"
result_json = json.dumps(result, ensure_ascii=False, skipkeys=True)
return HttpResponse(result_json, content_type='application/json')
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s02/CWE78_OS_Command_Injection__char_environment_execl_83a.cpp | 2119 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_environment_execl_83a.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-83a.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: environment Read input from an environment variable
* GoodSource: Fixed string
* Sinks: execl
* BadSink : execute command with execl
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__char_environment_execl_83.h"
namespace CWE78_OS_Command_Injection__char_environment_execl_83
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
CWE78_OS_Command_Injection__char_environment_execl_83_bad badObject(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
CWE78_OS_Command_Injection__char_environment_execl_83_goodG2B goodG2BObject(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE78_OS_Command_Injection__char_environment_execl_83; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
jmahmood/pytbar | setup.py | 482 | #!/usr/bin/env python
__author__ = 'jawaad'
from distutils.core import setup
setup(name='pytbar',
version='0.300',
description='Library that converts the Japanese Post Office\'s CSV files into a python class. These are '
'thereafter added to a database.',
author='Jawaad Mahmood',
author_email='[email protected]',
url='https://github.com/jmahmood/pytbar/',
license='MIT',
packages=['pytbar'], requires=['redis']) | mit |
Mastodonic/youtube-player | src/js/helpers.js | 788 | export default {
getEl(selector) {
return document.querySelectorAll(selector);
},
/**
* Mobile & Tablet Detection
* @return {Boolean}
*/
isMobile: {
Android() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows() {
return navigator.userAgent.match(/IEMobile/i);
},
any() {
return (this.Android() || this.BlackBerry() || this.iOS() || this.Opera() || this.Windows());
}
}
};
| mit |
adam-boduch/coyote | app/Services/Media/Filters/Logo.php | 204 | <?php
namespace Coyote\Services\Media\Filters;
class Logo extends Thumbnail
{
/**
* @var int
*/
protected $width = 140;
/**
* @var int
*/
protected $height = 140;
}
| mit |
rekyyang/ArtificalLiverCloud | node_modules/material-ui/TimePicker/ClockNumber.js | 5143 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _timeUtils = require('./timeUtils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function getStyles(props, context) {
var styles = {
root: {
display: 'inline-block',
position: 'absolute',
width: 32,
height: 32,
borderRadius: '100%',
left: 'calc(50% - 16px)',
top: 10,
textAlign: 'center',
paddingTop: 5,
userSelect: 'none', /* Chrome all / Safari all */
fontSize: '1.1em',
pointerEvents: 'none',
boxSizing: 'border-box'
}
};
var muiTheme = context.muiTheme;
var pos = props.value;
if (props.type === 'hour') {
pos %= 12;
} else {
pos = pos / 5;
}
var positions = [[0, 5], [54.5, 16.6], [94.4, 59.5], [109, 114], [94.4, 168.5], [54.5, 208.4], [0, 223], [-54.5, 208.4], [-94.4, 168.5], [-109, 114], [-94.4, 59.5], [-54.5, 19.6]];
var innerPositions = [[0, 40], [36.9, 49.9], [64, 77], [74, 114], [64, 151], [37, 178], [0, 188], [-37, 178], [-64, 151], [-74, 114], [-64, 77], [-37, 50]];
if (props.isSelected) {
styles.root.backgroundColor = muiTheme.timePicker.accentColor;
styles.root.color = muiTheme.timePicker.selectTextColor;
}
var transformPos = positions[pos];
if ((0, _timeUtils.isInner)(props)) {
styles.root.width = 28;
styles.root.height = 28;
styles.root.left = 'calc(50% - 14px)';
transformPos = innerPositions[pos];
}
var _transformPos = transformPos;
var _transformPos2 = _slicedToArray(_transformPos, 2);
var x = _transformPos2[0];
var y = _transformPos2[1];
styles.root.transform = 'translate(' + x + 'px, ' + y + 'px)';
return styles;
}
var ClockNumber = function (_React$Component) {
_inherits(ClockNumber, _React$Component);
function ClockNumber() {
_classCallCheck(this, ClockNumber);
return _possibleConstructorReturn(this, Object.getPrototypeOf(ClockNumber).apply(this, arguments));
}
_createClass(ClockNumber, [{
key: 'render',
value: function render() {
var prepareStyles = this.context.muiTheme.prepareStyles;
var styles = getStyles(this.props, this.context);
var clockNumber = this.props.value === 0 ? '00' : this.props.value;
return _react2.default.createElement(
'span',
{ style: prepareStyles(styles.root) },
clockNumber
);
}
}]);
return ClockNumber;
}(_react2.default.Component);
ClockNumber.propTypes = {
isSelected: _react2.default.PropTypes.bool,
onSelected: _react2.default.PropTypes.func,
type: _react2.default.PropTypes.oneOf(['hour', 'minute']),
value: _react2.default.PropTypes.number
};
ClockNumber.defaultProps = {
value: 0,
type: 'minute',
isSelected: false
};
ClockNumber.contextTypes = {
muiTheme: _react2.default.PropTypes.object.isRequired
};
exports.default = ClockNumber; | mit |
sousic/kr.huny | src/main/java/kr/huny/controller/tools/ToolsUserController.java | 1235 | package kr.huny.controller.tools;
import kr.huny.model.db.User;
import kr.huny.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Arrays;
@Controller
@Slf4j
@RequestMapping("/tools/user")
public class ToolsUserController {
@RequestMapping
public String root()
{
return "redirect:/list";
}
@Autowired
UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model)
{
Sort sort = new Sort(Sort.Direction.DESC, Arrays.asList("seq"));
Pageable pageable = new PageRequest(0, 10, sort);
Page<User> users = userService.findAll(pageable);
model.addAttribute("users", users);
return "tools/user/list";
}
}
| mit |
tjmehta/primus-graphql | __browser_tests__/fixtures/mem-db.js | 913 | var EventEmitter = require('events').EventEmitter
var debug = require('debug')('primus-graphql:fixtures:mem-db')
var listenAll = require('listen-all')
var nextUserId = 0
var db = module.exports = {}
db.users = []
db.ee = new EventEmitter()
listenAll(db.ee, function () {
debug('db event', arguments)
})
db.createUser = function (data) {
var user = Object.assign({}, data, { id: nextUserId })
db.users.push(user)
nextUserId++
return user
}
db.getUser = function (userId) {
return db.users.find((u) => u.id.toString() === userId.toString())
}
db.updateUser = function (userId, data) {
var user = db.getUser(userId)
if (user) {
var index = db.users.findIndex((u) => u.id.toString() === userId.toString())
user = db.users[index] = Object.assign({}, user, data)
db.ee.emit('users:' + user.id, Object.assign({}, user))
return user
}
}
db.reset = function () {
db.users = []
}
| mit |
OpenSprites/OpenSprites | public_html/assets/js/spectrum/spectrum.js | 78981 | // Spectrum Colorpicker v1.7.0
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) { // AMD
define(['jquery'], factory);
}
else if (typeof exports == "object" && typeof module == "object") { // CommonJS
module.exports = factory;
}
else { // Browser
factory(jQuery);
}
})(function($, undefined) {
"use strict";
var defaultOpts = {
// Callbacks
beforeShow: noop,
move: noop,
change: noop,
show: noop,
hide: noop,
// Options
color: false,
flat: false,
showInput: false,
allowEmpty: false,
showButtons: true,
clickoutFiresChange: true,
showInitial: false,
showPalette: false,
showPaletteOnly: false,
hideAfterPaletteSelect: false,
togglePaletteOnly: false,
showSelectionPalette: true,
localStorageKey: false,
appendTo: "body",
maxSelectionSize: 7,
cancelText: "cancel",
chooseText: "choose",
togglePaletteMoreText: "more",
togglePaletteLessText: "less",
clearText: "Clear Color Selection",
noColorSelectedText: "No Color Selected",
preferredFormat: false,
className: "", // Deprecated - use containerClassName and replacerClassName instead.
containerClassName: "",
replacerClassName: "",
showAlpha: false,
theme: "sp-light",
palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]],
selectionPalette: [],
disabled: false,
offset: null
},
spectrums = [],
IE = !!/msie/i.exec( window.navigator.userAgent ),
rgbaSupport = (function() {
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
var elem = document.createElement('div');
var style = elem.style;
style.cssText = 'background-color:rgba(0,0,0,.5)';
return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
})(),
replaceInput = [
"<div class='sp-replacer'>",
"<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
"<div class='sp-dd'>▼</div>",
"</div>"
].join(''),
markup = (function () {
// IE does not support gradients with multiple stops, so we need to simulate
// that for the rainbow slider with 8 divs that each have a single gradient
var gradientFix = "";
if (IE) {
for (var i = 1; i <= 6; i++) {
gradientFix += "<div class='sp-" + i + "'></div>";
}
}
return [
"<div class='sp-container sp-hidden'>",
"<div class='sp-palette-container'>",
"<div class='sp-palette sp-thumb sp-cf'></div>",
"<div class='sp-palette-button-container sp-cf'>",
"<button type='button' class='sp-palette-toggle'></button>",
"</div>",
"</div>",
"<div class='sp-picker-container'>",
"<div class='sp-top sp-cf'>",
"<div class='sp-fill'></div>",
"<div class='sp-top-inner'>",
"<div class='sp-color'>",
"<div class='sp-sat'>",
"<div class='sp-val'>",
"<div class='sp-dragger'></div>",
"</div>",
"</div>",
"</div>",
"<div class='sp-clear sp-clear-display'>",
"</div>",
"<div class='sp-hue'>",
"<div class='sp-slider'></div>",
gradientFix,
"</div>",
"</div>",
"<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
"</div>",
"<div class='sp-input-container sp-cf'>",
"<input class='sp-input' type='text' spellcheck='false' />",
"</div>",
"<div class='sp-initial sp-thumb sp-cf'></div>",
"<div class='sp-button-container sp-cf'>",
"<a class='sp-cancel' href='#'></a>",
"<button type='button' class='sp-choose'></button>",
"</div>",
"</div>",
"</div>"
].join("");
})();
function paletteTemplate (p, color, className, opts) {
var html = [];
for (var i = 0; i < p.length; i++) {
var current = p[i];
if(current) {
var tiny = tinycolor(current);
var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
var formattedString = tiny.toString(opts.preferredFormat || "rgb");
var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';" /></span>');
} else {
var cls = 'sp-clear-display';
html.push($('<div />')
.append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>')
.attr('title', opts.noColorSelectedText)
)
.html()
);
}
}
return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
}
function hideAll() {
for (var i = 0; i < spectrums.length; i++) {
if (spectrums[i]) {
spectrums[i].hide();
}
}
}
function instanceOptions(o, callbackContext) {
var opts = $.extend({}, defaultOpts, o);
opts.callbacks = {
'move': bind(opts.move, callbackContext),
'change': bind(opts.change, callbackContext),
'show': bind(opts.show, callbackContext),
'hide': bind(opts.hide, callbackContext),
'beforeShow': bind(opts.beforeShow, callbackContext)
};
return opts;
}
function spectrum(element, o) {
var opts = instanceOptions(o, element),
flat = opts.flat,
showSelectionPalette = opts.showSelectionPalette,
localStorageKey = opts.localStorageKey,
theme = opts.theme,
callbacks = opts.callbacks,
resize = throttle(reflow, 10),
visible = false,
isDragging = false,
dragWidth = 0,
dragHeight = 0,
dragHelperHeight = 0,
slideHeight = 0,
slideWidth = 0,
alphaWidth = 0,
alphaSlideHelperWidth = 0,
slideHelperHeight = 0,
currentHue = 0,
currentSaturation = 0,
currentValue = 0,
currentAlpha = 1,
palette = [],
paletteArray = [],
paletteLookup = {},
selectionPalette = opts.selectionPalette.slice(0),
maxSelectionSize = opts.maxSelectionSize,
draggingClass = "sp-dragging",
shiftMovementDirection = null;
var doc = element.ownerDocument,
body = doc.body,
boundElement = $(element),
disabled = false,
container = $(markup, doc).addClass(theme),
pickerContainer = container.find(".sp-picker-container"),
dragger = container.find(".sp-color"),
dragHelper = container.find(".sp-dragger"),
slider = container.find(".sp-hue"),
slideHelper = container.find(".sp-slider"),
alphaSliderInner = container.find(".sp-alpha-inner"),
alphaSlider = container.find(".sp-alpha"),
alphaSlideHelper = container.find(".sp-alpha-handle"),
textInput = container.find(".sp-input"),
paletteContainer = container.find(".sp-palette"),
initialColorContainer = container.find(".sp-initial"),
cancelButton = container.find(".sp-cancel"),
clearButton = container.find(".sp-clear"),
chooseButton = container.find(".sp-choose"),
toggleButton = container.find(".sp-palette-toggle"),
isInput = boundElement.is("input"),
isInputTypeColor = isInput && boundElement.attr("type") === "color" && inputTypeColorSupport(),
shouldReplace = isInput && !flat,
replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]),
offsetElement = (shouldReplace) ? replacer : boundElement,
previewElement = replacer.find(".sp-preview-inner"),
initialColor = opts.color || (isInput && boundElement.val()),
colorOnShow = false,
preferredFormat = opts.preferredFormat,
currentPreferredFormat = preferredFormat,
clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
isEmpty = !initialColor,
allowEmpty = opts.allowEmpty && !isInputTypeColor;
function applyOptions() {
if (opts.showPaletteOnly) {
opts.showPalette = true;
}
toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
if (opts.palette) {
palette = opts.palette.slice(0);
paletteArray = $.isArray(palette[0]) ? palette : [palette];
paletteLookup = {};
for (var i = 0; i < paletteArray.length; i++) {
for (var j = 0; j < paletteArray[i].length; j++) {
var rgb = tinycolor(paletteArray[i][j]).toRgbString();
paletteLookup[rgb] = true;
}
}
}
container.toggleClass("sp-flat", flat);
container.toggleClass("sp-input-disabled", !opts.showInput);
container.toggleClass("sp-alpha-enabled", opts.showAlpha);
container.toggleClass("sp-clear-enabled", allowEmpty);
container.toggleClass("sp-buttons-disabled", !opts.showButtons);
container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly);
container.toggleClass("sp-palette-disabled", !opts.showPalette);
container.toggleClass("sp-palette-only", opts.showPaletteOnly);
container.toggleClass("sp-initial-disabled", !opts.showInitial);
container.addClass(opts.className).addClass(opts.containerClassName);
reflow();
}
function initialize() {
if (IE) {
container.find("*:not(input)").attr("unselectable", "on");
}
applyOptions();
if (shouldReplace) {
boundElement.after(replacer).hide();
}
if (!allowEmpty) {
clearButton.hide();
}
if (flat) {
boundElement.after(container).hide();
}
else {
var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
if (appendTo.length !== 1) {
appendTo = $("body");
}
appendTo.append(container);
}
updateSelectionPaletteFromStorage();
offsetElement.bind("click.spectrum touchstart.spectrum", function (e) {
if (!disabled) {
toggle();
}
e.stopPropagation();
if (!$(e.target).is("input")) {
e.preventDefault();
}
});
if(boundElement.is(":disabled") || (opts.disabled === true)) {
disable();
}
// Prevent clicks from bubbling up to document. This would cause it to be hidden.
container.click(stopPropagation);
// Handle user typed input
textInput.change(setFromTextInput);
textInput.bind("paste", function () {
setTimeout(setFromTextInput, 1);
});
textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });
cancelButton.text(opts.cancelText);
cancelButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
revert();
hide();
});
clearButton.attr("title", opts.clearText);
clearButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
isEmpty = true;
move();
if(flat) {
//for the flat style, this is a change event
updateOriginalInput(true);
}
});
chooseButton.text(opts.chooseText);
chooseButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
if (IE && textInput.is(":focus")) {
textInput.trigger('change');
}
if (isValid()) {
updateOriginalInput(true);
hide();
}
});
toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
toggleButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
opts.showPaletteOnly = !opts.showPaletteOnly;
// To make sure the Picker area is drawn on the right, next to the
// Palette area (and not below the palette), first move the Palette
// to the left to make space for the picker, plus 5px extra.
// The 'applyOptions' function puts the whole container back into place
// and takes care of the button-text and the sp-palette-only CSS class.
if (!opts.showPaletteOnly && !flat) {
container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
}
applyOptions();
});
draggable(alphaSlider, function (dragX, dragY, e) {
currentAlpha = (dragX / alphaWidth);
isEmpty = false;
if (e.shiftKey) {
currentAlpha = Math.round(currentAlpha * 10) / 10;
}
move();
}, dragStart, dragStop);
draggable(slider, function (dragX, dragY) {
currentHue = parseFloat(dragY / slideHeight);
isEmpty = false;
if (!opts.showAlpha) {
currentAlpha = 1;
}
move();
}, dragStart, dragStop);
draggable(dragger, function (dragX, dragY, e) {
// shift+drag should snap the movement to either the x or y axis.
if (!e.shiftKey) {
shiftMovementDirection = null;
}
else if (!shiftMovementDirection) {
var oldDragX = currentSaturation * dragWidth;
var oldDragY = dragHeight - (currentValue * dragHeight);
var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
shiftMovementDirection = furtherFromX ? "x" : "y";
}
var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
var setValue = !shiftMovementDirection || shiftMovementDirection === "y";
if (setSaturation) {
currentSaturation = parseFloat(dragX / dragWidth);
}
if (setValue) {
currentValue = parseFloat((dragHeight - dragY) / dragHeight);
}
isEmpty = false;
if (!opts.showAlpha) {
currentAlpha = 1;
}
move();
}, dragStart, dragStop);
if (!!initialColor) {
set(initialColor);
// In case color was black - update the preview UI and set the format
// since the set function will not run (default color is black).
updateUI();
currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;
addColorToSelectionPalette(initialColor);
}
else {
updateUI();
}
if (flat) {
show();
}
function paletteElementClick(e) {
if (e.data && e.data.ignore) {
set($(e.target).closest(".sp-thumb-el").data("color"));
move();
}
else {
set($(e.target).closest(".sp-thumb-el").data("color"));
move();
updateOriginalInput(true);
if (opts.hideAfterPaletteSelect) {
hide();
}
}
return false;
}
var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
paletteContainer.delegate(".sp-thumb-el", paletteEvent, paletteElementClick);
initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, paletteElementClick);
}
function updateSelectionPaletteFromStorage() {
if (localStorageKey && window.localStorage) {
// Migrate old palettes over to new format. May want to remove this eventually.
try {
var oldPalette = window.localStorage[localStorageKey].split(",#");
if (oldPalette.length > 1) {
delete window.localStorage[localStorageKey];
$.each(oldPalette, function(i, c) {
addColorToSelectionPalette(c);
});
}
}
catch(e) { }
try {
selectionPalette = window.localStorage[localStorageKey].split(";");
}
catch (e) { }
}
}
function addColorToSelectionPalette(color) {
if (showSelectionPalette) {
var rgb = tinycolor(color).toRgbString();
if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
selectionPalette.push(rgb);
while(selectionPalette.length > maxSelectionSize) {
selectionPalette.shift();
}
}
if (localStorageKey && window.localStorage) {
try {
window.localStorage[localStorageKey] = selectionPalette.join(";");
}
catch(e) { }
}
}
}
function getUniqueSelectionPalette() {
var unique = [];
if (opts.showPalette) {
for (var i = 0; i < selectionPalette.length; i++) {
var rgb = tinycolor(selectionPalette[i]).toRgbString();
if (!paletteLookup[rgb]) {
unique.push(selectionPalette[i]);
}
}
}
return unique.reverse().slice(0, opts.maxSelectionSize);
}
function drawPalette() {
var currentColor = get();
var html = $.map(paletteArray, function (palette, i) {
return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts);
});
updateSelectionPaletteFromStorage();
if (selectionPalette) {
html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts));
}
paletteContainer.html(html.join(""));
}
function drawInitial() {
if (opts.showInitial) {
var initial = colorOnShow;
var current = get();
initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts));
}
}
function dragStart() {
if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
reflow();
}
isDragging = true;
container.addClass(draggingClass);
shiftMovementDirection = null;
boundElement.trigger('dragstart.spectrum', [ get() ]);
}
function dragStop() {
isDragging = false;
container.removeClass(draggingClass);
boundElement.trigger('dragstop.spectrum', [ get() ]);
}
function setFromTextInput() {
var value = textInput.val();
if ((value === null || value === "") && allowEmpty) {
set(null);
updateOriginalInput(true);
}
else {
var tiny = tinycolor(value);
if (tiny.isValid()) {
set(tiny);
updateOriginalInput(true);
}
else {
textInput.addClass("sp-validation-error");
}
}
}
function toggle() {
if (visible) {
hide();
}
else {
show();
}
}
function show() {
var event = $.Event('beforeShow.spectrum');
if (visible) {
reflow();
return;
}
boundElement.trigger(event, [ get() ]);
if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
return;
}
hideAll();
visible = true;
$(doc).bind("keydown.spectrum", onkeydown);
$(doc).bind("click.spectrum", clickout);
$(window).bind("resize.spectrum", resize);
replacer.addClass("sp-active");
container.removeClass("sp-hidden");
reflow();
updateUI();
colorOnShow = get();
drawInitial();
callbacks.show(colorOnShow);
boundElement.trigger('show.spectrum', [ colorOnShow ]);
}
function onkeydown(e) {
// Close on ESC
if (e.keyCode === 27) {
hide();
}
}
function clickout(e) {
// Return on right click.
if (e.button == 2) { return; }
// If a drag event was happening during the mouseup, don't hide
// on click.
if (isDragging) { return; }
if (clickoutFiresChange) {
updateOriginalInput(true);
}
else {
revert();
}
hide();
}
function hide() {
// Return if hiding is unnecessary
if (!visible || flat) { return; }
visible = false;
$(doc).unbind("keydown.spectrum", onkeydown);
$(doc).unbind("click.spectrum", clickout);
$(window).unbind("resize.spectrum", resize);
replacer.removeClass("sp-active");
container.addClass("sp-hidden");
callbacks.hide(get());
boundElement.trigger('hide.spectrum', [ get() ]);
}
function revert() {
set(colorOnShow, true);
}
function set(color, ignoreFormatChange) {
if (tinycolor.equals(color, get())) {
// Update UI just in case a validation error needs
// to be cleared.
updateUI();
return;
}
var newColor, newHsv;
if (!color && allowEmpty) {
isEmpty = true;
} else {
isEmpty = false;
newColor = tinycolor(color);
newHsv = newColor.toHsv();
currentHue = (newHsv.h % 360) / 360;
currentSaturation = newHsv.s;
currentValue = newHsv.v;
currentAlpha = newHsv.a;
}
updateUI();
if (newColor && newColor.isValid() && !ignoreFormatChange) {
currentPreferredFormat = preferredFormat || newColor.getFormat();
}
}
function get(opts) {
opts = opts || { };
if (allowEmpty && isEmpty) {
return null;
}
return tinycolor.fromRatio({
h: currentHue,
s: currentSaturation,
v: currentValue,
a: Math.round(currentAlpha * 100) / 100
}, { format: opts.format || currentPreferredFormat });
}
function isValid() {
return !textInput.hasClass("sp-validation-error");
}
function move() {
updateUI();
callbacks.move(get());
boundElement.trigger('move.spectrum', [ get() ]);
}
function updateUI() {
textInput.removeClass("sp-validation-error");
updateHelperLocations();
// Update dragger background color (gradients take care of saturation and value).
var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
dragger.css("background-color", flatColor.toHexString());
// Get a format that alpha will be included in (hex and names ignore alpha)
var format = currentPreferredFormat;
if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
format = "rgb";
}
}
var realColor = get({ format: format }),
displayColor = '';
//reset background info for preview element
previewElement.removeClass("sp-clear-display");
previewElement.css('background-color', 'transparent');
if (!realColor && allowEmpty) {
// Update the replaced elements background with icon indicating no color selection
previewElement.addClass("sp-clear-display");
}
else {
var realHex = realColor.toHexString(),
realRgb = realColor.toRgbString();
// Update the replaced elements background color (with actual selected color)
if (rgbaSupport || realColor.alpha === 1) {
previewElement.css("background-color", realRgb);
}
else {
previewElement.css("background-color", "transparent");
previewElement.css("filter", realColor.toFilter());
}
if (opts.showAlpha) {
var rgb = realColor.toRgb();
rgb.a = 0;
var realAlpha = tinycolor(rgb).toRgbString();
var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";
if (IE) {
alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
}
else {
alphaSliderInner.css("background", "-webkit-" + gradient);
alphaSliderInner.css("background", "-moz-" + gradient);
alphaSliderInner.css("background", "-ms-" + gradient);
// Use current syntax gradient on unprefixed property.
alphaSliderInner.css("background",
"linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
}
}
displayColor = realColor.toString(format);
}
// Update the text entry input as it changes happen
if (opts.showInput) {
textInput.val(displayColor);
}
if (opts.showPalette) {
drawPalette();
}
drawInitial();
}
function updateHelperLocations() {
var s = currentSaturation;
var v = currentValue;
if(allowEmpty && isEmpty) {
//if selected color is empty, hide the helpers
alphaSlideHelper.hide();
slideHelper.hide();
dragHelper.hide();
}
else {
//make sure helpers are visible
alphaSlideHelper.show();
slideHelper.show();
dragHelper.show();
// Where to show the little circle in that displays your current selected color
var dragX = s * dragWidth;
var dragY = dragHeight - (v * dragHeight);
dragX = Math.max(
-dragHelperHeight,
Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
);
dragY = Math.max(
-dragHelperHeight,
Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
);
dragHelper.css({
"top": dragY + "px",
"left": dragX + "px"
});
var alphaX = currentAlpha * alphaWidth;
alphaSlideHelper.css({
"left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
});
// Where to show the bar that displays your current selected hue
var slideY = (currentHue) * slideHeight;
slideHelper.css({
"top": (slideY - slideHelperHeight) + "px"
});
}
}
function updateOriginalInput(fireCallback) {
var color = get(),
displayColor = '',
hasChanged = !tinycolor.equals(color, colorOnShow);
if (color) {
displayColor = color.toString(currentPreferredFormat);
// Update the selection palette with the current color
addColorToSelectionPalette(color);
}
if (isInput) {
boundElement.val(displayColor);
}
if (fireCallback && hasChanged) {
callbacks.change(color);
boundElement.trigger('change', [ color ]);
}
}
function reflow() {
dragWidth = dragger.width();
dragHeight = dragger.height();
dragHelperHeight = dragHelper.height();
slideWidth = slider.width();
slideHeight = slider.height();
slideHelperHeight = slideHelper.height();
alphaWidth = alphaSlider.width();
alphaSlideHelperWidth = alphaSlideHelper.width();
if (!flat) {
container.css("position", "absolute");
if (opts.offset) {
container.offset(opts.offset);
} else {
container.offset(getOffset(container, offsetElement));
}
}
updateHelperLocations();
if (opts.showPalette) {
drawPalette();
}
boundElement.trigger('reflow.spectrum');
}
function destroy() {
boundElement.show();
offsetElement.unbind("click.spectrum touchstart.spectrum");
container.remove();
replacer.remove();
spectrums[spect.id] = null;
}
function option(optionName, optionValue) {
if (optionName === undefined) {
return $.extend({}, opts);
}
if (optionValue === undefined) {
return opts[optionName];
}
opts[optionName] = optionValue;
applyOptions();
}
function enable() {
disabled = false;
boundElement.attr("disabled", false);
offsetElement.removeClass("sp-disabled");
}
function disable() {
hide();
disabled = true;
boundElement.attr("disabled", true);
offsetElement.addClass("sp-disabled");
}
function setOffset(coord) {
opts.offset = coord;
reflow();
}
initialize();
var spect = {
show: show,
hide: hide,
toggle: toggle,
reflow: reflow,
option: option,
enable: enable,
disable: disable,
offset: setOffset,
set: function (c) {
set(c);
updateOriginalInput();
},
get: get,
destroy: destroy,
container: container
};
spect.id = spectrums.push(spect) - 1;
return spect;
}
/**
* checkOffset - get the offset below/above and left/right element depending on screen position
* Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
*/
function getOffset(picker, input) {
var extraY = 0;
var dpWidth = picker.outerWidth();
var dpHeight = picker.outerHeight();
var inputHeight = input.outerHeight();
var doc = picker[0].ownerDocument;
var docElem = doc.documentElement;
var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
var viewHeight = docElem.clientHeight + $(doc).scrollTop();
var offset = input.offset();
offset.top += inputHeight;
offset.left -=
Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -=
Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight - extraY) : extraY));
return offset;
}
/**
* noop - do nothing
*/
function noop() {
}
/**
* stopPropagation - makes the code only doing this a little easier to read in line
*/
function stopPropagation(e) {
e.stopPropagation();
}
/**
* Create a function bound to a given object
* Thanks to underscore.js
*/
function bind(func, obj) {
var slice = Array.prototype.slice;
var args = slice.call(arguments, 2);
return function () {
return func.apply(obj, args.concat(slice.call(arguments)));
};
}
/**
* Lightweight drag helper. Handles containment within the element, so that
* when dragging, the x is within [0,element.width] and y is within [0,element.height]
*/
function draggable(element, onmove, onstart, onstop) {
onmove = onmove || function () { };
onstart = onstart || function () { };
onstop = onstop || function () { };
var doc = document;
var dragging = false;
var offset = {};
var maxHeight = 0;
var maxWidth = 0;
var hasTouch = ('ontouchstart' in window);
var duringDragEvents = {};
duringDragEvents["selectstart"] = prevent;
duringDragEvents["dragstart"] = prevent;
duringDragEvents["touchmove mousemove"] = move;
duringDragEvents["touchend mouseup"] = stop;
function prevent(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
function move(e) {
if (dragging) {
// Mouseup happened outside of window
if (IE && doc.documentMode < 9 && !e.button) {
return stop();
}
var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0];
var pageX = t0 && t0.pageX || e.pageX;
var pageY = t0 && t0.pageY || e.pageY;
var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));
if (hasTouch) {
// Stop scrolling in iOS
prevent(e);
}
onmove.apply(element, [dragX, dragY, e]);
}
}
function start(e) {
var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);
if (!rightclick && !dragging) {
if (onstart.apply(element, arguments) !== false) {
dragging = true;
maxHeight = $(element).height();
maxWidth = $(element).width();
offset = $(element).offset();
$(doc).bind(duringDragEvents);
$(doc.body).addClass("sp-dragging");
move(e);
prevent(e);
}
}
}
function stop() {
if (dragging) {
$(doc).unbind(duringDragEvents);
$(doc.body).removeClass("sp-dragging");
// Wait a tick before notifying observers to allow the click event
// to fire in Chrome.
setTimeout(function() {
onstop.apply(element, arguments);
}, 0);
}
dragging = false;
}
$(element).bind("touchstart mousedown", start);
}
function throttle(func, wait, debounce) {
var timeout;
return function () {
var context = this, args = arguments;
var throttler = function () {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
}
function inputTypeColorSupport() {
return $.fn.spectrum.inputTypeColorSupport();
}
/**
* Define a jQuery plugin
*/
var dataID = "spectrum.id";
$.fn.spectrum = function (opts, extra) {
if (typeof opts == "string") {
var returnValue = this;
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function () {
var spect = spectrums[$(this).data(dataID)];
if (spect) {
var method = spect[opts];
if (!method) {
throw new Error( "Spectrum: no such method: '" + opts + "'" );
}
if (opts == "get") {
returnValue = spect.get();
}
else if (opts == "container") {
returnValue = spect.container;
}
else if (opts == "option") {
returnValue = spect.option.apply(spect, args);
}
else if (opts == "destroy") {
spect.destroy();
$(this).removeData(dataID);
}
else {
method.apply(spect, args);
}
}
});
return returnValue;
}
// Initializing a new instance of spectrum
return this.spectrum("destroy").each(function () {
var options = $.extend({}, opts, $(this).data());
var spect = spectrum(this, options);
$(this).data(dataID, spect.id);
});
};
$.fn.spectrum.load = true;
$.fn.spectrum.loadOpts = {};
$.fn.spectrum.draggable = draggable;
$.fn.spectrum.defaults = defaultOpts;
$.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
if (typeof inputTypeColorSupport._cachedResult === "undefined") {
var colorInput = $("<input type='color' value='!' />")[0];
inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== "!";
}
return inputTypeColorSupport._cachedResult;
};
$.spectrum = { };
$.spectrum.localization = { };
$.spectrum.palettes = { };
$.fn.spectrum.processNativeColorInputs = function () {
var colorInputs = $("input[type=color]");
if (colorInputs.length && !inputTypeColorSupport()) {
colorInputs.spectrum({
preferredFormat: "hex6"
});
}
};
// TinyColor v1.1.2
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License
(function() {
var trimLeft = /^[\s,#]+/,
trimRight = /\s+$/,
tinyCounter = 0,
math = Math,
mathRound = math.round,
mathMin = math.min,
mathMax = math.max,
mathRandom = math.random;
var tinycolor = function(color, opts) {
color = (color) ? color : '';
opts = opts || { };
// If input is already a tinycolor, return itself
if (color instanceof tinycolor) {
return color;
}
// If we are called as a function, call using new instead
if (!(this instanceof tinycolor)) {
return new tinycolor(color, opts);
}
var rgb = inputToRGB(color);
this._originalInput = color,
this._r = rgb.r,
this._g = rgb.g,
this._b = rgb.b,
this._a = rgb.a,
this._roundA = mathRound(100*this._a) / 100,
this._format = opts.format || rgb.format;
this._gradientType = opts.gradientType;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (this._r < 1) { this._r = mathRound(this._r); }
if (this._g < 1) { this._g = mathRound(this._g); }
if (this._b < 1) { this._b = mathRound(this._b); }
this._ok = rgb.ok;
this._tc_id = tinyCounter++;
};
tinycolor.prototype = {
isDark: function() {
return this.getBrightness() < 128;
},
isLight: function() {
return !this.isDark();
},
isValid: function() {
return this._ok;
},
getOriginalInput: function() {
return this._originalInput;
},
getFormat: function() {
return this._format;
},
getAlpha: function() {
return this._a;
},
getBrightness: function() {
var rgb = this.toRgb();
return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
},
setAlpha: function(value) {
this._a = boundAlpha(value);
this._roundA = mathRound(100*this._a) / 100;
return this;
},
toHsv: function() {
var hsv = rgbToHsv(this._r, this._g, this._b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
},
toHsvString: function() {
var hsv = rgbToHsv(this._r, this._g, this._b);
var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
return (this._a == 1) ?
"hsv(" + h + ", " + s + "%, " + v + "%)" :
"hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
},
toHsl: function() {
var hsl = rgbToHsl(this._r, this._g, this._b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
},
toHslString: function() {
var hsl = rgbToHsl(this._r, this._g, this._b);
var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
return (this._a == 1) ?
"hsl(" + h + ", " + s + "%, " + l + "%)" :
"hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
},
toHex: function(allow3Char) {
return rgbToHex(this._r, this._g, this._b, allow3Char);
},
toHexString: function(allow3Char) {
return '#' + this.toHex(allow3Char);
},
toHex8: function() {
return rgbaToHex(this._r, this._g, this._b, this._a);
},
toHex8String: function() {
return '#' + this.toHex8();
},
toRgb: function() {
return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
},
toRgbString: function() {
return (this._a == 1) ?
"rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
"rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
},
toPercentageRgb: function() {
return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
},
toPercentageRgbString: function() {
return (this._a == 1) ?
"rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
"rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
},
toName: function() {
if (this._a === 0) {
return "transparent";
}
if (this._a < 1) {
return false;
}
return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
},
toFilter: function(secondColor) {
var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
var secondHex8String = hex8String;
var gradientType = this._gradientType ? "GradientType = 1, " : "";
if (secondColor) {
var s = tinycolor(secondColor);
secondHex8String = s.toHex8String();
}
return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
},
toString: function(format) {
var formatSet = !!format;
format = format || this._format;
var formattedString = false;
var hasAlpha = this._a < 1 && this._a >= 0;
var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
if (needsAlphaFormat) {
// Special case for "transparent", all other non-alpha formats
// will return rgba when there is transparency.
if (format === "name" && this._a === 0) {
return this.toName();
}
return this.toRgbString();
}
if (format === "rgb") {
formattedString = this.toRgbString();
}
if (format === "prgb") {
formattedString = this.toPercentageRgbString();
}
if (format === "hex" || format === "hex6") {
formattedString = this.toHexString();
}
if (format === "hex3") {
formattedString = this.toHexString(true);
}
if (format === "hex8") {
formattedString = this.toHex8String();
}
if (format === "name") {
formattedString = this.toName();
}
if (format === "hsl") {
formattedString = this.toHslString();
}
if (format === "hsv") {
formattedString = this.toHsvString();
}
return formattedString || this.toHexString();
},
_applyModification: function(fn, args) {
var color = fn.apply(null, [this].concat([].slice.call(args)));
this._r = color._r;
this._g = color._g;
this._b = color._b;
this.setAlpha(color._a);
return this;
},
lighten: function() {
return this._applyModification(lighten, arguments);
},
brighten: function() {
return this._applyModification(brighten, arguments);
},
darken: function() {
return this._applyModification(darken, arguments);
},
desaturate: function() {
return this._applyModification(desaturate, arguments);
},
saturate: function() {
return this._applyModification(saturate, arguments);
},
greyscale: function() {
return this._applyModification(greyscale, arguments);
},
spin: function() {
return this._applyModification(spin, arguments);
},
_applyCombination: function(fn, args) {
return fn.apply(null, [this].concat([].slice.call(args)));
},
analogous: function() {
return this._applyCombination(analogous, arguments);
},
complement: function() {
return this._applyCombination(complement, arguments);
},
monochromatic: function() {
return this._applyCombination(monochromatic, arguments);
},
splitcomplement: function() {
return this._applyCombination(splitcomplement, arguments);
},
triad: function() {
return this._applyCombination(triad, arguments);
},
tetrad: function() {
return this._applyCombination(tetrad, arguments);
}
};
// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
if (typeof color == "object") {
var newColor = {};
for (var i in color) {
if (color.hasOwnProperty(i)) {
if (i === "a") {
newColor[i] = color[i];
}
else {
newColor[i] = convertToPercentage(color[i]);
}
}
}
color = newColor;
}
return tinycolor(color, opts);
};
// Given a string or object, convert that input to RGB
// Possible string inputs:
//
// "red"
// "#f00" or "f00"
// "#ff0000" or "ff0000"
// "#ff000000" or "ff000000"
// "rgb 255 0 0" or "rgb (255, 0, 0)"
// "rgb 1.0 0 0" or "rgb (1, 0, 0)"
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {
var rgb = { r: 0, g: 0, b: 0 };
var a = 1;
var ok = false;
var format = false;
if (typeof color == "string") {
color = stringInputToObject(color);
}
if (typeof color == "object") {
if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
rgb = rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
}
else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
color.s = convertToPercentage(color.s);
color.v = convertToPercentage(color.v);
rgb = hsvToRgb(color.h, color.s, color.v);
ok = true;
format = "hsv";
}
else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
color.s = convertToPercentage(color.s);
color.l = convertToPercentage(color.l);
rgb = hslToRgb(color.h, color.s, color.l);
ok = true;
format = "hsl";
}
if (color.hasOwnProperty("a")) {
a = color.a;
}
}
a = boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a
};
}
// Conversion Functions
// --------------------
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <https://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <https://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};
}
// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min) {
h = s = 0; // achromatic
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
var r, g, b;
h = bound01(h, 360);
s = bound01(s, 100);
l = bound01(l, 100);
function hue2rgb(p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
if(s === 0) {
r = g = b = l; // achromatic
}
else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min) {
h = 0; // achromatic
}
else {
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, v: v };
}
// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hsvToRgb(h, s, v) {
h = bound01(h, 360) * 6;
s = bound01(s, 100);
v = bound01(v, 100);
var i = math.floor(h),
f = h - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
mod = i % 6,
r = [v, q, p, p, t, v][mod],
g = [t, v, v, q, p, p][mod],
b = [p, p, t, v, v, q][mod];
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {
var hex = [
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
// Return a 3 character hex if possible
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b and a are contained in the set [0, 255]
// Returns an 8 character hex
function rgbaToHex(r, g, b, a) {
var hex = [
pad2(convertDecimalToHex(a)),
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
return hex.join("");
}
// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
if (!color1 || !color2) { return false; }
return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};
tinycolor.random = function() {
return tinycolor.fromRatio({
r: mathRandom(),
g: mathRandom(),
b: mathRandom()
});
};
// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
function desaturate(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s -= amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function saturate(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s += amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function greyscale(color) {
return tinycolor(color).desaturate(100);
}
function lighten (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l += amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
function brighten(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var rgb = tinycolor(color).toRgb();
rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
return tinycolor(rgb);
}
function darken (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l -= amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
var hsl = tinycolor(color).toHsl();
var hue = (mathRound(hsl.h) + amount) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return tinycolor(hsl);
}
// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
function complement(color) {
var hsl = tinycolor(color).toHsl();
hsl.h = (hsl.h + 180) % 360;
return tinycolor(hsl);
}
function triad(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
];
}
function tetrad(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
];
}
function splitcomplement(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
];
}
function analogous(color, results, slices) {
results = results || 6;
slices = slices || 30;
var hsl = tinycolor(color).toHsl();
var part = 360 / slices;
var ret = [tinycolor(color)];
for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
hsl.h = (hsl.h + part) % 360;
ret.push(tinycolor(hsl));
}
return ret;
}
function monochromatic(color, results) {
results = results || 6;
var hsv = tinycolor(color).toHsv();
var h = hsv.h, s = hsv.s, v = hsv.v;
var ret = [];
var modification = 1 / results;
while (results--) {
ret.push(tinycolor({ h: h, s: s, v: v}));
v = (v + modification) % 1;
}
return ret;
}
// Utility Functions
// ---------------------
tinycolor.mix = function(color1, color2, amount) {
amount = (amount === 0) ? 0 : (amount || 50);
var rgb1 = tinycolor(color1).toRgb();
var rgb2 = tinycolor(color2).toRgb();
var p = amount / 100;
var w = p * 2 - 1;
var a = rgb2.a - rgb1.a;
var w1;
if (w * a == -1) {
w1 = w;
} else {
w1 = (w + a) / (1 + w * a);
}
w1 = (w1 + 1) / 2;
var w2 = 1 - w1;
var rgba = {
r: rgb2.r * w1 + rgb1.r * w2,
g: rgb2.g * w1 + rgb1.g * w2,
b: rgb2.b * w1 + rgb1.b * w2,
a: rgb2.a * p + rgb1.a * (1 - p)
};
return tinycolor(rgba);
};
// Readability Functions
// ---------------------
// <https://www.w3.org/TR/AERT#color-contrast>
// `readability`
// Analyze the 2 colors and returns an object with the following properties:
// `brightness`: difference in brightness between the two colors
// `color`: difference in color/hue between the two colors
tinycolor.readability = function(color1, color2) {
var c1 = tinycolor(color1);
var c2 = tinycolor(color2);
var rgb1 = c1.toRgb();
var rgb2 = c2.toRgb();
var brightnessA = c1.getBrightness();
var brightnessB = c2.getBrightness();
var colorDiff = (
Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
);
return {
brightness: Math.abs(brightnessA - brightnessB),
color: colorDiff
};
};
// `readable`
// https://www.w3.org/TR/AERT#color-contrast
// Ensure that foreground and background color combinations provide sufficient contrast.
// *Example*
// tinycolor.isReadable("#000", "#111") => false
tinycolor.isReadable = function(color1, color2) {
var readability = tinycolor.readability(color1, color2);
return readability.brightness > 125 && readability.color > 500;
};
// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// *Example*
// tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
tinycolor.mostReadable = function(baseColor, colorList) {
var bestColor = null;
var bestScore = 0;
var bestIsReadable = false;
for (var i=0; i < colorList.length; i++) {
// We normalize both around the "acceptable" breaking point,
// but rank brightness constrast higher than hue.
var readability = tinycolor.readability(baseColor, colorList[i]);
var readable = readability.brightness > 125 && readability.color > 500;
var score = 3 * (readability.brightness / 125) + (readability.color / 500);
if ((readable && ! bestIsReadable) ||
(readable && bestIsReadable && score > bestScore) ||
((! readable) && (! bestIsReadable) && score > bestScore)) {
bestIsReadable = readable;
bestScore = score;
bestColor = tinycolor(colorList[i]);
}
}
return bestColor;
};
// Big List of Colors
// ------------------
// <https://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
aliceblue: "f0f8ff",
antiquewhite: "faebd7",
aqua: "0ff",
aquamarine: "7fffd4",
azure: "f0ffff",
beige: "f5f5dc",
bisque: "ffe4c4",
black: "000",
blanchedalmond: "ffebcd",
blue: "00f",
blueviolet: "8a2be2",
brown: "a52a2a",
burlywood: "deb887",
burntsienna: "ea7e5d",
cadetblue: "5f9ea0",
chartreuse: "7fff00",
chocolate: "d2691e",
coral: "ff7f50",
cornflowerblue: "6495ed",
cornsilk: "fff8dc",
crimson: "dc143c",
cyan: "0ff",
darkblue: "00008b",
darkcyan: "008b8b",
darkgoldenrod: "b8860b",
darkgray: "a9a9a9",
darkgreen: "006400",
darkgrey: "a9a9a9",
darkkhaki: "bdb76b",
darkmagenta: "8b008b",
darkolivegreen: "556b2f",
darkorange: "ff8c00",
darkorchid: "9932cc",
darkred: "8b0000",
darksalmon: "e9967a",
darkseagreen: "8fbc8f",
darkslateblue: "483d8b",
darkslategray: "2f4f4f",
darkslategrey: "2f4f4f",
darkturquoise: "00ced1",
darkviolet: "9400d3",
deeppink: "ff1493",
deepskyblue: "00bfff",
dimgray: "696969",
dimgrey: "696969",
dodgerblue: "1e90ff",
firebrick: "b22222",
floralwhite: "fffaf0",
forestgreen: "228b22",
fuchsia: "f0f",
gainsboro: "dcdcdc",
ghostwhite: "f8f8ff",
gold: "ffd700",
goldenrod: "daa520",
gray: "808080",
green: "008000",
greenyellow: "adff2f",
grey: "808080",
honeydew: "f0fff0",
hotpink: "ff69b4",
indianred: "cd5c5c",
indigo: "4b0082",
ivory: "fffff0",
khaki: "f0e68c",
lavender: "e6e6fa",
lavenderblush: "fff0f5",
lawngreen: "7cfc00",
lemonchiffon: "fffacd",
lightblue: "add8e6",
lightcoral: "f08080",
lightcyan: "e0ffff",
lightgoldenrodyellow: "fafad2",
lightgray: "d3d3d3",
lightgreen: "90ee90",
lightgrey: "d3d3d3",
lightpink: "ffb6c1",
lightsalmon: "ffa07a",
lightseagreen: "20b2aa",
lightskyblue: "87cefa",
lightslategray: "789",
lightslategrey: "789",
lightsteelblue: "b0c4de",
lightyellow: "ffffe0",
lime: "0f0",
limegreen: "32cd32",
linen: "faf0e6",
magenta: "f0f",
maroon: "800000",
mediumaquamarine: "66cdaa",
mediumblue: "0000cd",
mediumorchid: "ba55d3",
mediumpurple: "9370db",
mediumseagreen: "3cb371",
mediumslateblue: "7b68ee",
mediumspringgreen: "00fa9a",
mediumturquoise: "48d1cc",
mediumvioletred: "c71585",
midnightblue: "191970",
mintcream: "f5fffa",
mistyrose: "ffe4e1",
moccasin: "ffe4b5",
navajowhite: "ffdead",
navy: "000080",
oldlace: "fdf5e6",
olive: "808000",
olivedrab: "6b8e23",
orange: "ffa500",
orangered: "ff4500",
orchid: "da70d6",
palegoldenrod: "eee8aa",
palegreen: "98fb98",
paleturquoise: "afeeee",
palevioletred: "db7093",
papayawhip: "ffefd5",
peachpuff: "ffdab9",
peru: "cd853f",
pink: "ffc0cb",
plum: "dda0dd",
powderblue: "b0e0e6",
purple: "800080",
rebeccapurple: "663399",
red: "f00",
rosybrown: "bc8f8f",
royalblue: "4169e1",
saddlebrown: "8b4513",
salmon: "fa8072",
sandybrown: "f4a460",
seagreen: "2e8b57",
seashell: "fff5ee",
sienna: "a0522d",
silver: "c0c0c0",
skyblue: "87ceeb",
slateblue: "6a5acd",
slategray: "708090",
slategrey: "708090",
snow: "fffafa",
springgreen: "00ff7f",
steelblue: "4682b4",
tan: "d2b48c",
teal: "008080",
thistle: "d8bfd8",
tomato: "ff6347",
turquoise: "40e0d0",
violet: "ee82ee",
wheat: "f5deb3",
white: "fff",
whitesmoke: "f5f5f5",
yellow: "ff0",
yellowgreen: "9acd32"
};
// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);
// Utilities
// ---------
// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
var flipped = { };
for (var i in o) {
if (o.hasOwnProperty(i)) {
flipped[o[i]] = i;
}
}
return flipped;
}
// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
if (isOnePointZero(n)) { n = "100%"; }
var processPercent = isPercentage(n);
n = mathMin(max, mathMax(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt(n * max, 10) / 100;
}
// Handle floating point rounding errors
if ((math.abs(n - max) < 0.000001)) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / parseFloat(max);
}
// Force a number between 0 and 1
function clamp01(val) {
return mathMin(1, mathMax(0, val));
}
// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
return parseInt(val, 16);
}
// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <https://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}
// Check to see if string passed in is a percentage
function isPercentage(n) {
return typeof n === "string" && n.indexOf('%') != -1;
}
// Force a hex value to have 2 characters
function pad2(c) {
return c.length == 1 ? '0' + c : '' + c;
}
// Replace a decimal with it's percentage value
function convertToPercentage(n) {
if (n <= 1) {
n = (n * 100) + "%";
}
return n;
}
// Converts a decimal to a hex value
function convertDecimalToHex(d) {
return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
return (parseIntFromHex(h) / 255);
}
var matchers = (function() {
// <https://www.w3.org/TR/css3-values/#integers>
var CSS_INTEGER = "[-\\+]?\\d+%?";
// <https://www.w3.org/TR/css3-values/#number-value>
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};
})();
// `stringInputToObject`
// Permissive string parsing. Take in a number of formats, and output an object
// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {
color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
var named = false;
if (names[color]) {
color = names[color];
named = true;
}
else if (color == 'transparent') {
return { r: 0, g: 0, b: 0, a: 0, format: "name" };
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
var match;
if ((match = matchers.rgb.exec(color))) {
return { r: match[1], g: match[2], b: match[3] };
}
if ((match = matchers.rgba.exec(color))) {
return { r: match[1], g: match[2], b: match[3], a: match[4] };
}
if ((match = matchers.hsl.exec(color))) {
return { h: match[1], s: match[2], l: match[3] };
}
if ((match = matchers.hsla.exec(color))) {
return { h: match[1], s: match[2], l: match[3], a: match[4] };
}
if ((match = matchers.hsv.exec(color))) {
return { h: match[1], s: match[2], v: match[3] };
}
if ((match = matchers.hsva.exec(color))) {
return { h: match[1], s: match[2], v: match[3], a: match[4] };
}
if ((match = matchers.hex8.exec(color))) {
return {
a: convertHexToDecimal(match[1]),
r: parseIntFromHex(match[2]),
g: parseIntFromHex(match[3]),
b: parseIntFromHex(match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = matchers.hex6.exec(color))) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if ((match = matchers.hex3.exec(color))) {
return {
r: parseIntFromHex(match[1] + '' + match[1]),
g: parseIntFromHex(match[2] + '' + match[2]),
b: parseIntFromHex(match[3] + '' + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
window.tinycolor = tinycolor;
})();
$(function () {
if ($.fn.spectrum.load) {
$.fn.spectrum.processNativeColorInputs();
}
});
});
| mit |
EdwardEisenhart/Project_Euler | Problem005/Python/Problem005.py | 738 | from pip._vendor.requests.packages.urllib3.connectionpool import xrange
# Solution to ProjectEuler problem 005 from ProjectEuler.net.
# Calculates the smallest number that is evenly divisible
# by all of the numbers from 1 to 20.
# Created By: Edward Eisenhart
# Created On: Apr-06-2015
# Contact: [email protected]
# Calculates the LCM (least common multiple) of a and b
def calculateLCM(a, b):
return (a*b)/(calculateGCD(a, b))
# Calculates the GCD (greatest common divisor of a and b)
def calculateGCD(a, b):
# Euclidean algorithm
while b != 0:
t = b
b = a % b
a = t
return a
# Main
sm = 1 #smallest multiple
for i in xrange(2, 20):
sm = calculateLCM(sm, i)
print(sm) | mit |
smartquant/SharpQuant.QuantStudio | SharpQuant.QuantStudio/Startup/SplashScreen.cs | 5431 |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace QuantStudio.Startup
{
public interface ISplashScreen
{
void SetProgressText(string text);
void CloseThis();
}
public class SplashScreen : Form, ISplashScreen
{
private IContainer components;
public Label lblCopyright;
public Label lblProgress;
public Label lblInfoText;
public PictureBox pictureBox;
public SplashScreen()
{
this.InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
{
this.components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SplashScreen));
this.pictureBox = new System.Windows.Forms.PictureBox();
this.lblProgress = new System.Windows.Forms.Label();
this.lblCopyright = new System.Windows.Forms.Label();
this.lblInfoText = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// pictureBox
//
this.pictureBox.BackColor = System.Drawing.Color.White;
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.ErrorImage = ((System.Drawing.Image)(resources.GetObject("pictureBox.ErrorImage")));
this.pictureBox.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox.Image")));
this.pictureBox.Location = new System.Drawing.Point(1, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(398, 156);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// lblProgress
//
this.lblProgress.BackColor = System.Drawing.SystemColors.Control;
this.lblProgress.Dock = System.Windows.Forms.DockStyle.Bottom;
this.lblProgress.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblProgress.Location = new System.Drawing.Point(1, 184);
this.lblProgress.Name = "lblProgress";
this.lblProgress.Padding = new System.Windows.Forms.Padding(5, 5, 0, 0);
this.lblProgress.Size = new System.Drawing.Size(398, 30);
this.lblProgress.TabIndex = 1;
this.lblProgress.Text = "Loading";
//
// lblCopyright
//
this.lblCopyright.BackColor = System.Drawing.Color.White;
this.lblCopyright.Dock = System.Windows.Forms.DockStyle.Top;
this.lblCopyright.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblCopyright.ForeColor = System.Drawing.Color.SteelBlue;
this.lblCopyright.Location = new System.Drawing.Point(1, 1);
this.lblCopyright.Name = "lblCopyright";
this.lblCopyright.Padding = new System.Windows.Forms.Padding(0, 0, 10, 0);
this.lblCopyright.Size = new System.Drawing.Size(398, 27);
this.lblCopyright.TabIndex = 2;
this.lblCopyright.Text = "Copyright (c) 2014 Joachim Loebb All rights reserved.";
this.lblCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblInfoText
//
this.lblInfoText.AutoSize = true;
this.lblInfoText.Location = new System.Drawing.Point(136, 44);
this.lblInfoText.Name = "lblInfoText";
this.lblInfoText.Size = new System.Drawing.Size(16, 13);
this.lblInfoText.TabIndex = 3;
this.lblInfoText.Text = "...";
//
// SplashScreen
//
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(400, 214);
this.ControlBox = false;
this.Controls.Add(this.lblInfoText);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.lblCopyright);
this.Controls.Add(this.lblProgress);
this.Name = "SplashScreen";
this.Padding = new System.Windows.Forms.Padding(1, 1, 1, 0);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "SplashScreen";
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public void SetProgressText(string text)
{
MethodInvoker methodInvoker = () => { lblProgress.Text = text; };
this.lblProgress.Invoke(methodInvoker);
}
public void CloseThis()
{
MethodInvoker methodInvoker = () => { this.Close(); };
this.Invoke(methodInvoker);
}
}
} | mit |
albsierra/instituto | src/IES2Mares/TutoresBundle/Admin/MateriaAdmin.php | 1491 | <?php
/**
* Created by PhpStorm.
* User: alberto
* Date: 2/02/15
* Time: 20:40
*/
namespace IES2Mares\TutoresBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class MateriaAdmin extends Admin
{
protected $baseRouteName = 'sonata_admin_materia';
protected $baseRoutePattern = 'materia';
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('codigo', 'text', array('label' => 'Código'))
->add('materia', 'text', array('label' => 'Materia'))
->add('curso', 'text', array('label' => 'Curso'))
->add('ensenanza', 'text', array('label' => 'Enseñanza'))
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('codigo')
->add('materia')
->add('curso')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('codigo')
->add('materia', 'text', array('label' => 'Materia'))
->add('curso', 'text', array('label' => 'Curso'))
->add('ensenanza', 'text', array('label' => 'Enseñanza'))
;
}
}
| mit |
clarat-org/claradmin | app/concepts/target_audience_filters_offer/create.rb | 549 | # frozen_string_literal: true
class TargetAudienceFiltersOffer::Create < Trailblazer::Operation
step Model(::TargetAudienceFiltersOffer, :new)
step Policy::Pundit(PermissivePolicy, :create?)
step Contract::Build(constant: TargetAudienceFiltersOffer::Contracts::Create)
step Contract::Validate()
step Wrap(::Lib::Transaction) {
step ::Lib::Macros::Nested::Find :target_audience_filter,
::TargetAudienceFilter
step ::Lib::Macros::Nested::Find :offer, ::Offer
}
step Contract::Persist()
end
| mit |
developerdevice/Vourto | Vourto/vendor/__class/Prop.class.php | 136 | <?php
class Prop
{
static function exec($type, $escope, callable $onsuccess = null){
return new Fn($type, $escope, $onsuccess);
}
} | mit |
se-panfilov/jsvat | lib/es6/lib/countries/czechRepublic.js | 2796 | export const czechRepublic = {
name: 'Czech Republic',
codes: ['CZ', 'CZE', '203'],
calcFn: (vat) => {
const { rules } = czechRepublic;
const { multipliers, additional, lookup } = rules;
if (!additional)
return false;
return (isLegalEntities(vat, multipliers.common, additional) ||
isIndividualType2(vat, multipliers.common, additional, lookup) ||
isIndividualType3(vat, additional) ||
isIndividualType1(vat, additional));
},
rules: {
multipliers: {
common: [8, 7, 6, 5, 4, 3, 2]
},
lookup: [8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8],
regex: [/^(CZ)(\d{8,10})(\d{3})?$/],
additional: [/^\d{8}$/, /^[0-5][0-9][0|1|5|6]\d[0-3]\d\d{3}$/, /^6\d{8}$/, /^\d{2}[0-3|5-8]\d[0-3]\d\d{4}$/]
}
};
function isLegalEntities(vat, multipliers, additional) {
let total = 0;
if (additional[0].test(vat)) {
// Extract the next digit and multiply by the counter.
for (let i = 0; i < 7; i++) {
total += Number(vat.charAt(i)) * multipliers[i];
}
// Establish check digit.
total = 11 - (total % 11);
if (total === 10)
total = 0;
if (total === 11)
total = 1;
// Compare it with the last character of the VAT number. If it's the same, then it's valid.
const expect = Number(vat.slice(7, 8));
return total === expect;
}
return false;
}
function isIndividualType1(vat, additional) {
if (additional[1].test(vat)) {
return Number(vat.slice(0, 2)) <= 62;
}
return false;
}
function isIndividualType2(vat, multipliers, additional, lookup) {
let total = 0;
if (additional[2].test(vat)) {
// Extract the next digit and multiply by the counter.
for (let j = 0; j < 7; j++) {
total += Number(vat.charAt(j + 1)) * multipliers[j];
}
// Establish check digit.
let a;
if (total % 11 === 0) {
a = total + 11;
}
else {
a = Math.ceil(total / 11) * 11;
}
const pointer = a - total - 1;
// Convert calculated check digit according to a lookup table
const expect = Number(vat.slice(8, 9));
if (!lookup)
return false;
return lookup[pointer] === expect;
}
return false;
}
function isIndividualType3(vat, additional) {
if (additional[3].test(vat)) {
const temp = Number(vat.slice(0, 2)) +
Number(vat.slice(2, 4)) +
Number(vat.slice(4, 6)) +
Number(vat.slice(6, 8)) +
Number(vat.slice(8));
const expect = Number(vat) % 11 === 0;
return !!(temp % 11 === 0 && expect);
}
return false;
}
| mit |
RaoHai/crowdwriting | public/javascripts/storage.js | 4552 | // Setup an empty localStorage or upgrade an existing one
define([
"underscore"
], function(_) {
// Create the file system if not exist
if (localStorage["file.list"] === undefined) {
localStorage["file.list"] = ";";
}
var fileIndexList = _.compact(localStorage["file.list"].split(";"));
// localStorage versioning
var version = localStorage["version"];
// Upgrade from v0 to v1
if(version === undefined) {
// Not used anymore
localStorage.removeItem("sync.queue");
localStorage.removeItem("sync.current");
localStorage.removeItem("file.counter");
_.each(fileIndexList, function(fileIndex) {
localStorage[fileIndex + ".publish"] = ";";
var syncIndexList = _.compact(localStorage[fileIndex + ".sync"].split(";"));
_.each(syncIndexList, function(syncIndex) {
localStorage[syncIndex + ".contentCRC"] = "0";
// We store title CRC only for Google Drive synchronization
if(localStorage[syncIndex + ".etag"] !== undefined) {
localStorage[syncIndex + ".titleCRC"] = "0";
}
});
});
version = "v1";
}
// Upgrade from v1 to v2
if(version == "v1") {
var gdriveLastChangeId = localStorage["sync.gdrive.lastChangeId"];
if(gdriveLastChangeId) {
localStorage["gdrive.lastChangeId"] = gdriveLastChangeId;
localStorage.removeItem("sync.gdrive.lastChangeId");
}
var dropboxLastChangeId = localStorage["sync.dropbox.lastChangeId"];
if(dropboxLastChangeId) {
localStorage["dropbox.lastChangeId"] = dropboxLastChangeId;
localStorage.removeItem("sync.dropbox.lastChangeId");
}
var PROVIDER_GDRIVE = "gdrive";
var PROVIDER_DROPBOX = "dropbox";
var SYNC_PROVIDER_GDRIVE = "sync." + PROVIDER_GDRIVE + ".";
var SYNC_PROVIDER_DROPBOX = "sync." + PROVIDER_DROPBOX + ".";
_.each(fileIndexList, function(fileIndex) {
var syncIndexList = _.compact(localStorage[fileIndex + ".sync"].split(";"));
_.each(syncIndexList, function(syncIndex) {
var syncAttributes = {};
if (syncIndex.indexOf(SYNC_PROVIDER_GDRIVE) === 0) {
syncAttributes.provider = PROVIDER_GDRIVE;
syncAttributes.id = syncIndex.substring(SYNC_PROVIDER_GDRIVE.length);
syncAttributes.etag = localStorage[syncIndex + ".etag"];
syncAttributes.contentCRC = localStorage[syncIndex + ".contentCRC"];
syncAttributes.titleCRC = localStorage[syncIndex + ".titleCRC"];
}
else if (syncIndex.indexOf(SYNC_PROVIDER_DROPBOX) === 0) {
syncAttributes.provider = PROVIDER_DROPBOX;
syncAttributes.path = decodeURIComponent(syncIndex.substring(SYNC_PROVIDER_DROPBOX.length));
syncAttributes.version = localStorage[syncIndex + ".version"];
syncAttributes.contentCRC = localStorage[syncIndex + ".contentCRC"];
}
localStorage[syncIndex] = JSON.stringify(syncAttributes);
localStorage.removeItem(syncIndex + ".etag");
localStorage.removeItem(syncIndex + ".version");
localStorage.removeItem(syncIndex + ".contentCRC");
localStorage.removeItem(syncIndex + ".titleCRC");
});
});
version = "v2";
}
// Upgrade from v2 to v3
if(version == "v2") {
_.each(fileIndexList, function(fileIndex) {
if(!_.has(localStorage, fileIndex + ".sync")) {
localStorage.removeItem(fileIndex + ".title");
localStorage.removeItem(fileIndex + ".publish");
localStorage.removeItem(fileIndex + ".content");
localStorage["file.list"] = localStorage["file.list"].replace(";"
+ fileIndex + ";", ";");
}
});
version = "v3";
}
// Upgrade from v3 to v4
if(version == "v3") {
var currentFileIndex = localStorage["file.current"];
if(currentFileIndex !== undefined &&
localStorage["file.list"].indexOf(";" + currentFileIndex + ";") === -1)
{
localStorage.removeItem("file.current");
}
version = "v4";
}
// Upgrade from v4 to v5
if(version == "v4") {
// Recreate GitHub token
localStorage.removeItem("githubToken");
version = "v5";
}
// Upgrade from v5 to v6
if(version == "v5") {
_.each(fileIndexList, function(fileIndex) {
var publishIndexList = _.compact(localStorage[fileIndex + ".publish"].split(";"));
_.each(publishIndexList, function(publishIndex) {
var publishAttributes = JSON.parse(localStorage[publishIndex]);
if(publishAttributes.provider == "gdrive") {
// Change fileId to Id to be consistent with syncAttributes
publishAttributes.id = publishAttributes.fileId;
publishAttributes.fileId = undefined;
localStorage[publishIndex] = JSON.stringify(publishAttributes);
}
});
});
version = "v6";
}
localStorage["version"] = version;
}); | mit |
shunobaka/Interapp | Source/Web/Interapp.Web/ViewModels/Account/ForgotViewModel.cs | 239 | namespace Interapp.Web.ViewModels.Account
{
using System.ComponentModel.DataAnnotations;
public class ForgotViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
}
| mit |
argentumproject/electrum-arg | plugins/hw_wallet/plugin.py | 2096 | #!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 The Electrum developers
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from electrum_arg.plugins import BasePlugin, hook
from electrum_arg.i18n import _
class HW_PluginBase(BasePlugin):
# Derived classes provide:
#
# class-static variables: client_class, firmware_URL, handler_class,
# libraries_available, libraries_URL, minimum_firmware,
# wallet_class, ckd_public, types, HidTransport
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.device = self.keystore_class.device
self.keystore_class.plugin = self
def is_enabled(self):
return self.libraries_available
def device_manager(self):
return self.parent.device_manager
@hook
def close_wallet(self, wallet):
for keystore in wallet.get_keystores():
if isinstance(keystore, self.keystore_class):
self.device_manager().unpair_xpub(keystore.xpub)
| mit |
newscloud/n2 | db/migrate/20110916233249_add_profile_image_to_user_profiles.rb | 213 | class AddProfileImageToUserProfiles < ActiveRecord::Migration
def self.up
add_column :user_profiles, :profile_image, :string
end
def self.down
remove_column :user_profiles, :profile_image
end
end
| mit |
brocc0li/Google-Maps-mySQL-PHP-javascript | map.php | 2609 | <?php
include "dbconnect.php";
$sql = "SELECT id, lat, lng, info, address FROM maps";
if ($result = $conn->query($sql)) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lat = $row['lat'];
$lng = $row['lng'];
$info = $row['info'];
$address = $row['address'];
/* Each row is added as a new array */
$locations[]=array( 'lat'=>$lat, 'lng'=>$lng, 'info'=>$info, 'address'=>$address );
}
} else {
echo "failed contact an administrator to solve this issue.";
}
?>
<head>
<style>
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
</style>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_Key_Here"></script>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 64.2868021,
lng: 8.7824582
}
});
var infoWin = new google.maps.InfoWindow();
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location
});
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
// markerCluster.setMarkers(markers);
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [
<?php for($i=0;$i<sizeof($locations);$i++){ $j=$i+1;?>
{
lat: <?php echo $locations[$i]["lat"];?>,
lng: <?php echo $locations[$i]["lng"];?>,
info: '<div class="info_content"><h3><?php echo $locations[0]['address'];?></h3><p><?php echo $locations[0]['info'];?>"></p></div><hr>',
}<?php if($j!=sizeof($locations))echo ","; };?>
];
google.maps.event.addDomListener(window, "load", initMap);
</script>
| mit |
TateMedia/pagediff | lib/phantom.js | 10183 | "use strict";
var fs = require('fs');
var system = require('system');
var args = system.args;
var cmd = args[1];
var url = args[2];
var size = [1024, 768];
var verbose = false;
var directories = {
'before' : fs.workingDirectory,
'after' : fs.workingDirectory,
'output' : fs.workingDirectory,
};
/*
Call with:
phantomjs --web-security=false phantom.js before <url>
This will produce a png file with the name before-<url>-<width>x<height>.png
phantomjs --web-security=false phantom.js after <url>
This will produce a png file with the name after-<url>-<width>x<height>.png
and a comparisson file with the name output-<url>-<width>x<height>.png
The url will be sanitized to make it into a half-decent filename.
*/
// See if the size is overridden
if (args[3]) {
var arr = args[3].match(/([0-9]+)x([0-9]+)/);
if (arr === null) {
quit("No valid size specified");
}
size = [ arr[1] , arr[2] ];
}
// Choose some sensible defaults
var processing_options = {
"bounding" : false,
"threshold" : 0,
"hide_before_and_after" : false,
}
// Override defaults
if (args.length > 4) {
var re = /--([a-z0-9\-]+)(=(.+))?/;
for (var i = 4; i < args.length; i++) {
var kv = args[i].match(re);
if (kv !== null) {
switch(kv[1]) {
/*
case '--bounding-box':
config.bounding = true;
break;
*/
case 'verbose':
verbose = true;
break;
case 'output':
processing_options.output = kv[3];
break;
case 'url2':
processing_options.url2 = kv[3];
break;
case 'threshold':
if (parseInt(kv[3]) !== NaN) {
processing_options.threshold = parseInt(kv[3]);
}
break;
case 'hide-before-and-after':
processing_options.hide_before_and_after = true;
break;
case 'filter':
processing_options.filter = kv[3];
break;
case 'before-dir':
if (fs.isDirectory(kv[3]) && fs.isWritable(kv[3])) {
directories.before = kv[3];
} else {
quit("Directory for before images (" + kv[3] + ") is not writable");
}
break;
case 'after-dir':
if (fs.isDirectory(kv[3]) && fs.isWritable(kv[3])) {
directories.after = kv[3];
} else {
quit("Directory for after images (" + kv[3] + ") is not writable");
}
break;
case 'output-dir':
if (fs.isDirectory(kv[3]) && fs.isWritable(kv[3])) {
directories.output = kv[3];
} else {
quit("Directory for output images (" + kv[3] + ") is not writable");
}
break;
}
}
}
}
if (verbose) {
console.log("Args: " + args.join(", "));
console.log("After dir: " + directories.after);
console.log("Before dir: " + directories.before);
console.log("Output dir: " + directories.output);
}
if (null === url.match(/(http|https|file):\/\/.+/)) {
quit("URL must be a full http:// URL (or file:// for a local file)");
}
if (cmd == "before") {
// Capture the before image and quit
capture(url, size, 'before', function () {
quit();
});
} else if (cmd == "after") {
// Check we have a before file to compare
if (!fs.isFile(getFilename(url, size, 'before'))) {
quit("No before file");
}
var output = getFilename(url, size, 'output');
if (processing_options.output !== undefined) {
output = directories.output + '/' + processing_options.output;
}
// Capture the after image
capture(url, size, 'after', function () {
// Compare it to the before image for the same url
compare(
url,
getFilename(url, size, 'before'),
getFilename(url, size, 'after'),
output,
size,
processing_options
);
});
} else if (cmd == "compare") {
// Immediately compare two urls
var output = getFilename(url, size, 'output');
if (processing_options.output !== undefined) {
output = directories.output + '/' + processing_options.output;
}
capture(url, size, 'before', function () {
capture(processing_options.url2, size, 'after', function () {
compare(
url,
getFilename(url, size, 'before'),
getFilename(processing_options.url2, size, 'after'),
output,
size,
processing_options
);
});
});
} else {
// Help text.
console.log("phantomjs --web-security=false phantom.js before <url> <options>");
console.log("Where options are:");
console.log(" --threshold=nn Percentage of pixels needed before an output image is created. Default 0");
console.log(" --hide-before-and-after Hide the before and after images in the output. Just show composite");
console.log(" --before-dir=xxx Directory to put the before image in.");
console.log(" --after-dir=xxx Directory to put the after image in.");
console.log(" --output-dir=xxx Directory to put the output image in.");
console.log(" --output=xxx Output filename to use. Overrides default auto-generated attempt.");
console.log(" --filter=xxx Filter function to use 'differ_green_red' or 'differ_super_red'.");
console.log(" --url2=xxx Second URL if it's a direct comparison.");
quit();
}
/**
* Quit with an optional message
*
* @param {string} msg Message to return
*/
function quit(msg) {
if (msg) {
console.log(msg);
}
phantom.exit();
}
/**
* Compare two images
*
* Options:
* - filter {string} Which filter to use. differ_green_red differ_super_red
* - hide_before_and_after {boolean} Only output composite image
* - threshold {number} Percentage of pixels that need to be different to
* trigger output image.
*
* @param {string} url The url that is being worked on. Used as a title
* @param {string} before_filename
* @param {string} after_filename
* @param {string} output_filename
* @param {array} size Two dimensional array of numbers. width, height.
* @param {object} options
*/
function compare(url, before_filename, after_filename, output_filename, size, options) {
var page = require('webpage').create();
page.viewportSize = { width: size[0], height : size[1] };
page.content = '<html>\
<body> \
<h1 style="font-size=14px;">' + url +'</h1> \
<canvas id="result"></canvas> \
<canvas id="before"></canvas> \
<canvas id="after"></canvas> \
</body></html>';
// Set the config in the web page
page.evaluate(function(b, a, s, filter) {
window.burl = "file://"+ b;
window.aurl = "file://"+ a;
window.size = [s[0], s[1]];
window.filter = filter;
},
fs.absolute(before_filename),
fs.absolute(after_filename),
size,
options.filter
);
if (!page.injectJs('compare.js')) {
quit("Could not load javascript into page.");
}
// Useful for debugging
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
// Wait for the page to load
page.onLoadFinished = function(status) {
var grab = function () {
page.render(output_filename);
page.close();
quit();
};
// We need to wait to do the screen grab until the page title has been changed to done.
var id = setInterval(function () {
// Grab the page title
var title = page.evaluate(function() {
return document.title;
});
if (title == "done") {
clearInterval(id);
// There is a stats object set on the window that gives results of the comparisson
var stats = page.evaluate(function() {
return window.stats;
});
if (options.hide_before_and_after) {
page.clipRect = { top: 0, left: 0, width: size[0], height: size[1] };
}
// If the difference meets or exceeds the threshold then grab an image
if (!options.threshold || stats.percentage >= options.threshold) {
grab();
} else {
quit();
}
}
}, 50);
};
}
/**
* Make a good filename for our url
*
* Uses the directories obejct (before, after, output) to set directory.
*
* @param {string} url
* @param {array} size Two dimensions. width, height
* @param {string} prefix First part of filename
*
* @returns {string}
*/
function getFilename(url, size, prefix) {
var re = /[^A-Za-z0-9\.\-]/g;
var str = prefix + '-' + url + '-' + size[0] + 'x' + size[1] + '.png';
var filename = str.replace(re, "-");
switch(prefix) {
case 'before':
filename = directories.before + '/' + filename;
break;
case 'after':
filename = directories.after + '/' + filename;
break;
case 'output':
filename = directories.output + '/' + filename;
break;
}
return filename;
}
/**
* Capture a page.
*
* @param {string} url
* @param {array} size Two dimensions. width, height
* @param {string} prefix First part of filename
* @param {function} callback
*/
function capture(url, size, prefix, callback) {
var page = require('webpage').create();
page.viewportSize = {
width: size[0],
height: size[1]
};
page.zoomFactor = 1;
// Useful for debugging
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg);
};
var filename = getFilename(url, size, prefix);
// We can only work with absolute filenames
var m = url.match(/file:\/\/(.+)/);
if (null !== m) {
url = 'file://' + fs.absolute(m[1]);
}
page.open(url, function (status) {
page.evaluate(function() {
document.body.bgColor = 'white';
});
page.render(filename);
page.close();
if (callback != undefined) {
callback();
}
});
}
| mit |
denislevin/webapp-dashboard | app/database/migrations/2015_05_26_072053_area_manager_initialization.php | 2479 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AreaManagerInitialization extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$role = new \Role ();
$role -> name = 'area-manager';
$role -> save();
$structures = [
[0, 1, 1, 10, 1, 'Units', 'Units', 'module', '/units', '', 'fa fa-home'],
[0, 1, 1, 20, 1, 'Users', 'Users', 'module', '/users', '', 'fa fa-users'],
[0, 1, 1, 30, 1, 'Company Haccp', 'Company Haccp', 'module', '/haccp-company', '', 'fa fa-folder-open'],
[0, 1, 1, 50, 1, 'Units Map', 'Units Map', 'module', '/units-map', '', 'fa fa-map-marker'],
[0, 1, 1, 60, 1, 'Logout', 'Logout', 'link', '', 'logout', 'fa fa-power-off'],
[0, 1, 1, 40, 1, 'Company Knowledge', 'Company Knowledge', 'module', '/knowledge-company', '', 'fa fa-book'],
[0, 1, 1, 25, 1, 'Site Stats', 'Site Stats', 'module', '/sitestats', NULL, 'fa fa-bar-chart'],
[0, 1, 1, 43, 1, 'Usage Stats', 'Usage Stats', 'module', '/usagestats', NULL, 'fa fa-bar-chart'],
[0, 1, 1, 46, 1, 'Use Navitas As', 'Use Navitas As', 'module', '/usenavitas', NULL, 'fa fa-exchange'],
[0, 1, 1, 5, 1, 'Dashboard', 'Dashboard', 'module', '/index', NULL, 'fa fa-dashboard']
];
list($target_type,$root,$lft,$rgt,$lvl,$sort,$active,$title,$menu_title,$type,$route_path,$link,$ico,$lang) = ['area-manager',0,0,0,0,0,0,'ROOT','ROOT',NULL,NULL,NULL,'','en'];
$root = \Model\MenuStructures::create(['target_type'=>$target_type,'root'=>$root,'lft'=>$lft,'rgt'=>$rgt,'lvl'=>$lvl,'sort'=>$sort,'active'=>$active,'title'=>$title,'menu_title'=>$menu_title,'type'=>$type,'route_path'=>$route_path,'link'=>$link,'ico'=>$ico,'lang'=>$lang]);
$root->update(['root'=>$root->id]);
foreach ($structures as $structure){
list($lft,$rgt,$lvl,$sort,$active,$title,$menu_title,$type,$route_path,$link,$ico) = $structure;
\Model\MenuStructures::create(['target_type'=>$target_type,'target_id'=>$root->id,'root'=>$root->id,'lft'=>$lft,'rgt'=>$rgt,'lvl'=>$lvl,'sort'=>$sort,'active'=>$active,'title'=>$title,'menu_title'=>$menu_title,'type'=>$type,'route_path'=>$route_path,'link'=>$link,'ico'=>$ico,'lang'=>$lang]);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
} | mit |
PowerDMS/Owin.Scim | source/_tests/Owin.Scim.Tests/Integration/Groups/Retrieve/when_retrieving_a_group.cs | 1049 | namespace Owin.Scim.Tests.Integration.Groups.Retrieve
{
using System.Net;
using System.Net.Http;
using Machine.Specifications;
using Model.Groups;
using v2.Model;
public class when_retrieving_a_group : using_existing_user_and_group
{
Because of = () =>
{
Response = Server
.HttpClient
.GetAsync("v2/groups/" + GroupId)
.Result;
RetrievedGroup = Response.StatusCode == HttpStatusCode.OK
? Response.Content.ScimReadAsAsync<ScimGroup2>().Result
: null;
Error = Response.StatusCode == HttpStatusCode.BadRequest
? Response.Content.ScimReadAsAsync<Model.ScimError>().Result
: null;
};
protected static string GroupId;
protected static ScimGroup GroupDto;
protected static ScimGroup RetrievedGroup;
protected static HttpResponseMessage Response;
protected static Model.ScimError Error;
}
} | mit |
KristianOellegaard/django-filer | tests/project/settings.py | 752 | #-*- coding: utf-8 -*-
import os
DEBUG = True
PACKAGE_ROOT = os.path.abspath( os.path.join(os.path.dirname(__file__), '../') )
PROJECT_ROOT = os.path.join(PACKAGE_ROOT, 'project')
TMP_ROOT = os.path.abspath( os.path.join(PACKAGE_ROOT, 'tmp') )
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(TMP_ROOT,'filer_test.db') # won't actually be used. tests under SQLite are run in-memory
INSTALLED_APPS = [
'filer',
'mptt',
'easy_thumbnails',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sessions',
'django.contrib.staticfiles']
ROOT_URLCONF = 'project.urls'
MEDIA_ROOT = os.path.abspath( os.path.join(TMP_ROOT, 'media') )
MEDIA_URL = '/media/'
STATIC_URL = '/static/' | mit |
gr-jialeiwang/fuelphp_dev | fuel/app/modules/admin/config/routes.php | 83 | <?php
return array(
'_root_' => 'admin/index/index', // The default route
);
| mit |
wmira/react-icons-kit | src/md/ic_text_rotate_up_outline.js | 351 | export const ic_text_rotate_up_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0zm0 0h24v24H0V0zm0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M18 4l-3 3h2v13h2V7h2l-3-3zm-6.2 11.5v-5l2.2-.9V7.5L3 12.25v1.5l11 4.75v-2.1l-2.2-.9zM4.98 13L10 11.13v3.74L4.98 13z"},"children":[]}]}; | mit |
rocachien/neptune-map-finder | src/components/common/table/table-component.js | 3287 | "use strict";
import React, {Component, PropTypes} from "react";
export default class TableComponent extends Component {
renderRow(item, rowIndex) {
const {style, rowStyle, onClick} = this.props;
if (item && item.length>0) {
return (<tr key={rowIndex} style={rowStyle}>
{
item.map((item, index)=> {
let handleClick = () => onClick ? onClick(rowIndex) : {};
let _style = (style && style[index]) ? style[index] : {};
return (<td key={index} onClick={handleClick} style={_style}>{item}</td>);
})
}
</tr>);
}
return false;
}
renderHeader(data) {
const {style, headerStyle} = this.props;
if (data && data.length>0) {
return data.map((item, index)=> {
let _style = {};
if (headerStyle) {
_style = headerStyle;
} else if (style && style[index]) {
_style = style[index];
}
return (<th key={index} style={_style}
>{item}</th>);
});
}
return null;
}
render() {
const {header, body, customHeaderBackgroundStyle} = this.props;
if ((body && body.length > 0) || header) {
return (
<div style={{overflow:'scroll', overflowY:'hidden'}}>
<table className="tableWrapper">
<thead style={customHeaderBackgroundStyle}>
<tr>
{
this.renderHeader(header)
}
</tr>
</thead>
<tbody>
{
body.map((row, index)=> {
return this.renderRow(row, index);
})
}
</tbody>
<style>{css}</style>
</table>
</div>
);
}
return null;
}
}
TableComponent.propTypes = {
header: PropTypes.array,
body: PropTypes.array,
onClick: PropTypes.func,
style: PropTypes.array,
rowStyle: PropTypes.object,
headerStyle: PropTypes.object,
customHeaderBackgroundStyle: PropTypes.object
};
const css = `
.tableWrapper{
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
.tableWrapper thead{
background-color: #fcd000;
}
.tableWrapper thead th{
padding:8px;
font-weight:normal;
color: #00105a;
font-size:11px;
text-align:center;
}
.tableWrapper tbody tr:nth-child(even) {background: #FFF}
.tableWrapper tbody tr:nth-child(odd) {background: #efefef}
.tableWrapper tbody td{
padding:8px;
text-align:center;
white-space: nowrap;
max-width: 126px;
text-overflow: ellipsis;
overflow: hidden;
}
.tableWrapper tbody td.name{
text-align:left;
font-weight:bold;
text-decoration: underline;
}
.tableWrapper thead th.name{
text-align:left;
}
`;
| mit |
ymyang/node-startup | socket.js | 1333 | /**
* Created by yang on 2015/6/22.
*/
var server = require('http').createServer();
var io = require('socket.io')(server);
var pub = require('redis').createClient(6379, '192.168.1.54');
var sub = require('redis').createClient(6379, '192.168.1.54');
var pchannel = 'channel.user.';
var cacheSockets = {};
io.on('connection', function(socket) {
var userId = socket.handshake.query.userId;
cacheSockets[userId] = socket;
socket.on('message', function(data) {
console.log('[userId]-', userId, ':', data);
var msg = JSON.parse(data);
var channel = pchannel + msg.userId;
console.log('[channel]-', channel);
pub.publish(channel, data);
});
socket.on('disconnect', function() {
console.log('disconnect:', userId);
delete cacheSockets[userId];
});
});
sub.psubscribe(pchannel + '*');
sub.on('pmessage', function(pattern, channel, msg) {
var userId = channel.substr(channel.lastIndexOf('.') + 1);
console.log('[userId]:', userId, ', [channel]:', channel, ', [msg]:', msg);
if (userId) {
if (userId === '*') {
io.emit('message', msg);
} else {
var socket = cacheSockets[userId];
if (socket) {
socket.emit('message', msg);
}
}
}
});
server.listen(3001); | mit |
biow0lf/eve_online | spec/eve_online/esi/models/moon_spec.rb | 1994 | # frozen_string_literal: true
require "spec_helper"
describe EveOnline::ESI::Models::Moon do
let(:options) { double }
subject { described_class.new(options) }
it { should be_a(EveOnline::ESI::Models::Base) }
describe "#initialize" do
its(:options) { should eq(options) }
end
describe "#as_json" do
let(:moon) { described_class.new(options) }
before { expect(moon).to receive(:moon_id).and_return(40_000_004) }
before { expect(moon).to receive(:name).and_return("Tanoo I - Moon 1") }
before { expect(moon).to receive(:system_id).and_return(30_000_001) }
subject { moon.as_json }
its([:moon_id]) { should eq(40_000_004) }
its([:name]) { should eq("Tanoo I - Moon 1") }
its([:system_id]) { should eq(30_000_001) }
end
describe "#moon_id" do
before { expect(options).to receive(:[]).with("moon_id") }
specify { expect { subject.moon_id }.not_to raise_error }
end
describe "#name" do
before { expect(options).to receive(:[]).with("name") }
specify { expect { subject.name }.not_to raise_error }
end
describe "#system_id" do
before { expect(options).to receive(:[]).with("system_id") }
specify { expect { subject.system_id }.not_to raise_error }
end
describe "#position" do
context "when @position set" do
let(:position) { double }
before { subject.instance_variable_set(:@position, position) }
specify { expect(subject.position).to eq(position) }
end
context "when @position not set" do
let(:position) { double }
let(:options) { {"position" => position} }
let(:model) { instance_double(EveOnline::ESI::Models::Position) }
before { expect(EveOnline::ESI::Models::Position).to receive(:new).with(position).and_return(model) }
specify { expect { subject.position }.not_to raise_error }
specify { expect { subject.position }.to change { subject.instance_variable_get(:@position) }.from(nil).to(model) }
end
end
end
| mit |
richardszalay/helix-publishing-targets | src/tasks/RichardSzalay.Helix.Publishing.Tasks/MergeXmlTransforms.cs | 1566 | using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.IO;
using System.Linq;
using System.Xml;
namespace RichardSzalay.Helix.Publishing.Tasks
{
public class MergeXmlTransforms : Task
{
[Required]
public ITaskItem[] Transforms { get; set; }
[Required]
public string OutputPath { get; set; }
[Output]
public ITaskItem Output { get; set; }
public override bool Execute()
{
if (Transforms == null || Transforms.Length == 0)
{
Log.LogError("No transforms were supplied");
return false;
}
try
{
var transformXml = Transforms.Select(item => ParseXmlDocument(item.ItemSpec));
var mergedTransforms = XmlTransformMerger.Merge(transformXml);
EnsureDirectoryExists(Path.GetDirectoryName(OutputPath));
mergedTransforms.Save(OutputPath);
return true;
}
catch (Exception ex)
{
Log.LogErrorFromException(ex);
return false;
}
}
private void EnsureDirectoryExists(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
static XmlDocument ParseXmlDocument(string xml)
{
var doc = new XmlDocument();
doc.Load(xml);
return doc;
}
}
}
| mit |
adnanaziz/epicode | java/src/main/java/com/epi/NormalizedPathnamesTest.java | 2574 | package com.epi;
// @pg_import:4
import com.epi.utils.AbstractTestOptions;
import com.epi.utils.AbstractTestStream;
import com.epi.utils.JsonTestOptions;
import com.epi.utils.TestType;
// @pg_ignore:1
import static com.epi.NormalizedPathnames.shortestEquivalentPath;
public class NormalizedPathnamesTest {
// @pg_ignore
// @pg_include:NormalizedPathnames.java
// @pg_end
private static void unitTest(AbstractTestOptions options, String description,
String input, String expected) {
AbstractTestStream stream = options.getStream();
stream.startTest(TestType.NORMAL, description);
stream.registerInput(input);
stream.registerExpectedOutput(expected.isEmpty() ? "Invalid path!" : expected);
try {
String result = shortestEquivalentPath(input);
stream.registerUserOutput(result, !expected.isEmpty() && expected.equals(result));
} catch (IllegalArgumentException e) {
stream.registerUserOutput("Invalid path!", expected.isEmpty());
} catch (NullPointerException e) {
stream.registerNullPointerException();
} catch (Exception e) {
stream.registerUnhandledException();
}
stream.endTest();
}
public static void directedTests(AbstractTestOptions options) {
options.startTests(0, "Normalized pathnames");
unitTest(options, "Trivial test #1", "/", "/");
unitTest(options, "Normalized path test #1", "foo/bar", "foo/bar");
unitTest(options, "Normalized path test #2", "/foo/bar", "/foo/bar");
unitTest(options, "Double-dot test #1", "usr/lib/../bin/gcc", "usr/bin/gcc");
unitTest(options, "Double-dot test #2", "usr/bin/../lib/../bin/gcc", "usr/bin/gcc");
unitTest(options, "Double-dot test #3", "usr/bin/gcc/include/../../../", "usr");
unitTest(options, "Double-dot test #4", "./../", "..");
unitTest(options, "Double-dot test #5", "..", "..");
unitTest(options, "Double-dot test #6", "../../local", "../../local");
unitTest(options, "Redundant symbols test #1", "./.././../local", "../../local");
unitTest(options, "Redundant symbols test #2", "/foo/../foo/././../././", "/");
unitTest(options, "Redundant symbols test #3", "scripts//./../scripts///awkscripts/././", "scripts/awkscripts");
unitTest(options, "Invalid path test #1", "/..", "");
unitTest(options, "Invalid path test #2", "/foo/.././../", "");
unitTest(options, "Invalid path test #3", "/./.././/", "");
options.endTests();
}
public static void main(String[] args) {
directedTests(new JsonTestOptions(System.out));
}
}
| mit |
Python-Tools/pmfp | pmfp/new/utils.py | 2472 | """new模块的通用工具."""
import json
from string import Template
from pathlib import Path
from typing import Dict, Any
from pmfp.const import (
JS_ENV_PATH
)
def template_2_file(path: Path,**kwargs):
"""将模板转换为项目中的文件.
Args:
project_name (str): 项目名
path (Path): 模板文件复制到项目中的地址
"""
if (".py" in path.name) or (
".c" in path.name) or (
".cpp" in path.name) or (
".go" in path.name) or (
"docker" in path.name) or (
".json" in path.name) or (
".mod" in path.name) or (
".proto" in path.name) or (
".js" in path.name) or (
".yaml" in path.name):
try:
template_content = Template(path.open(encoding='utf-8').read())
content = template_content.safe_substitute(
**kwargs
)
except:
print(f"位置{path} 执行template2file出错")
raise
else:
path.open("w", encoding='utf-8').write(content)
else:
try:
content = path.open("r", encoding='utf-8').read()
except UnicodeDecodeError as e:
content = path.open("rb").read()
path.open("wb").write(content)
else:
path.open("w", encoding='utf-8').write(content)
newpath = str(path).replace(".temp", "")
path.rename(Path(newpath))
def iter_template_2_file( project_name: str,path: Path):
"""遍历并将模板转化为项目中的文件.
Args:
project_name (str): 项目名
path (Path): 模板文件复制到项目中的地址
"""
for p in path.iterdir():
if p.is_file():
if p.suffix == ".temp":
template_2_file(p,project_name=project_name)
else:
iter_template_2_file(project_name,p)
def new_json_package(config: Dict[str, Any]) -> None:
"""创建package.json.
Args:
config (Dict[str, Any]): 项目信息字典.
"""
if not JS_ENV_PATH.exists():
with open(str(JS_ENV_PATH), "w", encoding="utf-8") as f:
content = {
"name": config["project-name"],
"version": config["version"],
"description": config["description"],
"author": config["author"],
"license": config["license"]
}
json.dump(content, f)
| mit |
thisismyjam/jam-image-filter | jam_image_filter/leaves.py | 948 | import os
import sys
import math
import Image
import ImageOps
import util
import colorsys
import random
def leaves(image):
image = image.convert('RGB')
colours = util.get_dominant_colours(image, 8)
light, dark = [colours[i] for i in random.sample(range(len(colours)), 2)]
layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' +
'assets/leaves.png')
layer = layer.convert('RGB')
layer = ImageOps.grayscale(layer)
layer = ImageOps.colorize(layer, dark, light)
width, height = layer.size
# shift half of the image horizontally
left = layer.crop((0, 0, width / 2, height))
right = layer.crop((width / 2, 0, width, height))
new = Image.new('RGB', (width, height))
new.paste(left, (width / 2, 0))
new.paste(right, (0, 0))
return new
if __name__ == '__main__':
im = Image.open(sys.argv[1])
im = leaves(im)
im.save(sys.argv[2], quality=90)
| mit |
naoa/activerecord-mysql-comment | lib/activerecord-mysql-comment/active_record/schema_dumper.rb | 1306 | require 'active_record/schema_dumper'
module ActiveRecord
module Mysql
module Comment
module SchemaDumper
private
def table(table, stream)
@types = @types.merge(@connection.options_for_column_spec(table))
super(table, stream)
ensure
@types = @connection.native_database_types
end
def indexes(table, stream)
buf = StringIO.new
super(table, buf)
buf = buf.string
output = add_index_comment(table, buf)
stream.print output
stream
end
def add_index_comment(table, buf)
output = ""
buf.each_line do |line|
output << line
if matched = line.match(/name: \"(?<name>.*)\", /)
index_name = matched[:name]
end
if index_name.present?
comment = @connection.select_one("SHOW INDEX FROM #{table} WHERE Key_name = '#{index_name}';")["Index_comment"]
if comment.present?
output = output.chop
output << ", comment: #{comment.inspect}\n"
end
end
end
output
end
end
end
end
class SchemaDumper #:nodoc:
prepend Mysql::Comment::SchemaDumper
end
end
| mit |
Condors/TunisiaMall | vendor/jms/serializer/src/JMS/Serializer/EventDispatcher/LazyEventDispatcher.php | 1560 | <?php
/*
* Copyright 2013 Johannes M. Schmitt <[email protected]>
*
* 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.
*/
namespace JMS\Serializer\EventDispatcher;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LazyEventDispatcher extends EventDispatcher
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
protected function initializeListeners($eventName, $loweredClass, $format)
{
$listeners = parent::initializeListeners($eventName, $loweredClass, $format);
foreach ($listeners as &$listener) {
if ( ! is_array($listener) || ! is_string($listener[0])) {
continue;
}
if ( ! $this->container->has($listener[0])) {
continue;
}
$listener[0] = $this->container->get($listener[0]);
}
return $listeners;
}
}
| mit |
hiroyuki-seki/hryky-codebase | lib/window/src/window_module.cpp | 2665 | /**
@file window_module.cpp
@brief manages window module.
@author HRYKY
@version $Id: window_module.cpp 375 2014-07-29 04:27:53Z [email protected] $
*/
#include "precompiled.h"
#include "hryky/sdl/sdl_video.h"
#include "hryky/window/window_module.h"
#include "hryky/log/log_definition.h"
#include "hryky/clear.h"
//------------------------------------------------------------------------------
// macro
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// anonymous namespace
//------------------------------------------------------------------------------
namespace
{
}
//------------------------------------------------------------------------------
// static variable
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// function prototype
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines public member functions
//------------------------------------------------------------------------------
/**
@brief destructor.
*/
hryky::window::Module::~Module()
{
}
/**
@brief confirms whether the instance is invalid.
*/
bool hryky::window::Module::is_null() const
{
return hryky_is_null(this->impl_);
}
//------------------------------------------------------------------------------
// defines protected member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines private member functions
//------------------------------------------------------------------------------
/**
@brief constructor.
*/
hryky::window::Module::Module()
: impl_()
{
if (this->is_null()) {
hryky_log_alert(
"failed to initialize implementation of Window System");
}
}
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// static functions
//------------------------------------------------------------------------------
namespace
{
}
//------------------------------------------------------------------------------
// explicit instantiation
//------------------------------------------------------------------------------
// end of file
| mit |
Orangeyness/RuRu | src/ruru/events/EventService.cpp | 109 | #include "ruru/events/EventService.h"
using namespace RuRu;
EventDelegateHandle_t EventService::NextId = 0;
| mit |
Daynos/node_project | app/routes/index.js | 409 | var express = require('express');
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// console.log('Log test (/routes/index.js)');
next(); // make sure we go to the next routes and don't stop here
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
| mit |
madgik/exareme | Exareme-Docker/src/exareme/exareme-tools/madis/src/functions/row/datasets.py | 564 | # coding: utf-8
import functions
def datasets(*args):
if args[0] == "0":
raise functions.OperatorError("DATASET", "Dataset does not exist")
else:
return 1
datasets.registered = True
if not ('.' in __name__):
"""
This is needed to be able to test the function, put it at the end of every
new function you create
"""
import sys
from functions import *
testfunction()
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf-8')
import doctest
doctest.testmod()
| mit |
youxidou/game-php-sdk | src/Support/Str.php | 4194 | <?php namespace Yxd\Game\Support;
use Yxd\Game\Core\Exceptions\RuntimeException;
class Str
{
/**
* The cache of snake-cased words.
*
* @var array
*/
protected static $snakeCache = [];
/**
* The cache of camel-cased words.
*
* @var array
*/
protected static $camelCache = [];
/**
* The cache of studly-cased words.
*
* @var array
*/
protected static $studlyCache = [];
/**
* Convert a value to camel case.
*
* @param string $value
*
* @return string
*/
public static function camel($value)
{
if (isset(static::$camelCache[$value])) {
return static::$camelCache[$value];
}
return static::$camelCache[$value] = lcfirst(static::studly($value));
}
/**
* Generate a more truly "random" alpha-numeric string.
*
* @param int $length
*
* @return string
*
* @throws \RuntimeException
*/
public static function random($length = 16)
{
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = static::randomBytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
/**
* Generate a more truly "random" bytes.
*
* @param int $length
*
* @return string
*
* @throws RuntimeException
*/
public static function randomBytes($length = 16)
{
if (function_exists('random_bytes')) {
$bytes = random_bytes($length);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($length, $strong);
if ($bytes === false || $strong === false) {
throw new RuntimeException('Unable to generate random string.');
}
} else {
throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');
}
return $bytes;
}
/**
* Generate a "random" alpha-numeric string.
*
* Should not be considered sufficient for cryptography, etc.
*
* @param int $length
*
* @return string
*/
public static function quickRandom($length = 16)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
/**
* Convert the given string to upper-case.
*
* @param string $value
*
* @return string
*/
public static function upper($value)
{
return mb_strtoupper($value);
}
/**
* Convert the given string to title case.
*
* @param string $value
*
* @return string
*/
public static function title($value)
{
return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
}
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter
*
* @return string
*/
public static function snake($value, $delimiter = '_')
{
$key = $value . $delimiter;
if (isset(static::$snakeCache[$key])) {
return static::$snakeCache[$key];
}
if (!ctype_lower($value)) {
$value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value));
}
return static::$snakeCache[$key] = $value;
}
/**
* Convert a value to studly caps case.
*
* @param string $value
*
* @return string
*/
public static function studly($value)
{
$key = $value;
if (isset(static::$studlyCache[$key])) {
return static::$studlyCache[$key];
}
$value = ucwords(str_replace(['-', '_'], ' ', $value));
return static::$studlyCache[$key] = str_replace(' ', '', $value);
}
public static function isJson($value)
{
return json_decode($value) !== null;
}
public static function json2Array($value)
{
return json_decode($value, true);
}
}
| mit |
sergeche/grunt-frontend | tasks/lib/utils.js | 4313 | var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var crc32 = require('./crc32');
var _ = require('underscore');
var filter = require('./hash-filter');
function padNumber(num) {
return (num < 10 ? '0' : '') + num;
}
function FileInfo(file, options) {
this._path = file;
this.absPath = module.exports.absPath(file, options.cwd);
this.catalogPath = module.exports.catalogPath(file, options);
this._hash = null;
this._content = null;
this._options = options || {};
}
FileInfo._readerOptions = {encoding: null};
FileInfo.prototype = {
get content() {
if (this._content === null) {
if (fs.existsSync(this.absPath)) {
this._content = fs.readFileSync(this.absPath, FileInfo._readerOptions);
} else if (this._options.content) {
this._content = this._options.content;
}
}
return this._content;
},
set content(value) {
this._content = value;
this._hash = null;
},
get hash() {
if (this._hash === null && this.content !== null) {
this._hash = filter(module.exports.crc32(this.content));
}
return this._hash;
},
versionedUrl: function(config) {
return module.exports.versionedUrl(this.catalogPath, this.hash, config);
}
};
module.exports = {
/**
* Returns string timestamp of given date in "yyyymmddhhss" format
* @param {Date} dt Source date. If not specified, current date is used
* @return {String}
*/
timestamp: function(dt) {
dt = dt || new Date();
return [dt.getFullYear(),
padNumber(dt.getMonth() + 1),
padNumber(dt.getDate()),
padNumber(dt.getHours()),
padNumber(dt.getMinutes()),
padNumber(dt.getSeconds())
].join('');
},
/**
* Returns md5 hash of given content
* @param {Buffer} content
* @return {String}
*/
md5: function(content) {
return crypto.createHash('md5').update(content).digest('');
},
/**
* Returns crc32 stamp from given content
* @param {Buffer} content
* @return {String}
*/
crc32: function(content) {
return crc32(content, true);
},
/**
* Return absolute path to given file
* @param {String} file File path to transform
* @return {String}
*/
absPath: function(file) {
return path.resolve(file);
},
/**
* Returns file path suitable for storing in catalog
* @param {String} file File path
* @param {Object} options Options for transforming path
* @return {String}
*/
catalogPath: function(file, options) {
file = this.absPath(file);
var cwd = (options && options.cwd) || '';
if (file.substring(0, cwd.length) == cwd) {
file = file.substring(cwd.length);
if (file.charAt(0) != '/') {
file = '/' + file;
}
}
return file;
},
/**
* Returns object with files‘ meta info
* @param {String} file
* @param {Object}
* @return {FileInfo}
*/
fileInfo: function(file, options) {
return new FileInfo(file, options);
},
/**
* Returns config for currently running grunt task
* @param {Object} grunt
* @param {Object} task
* @return {Object}
*/
config: function(grunt, task) {
var config = task.options(grunt.config.getRaw('frontend') || {});
if (!config.webroot) {
return grunt.fail.fatal('You should specify "webroot" property in frontend config', 100);
}
var cwd = this.absPath(config.cwd || config.webroot);
var force = false;
if ('force' in config) {
force = !!config.force;
}
return grunt.util._.extend(config, {
force: force,
cwd: this.absPath(config.cwd || config.webroot),
webroot: this.absPath(config.webroot),
srcWebroot: this.absPath(config.srcWebroot || config.webroot)
});
},
/**
* Creates versioned URL from original one
* @param {String} url Original URL
* @param {String} version Cache-busting token
* @param {Object} config
* @return {String}
*/
versionedUrl: function(url, version, config) {
if (!config.rewriteScheme) {
return url;
}
var basename = path.basename(url);
var ext = path.extname(url).substr(1);
var filename = basename.replace(new RegExp('\\.' + ext + '$'), '');
var data = {
url: url,
dirname: path.dirname(url),
basename: basename,
ext: ext,
filename: filename,
version: version
};
if (typeof config.rewriteScheme == 'string') {
return _.template(config.rewriteScheme, data);
}
return config.rewriteScheme(data);
}
}; | mit |
TyrfingX/TyrLib | legacy/TyrLib2/src/com/tyrlib2/math/IMatrixImpl.java | 1116 | package com.tyrlib2.math;
public interface IMatrixImpl {
public void setIdentityM(float[] m, int offset);
public void scaleM(float[] m, int offset, float scaleX, float scaleY, float scaleZ);
public void multiplyMM(float[] result, int offsetResult, float[] lhs, int offsetLeft, float[] rhs, int offsetRight);
public void translateM(float[] m, int offset, float x, float y, float z);
public void multiplyMV(float[] result, int offsetResult, float[] m, int offsetMatrix, float[] v, int offsetVector);
public void invertM(float[] inv, int offsetResult, float[] m, int offsetMatrix);
public void rotateM(float[] result, int offsetResult, float rotation, float x, float y, float z);
public void orthoM(float[] result, int offsetResult, float left, float right, float bottom, float top, float near, float far);
public void frustumM(float[] m, int offsetResult, float left, float right, float bottom, float top, float near, float far);
public void setLookAtM(float[] rm, int rmOffset, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX,float upY, float upZ);
} | mit |
JHKennedy4/nqr-client | jspm_packages/npm/[email protected]/client/core.min.js | 93082 | /* */
"format cjs";
(function(process) {
!function(b, c, a) {
"use strict";
!function(b) {
function __webpack_require__(c) {
if (a[c])
return a[c].exports;
var d = a[c] = {
exports: {},
id: c,
loaded: !1
};
return b[c].call(d.exports, d, d.exports, __webpack_require__), d.loaded = !0, d.exports;
}
var a = {};
return __webpack_require__.m = b, __webpack_require__.c = a, __webpack_require__.p = "", __webpack_require__(0);
}([function(b, c, a) {
a(1), a(34), a(40), a(42), a(44), a(46), a(48), a(50), a(51), a(52), a(53), a(54), a(55), a(56), a(57), a(58), a(59), a(60), a(61), a(64), a(65), a(66), a(68), a(69), a(70), a(71), a(72), a(73), a(74), a(76), a(77), a(78), a(80), a(81), a(82), a(84), a(85), a(86), a(87), a(88), a(89), a(90), a(91), a(92), a(93), a(94), a(95), a(96), a(97), a(99), a(103), a(104), a(106), a(107), a(111), a(116), a(117), a(120), a(122), a(124), a(126), a(127), a(128), a(130), a(131), a(133), a(134), a(135), a(136), a(143), a(146), a(147), a(149), a(150), a(151), a(152), a(153), a(154), a(155), a(156), a(157), a(158), a(159), a(160), a(162), a(163), a(164), a(165), a(166), a(167), a(169), a(170), a(171), a(172), a(174), a(175), a(177), a(178), a(180), a(181), a(182), a(183), a(186), a(114), a(188), a(187), a(189), a(190), a(191), a(192), a(193), a(195), a(196), a(197), a(198), a(199), b.exports = a(200);
}, function(V, U, b) {
var o,
d = b(2),
H = b(3),
S = b(5),
q = b(6),
F = b(8),
k = b(10),
N = b(11),
c = b(12),
T = b(17),
g = b(18),
m = b(16)("__proto__"),
R = b(9),
t = b(30),
D = b(20),
J = b(22),
A = b(31),
L = b(25),
z = b(32),
h = b(24),
n = b(21),
u = b(4),
B = Object.prototype,
v = [],
l = v.slice,
M = v.join,
w = d.setDesc,
O = d.getDesc,
r = d.setDescs,
y = b(33)(!1),
p = {};
H || (o = !u(function() {
return 7 != w(F("div"), "a", {get: function() {
return 7;
}}).a;
}), d.setDesc = function(b, c, a) {
if (o)
try {
return w(b, c, a);
} catch (d) {}
if ("get" in a || "set" in a)
throw TypeError("Accessors not supported!");
return "value" in a && (t(b)[c] = a.value), b;
}, d.getDesc = function(a, b) {
if (o)
try {
return O(a, b);
} catch (c) {}
return k(a, b) ? S(!B.propertyIsEnumerable.call(a, b), a[b]) : void 0;
}, d.setDescs = r = function(a, b) {
t(a);
for (var c,
e = d.getKeys(b),
g = e.length,
f = 0; g > f; )
d.setDesc(a, c = e[f++], b[c]);
return a;
}), c(c.S + c.F * !H, "Object", {
getOwnPropertyDescriptor: d.getDesc,
defineProperty: d.setDesc,
defineProperties: r
});
var j = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),
I = j.concat("length", "prototype"),
C = j.length,
i = function() {
var a,
b = F("iframe"),
c = C,
d = ">";
for (b.style.display = "none", q.appendChild(b), b.src = "javascript:", a = b.contentWindow.document, a.open(), a.write("<script>document.F=Object</script" + d), a.close(), i = a.F; c--; )
delete i.prototype[j[c]];
return i();
},
E = function(a, b) {
return function(g) {
var c,
e = A(g),
f = 0,
d = [];
for (c in e)
c != m && k(e, c) && d.push(c);
for (; b > f; )
k(e, c = a[f++]) && (~y(d, c) || d.push(c));
return d;
};
},
s = function() {};
c(c.S, "Object", {
getPrototypeOf: d.getProto = d.getProto || function(a) {
return a = J(a), k(a, m) ? a[m] : "function" == typeof a.constructor && a instanceof a.constructor ? a.constructor.prototype : a instanceof Object ? B : null;
},
getOwnPropertyNames: d.getNames = d.getNames || E(I, I.length, !0),
create: d.create = d.create || function(c, d) {
var b;
return null !== c ? (s.prototype = t(c), b = new s, s.prototype = null, b[m] = c) : b = i(), d === a ? b : r(b, d);
},
keys: d.getKeys = d.getKeys || E(j, C, !1)
});
var P = function(d, a, e) {
if (!(a in p)) {
for (var c = [],
b = 0; a > b; b++)
c[b] = "a[" + b + "]";
p[a] = Function("F,a", "return new F(" + c.join(",") + ")");
}
return p[a](d, e);
};
c(c.P, "Function", {bind: function bind(c) {
var a = D(this),
d = l.call(arguments, 1),
b = function() {
var e = d.concat(l.call(arguments));
return this instanceof b ? P(a, e.length, e) : T(a, e, c);
};
return R(a.prototype) && (b.prototype = a.prototype), b;
}});
var Q = u(function() {
q && l.call(q);
});
c(c.P + c.F * Q, "Array", {slice: function(f, b) {
var d = h(this.length),
g = N(this);
if (b = b === a ? d : b, "Array" == g)
return l.call(this, f, b);
for (var e = z(f, d),
k = z(b, d),
i = h(k - e),
j = Array(i),
c = 0; i > c; c++)
j[c] = "String" == g ? this.charAt(e + c) : this[e + c];
return j;
}}), c(c.P + c.F * (n != Object), "Array", {join: function() {
return M.apply(n(this), arguments);
}}), c(c.S, "Array", {isArray: b(27)});
var G = function(a) {
return function(g, d) {
D(g);
var c = n(this),
e = h(c.length),
b = a ? e - 1 : 0,
f = a ? -1 : 1;
if (arguments.length < 2)
for (; ; ) {
if (b in c) {
d = c[b], b += f;
break;
}
if (b += f, a ? 0 > b : b >= e)
throw TypeError("Reduce of empty array with no initial value");
}
for (; a ? b >= 0 : e > b; b += f)
b in c && (d = g(d, c[b], b, this));
return d;
};
},
f = function(a) {
return function(b) {
return a(this, b, arguments[1]);
};
};
c(c.P, "Array", {
forEach: d.each = d.each || f(g(0)),
map: f(g(1)),
filter: f(g(2)),
some: f(g(3)),
every: f(g(4)),
reduce: G(!1),
reduceRight: G(!0),
indexOf: f(y),
lastIndexOf: function(d, e) {
var b = A(this),
c = h(b.length),
a = c - 1;
for (arguments.length > 1 && (a = Math.min(a, L(e))), 0 > a && (a = h(c + a)); a >= 0; a--)
if (a in b && b[a] === d)
return a;
return -1;
}
}), c(c.S, "Date", {now: function() {
return +new Date;
}});
var e = function(a) {
return a > 9 ? a : "0" + a;
},
x = new Date(-5e13 - 1),
K = !(x.toISOString && "0385-07-25T07:06:39.999Z" == x.toISOString() && u(function() {
new Date(NaN).toISOString();
}));
c(c.P + c.F * K, "Date", {toISOString: function toISOString() {
if (!isFinite(this))
throw RangeError("Invalid time value");
var a = this,
b = a.getUTCFullYear(),
c = a.getUTCMilliseconds(),
d = 0 > b ? "-" : b > 9999 ? "+" : "";
return d + ("00000" + Math.abs(b)).slice(d ? -6 : -4) + "-" + e(a.getUTCMonth() + 1) + "-" + e(a.getUTCDate()) + "T" + e(a.getUTCHours()) + ":" + e(a.getUTCMinutes()) + ":" + e(a.getUTCSeconds()) + "." + (c > 99 ? c : "0" + e(c)) + "Z";
}});
}, function(b, c) {
var a = Object;
b.exports = {
create: a.create,
getProto: a.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: a.getOwnPropertyDescriptor,
setDesc: a.defineProperty,
setDescs: a.defineProperties,
getKeys: a.keys,
getNames: a.getOwnPropertyNames,
getSymbols: a.getOwnPropertySymbols,
each: [].forEach
};
}, function(a, c, b) {
a.exports = !b(4)(function() {
return 7 != Object.defineProperty({}, "a", {get: function() {
return 7;
}}).a;
});
}, function(a, b) {
a.exports = function(a) {
try {
return !!a();
} catch (b) {
return !0;
}
};
}, function(a, b) {
a.exports = function(a, b) {
return {
enumerable: !(1 & a),
configurable: !(2 & a),
writable: !(4 & a),
value: b
};
};
}, function(a, c, b) {
a.exports = b(7).document && document.documentElement;
}, function(a, d) {
var b = a.exports = "undefined" != typeof window && window.Math == Math ? window : "undefined" != typeof self && self.Math == Math ? self : Function("return this")();
"number" == typeof c && (c = b);
}, function(d, f, b) {
var c = b(9),
a = b(7).document,
e = c(a) && c(a.createElement);
d.exports = function(b) {
return e ? a.createElement(b) : {};
};
}, function(a, b) {
a.exports = function(a) {
return "object" == typeof a ? null !== a : "function" == typeof a;
};
}, function(a, c) {
var b = {}.hasOwnProperty;
a.exports = function(a, c) {
return b.call(a, c);
};
}, function(a, c) {
var b = {}.toString;
a.exports = function(a) {
return b.call(a).slice(8, -1);
};
}, function(g, j, c) {
var b = c(7),
d = c(13),
h = c(14),
i = c(15),
e = "prototype",
f = function(a, b) {
return function() {
return a.apply(b, arguments);
};
},
a = function(k, j, p) {
var g,
m,
c,
q,
o = k & a.G,
r = k & a.P,
l = o ? b : k & a.S ? b[j] || (b[j] = {}) : (b[j] || {})[e],
n = o ? d : d[j] || (d[j] = {});
o && (p = j);
for (g in p)
m = !(k & a.F) && l && g in l, c = (m ? l : p)[g], q = k & a.B && m ? f(c, b) : r && "function" == typeof c ? f(Function.call, c) : c, l && !m && i(l, g, c), n[g] != c && h(n, g, q), r && ((n[e] || (n[e] = {}))[g] = c);
};
b.core = d, a.F = 1, a.G = 2, a.S = 4, a.P = 8, a.B = 16, a.W = 32, g.exports = a;
}, function(a, d) {
var c = a.exports = {version: "1.2.5"};
"number" == typeof b && (b = c);
}, function(b, e, a) {
var c = a(2),
d = a(5);
b.exports = a(3) ? function(a, b, e) {
return c.setDesc(a, b, d(1, e));
} : function(a, b, c) {
return a[b] = c, a;
};
}, function(f, i, a) {
var g = a(7),
b = a(14),
c = a(16)("src"),
d = "toString",
e = Function[d],
h = ("" + e).split(d);
a(13).inspectSource = function(a) {
return e.call(a);
}, (f.exports = function(e, a, d, f) {
"function" == typeof d && (d.hasOwnProperty(c) || b(d, c, e[a] ? "" + e[a] : h.join(String(a))), d.hasOwnProperty("name") || b(d, "name", a)), e === g ? e[a] = d : (f || delete e[a], b(e, a, d));
})(Function.prototype, d, function toString() {
return "function" == typeof this && this[c] || e.call(this);
});
}, function(b, e) {
var c = 0,
d = Math.random();
b.exports = function(b) {
return "Symbol(".concat(b === a ? "" : b, ")_", (++c + d).toString(36));
};
}, function(b, c) {
b.exports = function(c, b, d) {
var e = d === a;
switch (b.length) {
case 0:
return e ? c() : c.call(d);
case 1:
return e ? c(b[0]) : c.call(d, b[0]);
case 2:
return e ? c(b[0], b[1]) : c.call(d, b[0], b[1]);
case 3:
return e ? c(b[0], b[1], b[2]) : c.call(d, b[0], b[1], b[2]);
case 4:
return e ? c(b[0], b[1], b[2], b[3]) : c.call(d, b[0], b[1], b[2], b[3]);
}
return c.apply(d, b);
};
}, function(d, i, b) {
var e = b(19),
f = b(21),
g = b(22),
h = b(24),
c = b(26);
d.exports = function(b) {
var i = 1 == b,
k = 2 == b,
l = 3 == b,
d = 4 == b,
j = 6 == b,
m = 5 == b || j;
return function(p, v, x) {
for (var o,
r,
u = g(p),
s = f(u),
w = e(v, x, 3),
t = h(s.length),
n = 0,
q = i ? c(p, t) : k ? c(p, 0) : a; t > n; n++)
if ((m || n in s) && (o = s[n], r = w(o, n, u), b))
if (i)
q[n] = r;
else if (r)
switch (b) {
case 3:
return !0;
case 5:
return o;
case 6:
return n;
case 2:
q.push(o);
}
else if (d)
return !1;
return j ? -1 : l || d ? d : q;
};
};
}, function(b, e, c) {
var d = c(20);
b.exports = function(b, c, e) {
if (d(b), c === a)
return b;
switch (e) {
case 1:
return function(a) {
return b.call(c, a);
};
case 2:
return function(a, d) {
return b.call(c, a, d);
};
case 3:
return function(a, d, e) {
return b.call(c, a, d, e);
};
}
return function() {
return b.apply(c, arguments);
};
};
}, function(a, b) {
a.exports = function(a) {
if ("function" != typeof a)
throw TypeError(a + " is not a function!");
return a;
};
}, function(a, d, b) {
var c = b(11);
a.exports = Object("z").propertyIsEnumerable(0) ? Object : function(a) {
return "String" == c(a) ? a.split("") : Object(a);
};
}, function(a, d, b) {
var c = b(23);
a.exports = function(a) {
return Object(c(a));
};
}, function(b, c) {
b.exports = function(b) {
if (b == a)
throw TypeError("Can't call method on " + b);
return b;
};
}, function(a, e, b) {
var c = b(25),
d = Math.min;
a.exports = function(a) {
return a > 0 ? d(c(a), 9007199254740991) : 0;
};
}, function(a, d) {
var b = Math.ceil,
c = Math.floor;
a.exports = function(a) {
return isNaN(a = +a) ? 0 : (a > 0 ? c : b)(a);
};
}, function(d, g, b) {
var e = b(9),
c = b(27),
f = b(28)("species");
d.exports = function(d, g) {
var b;
return c(d) && (b = d.constructor, "function" != typeof b || b !== Array && !c(b.prototype) || (b = a), e(b) && (b = b[f], null === b && (b = a))), new (b === a ? Array : b)(g);
};
}, function(a, d, b) {
var c = b(11);
a.exports = Array.isArray || function(a) {
return "Array" == c(a);
};
}, function(d, f, a) {
var c = a(29)("wks"),
e = a(16),
b = a(7).Symbol;
d.exports = function(a) {
return c[a] || (c[a] = b && b[a] || (b || e)("Symbol." + a));
};
}, function(d, f, e) {
var a = e(7),
b = "__core-js_shared__",
c = a[b] || (a[b] = {});
d.exports = function(a) {
return c[a] || (c[a] = {});
};
}, function(a, d, b) {
var c = b(9);
a.exports = function(a) {
if (!c(a))
throw TypeError(a + " is not an object!");
return a;
};
}, function(b, e, a) {
var c = a(21),
d = a(23);
b.exports = function(a) {
return c(d(a));
};
}, function(a, f, b) {
var c = b(25),
d = Math.max,
e = Math.min;
a.exports = function(a, b) {
return a = c(a), 0 > a ? d(a + b, 0) : e(a, b);
};
}, function(b, f, a) {
var c = a(31),
d = a(24),
e = a(32);
b.exports = function(a) {
return function(j, g, k) {
var h,
f = c(j),
i = d(f.length),
b = e(k, i);
if (a && g != g) {
for (; i > b; )
if (h = f[b++], h != h)
return !0;
} else
for (; i > b; b++)
if ((a || b in f) && f[b] === g)
return a || b;
return !a && -1;
};
};
}, function(W, V, b) {
var e = b(2),
x = b(7),
d = b(10),
w = b(3),
f = b(12),
G = b(15),
H = b(4),
J = b(29),
s = b(35),
S = b(16),
A = b(28),
R = b(36),
C = b(37),
Q = b(38),
P = b(27),
O = b(30),
p = b(31),
v = b(5),
I = e.getDesc,
i = e.setDesc,
k = e.create,
z = C.get,
g = x.Symbol,
l = x.JSON,
m = l && l.stringify,
n = !1,
c = A("_hidden"),
N = e.isEnum,
o = J("symbol-registry"),
h = J("symbols"),
q = "function" == typeof g,
j = Object.prototype,
y = w && H(function() {
return 7 != k(i({}, "a", {get: function() {
return i(this, "a", {value: 7}).a;
}})).a;
}) ? function(c, a, d) {
var b = I(j, a);
b && delete j[a], i(c, a, d), b && c !== j && i(j, a, b);
} : i,
L = function(a) {
var b = h[a] = k(g.prototype);
return b._k = a, w && n && y(j, a, {
configurable: !0,
set: function(b) {
d(this, c) && d(this[c], a) && (this[c][a] = !1), y(this, a, v(1, b));
}
}), b;
},
r = function(a) {
return "symbol" == typeof a;
},
t = function defineProperty(a, b, e) {
return e && d(h, b) ? (e.enumerable ? (d(a, c) && a[c][b] && (a[c][b] = !1), e = k(e, {enumerable: v(0, !1)})) : (d(a, c) || i(a, c, v(1, {})), a[c][b] = !0), y(a, b, e)) : i(a, b, e);
},
u = function defineProperties(a, b) {
O(a);
for (var c,
d = Q(b = p(b)),
e = 0,
f = d.length; f > e; )
t(a, c = d[e++], b[c]);
return a;
},
F = function create(b, c) {
return c === a ? k(b) : u(k(b), c);
},
E = function propertyIsEnumerable(a) {
var b = N.call(this, a);
return b || !d(this, a) || !d(h, a) || d(this, c) && this[c][a] ? b : !0;
},
D = function getOwnPropertyDescriptor(a, b) {
var e = I(a = p(a), b);
return !e || !d(h, b) || d(a, c) && a[c][b] || (e.enumerable = !0), e;
},
B = function getOwnPropertyNames(g) {
for (var a,
b = z(p(g)),
e = [],
f = 0; b.length > f; )
d(h, a = b[f++]) || a == c || e.push(a);
return e;
},
M = function getOwnPropertySymbols(f) {
for (var a,
b = z(p(f)),
c = [],
e = 0; b.length > e; )
d(h, a = b[e++]) && c.push(h[a]);
return c;
},
T = function stringify(e) {
if (e !== a && !r(e)) {
for (var b,
c,
d = [e],
f = 1,
g = arguments; g.length > f; )
d.push(g[f++]);
return b = d[1], "function" == typeof b && (c = b), (c || !P(b)) && (b = function(b, a) {
return c && (a = c.call(this, b, a)), r(a) ? void 0 : a;
}), d[1] = b, m.apply(l, d);
}
},
U = H(function() {
var a = g();
return "[null]" != m([a]) || "{}" != m({a: a}) || "{}" != m(Object(a));
});
q || (g = function Symbol() {
if (r(this))
throw TypeError("Symbol is not a constructor");
return L(S(arguments.length > 0 ? arguments[0] : a));
}, G(g.prototype, "toString", function toString() {
return this._k;
}), r = function(a) {
return a instanceof g;
}, e.create = F, e.isEnum = E, e.getDesc = D, e.setDesc = t, e.setDescs = u, e.getNames = C.get = B, e.getSymbols = M, w && !b(39) && G(j, "propertyIsEnumerable", E, !0));
var K = {
"for": function(a) {
return d(o, a += "") ? o[a] : o[a] = g(a);
},
keyFor: function keyFor(a) {
return R(o, a);
},
useSetter: function() {
n = !0;
},
useSimple: function() {
n = !1;
}
};
e.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","), function(a) {
var b = A(a);
K[a] = q ? b : L(b);
}), n = !0, f(f.G + f.W, {Symbol: g}), f(f.S, "Symbol", K), f(f.S + f.F * !q, "Object", {
create: F,
defineProperty: t,
defineProperties: u,
getOwnPropertyDescriptor: D,
getOwnPropertyNames: B,
getOwnPropertySymbols: M
}), l && f(f.S + f.F * (!q || U), "JSON", {stringify: T}), s(g, "Symbol"), s(Math, "Math", !0), s(x.JSON, "JSON", !0);
}, function(c, f, a) {
var d = a(2).setDesc,
e = a(10),
b = a(28)("toStringTag");
c.exports = function(a, c, f) {
a && !e(a = f ? a : a.prototype, b) && d(a, b, {
configurable: !0,
value: c
});
};
}, function(b, e, a) {
var c = a(2),
d = a(31);
b.exports = function(g, h) {
for (var a,
b = d(g),
e = c.getKeys(b),
i = e.length,
f = 0; i > f; )
if (b[a = e[f++]] === h)
return a;
};
}, function(d, h, a) {
var e = {}.toString,
f = a(31),
b = a(2).getNames,
c = "object" == typeof window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [],
g = function(a) {
try {
return b(a);
} catch (d) {
return c.slice();
}
};
d.exports.get = function getOwnPropertyNames(a) {
return c && "[object Window]" == e.call(a) ? g(a) : b(f(a));
};
}, function(b, d, c) {
var a = c(2);
b.exports = function(b) {
var c = a.getKeys(b),
d = a.getSymbols;
if (d)
for (var e,
f = d(b),
h = a.isEnum,
g = 0; f.length > g; )
h.call(b, e = f[g++]) && c.push(e);
return c;
};
}, function(a, b) {
a.exports = !1;
}, function(c, d, b) {
var a = b(12);
a(a.S + a.F, "Object", {assign: b(41)});
}, function(c, f, a) {
var b = a(2),
d = a(22),
e = a(21);
c.exports = a(4)(function() {
var a = Object.assign,
b = {},
c = {},
d = Symbol(),
e = "abcdefghijklmnopqrst";
return b[d] = 7, e.split("").forEach(function(a) {
c[a] = a;
}), 7 != a({}, b)[d] || Object.keys(a({}, c)).join("") != e;
}) ? function assign(n, q) {
for (var g = d(n),
h = arguments,
o = h.length,
j = 1,
f = b.getKeys,
l = b.getSymbols,
m = b.isEnum; o > j; )
for (var c,
a = e(h[j++]),
k = l ? f(a).concat(l(a)) : f(a),
p = k.length,
i = 0; p > i; )
m.call(a, c = k[i++]) && (g[c] = a[c]);
return g;
} : Object.assign;
}, function(c, d, a) {
var b = a(12);
b(b.S, "Object", {is: a(43)});
}, function(a, b) {
a.exports = Object.is || function is(a, b) {
return a === b ? 0 !== a || 1 / a === 1 / b : a != a && b != b;
};
}, function(c, d, a) {
var b = a(12);
b(b.S, "Object", {setPrototypeOf: a(45).set});
}, function(d, h, b) {
var e = b(2).getDesc,
f = b(9),
g = b(30),
c = function(b, a) {
if (g(b), !f(a) && null !== a)
throw TypeError(a + ": can't set as prototype!");
};
d.exports = {
set: Object.setPrototypeOf || ("__proto__" in {} ? function(f, a, d) {
try {
d = b(19)(Function.call, e(Object.prototype, "__proto__").set, 2), d(f, []), a = !(f instanceof Array);
} catch (g) {
a = !0;
}
return function setPrototypeOf(b, e) {
return c(b, e), a ? b.__proto__ = e : d(b, e), b;
};
}({}, !1) : a),
check: c
};
}, function(d, e, a) {
var c = a(47),
b = {};
b[a(28)("toStringTag")] = "z", b + "" != "[object z]" && a(15)(Object.prototype, "toString", function toString() {
return "[object " + c(this) + "]";
}, !0);
}, function(d, g, c) {
var b = c(11),
e = c(28)("toStringTag"),
f = "Arguments" == b(function() {
return arguments;
}());
d.exports = function(d) {
var c,
g,
h;
return d === a ? "Undefined" : null === d ? "Null" : "string" == typeof(g = (c = Object(d))[e]) ? g : f ? b(c) : "Object" == (h = b(c)) && "function" == typeof c.callee ? "Arguments" : h;
};
}, function(c, d, a) {
var b = a(9);
a(49)("freeze", function(a) {
return function freeze(c) {
return a && b(c) ? a(c) : c;
};
});
}, function(b, e, a) {
var c = (a(12), a(13)),
d = a(4);
b.exports = function(b, h) {
var e = a(12),
f = (c.Object || {})[b] || Object[b],
g = {};
g[b] = h(f), e(e.S + e.F * d(function() {
f(1);
}), "Object", g);
};
}, function(c, d, a) {
var b = a(9);
a(49)("seal", function(a) {
return function seal(c) {
return a && b(c) ? a(c) : c;
};
});
}, function(c, d, a) {
var b = a(9);
a(49)("preventExtensions", function(a) {
return function preventExtensions(c) {
return a && b(c) ? a(c) : c;
};
});
}, function(c, d, a) {
var b = a(9);
a(49)("isFrozen", function(a) {
return function isFrozen(c) {
return b(c) ? a ? a(c) : !1 : !0;
};
});
}, function(c, d, a) {
var b = a(9);
a(49)("isSealed", function(a) {
return function isSealed(c) {
return b(c) ? a ? a(c) : !1 : !0;
};
});
}, function(c, d, a) {
var b = a(9);
a(49)("isExtensible", function(a) {
return function isExtensible(c) {
return b(c) ? a ? a(c) : !0 : !1;
};
});
}, function(c, d, a) {
var b = a(31);
a(49)("getOwnPropertyDescriptor", function(a) {
return function getOwnPropertyDescriptor(c, d) {
return a(b(c), d);
};
});
}, function(c, d, a) {
var b = a(22);
a(49)("getPrototypeOf", function(a) {
return function getPrototypeOf(c) {
return a(b(c));
};
});
}, function(c, d, a) {
var b = a(22);
a(49)("keys", function(a) {
return function keys(c) {
return a(b(c));
};
});
}, function(b, c, a) {
a(49)("getOwnPropertyNames", function() {
return a(37).get;
});
}, function(h, i, a) {
var c = a(2).setDesc,
e = a(5),
f = a(10),
d = Function.prototype,
g = /^\s*function ([^ (]*)/,
b = "name";
b in d || a(3) && c(d, b, {
configurable: !0,
get: function() {
var a = ("" + this).match(g),
d = a ? a[1] : "";
return f(this, b) || c(this, b, e(5, d)), d;
}
});
}, function(f, g, a) {
var b = a(2),
c = a(9),
d = a(28)("hasInstance"),
e = Function.prototype;
d in e || b.setDesc(e, d, {value: function(a) {
if ("function" != typeof this || !c(a))
return !1;
if (!c(this.prototype))
return a instanceof this;
for (; a = b.getProto(a); )
if (this.prototype === a)
return !0;
return !1;
}});
}, function(q, p, b) {
var c = b(2),
h = b(7),
i = b(10),
j = b(11),
l = b(62),
k = b(4),
n = b(63).trim,
d = "Number",
a = h[d],
e = a,
f = a.prototype,
o = j(c.create(f)) == d,
m = "trim" in String.prototype,
g = function(i) {
var a = l(i, !1);
if ("string" == typeof a && a.length > 2) {
a = m ? a.trim() : n(a, 3);
var b,
c,
d,
e = a.charCodeAt(0);
if (43 === e || 45 === e) {
if (b = a.charCodeAt(2), 88 === b || 120 === b)
return NaN;
} else if (48 === e) {
switch (a.charCodeAt(1)) {
case 66:
case 98:
c = 2, d = 49;
break;
case 79:
case 111:
c = 8, d = 55;
break;
default:
return +a;
}
for (var f,
g = a.slice(2),
h = 0,
j = g.length; j > h; h++)
if (f = g.charCodeAt(h), 48 > f || f > d)
return NaN;
return parseInt(g, c);
}
}
return +a;
};
a(" 0o1") && a("0b1") && !a("+0x1") || (a = function Number(h) {
var c = arguments.length < 1 ? 0 : h,
b = this;
return b instanceof a && (o ? k(function() {
f.valueOf.call(b);
}) : j(b) != d) ? new e(g(c)) : g(c);
}, c.each.call(b(3) ? c.getNames(e) : "MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","), function(b) {
i(e, b) && !i(a, b) && c.setDesc(a, b, c.getDesc(e, b));
}), a.prototype = f, f.constructor = a, b(15)(h, d, a));
}, function(b, d, c) {
var a = c(9);
b.exports = function(b, e) {
if (!a(b))
return b;
var c,
d;
if (e && "function" == typeof(c = b.toString) && !a(d = c.call(b)))
return d;
if ("function" == typeof(c = b.valueOf) && !a(d = c.call(b)))
return d;
if (!e && "function" == typeof(c = b.toString) && !a(d = c.call(b)))
return d;
throw TypeError("Can't convert object to primitive value");
};
}, function(g, m, b) {
var c = b(12),
h = b(23),
i = b(4),
d = " \n\f\r \u2028\u2029\ufeff",
a = "[" + d + "]",
f = "
",
j = RegExp("^" + a + a + "*"),
k = RegExp(a + a + "*$"),
e = function(a, e) {
var b = {};
b[a] = e(l), c(c.P + c.F * i(function() {
return !!d[a]() || f[a]() != f;
}), "String", b);
},
l = e.trim = function(a, b) {
return a = String(h(a)), 1 & b && (a = a.replace(j, "")), 2 & b && (a = a.replace(k, "")), a;
};
g.exports = e;
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {EPSILON: Math.pow(2, -52)});
}, function(d, e, a) {
var b = a(12),
c = a(7).isFinite;
b(b.S, "Number", {isFinite: function isFinite(a) {
return "number" == typeof a && c(a);
}});
}, function(c, d, a) {
var b = a(12);
b(b.S, "Number", {isInteger: a(67)});
}, function(a, e, b) {
var c = b(9),
d = Math.floor;
a.exports = function isInteger(a) {
return !c(a) && isFinite(a) && d(a) === a;
};
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {isNaN: function isNaN(a) {
return a != a;
}});
}, function(e, f, a) {
var b = a(12),
c = a(67),
d = Math.abs;
b(b.S, "Number", {isSafeInteger: function isSafeInteger(a) {
return c(a) && d(a) <= 9007199254740991;
}});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {MAX_SAFE_INTEGER: 9007199254740991});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {MIN_SAFE_INTEGER: -9007199254740991});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {parseFloat: parseFloat});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Number", {parseInt: parseInt});
}, function(f, g, b) {
var a = b(12),
e = b(75),
c = Math.sqrt,
d = Math.acosh;
a(a.S + a.F * !(d && 710 == Math.floor(d(Number.MAX_VALUE))), "Math", {acosh: function acosh(a) {
return (a = +a) < 1 ? NaN : a > 94906265.62425156 ? Math.log(a) + Math.LN2 : e(a - 1 + c(a - 1) * c(a + 1));
}});
}, function(a, b) {
a.exports = Math.log1p || function log1p(a) {
return (a = +a) > -1e-8 && 1e-8 > a ? a - a * a / 2 : Math.log(1 + a);
};
}, function(c, d, b) {
function asinh(a) {
return isFinite(a = +a) && 0 != a ? 0 > a ? -asinh(-a) : Math.log(a + Math.sqrt(a * a + 1)) : a;
}
var a = b(12);
a(a.S, "Math", {asinh: asinh});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Math", {atanh: function atanh(a) {
return 0 == (a = +a) ? a : Math.log((1 + a) / (1 - a)) / 2;
}});
}, function(d, e, a) {
var b = a(12),
c = a(79);
b(b.S, "Math", {cbrt: function cbrt(a) {
return c(a = +a) * Math.pow(Math.abs(a), 1 / 3);
}});
}, function(a, b) {
a.exports = Math.sign || function sign(a) {
return 0 == (a = +a) || a != a ? a : 0 > a ? -1 : 1;
};
}, function(c, d, b) {
var a = b(12);
a(a.S, "Math", {clz32: function clz32(a) {
return (a >>>= 0) ? 31 - Math.floor(Math.log(a + .5) * Math.LOG2E) : 32;
}});
}, function(d, e, c) {
var a = c(12),
b = Math.exp;
a(a.S, "Math", {cosh: function cosh(a) {
return (b(a = +a) + b(-a)) / 2;
}});
}, function(c, d, a) {
var b = a(12);
b(b.S, "Math", {expm1: a(83)});
}, function(a, b) {
a.exports = Math.expm1 || function expm1(a) {
return 0 == (a = +a) ? a : a > -1e-6 && 1e-6 > a ? a + a * a / 2 : Math.exp(a) - 1;
};
}, function(k, j, e) {
var f = e(12),
g = e(79),
a = Math.pow,
d = a(2, -52),
b = a(2, -23),
i = a(2, 127) * (2 - b),
c = a(2, -126),
h = function(a) {
return a + 1 / d - 1 / d;
};
f(f.S, "Math", {fround: function fround(k) {
var f,
a,
e = Math.abs(k),
j = g(k);
return c > e ? j * h(e / c / b) * c * b : (f = (1 + b / d) * e, a = f - (f - e), a > i || a != a ? j * (1 / 0) : j * a);
}});
}, function(d, e, b) {
var a = b(12),
c = Math.abs;
a(a.S, "Math", {hypot: function hypot(i, j) {
for (var a,
b,
e = 0,
f = 0,
g = arguments,
h = g.length,
d = 0; h > f; )
a = c(g[f++]), a > d ? (b = d / a, e = e * b * b + 1, d = a) : a > 0 ? (b = a / d, e += b * b) : e += a;
return d === 1 / 0 ? 1 / 0 : d * Math.sqrt(e);
}});
}, function(d, e, b) {
var a = b(12),
c = Math.imul;
a(a.S + a.F * b(4)(function() {
return -5 != c(4294967295, 5) || 2 != c.length;
}), "Math", {imul: function imul(f, g) {
var a = 65535,
b = +f,
c = +g,
d = a & b,
e = a & c;
return 0 | d * e + ((a & b >>> 16) * e + d * (a & c >>> 16) << 16 >>> 0);
}});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Math", {log10: function log10(a) {
return Math.log(a) / Math.LN10;
}});
}, function(c, d, a) {
var b = a(12);
b(b.S, "Math", {log1p: a(75)});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Math", {log2: function log2(a) {
return Math.log(a) / Math.LN2;
}});
}, function(c, d, a) {
var b = a(12);
b(b.S, "Math", {sign: a(79)});
}, function(e, f, a) {
var b = a(12),
c = a(83),
d = Math.exp;
b(b.S + b.F * a(4)(function() {
return -2e-17 != !Math.sinh(-2e-17);
}), "Math", {sinh: function sinh(a) {
return Math.abs(a = +a) < 1 ? (c(a) - c(-a)) / 2 : (d(a - 1) - d(-a - 1)) * (Math.E / 2);
}});
}, function(e, f, a) {
var b = a(12),
c = a(83),
d = Math.exp;
b(b.S, "Math", {tanh: function tanh(a) {
var b = c(a = +a),
e = c(-a);
return b == 1 / 0 ? 1 : e == 1 / 0 ? -1 : (b - e) / (d(a) + d(-a));
}});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Math", {trunc: function trunc(a) {
return (a > 0 ? Math.floor : Math.ceil)(a);
}});
}, function(f, g, b) {
var a = b(12),
e = b(32),
c = String.fromCharCode,
d = String.fromCodePoint;
a(a.S + a.F * (!!d && 1 != d.length), "String", {fromCodePoint: function fromCodePoint(h) {
for (var a,
b = [],
d = arguments,
g = d.length,
f = 0; g > f; ) {
if (a = +d[f++], e(a, 1114111) !== a)
throw RangeError(a + " is not a valid code point");
b.push(65536 > a ? c(a) : c(((a -= 65536) >> 10) + 55296, a % 1024 + 56320));
}
return b.join("");
}});
}, function(e, f, a) {
var b = a(12),
c = a(31),
d = a(24);
b(b.S, "String", {raw: function raw(g) {
for (var e = c(g.raw),
h = d(e.length),
f = arguments,
i = f.length,
b = [],
a = 0; h > a; )
b.push(String(e[a++])), i > a && b.push(String(f[a]));
return b.join("");
}});
}, function(b, c, a) {
a(63)("trim", function(a) {
return function trim() {
return a(this, 3);
};
});
}, function(d, e, a) {
var b = a(12),
c = a(98)(!1);
b(b.P, "String", {codePointAt: function codePointAt(a) {
return c(this, a);
}});
}, function(c, f, b) {
var d = b(25),
e = b(23);
c.exports = function(b) {
return function(j, k) {
var f,
h,
g = String(e(j)),
c = d(k),
i = g.length;
return 0 > c || c >= i ? b ? "" : a : (f = g.charCodeAt(c), 55296 > f || f > 56319 || c + 1 === i || (h = g.charCodeAt(c + 1)) < 56320 || h > 57343 ? b ? g.charAt(c) : f : b ? g.slice(c, c + 2) : (f - 55296 << 10) + (h - 56320) + 65536);
};
};
}, function(h, i, b) {
var c = b(12),
e = b(24),
g = b(100),
d = "endsWith",
f = ""[d];
c(c.P + c.F * b(102)(d), "String", {endsWith: function endsWith(i) {
var b = g(this, i, d),
j = arguments,
k = j.length > 1 ? j[1] : a,
l = e(b.length),
c = k === a ? l : Math.min(e(k), l),
h = String(i);
return f ? f.call(b, h, c) : b.slice(c - h.length, c) === h;
}});
}, function(b, e, a) {
var c = a(101),
d = a(23);
b.exports = function(a, b, e) {
if (c(b))
throw TypeError("String#" + e + " doesn't accept regex!");
return String(d(a));
};
}, function(c, g, b) {
var d = b(9),
e = b(11),
f = b(28)("match");
c.exports = function(b) {
var c;
return d(b) && ((c = b[f]) !== a ? !!c : "RegExp" == e(b));
};
}, function(a, d, b) {
var c = b(28)("match");
a.exports = function(b) {
var a = /./;
try {
"/./"[b](a);
} catch (d) {
try {
return a[c] = !1, !"/./"[b](a);
} catch (e) {}
}
return !0;
};
}, function(f, g, b) {
var c = b(12),
e = b(100),
d = "includes";
c(c.P + c.F * b(102)(d), "String", {includes: function includes(b) {
return !!~e(this, b, d).indexOf(b, arguments.length > 1 ? arguments[1] : a);
}});
}, function(c, d, a) {
var b = a(12);
b(b.P, "String", {repeat: a(105)});
}, function(b, e, a) {
var c = a(25),
d = a(23);
b.exports = function repeat(f) {
var b = String(d(this)),
e = "",
a = c(f);
if (0 > a || a == 1 / 0)
throw RangeError("Count can't be negative");
for (; a > 0; (a >>>= 1) && (b += b))
1 & a && (e += b);
return e;
};
}, function(h, i, b) {
var c = b(12),
f = b(24),
g = b(100),
d = "startsWith",
e = ""[d];
c(c.P + c.F * b(102)(d), "String", {startsWith: function startsWith(i) {
var b = g(this, i, d),
j = arguments,
c = f(Math.min(j.length > 1 ? j[1] : a, b.length)),
h = String(i);
return e ? e.call(b, h, c) : b.slice(c, c + h.length) === h;
}});
}, function(d, e, b) {
var c = b(98)(!0);
b(108)(String, "String", function(a) {
this._t = String(a), this._i = 0;
}, function() {
var b,
d = this._t,
e = this._i;
return e >= d.length ? {
value: a,
done: !0
} : (b = c(d, e), this._i += b.length, {
value: b,
done: !1
});
});
}, function(q, r, a) {
var k = a(39),
d = a(12),
p = a(15),
g = a(14),
o = a(10),
c = a(28)("iterator"),
f = a(109),
n = a(110),
l = a(35),
m = a(2).getProto,
e = !([].keys && "next" in [].keys()),
j = "@@iterator",
h = "keys",
b = "values",
i = function() {
return this;
};
q.exports = function(A, u, t, D, r, C, y) {
n(t, u, D);
var s,
v,
w = function(c) {
if (!e && c in a)
return a[c];
switch (c) {
case h:
return function keys() {
return new t(this, c);
};
case b:
return function values() {
return new t(this, c);
};
}
return function entries() {
return new t(this, c);
};
},
z = u + " Iterator",
a = A.prototype,
x = a[c] || a[j] || r && a[r],
q = x || w(r);
if (x) {
var B = m(q.call(new A));
l(B, z, !0), !k && o(a, j) && g(B, c, i);
}
if (k && !y || !e && c in a || g(a, c, q), f[u] = q, f[z] = i, r)
if (s = {
values: r == b ? q : w(b),
keys: C ? q : w(h),
entries: r != b ? q : w("entries")
}, y)
for (v in s)
v in a || p(a, v, s[v]);
else
d(d.P + d.F * e, u, s);
return s;
};
}, function(a, b) {
a.exports = {};
}, function(c, g, a) {
var d = a(2),
e = a(5),
f = a(35),
b = {};
a(14)(b, a(28)("iterator"), function() {
return this;
}), c.exports = function(a, c, g) {
a.prototype = d.create(b, {next: e(1, g)}), f(a, c + " Iterator");
};
}, function(j, k, b) {
var d = b(19),
c = b(12),
e = b(22),
f = b(112),
g = b(113),
h = b(24),
i = b(114);
c(c.S + c.F * !b(115)(function(a) {
Array.from(a);
}), "Array", {from: function from(t) {
var n,
c,
r,
m,
j = e(t),
l = "function" == typeof this ? this : Array,
p = arguments,
s = p.length,
k = s > 1 ? p[1] : a,
q = k !== a,
b = 0,
o = i(j);
if (q && (k = d(k, s > 2 ? p[2] : a, 2)), o == a || l == Array && g(o))
for (n = h(j.length), c = new l(n); n > b; b++)
c[b] = q ? k(j[b], b) : j[b];
else
for (m = o.call(j), c = new l; !(r = m.next()).done; b++)
c[b] = q ? f(m, k, [r.value, b], !0) : r.value;
return c.length = b, c;
}});
}, function(c, e, d) {
var b = d(30);
c.exports = function(d, e, c, g) {
try {
return g ? e(b(c)[0], c[1]) : e(c);
} catch (h) {
var f = d["return"];
throw f !== a && b(f.call(d)), h;
}
};
}, function(b, f, a) {
var c = a(109),
d = a(28)("iterator"),
e = Array.prototype;
b.exports = function(a) {
return (c.Array || e[d]) === a;
};
}, function(c, g, b) {
var d = b(47),
e = b(28)("iterator"),
f = b(109);
c.exports = b(13).getIteratorMethod = function(b) {
return b != a ? b[e] || b["@@iterator"] || f[d(b)] : void 0;
};
}, function(d, f, e) {
var a = e(28)("iterator"),
b = !1;
try {
var c = [7][a]();
c["return"] = function() {
b = !0;
}, Array.from(c, function() {
throw 2;
});
} catch (g) {}
d.exports = function(f, g) {
if (!g && !b)
return !1;
var d = !1;
try {
var c = [7],
e = c[a]();
e.next = function() {
d = !0;
}, c[a] = function() {
return e;
}, f(c);
} catch (h) {}
return d;
};
}, function(c, d, b) {
var a = b(12);
a(a.S + a.F * b(4)(function() {
function F() {}
return !(Array.of.call(F) instanceof F);
}), "Array", {of: function of() {
for (var a = 0,
d = arguments,
b = d.length,
c = new ("function" == typeof this ? this : Array)(b); b > a; )
c[a] = d[a++];
return c.length = b, c;
}});
}, function(f, h, b) {
var d = b(118),
c = b(119),
e = b(109),
g = b(31);
f.exports = b(108)(Array, "Array", function(a, b) {
this._t = g(a), this._i = 0, this._k = b;
}, function() {
var d = this._t,
e = this._k,
b = this._i++;
return !d || b >= d.length ? (this._t = a, c(1)) : "keys" == e ? c(0, b) : "values" == e ? c(0, d[b]) : c(0, [b, d[b]]);
}, "values"), e.Arguments = e.Array, d("keys"), d("values"), d("entries");
}, function(e, f, d) {
var b = d(28)("unscopables"),
c = Array.prototype;
c[b] == a && d(14)(c, b, {}), e.exports = function(a) {
c[b][a] = !0;
};
}, function(a, b) {
a.exports = function(a, b) {
return {
value: b,
done: !!a
};
};
}, function(b, c, a) {
a(121)("Array");
}, function(c, g, a) {
var d = a(7),
e = a(2),
f = a(3),
b = a(28)("species");
c.exports = function(c) {
var a = d[c];
f && a && !a[b] && e.setDesc(a, b, {
configurable: !0,
get: function() {
return this;
}
});
};
}, function(c, d, a) {
var b = a(12);
b(b.P, "Array", {copyWithin: a(123)}), a(118)("copyWithin");
}, function(d, g, b) {
var e = b(22),
c = b(32),
f = b(24);
d.exports = [].copyWithin || function copyWithin(m, n) {
var g = e(this),
h = f(g.length),
b = c(m, h),
d = c(n, h),
k = arguments,
l = k.length > 2 ? k[2] : a,
i = Math.min((l === a ? h : c(l, h)) - d, h - b),
j = 1;
for (b > d && d + i > b && (j = -1, d += i - 1, b += i - 1); i-- > 0; )
d in g ? g[b] = g[d] : delete g[b], b += j, d += j;
return g;
};
}, function(c, d, a) {
var b = a(12);
b(b.P, "Array", {fill: a(125)}), a(118)("fill");
}, function(d, g, b) {
var e = b(22),
c = b(32),
f = b(24);
d.exports = [].fill || function fill(k) {
for (var b = e(this, !0),
d = f(b.length),
g = arguments,
h = g.length,
i = c(h > 1 ? g[1] : a, d),
j = h > 2 ? g[2] : a,
l = j === a ? d : c(j, d); l > i; )
b[i++] = k;
return b;
};
}, function(g, h, b) {
var c = "find",
d = b(12),
e = !0,
f = b(18)(5);
c in [] && Array(1)[c](function() {
e = !1;
}), d(d.P + d.F * e, "Array", {find: function find(b) {
return f(this, b, arguments.length > 1 ? arguments[1] : a);
}}), b(118)(c);
}, function(g, h, b) {
var c = "findIndex",
d = b(12),
e = !0,
f = b(18)(6);
c in [] && Array(1)[c](function() {
e = !1;
}), d(d.P + d.F * e, "Array", {findIndex: function findIndex(b) {
return f(this, b, arguments.length > 1 ? arguments[1] : a);
}}), b(118)(c);
}, function(n, m, c) {
var f = c(2),
i = c(7),
k = c(101),
l = c(129),
b = i.RegExp,
d = b,
j = b.prototype,
e = /a/g,
g = /a/g,
h = new b(e) !== e;
!c(3) || h && !c(4)(function() {
return g[c(28)("match")] = !1, b(e) != e || b(g) == g || "/a/i" != b(e, "i");
}) || (b = function RegExp(c, f) {
var e = k(c),
g = f === a;
return this instanceof b || !e || c.constructor !== b || !g ? h ? new d(e && !g ? c.source : c, f) : d((e = c instanceof b) ? c.source : c, e && g ? l.call(c) : f) : c;
}, f.each.call(f.getNames(d), function(a) {
a in b || f.setDesc(b, a, {
configurable: !0,
get: function() {
return d[a];
},
set: function(b) {
d[a] = b;
}
});
}), j.constructor = b, b.prototype = j, c(15)(i, "RegExp", b)), c(121)("RegExp");
}, function(a, d, b) {
var c = b(30);
a.exports = function() {
var b = c(this),
a = "";
return b.global && (a += "g"), b.ignoreCase && (a += "i"), b.multiline && (a += "m"), b.unicode && (a += "u"), b.sticky && (a += "y"), a;
};
}, function(c, d, a) {
var b = a(2);
a(3) && "g" != /./g.flags && b.setDesc(RegExp.prototype, "flags", {
configurable: !0,
get: a(129)
});
}, function(c, d, b) {
b(132)("match", 1, function(c, b) {
return function match(d) {
var e = c(this),
f = d == a ? a : d[b];
return f !== a ? f.call(d, e) : new RegExp(d)[b](String(e));
};
});
}, function(b, h, a) {
var c = a(14),
d = a(15),
e = a(4),
f = a(23),
g = a(28);
b.exports = function(a, i, j) {
var b = g(a),
h = ""[a];
e(function() {
var c = {};
return c[b] = function() {
return 7;
}, 7 != ""[a](c);
}) && (d(String.prototype, a, j(f, b, h)), c(RegExp.prototype, b, 2 == i ? function(a, b) {
return h.call(a, this, b);
} : function(a) {
return h.call(a, this);
}));
};
}, function(c, d, b) {
b(132)("replace", 2, function(b, c, d) {
return function replace(e, f) {
var g = b(this),
h = e == a ? a : e[c];
return h !== a ? h.call(e, g, f) : d.call(String(g), e, f);
};
});
}, function(c, d, b) {
b(132)("search", 1, function(c, b) {
return function search(d) {
var e = c(this),
f = d == a ? a : d[b];
return f !== a ? f.call(d, e) : new RegExp(d)[b](String(e));
};
});
}, function(c, d, b) {
b(132)("split", 2, function(b, c, d) {
return function split(e, f) {
var g = b(this),
h = e == a ? a : e[c];
return h !== a ? h.call(e, g, f) : d.call(String(g), e, f);
};
});
}, function(J, I, b) {
var o,
k = b(2),
z = b(39),
j = b(7),
i = b(19),
n = b(47),
d = b(12),
q = b(9),
F = b(30),
l = b(20),
B = b(137),
u = b(138),
x = b(45).set,
G = b(43),
E = b(28)("species"),
A = b(139),
h = b(16)("record"),
p = b(140),
e = "Promise",
r = j.process,
H = "process" == n(r),
c = j[e],
t = function(b) {
var a = new c(function() {});
return b && (a.constructor = Object), c.resolve(a) === a;
},
f = function() {
function P2(b) {
var a = new c(b);
return x(a, P2.prototype), a;
}
var a = !1;
try {
if (a = c && c.resolve && t(), x(P2, c), P2.prototype = k.create(c.prototype, {constructor: {value: P2}}), P2.resolve(5).then(function() {}) instanceof P2 || (a = !1), a && b(3)) {
var d = !1;
c.resolve(k.setDesc({}, "then", {get: function() {
d = !0;
}})), a = d;
}
} catch (e) {
a = !1;
}
return a;
}(),
C = function(a) {
return q(a) && (f ? "Promise" == n(a) : h in a);
},
D = function(a, b) {
return z && a === c && b === o ? !0 : G(a, b);
},
v = function(b) {
var c = F(b)[E];
return c != a ? c : b;
},
w = function(a) {
var b;
return q(a) && "function" == typeof(b = a.then) ? b : !1;
},
m = function(b, d) {
if (!b.n) {
b.n = !0;
var c = b.c;
p(function() {
for (var e = b.v,
f = 1 == b.s,
g = 0,
h = function(a) {
var c,
g,
d = f ? a.ok : a.fail;
try {
d ? (f || (b.h = !0), c = d === !0 ? e : d(e), c === a.P ? a.rej(TypeError("Promise-chain cycle")) : (g = w(c)) ? g.call(c, a.res, a.rej) : a.res(c)) : a.rej(e);
} catch (h) {
a.rej(h);
}
}; c.length > g; )
h(c[g++]);
c.length = 0, b.n = !1, d && setTimeout(function() {
var f,
c,
d = b.p;
y(d) && (H ? r.emit("unhandledRejection", e, d) : (f = j.onunhandledrejection) ? f({
promise: d,
reason: e
}) : (c = j.console) && c.error && c.error("Unhandled promise rejection", e)), b.a = a;
}, 1);
});
}
},
y = function(e) {
var a,
b = e[h],
c = b.a || b.c,
d = 0;
if (b.h)
return !1;
for (; c.length > d; )
if (a = c[d++], a.fail || !y(a.P))
return !1;
return !0;
},
g = function(b) {
var a = this;
a.d || (a.d = !0, a = a.r || a, a.v = b, a.s = 2, a.a = a.c.slice(), m(a, !0));
},
s = function(b) {
var c,
a = this;
if (!a.d) {
a.d = !0, a = a.r || a;
try {
(c = w(b)) ? p(function() {
var d = {
r: a,
d: !1
};
try {
c.call(b, i(s, d, 1), i(g, d, 1));
} catch (e) {
g.call(d, e);
}
}) : (a.v = b, a.s = 1, m(a, !1));
} catch (d) {
g.call({
r: a,
d: !1
}, d);
}
}
};
f || (c = function Promise(d) {
l(d);
var b = {
p: B(this, c, e),
c: [],
a: a,
s: 0,
d: !1,
v: a,
h: !1,
n: !1
};
this[h] = b;
try {
d(i(s, b, 1), i(g, b, 1));
} catch (f) {
g.call(b, f);
}
}, b(142)(c.prototype, {
then: function then(d, e) {
var a = {
ok: "function" == typeof d ? d : !0,
fail: "function" == typeof e ? e : !1
},
f = a.P = new (A(this, c))(function(b, c) {
a.res = b, a.rej = c;
});
l(a.res), l(a.rej);
var b = this[h];
return b.c.push(a), b.a && b.a.push(a), b.s && m(b, !1), f;
},
"catch": function(b) {
return this.then(a, b);
}
})), d(d.G + d.W + d.F * !f, {Promise: c}), b(35)(c, e), b(121)(e), o = b(13)[e], d(d.S + d.F * !f, e, {reject: function reject(a) {
return new this(function(c, b) {
b(a);
});
}}), d(d.S + d.F * (!f || t(!0)), e, {resolve: function resolve(a) {
return C(a) && D(a.constructor, this) ? a : new this(function(b) {
b(a);
});
}}), d(d.S + d.F * !(f && b(115)(function(a) {
c.all(a)["catch"](function() {});
})), e, {
all: function all(c) {
var b = v(this),
a = [];
return new b(function(f, g) {
u(c, !1, a.push, a);
var d = a.length,
e = Array(d);
d ? k.each.call(a, function(a, c) {
b.resolve(a).then(function(a) {
e[c] = a, --d || f(e);
}, g);
}) : f(e);
});
},
race: function race(b) {
var a = v(this);
return new a(function(c, d) {
u(b, !1, function(b) {
a.resolve(b).then(c, d);
});
});
}
});
}, function(a, b) {
a.exports = function(a, b, c) {
if (!(a instanceof b))
throw TypeError(c + ": use the 'new' operator!");
return a;
};
}, function(b, i, a) {
var c = a(19),
d = a(112),
e = a(113),
f = a(30),
g = a(24),
h = a(114);
b.exports = function(a, j, o, p) {
var n,
b,
k,
l = h(a),
m = c(o, p, j ? 2 : 1),
i = 0;
if ("function" != typeof l)
throw TypeError(a + " is not iterable!");
if (e(l))
for (n = g(a.length); n > i; i++)
j ? m(f(b = a[i])[0], b[1]) : m(a[i]);
else
for (k = l.call(a); !(b = k.next()).done; )
d(k, m, b.value, j);
};
}, function(d, g, b) {
var c = b(30),
e = b(20),
f = b(28)("species");
d.exports = function(g, h) {
var b,
d = c(g).constructor;
return d === a || (b = c(d)[f]) == a ? h : e(b);
};
}, function(m, o, g) {
var b,
e,
f,
d = g(7),
n = g(141).set,
j = d.MutationObserver || d.WebKitMutationObserver,
c = d.process,
h = "process" == g(11)(c),
i = function() {
var f,
d;
for (h && (f = c.domain) && (c.domain = null, f.exit()); b; )
d = b.domain, d && d.enter(), b.fn.call(), d && d.exit(), b = b.next;
e = a, f && f.enter();
};
if (h)
f = function() {
c.nextTick(i);
};
else if (j) {
var k = 1,
l = document.createTextNode("");
new j(i).observe(l, {characterData: !0}), f = function() {
l.data = k = -k;
};
} else
f = function() {
n.call(d, i);
};
m.exports = function asap(g) {
var d = {
fn: g,
next: a,
domain: h && c.domain
};
e && (e.next = d), b || (b = d, f()), e = d;
};
}, function(s, t, b) {
var c,
g,
f,
k = b(19),
r = b(17),
n = b(6),
p = b(8),
a = b(7),
l = a.process,
h = a.setImmediate,
i = a.clearImmediate,
o = a.MessageChannel,
j = 0,
d = {},
q = "onreadystatechange",
e = function() {
var a = +this;
if (d.hasOwnProperty(a)) {
var b = d[a];
delete d[a], b();
}
},
m = function(a) {
e.call(a.data);
};
h && i || (h = function setImmediate(a) {
for (var b = [],
e = 1; arguments.length > e; )
b.push(arguments[e++]);
return d[++j] = function() {
r("function" == typeof a ? a : Function(a), b);
}, c(j), j;
}, i = function clearImmediate(a) {
delete d[a];
}, "process" == b(11)(l) ? c = function(a) {
l.nextTick(k(e, a, 1));
} : o ? (g = new o, f = g.port2, g.port1.onmessage = m, c = k(f.postMessage, f, 1)) : a.addEventListener && "function" == typeof postMessage && !a.importScripts ? (c = function(b) {
a.postMessage(b + "", "*");
}, a.addEventListener("message", m, !1)) : c = q in p("script") ? function(a) {
n.appendChild(p("script"))[q] = function() {
n.removeChild(this), e.call(a);
};
} : function(a) {
setTimeout(k(e, a, 1), 0);
}), s.exports = {
set: h,
clear: i
};
}, function(a, d, b) {
var c = b(15);
a.exports = function(a, b) {
for (var d in b)
c(a, d, b[d]);
return a;
};
}, function(d, e, c) {
var b = c(144);
c(145)("Map", function(b) {
return function Map() {
return b(this, arguments.length > 0 ? arguments[0] : a);
};
}, {
get: function get(c) {
var a = b.getEntry(this, c);
return a && a.v;
},
set: function set(a, c) {
return b.def(this, 0 === a ? 0 : a, c);
}
}, b, !0);
}, function(v, w, b) {
var j = b(2),
m = b(14),
o = b(142),
n = b(19),
p = b(137),
r = b(23),
t = b(138),
l = b(108),
d = b(119),
f = b(16)("id"),
k = b(10),
h = b(9),
q = b(121),
i = b(3),
s = Object.isExtensible || h,
c = i ? "_s" : "size",
u = 0,
g = function(a, b) {
if (!h(a))
return "symbol" == typeof a ? a : ("string" == typeof a ? "S" : "P") + a;
if (!k(a, f)) {
if (!s(a))
return "F";
if (!b)
return "E";
m(a, f, ++u);
}
return "O" + a[f];
},
e = function(b, c) {
var a,
d = g(c);
if ("F" !== d)
return b._i[d];
for (a = b._f; a; a = a.n)
if (a.k == c)
return a;
};
v.exports = {
getConstructor: function(d, f, g, h) {
var b = d(function(d, e) {
p(d, b, f), d._i = j.create(null), d._f = a, d._l = a, d[c] = 0, e != a && t(e, g, d[h], d);
});
return o(b.prototype, {
clear: function clear() {
for (var d = this,
e = d._i,
b = d._f; b; b = b.n)
b.r = !0, b.p && (b.p = b.p.n = a), delete e[b.i];
d._f = d._l = a, d[c] = 0;
},
"delete": function(g) {
var b = this,
a = e(b, g);
if (a) {
var d = a.n,
f = a.p;
delete b._i[a.i], a.r = !0, f && (f.n = d), d && (d.p = f), b._f == a && (b._f = d), b._l == a && (b._l = f), b[c]--;
}
return !!a;
},
forEach: function forEach(c) {
for (var b,
d = n(c, arguments.length > 1 ? arguments[1] : a, 3); b = b ? b.n : this._f; )
for (d(b.v, b.k, this); b && b.r; )
b = b.p;
},
has: function has(a) {
return !!e(this, a);
}
}), i && j.setDesc(b.prototype, "size", {get: function() {
return r(this[c]);
}}), b;
},
def: function(b, f, j) {
var h,
i,
d = e(b, f);
return d ? d.v = j : (b._l = d = {
i: i = g(f, !0),
k: f,
v: j,
p: h = b._l,
n: a,
r: !1
}, b._f || (b._f = d), h && (h.n = d), b[c]++, "F" !== i && (b._i[i] = d)), b;
},
getEntry: e,
setStrong: function(e, b, c) {
l(e, b, function(b, c) {
this._t = b, this._k = c, this._l = a;
}, function() {
for (var c = this,
e = c._k,
b = c._l; b && b.r; )
b = b.p;
return c._t && (c._l = b = b ? b.n : c._t._f) ? "keys" == e ? d(0, b.k) : "values" == e ? d(0, b.v) : d(0, [b.k, b.v]) : (c._t = a, d(1));
}, c ? "entries" : "values", !c, !0), q(b);
}
};
}, function(l, n, b) {
var k = b(7),
c = b(12),
g = b(15),
f = b(142),
i = b(138),
j = b(137),
d = b(9),
e = b(4),
h = b(115),
m = b(35);
l.exports = function(o, v, y, x, p, l) {
var t = k[o],
b = t,
s = p ? "set" : "add",
n = b && b.prototype,
w = {},
r = function(b) {
var c = n[b];
g(n, b, "delete" == b ? function(a) {
return l && !d(a) ? !1 : c.call(this, 0 === a ? 0 : a);
} : "has" == b ? function has(a) {
return l && !d(a) ? !1 : c.call(this, 0 === a ? 0 : a);
} : "get" == b ? function get(b) {
return l && !d(b) ? a : c.call(this, 0 === b ? 0 : b);
} : "add" == b ? function add(a) {
return c.call(this, 0 === a ? 0 : a), this;
} : function set(a, b) {
return c.call(this, 0 === a ? 0 : a, b), this;
});
};
if ("function" == typeof b && (l || n.forEach && !e(function() {
(new b).entries().next();
}))) {
var u,
q = new b,
z = q[s](l ? {} : -0, 1) != q,
A = e(function() {
q.has(1);
}),
B = h(function(a) {
new b(a);
});
B || (b = v(function(e, d) {
j(e, b, o);
var c = new t;
return d != a && i(d, p, c[s], c), c;
}), b.prototype = n, n.constructor = b), l || q.forEach(function(b, a) {
u = 1 / a === -(1 / 0);
}), (A || u) && (r("delete"), r("has"), p && r("get")), (u || z) && r(s), l && n.clear && delete n.clear;
} else
b = x.getConstructor(v, o, p, s), f(b.prototype, y);
return m(b, o), w[o] = b, c(c.G + c.W + c.F * (b != t), w), l || x.setStrong(b, o, p), b;
};
}, function(d, e, b) {
var c = b(144);
b(145)("Set", function(b) {
return function Set() {
return b(this, arguments.length > 0 ? arguments[0] : a);
};
}, {add: function add(a) {
return c.def(this, a = 0 === a ? 0 : a, a);
}}, c);
}, function(n, m, b) {
var l = b(2),
k = b(15),
c = b(148),
d = b(9),
j = b(10),
i = c.frozenStore,
h = c.WEAK,
f = Object.isExtensible || d,
e = {},
g = b(145)("WeakMap", function(b) {
return function WeakMap() {
return b(this, arguments.length > 0 ? arguments[0] : a);
};
}, {
get: function get(a) {
if (d(a)) {
if (!f(a))
return i(this).get(a);
if (j(a, h))
return a[h][this._i];
}
},
set: function set(a, b) {
return c.def(this, a, b);
}
}, c, !0, !0);
7 != (new g).set((Object.freeze || Object)(e), 7).get(e) && l.each.call(["delete", "has", "get", "set"], function(a) {
var b = g.prototype,
c = b[a];
k(b, a, function(b, e) {
if (d(b) && !f(b)) {
var g = i(this)[a](b, e);
return "set" == a ? this : g;
}
return c.call(this, b, e);
});
});
}, function(s, t, c) {
var r = c(14),
n = c(142),
m = c(30),
l = c(137),
o = c(138),
j = c(18),
b = c(16)("weak"),
h = c(9),
d = c(10),
f = Object.isExtensible || h,
k = j(5),
p = j(6),
q = 0,
e = function(a) {
return a._l || (a._l = new i);
},
i = function() {
this.a = [];
},
g = function(a, b) {
return k(a.a, function(a) {
return a[0] === b;
});
};
i.prototype = {
get: function(b) {
var a = g(this, b);
return a ? a[1] : void 0;
},
has: function(a) {
return !!g(this, a);
},
set: function(a, b) {
var c = g(this, a);
c ? c[1] = b : this.a.push([a, b]);
},
"delete": function(b) {
var a = p(this.a, function(a) {
return a[0] === b;
});
return ~a && this.a.splice(a, 1), !!~a;
}
}, s.exports = {
getConstructor: function(g, i, j, k) {
var c = g(function(b, d) {
l(b, c, i), b._i = q++, b._l = a, d != a && o(d, j, b[k], b);
});
return n(c.prototype, {
"delete": function(a) {
return h(a) ? f(a) ? d(a, b) && d(a[b], this._i) && delete a[b][this._i] : e(this)["delete"](a) : !1;
},
has: function has(a) {
return h(a) ? f(a) ? d(a, b) && d(a[b], this._i) : e(this).has(a) : !1;
}
}), c;
},
def: function(c, a, g) {
return f(m(a)) ? (d(a, b) || r(a, b, {}), a[b][c._i] = g) : e(c).set(a, g), c;
},
frozenStore: e,
WEAK: b
};
}, function(d, e, b) {
var c = b(148);
b(145)("WeakSet", function(b) {
return function WeakSet() {
return b(this, arguments.length > 0 ? arguments[0] : a);
};
}, {add: function add(a) {
return c.def(this, a, !0);
}}, c, !1, !0);
}, function(d, e, b) {
var a = b(12),
c = Function.apply;
a(a.S, "Reflect", {apply: function apply(a, b, d) {
return c.call(a, b, d);
}});
}, function(i, j, b) {
var f = b(2),
c = b(12),
d = b(20),
g = b(30),
e = b(9),
h = Function.bind || b(13).Function.prototype.bind;
c(c.S + c.F * b(4)(function() {
function F() {}
return !(Reflect.construct(function() {}, [], F) instanceof F);
}), "Reflect", {construct: function construct(c, b) {
d(c);
var j = arguments.length < 3 ? c : d(arguments[2]);
if (c == j) {
if (b != a)
switch (g(b).length) {
case 0:
return new c;
case 1:
return new c(b[0]);
case 2:
return new c(b[0], b[1]);
case 3:
return new c(b[0], b[1], b[2]);
case 4:
return new c(b[0], b[1], b[2], b[3]);
}
var i = [null];
return i.push.apply(i, b), new (h.apply(c, i));
}
var k = j.prototype,
l = f.create(e(k) ? k : Object.prototype),
m = Function.apply.call(c, l, b);
return e(m) ? m : l;
}});
}, function(e, f, a) {
var c = a(2),
b = a(12),
d = a(30);
b(b.S + b.F * a(4)(function() {
Reflect.defineProperty(c.setDesc({}, 1, {value: 1}), 1, {value: 2});
}), "Reflect", {defineProperty: function defineProperty(a, b, e) {
d(a);
try {
return c.setDesc(a, b, e), !0;
} catch (f) {
return !1;
}
}});
}, function(e, f, a) {
var b = a(12),
c = a(2).getDesc,
d = a(30);
b(b.S, "Reflect", {deleteProperty: function deleteProperty(a, b) {
var e = c(d(a), b);
return e && !e.configurable ? !1 : delete a[b];
}});
}, function(f, g, b) {
var c = b(12),
e = b(30),
d = function(a) {
this._t = e(a), this._i = 0;
var b,
c = this._k = [];
for (b in a)
c.push(b);
};
b(110)(d, "Object", function() {
var c,
b = this,
d = b._k;
do
if (b._i >= d.length)
return {
value: a,
done: !0
};
while (!((c = d[b._i++]) in b._t));
return {
value: c,
done: !1
};
}), c(c.S, "Reflect", {enumerate: function enumerate(a) {
return new d(a);
}});
}, function(h, i, b) {
function get(b, h) {
var d,
j,
i = arguments.length < 3 ? b : arguments[2];
return g(b) === i ? b[h] : (d = c.getDesc(b, h)) ? e(d, "value") ? d.value : d.get !== a ? d.get.call(i) : a : f(j = c.getProto(b)) ? get(j, h, i) : void 0;
}
var c = b(2),
e = b(10),
d = b(12),
f = b(9),
g = b(30);
d(d.S, "Reflect", {get: get});
}, function(e, f, a) {
var c = a(2),
b = a(12),
d = a(30);
b(b.S, "Reflect", {getOwnPropertyDescriptor: function getOwnPropertyDescriptor(a, b) {
return c.getDesc(d(a), b);
}});
}, function(e, f, a) {
var b = a(12),
c = a(2).getProto,
d = a(30);
b(b.S, "Reflect", {getPrototypeOf: function getPrototypeOf(a) {
return c(d(a));
}});
}, function(c, d, b) {
var a = b(12);
a(a.S, "Reflect", {has: function has(a, b) {
return b in a;
}});
}, function(e, f, a) {
var b = a(12),
d = a(30),
c = Object.isExtensible;
b(b.S, "Reflect", {isExtensible: function isExtensible(a) {
return d(a), c ? c(a) : !0;
}});
}, function(c, d, a) {
var b = a(12);
b(b.S, "Reflect", {ownKeys: a(161)});
}, function(d, f, a) {
var b = a(2),
e = a(30),
c = a(7).Reflect;
d.exports = c && c.ownKeys || function ownKeys(a) {
var c = b.getNames(e(a)),
d = b.getSymbols;
return d ? c.concat(d(a)) : c;
};
}, function(e, f, a) {
var b = a(12),
d = a(30),
c = Object.preventExtensions;
b(b.S, "Reflect", {preventExtensions: function preventExtensions(a) {
d(a);
try {
return c && c(a), !0;
} catch (b) {
return !1;
}
}});
}, function(i, j, b) {
function set(j, i, k) {
var l,
m,
d = arguments.length < 4 ? j : arguments[3],
b = c.getDesc(h(j), i);
if (!b) {
if (f(m = c.getProto(j)))
return set(m, i, k, d);
b = e(0);
}
return g(b, "value") ? b.writable !== !1 && f(d) ? (l = c.getDesc(d, i) || e(0), l.value = k, c.setDesc(d, i, l), !0) : !1 : b.set === a ? !1 : (b.set.call(d, k), !0);
}
var c = b(2),
g = b(10),
d = b(12),
e = b(5),
h = b(30),
f = b(9);
d(d.S, "Reflect", {set: set});
}, function(d, e, b) {
var c = b(12),
a = b(45);
a && c(c.S, "Reflect", {setPrototypeOf: function setPrototypeOf(b, c) {
a.check(b, c);
try {
return a.set(b, c), !0;
} catch (d) {
return !1;
}
}});
}, function(e, f, b) {
var c = b(12),
d = b(33)(!0);
c(c.P, "Array", {includes: function includes(b) {
return d(this, b, arguments.length > 1 ? arguments[1] : a);
}}), b(118)("includes");
}, function(d, e, a) {
var b = a(12),
c = a(98)(!0);
b(b.P, "String", {at: function at(a) {
return c(this, a);
}});
}, function(e, f, b) {
var c = b(12),
d = b(168);
c(c.P, "String", {padLeft: function padLeft(b) {
return d(this, b, arguments.length > 1 ? arguments[1] : a, !0);
}});
}, function(c, g, b) {
var d = b(24),
e = b(105),
f = b(23);
c.exports = function(l, m, i, n) {
var c = String(f(l)),
j = c.length,
g = i === a ? " " : String(i),
k = d(m);
if (j >= k)
return c;
"" == g && (g = " ");
var h = k - j,
b = e.call(g, Math.ceil(h / g.length));
return b.length > h && (b = b.slice(0, h)), n ? b + c : c + b;
};
}, function(e, f, b) {
var c = b(12),
d = b(168);
c(c.P, "String", {padRight: function padRight(b) {
return d(this, b, arguments.length > 1 ? arguments[1] : a, !1);
}});
}, function(b, c, a) {
a(63)("trimLeft", function(a) {
return function trimLeft() {
return a(this, 1);
};
});
}, function(b, c, a) {
a(63)("trimRight", function(a) {
return function trimRight() {
return a(this, 2);
};
});
}, function(d, e, a) {
var b = a(12),
c = a(173)(/[\\^$*+?.()|[\]{}]/g, "\\$&");
b(b.S, "RegExp", {escape: function escape(a) {
return c(a);
}});
}, function(a, b) {
a.exports = function(b, a) {
var c = a === Object(a) ? function(b) {
return a[b];
} : a;
return function(a) {
return String(a).replace(b, c);
};
};
}, function(g, h, a) {
var b = a(2),
c = a(12),
d = a(161),
e = a(31),
f = a(5);
c(c.S, "Object", {getOwnPropertyDescriptors: function getOwnPropertyDescriptors(k) {
for (var a,
g,
h = e(k),
l = b.setDesc,
m = b.getDesc,
i = d(h),
c = {},
j = 0; i.length > j; )
g = m(h, a = i[j++]), a in c ? l(c, a, f(0, g)) : c[a] = g;
return c;
}});
}, function(d, e, a) {
var b = a(12),
c = a(176)(!1);
b(b.S, "Object", {values: function values(a) {
return c(a);
}});
}, function(c, f, a) {
var b = a(2),
d = a(31),
e = b.isEnum;
c.exports = function(a) {
return function(j) {
for (var c,
f = d(j),
g = b.getKeys(f),
k = g.length,
h = 0,
i = []; k > h; )
e.call(f, c = g[h++]) && i.push(a ? [c, f[c]] : f[c]);
return i;
};
};
}, function(d, e, a) {
var b = a(12),
c = a(176)(!0);
b(b.S, "Object", {entries: function entries(a) {
return c(a);
}});
}, function(c, d, a) {
var b = a(12);
b(b.P, "Map", {toJSON: a(179)("Map")});
}, function(b, e, a) {
var c = a(138),
d = a(47);
b.exports = function(a) {
return function toJSON() {
if (d(this) != a)
throw TypeError(a + "#toJSON isn't generic");
var b = [];
return c(this, !1, b.push, b), b;
};
};
}, function(c, d, a) {
var b = a(12);
b(b.P, "Set", {toJSON: a(179)("Set")});
}, function(d, e, b) {
var a = b(12),
c = b(141);
a(a.G + a.B, {
setImmediate: c.set,
clearImmediate: c.clear
});
}, function(l, k, a) {
a(117);
var h = a(7),
i = a(14),
c = a(109),
b = a(28)("iterator"),
d = h.NodeList,
e = h.HTMLCollection,
j = d && d.prototype,
g = e && e.prototype,
f = c.NodeList = c.HTMLCollection = c.Array;
!d || b in j || i(j, b, f), !e || b in g || i(g, b, f);
}, function(i, j, a) {
var c = a(7),
b = a(12),
g = a(17),
h = a(184),
d = c.navigator,
e = !!d && /MSIE .\./.test(d.userAgent),
f = function(a) {
return e ? function(b, c) {
return a(g(h, [].slice.call(arguments, 2), "function" == typeof b ? b : Function(b)), c);
} : a;
};
b(b.G + b.B + b.F * e, {
setTimeout: f(c.setTimeout),
setInterval: f(c.setInterval)
});
}, function(c, f, a) {
var d = a(185),
b = a(17),
e = a(20);
c.exports = function() {
for (var h = e(this),
a = arguments.length,
c = Array(a),
f = 0,
i = d._,
g = !1; a > f; )
(c[f] = arguments[f++]) === i && (g = !0);
return function() {
var d,
k = this,
f = arguments,
l = f.length,
e = 0,
j = 0;
if (!g && !l)
return b(h, c, k);
if (d = c.slice(), g)
for (; a > e; e++)
d[e] === i && (d[e] = f[j++]);
for (; l > j; )
d.push(f[j++]);
return b(h, d, k);
};
};
}, function(a, c, b) {
a.exports = b(7);
}, function(x, w, b) {
function Dict(b) {
var c = f.create(null);
return b != a && (r(b) ? q(b, !0, function(a, b) {
c[a] = b;
}) : o(c, b)), c;
}
function reduce(g, h, l) {
p(h);
var a,
c,
b = i(g),
e = k(b),
j = e.length,
f = 0;
if (arguments.length < 3) {
if (!j)
throw TypeError("Reduce of empty object with no initial value");
a = b[e[f++]];
} else
a = Object(l);
for (; j > f; )
d(b, c = e[f++]) && (a = h(a, b[c], c, g));
return a;
}
function includes(c, b) {
return (b == b ? j(c, b) : l(c, function(a) {
return a != a;
})) !== a;
}
function get(a, b) {
return d(a, b) ? a[b] : void 0;
}
function set(a, b, c) {
return v && b in Object ? f.setDesc(a, b, t(0, c)) : a[b] = c, a;
}
function isDict(a) {
return u(a) && f.getProto(a) === Dict.prototype;
}
var f = b(2),
n = b(19),
e = b(12),
t = b(5),
o = b(41),
j = b(36),
p = b(20),
q = b(138),
r = b(187),
s = b(110),
g = b(119),
u = b(9),
i = b(31),
v = b(3),
d = b(10),
k = f.getKeys,
c = function(b) {
var e = 1 == b,
c = 4 == b;
return function(l, m, o) {
var f,
h,
g,
p = n(m, o, 3),
k = i(l),
j = e || 7 == b || 2 == b ? new ("function" == typeof this ? this : Dict) : a;
for (f in k)
if (d(k, f) && (h = k[f], g = p(h, f, l), b))
if (e)
j[f] = g;
else if (g)
switch (b) {
case 2:
j[f] = h;
break;
case 3:
return !0;
case 5:
return h;
case 6:
return f;
case 7:
j[g[0]] = g[1];
}
else if (c)
return !1;
return 3 == b || c ? c : j;
};
},
l = c(6),
h = function(a) {
return function(b) {
return new m(b, a);
};
},
m = function(a, b) {
this._t = i(a), this._a = k(a), this._i = 0, this._k = b;
};
s(m, "Dict", function() {
var c,
b = this,
e = b._t,
f = b._a,
h = b._k;
do
if (b._i >= f.length)
return b._t = a, g(1);
while (!d(e, c = f[b._i++]));
return "keys" == h ? g(0, c) : "values" == h ? g(0, e[c]) : g(0, [c, e[c]]);
}), Dict.prototype = null, e(e.G + e.F, {Dict: Dict}), e(e.S, "Dict", {
keys: h("keys"),
values: h("values"),
entries: h("entries"),
forEach: c(0),
map: c(1),
filter: c(2),
some: c(3),
every: c(4),
find: c(5),
findKey: l,
mapPairs: c(7),
reduce: reduce,
keyOf: j,
includes: includes,
has: d,
get: get,
set: set,
isDict: isDict
});
}, function(b, f, a) {
var c = a(47),
d = a(28)("iterator"),
e = a(109);
b.exports = a(13).isIterable = function(b) {
var a = Object(b);
return d in a || "@@iterator" in a || e.hasOwnProperty(c(a));
};
}, function(b, e, a) {
var c = a(30),
d = a(114);
b.exports = a(13).getIterator = function(a) {
var b = d(a);
if ("function" != typeof b)
throw TypeError(a + " is not iterable!");
return c(b.call(a));
};
}, function(f, g, a) {
var c = a(7),
d = a(13),
b = a(12),
e = a(184);
b(b.G + b.F, {delay: function delay(a) {
return new (d.Promise || c.Promise)(function(b) {
setTimeout(e.call(b, !0), a);
});
}});
}, function(d, e, a) {
var c = a(185),
b = a(12);
a(13)._ = c._ = c._ || {}, b(b.P + b.F, "Function", {part: a(184)});
}, function(c, d, b) {
var a = b(12);
a(a.S + a.F, "Object", {isObject: b(9)});
}, function(c, d, b) {
var a = b(12);
a(a.S + a.F, "Object", {classof: b(47)});
}, function(d, e, b) {
var a = b(12),
c = b(194);
a(a.S + a.F, "Object", {define: c});
}, function(c, f, a) {
var b = a(2),
d = a(161),
e = a(31);
c.exports = function define(a, c) {
for (var f,
g = d(e(c)),
i = g.length,
h = 0; i > h; )
b.setDesc(a, f = g[h++], b.getDesc(c, f));
return a;
};
}, function(e, f, a) {
var b = a(12),
c = a(2).create,
d = a(194);
b(b.S + b.F, "Object", {make: function(a, b) {
return d(c(a), b);
}});
}, function(c, d, b) {
b(108)(Number, "Number", function(a) {
this._l = +a, this._i = 0;
}, function() {
var b = this._i++,
c = !(this._l > b);
return {
done: c,
value: c ? a : b
};
});
}, function(d, e, b) {
var a = b(12),
c = b(173)(/[&<>"']/g, {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
});
a(a.P + a.F, "String", {escapeHTML: function escapeHTML() {
return c(this);
}});
}, function(d, e, b) {
var a = b(12),
c = b(173)(/&(?:amp|lt|gt|quot|apos);/g, {
"&": "&",
"<": "<",
">": ">",
""": '"',
"'": "'"
});
a(a.P + a.F, "String", {unescapeHTML: function unescapeHTML() {
return c(this);
}});
}, function(g, h, a) {
var e = a(2),
f = a(7),
b = a(12),
c = {},
d = !0;
e.each.call("assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(","), function(a) {
c[a] = function() {
var b = f.console;
return d && b && b[a] ? Function.apply.call(b[a], b, arguments) : void 0;
};
}), b(b.G + b.F, {log: a(41)(c.log, c, {
enable: function() {
d = !0;
},
disable: function() {
d = !1;
}
})});
}, function(i, j, b) {
var g = b(2),
e = b(12),
h = b(19),
f = b(13).Array || Array,
c = {},
d = function(d, b) {
g.each.call(d.split(","), function(d) {
b == a && d in f ? c[d] = f[d] : d in [] && (c[d] = h(Function.call, [][d], b));
});
};
d("pop,reverse,shift,keys,values,entries", 1), d("indexOf,every,some,forEach,map,filter,find,findIndex,includes", 3), d("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill"), e(e.S, "Array", c);
}]), "undefined" != typeof module && module.exports ? module.exports = b : "function" == typeof define && define.amd ? define(function() {
return b;
}) : c.core = b;
}(1, 1);
})(require("process"));
| mit |
ashnewport/elasticsearch | kibana-5.0.2-linux-x86_64/src/core_plugins/timelion/public/directives/fullscreen/fullscreen.js | 548 | var _ = require('lodash');
var $ = require('jquery');
require('angularSortableView');
require('plugins/timelion/directives/chart/chart');
require('plugins/timelion/directives/timelion_grid');
var app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']);
var html = require('./fullscreen.html');
app.directive('timelionFullscreen', function () {
return {
restrict: 'E',
scope: {
expression: '=',
series: '=',
state: '=',
transient: '=',
onSearch: '=',
},
template: html
};
});
| mit |
SuvanL/delet | node_modules/komada/functions/runMessageMonitors.js | 287 | module.exports = (client, msg) => {
client.messageMonitors.forEach((monit) => {
if (monit.conf.enabled) {
if (monit.conf.ignoreBots && msg.author.bot) return;
if (monit.conf.ignoreSelf && client.user === msg.author) return;
monit.run(client, msg);
}
});
};
| mit |
arivera12/cbooks | templates/purity_iii/tpls/blocks/mainbody/one-sidebar-right.php | 897 | <?php
/**
* @package T3 Blank
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Mainbody 2 columns: content - sidebar
*/
?>
<div id="t3-mainbody" class="col-xs-12 t3-mainbody">
<div class="row">
<!-- MAIN CONTENT -->
<div id="t3-content" class="t3-content col-xs-12 col-sm-8 col-md-9">
<?php if($this->hasMessage()) : ?>
<jdoc:include type="message" />
<?php endif ?>
<jdoc:include type="component" />
</div>
<!-- //MAIN CONTENT -->
<!-- SIDEBAR RIGHT -->
<div class="t3-sidebar t3-sidebar-right col-xs-12 col-sm-4 col-md-3 <?php $this->_c($vars['sidebar']) ?>">
<jdoc:include type="modules" name="<?php $this->_p($vars['sidebar']) ?>" style="T3Xhtml" />
</div>
<!-- //SIDEBAR RIGHT -->
</div>
</div>
| mit |
edwardmeng/wheatech.ServiceModel | src/Windsor/ServiceBridge.Windsor.Interception/Properties/AssemblyInfo.cs | 172 | using System.Reflection;
[assembly: AssemblyTitle("ServiceBridge.Windsor.Interception")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
| mit |
Assembly-WebCrew/contentful-web | src/app/content-blocks/block-news/block-news.component.spec.ts | 1022 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BlockNewsComponent } from './block-news.component';
import { ContentfulService } from '../../core/contentful.service';
import { RouterTestingModule } from '@angular/router/testing';
describe('BlockNewsComponent', () => {
let component: BlockNewsComponent;
let fixture: ComponentFixture<BlockNewsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ BlockNewsComponent ],
providers: [
{
provide: ContentfulService,
useValue: { query: () => Promise.resolve({ data: { newsItems: []}}), getEvent: () => ({name: 'summer18'}) }
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BlockNewsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| mit |
npmcomponent/nbubna-Eventi | src/declare.js | 4091 | _.parsers.unshift([/=>(\w+)$/, function(event, handler, alias) {
handler.alias = alias;
if (handler !== event) {
handler.data = handler.data || [];
handler.data.push(alias);
}
}]);
if (document) {
_.init = function init() {
var nodes = document.querySelectorAll('[data-eventi]');
for (var i=0,m=nodes.length; i<m; i++) {
var target = nodes[i],
mapping = target.getAttribute('data-eventi');
if (mapping !== target.eventi) {
if (_.off && target.eventi) {
Eventi.off(target, target.eventi, _.declared);
}
target.eventi = mapping;
_.declare(target, mapping);
}
}
if (nodes.length || document.querySelectorAll('[click]').length) {
Eventi.on('click keyup', _.check);
}
};
_.declare = function(target, mapping) {// register listener
var texts = _.split.ter(mapping);
for (var i=0,m=texts.length; i<m; i++) {
Eventi.on(target, texts[i], _.declared);
}
};
_.declared = function(e, alias) {// lookup handlers
alias = typeof alias === "string" ? alias : e.type;
var nodes = _.declarers(this, alias, e.target);
for (var i=0,m=nodes.length; i<m; i++) {
_.respond(nodes[i], alias, e);
}
};
_.declarers = function(target, alias, node) {
var query = '['+alias+']',
// gather matching parents up to the target
nodes = [],
descendant = false;
while (node && node.matches) {
if (node.matches(query)) {
nodes.push(node);
}
if (node === target) {
descendant = true;
break;
}
node = node.parentNode;
}
// if node isn't a descendant of target, handler must be global
return descendant ? nodes : target.querySelectorAll(query);
};
_.respond = function(node, alias, e) {// execute handler
var response = node.getAttribute(alias);
if (response) {
var fn = _.resolve(response, node) || _.resolve(response);
if (typeof fn === "function") {
fn.call(node, e);
} else {
Eventi.fire(node, response, e);
}
}
};
_.check = function(e) {
var click = e.target.getAttribute &&
((e.type === 'click' && _.click(e.target)) ||
(e.keyCode === 13 && _.click(e.target, true)));
if (click) {
_.declared.call(document.documentElement, e, 'click');
if (click === 'noDefault' && !_.allowDefault(e.target)) {
e.preventDefault();
}
}
};
_.allowDefault = function(el) {
return el.type === 'radio' || el.type === 'checkbox';
};
_.click = function(el, enter) {
// click attributes with non-false value override everything
var click = el.getAttribute('click');
if (click && click !== "false") {
return 'noDefault';
}
// editables, select, textarea, non-button inputs all use click to alter focus w/o action
// textarea and editables use enter to add a new line w/o action
// a[href], buttons, button inputs all automatically dispatch 'click' on enter
// in all three situations, dev must declare on element, not on parent to avoid insanity
if (!el.isContentEditable) {
var name = el.nodeName.toLowerCase();
return name !== 'textarea' &&
(name !== 'select' || enter) &&
(enter ? (name !== 'a' || !el.getAttribute('href')) &&
name !== 'button' &&
(name !== 'input' || !_.buttonRE.test(el.type))
: name !== 'input' || _.buttonRE.test(el.type));
}
};
_.buttonRE = /^(submit|button|reset)$/;
Eventi.on('DOMContentLoaded', _.init);
}
| mit |
zedoul/AnomalyDetection | temp/data_loader.py | 616 | # -*- coding: utf-8 -*-
"""
http://www.astroml.org/sklearn_tutorial/dimensionality_reduction.html
"""
print (__doc__)
import cPickle as pickle
import nslkdd.preprocessing as preprocessing
if __name__ == '__main__':
import time
start = time.time()
datasize = 1000
print "preprocessing data..."
df, headers = preprocessing.get_preprocessed_data(datasize)
with open('df.pkl','wb') as output:
pickle.dump(df, output,-1)
with open('headers.pkl','wb') as output:
pickle.dump(headers, output,-1)
elapsed = (time.time() - start)
print "done in %s seconds" % (elapsed)
| mit |
mingyuchoo/mg-react | client/components/layout/Aside.js | 241 | import React, { Component, PropTypes } from 'react'
class Aside extends Component {
constructor(props) {
super(props)
}
render() {
return (
<aside>
<h3>Aside</h3>
</aside>
)
}
}
export default Aside
| mit |
ksakuntanak/buffohero_cms | fuel/app/views/help/index.php | 2597 | <?php if (count($helps)){ ?>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>หัวข้อช่วยเหลือ</th>
<th>หมวดหมู่</th>
<th>วันที่เขียน</th>
<th>สถานะ</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach ($helps as $item){ ?>
<tr>
<td><?php echo $item['id']; ?></td>
<td>
<?php echo $item['help_title_th']; ?><br>
<?php echo $item['help_title_en']; ?>
</td>
<td><?php echo $cats[$item['cat_id']]; ?></td>
<td><?php echo date('Y-m-d H:i:s',$item['created_at']); ?></td>
<td><?php echo $item['help_is_active']?"<i class=\"fa fa-check-circle color-green\"> </i> เผยแพร่":"<i class=\"fa fa-ban color-red\"> </i> ระงับ"; ?></td>
<td>
<?php echo Html::anchor('help/edit/' . $item['id'], '<i class="fa fa-wrench"></i> แก้ไขข้อมูล'); ?>
<?php echo Html::anchor('help/delete/' . $item['id'], '<i class="fa fa-trash-o"></i> ลบข้อมูล', array('onclick' => "return confirm('Help #".$item['id']." will be deleted. Continue?')")); ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<p>ยังไม่มีหัวข้อช่วยเหลือในระบบ</p>
<?php } ?>
<div class="clearfix">
<?php echo html_entity_decode($pagination); ?>
</div>
<?php echo Html::anchor('help/create', '<i class="fa fa-plus"></i> เพิ่มหัวข้อช่วยเหลือใหม่', array('class' => 'btn btn-success')); ?>
<script type="text/javascript">
var page = <?php echo $page; ?>;
var totalPage = <?php echo $total_page; ?>;
function toPage(next){
window.location.href = "<?php echo Uri::create('help'); ?>/?page="+next;
}
function firstPage(){
toPage(1);
}
function prevPage(){
var next = page - 1;
if(next < 1) next = 1;
toPage(next);
}
function nextPage(){
var next = page + 1;
if(next > totalPage) next = totalPage;
toPage(next);
}
function lastPage(){
toPage(totalPage);
}
</script>
| mit |
travco/postcss-secmodify | index.js | 3744 | 'use strict';
var postcss = require('postcss');
// /*DEBUG*/ var appendout = require('fs').appendFileSync;
module.exports = postcss.plugin('postcss-secmodify', function secModify(SMI) {
return function(css, result) {
//Nothing to replace with? Bug out!
if (!SMI.hasOwnProperty('rString')) {
result.warn('\'rString\', the value that will be used during a replace is undefined, make sure you pass an object with the \'rString\' keyvalue into secModify');
return;
} else if (typeof SMI.rString !== 'string' && typeof SMI.rString !== 'function') {
result.warn('\'rString\', the value that will be used during a replace is not a string or a function, make sure you give \'rString\' a string when passing it in.');
return;
}
// /*DEBUG*/ appendout('./test/debugout.txt', '\n----------------------------------------');
['sel', 'dec', 'decVal', 'atRule', 'media', 'selInMedia', 'decInMedia', 'decValInMedia', 'atRuleInMedia'].forEach(function(filter) {
if (!SMI.hasOwnProperty(filter)) {
return;
} else if (typeof SMI[filter] === 'undefined') {
return;
}
if (filter.indexOf('sel') !== -1) {
css.walkRules(function(targetNode) {
secReplace(targetNode, filter, 'selector');
});
}else if (filter.indexOf('dec') !== -1) {
var key = 'prop';
if (filter.indexOf('Val') !== -1) {
key = 'value';
}
css.walkDecls(function(targetNode) {
secReplace(targetNode, filter, key);
});
}else if (filter.indexOf('atRule') !== -1) {
css.walkAtRules(function(targetNode) {
secReplace(targetNode, filter, 'params');
});
}else if (filter === 'media') {
css.walkAtRules(function(targetNode) {
if (targetNode.name !== 'media') {
return;
}
var str = targetNode.params;
//Bailout for a bad node[key] or a non-target
if (str === '' || typeof str === 'undefined') {
return;
}
// // /*DEBUG*/ appendout('./test/debugout.txt', '\n\nRunning with SMI[' + filter + '], which contains:\n' + SMI[filter] + '\nwith key: params, and str: ' + str);
if (SMI[filter].constructor === Array) {
SMI[filter].forEach(function(rExpression) {
str = str.replace(rExpression, SMI.rString);
});
} else {
str = str.replace(SMI[filter], SMI.rString);
}
targetNode.params = str;
});
}
});
function secReplace(node, filter, key) {
var mediaOnly = (filter.indexOf('InMedia') !== -1);
var str = '';
if (mediaOnly && hasMediaAncestor(node)) {
str = node[key];
} else if (!mediaOnly && !hasMediaAncestor(node)) {
str = node[key];
}
//Bailout for a bad node[key] or a non-target
if (str === '' || typeof str === 'undefined') {
return;
}
// /*DEBUG*/ appendout('./test/debugout.txt', '\n\nRunning with SMI[' + filter + '], which contains:\n' + SMI[filter] + '\nwith key: ' + key + ', and str: ' + str);
if (SMI[filter].constructor === Array) {
SMI[filter].forEach(function(matcher) {
str = str.replace(matcher, SMI.rString);
});
} else {
str = str.replace(SMI[filter], SMI.rString);
}
node[key] = str;
}
function hasMediaAncestor(node) {
var parent = node.parent;
if (parent === undefined) {
return false;
}
if (parent.type === 'atrule' && parent.name === 'media') {
return true;
}
if (parent.type !== 'root') {
return hasMediaAncestor(parent);
}
}
};
});
| mit |
rodislav/Mister_JavaBean_Lessons | src/junior/calculator/App.java | 1924 | package junior.calculator;
public class App {
// let's create a application that behaves like a real one
// let's see what parts do we have in real app
// 1. the app itself (App.java)
// 2. display of the result or messages
// 3. the input or the keypad
// 4. the calculation unit, that does the calculation
// we are going to create a console app, which looks different, but behaves
// exactly like a normal one
static Input input = new Input();
public static void main(String[] args) throws Exception {
// we have as well the display, let's use it here
// since the functions are static, we can call the directly
// without creating a instance!
Display.showWelcomMessage();
// let's see what is the first step in real life calculator
// 1st one is to ask for first operand!
// this function does not exist, but we can create it!
Display.askFirstOperand();
// next we have to wait for user's input!
// so we need to give a way to do it
// let's create the input
int operand1 = input.getOperand1();
// next step is to ask for operation
Display.askOperation();
String operation = input.getOperation();
Display.askSecondOperand();
int operand2 = input.getOperand2();
// now we need to calculate the result and display it
// let's create the calculation unit
CalculationUnit calculationUnit = new CalculationUnit();
// since the function could throw an exception, we have to do something about it
// we have to explicitly declare that we are expecting one at application level
// or catch it here, for now we'll declare it at this App's level
int result = calculationUnit.calculate(operand1, operation, operand2);
Display.showResult(result);
Display.showBye();
}
}
| mit |
wbyoung/yahoo-finance-stream | test/stream_tests.js | 8579 | 'use strict';
var _ = require('lodash');
var chai = require('chai');
var expect = chai.expect;
var util = require('util');
var Stream = require('..');
var sinon = require('sinon');
chai.use(require('sinon-chai'));
// fake endpoint app
var app = require('./fakes/endpoint'), server;
var port = 23493;
var endpoint = util.format('http://localhost:%d', port);
describe('stream', function() {
before(function(done) { server = app.listen(port, done); });
after(function(done) { server.close(done); });
beforeEach(function() { app.reset(); });
it('can be created without new', function() {
expect(Stream({ endpoint: endpoint })).to.be.an.instanceof(Stream);
});
it('connects to api endpoint', function(done) {
var stocks = new Stream({ endpoint: endpoint });
stocks.watch('vti');
stocks.on('data', function() {
expect(app.requests.length).to.eql(1);
stocks.close();
});
stocks.on('error', done);
stocks.on('end', done);
});
it('does not connect to api endpoint if not watching any stocks', function(done) {
var stocks = new Stream({ endpoint: endpoint });
stocks.on('data', function() {
done(new Error('No data should have been retrieved'));
});
setTimeout(function() {
expect(app.requests.length).to.eql(0);
stocks.close();
}, 10);
stocks.on('error', done);
stocks.on('end', done);
});
it('connects to api endpoint only once stock is added', function(done) {
var stocks = new Stream({ endpoint: endpoint });
stocks.on('data', function() {
expect(app.requests.length).to.eql(1);
stocks.close();
});
setTimeout(function() {
expect(app.requests.length).to.eql(0);
stocks.watch('vti');
}, 10);
stocks.on('error', done);
stocks.on('end', done);
});
it('accepts a frequency setting', function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
stocks.watch('vti');
stocks.on('data', function() {
if (app.requests.length == 4) {
stocks.close();
}
});
stocks.on('error', done);
stocks.on('end', done);
});
it('emits pending data after close', function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
var spy = sinon.spy();
stocks.watch('vti');
stocks.resume();
app.on('req', function() {
stocks.close();
expect(spy).to.not.have.been.called;
});
stocks.on('data', spy);
stocks.on('error', done);
stocks.on('end', function() {
expect(spy).to.have.been.called;
done();
});
});
it('allows pause & resume', function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
stocks.watch('vti');
stocks.once('data', function() {
expect(app.requests.length).to.eql(1);
});
stocks.pause();
setTimeout(function() {
expect(app.requests.length).to.eql(1);
stocks.resume();
}, 20);
app.on('req', function() {
if (app.requests.length === 4) {
stocks.close();
}
});
stocks.on('error', done);
stocks.on('end', done);
});
it('can be closed immediately', function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
stocks.close();
stocks.resume(); // must be flowing
stocks.on('error', done);
stocks.on('end', function() {
expect(app.requests.length).to.eql(0);
done();
});
});
it('can be closed immediately after watching a stock', function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
stocks.watch('vti');
stocks.close();
stocks.resume(); // must be flowing
stocks.on('error', done);
stocks.on('end', function() {
expect(app.requests.length).to.eql(0);
done();
});
});
it('emits errors for connection problems', function(done) {
var stocks = new Stream({ endpoint: 'http://localhost:39232' });
stocks.watch('vti');
stocks.resume();
stocks.on('error', function(e) {
expect(e).to.exist;
done();
});
stocks.on('end', function() {
done(new Error('Expected error to occur.'));
});
});
it('builds url for a single stock', function() {
var stocks = new Stream({ endpoint: endpoint });
var query = 'select%20*%20' +
'from%20yahoo.finance.quotes%20' +
'where%20symbol%20in%20(%22VTI%22)';
var env = 'store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
var url = endpoint +
'?q=' + query +
'&format=json' +
'&env=' + env +
'&callback=';
stocks.watch('vti');
expect(stocks._url()).to.eql(url);
});
it('builds url for multiple stocks', function() {
var stocks = new Stream({ endpoint: endpoint });
var query = 'select%20*%20' +
'from%20yahoo.finance.quotes%20' +
'where%20symbol%20in%20(%22VTI%22%2C%22VXUS%22)';
var env = 'store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
var url = endpoint +
'?q=' + query +
'&format=json' +
'&env=' + env +
'&callback=';
stocks.watch('vti');
stocks.watch('vxus');
expect(stocks._url()).to.eql(url);
});
describe('when getting a single stock', function() {
before(function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
var quotes = this.quotes = [];
stocks.watch('vti');
stocks.on('data', function(quote) {
quotes.push(quote);
if (quotes.length === 3) {
stocks.close();
}
});
stocks.on('error', done);
stocks.on('end', done);
});
it('has the proper symbol', function() {
expect(this.quotes[0].symbol).to.eql('VTI');
});
it('continues to send the same symbol', function() {
expect(this.quotes[1].symbol).to.eql('VTI');
});
it('standardizes the quote object', function() {
expect(this.quotes[0].yearHigh).to.eql(110.09);
expect(this.quotes[0].percentChange).to.be.closeTo(0.0007, 0.000001);
});
it('stores original quote object', function() {
expect(this.quotes[0]._quote['YearHigh']).to.eql('110.09');
});
});
describe('when getting a multiple stocks', function() {
before(function(done) {
var stocks = new Stream({ endpoint: endpoint, frequency: 1 });
var quotes = this.quotes = [];
stocks.watch('vti');
stocks.watch('vxus');
stocks.on('data', function(quote) {
quotes.push(quote);
if (quotes.length === 4) {
stocks.close();
}
});
stocks.on('error', done);
stocks.on('end', done);
});
it('has the proper symbols', function() {
expect(_.map(this.quotes.slice(0, 2), 'symbol'))
.to.eql(['VTI', 'VXUS']);
});
it('has the proper symbols', function() {
expect(_.map(this.quotes.slice(2, 4), 'symbol'))
.to.eql(['VTI', 'VXUS']);
});
});
it('does not make more requests than required', function(done) {
var stocks = new Stream({ endpoint: endpoint });
stocks.watch('vti');
stocks.on('data', function() {
expect(app.requests.length).to.eql(1);
});
setTimeout(stocks.close.bind(stocks), 10);
stocks.on('error', done);
stocks.on('end', done);
});
it('queues an immediate request for newly added symbols', function(done) {
// we add VTI, and a quote will be scheduled to come in immediately.
var stocks = new Stream({ endpoint: endpoint });
stocks.watch('vti');
// we add VXUS, but not right away. instead, we add it midway through the
// handling of the request for VTI.
app.on('req', function() {
if (app.requests.length === 1) {
stocks.watch('vxus');
}
});
// we expect that even though the polling frequency is at 60 seconds,
// that the late addition of the VXUS will queue up another request right
// after the initial request completes.
stocks.on('data', function() {
if (app.requests.length === 2) {
// once all requests we expect are in, we delay just a bit on closing
// the stream to ensure that we're back to the same 60 second polling
// schedule and no more requests come in.
setTimeout(stocks.close.bind(stocks), 10);
}
});
stocks.on('error', done);
stocks.on('end', function() {
expect(app.requests.length).to.eql(2);
done();
});
});
it('throws an error when run in an invalid state', function() {
var stocks = new Stream({ endpoint: endpoint });
expect(stocks._run.bind(stocks)).to.throw(/cannot run/i);
});
});
| mit |
Remuv/corto_connectors | mongo/driver/cxx/mongocxx/src/options/update.cpp | 1416 | // Copyright 2014 MongoDB Inc.
//
// 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.
#include <mongocxx/options/update.hpp>
#include <mongocxx/config/private/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
namespace options {
void update::upsert(bool upsert) {
_upsert = upsert;
}
void update::bypass_document_validation(bool bypass_document_validation) {
_bypass_document_validation = bypass_document_validation;
}
void update::write_concern(class write_concern wc) {
_write_concern = std::move(wc);
}
const stdx::optional<bool>& update::upsert() const {
return _upsert;
}
const stdx::optional<bool>& update::bypass_document_validation() const {
return _bypass_document_validation;
}
const stdx::optional<class write_concern>& update::write_concern() const {
return _write_concern;
}
} // namespace options
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
| mit |
mustaphakd/brazza-ville | source/brzframe/package.js | 79 | enyo.depends(
"parts",
//"scriptloader.js",
"externlibs",
"brazzaApp.js"
); | mit |
jdt/ambushift | Build/Puppet/dev/modules/composer/lib/puppet/parser/functions/create_config_hash.rb | 1291 | def create_hash(value, user, ensure_entry, entry, home_dir)
hash = {
:user => user,
:ensure => ensure_entry,
:entry => entry
}
unless value.nil?
hash[:value] = value
end
unless home_dir.empty?
hash[:custom_home_dir] = home_dir
end
hash
end
module Puppet::Parser::Functions
newfunction(:create_config_hash, :type => :rvalue) do |args|
configs = args[0]
user = args[1].to_s
ensure_entry = args[2].to_s
hash = {}
home_dir = args[3].nil? ? '' : args[3].to_s
if configs.is_a? Hash
configs.each do |entry, value|
if value.is_a? Hash
value.each do |key, value|
value = value.join ' ' if value.is_a? Array
cnf_entry = "'#{entry}'.'#{key}'"
hash["#{cnf_entry}-#{user}-create"] = create_hash value, user, ensure_entry, cnf_entry, home_dir
end
else
if value.is_a? Array
value = value.join ' '
end
hash["#{entry}-#{user}-create"] = create_hash value, user, ensure_entry, entry, home_dir
end
end
else
configs.each do |value|
hash["#{value}-#{user}-remove"] = create_hash nil, user, 'absent', value, home_dir
end
end
return hash
end
end
| mit |
dpenkova/Simple-Project-Management | SimpleProjectManagement/SPM.Web/Controllers/AccountController.cs | 17355 | namespace SPM.Web.Controllers
{
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using SPM.Models;
using SPM.Web.ViewModels.Account;
[Authorize]
public class AccountController : Controller
{
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
}
public ApplicationUserManager UserManager
{
get
{
return this._userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
this._userManager = value;
}
}
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return this.View();
}
private ApplicationSignInManager _signInManager;
public ApplicationSignInManager SignInManager
{
get
{
return this._signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { this._signInManager = value; }
}
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return this.View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await this.SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.RequiresVerification:
return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return this.View(model);
}
}
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await this.SignInManager.HasBeenVerifiedAsync())
{
return this.View("Error");
}
var user = await this.UserManager.FindByIdAsync(await this.SignInManager.GetVerifiedUserIdAsync());
if (user != null)
{
var code = await this.UserManager.GenerateTwoFactorTokenAsync(user.Id, provider);
}
return this.View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return this.View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await this.SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return this.View(model);
}
}
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return this.View();
}
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName };
var result = await this.UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return this.RedirectToAction("Index", "Home");
}
this.AddErrors(result);
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return this.View("Error");
}
var result = await this.UserManager.ConfirmEmailAsync(userId, code);
return this.View(result.Succeeded ? "ConfirmEmail" : "Error");
}
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return this.View();
}
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await this.UserManager.FindByNameAsync(model.Email);
if (user == null || !(await this.UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return this.View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return this.View();
}
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? this.View("Error") : this.View();
}
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return this.View(model);
}
var user = await this.UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return this.RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await this.UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return this.RedirectToAction("ResetPasswordConfirmation", "Account");
}
this.AddErrors(result);
return this.View();
}
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return this.View();
}
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await this.SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return this.View("Error");
}
var userFactors = await this.UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return this.View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return this.View();
}
// Generate the token and send it
if (!await this.SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return this.View("Error");
}
return this.RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await this.AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return this.RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await this.SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return this.RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return this.View("Lockout");
case SignInStatus.RequiresVerification:
return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return this.View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return this.RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await this.AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return this.View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await this.UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await this.UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return this.RedirectToLocal(returnUrl);
}
}
this.AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return this.View(model);
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
this.AuthenticationManager.SignOut();
return this.RedirectToAction("Index", "Home");
}
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return this.View();
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
this.LoginProvider = provider;
this.RedirectUri = redirectUri;
this.UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (this.UserId != null)
{
properties.Dictionary[XsrfKey] = this.UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, this.LoginProvider);
}
}
#endregion
}
} | mit |
NetOfficeFw/NetOffice | Source/PowerPoint/DispatchInterfaces/FileDialogExtension.cs | 5084 | using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.PowerPointApi
{
/// <summary>
/// DispatchInterface FileDialogExtension
/// SupportByVersion PowerPoint, 9
/// </summary>
[SupportByVersion("PowerPoint", 9)]
[EntityType(EntityType.IsDispatchInterface)]
public class FileDialogExtension : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(FileDialogExtension);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public FileDialogExtension(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public FileDialogExtension(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public FileDialogExtension(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get
/// </summary>
[SupportByVersion("PowerPoint", 9)]
public NetOffice.PowerPointApi.Application Application
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.Application>(this, "Application", NetOffice.PowerPointApi.Application.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("PowerPoint", 9), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersion("PowerPoint", 9)]
public string Extensions
{
get
{
return Factory.ExecuteStringPropertyGet(this, "Extensions");
}
set
{
Factory.ExecuteValuePropertySet(this, "Extensions", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 9
/// Get/Set
/// </summary>
[SupportByVersion("PowerPoint", 9)]
public string Description
{
get
{
return Factory.ExecuteStringPropertyGet(this, "Description");
}
set
{
Factory.ExecuteValuePropertySet(this, "Description", value);
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| mit |
wccrawford/LD27 | Assets/Scripts/LockCursor.cs | 342 | using UnityEngine;
using System.Collections;
public class LockCursor : MonoBehaviour {
void Start() {
Screen.lockCursor = true;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown("escape")) {
Screen.lockCursor = false;
}
if(Input.GetMouseButtonDown(0)) {
Screen.lockCursor = true;
}
}
}
| mit |
java-hz/datacollector | src/in/foobars/datacollector/helpers/SharedPreferenceHelper.java | 3201 | package in.foobars.datacollector.helpers;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by harsh on 27/10/17.
*/
public class SharedPreferenceHelper {
private final static String PREF_FILE = "IGNITE";
/**
* Set a string shared preference
*
* @param key - Key to set shared preference
* @param value - Value for the key
*/
public static void setSharedPreferenceString(Context context, String key, String value) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.apply();
}
/**
* Set a integer shared preference
*
* @param key - Key to set shared preference
* @param value - Value for the key
*/
public static void setSharedPreferenceInt(Context context, String key, int value) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.apply();
}
/**
* Set a Boolean shared preference
*
* @param key - Key to set shared preference
* @param value - Value for the key
*/
public static void setSharedPreferenceBoolean(Context context, String key, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.apply();
}
/**
* Get a string shared preference
*
* @param key - Key to look up in shared preferences.
* @param defValue - Default value to be returned if shared preference isn't found.
* @return value - String containing value of the shared preference if found.
*/
public static String getSharedPreferenceString(Context context, String key, String defValue) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
return settings.getString(key, defValue);
}
/**
* Get a integer shared preference
*
* @param key - Key to look up in shared preferences.
* @param defValue - Default value to be returned if shared preference isn't found.
* @return value - String containing value of the shared preference if found.
*/
public static int getSharedPreferenceInt(Context context, String key, int defValue) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
return settings.getInt(key, defValue);
}
/**
* Get a boolean shared preference
*
* @param key - Key to look up in shared preferences.
* @param defValue - Default value to be returned if shared preference isn't found.
* @return value - String containing value of the shared preference if found.
*/
public static boolean getSharedPreferenceBoolean(Context context, String key, boolean defValue) {
SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
return settings.getBoolean(key, defValue);
}
} | mit |
minhjemmesiden/Wakfusharp | Utilities/Crypto/RSA.cs | 4726 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace WakSharp.Utilities.Crypto
{
public class RSA
{
public class RSAProvider
{
private RSACryptoServiceProvider _rsa { get; set; }
public RSAProvider(int lenght)
{
CspParameters csp = new CspParameters()
{
ProviderType = 1,
KeyNumber = 1
};
this._rsa = new RSACryptoServiceProvider(lenght, csp);
this._rsa.PersistKeyInCsp = true;
}
public RSAProvider(string value)
{
CspParameters csp = new CspParameters()
{
ProviderType = 1,
KeyNumber = 1
};
this._rsa = new RSACryptoServiceProvider(csp);
this._rsa.FromXmlString(this.ImportKeyFromXml(value));
this._rsa.PersistKeyInCsp = true;
}
public byte[] Encrypt(byte[] DataToEncrypt, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(this._rsa.ExportParameters(false));
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch
{
return null;
}
}
public byte[] Decrypt(byte[] DataToDecrypt, bool DoOAEPPadding)
{
try
{
byte[] decryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(this._rsa.ExportParameters(true));
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch
{
return null;
}
}
public byte[] GetKey()
{
return this._rsa.ExportCspBlob(false);
}
public void ExportKeyToXml(string path)
{
try
{
var writer = new StreamWriter(path);
writer.Write(this._rsa.ToXmlString(true));
writer.Close();
}
catch { }
}
public byte[] ExportToX509()
{
try
{
return AsnKeyBuilder.PublicKeyToX509(this._rsa.ExportParameters(false)).GetBytes();
}
catch
{
return null;
}
}
public string ImportKeyFromXml(string path)
{
try
{
var key = ("");
var reader = new StreamReader(path);
key = reader.ReadToEnd();
reader.Close();
return key;
}
catch { return ""; }
}
public RSACryptoServiceProvider GetProvider
{
get
{
return this._rsa;
}
}
}
}
}
| mit |
lafayette/JBTT | application/app/tracker/util/bbcode/codes/H6.java | 315 | package tracker.util.bbcode.codes;
import tracker.util.bbcode.AbstractCode;
public class H6 extends AbstractCode {
public String[] getTagNames() {
return new String[] { "h6" };
}
public String getOpenTagHtml(String attribute) {
return "<h6>";
}
public String getCloseTagHtml() {
return "</h6>";
}
}
| mit |
akkirilov/SoftUniProject | 07_OOP_Advanced/08_EnumerationsAndAnnotations_ex/src/p10_InfernoInfinity/entities/WeaponBase.java | 3133 | package p10_InfernoInfinity.entities;
import p10_InfernoInfinity.enums.Gem;
public abstract class WeaponBase implements Weapon, Comparable<Weapon> {
private String name;
private int minDamage;
private int maxDamage;
private int numberOfSockets;
private Gem[] gems;
private int strengthBonus;
private int agilityBonus;
private int vitalityBonus;
public WeaponBase(String name, int minDamage, int maxDamage, int numberOfSockets) {
super();
this.name = name;
this.minDamage = minDamage;
this.maxDamage = maxDamage;
this.numberOfSockets = numberOfSockets;
this.gems = new Gem[numberOfSockets];
this.strengthBonus = 0;
this.agilityBonus = 0;
this.vitalityBonus = 0;
}
@Override
public double getWeaponLevel() {
return ((this.minDamage + this.maxDamage) / 2.0)
+ this.strengthBonus
+ this.agilityBonus
+ this.vitalityBonus;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getNumberOfSockets() {
return this.numberOfSockets;
}
@Override
public void addGem(int socketIndex, Gem gem) {
if (this.gems[socketIndex] != null) {
this.removeGem(socketIndex);
}
if (gem.equals(this.gems[socketIndex])) {
return;
}
this.gems[socketIndex] = gem;
this.strengthBonus += gem.getStrength();
this.agilityBonus += gem.getAgility();
this.vitalityBonus += gem.getVitality();
for (int i = 0; i < gem.getStrength(); i++) {
this.minDamage += 2;
this.maxDamage += 3;
}
for (int i = 0; i < gem.getAgility(); i++) {
this.minDamage += 1;
this.maxDamage += 4;
}
}
@Override
public void removeGem(int socketIndex) {
if (this.gems[socketIndex] == null) {
return;
}
Gem gem = this.gems[socketIndex];
this.gems[socketIndex] = null;
this.strengthBonus -= gem.getStrength();
this.agilityBonus -= gem.getAgility();
this.vitalityBonus -= gem.getVitality();
for (int i = 0; i < gem.getStrength(); i++) {
this.minDamage -= 2;
this.maxDamage -= 3;
}
for (int i = 0; i < gem.getAgility(); i++) {
this.minDamage -= 1;
this.maxDamage -= 4;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WeaponBase other = (WeaponBase) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String additionalPrint() {
return String.format("%s (Item Level: %.1f)", this.toString(), this.getWeaponLevel()) ;
}
@Override
public String toString() {
return String.format("%s: %d-%d Damage, +%d Strength, +%d Agility, +%d Vitality",
this.getName(),
this.minDamage,
this.maxDamage,
this.strengthBonus,
this.agilityBonus,
this.vitalityBonus);
}
@Override
public int compareTo(Weapon weapon) {
return Double.compare(weapon.getWeaponLevel(), this.getWeaponLevel());
}
}
| mit |
NERDDISCO/VisionLord | src/reducers/app.js | 786 | import {
UPDATE_PAGE,
UPDATE_OFFLINE,
OPEN_SNACKBAR,
CLOSE_SNACKBAR,
UPDATE_DRAWER_STATE
} from '../actions/app.js'
const app = (state = {drawerOpened: false}, action) => {
switch (action.type) {
case UPDATE_PAGE:
return {
...state,
page: action.page,
entityId: action.entityId
}
case UPDATE_OFFLINE:
return {
...state,
offline: action.offline
}
case UPDATE_DRAWER_STATE:
return {
...state,
drawerOpened: action.opened
}
case OPEN_SNACKBAR:
return {
...state,
snackbarOpened: true
}
case CLOSE_SNACKBAR:
return {
...state,
snackbarOpened: false
}
default:
return state
}
}
export default app
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/xlsx/0.7.9/xlsx.js | 131 | version https://git-lfs.github.com/spec/v1
oid sha256:34301ad983ebd397d86268a18727b768142d019126e2af62a6e9293823180b4e
size 197717
| mit |
gabornemeth/StravaSharp | src/Samples/Sample.Core/ViewModels/MainViewModel.cs | 1998 | using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using StravaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
namespace Sample.ViewModels
{
public class MainViewModel : ViewModelBase
{
Client _client;
public MainViewModel(Client client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
public bool IsAuthenticated { get; protected set; }
public IList<ActivityViewModel> Activities { get; } = new ObservableCollection<ActivityViewModel>();
public async Task GetActivitiesAsync()
{
Status = "requesting Activities...";
var activities = await _client.Activities.GetAthleteActivities();
foreach (var activity in activities)
{
Activities.Add(new ActivityViewModel(activity));
}
if (activities.Any())
{
Status = $"retrieved {activities.Count} activities from Strava";
}
else
{
Status = "Could not retrieve any activities";
}
}
private RelayCommand _getActivitiesCommand;
public RelayCommand GetActivitiesCommand
{
get
{
return _getActivitiesCommand ?? (_getActivitiesCommand = new RelayCommand(async () => await GetActivitiesAsync()));
}
}
private string _status = string.Empty;
/// <summary>
/// Sets and gets the Status property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string Status
{
get => _status;
set
{
Set(()=>Status, ref _status, value);
}
}
}
}
| mit |
josetonyp/erems | spec/spec_helper.rb | 611 | require 'simplecov'
require 'pry'
module SimpleCov::Configuration
def clean_filters
@filters = []
end
end
SimpleCov.configure do
clean_filters
load_adapter 'test_frameworks'
end
ENV["COVERAGE"] && SimpleCov.start do
add_filter "/.rvm/"
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'erems'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
RSpec.configure do |config|
end
| mit |
sebastianjonasson/svdfeed | webroot/test.php | 711 | <?php
/*
*
* Include config
*/
require __DIR__.'/config.php';
/*
*
* Initialize frontcontroller intances
*/
$di = new \Anax\DI\CDIFactoryDefault();
$app = new \Anax\Kernel\CAnax($di);
/*
*
* Theme configuration
*/
$app->theme->configure(ANAX_APP_PATH . 'config/theme.php');
/*
*
* Main route
*/
$app->router->add('', function() use ($app) {
$query = $app->request->getPost('search');
$feed = new \cbass\SvdFeed\CSvdFeed();
$content = $feed->getNewsFeed($query);
$app->views->add('feed/feed', ['articles' => $content['articles'], 'meta' => $content['meta']], 'main');
});
/*
*
* Handle routes
*/
$app->router->handle();
/*
*
* Render theme
*/
$app->theme->render();
| mit |
ganlanshu0211/captcha | src/Handlers/SetHandler.php | 1749 | <?php
/**
* This file is part of Notadd.
*
* @author TwilRoad <[email protected]>
* @copyright (c) 2017, iBenchu.org
* @datetime 2017-02-23 19:45
*/
namespace Notadd\Captcha\Handlers;
use Illuminate\Container\Container;
use Notadd\Foundation\Passport\Abstracts\SetHandler as AbstractSetHandler;
use Notadd\Foundation\Setting\Contracts\SettingsRepository;
/**
* Class ConfigurationHandler.
*/
class SetHandler extends AbstractSetHandler
{
/**
* @var \Notadd\Foundation\Setting\Contracts\SettingsRepository
*/
protected $settings;
/**
* SetHandler constructor.
*
* @param \Illuminate\Container\Container $container
* @param \Notadd\Foundation\Setting\Contracts\SettingsRepository $settings
*/
public function __construct(
Container $container,
SettingsRepository $settings
) {
parent::__construct($container);
$this->messages->push($this->translator->trans('Captcha::setting.success'));
$this->settings = $settings;
}
/**
* Data for handler.
*
* @return array
*/
public function data()
{
return $this->settings->all()->toArray();
}
/**
* Execute Handler.
*
* @return bool
*/
public function execute()
{
$this->settings->set('captcha.enabled', $this->request->input('enabled'));
$this->settings->set('captcha.length', $this->request->input('length'));
$this->settings->set('captcha.width', $this->request->input('width'));
$this->settings->set('captcha.height', $this->request->input('height'));
$this->settings->set('captcha.quality', $this->request->input('quality'));
return true;
}
}
| mit |
sarunint/angular | packages/compiler-cli/ngcc/test/rendering/renderer_spec.ts | 20881 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import MagicString from 'magic-string';
import * as ts from 'typescript';
import {fromObject, generateMapFileComment, SourceMapConverter} from 'convert-source-map';
import {absoluteFrom, getFileSystem} from '../../../src/ngtsc/file_system';
import {TestFile, runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {loadTestFiles} from '../../../test/helpers';
import {Import, ImportManager} from '../../../src/ngtsc/translator';
import {DecorationAnalyzer} from '../../src/analysis/decoration_analyzer';
import {CompiledClass} from '../../src/analysis/types';
import {NgccReferencesRegistry} from '../../src/analysis/ngcc_references_registry';
import {ModuleWithProvidersInfo} from '../../src/analysis/module_with_providers_analyzer';
import {PrivateDeclarationsAnalyzer, ExportInfo} from '../../src/analysis/private_declarations_analyzer';
import {SwitchMarkerAnalyzer} from '../../src/analysis/switch_marker_analyzer';
import {Esm2015ReflectionHost} from '../../src/host/esm2015_host';
import {Renderer} from '../../src/rendering/renderer';
import {MockLogger} from '../helpers/mock_logger';
import {RenderingFormatter, RedundantDecoratorMap} from '../../src/rendering/rendering_formatter';
import {makeTestEntryPointBundle, getRootFiles} from '../helpers/utils';
class TestRenderingFormatter implements RenderingFormatter {
addImports(output: MagicString, imports: Import[], sf: ts.SourceFile) {
output.prepend('\n// ADD IMPORTS\n');
}
addExports(output: MagicString, baseEntryPointPath: string, exports: ExportInfo[]) {
output.prepend('\n// ADD EXPORTS\n');
}
addConstants(output: MagicString, constants: string, file: ts.SourceFile): void {
output.prepend('\n// ADD CONSTANTS\n');
}
addDefinitions(output: MagicString, compiledClass: CompiledClass, definitions: string) {
output.prepend('\n// ADD DEFINITIONS\n');
}
removeDecorators(output: MagicString, decoratorsToRemove: RedundantDecoratorMap) {
output.prepend('\n// REMOVE DECORATORS\n');
}
rewriteSwitchableDeclarations(output: MagicString, sourceFile: ts.SourceFile): void {
output.prepend('\n// REWRITTEN DECLARATIONS\n');
}
addModuleWithProvidersParams(
output: MagicString, moduleWithProviders: ModuleWithProvidersInfo[],
importManager: ImportManager): void {
output.prepend('\n// ADD MODUlE WITH PROVIDERS PARAMS\n');
}
}
function createTestRenderer(
packageName: string, files: TestFile[], dtsFiles?: TestFile[], mappingFiles?: TestFile[]) {
const logger = new MockLogger();
loadTestFiles(files);
if (dtsFiles) {
loadTestFiles(dtsFiles);
}
if (mappingFiles) {
loadTestFiles(mappingFiles);
}
const fs = getFileSystem();
const isCore = packageName === '@angular/core';
const bundle = makeTestEntryPointBundle(
'test-package', 'esm2015', isCore, getRootFiles(files), dtsFiles && getRootFiles(dtsFiles));
const typeChecker = bundle.src.program.getTypeChecker();
const host = new Esm2015ReflectionHost(logger, isCore, typeChecker, bundle.dts);
const referencesRegistry = new NgccReferencesRegistry(host);
const decorationAnalyses =
new DecorationAnalyzer(fs, bundle, host, referencesRegistry).analyzeProgram();
const switchMarkerAnalyses =
new SwitchMarkerAnalyzer(host, bundle.entryPoint.package).analyzeProgram(bundle.src.program);
const privateDeclarationsAnalyses =
new PrivateDeclarationsAnalyzer(host, referencesRegistry).analyzeProgram(bundle.src.program);
const testFormatter = new TestRenderingFormatter();
spyOn(testFormatter, 'addExports').and.callThrough();
spyOn(testFormatter, 'addImports').and.callThrough();
spyOn(testFormatter, 'addDefinitions').and.callThrough();
spyOn(testFormatter, 'addConstants').and.callThrough();
spyOn(testFormatter, 'removeDecorators').and.callThrough();
spyOn(testFormatter, 'rewriteSwitchableDeclarations').and.callThrough();
spyOn(testFormatter, 'addModuleWithProvidersParams').and.callThrough();
const renderer = new Renderer(testFormatter, fs, logger, bundle);
return {renderer,
testFormatter,
decorationAnalyses,
switchMarkerAnalyses,
privateDeclarationsAnalyses,
bundle};
}
runInEachFileSystem(() => {
describe('Renderer', () => {
let _: typeof absoluteFrom;
let INPUT_PROGRAM: TestFile;
let COMPONENT_PROGRAM: TestFile;
let NGMODULE_PROGRAM: TestFile;
let INPUT_PROGRAM_MAP: SourceMapConverter;
let RENDERED_CONTENTS: string;
let OUTPUT_PROGRAM_MAP: SourceMapConverter;
let MERGED_OUTPUT_PROGRAM_MAP: SourceMapConverter;
beforeEach(() => {
_ = absoluteFrom;
INPUT_PROGRAM = {
name: _('/node_modules/test-package/src/file.js'),
contents:
`import { Directive } from '@angular/core';\nexport class A {\n foo(x) {\n return x;\n }\n}\nA.decorators = [\n { type: Directive, args: [{ selector: '[a]' }] }\n];\n`
};
COMPONENT_PROGRAM = {
name: _('/node_modules/test-package/src/component.js'),
contents:
`import { Component } from '@angular/core';\nexport class A {}\nA.decorators = [\n { type: Component, args: [{ selector: 'a', template: '{{ person!.name }}' }] }\n];\n`
};
NGMODULE_PROGRAM = {
name: _('/node_modules/test-package/src/ngmodule.js'),
contents:
`import { NgModule } from '@angular/core';\nexport class A {}\nA.decorators = [\n { type: NgModule, args: [{}] }\n];\n`
};
INPUT_PROGRAM_MAP = fromObject({
'version': 3,
'file': _('/node_modules/test-package/src/file.js'),
'sourceRoot': '',
'sources': [_('/node_modules/test-package/src/file.ts')],
'names': [],
'mappings':
'AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,MAAM;IACF,GAAG,CAAC,CAAS;QACT,OAAO,CAAC,CAAC;IACb,CAAC;;AACM,YAAU,GAAG;IAChB,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE;CACnD,CAAC',
'sourcesContent': [INPUT_PROGRAM.contents]
});
RENDERED_CONTENTS = `
// ADD IMPORTS
// ADD EXPORTS
// ADD CONSTANTS
// ADD DEFINITIONS
// REMOVE DECORATORS
` + INPUT_PROGRAM.contents;
OUTPUT_PROGRAM_MAP = fromObject({
'version': 3,
'file': 'file.js',
'sources': [_('/node_modules/test-package/src/file.js')],
'sourcesContent': [INPUT_PROGRAM.contents],
'names': [],
'mappings': ';;;;;;;;;;AAAA;;;;;;;;;'
});
MERGED_OUTPUT_PROGRAM_MAP = fromObject({
'version': 3,
'sources': [_('/node_modules/test-package/src/file.ts')],
'names': [],
'mappings': ';;;;;;;;;;AAAA',
'file': 'file.js',
'sourcesContent': [INPUT_PROGRAM.contents]
});
});
describe('renderProgram()', () => {
it('should render the modified contents; and a new map file, if the original provided no map file.',
() => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses} =
createTestRenderer('test-package', [INPUT_PROGRAM]);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
expect(result[0].path).toEqual(_('/node_modules/test-package/src/file.js'));
expect(result[0].contents)
.toEqual(RENDERED_CONTENTS + '\n' + generateMapFileComment('file.js.map'));
expect(result[1].path).toEqual(_('/node_modules/test-package/src/file.js.map'));
expect(result[1].contents).toEqual(OUTPUT_PROGRAM_MAP.toJSON());
});
it('should render as JavaScript', () => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [COMPONENT_PROGRAM]);
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
expect(addDefinitionsSpy.calls.first().args[2])
.toEqual(`A.ɵfac = function A_Factory(t) { return new (t || A)(); };
A.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: A, selectors: [["a"]], decls: 1, vars: 1, template: function A_Template(rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵtext(0);
} if (rf & 2) {
ɵngcc0.ɵɵtextInterpolate(ctx.person.name);
} }, encapsulation: 2 });
/*@__PURE__*/ ɵngcc0.ɵsetClassMetadata(A, [{
type: Component,
args: [{ selector: 'a', template: '{{ person!.name }}' }]
}], null, null);`);
});
describe('calling RenderingFormatter methods', () => {
it('should call addImports with the source code and info about the core Angular library.',
() => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [INPUT_PROGRAM]);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addImportsSpy = testFormatter.addImports as jasmine.Spy;
expect(addImportsSpy.calls.first().args[0].toString()).toEqual(RENDERED_CONTENTS);
expect(addImportsSpy.calls.first().args[1]).toEqual([
{specifier: '@angular/core', qualifier: 'ɵngcc0'}
]);
});
it('should call addDefinitions with the source code, the analyzed class and the rendered definitions.',
() => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [INPUT_PROGRAM]);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
expect(addDefinitionsSpy.calls.first().args[0].toString()).toEqual(RENDERED_CONTENTS);
expect(addDefinitionsSpy.calls.first().args[1]).toEqual(jasmine.objectContaining({
name: 'A',
decorators: [jasmine.objectContaining({name: 'Directive'})]
}));
expect(addDefinitionsSpy.calls.first().args[2])
.toEqual(`A.ɵfac = function A_Factory(t) { return new (t || A)(); };
A.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: A, selectors: [["", "a", ""]] });
/*@__PURE__*/ ɵngcc0.ɵsetClassMetadata(A, [{
type: Directive,
args: [{ selector: '[a]' }]
}], null, { foo: [] });`);
});
it('should call removeDecorators with the source code, a map of class decorators that have been analyzed',
() => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [INPUT_PROGRAM]);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const removeDecoratorsSpy = testFormatter.removeDecorators as jasmine.Spy;
expect(removeDecoratorsSpy.calls.first().args[0].toString())
.toEqual(RENDERED_CONTENTS);
// Each map key is the TS node of the decorator container
// Each map value is an array of TS nodes that are the decorators to remove
const map = removeDecoratorsSpy.calls.first().args[1] as Map<ts.Node, ts.Node[]>;
const keys = Array.from(map.keys());
expect(keys.length).toEqual(1);
expect(keys[0].getText())
.toEqual(`[\n { type: Directive, args: [{ selector: '[a]' }] }\n]`);
const values = Array.from(map.values());
expect(values.length).toEqual(1);
expect(values[0].length).toEqual(1);
expect(values[0][0].getText())
.toEqual(`{ type: Directive, args: [{ selector: '[a]' }] }`);
});
it('should render static fields before any additional statements', () => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [NGMODULE_PROGRAM]);
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
const definitions: string = addDefinitionsSpy.calls.first().args[2];
const ngModuleDef = definitions.indexOf('ɵmod');
expect(ngModuleDef).not.toEqual(-1, 'ɵmod should exist');
const ngInjectorDef = definitions.indexOf('ɵinj');
expect(ngInjectorDef).not.toEqual(-1, 'ɵinj should exist');
const setClassMetadata = definitions.indexOf('setClassMetadata');
expect(setClassMetadata).not.toEqual(-1, 'setClassMetadata call should exist');
expect(setClassMetadata)
.toBeGreaterThan(ngModuleDef, 'setClassMetadata should follow ɵmod');
expect(setClassMetadata)
.toBeGreaterThan(ngInjectorDef, 'setClassMetadata should follow ɵinj');
});
it('should render classes without decorators if handler matches', () => {
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} =
createTestRenderer('test-package', [{
name: _('/node_modules/test-package/src/file.js'),
contents: `
import { Directive, ViewChild } from '@angular/core';
export class UndecoratedBase { test = null; }
UndecoratedBase.propDecorators = {
test: [{
type: ViewChild,
args: ["test", {static: true}]
}],
};
`
}]);
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
expect(addDefinitionsSpy.calls.first().args[2])
.toEqual(
`UndecoratedBase.ngBaseDef = ɵngcc0.ɵɵdefineBase({ viewQuery: function (rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵstaticViewQuery(_c0, true);
} if (rf & 2) {
var _t;
ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx.test = _t.first);
} } });`);
});
it('should call renderImports after other abstract methods', () => {
// This allows the other methods to add additional imports if necessary
const {renderer, decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('test-package', [INPUT_PROGRAM]);
const addExportsSpy = testFormatter.addExports as jasmine.Spy;
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
const addConstantsSpy = testFormatter.addConstants as jasmine.Spy;
const addImportsSpy = testFormatter.addImports as jasmine.Spy;
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
expect(addExportsSpy).toHaveBeenCalledBefore(addImportsSpy);
expect(addDefinitionsSpy).toHaveBeenCalledBefore(addImportsSpy);
expect(addConstantsSpy).toHaveBeenCalledBefore(addImportsSpy);
});
});
describe('source map merging', () => {
it('should merge any inline source map from the original file and write the output as an inline source map',
() => {
const {decorationAnalyses, renderer, switchMarkerAnalyses,
privateDeclarationsAnalyses} =
createTestRenderer(
'test-package', [{
...INPUT_PROGRAM,
contents: INPUT_PROGRAM.contents + '\n' + INPUT_PROGRAM_MAP.toComment()
}]);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
expect(result[0].path).toEqual(_('/node_modules/test-package/src/file.js'));
expect(result[0].contents)
.toEqual(RENDERED_CONTENTS + '\n' + MERGED_OUTPUT_PROGRAM_MAP.toComment());
expect(result[1]).toBeUndefined();
});
it('should merge any external source map from the original file and write the output to an external source map',
() => {
const sourceFiles: TestFile[] = [{
...INPUT_PROGRAM,
contents: INPUT_PROGRAM.contents + '\n//# sourceMappingURL=file.js.map'
}];
const mappingFiles: TestFile[] =
[{name: _(INPUT_PROGRAM.name + '.map'), contents: INPUT_PROGRAM_MAP.toJSON()}];
const {decorationAnalyses, renderer, switchMarkerAnalyses,
privateDeclarationsAnalyses} =
createTestRenderer('test-package', sourceFiles, undefined, mappingFiles);
const result = renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
expect(result[0].path).toEqual(_('/node_modules/test-package/src/file.js'));
expect(result[0].contents)
.toEqual(RENDERED_CONTENTS + '\n' + generateMapFileComment('file.js.map'));
expect(result[1].path).toEqual(_('/node_modules/test-package/src/file.js.map'));
expect(JSON.parse(result[1].contents)).toEqual(MERGED_OUTPUT_PROGRAM_MAP.toObject());
});
});
describe('@angular/core support', () => {
it('should render relative imports in ESM bundles', () => {
const CORE_FILE: TestFile = {
name: _('/node_modules/test-package/src/core.js'),
contents:
`import { NgModule } from './ng_module';\nexport class MyModule {}\nMyModule.decorators = [\n { type: NgModule, args: [] }\n];\n`
};
const R3_SYMBOLS_FILE: TestFile = {
// r3_symbols in the file name indicates that this is the path to rewrite core imports
// to
name: _('/node_modules/test-package/src/r3_symbols.js'),
contents: `export const NgModule = () => null;`
};
// The package name of `@angular/core` indicates that we are compiling the core library.
const {decorationAnalyses, renderer, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('@angular/core', [CORE_FILE, R3_SYMBOLS_FILE]);
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
expect(addDefinitionsSpy.calls.first().args[2])
.toContain(`/*@__PURE__*/ ɵngcc0.setClassMetadata(`);
const addImportsSpy = testFormatter.addImports as jasmine.Spy;
expect(addImportsSpy.calls.first().args[1]).toEqual([
{specifier: './r3_symbols', qualifier: 'ɵngcc0'}
]);
});
it('should render no imports in FESM bundles', () => {
const CORE_FILE: TestFile = {
name: _('/node_modules/test-package/src/core.js'),
contents: `export const NgModule = () => null;
export class MyModule {}\nMyModule.decorators = [\n { type: NgModule, args: [] }\n];\n`
};
const {decorationAnalyses, renderer, switchMarkerAnalyses, privateDeclarationsAnalyses,
testFormatter} = createTestRenderer('@angular/core', [CORE_FILE]);
renderer.renderProgram(
decorationAnalyses, switchMarkerAnalyses, privateDeclarationsAnalyses);
const addDefinitionsSpy = testFormatter.addDefinitions as jasmine.Spy;
expect(addDefinitionsSpy.calls.first().args[2])
.toContain(`/*@__PURE__*/ setClassMetadata(`);
const addImportsSpy = testFormatter.addImports as jasmine.Spy;
expect(addImportsSpy.calls.first().args[1]).toEqual([]);
});
});
});
});
});
| mit |
Jheysoon/lcis | application/views/audit/account_list.php | 7087 | <div class="col-md-3"></div>
<div class="col-md-9 body-container">
<div class="panel p-body">
<div class="panel-heading search">
<div class="col-md-6">
<h4>List of Accounts</h4>
</div>
</div>
<div class="form-group">
<div class="panel-body">
<div class="col-md-4">
<form class="form" role="form">
<div class="form-group">
<select class="form-control" name='course' required>
<option> ALL</option>
<option> ASSET</option>
<option> LIABILITY</option>
<option> EQUITY</option>
<option> INCOME</option>
<option> EXPENSE</option>
</select>
</div>
</form>
</div>
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<tr>
<th>ACCOUNT NUMBER</th>
<th>CATEGORY</th>
<th>ACCOUNT DESCRIPTION</th>
<th>ACTION</th>
</tr>
<tr>
<td>0000001.020.001.001</td>
<td>CASH ON HAND</td>
<td>CASHIER WINDOW 1</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.020.002.001</td>
<td>CASH ON HAND</td>
<td>CASHIER WINDOW 2</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.601.000.001</td>
<td>MATRICULATION REVENUE</td>
<td>MATRICULATION COLLEGE OF CRIMINOLOGY</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.621.000.001</td>
<td>TUITION REVENUE</td>
<td>TUITION COLLEGE OF CRIMINOLOGY</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.631.000.001</td>
<td>ENROLMENT FEES</td>
<td>LIBRARY</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.632.000.001</td>
<td>ENROLMENT FEES</td>
<td>ATHLETICS</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.633.000.001</td>
<td>ENROLMENT FEES</td>
<td>DENTAL AND MEDICAL</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.634.000.001</td>
<td>ENROLMENT FEES</td>
<td>TEST SUPPLIES</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.634.000.001</td>
<td>ENROLMENT FEES</td>
<td>GUIDANCE AND COUNSELING</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.651.000.001</td>
<td>OTHER FEES</td>
<td>TRANSCRIPT OF RECORDS</td>
<td><a class="a-table label label-success" href="<?php echo base_url('adt_viewCashierAccountMovement'); ?>">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.652.000.001</td>
<td>OTHER FEES</td>
<td>DIPLOMA</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.653.000.001</td>
<td>OTHER FEES</td>
<td>CERTIFICATION</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.801.000.001</td>
<td>SALARIES AND WAGES</td>
<td>ACADEMIC EMPLOYEES</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0000001.802.000.001</td>
<td>SALARIES AND WAGES</td>
<td>ADMINISTRATIVE EMPLOYEES</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0101121.101.000.001</td>
<td>RECEIVABLES - ENROLMENT</td>
<td>MICHAEL LAUDICO - B.S. CRIMINOLOGY</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0101214.101.000.001</td>
<td>RECEIVABLES - ENROLMENT</td>
<td>LAURA FABI - BACHELOR IN SECONDARY EDUCATION</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0101144.101.000.001</td>
<td>RECEIVABLES - ENROLMENT</td>
<td>JOSE MARCO REYES - A.B. POLITICAL SCIENCE</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0100184.101.000.001</td>
<td>RECEIVABLES - ENROLMENT</td>
<td>JAIME FRANCISCO - B.S. CRIMINOLOGY</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0500001.040.000.001</td>
<td>CASH IN BANK</td>
<td>LAND BANK OF THE PHILIPPINES - ZAMORA ST. BRANCH</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
<tr>
<td>0500001.040.000.001</td>
<td>CASH IN BANK</td>
<td>EAST WEST BANK - MARASBARAS BRANCH</td>
<td><a class="a-table label label-success" href="index.php?page=viewCashierMovement">Acct Movement <span class="glyphicon glyphicon-search"></span></a>
</td>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div> | mit |
giskou/Optimization | src/libs/functions/cooling/CoolingSchedule.java | 202 | /**
*
*/
package libs.functions.cooling;
import java.util.LinkedList;
import libs.Point;
/**
* @author iskoulis
*
*/
public interface CoolingSchedule {
public double U(LinkedList<Point> z);
}
| mit |
RectorPHP/Rector | vendor/symfony/http-foundation/File/Exception/FileException.php | 486 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RectorPrefix20210615\Symfony\Component\HttpFoundation\File\Exception;
/**
* Thrown when an error occurred in the component File.
*
* @author Bernhard Schussek <[email protected]>
*/
class FileException extends \RuntimeException
{
}
| mit |
nicroto/restr | test/restr-loader-test.js | 2516 | var ExpressAppMock = function() {};
ExpressAppMock.prototype = {
map: {},
post: function(route, callback) { this.mapRoute("post", route, callback); },
get: function(route, callback) { this.mapRoute("get", route, callback); },
put: function(route, callback) { this.mapRoute("put", route, callback); },
delete: function(route, callback) { this.mapRoute("delete", route, callback); },
mapRoute: function(verb, route, callback) {
this.map[verb + route] = callback;
}
};
var assert = require("assert"),
RestrLoader = require('../src/custom-modules/restr-loader.js'),
badLoader = new RestrLoader(),
expressApp = new ExpressAppMock(),
loader = new RestrLoader(expressApp);
var goodServiceSpec = {
name: "userService",
methods: [
{
route: "/api/user/:id/:otherId?",
name: "updateUser",
params: {
query: {
name: "string"
},
body: {
description: "string"
}
},
verb: "put",
logic: function(req, res, id) {
if ( req && res && id ) {}
return true;
}
}
]
};
describe('RestrLoader', function() {
describe('customLoader', function() {
before(function(done){
loader = new RestrLoader();
loader.customLoader = function() { return true; };
done();
});
after(function(done){
loader = new RestrLoader(expressApp = new ExpressAppMock());
done();
});
it('is used if no expressApp passed on initialization', function() {
assert.ok(loader.loadService(goodServiceSpec));
});
});
describe('loadServices', function() {
it('should throw error if no specs are passed (no args)', function() {
assert.throws( function() {
loader.loadServices();
}, Error );
});
it('should throw error if no specs are passed (empty array)', function() {
assert.throws( function() {
loader.loadServices([]);
}, Error );
});
});
describe('loadService', function() {
afterEach(function(done){
loader = new RestrLoader(expressApp = new ExpressAppMock());
done();
});
it('should throw error if no loader available (not expressApp, nor customLoader is set)', function() {
assert.throws( function() {
badLoader.loadService(goodServiceSpec);
}, Error );
});
it('should register new API method when data is correct)', function() {
loader.loadService(goodServiceSpec);
var methodSpec = goodServiceSpec.methods[0];
var funcName = methodSpec.verb + methodSpec.route;
assert.ok(expressApp.map[funcName](), "funcName = " + funcName + "\n" + JSON.stringify(expressApp));
});
});
}); | mit |
berryma4/diirt | pvmanager/datasource-formula/src/test/java/org/diirt/datasource/formula/vtable/VTableFunctionSetTest.java | 12677 | /**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource.formula.vtable;
import java.util.Arrays;
import org.diirt.datasource.formula.FormulaFunctionSet;
import org.diirt.datasource.formula.FunctionTester;
import org.diirt.util.array.ArrayDouble;
import org.diirt.vtype.VNumberArray;
import org.diirt.vtype.VString;
import org.diirt.vtype.VStringArray;
import org.diirt.vtype.VTable;
import org.diirt.vtype.VType;
import static org.diirt.vtype.ValueFactory.*;
import org.diirt.vtype.table.Column;
import org.diirt.vtype.table.VTableFactory;
import static org.diirt.vtype.table.VTableFactory.*;
import org.junit.Test;
/**
*
* @author carcassi
*/
public class VTableFunctionSetTest {
private static FormulaFunctionSet set = new VTableFunctionSet();
@Test
public void columnOf() {
VTable data = newVTable(Arrays.<Class<?>>asList(String.class, double.class, double.class),
Arrays.asList("x", "y", "z"), Arrays.<Object>asList(Arrays.asList("a", "b", "c"), new ArrayDouble(1,2,3), new ArrayDouble(5,4,6)));
VStringArray expected1 = newVStringArray(Arrays.asList("a", "b", "c"), alarmNone(), timeNow());
VNumberArray expected2 = newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone());
FunctionTester.findByName(set, "columnOf")
.compareReturnValue(expected1, data, "x")
.compareReturnValue(expected2, data, "y")
.compareReturnValue(null, data, null)
.compareReturnValue(null, null, "y");
}
@Test
public void tableOf1() {
VTable expected = newVTable(Arrays.<Class<?>>asList(double.class, double.class),
Arrays.asList("A", "B"), Arrays.<Object>asList(new ArrayDouble(0.0, 0.1, 0.2), new ArrayDouble(1,2,3)));
Column column1 = VTableFactory.column("A", VTableFactory.step(0, 0.1));
Column column2 = VTableFactory.column("B", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone()));
FunctionTester.findByName(set, "tableOf")
.compareReturnValue(expected, column1, column2);
}
@Test
public void tableOf2() {
VTable expected = newVTable(Arrays.<Class<?>>asList(double.class),
Arrays.asList("B"), Arrays.<Object>asList(new ArrayDouble(1,2,3)));
Column column2 = VTableFactory.column("B", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone()));
FunctionTester.findByName(set, "tableOf")
.compareReturnValue(expected, null, column2);
}
@Test
public void tableOf3() {
Column column1 = VTableFactory.column("A", VTableFactory.step(0, 0.1));
FunctionTester.findByName(set, "tableOf")
.compareReturnValue(null, column1, null);
}
@Test
public void column1() {
VStringArray array = newVStringArray(Arrays.asList("A", "B", "C"), alarmNone(), timeNow());
Column column = VTableFactory.column("A", array);
FunctionTester.findBySignature(set, "column", VString.class, VStringArray.class)
.compareReturnValue(column, "A", array);
}
@Test
public void tableRangeFilter1() {
VTable table = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286"), alarmNone(), timeNow())));
FunctionTester.findBySignature(set, "tableRangeFilter", VTable.class, VString.class, VType.class, VType.class)
.compareReturnValue(expected, table, "Slot", 1.0, 2.5)
.compareReturnValue(null, null, "Slot", 1.0, 2.5)
.compareReturnValue(null, table, null, 1.0, 2.5)
.compareReturnValue(null, table, "Slot", null, 2.5)
.compareReturnValue(null, table, "Slot", 1.0, null);
}
@Test
public void tableValueFilter1() {
VTable table = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286"), alarmNone(), timeNow())));
FunctionTester.findByName(set, "tableValueFilter")
.compareReturnValue(expected, table, "CPU", "286")
.compareReturnValue(null, null, "CPU", "286")
.compareReturnValue(null, table, null, "286")
.compareReturnValue(null, table, "CPU", null);
}
@Test
public void tableValueFilter2() {
VTable table = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286"), alarmNone(), timeNow())));
FunctionTester.findByName(set, "tableStringMatchFilter")
.compareReturnValue(expected, table, "CPU", "28")
.compareReturnValue(null, null, "CPU", "28")
.compareReturnValue(null, table, null, "28")
.compareReturnValue(null, table, "CPU", null);
}
@Test
public void tableRangeFilter2() {
VTable table = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286"), alarmNone(), timeNow())));
FunctionTester.findBySignature(set, "tableRangeFilter", VTable.class, VString.class, VNumberArray.class)
.compareReturnValue(expected, table, "Slot", new ArrayDouble(1.0, 2.5))
.compareReturnValue(null, null, "Slot", new ArrayDouble(1.0, 2.5))
.compareReturnValue(null, table, null, new ArrayDouble(1.0, 2.5))
.compareReturnValue(null, table, "Slot", null);
}
@Test
public void tableUnion() {
VTable table1 = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable table2 = newVTable(column("Rack", newVStringArray(Arrays.asList("B", "B", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(3,2,1), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Table", newVStringArray(Arrays.asList("1", "1", "1", "2", "2", "2"), alarmNone(), timeNow())),
column("Rack", newVStringArray(Arrays.asList("A", "A", "B", "B", "B", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3,3,2,1), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386","286", "286", "386"), alarmNone(), timeNow())));
// TODO: add null cases
FunctionTester.findBySignature(set, "union", VString.class, VStringArray.class, VTable.class)
.compareReturnValue(expected, "Table", Arrays.asList("1", "2"), table1, table2);
}
@Test
public void tableUnion2() {
VTable table1 = newVTable(column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable table2 = newVTable(column("Rack", newVStringArray(Arrays.asList("B", "B", "A"), alarmNone(), timeNow())),
column("Position", newVDoubleArray(new ArrayDouble(3,2,1), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected = newVTable(column("Table", newVStringArray(Arrays.asList("1", "1", "1", "2", "2", "2"), alarmNone(), timeNow())),
column("Rack", newVStringArray(Arrays.asList("A", "A", "B", "B", "B", "A"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3,Double.NaN,Double.NaN,Double.NaN), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386","286", "286", "386"), alarmNone(), timeNow())),
column("Position", newVDoubleArray(new ArrayDouble(Double.NaN,Double.NaN,Double.NaN,3,2,1), alarmNone(), timeNow(), displayNone())));
VTable expected2 = newVTable(column("Table", newVStringArray(Arrays.asList("1", "1", "1"), alarmNone(), timeNow())),
column("Rack", newVStringArray(Arrays.asList("A", "A", "B"), alarmNone(), timeNow())),
column("Slot", newVDoubleArray(new ArrayDouble(1,2,3), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
VTable expected3 = newVTable(column("Table", newVStringArray(Arrays.asList("2", "2", "2"), alarmNone(), timeNow())),
column("Rack", newVStringArray(Arrays.asList("B", "B", "A"), alarmNone(), timeNow())),
column("Position", newVDoubleArray(new ArrayDouble(3,2,1), alarmNone(), timeNow(), displayNone())),
column("CPU", newVStringArray(Arrays.asList("286", "286", "386"), alarmNone(), timeNow())));
// TODO: add null cases
FunctionTester.findBySignature(set, "union", VString.class, VStringArray.class, VTable.class)
.compareReturnValue(expected, "Table", Arrays.asList("1", "2"), table1, table2)
.compareReturnValue(expected2, "Table", Arrays.asList("1", "2"), table1, null)
.compareReturnValue(expected3, "Table", Arrays.asList("1", "2"), null, table2)
.compareReturnValue(null, "Table", Arrays.asList("1", "2"), null, null);
}
}
| mit |
caseyscarborough/brewerydb-api | src/main/java/com/brewerydb/api/request/ingredient/IngredientRequest.java | 204 | package com.brewerydb.api.request.ingredient;
public class IngredientRequest {
public static GetIngredientsRequest.Builder getIngredients() {
return GetIngredientsRequest.builder();
}
}
| mit |
activecollab/authentication | src/Authorizer/RequestAware/RequestAware.php | 901 | <?php
/*
* This file is part of the Active Collab Authentication project.
*
* (c) A51 doo <[email protected]>. All rights reserved.
*/
namespace ActiveCollab\Authentication\Authorizer\RequestAware;
use ActiveCollab\Authentication\Authorizer\RequestProcessor\RequestProcessorInterface;
/**
* @package ActiveCollab\Authentication\Authorizer\RequestAware
*/
trait RequestAware
{
/**
* @var RequestProcessorInterface
*/
private $request_processor;
/**
* {@inheritdoc}
*/
public function getRequestProcessor()
{
return $this->request_processor;
}
/**
* @param RequestProcessorInterface|null $request_processor
* @return $this
*/
protected function &setRequestProcessor(RequestProcessorInterface $request_processor = null)
{
$this->request_processor = $request_processor;
return $this;
}
}
| mit |
senlinzhan/soke | src/EventLoop.hpp | 1092 | #ifndef EVENTLOOP_H
#define EVENTLOOP_H
#include "Epoll.hpp"
#include <queue>
#include <memory>
#include <thread>
#include <vector>
#include <unordered_map>
#include <unordered_set>
namespace soke
{
class Channel;
class EventLoop
{
public:
using Task = std::function<void ()>;
EventLoop();
~EventLoop();
EventLoop(const EventLoop &) = delete;
EventLoop &operator=(const EventLoop &) = delete;
void updateChannel(Channel *channel);
void removeChannel(Channel *channel);
void loop();
void quit();
void queueInLoop(Task task);
private:
bool looping_;
bool quit_;
std::thread::id tid_;
std::queue<Task> taskQueue_;
Epoll epoll_;
std::unordered_map<int, Channel *> channels_;
std::unordered_set<int> unregisteredFds_;
};
};
#endif /* EVENTLOOP_H */
| mit |
phisiart/C-Compiler | Parser/Expressions.cs | 16153 | using System.Collections.Immutable;
using AST;
using static Parsing.ParserCombinator;
using Attribute = AST.Attribute;
namespace Parsing {
public partial class CParsers {
public static NamedParser<Expr>
Expression { get; } = Parser.Create<Expr>("expression");
public static NamedParser<Expr>
PrimaryExpression { get; } = Parser.Create<Expr>("primary-expression");
public static NamedParser<Expr>
Variable { get; } = Parser.Create<Expr>("variable");
public static NamedParser<Expr>
Constant { get; } = Parser.Create<Expr>("constant");
public static NamedParser<Expr>
ConstantExpression { get; } = Parser.Create<Expr>("constant-expression");
public static NamedParser<Expr>
ConditionalExpression { get; } = Parser.Create<Expr>("conditional-expression");
public static NamedParser<Expr>
AssignmentExpression { get; } = Parser.Create<Expr>("assignment-expression");
public static NamedParser<Expr>
PostfixExpression { get; } = Parser.Create<Expr>("postfix-expression");
public static NamedParser<ImmutableList<Expr>>
ArgumentExpressionList { get; } = Parser.Create<ImmutableList<Expr>>("argument-expression-list");
public static NamedParser<Expr>
UnaryExpression { get; } = Parser.Create<Expr>("unary-expression");
public static NamedParser<Expr>
CastExpression { get; } = Parser.Create<Expr>("cast-expression");
public static NamedParser<Expr>
MultiplicativeExpression { get; } = Parser.Create<Expr>("multiplicative-expression");
public static NamedParser<Expr>
AdditiveExpression { get; } = Parser.Create<Expr>("additive-expression");
public static NamedParser<Expr>
ShiftExpression { get; } = Parser.Create<Expr>("shift-expression");
public static NamedParser<Expr>
RelationalExpression { get; } = Parser.Create<Expr>("relational-expression");
public static NamedParser<Expr>
EqualityExpression { get; } = Parser.Create<Expr>("equality-expression");
public static NamedParser<Expr>
AndExpression { get; } = Parser.Create<Expr>("and-expression");
public static NamedParser<Expr>
ExclusiveOrExpression { get; } = Parser.Create<Expr>("exclusive-or-expression");
public static NamedParser<Expr>
InclusiveOrExpression { get; } = Parser.Create<Expr>("inclusive-or-expression");
public static NamedParser<Expr>
LogicalAndExpression { get; } = Parser.Create<Expr>("logical-and-expression");
public static NamedParser<Expr>
LogicalOrExpression { get; } = Parser.Create<Expr>("logical-or-expression");
/// <summary>
/// The following are rules for C expressions.
/// </summary>
public static void SetExpressionRules() {
// expression
// : assignment-expression [ ',' assignment-expression ]*
Expression.Is(
AssignmentExpression
.OneOrMore(Comma)
.Then(exprs => {
if (exprs.Count == 1) {
return exprs[0];
}
return AssignmentList.Create(exprs);
})
);
// primary-expression
// : identifier # Cannot be a typedef name.
// | constant
// | string-literal
// | '(' expression ')'
PrimaryExpression.Is(
Either(Variable)
.Or(Constant)
.Or(StringLiteral)
.Or(
(LeftParen).Then(Expression).Then(RightParen)
)
);
// An identifier for a variable must not be defined as a typedef name.
Variable.Is(
Identifier.Check(result => !result.Environment.IsTypedefName(result.Result)).Then(AST.Variable.Create)
);
// constant
// : const-char
// : const-int
// : const-float
Constant.Is(
Either(ConstChar)
.Or(ConstInt)
.Or(ConstFloat)
);
// constant-expression
// : conditional-expression
//
// Note:
// The size of an array should be a constant.
// Note that the check is actually performed in semantic analysis.
ConstantExpression.Is(
ConditionalExpression
);
// conditional-expression
// : logical-or-expression [ '?' expression ':' conditional-expression ]?
ConditionalExpression.Is(
(LogicalOrExpression)
.Then(
Given<Expr>()
.Then(Question)
.Then(Expression)
.Then(Colon)
.Then(ConditionalExpression)
.Then(AST.ConditionalExpression.Create)
.Optional()
)
);
// assignment-expression
// : unary-expression assignment-operator assignment-expression # first-set = first-set(unary-expression)
// | conditional-expression # first-set = first-set(cast-expression) = first-set(unary-expression) ++ { '(' }
//
// Note:
// Assignment operators are:
// '=', '*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=', '|='
AssignmentExpression.Is(
Either(
AssignmentOperator(
UnaryExpression,
AssignmentExpression,
BinaryOperatorBuilder.Create(Assign, Assignment.Create),
BinaryOperatorBuilder.Create(MultAssign, AST.MultAssign.Create),
BinaryOperatorBuilder.Create(DivAssign, AST.DivAssign.Create),
BinaryOperatorBuilder.Create(ModAssign, AST.ModAssign.Create),
BinaryOperatorBuilder.Create(AddAssign, AST.AddAssign.Create),
BinaryOperatorBuilder.Create(SubAssign, AST.SubAssign.Create),
BinaryOperatorBuilder.Create(LeftShiftAssign, LShiftAssign.Create),
BinaryOperatorBuilder.Create(RightShiftAssign, RShiftAssign.Create),
BinaryOperatorBuilder.Create(BitwiseAndAssign, AST.BitwiseAndAssign.Create),
BinaryOperatorBuilder.Create(XorAssign, AST.XorAssign.Create),
BinaryOperatorBuilder.Create(BitwiseOrAssign, AST.BitwiseOrAssign.Create)
)
).Or(
ConditionalExpression
)
);
// postfix-expression
// : primary-expression [
// '[' expression ']' # Get element from array
// | '(' [argument-expression-list]? ')' # Function call
// | '.' identifier # Get member from struct/union
// | '->' identifier # Get member from struct/union
// | '++' # Increment
// | '--' # Decrement
// ]*
PostfixExpression.Is(
PrimaryExpression
.Then(
Either(
Given<Expr>()
.Then(LeftBracket)
.Then(Expression)
.Then(RightBracket)
.Then((array, index) => Dereference.Create(AST.Add.Create(array, index)))
).Or(
Given<Expr>()
.Then(LeftParen)
.Then(ArgumentExpressionList.Optional(ImmutableList<Expr>.Empty))
.Then(RightParen)
.Then(FuncCall.Create)
).Or(
Given<Expr>()
.Then(Period)
.Then(Identifier)
.Then(Attribute.Create)
).Or(
Given<Expr>()
.Then(RightArrow)
.Then(Identifier)
.Then((expr, member) => Attribute.Create(Dereference.Create(expr), member))
).Or(
Given<Expr>()
.Then(Increment)
.Then(PostIncrement.Create)
).Or(
Given<Expr>()
.Then(Decrement)
.Then(PostDecrement.Create)
).ZeroOrMore()
)
);
// argument-expression-list
// : assignment-expression [ ',' assignment-expression ]*
ArgumentExpressionList.Is(
AssignmentExpression.OneOrMore(Comma)
);
// unary-expression
// : postfix-expression # first-set = { id, const, string }
// | '++' unary-expression # first-set = { '++' }
// | '--' unary-expression # first-set = { '--' }
// | unary-operator cast-expression # first-set = { '&', '*', '+', '-', '~', '!' }
// | 'sizeof' unary-expression # first-set = { 'sizeof' }
// | 'sizeof' '(' Type-name ')' # first-set = { 'sizeof' }
//
// Notes:
// 1. unary-operator can be '&', '*', '+', '-', '~', '!'.
// 2. The last two rules are ambiguous: you can't figure out whether the x in sizeof(x) is a typedef of a variable.
// I have a parser hack for this: add a parser environment to track all the typedefs.
// 3. first_set = first_set(postfix-expression) + { '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
// = first_set(primary-expression) + { '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
// = { id, const, string, '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
UnaryExpression.Is(
Either(
PostfixExpression
).Or(
(Increment).Then(UnaryExpression).Then(PreIncrement.Create)
).Or(
(Decrement).Then(UnaryExpression).Then(PreDecrement.Create)
).Or(
(BitwiseAnd).Then(CastExpression).Then(Reference.Create)
).Or(
(Mult).Then(CastExpression).Then(Dereference.Create)
).Or(
(Add).Then(CastExpression).Then(Positive.Create)
).Or(
(Sub).Then(CastExpression).Then(Negative.Create)
).Or(
(BitwiseNot).Then(CastExpression).Then(AST.BitwiseNot.Create)
).Or(
(LogicalNot).Then(CastExpression).Then(AST.LogicalNot.Create)
).Or(
(SizeOf).Then(UnaryExpression).Then(SizeofExpr.Create)
).Or(
(SizeOf).Then(LeftParen).Then(TypeName).Then(RightParen).Then(SizeofType.Create)
)
);
// cast-expression
// : unary-expression # first-set = { id, const, string, '++', '--', '&', '*', '+', '-', '~', '!', 'sizeof' }
// | '(' type_name ')' cast-expression # first-set = '('
CastExpression.Is(
Either(
UnaryExpression
).Or(
(LeftParen).Then(TypeName).Then(RightParen).Then(CastExpression)
.Then(TypeCast.Create)
)
);
// multiplicative-expression
// : cast-expression [ [ '*' | '/' | '%' ] cast-expression ]*
MultiplicativeExpression.Is(
BinaryOperator(
CastExpression,
BinaryOperatorBuilder.Create(Mult, Multiply.Create),
BinaryOperatorBuilder.Create(Div, Divide.Create),
BinaryOperatorBuilder.Create(Mod, Modulo.Create)
)
);
// additive-expression
// : multiplicative-expression [ [ '+' | '-' ] multiplicative-expression ]*
AdditiveExpression.Is(
BinaryOperator(
MultiplicativeExpression,
BinaryOperatorBuilder.Create(Add, AST.Add.Create),
BinaryOperatorBuilder.Create(Sub, AST.Sub.Create)
)
);
// shift-expression
// : additive-expression [ [ '<<' | '>>' ] additive-expression ]*
ShiftExpression.Is(
BinaryOperator(
AdditiveExpression,
BinaryOperatorBuilder.Create(LeftShift, LShift.Create),
BinaryOperatorBuilder.Create(RightShift, RShift.Create)
)
);
// relational-expression
// : shift-expression [ [ '<' | '>' | '<=' | '>=' ] shift-expression ]*
RelationalExpression.Is(
BinaryOperator(
ShiftExpression,
BinaryOperatorBuilder.Create(Less, AST.Less.Create),
BinaryOperatorBuilder.Create(Greater, AST.Greater.Create),
BinaryOperatorBuilder.Create(LessEqual, LEqual.Create),
BinaryOperatorBuilder.Create(GreaterEqual, GEqual.Create)
)
);
// equality-expression
// : relational-expression [ [ '==' | '!=' ] relational-expression ]*
EqualityExpression.Is(
BinaryOperator(
RelationalExpression,
BinaryOperatorBuilder.Create(Equal, AST.Equal.Create),
BinaryOperatorBuilder.Create(NotEqual, AST.NotEqual.Create)
)
);
// and-expression
// : equality-expression [ '&' equality-expression ]*
AndExpression.Is(
BinaryOperator(
EqualityExpression,
BinaryOperatorBuilder.Create(BitwiseAnd, AST.BitwiseAnd.Create)
)
);
// exclusive-or-expression
// : and-expression [ '^' and-expression ]*
ExclusiveOrExpression.Is(
BinaryOperator(
AndExpression,
BinaryOperatorBuilder.Create(Xor, AST.Xor.Create)
)
);
// inclusive-or-expression
// : exclusive-or-expression [ '|' exclusive-or-expression ]*
InclusiveOrExpression.Is(
BinaryOperator(
ExclusiveOrExpression,
BinaryOperatorBuilder.Create(BitwiseOr, AST.BitwiseOr.Create)
)
);
// logical-and-expression
// : inclusive-or-expression [ '&&' inclusive-or-expression ]*
LogicalAndExpression.Is(
BinaryOperator(
InclusiveOrExpression,
BinaryOperatorBuilder.Create(LogicalAnd, AST.LogicalAnd.Create)
)
);
// logical-or-expression
// :logical-and-expression [ '||' logical-and-expression ]*
LogicalOrExpression.Is(
BinaryOperator(
LogicalAndExpression,
BinaryOperatorBuilder.Create(LogicalOr, AST.LogicalOr.Create)
)
);
}
}
}
| mit |
BookFrank/CodePlay | codeplay-design-pattern/src/main/java/com/tazine/design/strategy/YellowDuck.java | 403 | package com.tazine.design.strategy;
import com.tazine.design.strategy.family.FlyingWithWings;
/**
* 大黄鸭
*
* @author frank
* @date 2018/01/15
*/
public class YellowDuck extends Duck {
public YellowDuck() {
super();
super.setFlyingStrategy(new FlyingWithWings());
}
@Override
protected void display() {
System.out.println("我是大黄鸭");
}
}
| mit |
nicholasyang/MeleeStats | app/src/main/java/com/nicholasyang/meleestats/NemesisOverallFragment.java | 4145 | package com.nicholasyang.meleestats;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.IOException;
import java.text.DecimalFormat;
import butterknife.Bind;
import butterknife.ButterKnife;
public class NemesisOverallFragment extends Fragment {
private String nemesis;
private NemesisDataAnalysis da;
private OnFragmentInteractionListener mListener;
@Bind(R.id.gameRecordInfo) TextView gameRecordInfo;
@Bind(R.id.gameRecord) TextView gameRecord;
@Bind(R.id.optimalCharacter) TextView optimalCharacter;
@Bind(R.id.optimalCharacterRecord) TextView optimalCharacterRecord;
@Bind(R.id.optimalStage) TextView optimalStage;
@Bind(R.id.optimalStageRecord) TextView optimalStageRecord;
public NemesisOverallFragment() {
}
public static NemesisOverallFragment newInstance(String nemesis) {
NemesisOverallFragment fragment = new NemesisOverallFragment();
Bundle args = new Bundle();
args.putString("nemesis", nemesis);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
nemesis = getArguments().getString("nemesis");
try {
da = new NemesisDataAnalysis(nemesis, getContext());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_nemesis_overall, container, false);
ButterKnife.bind(this, v);
if(da.getWins(da.getList()) > da.getLosses(da.getList())){
gameRecordInfo.setText("You have an edge over " + nemesis + ".");
gameRecordInfo.setTextColor(ContextCompat.getColor(getContext(), R.color.materialGreen600));
} else if(da.getWins(da.getList()) < da.getLosses(da.getList())){
gameRecordInfo.setText(nemesis + " has an edge over you.");
gameRecordInfo.setTextColor(ContextCompat.getColor(getContext(), R.color.materialRed400));
} else {
gameRecordInfo.setText("You and " + nemesis + " are tied.");
}
gameRecord.setText(da.getWins(da.getList()) + " to " + da.getLosses(da.getList()) + ", " + da.getFormattedWinRate(da.getList()) + "% wins");
try {
optimalCharacter.setText(da.getOptimalCharacter().toString());
optimalCharacterRecord.setText(da.getWins(da.getCharacterGameList(da.getOptimalCharacter())) + "/" + da.getCharacterGameList(da.getOptimalCharacter()).size() + ", " + da.getFormattedWinRate(da.getCharacterGameList(da.getOptimalCharacter())) + "% win rate");
optimalStage.setText(da.getOptimalStage().toString());
optimalStageRecord.setText(da.getWins(da.getStageGameList(da.getOptimalStage())) + "/" + da.getStageGameList(da.getOptimalStage()).size() + ", " + da.getFormattedWinRate(da.getStageGameList(da.getOptimalStage())) + "% win rate");
} catch (IOException e) {
e.printStackTrace();
}
return v;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| mit |
stuliveshere/SeismicProcessing2015 | prac2_student_working/02.0_brute_vels.py | 780 | import toolbox
import numpy as np
import pylab
data, params = toolbox.initialise('prepro.su')
cdps = np.unique(data['cdp'])
#recreate original velocity field
vels = {}
vels[753]= (2456.0, 0.153), (2772.1, 0.413), (3003.2, 0.612), (3076.1, 0.704), (3270.7, 1.056), (3367.9, 1.668), (3538.2, 2.204), (3671.9, 3.566), (3915.1, 5.908),
vels[3056]=(2456.0, 0.153), (2772.1, 0.413), (3003.2, 0.612), (3076.1, 0.704), (3270.7, 1.056), (3367.9, 1.668), (3538.2, 2.204), (3671.9, 3.566), (3915.1, 5.908),
params['cdp'] = cdps
params['vels'] = toolbox.build_vels(vels, **params)
np.array(params['vels']).tofile('vels_initial.bin')
params['vels'] = np.fromfile('vels_initial.bin').reshape(-1, params['ns'])
pylab.imshow(params['vels'].T, aspect='auto')
pylab.colorbar()
pylab.show()
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.