repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
wgroeneveld/jasmine-junit-runner | src/test/java/be/klak/junit/jasmine/JasmineSuiteGeneratesRunnerTest.java | 4095 | package be.klak.junit.jasmine;
import static org.fest.assertions.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import be.klak.junit.jasmine.JasmineTestRunner;
import be.klak.junit.jasmine.classes.JasmineSuiteGeneratorClassWithRunner;
import be.klak.junit.jasmine.classes.JasmineSuiteGeneratorClassWithRunnerInSubDir;
import be.klak.junit.jasmine.classes.JasmineSuiteGeneratorClassWithoutRunner;
@RunWith(MockitoJUnitRunner.class)
public class JasmineSuiteGeneratesRunnerTest {
private static final String RUNNERS_OUTPUT_DIR = "src/test/javascript/runners/";
@Mock
private RunNotifier notifierMock;
@Before
public void clearRunnersOutputDirectory() throws IOException {
FileUtils.cleanDirectory(new File(RUNNERS_OUTPUT_DIR));
}
@Test
public void byDefaultDoNotGenerateJasmineTestRunner() {
Class<JasmineSuiteGeneratorClassWithoutRunner> testClass = JasmineSuiteGeneratorClassWithoutRunner.class;
new JasmineTestRunner(testClass).run(notifierMock);
File runnerResult = getTestRunnerResultFile(testClass);
assertThat(runnerResult.isFile()).isFalse();
}
@Test
public void generateJasmineTestRunnerAfterRunningTests() throws IOException {
Class<JasmineSuiteGeneratorClassWithRunner> testClass = JasmineSuiteGeneratorClassWithRunner.class;
new JasmineTestRunner(testClass).run(notifierMock);
File runnerResult = getTestRunnerResultFile(testClass);
assertThat(runnerResult.isFile()).isTrue();
String runnerContent = FileUtils.readFileToString(runnerResult);
assertThat(runnerContent).contains("jasmine.getEnv().addReporter(new jasmine.TrivialReporter());");
assertJSFileIncluded(runnerContent,
"./../../../main/webapp/js/source1.js",
"./../../../main/webapp/js/source2.js",
"./../specs/spec1.js",
"./../specs/spec2.js");
}
@Test
public void generateJasmineTestRunnerAfterRunningTestsWithSubDir() throws IOException {
Class<JasmineSuiteGeneratorClassWithRunnerInSubDir> testClass =
JasmineSuiteGeneratorClassWithRunnerInSubDir.class;
new JasmineTestRunner(testClass).run(notifierMock);
File runnerResult = getTestRunnerResultFile(testClass, "subDir1/subDir2");
assertThat(runnerResult.isFile()).isTrue();
String runnerContent = FileUtils.readFileToString(runnerResult);
assertThat(runnerContent).contains("jasmine.getEnv().addReporter(new jasmine.TrivialReporter());");
assertJSFileIncluded(runnerContent,
"./../../../main/webapp/js/source1.js",
"./../../../main/webapp/js/source2.js",
"./../specs/spec1.js",
"./../specs/spec2.js");
}
private File getTestRunnerResultFile(Class<?> testClass) {
return getTestRunnerResultFile(testClass, StringUtils.EMPTY);
}
// private File getTestRunnerResultFile(Class<?> testClass) {
// return new File(RUNNERS_OUTPUT_DIR + testClass.getSimpleName() + "Runner.html");
// }
private File getTestRunnerResultFile(Class<?> testClass, String subDir) {
StringBuffer filePath = new StringBuffer(RUNNERS_OUTPUT_DIR);
if (StringUtils.isNotBlank(subDir)) {
filePath.append(subDir).append('/');
}
filePath.append(testClass.getSimpleName()).append("Runner.html");
return new File(filePath.toString());
}
private void assertJSFileIncluded(String rawContent, String... files) {
for (String file : files) {
assertThat(rawContent).contains("<script type='text/javascript' src='" + file + "'></script>");
}
}
}
| mit |
ctongfei/nexus | diff/src/main/scala/nexus/diff/ops/control.scala | 2089 | package nexus.diff.ops
import nexus.diff._
import nexus.diff.execution._
import nexus.diff.exception._
import nexus._
/**
* Conditional expression.
*
* @author Tongfei Chen
* @since 0.1.0
*/
object If extends PolyOp3 {
implicit def ifF[X](implicit X: Grad[X]): P[Boolean, X, X, X] = new P[Boolean, X, X, X] {
def name = "If"
def tag = Tag.of(X)
def forward(c: Boolean, t: X, f: X) = if (c) t else f
def backward1(dy: X, y: X, c: Boolean, t: X, f: X) = throw new OperatorNotDifferentiableException(this, 1)
def backward2(dy: X, y: X, c: Boolean, t: X, f: X) = if (c) dy else X.zeroBy(t)
def backward3(dy: X, y: X, c: Boolean, t: X, f: X) = if (!c) dy else X.zeroBy(f)
}
/**
* @note Known in other libraries as `torch.where` / `tf.cond`.
*/
object Elementwise extends PolyOp3 {
implicit def ifElementwiseF[TB[_], B, TR[_], R, U](
implicit TB: BoolTensorK[TB, B],
TR: IsRealTensorK[TR, R]
): P[TB[U], TR[U], TR[U], TR[U]] =
new P[TB[U], TR[U], TR[U], TR[U]] {
def name = "If.Elementwise"
def tag = Tag.realTensor[TR, R, U]
def forward(x1: TB[U], x2: TR[U], x3: TR[U]) = ???
def backward1(dy: TR[U], y: TR[U], x1: TB[U], x2: TR[U], x3: TR[U]) = throw new OperatorNotDifferentiableException(this, 1)
def backward2(dy: TR[U], y: TR[U], x1: TB[U], x2: TR[U], x3: TR[U]) = ???
def backward3(dy: TR[U], y: TR[U], x1: TB[U], x2: TR[U], x3: TR[U]) = ???
}
}
}
/**
* Identity function for any expression, but stops gradient backpropagation.
* @author Tongfei Chen
* @since 0.1.0
*/
object StopGrad extends PolyOp1 {
implicit def stopGradF[X]: P[X, X] =
new P[X, X] {
def name = "StopGrad"
def tag = Tag.none[X]
override def differentiable = false
def forward(x: X) = x
def backward(dy: X, y: X, x: X) = throw new OperatorNotDifferentiableException(this, 1)
}
}
| mit |
dlidstrom/MinaGlosor | MinaGlosor.Tool/Program.cs | 4010 | using System;
using System.Linq;
using Castle.Windsor;
using MinaGlosor.Tool.Commands;
using MinaGlosor.Tool.Infrastructure;
using NDesk.Options;
namespace MinaGlosor.Tool
{
internal class Program
{
private static void Main(string[] args)
{
try
{
string username = null;
string password = null;
var showHelp = false;
var optionSet = new OptionSet
{
{
"u=|username=",
"Sets the logon username",
o => username = o
},
{
"p=|password=",
"Sets the logon password",
o => password = o
},
{
"h|help|?",
"Show this help",
o => showHelp = true
}
};
var container = ContainerBuilder.BuildContainer();
var commandArgs = optionSet.Parse(args);
do
{
if (showHelp)
{
break;
}
if (string.IsNullOrWhiteSpace(username))
{
Console.WriteLine("Missing username");
break;
}
if (string.IsNullOrWhiteSpace(password))
{
Console.WriteLine("Missing password");
break;
}
if (commandArgs.Count == 0)
{
Console.WriteLine("Missing command name");
break;
}
var commandName = commandArgs.First();
var commandRunnerType = Type.GetType(string.Format("MinaGlosor.Tool.Commands.{0}CommandRunner", commandName));
if (commandRunnerType == null)
{
Console.WriteLine("Unrecognized command name: '{0}'", commandName);
break;
}
object commandRunner = null;
try
{
commandRunner = container.Resolve(commandName, commandRunnerType);
var runMethod = commandRunner.GetType().GetMethod("Run");
runMethod.Invoke(commandRunner, new[] { username, password, (object)commandArgs.Skip(1).ToArray() });
}
finally
{
if (commandRunner != null) container.Release(commandRunner);
}
return;
#pragma warning disable 162
} while (false);
#pragma warning restore 162
ShowHelp(optionSet, container);
}
catch (OptionException)
{
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void ShowHelp(OptionSet optionSet, IWindsorContainer container)
{
Console.WriteLine("Usage: {0} <options> command", AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("Options:");
optionSet.WriteOptionDescriptions(Console.Out);
Console.WriteLine();
Console.WriteLine("Available commands:");
var commandHandlers = container.Kernel.GetAssignableHandlers(typeof(ICommandRunner));
var commandNames = commandHandlers.Select(x => x.ComponentModel.ComponentName);
Console.WriteLine(string.Join(Environment.NewLine, commandNames));
}
}
} | mit |
OsmondShine/J2SE-DEMO | src/com/xl/designpattern/command/Computer.java | 294 | package com.xl.designpattern.command;
/**
* @author 作者:谢亮
* @data 创建时间:2017-5-25
* @description
* @version 1.0
*/
public class Computer {
public void on(){
System.out.println("开电脑!");
}
public void off(){
System.out.println("关电脑!");
}
}
| mit |
ggaughan/dee | DeeWebDemo.py | 7082 | #!/usr/bin/env python
"""DeeWebDemo: web server and front-end for Dee demoCluster"""
__version__ = "0.12"
__author__ = "Greg Gaughan"
__copyright__ = "Copyright (C) 2007 Greg Gaughan"
__license__ = "MIT" #see Licence.txt for licence information
import re
import webbrowser
import mimetypes
from Dee import *
from demoCluster import *
import web #Public domain: see web.py for details
STATIC_DIRS = ('css', 'js', 'images', 'media')
urls = (
'/(' + '|'.join(STATIC_DIRS) + ')/.*', 'static',
'/', 'index',
)
class session:
def __init__(self):
self.input=""
self.output=""
self.history=[]
self.history_cursor=len(self.history)
self.database=demoCluster.values()[0]
sessions = []
nextSessionId = 0
assign_pattern = re.compile("^(\w+)(\s*)(=|\|=|\-=)(\s*)[^=](.*)")
def getSession():
global nextSessionId
res = None
sessionref = web.cookies()
#web.debugwrite("Before:"+str(sessions))
if sessionref:
try:
web.debugwrite("Using existing session %s" % sessionref.id)
res = sessions[int(sessionref.id)]
except:
web.debugwrite(" - session no longer valid")
pass
if not res:
web.debugwrite("Creating new session %s" % nextSessionId)
if len(sessions) == nextSessionId:
sessions.append(session())
else:
assert False, "Sessions out of sync. with nextSessionId"
res = sessions[nextSessionId]
web.setcookie('id', nextSessionId)
nextSessionId += 1 #todo random!
#web.debugwrite("After:"+str(sessions))
return res
class index:
def GET(self):
s = getSession()
print """<html>
<head>
<title>Dee</title>
<link rel="stylesheet" type="text/css" href="css/plainold.css" media="screen"/>
</head>
<body>
<font face=verdana,tahoma,arial,helvetica,sans>
<h1>%(current_database)s</h1>
<form method="post" action="/">
<p>
<p>Default database:
<select name="database_name">%(database)s</select> <input type="submit" name="command" value="Change database" />
</p>
<input type="submit" name="command" value="<<" />
<input type="submit" name="command" value=">>" />
<input type="submit" name="command" value="Paste Relation template" />
<input type="submit" name="command" value="Paste catalog query" />
<br />
<label for="expression">Expression:</label><br />
<font face=courier>
<textarea name="expression" cols=100 rows=10>%(input)s</textarea>
</font>
<input type="submit" name="command" value="Evaluate" />
</p>
<p>
<font face=courier>
%(output)s
</font>
</p>
</form>
</font>
</body>
</html>
""" % {"current_database":s.database.name,
"database": "\n".join(['<option value="%(database_name)s" %(selected)s>%(database_name)s' % t for t in demoCluster.databases(['database_name']).extend(['selected'], lambda t:{'selected':t.database_name==s.database.name and "selected" or ""}).toTupleList(sort=(True,['database_name']))]),
"input":s.input, "output":s.output}
def POST(self):
s = getSession()
i = web.input()
if i.command == "Evaluate":
inp = ""
exp = i.expression.rstrip()
s.history.append(exp)
s.history_cursor=len(s.history)
exp = exp.replace('\n', ' ').replace('\r', '')
if assign_pattern.match(exp):
try:
exec(exp, globals(), s.database.transactions[s.database.transactionId])
r=""
except Exception, e:
r=e
inp=i.expression
else:
try:
r=eval(exp, globals(), s.database.transactions[s.database.transactionId])
if isinstance(r, Relation):
r="""<div id="itsthetable">%s</div>""" % r.renderHTML()
else:
r=str(web.websafe(r))
except Exception, e:
r=e
inp=i.expression
s.input = inp
s.output = "<b>>>> %s</b><br />%s<br />%s" % (exp, r, s.output)
web.redirect('/')
else:
if i.command == "Paste Relation template":
s.input = """Relation(["a", "b"],
[('one', 1),
('two', 2),
('three', 3),
])"""
elif i.command == "Paste catalog query":
s.input = """relations"""
elif i.command == "<<":
if s.history_cursor>0:
s.history_cursor-=1
s.input = s.history[s.history_cursor]
else:
s.input = i.expression
elif i.command == ">>":
if s.history_cursor < len(s.history)-1:
s.history_cursor+=1
s.input = s.history[s.history_cursor]
else:
s.input = i.expression
elif i.command == "Shutdown":
s.database._dump()
sys.exit() #todo better way?
elif i.command == "Change database":
s.database = demoCluster[i.database_name]
else:
assert False, "Unexpected command"
web.redirect('/')
return
def mime_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
class static:
def GET(self, static_dir=''):
try:
static_file_name = web.context.path.split('/')[-1]
web.header('Content-type', mime_type(static_file_name))
static_file = open('.' + web.context.path, 'rb')
web.ctx.output = static_file
except IOError:
web.notfound()
# For debugging use only
web.internalerror = web.debugerror
if __name__ == "__main__":
open("startPage.html", 'w').write("""
<html>
<head>
<title>Starting</title>
</head>
<body>
<meta HTTP-EQUIV="Refresh" CONTENT="1; URL=http://127.0.0.1:8080">
<h1 align="center">Starting</h1>
</body>
</html>
""")
try:
webbrowser.open("startPage.html", new=0, autoraise=1)
except:
print "Point your browser at http://localhost:8080"
web.run(urls, web.reloader)
| mit |
zbw911/DevLib.EFRepository | Framework/Repository/Dev.Framework.Repository.ContainerAdapter.NInject/Properties/AssemblyInfo.cs | 1835 | // ***********************************************************************************
// Created by zbw911
// 创建于:2012年12月18日 13:28
//
// 修改于:2013年02月18日 18:24
// 文件名:AssemblyInfo.cs
//
// 如果有更好的建议或意见请邮件至zbw911#gmail.com
// ***********************************************************************************
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Kt.Framework.Repository.ContainerAdapter.NInject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Kt.Framework.Repository.ContainerAdapter.NInject")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b80d7b1b-d64e-4089-8f8a-7d2744be7685")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
thread-Chen/BEsystem | src/main/java/com/cqnu/base/mapper/RoleMapper.java | 790 | package com.cqnu.base.mapper;
import com.cqnu.base.domain.Role;
import com.cqnu.base.domain.RoleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface RoleMapper {
long countByExample(RoleExample example);
int deleteByExample(RoleExample example);
int deleteByPrimaryKey(Long id);
int insert(Role record);
int insertSelective(Role record);
List<Role> selectByExample(RoleExample example);
Role selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") Role record, @Param("example") RoleExample example);
int updateByExample(@Param("record") Role record, @Param("example") RoleExample example);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
} | mit |
aterai/java-swing-tips | NewTabButton/src/java/example/CloseTabIcon.java | 1600 | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import javax.swing.*;
class CloseTabIcon implements Icon {
private final Color color;
protected CloseTabIcon(Color color) {
this.color = color;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
g2.setPaint(color);
g2.drawLine(2, 2, 9, 9);
g2.drawLine(2, 3, 8, 9);
g2.drawLine(3, 2, 9, 8);
g2.drawLine(9, 2, 2, 9);
g2.drawLine(9, 3, 3, 9);
g2.drawLine(8, 2, 2, 8);
g2.dispose();
}
@Override public int getIconWidth() {
return 12;
}
@Override public int getIconHeight() {
return 12;
}
}
class PlusIcon implements Icon {
private final Rectangle viewRect = new Rectangle();
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
viewRect.setBounds(c.getBounds());
JComponent jc = c instanceof JComponent ? (JComponent) c : null;
OperaTabViewButtonUI.tabPainter(g2, SwingUtilities.calculateInnerArea(jc, viewRect));
g2.setPaint(Color.WHITE);
int w = viewRect.width;
int a = w / 2;
int b = w / 3;
w -= 2;
g2.drawLine(a, b, a, w - b);
g2.drawLine(a - 1, b, a - 1, w - b);
g2.drawLine(b, a, w - b, a);
g2.drawLine(b, a - 1, w - b, a - 1);
g2.dispose();
}
@Override public int getIconWidth() {
return 24;
}
@Override public int getIconHeight() {
return 24;
}
}
| mit |
Kagami/material-ui | docs/src/pages/discover-more/team/Team.js | 4534 | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import CardMedia from '@material-ui/core/CardMedia';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Github from '@material-ui/docs/svgIcons/GitHub';
import Twitter from '@material-ui/docs/svgIcons/Twitter';
const members = [
{
name: 'Hai Nguyen',
github: 'hai-cea',
twitter: 'haicea',
flag: 'v0.x creator',
city: 'Dallas, Texas, US',
},
{
name: 'Olivier Tassinari',
github: 'oliviertassinari',
twitter: 'olivtassinari',
flag: 'v1.x co-creator',
city: 'Paris, France',
},
{
name: 'Matt Brookes',
github: 'mbrookes',
twitter: 'randomtechdude',
flag: 'Core team',
city: 'London, UK',
},
{
name: 'Kevin Ross',
github: 'rosskevin',
twitter: 'rosskevin',
flag: 'Core team',
city: 'Franklin, Tennessee, US',
},
{
name: 'Sebastian Silbermann',
github: 'eps1lon',
twitter: 'sebsilbermann',
flag: 'Core team',
city: 'Dresden, Germany',
},
{
name: 'Nathan Marks',
github: 'nathanmarks',
flag: 'v1.x co-creator',
city: 'Toronto, ON',
},
{
name: 'Sebastian Sebald',
github: 'sebald',
twitter: 'sebastiansebald',
flag: 'Community partner, TypeScript',
city: 'Freiburg, Germany',
},
{
name: 'Maik Marschner',
github: 'leMaik',
twitter: 'leMaikOfficial',
flag: 'Community partner',
city: 'Hannover, Germany',
},
{
name: 'Oleg Slobodskoi',
github: 'kof',
twitter: 'oleg008',
flag: 'Community partner, JSS',
city: 'Berlin, Germany',
},
{
name: 'Ken Gregory',
github: 'kgregory',
flag: 'Community partner',
city: 'New Jersey, US',
},
{
name: 'Tom Crockett',
github: 'pelotom',
twitter: 'pelotom',
flag: 'Community partner',
city: 'Los Angeles, California, US',
},
];
const styles = theme => ({
details: {
margin: `${theme.spacing.unit}px ${theme.spacing.unit}px ${theme.spacing.unit}px 0`,
},
cover: {
width: theme.spacing.unit * 10,
height: theme.spacing.unit * 10,
margin: theme.spacing.unit * 2,
borderRadius: '50%',
flexShrink: 0,
backgroundColor: theme.palette.background.default,
},
icon: {
fontSize: 18,
padding: theme.spacing.unit,
},
});
function Team(props) {
const { classes } = props;
return (
<Grid container spacing={16}>
{members.map(member => (
<Grid key={member.name} item xs={12} md={6}>
<Paper>
<Grid container wrap="nowrap">
<Grid item>
<CardMedia
className={classes.cover}
image={`https://github.com/${member.github}.png`}
title="Picture"
/>
</Grid>
<Grid item>
<div className={classes.details}>
<Typography component="h2" variant="h5">
{member.name}
</Typography>
<Typography variant="subtitle1" color="textSecondary">
{member.flag}
</Typography>
<Typography color="textSecondary">{member.city}</Typography>
<Grid container>
{member.github && (
<IconButton
aria-label="GitHub"
component="a"
href={`https://github.com/${member.github}`}
className={classes.icon}
>
<Github fontSize="inherit" />
</IconButton>
)}
{member.twitter && (
<IconButton
aria-label="Twitter"
component="a"
href={`https://twitter.com/${member.twitter}`}
className={classes.icon}
>
<Twitter fontSize="inherit" />
</IconButton>
)}
</Grid>
</div>
</Grid>
</Grid>
</Paper>
</Grid>
))}
</Grid>
);
}
Team.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Team);
| mit |
ArnoVanDerVegt/wheel | js/shared/routes/device/SpikeRoutes.js | 3240 | /**
* Wheel, copyright (c) 2020 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const constants = require('../../device/spike/constants');
exports.SpikeRoutes = class {
constructor(opts) {
this._spike = opts.spike;
this._serialPortConstructor = opts.serialPortConstructor;
}
connect(req, res) {
let deviceName = req.body.deviceName;
let layerIndex = this._spike.connect(deviceName);
res.send(JSON.stringify({
connecting: (layerIndex !== -1),
deviceName: deviceName,
layerIndex: layerIndex
}));
}
disconnect(req, res) {
this._spike.disconnect(() => {});
res.send(JSON.stringify({}));
}
connecting(req, res) {
let connected = this._spike.getConnected();
let state = {};
if (connected) {
state = this._spike.getState();
}
res.send(JSON.stringify({
connected: connected,
state: state
}));
}
connected(req, res) {
res.send(JSON.stringify({connected: this._spike.getConnected()}));
}
update(req, res) {
let result = {error: false, connected: true};
let queue = (typeof req.body.queue === 'string') ? JSON.parse(req.body.queue) : req.body.queue;
let messagesReceived = {};
let spike = this._spike;
spike.setActiveLayerCount(req.body.activeLayerCount);
queue.forEach((params) => {
spike.module(params.module, params.command, params.data);
messagesReceived[params.messageId] = true;
});
result.state = spike.getState();
result.messagesReceived = messagesReceived;
res.send(JSON.stringify(result));
}
_createTimeoutCallback(res) {
let done = false;
let timeout = null;
let callback = function(success) {
if (done) {
return;
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
done = true;
res.send(JSON.stringify({error: !success}));
};
timeout = setTimeout(callback, 500);
return callback;
}
stopAllMotors(req, res) {
let result = {success: true};
let layerCount = req.body.layerCount;
let brake = req.body.brake ? 1 : 0;
let spike = this._spike;
for (let i = 0; i < layerCount; i++) {
for (let j = 0; j < 4; j++) {
spike.motorStop(i, j, brake);
}
}
res.send(JSON.stringify(result));
}
stopPolling(req, res) {
this._spike.stopPolling();
res.send(JSON.stringify({success: true}));
}
resumePolling(req, res) {
this._spike.resumePolling();
res.send(JSON.stringify({success: true}));
}
setMode(req, res) {
let body = req.body;
this._spike.setMode(body.layer, body.port, body.mode);
res.send(JSON.stringify({success: true}));
}
};
| mit |
Zhang-RQ/OI_DataBase | 51NOD/1565.cpp | 2627 | #include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cassert>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MAXN=262145<<1;
const double PI=acos(-1);
const double EPS=1E-8;
struct Complex{
double real,imag;
Complex(){}
Complex(double _,double __){real=_;imag=__;}
inline Complex operator + (const Complex &rhs) const {return Complex(real+rhs.real,imag+rhs.imag);}
inline Complex operator - (const Complex &rhs) const {return Complex(real-rhs.real,imag-rhs.imag);}
inline Complex operator * (const Complex &rhs) const {return Complex(real*rhs.real-imag*rhs.imag,real*rhs.imag+imag*rhs.real);}
}a[MAXN],b[MAXN];
int rev[MAXN],n,m,k,cc[4],mp[128],t[MAXN];
char s1[MAXN],s2[MAXN];
bool ss1[4][MAXN],ss2[4][MAXN];
void FFT(Complex *c,int n,int f)
{
for(int i=0;i<n;i++) if(i>rev[i]) swap(c[i],c[rev[i]]);
for(int i=2;i<=n;i<<=1)
{
Complex wn(cos(2*PI/i),f*sin(2*PI/i));
for(int j=0;j<n;j+=i)
{
Complex w(1,0);
for(int k=0;k<(i>>1);k++)
{
Complex u=c[j+k],t=c[j+k+(i>>1)]*w;
c[j+k]=u+t;c[j+k+(i>>1)]=u-t;
w=w*wn;
}
}
}
if(f==-1) for(int i=0;i<n;i++) c[i].real/=n;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
scanf("%s%s",s1,s2);
mp['A']=0;mp['T']=1;mp['C']=2;mp['G']=3;
for(int i=0;i<n;i++) s1[i]=mp[s1[i]];
for(int i=0;i<m;i++) s2[i]=mp[s2[i]];
cc[0]=cc[1]=cc[2]=cc[3]=k;
for(int i=0;i<n;i++)
{
cc[0]++;cc[1]++;cc[2]++;cc[3]++;
cc[s1[i]]=0;
for(int j=0;j<4;j++) if(cc[j]<=k) ss1[j][i]=1;
}
cc[0]=cc[1]=cc[2]=cc[3]=k;
for(int i=n-1;i>=0;i--)
{
cc[0]++;cc[1]++;cc[2]++;cc[3]++;
cc[s1[i]]=0;
for(int j=0;j<4;j++) if(cc[j]<=k) ss1[j][i]=1;
}
for(int i=0;i<m;i++) ss2[s2[i]][i]=1;
int tot=1,lg2=0;
while(n+m>=tot) tot<<=1,lg2++;
for(int i=0;i<tot;i++)
rev[i]=(rev[i>>1]>>1)|((i&1)<<(lg2-1));
for(int i=0;i<4;i++)
{
memset(a,0,sizeof a);memset(b,0,sizeof b);
for(int j=0;j<n;j++) a[j].real=1.0*ss1[i][j];
for(int j=0;j<m;j++) b[j].real=1.0*ss2[i][m-j-1];
FFT(a,tot,1);FFT(b,tot,1);
for(int j=0;j<tot;j++) a[j]=a[j]*b[j];
FFT(a,tot,-1);
for(int j=0;j<tot;j++) t[j]+=(int)(a[j].real+0.5);
}
int ans=0;
for(int i=m-1;i<n+m-1;i++) if(t[i]==m) ans++;
printf("%d\n",ans);
}
| mit |
therightsol/test2016 | application/views/cause-details.php | 27653 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Save a Soul | Project</title>
<!-- Stylesheets -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- Responsive -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link href="css/responsive.css" rel="stylesheet">
<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<!--[if lt IE 9]><script src="js/respond.js"></script><![endif]-->
</head>
<body>
<div class="page-wrapper">
<!-- Preloader -->
<div class="preloader"></div>
<!-- Main Header -->
<header class="main-header">
<!-- Header Upper -->
<div class="header-upper">
<div class="auto-container clearfix">
<!-- Logo -->
<div class="logo">
<a href="index-2.html"><img src="images/project_logo.png" alt="logo"></a>
</div>
<!--Info Outer-->
<div class="info-outer">
<!--Info Box-->
<div class="info-box">
<div class="icon"><span class="flaticon-interface"></span></div>
<strong>EMAIL</strong>
<a href="mailto:alishanvr@gmail.com">alishanvr@gmail.com</a>
</div>
<!--Info Box-->
<div class="info-box">
<div class="icon"><span class="flaticon-technology"></span></div>
<strong>Call Now</strong>
<a class="phone" href="#">(0800) 123-456-78</a>
</div>
<!--Info Box-->
<div class="info-box social-box">
<div class="social-links-one clearfix">
<a href="#" class="facebook img-circle"><span class="fa fa-facebook-f"></span></a>
<a href="#" class="twitter img-circle"><span class="fa fa-twitter"></span></a>
<a href="#" class="google-plus img-circle"><span class="fa fa-google-plus"></span></a>
<a href="#" class="linkedin img-circle"><span class="fa fa-linkedin"></span></a>
</div>
</div>
</div>
</div>
</div><!-- Header Top End -->
<!-- Header Lower -->
<div class="header-lower">
<div class="auto-container clearfix">
<!--Outer Box-->
<div class="outer-box clearfix">
<!--Search Box-->
<div class="search-box">
<!--Toggle Btn-->
<div class="search-box-toggle"><span class="fa fa-search"></span></div>
<form method="post" action="http://wp1.themexlab.com/html/giving-hands/index.html">
<div class="form-group">
<input type="search" name="search-field" value="" placeholder="Search here...">
<button type="submit"><span class="icon flaticon-tool"></span></button>
</div>
</form>
</div>
<!-- Main Menu -->
<nav class="main-menu">
<div class="navbar-header">
<!-- Toggle Button -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse clearfix">
<ul class="navigation">
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li class="dropdown current"><a href="causes-grid.html">Cause</a>
<ul class="submenu-dropdown">
<li><a href="causes-grid.html">Cause Grid View</a></li>
<li><a href="causes-list.html">Cause List View</a></li>
<li><a href="cause-details.html">Cause Details</a></li>
</ul>
</li>
<li class="dropdown"><a href="volunteers.html">Pages</a>
<ul class="submenu-dropdown">
<li><a href="volunteers.html">Our Volunteers</a></li>
<li class="dropdown"><a href="event-two-column.html">Events</a>
<ul class="submenu-dropdown">
<li><a href="event-two-column.html">Events Two Column</a></li>
<li><a href="event-details.html">Event Details</a></li>
</ul>
</li>
<li><a href="donations.html">Donations</a></li>
<li><a href="error.html">404 Page</a></li>
</ul>
</li>
<li class="dropdown"><a href="event-two-column.html">Events</a>
<ul class="submenu-dropdown">
<li><a href="event-two-column.html">Events Two Column</a></li>
<li><a href="event-details.html">Event Details</a></li>
</ul>
</li>
<li class="dropdown"><a href="gallery-fullwidth.html">Gallery</a>
<ul class="submenu-dropdown">
<li><a href="gallery-fullwidth.html">Gallery Fullwidth</a></li>
<li><a href="gallery-four-column.html">Gallery Four Column</a></li>
</ul>
</li>
<li><a href="contact.html">Contact Us</a></li>
</ul>
</div>
</nav><!-- Main Menu End-->
</div>
</div>
</div><!-- Header Lower End-->
</header><!--End Main Header -->
<!--Page Title-->
<section class="page-title" style="background-image:url(images/background/page-title-bg.jpg);">
<div class="auto-container">
<div class="sec-title">
<h1>Cause <span class="normal-font">Details</span></h1>
<div class="bread-crumb"><a href="#">Home</a> / <a href="#" class="current">Single Cause</a></div>
</div>
</div>
</section>
<!--Sidebar Page-->
<div class="sidebar-page">
<div class="auto-container">
<div class="row clearfix">
<!--Content Side-->
<div class="col-lg-9 col-md-8 col-sm-12 col-xs-12">
<!--Causes Details Section-->
<section class="causes-section cause-details no-padd-bottom no-padd-top">
<!--Cause Column-->
<div class="column cause-column padd-right-20">
<article class="inner-box">
<figure class="image-box">
<a href="#"><img src="images/resource/featured-image-25.jpg" alt=""></a>
</figure>
<div class="content-box">
<div class="row clearfix">
<div class="col-md-6 col-sm-12">
<div class="donation-progress-box">
<div class="donation-values">
Donation : <span class="value">$68,214</span> / <span class="value">$85,870</span>
</div>
<div class="donation-progress-bar">
<div class="inner-bar" data-value-collected="68214" data-value-total="85870"></div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-12 pull-right text-right padd-top-20"><a href="#" class="theme-btn btn-style-two">Donate</a></div>
</div>
<hr>
<div class="sec-title margin-bott-20">
<h2>Child Education Help</h2>
</div>
<div class="bigger-text">
<p>Lorem ipsum dolor sit amet, quo odio atqui tamquam eu, duo ex amet elitr. <strong>Ne essent feugiat vim, et soluta reprimique instructior mel</strong>, ne nonumes deserunt. Vix in dico vivendum forensibus. <strong>Munere tamquam referrentur ad duo</strong>, ei tibique dissentias.</p>
<br>
</div>
<div class="text">
<p>Lorem ipsum dolor sit amet, et electram comprehensam sit. Quo an splendide siniferman vix sententiae instructior laudem corrumpit dolor amet.</p>
<p>alienum corrumpit ullamcorper. Vel ea fabulas instructior, agam falli sit an.Ad cum amet graeco consequat, sed ei veri novum appellantur. Qui in quod ubique euismod, consul seo noster disputationi eos no, nec te latine repudiare. Te pro dolor volutpat.</p>
<br>
</div>
<ul class="styled-list-one">
<li>Lorem ipsum dolor sit amet, usu an quem augue admodum. </li>
<li>Lorem ipsum dolor sit amet, usu an quem augue admodum. </li>
<li>Lorem ipsum dolor sit amet, usu an quem augue admodum. </li>
<li>Lorem ipsum dolor sit amet, usu an quem augue admodum. </li>
</ul>
</div>
</article>
</div>
</section>
</div>
<!--Content Side-->
<!--Sidebar-->
<div class="col-lg-3 col-md-4 col-sm-12 col-xs-12">
<aside class="sidebar">
<!-- Search Form -->
<div class="widget search-box">
<form method="post" action="http://wp1.themexlab.com/html/giving-hands/index.html">
<div class="form-group">
<input type="search" name="search-field" value="" placeholder="Search">
<button type="submit"><span class="icon flaticon-tool"></span></button>
</div>
</form>
</div>
<!-- Recent Posts -->
<div class="widget recent-posts wow fadeInUp" data-wow-delay="0ms" data-wow-duration="1500ms">
<div class="sidebar-title"><h3>Latest Posts</h3></div>
<div class="post">
<h4><a href="#">Lorem ipsum dolor sit amet consetetur</a></h4>
<div class="post-info"><span class="icon fa fa-clock-o"></span> 11/01/2015 </div>
</div>
<div class="post">
<h4><a href="#">Lorem ipsum dolor sit amet consetetur</a></h4>
<div class="post-info"><span class="icon fa fa-clock-o"></span> 11/01/2015 </div>
</div>
<div class="post">
<h4><a href="#">Lorem ipsum dolor sit amet consetetur</a></h4>
<div class="post-info"><span class="icon fa fa-clock-o"></span> 11/01/2015 </div>
</div>
</div>
<!-- Popular Categories -->
<div class="widget popular-categories wow fadeInUp" data-wow-delay="0ms" data-wow-duration="1500ms">
<div class="sidebar-title"><h3>Categories</h3></div>
<ul class="list">
<li><a class="clearfix" href="#">Internet Marketing</a></li>
<li><a class="clearfix" href="#">Search Engine Optimization</a></li>
<li><a class="clearfix" href="#">Webdevelopement</a></li>
<li><a class="clearfix" href="#">Creative Strategies</a></li>
<li><a class="clearfix" href="#">Webhosting Services</a></li>
</ul>
</div>
<!-- Archives -->
<div class="widget archives-list wow fadeInUp" data-wow-delay="0ms" data-wow-duration="1500ms">
<div class="sidebar-title"><h3>Archives</h3></div>
<ul class="list">
<li><a class="clearfix" href="#"><span class="txt pull-left">2016 </span> <span class="count pull-right">(85)</span></a></li>
<li><a class="clearfix" href="#"><span class="txt pull-left">2015</span> <span class="count pull-right">(280)</span></a></li>
<li><a class="clearfix" href="#"><span class="txt pull-left">2014</span> <span class="count pull-right">(191)</span></a></li>
<li><a class="clearfix" href="#"><span class="txt pull-left">2013</span> <span class="count pull-right">(233)</span></a></li>
<li><a class="clearfix" href="#"><span class="txt pull-left">2012</span> <span class="count pull-right">(369)</span></a></li>
</ul>
</div>
<!-- Popular Tags -->
<div class="widget popular-tags">
<div class="sidebar-title"><h3>KeyWords</h3></div>
<a href="#">Child</a>
<a href="#">Water</a>
<a href="#">Donate</a>
<a href="#">Money</a>
<a href="#">Volunteer</a>
</div>
</aside>
</div>
<!--Sidebar-->
</div>
</div>
</div>
<!--Default Section-->
<section class="default-section no-padd-top">
<div class="auto-container">
<div class="sec-title margin-bott-30">
<h2><span class="text-capitalize">How can you <span class="normal-font">help us ?</span></span></h2>
</div>
<div class="row clearfix">
<!--Column-->
<div class="column col-md-4 col-sm-6 col-xs-12">
<!--Icon Box-->
<div class="icon-heading-column">
<article class="inner-box">
<div class="column-count">01</div>
<h3><span class="icon"><img src="images/icons/icon-4.png" alt=""></span> Donator</h3>
<p>Lorem ipsum dolor sit amet amet audiam copiosaei mei purto time am mea ne ei <a href="#" class="read-more">Read More</a></p>
</article>
</div>
</div>
<!--Column-->
<div class="column col-md-4 col-sm-6 col-xs-12">
<!--Icon Box-->
<div class="icon-heading-column">
<article class="inner-box">
<div class="column-count">02</div>
<h3><span class="icon"><img src="images/icons/icon-5.png" alt=""></span> Fundrising</h3>
<p>Lorem ipsum dolor sit amet amet audiam copiosaei mei purto time am mea ne ei <a href="#" class="read-more">Read More</a></p>
</article>
</div>
</div>
<!--Column-->
<div class="column col-md-4 col-sm-6 col-xs-12">
<!--Icon Box-->
<div class="icon-heading-column">
<article class="inner-box">
<div class="column-count">03</div>
<h3><span class="icon"><img src="images/icons/icon-6.png" alt=""></span> Volunteer</h3>
<p>Lorem ipsum dolor sit amet amet audiam copiosaei mei purto time am mea ne ei <a href="#" class="read-more">Read More</a></p>
</article>
</div>
</div>
</div>
</div>
</section>
<!--Intro Section-->
<section class="subscribe-intro">
<div class="auto-container">
<div class="row clearfix">
<!--Column-->
<div class="column col-md-9 col-sm-12 col-xs-12">
<h2>Subcribe for Newsletter</h2>
There are many variations of passages of Lorem Ipsum available but the majority have
</div>
<!--Column-->
<div class="column col-md-3 col-sm-12 col-xs-12">
<div class="text-right padd-top-20">
<a href="#" class="theme-btn btn-style-three">Subscribe Now</a>
</div>
</div>
</div>
</div>
</section>
<!--Main Footer-->
<footer class="main-footer" style="background-image:url(images/background/footer-bg.jpg);">
<!--Footer Upper-->
<div class="footer-upper">
<div class="auto-container">
<div class="row clearfix">
<!--Two 4th column-->
<div class="col-md-6 col-sm-12 col-xs-12">
<div class="row clearfix">
<div class="col-lg-8 col-sm-6 col-xs-12 column">
<div class="footer-widget about-widget">
<div class="logo"><a href="index-2.html"><img src="images/project_logo.png" class="img-responsive" alt=""></a></div>
<div class="text">
<p>Lorem ipsum dolor sit amet, eu me seo <br>laboramus, iudico dummy text.</p>
</div>
<ul class="contact-info">
<li><span class="icon fa fa-map-marker"></span> 60 Grant Ave. Carteret NJ 0708</li>
<li><span class="icon fa fa-phone"></span> (880) 1723801729</li>
<li><span class="icon fa fa-envelope-o"></span> example@gmail.com</li>
</ul>
<div class="social-links-two clearfix">
<a href="#" class="facebook img-circle"><span class="fa fa-facebook-f"></span></a>
<a href="#" class="twitter img-circle"><span class="fa fa-twitter"></span></a>
<a href="#" class="google-plus img-circle"><span class="fa fa-google-plus"></span></a>
<a href="#" class="linkedin img-circle"><span class="fa fa-pinterest-p"></span></a>
<a href="#" class="linkedin img-circle"><span class="fa fa-linkedin"></span></a>
</div>
</div>
</div>
<!--Footer Column-->
<div class="col-lg-4 col-sm-6 col-xs-12 column">
<h2>Our Project</h2>
<div class="footer-widget links-widget">
<ul>
<li><a href="#">Water Surve</a></li>
<li><a href="#">Education for all</a></li>
<li><a href="#">Treatment</a></li>
<li><a href="#">Food Serving</a></li>
<li><a href="#">Cloth</a></li>
<li><a href="#">Selter Project</a></li>
<li><a href="#">Help Orphan</a></li>
</ul>
</div>
</div>
</div>
</div><!--Two 4th column End-->
<!--Two 4th column-->
<div class="col-md-6 col-sm-12 col-xs-12">
<div class="row clearfix">
<!--Footer Column-->
<div class="col-lg-7 col-sm-6 col-xs-12 column">
<div class="footer-widget news-widget">
<h2>Latest News</h2>
<div class="news-post">
<div class="icon"></div>
<div class="news-content"><a href="#">If you need a crown or lorem an implant you will pay it gap it</a></div>
<div class="time">July 2, 2014</div>
</div>
<div class="news-post">
<div class="icon"></div>
<div class="news-content"><a href="#">If you need a crown or lorem an implant you will pay it gap it</a></div>
<div class="time">July 2, 2014</div>
</div>
<div class="news-post">
<div class="icon"></div>
<div class="news-content"><a href="#">If you need a crown or lorem an implant you will pay it gap it</a></div>
<div class="time">July 2, 2014</div>
</div>
</div>
</div>
<!--Footer Column-->
<div class="col-lg-5 col-sm-6 col-xs-12 column">
<div class="footer-widget links-widget">
<h2>Quick Links</h2>
<ul>
<li><a href="#">Water Surve</a></li>
<li><a href="#">Education for all</a></li>
<li><a href="#">Treatment</a></li>
<li><a href="#">Food Serving</a></li>
<li><a href="#">Cloth</a></li>
<li><a href="#">Selter Project</a></li>
<li><a href="#">Help Orphan</a></li>
</ul>
</div>
</div>
</div>
</div><!--Two 4th column End-->
</div>
</div>
</div>
<!--Footer Bottom-->
<div class="footer-bottom">
<div class="auto-container clearfix">
<!--Copyright-->
<div class="copyright text-center">Copyright 2016 © Designed by <a href="http://therightsol.com/">TR Solutions</a></div>
</div>
</div>
</footer>
</div>
<!--End pagewrapper-->
<!--Scroll to top-->
<div class="scroll-to-top scroll-to-target" data-target=".main-header"><span class="fa fa-arrow-up"></span></div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/revolution.min.js"></script>
<script src="js/jquery.appear.js"></script>
<script src="js/knob.js"></script>
<script src="js/jquery.fancybox.pack.js"></script>
<script src="js/jquery.fancybox-media.js"></script>
<script src="js/validate.js"></script>
<script src="js/wow.js"></script>
<script src="js/script.js"></script>
</body>
</html> | mit |
tlanders/javase8 | src/main/java/effectivejava/chapter7/Sublists.java | 674 | package effectivejava.chapter7;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Sublists {
public static <E> Stream<List<E>> of(List<E> list) {
return Stream.concat(Stream.of(Collections.emptyList()),
prefixes(list).flatMap(Sublists::suffixes));
}
public static <E> Stream<List<E>> prefixes(List<E> list) {
return IntStream.rangeClosed(0, list.size()).mapToObj(i -> list.subList(0, i));
}
public static <E> Stream<List<E>> suffixes(List<E> list) {
return IntStream.rangeClosed(0, list.size() - 1).mapToObj(i -> list.subList(i, list.size()));
}
}
| mit |
tenbits/LibJS | html2mask/index.build/script.js | 356594 | (function(global) {
var helper = {
each: function(arr, fn) {
if (arr instanceof Array) {
for (var i = 0; i < arr.length; i++) fn(arr[i]);
return;
}
fn(arr);
},
extendProto: function(proto, x) {
var prototype;
if (null == x) return;
switch (typeof x) {
case "function":
prototype = x.prototype;
break;
case "object":
prototype = x;
break;
default:
return;
}
for (var key in prototype) proto[key] = prototype[key];
},
extendClass: function(_class, _base, _extends, original) {
if ("object" !== typeof original) return;
this.extendPrototype = null == original["__proto__"] ? this.protoLess : this.proto;
this.extendPrototype(_class, _base, _extends, original);
},
proto: function(_class, _base, _extends, original) {
var prototype = original, proto = original;
prototype.constructor = _class.prototype.constructor;
if (null != _extends) {
proto["__proto__"] = {};
helper.each(_extends, function(x) {
helper.extendProto(proto["__proto__"], x);
});
proto = proto["__proto__"];
}
if (null != _base) proto["__proto__"] = _base.prototype;
_class.prototype = prototype;
},
protoLess: function(_class, _base, _extends, original) {
if (null != _base) {
var proto = {}, tmp = function() {};
tmp.prototype = _base.prototype;
_class.prototype = new tmp();
_class.prototype.constructor = _class;
}
helper.extendProto(_class.prototype, original);
if (null != _extends) helper.each(_extends, function(x) {
var a = {};
helper.extendProto(a, x);
delete a.constructor;
for (var key in a) _class.prototype[key] = a[key];
});
}
};
var Class = function(data) {
var _base = data.Base, _extends = data.Extends, _static = data.Static, _construct = data.Construct, _class = null, key;
if (null != _base) delete data.Base;
if (null != _extends) delete data.Extends;
if (null != _static) delete data.Static;
if (null != _construct) delete data.Construct;
if (null == _base && null == _extends) {
if (null == _construct) _class = function() {}; else _class = _construct;
data.constructor = _class.prototype.constructor;
if (null != _static) for (key in _static) _class[key] = _static[key];
_class.prototype = data;
return _class;
}
_class = function() {
if (null != _extends) {
var isarray = _extends instanceof Array, length = isarray ? _extends.length : 1, x = null;
for (var i = 0; isarray ? i < length : i < 1; i++) {
x = isarray ? _extends[i] : _extends;
if ("function" === typeof x) x.apply(this, arguments);
}
}
if (null != _base) _base.apply(this, arguments);
if (null != _construct) {
var r = _construct.apply(this, arguments);
if (null != r) return r;
}
return this;
};
if (null != _static) for (key in _static) _class[key] = _static[key];
helper.extendClass(_class, _base, _extends, data);
data = null;
_static = null;
return _class;
};
Class.bind = function(cntx) {
var arr = arguments, i = 1, length = arguments.length, key;
for (;i < length; i++) {
key = arr[i];
cntx[key] = cntx[key].bind(cntx);
}
return cntx;
};
global.Class = Class;
})("undefined" === typeof window ? global : window);
var __eval = function(source, include) {
"use strict";
var iparams = include && include.route.params;
return eval.call(window, source);
};
(function(global, document) {
"use strict";
var bin = {}, isWeb = !!(global.location && global.location.protocol && /^https?:/.test(global.location.protocol)), cfg = {
eval: null == document
}, handler = {}, hasOwnProp = {}.hasOwnProperty, XMLHttpRequest = global.XMLHttpRequest;
var Helper = {
uri: {
getDir: function(url) {
var index = url.lastIndexOf("/");
return index == -1 ? "" : url.substring(index + 1, -index);
},
resolveCurrent: function() {
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length - 1].getAttribute("src");
},
resolveUrl: function(url, parent) {
if (cfg.path && "/" == url[0]) url = cfg.path + url.substring(1);
switch (url.substring(0, 5)) {
case "file:":
case "http:":
return url;
}
if ("./" === url.substring(0, 2)) url = url.substring(2);
if ("/" === url[0]) {
if (false === isWeb || true === cfg.lockedToFolder) url = url.substring(1);
} else if (null != parent && null != parent.location) url = parent.location + url;
while (url.indexOf("../") > -1) url = url.replace(/[^\/]+\/\.\.\//, "");
return url;
}
},
extend: function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
if ("function" === typeof source) source = source.prototype;
for (var key in source) target[key] = source[key];
}
return target;
},
invokeEach: function(arr, args) {
if (null == arr) return;
if (arr instanceof Array) for (var i = 0, x, length = arr.length; i < length; i++) {
x = arr[i];
if ("function" === typeof x) null != args ? x.apply(this, args) : x();
}
},
doNothing: function(fn) {
"function" == typeof fn && fn();
},
reportError: function(e) {
console.error("IncludeJS Error:", e, e.message, e.url);
"function" == typeof handler.onerror && handler.onerror(e);
},
ensureArray: function(obj, xpath) {
if (!xpath) return obj;
var arr = xpath.split(".");
while (arr.length - 1) {
var key = arr.shift();
obj = obj[key] || (obj[key] = {});
}
return obj[arr.shift()] = [];
}
}, XHR = function(resource, callback) {
var xhr = new XMLHttpRequest(), s = Date.now();
xhr.onreadystatechange = function() {
4 == xhr.readyState && callback && callback(resource, xhr.responseText);
};
xhr.open("GET", "object" === typeof resource ? resource.url : resource, true);
xhr.send();
};
var RoutesLib = function() {
var routes = {}, regexpAlias = /([^\\\/]+)\.\w+$/;
return {
register: function(namespace, route) {
routes[namespace] = route instanceof Array ? route : route.split(/[\{\}]/g);
},
resolve: function(namespace, template) {
var questionMark = template.indexOf("?"), aliasIndex = template.indexOf("::"), alias, path, params, route, i, x, length;
if (~aliasIndex) {
alias = template.substring(aliasIndex + 2);
template = template.substring(0, aliasIndex);
}
if (~questionMark) {
var arr = template.substring(questionMark + 1).split("&");
params = {};
for (i = 0, length = arr.length; i < length; i++) {
x = arr[i].split("=");
params[x[0]] = x[1];
}
template = template.substring(0, questionMark);
}
template = template.split("/");
route = routes[namespace];
if (null == route) return {
path: template.join("/"),
params: params,
alias: alias
};
path = route[0];
for (i = 1; i < route.length; i++) if (0 === i % 2) path += route[i]; else {
var index = route[i] << 0;
if (index > template.length - 1) index = template.length - 1;
path += template[index];
if (i == route.length - 2) for (index++; index < template.length; index++) path += "/" + template[index];
}
return {
path: path,
params: params,
alias: alias
};
},
each: function(type, includeData, fn, namespace, xpath) {
var key;
if (null == includeData) {
console.error("Include Item has no Data", type, namespace);
return;
}
if ("lazy" == type && null == xpath) {
for (key in includeData) this.each(type, includeData[key], fn, null, key);
return;
}
if (includeData instanceof Array) {
for (var i = 0; i < includeData.length; i++) this.each(type, includeData[i], fn, namespace, xpath);
return;
}
if ("object" === typeof includeData) {
for (key in includeData) if (hasOwnProp.call(includeData, key)) this.each(type, includeData[key], fn, key, xpath);
return;
}
if ("string" === typeof includeData) {
var x = this.resolve(namespace, includeData);
if (namespace) namespace += "." + includeData;
fn(namespace, x, xpath);
return;
}
console.error("Include Package is invalid", arguments);
},
getRoutes: function() {
return routes;
},
parseAlias: function(route) {
var path = route.path, result = regexpAlias.exec(path);
return result && result[1];
}
};
};
var Routes = RoutesLib();
var Events = function(document) {
if (null == document) return {
ready: Helper.doNothing,
load: Helper.doNothing
};
var readycollection = [], loadcollection = null, timer = Date.now();
document.onreadystatechange = function() {
if (false === /complete|interactive/g.test(document.readyState)) return;
if (timer) console.log("DOMContentLoader", document.readyState, Date.now() - timer, "ms");
Events.ready = Helper.doNothing;
Helper.invokeEach(readycollection);
readycollection = null;
if ("complete" == document.readyState) {
Events.load = Helper.doNothing;
Helper.invokeEach(loadcollection);
loadcollection = null;
}
};
return {
ready: function(callback) {
readycollection.unshift(callback);
},
load: function(callback) {
(loadcollection || (loadcollection = [])).unshift(callback);
}
};
}(document);
var IncludeDeferred = function() {
this.callbacks = [];
this.state = 0;
};
IncludeDeferred.prototype = {
on: function(state, callback) {
state <= this.state ? callback(this) : this.callbacks[this.state < 3 ? "unshift" : "push"]({
state: state,
callback: callback
});
return this;
},
readystatechanged: function(state) {
var i, length, x, currentInclude;
if (state > this.state) this.state = state;
if (3 === this.state) {
var includes = this.includes;
if (null != includes && includes.length) for (i = 0; i < includes.length; i++) if (4 != includes[i].resource.state) return;
this.state = 4;
}
i = 0;
length = this.callbacks.length;
if (0 === length) return;
if ("js" === this.type && 4 === this.state) {
currentInclude = global.include;
global.include = this;
}
for (;i < length; i++) {
x = this.callbacks[i];
if (null == x || x.state > this.state) continue;
this.callbacks.splice(i, 1);
length--;
i--;
x.callback(this);
if (this.state < 4) break;
}
if (null != currentInclude) global.include = currentInclude;
},
ready: function(callback) {
var that = this;
return this.on(4, function() {
Events.ready(function() {
that.resolve(callback);
});
});
},
loaded: function(callback) {
return this.on(4, function() {
Events.load(callback);
});
},
done: function(callback) {
var that = this;
return this.on(4, function() {
that.resolve(callback);
});
},
resolve: function(callback) {
var includes = this.includes, length = null == includes ? 0 : includes.length;
if (length > 0 && null == this.response) {
this.response = {};
var resource, route;
for (var i = 0, x; i < length; i++) {
x = includes[i];
resource = x.resource;
route = x.route;
if (!resource.exports) continue;
var type = resource.type;
switch (type) {
case "js":
case "load":
case "ajax":
var alias = route.alias || Routes.parseAlias(route), obj = "js" == type ? this.response : this.response[type] || (this.response[type] = {});
if (alias) {
obj[alias] = resource.exports;
break;
} else console.warn("Resource Alias is Not defined", resource);
}
}
}
callback(this.response);
}
};
var Include = function() {
function embedPlugin(source) {
eval(source);
}
function enableModules() {
if ("undefined" === typeof Object.defineProperty) {
console.warn("Browser do not support Object.defineProperty");
return;
}
Object.defineProperty(global, "module", {
get: function() {
return global.include;
}
});
Object.defineProperty(global, "exports", {
get: function() {
var current = global.include;
return current.exports || (current.exports = {});
},
set: function(exports) {
global.include.exports = exports;
}
});
}
var Include = function() {};
Include.prototype = {
setCurrent: function(data) {
var resource = new Resource("js", {
path: data.id
}, data.namespace, null, null, data.id);
if (4 != resource.state) console.error("Current Resource should be loaded");
resource.state = 3;
global.include = resource;
},
incl: function(type, pckg) {
if (this instanceof Resource) return this.include(type, pckg);
var r = new Resource();
r.type = "js";
return r.include(type, pckg);
},
js: function(pckg) {
return this.incl("js", pckg);
},
css: function(pckg) {
return this.incl("css", pckg);
},
load: function(pckg) {
return this.incl("load", pckg);
},
ajax: function(pckg) {
return this.incl("ajax", pckg);
},
embed: function(pckg) {
return this.incl("embed", pckg);
},
lazy: function(pckg) {
return this.incl("lazy", pckg);
},
cfg: function(arg) {
switch (typeof arg) {
case "object":
for (var key in arg) {
cfg[key] = arg[key];
if ("modules" == key && true === arg[key]) enableModules();
}
break;
case "string":
if (1 == arguments.length) return cfg[arg];
if (2 == arguments.length) cfg[arg] = arguments[1];
break;
case "undefined":
return cfg;
}
return this;
},
routes: function(arg) {
if (null == arg) return Routes.getRoutes();
for (var key in arg) Routes.register(key, arg[key]);
return this;
},
promise: function(namespace) {
var arr = namespace.split("."), obj = global;
while (arr.length) {
var key = arr.shift();
obj = obj[key] || (obj[key] = {});
}
return obj;
},
register: function(_bin) {
for (var key in _bin) for (var i = 0; i < _bin[key].length; i++) {
var id = _bin[key][i].id, url = _bin[key][i].url, namespace = _bin[key][i].namespace, resource = new Resource();
resource.state = 4;
resource.namespace = namespace;
resource.type = key;
if (url) {
if ("/" == url[0]) url = url.substring(1);
resource.location = Helper.uri.getDir(url);
}
switch (key) {
case "load":
case "lazy":
var container = document.querySelector("#includejs-" + id.replace(/\W/g, ""));
if (null == container) {
console.error('"%s" Data was not embedded into html', id);
return;
}
resource.exports = container.innerHTML;
}
(bin[key] || (bin[key] = {}))[id] = resource;
}
},
instance: function() {
return new Resource();
},
getResource: function(url, type) {
var id = ("/" == url[0] ? "" : "/") + url;
if (null != type) return bin[type][id];
for (var key in bin) if (bin[key].hasOwnProperty(id)) return bin[key][id];
return null;
},
plugin: function(pckg, callback) {
var urls = [], length = 0, j = 0, i = 0, onload = function(url, response) {
j++;
embedPlugin(response);
if (j == length - 1 && callback) {
callback();
callback = null;
}
};
Routes.each("", pckg, function(namespace, route) {
urls.push("/" == route.path[0] ? route.path.substring(1) : route.path);
});
length = urls.length;
for (;i < length; i++) XHR(urls[i], onload);
return this;
}
};
return Include;
}();
var ScriptStack = function() {
var head, currentResource, stack = [], loadScript = function(url, callback) {
var tag = document.createElement("script");
tag.type = "text/javascript";
tag.src = url;
if ("onreadystatechange" in tag) tag.onreadystatechange = function() {
("complete" == this.readyState || "loaded" == this.readyState) && callback();
}; else tag.onload = tag.onerror = callback;
(head || (head = document.getElementsByTagName("head")[0])).appendChild(tag);
}, loadByEmbedding = function() {
if (0 === stack.length) return;
if (null != currentResource) return;
var resource = currentResource = stack[0];
if (1 === resource.state) return;
resource.state = 1;
global.include = resource;
global.iparams = resource.route.params;
function resourceLoaded(e) {
if (e && "error" == e.type) console.log("Script Loaded Error", resource.url);
var i = 0, length = stack.length;
for (;i < length; i++) if (stack[i] === resource) {
stack.splice(i, 1);
break;
}
if (i == length) {
console.error("Loaded Resource not found in stack", resource);
return;
}
resource.readystatechanged(3);
currentResource = null;
loadByEmbedding();
}
if (resource.source) {
__eval(resource.source, resource);
resourceLoaded();
return;
}
loadScript(resource.url, resourceLoaded);
}, processByEval = function() {
if (0 === stack.length) return;
if (null != currentResource) return;
var resource = stack[0];
if (resource.state < 2) return;
currentResource = resource;
resource.state = 1;
global.include = resource;
__eval(resource.source, resource);
for (var i = 0, x, length = stack.length; i < length; i++) {
x = stack[i];
if (x == resource) {
stack.splice(i, 1);
break;
}
}
resource.readystatechanged(3);
currentResource = null;
processByEval();
};
return {
load: function(resource, parent, forceEmbed) {
var added = false;
if (parent) for (var i = 0, length = stack.length; i < length; i++) if (stack[i] === parent) {
stack.splice(i, 0, resource);
added = true;
break;
}
if (!added) stack.push(resource);
if (!cfg.eval || forceEmbed) {
loadByEmbedding();
return;
}
if (true === cfg.sync) currentResource = null;
if (resource.source) {
resource.state = 2;
processByEval();
return;
}
XHR(resource, function(resource, response) {
if (!response) console.error("Not Loaded:", resource.url);
resource.source = response;
resource.state = 2;
processByEval();
});
},
moveToParent: function(resource, parent) {
var length = stack.length, parentIndex = -1, resourceIndex = -1, x, i;
for (i = 0; i < length; i++) if (stack[i] === resource) {
resourceIndex = i;
break;
}
if (resourceIndex === -1) {
console.error("Bug - Resource is not in stack", resource);
return;
}
for (i = 0; i < length; i++) if (stack[i] === parent) {
parentIndex = i;
break;
}
if (parentIndex === -1) return;
if (resourceIndex < parentIndex) return;
stack.splice(resourceIndex, 1);
stack.splice(parentIndex, 0, resource);
}
};
}();
var CustomLoader = function() {
var _loaders = {};
function createLoader(url) {
var extension = url.substring(url.lastIndexOf(".") + 1);
if (_loaders.hasOwnProperty(extension)) return _loaders[extension];
var loaderRoute = cfg.loader[extension], path = loaderRoute, namespace = null;
if ("object" === typeof loaderRoute) for (var key in loaderRoute) {
namespace = key;
path = loaderRoute[key];
break;
}
return _loaders[extension] = new Resource("js", Routes.resolve(namespace, path), namespace);
}
return {
load: function(resource, callback) {
var loader = createLoader(resource.url);
loader.done(function() {
XHR(resource, function(resource, response) {
callback(resource, loader.exports.process(response, resource));
});
});
},
exists: function(resource) {
if (!(resource.url && cfg.loader)) return false;
var url = resource.url, extension = url.substring(url.lastIndexOf(".") + 1);
return cfg.loader.hasOwnProperty(extension);
}
};
}();
var LazyModule = {
create: function(xpath, code) {
var arr = xpath.split("."), obj = global, module = arr[arr.length - 1];
while (arr.length > 1) {
var prop = arr.shift();
obj = obj[prop] || (obj[prop] = {});
}
arr = null;
Object.defineProperty(obj, module, {
get: function() {
delete obj[module];
try {
var r = __eval(code, global.include);
if (!(null == r || r instanceof Resource)) obj[module] = r;
} catch (error) {
error.xpath = xpath;
Helper.reportError(error);
} finally {
code = null;
xpath = null;
return obj[module];
}
}
});
}
};
var Resource = function(Include, IncludeDeferred, Routes, ScriptStack, CustomLoader) {
function process(resource, loader) {
var type = resource.type, parent = resource.parent, url = resource.url;
if (false === CustomLoader.exists(resource)) switch (type) {
case "js":
case "embed":
ScriptStack.load(resource, parent, "embed" == type);
break;
case "ajax":
case "load":
case "lazy":
XHR(resource, onXHRCompleted);
break;
case "css":
resource.state = 4;
var tag = document.createElement("link");
tag.href = url;
tag.rel = "stylesheet";
tag.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(tag);
} else CustomLoader.load(resource, onXHRCompleted);
return resource;
}
function onXHRCompleted(resource, response) {
if (!response) {
console.warn("Resource cannt be loaded", resource.url);
resource.readystatechanged(4);
return;
}
switch (resource.type) {
case "js":
case "embed":
resource.source = response;
ScriptStack.load(resource, resource.parent, "embed" == resource.type);
return;
case "load":
case "ajax":
resource.exports = response;
break;
case "lazy":
LazyModule.create(resource.xpath, response);
break;
case "css":
var tag = document.createElement("style");
tag.type = "text/css";
tag.innerHTML = response;
document.getElementsByTagName("head")[0].appendChild(tag);
}
resource.readystatechanged(4);
}
function childLoaded(resource, child) {
var includes = resource.includes;
if (includes && includes.length) {
if (resource.state < 3) return;
for (var i = 0; i < includes.length; i++) if (4 != includes[i].resource.state) return;
}
resource.readystatechanged(4);
}
var Resource = function(type, route, namespace, xpath, parent, id) {
Include.call(this);
IncludeDeferred.call(this);
var url = route && route.path;
if (null != url) this.url = url = Helper.uri.resolveUrl(url, parent);
this.route = route;
this.namespace = namespace;
this.type = type;
this.xpath = xpath;
this.parent = parent;
if (null == id && url) id = ("/" == url[0] ? "" : "/") + url;
var resource = bin[type] && bin[type][id];
if (resource) {
if (resource.state < 4 && "js" == type) ScriptStack.moveToParent(resource, parent);
return resource;
}
if (null == url) {
this.state = 3;
return this;
}
this.location = Helper.uri.getDir(url);
(bin[type] || (bin[type] = {}))[id] = this;
if (cfg.version) this.url += (!~this.url.indexOf("?") ? "?" : "&") + "v=" + cfg.version;
return process(this);
};
Resource.prototype = Helper.extend({}, IncludeDeferred, Include, {
include: function(type, pckg) {
var that = this;
this.state = this.state >= 3 ? 3 : 2;
if (null == this.includes) this.includes = [];
if (null == this.childLoaded) this.childLoaded = function(child) {
childLoaded.call(that, that, child);
};
this.response = null;
Routes.each(type, pckg, function(namespace, route, xpath) {
var resource = new Resource(type, route, namespace, xpath, that);
that.includes.push({
resource: resource,
route: route
});
resource.on(4, that.childLoaded);
});
return this;
}
});
return Resource;
}(Include, IncludeDeferred, Routes, ScriptStack, CustomLoader);
global.include = new Include();
global.includeLib = {
Helper: Helper,
Routes: RoutesLib,
Resource: Resource,
ScriptStack: ScriptStack,
registerLoader: CustomLoader.register
};
})("undefined" === typeof window ? global : window, "undefined" == typeof document ? null : document);
include.register({
css: [ {
id: "/script/preview/preview.css",
url: "/script/preview/preview.css"
}, {
id: "/script/tabs/tabs.css",
url: "/script/tabs/tabs.css"
}, {
id: "/script/dropdownMenu/dropdownMenu.css",
url: "/script/dropdownMenu/dropdownMenu.css"
}, {
id: "/script/shortend-dialog/shortend-dialog.css",
url: "/script/shortend-dialog/shortend-dialog.css"
}, {
id: "/style/main.css",
url: "/style/main.css",
namespace: ""
} ],
load: [ {
id: "/script/shortend-dialog/shortend-dialog.mask",
url: "/script/shortend-dialog/shortend-dialog.mask"
} ],
js: [ {
id: "/.reference/libjs/class/lib/class.js",
url: "/.reference/libjs/class/lib/class.js",
namespace: ""
}, {
id: "/.reference/libjs/include/lib/include.js",
url: "/.reference/libjs/include/lib/include.js",
namespace: ""
}, {
id: "/include.routes.js",
url: "/include.routes.js",
namespace: ""
}, {
id: "/script/htmlbeautify.js",
url: "/script/htmlbeautify.js",
namespace: ""
}, {
id: "/.reference/libjs/ruqq/lib/dom/jquery.js",
url: "/.reference/libjs/ruqq/lib/dom/jquery.js",
namespace: "ruqq.dom/jquery"
}, {
id: "/.reference/libjs/ruqq/lib/utils.js",
url: "/.reference/libjs/ruqq/lib/utils.js",
namespace: "ruqq.utils"
}, {
id: "/.reference/libjs/ruqq/lib/arr.js",
url: "/.reference/libjs/ruqq/lib/arr.js",
namespace: "ruqq.arr"
}, {
id: "/.reference/libjs/ruqq/lib/es5shim.js",
url: "/.reference/libjs/ruqq/lib/es5shim.js",
namespace: "ruqq.es5shim"
}, {
id: "/.reference/libjs/mask/lib/mask.js",
url: "/.reference/libjs/mask/lib/mask.js",
namespace: "lib.mask"
}, {
id: "/.reference/libjs/compo/lib/compo.js",
url: "/.reference/libjs/compo/lib/compo.js",
namespace: "lib.compo"
}, {
id: "/.reference/libjs/ruqq/lib/ruqq.base.js",
url: "/.reference/libjs/ruqq/lib/ruqq.base.js",
namespace: "ruqq.ruqq.base"
}, {
id: "/.reference/libjs/ranimate/lib/ranimate.js",
url: "/.reference/libjs/ranimate/lib/ranimate.js",
namespace: "lib.ranimate"
}, {
id: "/.reference/libjs/mask/lib/formatter.js",
url: "/.reference/libjs/mask/lib/formatter.js",
namespace: "lib.mask/formatter"
}, {
id: "/script/preview/preview.js",
url: "/script/preview/preview.js",
namespace: "component.preview"
}, {
id: "/script/tabs/tabs.js",
url: "/script/tabs/tabs.js",
namespace: "component.tabs"
}, {
id: "/script/dropdownMenu/dropdownMenu.js",
url: "/script/dropdownMenu/dropdownMenu.js",
namespace: "component.dropdownMenu"
}, {
id: "/script/shortend-dialog/shortend-dialog.js",
url: "/script/shortend-dialog/shortend-dialog.js",
namespace: "component.shortend-dialog"
}, {
id: "/.reference/libjs/vendor-lib/keymaster/keymaster.js",
url: "/.reference/libjs/vendor-lib/keymaster/keymaster.js",
namespace: "vendor.keymaster"
}, {
id: "/script/urlcode.js",
url: "/script/urlcode.js",
namespace: "script.urlcode"
}, {
id: "/script/main.js",
url: "/script/main.js",
namespace: ""
} ]
});
include.setCurrent({
id: "/include.routes.js",
namespace: "",
url: "/include.routes.js"
});
window.DEBUG = true;
include.routes({
lib: "/.reference/libjs/{0}/lib/{1}.js",
ruqq: "/.reference/libjs/ruqq/lib/{0}.js",
compo: "/.reference/libjs/compos/{0}/lib/{1}.js"
});
if (false) include.plugin({
lib: "include/include.autoreload"
});
if (window.location.href.indexOf("file") != -1) include.cfg({
loader: {
coffee: {
lib: "include/loader/coffee/loader"
},
less: {
lib: "include/loader/less/loader"
}
}
});
include.getResource("/include.routes.js", "js").readystatechanged(3);
function style_html(html_source, options) {
var multi_parser, indent_size, indent_character, max_char, brace_style, unformatted;
options = options || {};
indent_size = options.indent_size || 4;
indent_character = options.indent_char || " ";
brace_style = options.brace_style || "collapse";
max_char = 0 == options.max_char ? 1/0 : options.max_char || 70;
unformatted = options.unformatted || [ "a", "span", "bdo", "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "acronym", "q", "sub", "sup", "tt", "i", "b", "big", "small", "u", "s", "strike", "font", "ins", "del", "pre", "address", "dt", "h1", "h2", "h3", "h4", "h5", "h6" ];
function Parser() {
this.pos = 0;
this.token = "";
this.current_mode = "CONTENT";
this.tags = {
parent: "parent1",
parentcount: 1,
parent1: ""
};
this.tag_type = "";
this.token_text = this.last_token = this.last_text = this.token_type = "";
this.Utils = {
whitespace: "\n\r ".split(""),
single_token: "br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed,?php,?,?=".split(","),
extra_liners: "head,body,/html".split(","),
in_array: function(what, arr) {
for (var i = 0; i < arr.length; i++) if (what === arr[i]) return true;
return false;
}
};
this.get_content = function() {
var input_char = "", content = [], space = false;
while ("<" !== this.input.charAt(this.pos)) {
if (this.pos >= this.input.length) return content.length ? content.join("") : [ "", "TK_EOF" ];
input_char = this.input.charAt(this.pos);
this.pos++;
this.line_char_count++;
if (this.Utils.in_array(input_char, this.Utils.whitespace)) {
if (content.length) space = true;
this.line_char_count--;
continue;
} else if (space) {
if (this.line_char_count >= this.max_char) {
content.push("\n");
for (var i = 0; i < this.indent_level; i++) content.push(this.indent_string);
this.line_char_count = 0;
} else {
content.push(" ");
this.line_char_count++;
}
space = false;
}
content.push(input_char);
}
return content.length ? content.join("") : "";
};
this.get_contents_to = function(name) {
if (this.pos == this.input.length) return [ "", "TK_EOF" ];
var input_char = "";
var content = "";
var reg_match = new RegExp("</" + name + "\\s*>", "igm");
reg_match.lastIndex = this.pos;
var reg_array = reg_match.exec(this.input);
var end_script = reg_array ? reg_array.index : this.input.length;
if (this.pos < end_script) {
content = this.input.substring(this.pos, end_script);
this.pos = end_script;
}
return content;
};
this.record_tag = function(tag) {
if (this.tags[tag + "count"]) {
this.tags[tag + "count"]++;
this.tags[tag + this.tags[tag + "count"]] = this.indent_level;
} else {
this.tags[tag + "count"] = 1;
this.tags[tag + this.tags[tag + "count"]] = this.indent_level;
}
this.tags[tag + this.tags[tag + "count"] + "parent"] = this.tags.parent;
this.tags.parent = tag + this.tags[tag + "count"];
};
this.retrieve_tag = function(tag) {
if (this.tags[tag + "count"]) {
var temp_parent = this.tags.parent;
while (temp_parent) {
if (tag + this.tags[tag + "count"] === temp_parent) break;
temp_parent = this.tags[temp_parent + "parent"];
}
if (temp_parent) {
this.indent_level = this.tags[tag + this.tags[tag + "count"]];
this.tags.parent = this.tags[temp_parent + "parent"];
}
delete this.tags[tag + this.tags[tag + "count"] + "parent"];
delete this.tags[tag + this.tags[tag + "count"]];
if (1 == this.tags[tag + "count"]) delete this.tags[tag + "count"]; else this.tags[tag + "count"]--;
}
};
this.get_tag = function(peek) {
var input_char = "", content = [], space = false, tag_start, tag_end, peek = "undefined" !== typeof peek ? peek : false, orig_pos = this.pos, orig_line_char_count = this.line_char_count;
do {
if (this.pos >= this.input.length) {
if (peek) {
this.pos = orig_pos;
this.line_char_count = orig_line_char_count;
}
return content.length ? content.join("") : [ "", "TK_EOF" ];
}
input_char = this.input.charAt(this.pos);
this.pos++;
this.line_char_count++;
if (this.Utils.in_array(input_char, this.Utils.whitespace)) {
space = true;
this.line_char_count--;
continue;
}
if ("'" === input_char || '"' === input_char) if (!content[1] || "!" !== content[1]) {
input_char += this.get_unformatted(input_char);
space = true;
}
if ("=" === input_char) space = false;
if (content.length && "=" !== content[content.length - 1] && ">" !== input_char && space) {
if (this.line_char_count >= this.max_char) {
this.print_newline(false, content);
this.line_char_count = 0;
} else {
content.push(" ");
this.line_char_count++;
}
space = false;
}
if ("<" === input_char) tag_start = this.pos - 1;
content.push(input_char);
} while (">" !== input_char);
var tag_complete = content.join("");
var tag_index;
if (tag_complete.indexOf(" ") != -1) tag_index = tag_complete.indexOf(" "); else tag_index = tag_complete.indexOf(">");
var tag_check = tag_complete.substring(1, tag_index).toLowerCase();
if ("/" === tag_complete.charAt(tag_complete.length - 2) || this.Utils.in_array(tag_check, this.Utils.single_token)) {
if (!peek) this.tag_type = "SINGLE";
} else if ("script" === tag_check) {
if (!peek) {
this.record_tag(tag_check);
this.tag_type = "SCRIPT";
}
} else if ("style" === tag_check) {
if (!peek) {
this.record_tag(tag_check);
this.tag_type = "STYLE";
}
} else if (this.is_unformatted(tag_check, unformatted)) {
var comment = this.get_unformatted("</" + tag_check + ">", tag_complete);
content.push(comment);
if (tag_start > 0 && this.Utils.in_array(this.input.charAt(tag_start - 1), this.Utils.whitespace)) content.splice(0, 0, this.input.charAt(tag_start - 1));
tag_end = this.pos - 1;
if (this.Utils.in_array(this.input.charAt(tag_end + 1), this.Utils.whitespace)) content.push(this.input.charAt(tag_end + 1));
this.tag_type = "SINGLE";
} else if ("!" === tag_check.charAt(0)) if (tag_check.indexOf("[if") != -1) {
if (tag_complete.indexOf("!IE") != -1) {
var comment = this.get_unformatted("-->", tag_complete);
content.push(comment);
}
if (!peek) this.tag_type = "START";
} else if (tag_check.indexOf("[endif") != -1) {
this.tag_type = "END";
this.unindent();
} else if (tag_check.indexOf("[cdata[") != -1) {
var comment = this.get_unformatted("]]>", tag_complete);
content.push(comment);
if (!peek) this.tag_type = "SINGLE";
} else {
var comment = this.get_unformatted("-->", tag_complete);
content.push(comment);
this.tag_type = "SINGLE";
} else if (!peek) {
if ("/" === tag_check.charAt(0)) {
this.retrieve_tag(tag_check.substring(1));
this.tag_type = "END";
} else {
this.record_tag(tag_check);
this.tag_type = "START";
}
if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) this.print_newline(true, this.output);
}
if (peek) {
this.pos = orig_pos;
this.line_char_count = orig_line_char_count;
}
return content.join("");
};
this.get_unformatted = function(delimiter, orig_tag) {
if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) != -1) return "";
var input_char = "";
var content = "";
var space = true;
do {
if (this.pos >= this.input.length) return content;
input_char = this.input.charAt(this.pos);
this.pos++;
if (this.Utils.in_array(input_char, this.Utils.whitespace)) {
if (!space) {
this.line_char_count--;
continue;
}
if ("\n" === input_char || "\r" === input_char) {
content += "\n";
this.line_char_count = 0;
continue;
}
}
content += input_char;
this.line_char_count++;
space = true;
} while (content.toLowerCase().indexOf(delimiter) == -1);
return content;
};
this.get_token = function() {
var token;
if ("TK_TAG_SCRIPT" === this.last_token || "TK_TAG_STYLE" === this.last_token) {
var type = this.last_token.substr(7);
token = this.get_contents_to(type);
if ("string" !== typeof token) return token;
return [ token, "TK_" + type ];
}
if ("CONTENT" === this.current_mode) {
token = this.get_content();
if ("string" !== typeof token) return token; else return [ token, "TK_CONTENT" ];
}
if ("TAG" === this.current_mode) {
token = this.get_tag();
if ("string" !== typeof token) return token; else {
var tag_name_type = "TK_TAG_" + this.tag_type;
return [ token, tag_name_type ];
}
}
};
this.get_full_indent = function(level) {
level = this.indent_level + level || 0;
if (level < 1) return "";
return Array(level + 1).join(this.indent_string);
};
this.is_unformatted = function(tag_check, unformatted) {
if (!this.Utils.in_array(tag_check, unformatted)) return false;
if ("a" !== tag_check.toLowerCase() || !this.Utils.in_array("a", unformatted)) return true;
var next_tag = this.get_tag(true);
if (next_tag && this.Utils.in_array(next_tag, unformatted)) return true; else return false;
};
this.printer = function(js_source, indent_character, indent_size, max_char, brace_style) {
this.input = js_source || "";
this.output = [];
this.indent_character = indent_character;
this.indent_string = "";
this.indent_size = indent_size;
this.brace_style = brace_style;
this.indent_level = 0;
this.max_char = max_char;
this.line_char_count = 0;
for (var i = 0; i < this.indent_size; i++) this.indent_string += this.indent_character;
this.print_newline = function(ignore, arr) {
this.line_char_count = 0;
if (!arr || !arr.length) return;
if (!ignore) while (this.Utils.in_array(arr[arr.length - 1], this.Utils.whitespace)) arr.pop();
arr.push("\n");
for (var i = 0; i < this.indent_level; i++) arr.push(this.indent_string);
};
this.print_token = function(text) {
this.output.push(text);
};
this.indent = function() {
this.indent_level++;
};
this.unindent = function() {
if (this.indent_level > 0) this.indent_level--;
};
};
return this;
}
multi_parser = new Parser();
multi_parser.printer(html_source, indent_character, indent_size, max_char, brace_style);
while (true) {
var t = multi_parser.get_token();
multi_parser.token_text = t[0];
multi_parser.token_type = t[1];
if ("TK_EOF" === multi_parser.token_type) break;
switch (multi_parser.token_type) {
case "TK_TAG_START":
multi_parser.print_newline(false, multi_parser.output);
multi_parser.print_token(multi_parser.token_text);
multi_parser.indent();
multi_parser.current_mode = "CONTENT";
break;
case "TK_TAG_STYLE":
case "TK_TAG_SCRIPT":
multi_parser.print_newline(false, multi_parser.output);
multi_parser.print_token(multi_parser.token_text);
multi_parser.current_mode = "CONTENT";
break;
case "TK_TAG_END":
if ("TK_CONTENT" === multi_parser.last_token && "" === multi_parser.last_text) {
var tag_name = multi_parser.token_text.match(/\w+/)[0];
var tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length - 1].match(/<\s*(\w+)/);
if (null === tag_extracted_from_last_output || tag_extracted_from_last_output[1] !== tag_name) multi_parser.print_newline(true, multi_parser.output);
}
multi_parser.print_token(multi_parser.token_text);
multi_parser.current_mode = "CONTENT";
break;
case "TK_TAG_SINGLE":
var tag_check = multi_parser.token_text.match(/^\s*<([a-z]+)/i);
if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)) multi_parser.print_newline(false, multi_parser.output);
multi_parser.print_token(multi_parser.token_text);
multi_parser.current_mode = "CONTENT";
break;
case "TK_CONTENT":
if ("" !== multi_parser.token_text) multi_parser.print_token(multi_parser.token_text);
multi_parser.current_mode = "TAG";
break;
case "TK_STYLE":
case "TK_SCRIPT":
if ("" !== multi_parser.token_text) {
multi_parser.output.push("\n");
var text = multi_parser.token_text;
if ("TK_SCRIPT" == multi_parser.token_type) var _beautifier = "function" == typeof js_beautify && js_beautify; else if ("TK_STYLE" == multi_parser.token_type) var _beautifier = "function" == typeof css_beautify && css_beautify;
if ("keep" == options.indent_scripts) var script_indent_level = 0; else if ("separate" == options.indent_scripts) var script_indent_level = -multi_parser.indent_level; else var script_indent_level = 1;
var indentation = multi_parser.get_full_indent(script_indent_level);
if (_beautifier) text = _beautifier(text.replace(/^\s*/, indentation), options); else {
var white = text.match(/^\s*/)[0];
var _level = white.match(/[^\n\r]*$/)[0].split(multi_parser.indent_string).length - 1;
var reindent = multi_parser.get_full_indent(script_indent_level - _level);
text = text.replace(/^\s*/, indentation).replace(/\r\n|\r|\n/g, "\n" + reindent).replace(/\s*$/, "");
}
if (text) {
multi_parser.print_token(text);
multi_parser.print_newline(true, multi_parser.output);
}
}
multi_parser.current_mode = "TAG";
}
multi_parser.last_token = multi_parser.token_type;
multi_parser.last_text = multi_parser.token_text;
}
return multi_parser.output.join("");
}
if ("undefined" !== typeof exports) exports.html_beautify = style_html;
(function(a, b) {
function G(a) {
var b = F[a] = {};
return p.each(a.split(s), function(a, c) {
b[c] = !0;
}), b;
}
function J(a, c, d) {
if (d === b && 1 === a.nodeType) {
var e = "data-" + c.replace(I, "-$1").toLowerCase();
d = a.getAttribute(e);
if ("string" == typeof d) {
try {
d = "true" === d ? !0 : "false" === d ? !1 : "null" === d ? null : +d + "" === d ? +d : H.test(d) ? p.parseJSON(d) : d;
} catch (f) {}
p.data(a, c, d);
} else d = b;
}
return d;
}
function K(a) {
var b;
for (b in a) {
if ("data" === b && p.isEmptyObject(a[b])) continue;
if ("toJSON" !== b) return !1;
}
return !0;
}
function ba() {
return !1;
}
function bb() {
return !0;
}
function bh(a) {
return !a || !a.parentNode || 11 === a.parentNode.nodeType;
}
function bi(a, b) {
do a = a[b]; while (a && 1 !== a.nodeType);
return a;
}
function bj(a, b, c) {
b = b || 0;
if (p.isFunction(b)) return p.grep(a, function(a, d) {
var e = !!b.call(a, d, a);
return e === c;
});
if (b.nodeType) return p.grep(a, function(a, d) {
return a === b === c;
});
if ("string" == typeof b) {
var d = p.grep(a, function(a) {
return 1 === a.nodeType;
});
if (be.test(b)) return p.filter(b, d, !c);
b = p.filter(b, d);
}
return p.grep(a, function(a, d) {
return p.inArray(a, b) >= 0 === c;
});
}
function bk(a) {
var b = bl.split("|"), c = a.createDocumentFragment();
if (c.createElement) while (b.length) c.createElement(b.pop());
return c;
}
function bC(a, b) {
return a.getElementsByTagName(b)[0] || a.appendChild(a.ownerDocument.createElement(b));
}
function bD(a, b) {
if (1 !== b.nodeType || !p.hasData(a)) return;
var c, d, e, f = p._data(a), g = p._data(b, f), h = f.events;
if (h) {
delete g.handle, g.events = {};
for (c in h) for (d = 0, e = h[c].length; d < e; d++) p.event.add(b, c, h[c][d]);
}
g.data && (g.data = p.extend({}, g.data));
}
function bE(a, b) {
var c;
if (1 !== b.nodeType) return;
b.clearAttributes && b.clearAttributes(), b.mergeAttributes && b.mergeAttributes(a),
c = b.nodeName.toLowerCase(), "object" === c ? (b.parentNode && (b.outerHTML = a.outerHTML),
p.support.html5Clone && a.innerHTML && !p.trim(b.innerHTML) && (b.innerHTML = a.innerHTML)) : "input" === c && bv.test(a.type) ? (b.defaultChecked = b.checked = a.checked,
b.value !== a.value && (b.value = a.value)) : "option" === c ? b.selected = a.defaultSelected : "input" === c || "textarea" === c ? b.defaultValue = a.defaultValue : "script" === c && b.text !== a.text && (b.text = a.text),
b.removeAttribute(p.expando);
}
function bF(a) {
return "undefined" != typeof a.getElementsByTagName ? a.getElementsByTagName("*") : "undefined" != typeof a.querySelectorAll ? a.querySelectorAll("*") : [];
}
function bG(a) {
bv.test(a.type) && (a.defaultChecked = a.checked);
}
function bY(a, b) {
if (b in a) return b;
var c = b.charAt(0).toUpperCase() + b.slice(1), d = b, e = bW.length;
while (e--) {
b = bW[e] + c;
if (b in a) return b;
}
return d;
}
function bZ(a, b) {
return a = b || a, "none" === p.css(a, "display") || !p.contains(a.ownerDocument, a);
}
function b$(a, b) {
var c, d, e = [], f = 0, g = a.length;
for (;f < g; f++) {
c = a[f];
if (!c.style) continue;
e[f] = p._data(c, "olddisplay"), b ? (!e[f] && "none" === c.style.display && (c.style.display = ""),
"" === c.style.display && bZ(c) && (e[f] = p._data(c, "olddisplay", cc(c.nodeName)))) : (d = bH(c, "display"),
!e[f] && "none" !== d && p._data(c, "olddisplay", d));
}
for (f = 0; f < g; f++) {
c = a[f];
if (!c.style) continue;
if (!b || "none" === c.style.display || "" === c.style.display) c.style.display = b ? e[f] || "" : "none";
}
return a;
}
function b_(a, b, c) {
var d = bP.exec(b);
return d ? Math.max(0, d[1] - (c || 0)) + (d[2] || "px") : b;
}
function ca(a, b, c, d) {
var e = c === (d ? "border" : "content") ? 4 : "width" === b ? 1 : 0, f = 0;
for (;e < 4; e += 2) "margin" === c && (f += p.css(a, c + bV[e], !0)), d ? ("content" === c && (f -= parseFloat(bH(a, "padding" + bV[e])) || 0),
"margin" !== c && (f -= parseFloat(bH(a, "border" + bV[e] + "Width")) || 0)) : (f += parseFloat(bH(a, "padding" + bV[e])) || 0,
"padding" !== c && (f += parseFloat(bH(a, "border" + bV[e] + "Width")) || 0));
return f;
}
function cb(a, b, c) {
var d = "width" === b ? a.offsetWidth : a.offsetHeight, e = !0, f = p.support.boxSizing && "border-box" === p.css(a, "boxSizing");
if (d <= 0 || null == d) {
d = bH(a, b);
if (d < 0 || null == d) d = a.style[b];
if (bQ.test(d)) return d;
e = f && (p.support.boxSizingReliable || d === a.style[b]), d = parseFloat(d) || 0;
}
return d + ca(a, b, c || (f ? "border" : "content"), e) + "px";
}
function cc(a) {
if (bS[a]) return bS[a];
var b = p("<" + a + ">").appendTo(e.body), c = b.css("display");
b.remove();
if ("none" === c || "" === c) {
bI = e.body.appendChild(bI || p.extend(e.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
}));
if (!bJ || !bI.createElement) bJ = (bI.contentWindow || bI.contentDocument).document,
bJ.write("<!doctype html><html><body>"), bJ.close();
b = bJ.body.appendChild(bJ.createElement(a)), c = bH(b, "display"), e.body.removeChild(bI);
}
return bS[a] = c, c;
}
function ci(a, b, c, d) {
var e;
if (p.isArray(b)) p.each(b, function(b, e) {
c || ce.test(a) ? d(a, e) : ci(a + "[" + ("object" == typeof e ? b : "") + "]", e, c, d);
}); else if (!c && "object" === p.type(b)) for (e in b) ci(a + "[" + e + "]", b[e], c, d); else d(a, b);
}
function cz(a) {
return function(b, c) {
"string" != typeof b && (c = b, b = "*");
var d, e, f, g = b.toLowerCase().split(s), h = 0, i = g.length;
if (p.isFunction(c)) for (;h < i; h++) d = g[h], f = /^\+/.test(d), f && (d = d.substr(1) || "*"),
e = a[d] = a[d] || [], e[f ? "unshift" : "push"](c);
};
}
function cA(a, c, d, e, f, g) {
f = f || c.dataTypes[0], g = g || {}, g[f] = !0;
var h, i = a[f], j = 0, k = i ? i.length : 0, l = a === cv;
for (;j < k && (l || !h); j++) h = i[j](c, d, e), "string" == typeof h && (!l || g[h] ? h = b : (c.dataTypes.unshift(h),
h = cA(a, c, d, e, h, g)));
return (l || !h) && !g["*"] && (h = cA(a, c, d, e, "*", g)), h;
}
function cB(a, c) {
var d, e, f = p.ajaxSettings.flatOptions || {};
for (d in c) c[d] !== b && ((f[d] ? a : e || (e = {}))[d] = c[d]);
e && p.extend(!0, a, e);
}
function cC(a, c, d) {
var e, f, g, h, i = a.contents, j = a.dataTypes, k = a.responseFields;
for (f in k) f in d && (c[k[f]] = d[f]);
while ("*" === j[0]) j.shift(), e === b && (e = a.mimeType || c.getResponseHeader("content-type"));
if (e) for (f in i) if (i[f] && i[f].test(e)) {
j.unshift(f);
break;
}
if (j[0] in d) g = j[0]; else {
for (f in d) {
if (!j[0] || a.converters[f + " " + j[0]]) {
g = f;
break;
}
h || (h = f);
}
g = g || h;
}
if (g) return g !== j[0] && j.unshift(g), d[g];
}
function cD(a, b) {
var c, d, e, f, g = a.dataTypes.slice(), h = g[0], i = {}, j = 0;
a.dataFilter && (b = a.dataFilter(b, a.dataType));
if (g[1]) for (c in a.converters) i[c.toLowerCase()] = a.converters[c];
for (;e = g[++j]; ) if ("*" !== e) {
if ("*" !== h && h !== e) {
c = i[h + " " + e] || i["* " + e];
if (!c) for (d in i) {
f = d.split(" ");
if (f[1] === e) {
c = i[h + " " + f[0]] || i["* " + f[0]];
if (c) {
c === !0 ? c = i[d] : i[d] !== !0 && (e = f[0], g.splice(j--, 0, e));
break;
}
}
}
if (c !== !0) if (c && a["throws"]) b = c(b); else try {
b = c(b);
} catch (k) {
return {
state: "parsererror",
error: c ? k : "No conversion from " + h + " to " + e
};
}
}
h = e;
}
return {
state: "success",
data: b
};
}
function cL() {
try {
return new a.XMLHttpRequest();
} catch (b) {}
}
function cM() {
try {
return new a.ActiveXObject("Microsoft.XMLHTTP");
} catch (b) {}
}
function cU() {
return setTimeout(function() {
cN = b;
}, 0), cN = p.now();
}
function cV(a, b) {
p.each(b, function(b, c) {
var d = (cT[b] || []).concat(cT["*"]), e = 0, f = d.length;
for (;e < f; e++) if (d[e].call(a, b, c)) return;
});
}
function cW(a, b, c) {
var d, e = 0, f = 0, g = cS.length, h = p.Deferred().always(function() {
delete i.elem;
}), i = function() {
var b = cN || cU(), c = Math.max(0, j.startTime + j.duration - b), d = 1 - (c / j.duration || 0), e = 0, f = j.tweens.length;
for (;e < f; e++) j.tweens[e].run(d);
return h.notifyWith(a, [ j, d, c ]), d < 1 && f ? c : (h.resolveWith(a, [ j ]),
!1);
}, j = h.promise({
elem: a,
props: p.extend({}, b),
opts: p.extend(!0, {
specialEasing: {}
}, c),
originalProperties: b,
originalOptions: c,
startTime: cN || cU(),
duration: c.duration,
tweens: [],
createTween: function(b, c, d) {
var e = p.Tween(a, j.opts, b, c, j.opts.specialEasing[b] || j.opts.easing);
return j.tweens.push(e), e;
},
stop: function(b) {
var c = 0, d = b ? j.tweens.length : 0;
for (;c < d; c++) j.tweens[c].run(1);
return b ? h.resolveWith(a, [ j, b ]) : h.rejectWith(a, [ j, b ]), this;
}
}), k = j.props;
cX(k, j.opts.specialEasing);
for (;e < g; e++) {
d = cS[e].call(j, a, k, j.opts);
if (d) return d;
}
return cV(j, k), p.isFunction(j.opts.start) && j.opts.start.call(a, j), p.fx.timer(p.extend(i, {
anim: j,
queue: j.opts.queue,
elem: a
})), j.progress(j.opts.progress).done(j.opts.done, j.opts.complete).fail(j.opts.fail).always(j.opts.always);
}
function cX(a, b) {
var c, d, e, f, g;
for (c in a) {
d = p.camelCase(c), e = b[d], f = a[c], p.isArray(f) && (e = f[1], f = a[c] = f[0]),
c !== d && (a[d] = f, delete a[c]), g = p.cssHooks[d];
if (g && "expand" in g) {
f = g.expand(f), delete a[d];
for (c in f) c in a || (a[c] = f[c], b[c] = e);
} else b[d] = e;
}
}
function cY(a, b, c) {
var d, e, f, g, h, i, j, k, l = this, m = a.style, n = {}, o = [], q = a.nodeType && bZ(a);
c.queue || (j = p._queueHooks(a, "fx"), null == j.unqueued && (j.unqueued = 0, k = j.empty.fire,
j.empty.fire = function() {
j.unqueued || k();
}), j.unqueued++, l.always(function() {
l.always(function() {
j.unqueued--, p.queue(a, "fx").length || j.empty.fire();
});
})), 1 === a.nodeType && ("height" in b || "width" in b) && (c.overflow = [ m.overflow, m.overflowX, m.overflowY ],
"inline" === p.css(a, "display") && "none" === p.css(a, "float") && (!p.support.inlineBlockNeedsLayout || "inline" === cc(a.nodeName) ? m.display = "inline-block" : m.zoom = 1)),
c.overflow && (m.overflow = "hidden", p.support.shrinkWrapBlocks || l.done(function() {
m.overflow = c.overflow[0], m.overflowX = c.overflow[1], m.overflowY = c.overflow[2];
}));
for (d in b) {
f = b[d];
if (cP.exec(f)) {
delete b[d];
if (f === (q ? "hide" : "show")) continue;
o.push(d);
}
}
g = o.length;
if (g) {
h = p._data(a, "fxshow") || p._data(a, "fxshow", {}), q ? p(a).show() : l.done(function() {
p(a).hide();
}), l.done(function() {
var b;
p.removeData(a, "fxshow", !0);
for (b in n) p.style(a, b, n[b]);
});
for (d = 0; d < g; d++) e = o[d], i = l.createTween(e, q ? h[e] : 0), n[e] = h[e] || p.style(a, e),
e in h || (h[e] = i.start, q && (i.end = i.start, i.start = "width" === e || "height" === e ? 1 : 0));
}
}
function cZ(a, b, c, d, e) {
return new cZ.prototype.init(a, b, c, d, e);
}
function c$(a, b) {
var c, d = {
height: a
}, e = 0;
b = b ? 1 : 0;
for (;e < 4; e += 2 - b) c = bV[e], d["margin" + c] = d["padding" + c] = a;
return b && (d.opacity = d.width = a), d;
}
function da(a) {
return p.isWindow(a) ? a : 9 === a.nodeType ? a.defaultView || a.parentWindow : !1;
}
var c, d, e = a.document, f = a.location, g = a.navigator, h = a.jQuery, i = a.$, j = Array.prototype.push, k = Array.prototype.slice, l = Array.prototype.indexOf, m = Object.prototype.toString, n = Object.prototype.hasOwnProperty, o = String.prototype.trim, p = function(a, b) {
return new p.fn.init(a, b, c);
}, q = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, r = /\S/, s = /\s+/, t = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, u = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, v = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, w = /^[\],:{}\s]*$/, x = /(?:^|:|,)(?:\s*\[)+/g, y = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, z = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, A = /^-ms-/, B = /-([\da-z])/gi, C = function(a, b) {
return (b + "").toUpperCase();
}, D = function() {
e.addEventListener ? (e.removeEventListener("DOMContentLoaded", D, !1), p.ready()) : "complete" === e.readyState && (e.detachEvent("onreadystatechange", D),
p.ready());
}, E = {};
p.fn = p.prototype = {
constructor: p,
init: function(a, c, d) {
var f, g, h, i;
if (!a) return this;
if (a.nodeType) return this.context = this[0] = a, this.length = 1, this;
if ("string" == typeof a) {
"<" === a.charAt(0) && ">" === a.charAt(a.length - 1) && a.length >= 3 ? f = [ null, a, null ] : f = u.exec(a);
if (f && (f[1] || !c)) {
if (f[1]) return c = c instanceof p ? c[0] : c, i = c && c.nodeType ? c.ownerDocument || c : e,
a = p.parseHTML(f[1], i, !0), v.test(f[1]) && p.isPlainObject(c) && this.attr.call(a, c, !0),
p.merge(this, a);
g = e.getElementById(f[2]);
if (g && g.parentNode) {
if (g.id !== f[2]) return d.find(a);
this.length = 1, this[0] = g;
}
return this.context = e, this.selector = a, this;
}
return !c || c.jquery ? (c || d).find(a) : this.constructor(c).find(a);
}
return p.isFunction(a) ? d.ready(a) : (a.selector !== b && (this.selector = a.selector,
this.context = a.context), p.makeArray(a, this));
},
selector: "",
jquery: "1.8.2",
length: 0,
size: function() {
return this.length;
},
toArray: function() {
return k.call(this);
},
get: function(a) {
return null == a ? this.toArray() : a < 0 ? this[this.length + a] : this[a];
},
pushStack: function(a, b, c) {
var d = p.merge(this.constructor(), a);
return d.prevObject = this, d.context = this.context, "find" === b ? d.selector = this.selector + (this.selector ? " " : "") + c : b && (d.selector = this.selector + "." + b + "(" + c + ")"),
d;
},
each: function(a, b) {
return p.each(this, a, b);
},
ready: function(a) {
return p.ready.promise().done(a), this;
},
eq: function(a) {
return a = +a, a === -1 ? this.slice(a) : this.slice(a, a + 1);
},
first: function() {
return this.eq(0);
},
last: function() {
return this.eq(-1);
},
slice: function() {
return this.pushStack(k.apply(this, arguments), "slice", k.call(arguments).join(","));
},
map: function(a) {
return this.pushStack(p.map(this, function(b, c) {
return a.call(b, c, b);
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
push: j,
sort: [].sort,
splice: [].splice
}, p.fn.init.prototype = p.fn, p.extend = p.fn.extend = function() {
var a, c, d, e, f, g, h = arguments[0] || {}, i = 1, j = arguments.length, k = !1;
"boolean" == typeof h && (k = h, h = arguments[1] || {}, i = 2), "object" != typeof h && !p.isFunction(h) && (h = {}),
j === i && (h = this, --i);
for (;i < j; i++) if (null != (a = arguments[i])) for (c in a) {
d = h[c], e = a[c];
if (h === e) continue;
k && e && (p.isPlainObject(e) || (f = p.isArray(e))) ? (f ? (f = !1, g = d && p.isArray(d) ? d : []) : g = d && p.isPlainObject(d) ? d : {},
h[c] = p.extend(k, g, e)) : e !== b && (h[c] = e);
}
return h;
}, p.extend({
noConflict: function(b) {
return a.$ === p && (a.$ = i), b && a.jQuery === p && (a.jQuery = h), p;
},
isReady: !1,
readyWait: 1,
holdReady: function(a) {
a ? p.readyWait++ : p.ready(!0);
},
ready: function(a) {
if (a === !0 ? --p.readyWait : p.isReady) return;
if (!e.body) return setTimeout(p.ready, 1);
p.isReady = !0;
if (a !== !0 && --p.readyWait > 0) return;
d.resolveWith(e, [ p ]), p.fn.trigger && p(e).trigger("ready").off("ready");
},
isFunction: function(a) {
return "function" === p.type(a);
},
isArray: Array.isArray || function(a) {
return "array" === p.type(a);
},
isWindow: function(a) {
return null != a && a == a.window;
},
isNumeric: function(a) {
return !isNaN(parseFloat(a)) && isFinite(a);
},
type: function(a) {
return null == a ? String(a) : E[m.call(a)] || "object";
},
isPlainObject: function(a) {
if (!a || "object" !== p.type(a) || a.nodeType || p.isWindow(a)) return !1;
try {
if (a.constructor && !n.call(a, "constructor") && !n.call(a.constructor.prototype, "isPrototypeOf")) return !1;
} catch (c) {
return !1;
}
var d;
for (d in a) ;
return d === b || n.call(a, d);
},
isEmptyObject: function(a) {
var b;
for (b in a) return !1;
return !0;
},
error: function(a) {
throw new Error(a);
},
parseHTML: function(a, b, c) {
var d;
return !a || "string" != typeof a ? null : ("boolean" == typeof b && (c = b, b = 0),
b = b || e, (d = v.exec(a)) ? [ b.createElement(d[1]) ] : (d = p.buildFragment([ a ], b, c ? null : []),
p.merge([], (d.cacheable ? p.clone(d.fragment) : d.fragment).childNodes)));
},
parseJSON: function(b) {
if (!b || "string" != typeof b) return null;
b = p.trim(b);
if (a.JSON && a.JSON.parse) return a.JSON.parse(b);
if (w.test(b.replace(y, "@").replace(z, "]").replace(x, ""))) return new Function("return " + b)();
p.error("Invalid JSON: " + b);
},
parseXML: function(c) {
var d, e;
if (!c || "string" != typeof c) return null;
try {
a.DOMParser ? (e = new DOMParser(), d = e.parseFromString(c, "text/xml")) : (d = new ActiveXObject("Microsoft.XMLDOM"),
d.async = "false", d.loadXML(c));
} catch (f) {
d = b;
}
return (!d || !d.documentElement || d.getElementsByTagName("parsererror").length) && p.error("Invalid XML: " + c),
d;
},
noop: function() {},
globalEval: function(b) {
b && r.test(b) && (a.execScript || function(b) {
a.eval.call(a, b);
})(b);
},
camelCase: function(a) {
return a.replace(A, "ms-").replace(B, C);
},
nodeName: function(a, b) {
return a.nodeName && a.nodeName.toLowerCase() === b.toLowerCase();
},
each: function(a, c, d) {
var e, f = 0, g = a.length, h = g === b || p.isFunction(a);
if (d) {
if (h) {
for (e in a) if (c.apply(a[e], d) === !1) break;
} else for (;f < g; ) if (c.apply(a[f++], d) === !1) break;
} else if (h) {
for (e in a) if (c.call(a[e], e, a[e]) === !1) break;
} else for (;f < g; ) if (c.call(a[f], f, a[f++]) === !1) break;
return a;
},
trim: o && !o.call(" ") ? function(a) {
return null == a ? "" : o.call(a);
} : function(a) {
return null == a ? "" : (a + "").replace(t, "");
},
makeArray: function(a, b) {
var c, d = b || [];
return null != a && (c = p.type(a), null == a.length || "string" === c || "function" === c || "regexp" === c || p.isWindow(a) ? j.call(d, a) : p.merge(d, a)),
d;
},
inArray: function(a, b, c) {
var d;
if (b) {
if (l) return l.call(b, a, c);
d = b.length, c = c ? c < 0 ? Math.max(0, d + c) : c : 0;
for (;c < d; c++) if (c in b && b[c] === a) return c;
}
return -1;
},
merge: function(a, c) {
var d = c.length, e = a.length, f = 0;
if ("number" == typeof d) for (;f < d; f++) a[e++] = c[f]; else while (c[f] !== b) a[e++] = c[f++];
return a.length = e, a;
},
grep: function(a, b, c) {
var d, e = [], f = 0, g = a.length;
c = !!c;
for (;f < g; f++) d = !!b(a[f], f), c !== d && e.push(a[f]);
return e;
},
map: function(a, c, d) {
var e, f, g = [], h = 0, i = a.length, j = a instanceof p || i !== b && "number" == typeof i && (i > 0 && a[0] && a[i - 1] || 0 === i || p.isArray(a));
if (j) for (;h < i; h++) e = c(a[h], h, d), null != e && (g[g.length] = e); else for (f in a) e = c(a[f], f, d),
null != e && (g[g.length] = e);
return g.concat.apply([], g);
},
guid: 1,
proxy: function(a, c) {
var d, e, f;
return "string" == typeof c && (d = a[c], c = a, a = d), p.isFunction(a) ? (e = k.call(arguments, 2),
f = function() {
return a.apply(c, e.concat(k.call(arguments)));
}, f.guid = a.guid = a.guid || p.guid++, f) : b;
},
access: function(a, c, d, e, f, g, h) {
var i, j = null == d, k = 0, l = a.length;
if (d && "object" == typeof d) {
for (k in d) p.access(a, c, k, d[k], 1, g, e);
f = 1;
} else if (e !== b) {
i = h === b && p.isFunction(e), j && (i ? (i = c, c = function(a, b, c) {
return i.call(p(a), c);
}) : (c.call(a, e), c = null));
if (c) for (;k < l; k++) c(a[k], d, i ? e.call(a[k], k, c(a[k], d)) : e, h);
f = 1;
}
return f ? a : j ? c.call(a) : l ? c(a[0], d) : g;
},
now: function() {
return new Date().getTime();
}
}), p.ready.promise = function(b) {
if (!d) {
d = p.Deferred();
if ("complete" === e.readyState) setTimeout(p.ready, 1); else if (e.addEventListener) e.addEventListener("DOMContentLoaded", D, !1),
a.addEventListener("load", p.ready, !1); else {
e.attachEvent("onreadystatechange", D), a.attachEvent("onload", p.ready);
var c = !1;
try {
c = null == a.frameElement && e.documentElement;
} catch (f) {}
c && c.doScroll && function g() {
if (!p.isReady) {
try {
c.doScroll("left");
} catch (a) {
return setTimeout(g, 50);
}
p.ready();
}
}();
}
}
return d.promise(b);
}, p.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(a, b) {
E["[object " + b + "]"] = b.toLowerCase();
}), c = p(e);
var F = {};
p.Callbacks = function(a) {
a = "string" == typeof a ? F[a] || G(a) : p.extend({}, a);
var c, d, e, f, g, h, i = [], j = !a.once && [], k = function(b) {
c = a.memory && b, d = !0, h = f || 0, f = 0, g = i.length, e = !0;
for (;i && h < g; h++) if (i[h].apply(b[0], b[1]) === !1 && a.stopOnFalse) {
c = !1;
break;
}
e = !1, i && (j ? j.length && k(j.shift()) : c ? i = [] : l.disable());
}, l = {
add: function() {
if (i) {
var b = i.length;
(function d(b) {
p.each(b, function(b, c) {
var e = p.type(c);
"function" === e && (!a.unique || !l.has(c)) ? i.push(c) : c && c.length && "string" !== e && d(c);
});
})(arguments), e ? g = i.length : c && (f = b, k(c));
}
return this;
},
remove: function() {
return i && p.each(arguments, function(a, b) {
var c;
while ((c = p.inArray(b, i, c)) > -1) i.splice(c, 1), e && (c <= g && g--, c <= h && h--);
}), this;
},
has: function(a) {
return p.inArray(a, i) > -1;
},
empty: function() {
return i = [], this;
},
disable: function() {
return i = j = c = b, this;
},
disabled: function() {
return !i;
},
lock: function() {
return j = b, c || l.disable(), this;
},
locked: function() {
return !j;
},
fireWith: function(a, b) {
return b = b || [], b = [ a, b.slice ? b.slice() : b ], i && (!d || j) && (e ? j.push(b) : k(b)),
this;
},
fire: function() {
return l.fireWith(this, arguments), this;
},
fired: function() {
return !!d;
}
};
return l;
}, p.extend({
Deferred: function(a) {
var b = [ [ "resolve", "done", p.Callbacks("once memory"), "resolved" ], [ "reject", "fail", p.Callbacks("once memory"), "rejected" ], [ "notify", "progress", p.Callbacks("memory") ] ], c = "pending", d = {
state: function() {
return c;
},
always: function() {
return e.done(arguments).fail(arguments), this;
},
then: function() {
var a = arguments;
return p.Deferred(function(c) {
p.each(b, function(b, d) {
var f = d[0], g = a[b];
e[d[1]](p.isFunction(g) ? function() {
var a = g.apply(this, arguments);
a && p.isFunction(a.promise) ? a.promise().done(c.resolve).fail(c.reject).progress(c.notify) : c[f + "With"](this === e ? c : this, [ a ]);
} : c[f]);
}), a = null;
}).promise();
},
promise: function(a) {
return null != a ? p.extend(a, d) : d;
}
}, e = {};
return d.pipe = d.then, p.each(b, function(a, f) {
var g = f[2], h = f[3];
d[f[1]] = g.add, h && g.add(function() {
c = h;
}, b[1 ^ a][2].disable, b[2][2].lock), e[f[0]] = g.fire, e[f[0] + "With"] = g.fireWith;
}), d.promise(e), a && a.call(e, e), e;
},
when: function(a) {
var b = 0, c = k.call(arguments), d = c.length, e = 1 !== d || a && p.isFunction(a.promise) ? d : 0, f = 1 === e ? a : p.Deferred(), g = function(a, b, c) {
return function(d) {
b[a] = this, c[a] = arguments.length > 1 ? k.call(arguments) : d, c === h ? f.notifyWith(b, c) : --e || f.resolveWith(b, c);
};
}, h, i, j;
if (d > 1) {
h = new Array(d), i = new Array(d), j = new Array(d);
for (;b < d; b++) c[b] && p.isFunction(c[b].promise) ? c[b].promise().done(g(b, j, c)).fail(f.reject).progress(g(b, i, h)) : --e;
}
return e || f.resolveWith(j, c), f.promise();
}
}), p.support = function() {
var b, c, d, f, g, h, i, j, k, l, m, n = e.createElement("div");
n.setAttribute("className", "t"), n.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",
c = n.getElementsByTagName("*"), d = n.getElementsByTagName("a")[0], d.style.cssText = "top:1px;float:left;opacity:.5";
if (!c || !c.length) return {};
f = e.createElement("select"), g = f.appendChild(e.createElement("option")), h = n.getElementsByTagName("input")[0],
b = {
leadingWhitespace: 3 === n.firstChild.nodeType,
tbody: !n.getElementsByTagName("tbody").length,
htmlSerialize: !!n.getElementsByTagName("link").length,
style: /top/.test(d.getAttribute("style")),
hrefNormalized: "/a" === d.getAttribute("href"),
opacity: /^0.5/.test(d.style.opacity),
cssFloat: !!d.style.cssFloat,
checkOn: "on" === h.value,
optSelected: g.selected,
getSetAttribute: "t" !== n.className,
enctype: !!e.createElement("form").enctype,
html5Clone: "<:nav></:nav>" !== e.createElement("nav").cloneNode(!0).outerHTML,
boxModel: "CSS1Compat" === e.compatMode,
submitBubbles: !0,
changeBubbles: !0,
focusinBubbles: !1,
deleteExpando: !0,
noCloneEvent: !0,
inlineBlockNeedsLayout: !1,
shrinkWrapBlocks: !1,
reliableMarginRight: !0,
boxSizingReliable: !0,
pixelPosition: !1
}, h.checked = !0, b.noCloneChecked = h.cloneNode(!0).checked, f.disabled = !0,
b.optDisabled = !g.disabled;
try {
delete n.test;
} catch (o) {
b.deleteExpando = !1;
}
!n.addEventListener && n.attachEvent && n.fireEvent && (n.attachEvent("onclick", m = function() {
b.noCloneEvent = !1;
}), n.cloneNode(!0).fireEvent("onclick"), n.detachEvent("onclick", m)), h = e.createElement("input"),
h.value = "t", h.setAttribute("type", "radio"), b.radioValue = "t" === h.value,
h.setAttribute("checked", "checked"), h.setAttribute("name", "t"), n.appendChild(h),
i = e.createDocumentFragment(), i.appendChild(n.lastChild), b.checkClone = i.cloneNode(!0).cloneNode(!0).lastChild.checked,
b.appendChecked = h.checked, i.removeChild(h), i.appendChild(n);
if (n.attachEvent) for (k in {
submit: !0,
change: !0,
focusin: !0
}) j = "on" + k, l = j in n, l || (n.setAttribute(j, "return;"), l = "function" == typeof n[j]),
b[k + "Bubbles"] = l;
return p(function() {
var c, d, f, g, h = "padding:0;margin:0;border:0;display:block;overflow:hidden;", i = e.getElementsByTagName("body")[0];
if (!i) return;
c = e.createElement("div"), c.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",
i.insertBefore(c, i.firstChild), d = e.createElement("div"), c.appendChild(d), d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>",
f = d.getElementsByTagName("td"), f[0].style.cssText = "padding:0;margin:0;border:0;display:none",
l = 0 === f[0].offsetHeight, f[0].style.display = "", f[1].style.display = "none",
b.reliableHiddenOffsets = l && 0 === f[0].offsetHeight, d.innerHTML = "", d.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",
b.boxSizing = 4 === d.offsetWidth, b.doesNotIncludeMarginInBodyOffset = 1 !== i.offsetTop,
a.getComputedStyle && (b.pixelPosition = "1%" !== (a.getComputedStyle(d, null) || {}).top,
b.boxSizingReliable = "4px" === (a.getComputedStyle(d, null) || {
width: "4px"
}).width, g = e.createElement("div"), g.style.cssText = d.style.cssText = h, g.style.marginRight = g.style.width = "0",
d.style.width = "1px", d.appendChild(g), b.reliableMarginRight = !parseFloat((a.getComputedStyle(g, null) || {}).marginRight)),
"undefined" != typeof d.style.zoom && (d.innerHTML = "", d.style.cssText = h + "width:1px;padding:1px;display:inline;zoom:1",
b.inlineBlockNeedsLayout = 3 === d.offsetWidth, d.style.display = "block", d.style.overflow = "visible",
d.innerHTML = "<div></div>", d.firstChild.style.width = "5px", b.shrinkWrapBlocks = 3 !== d.offsetWidth,
c.style.zoom = 1), i.removeChild(c), c = d = f = g = null;
}), i.removeChild(n), c = d = f = g = h = i = n = null, b;
}();
var H = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, I = /([A-Z])/g;
p.extend({
cache: {},
deletedIds: [],
uuid: 0,
expando: "jQuery" + (p.fn.jquery + Math.random()).replace(/\D/g, ""),
noData: {
embed: !0,
object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
applet: !0
},
hasData: function(a) {
return a = a.nodeType ? p.cache[a[p.expando]] : a[p.expando], !!a && !K(a);
},
data: function(a, c, d, e) {
if (!p.acceptData(a)) return;
var f, g, h = p.expando, i = "string" == typeof c, j = a.nodeType, k = j ? p.cache : a, l = j ? a[h] : a[h] && h;
if ((!l || !k[l] || !e && !k[l].data) && i && d === b) return;
l || (j ? a[h] = l = p.deletedIds.pop() || p.guid++ : l = h), k[l] || (k[l] = {},
j || (k[l].toJSON = p.noop));
if ("object" == typeof c || "function" == typeof c) e ? k[l] = p.extend(k[l], c) : k[l].data = p.extend(k[l].data, c);
return f = k[l], e || (f.data || (f.data = {}), f = f.data), d !== b && (f[p.camelCase(c)] = d),
i ? (g = f[c], null == g && (g = f[p.camelCase(c)])) : g = f, g;
},
removeData: function(a, b, c) {
if (!p.acceptData(a)) return;
var d, e, f, g = a.nodeType, h = g ? p.cache : a, i = g ? a[p.expando] : p.expando;
if (!h[i]) return;
if (b) {
d = c ? h[i] : h[i].data;
if (d) {
p.isArray(b) || (b in d ? b = [ b ] : (b = p.camelCase(b), b in d ? b = [ b ] : b = b.split(" ")));
for (e = 0, f = b.length; e < f; e++) delete d[b[e]];
if (!(c ? K : p.isEmptyObject)(d)) return;
}
}
if (!c) {
delete h[i].data;
if (!K(h[i])) return;
}
g ? p.cleanData([ a ], !0) : p.support.deleteExpando || h != h.window ? delete h[i] : h[i] = null;
},
_data: function(a, b, c) {
return p.data(a, b, c, !0);
},
acceptData: function(a) {
var b = a.nodeName && p.noData[a.nodeName.toLowerCase()];
return !b || b !== !0 && a.getAttribute("classid") === b;
}
}), p.fn.extend({
data: function(a, c) {
var d, e, f, g, h, i = this[0], j = 0, k = null;
if (a === b) {
if (this.length) {
k = p.data(i);
if (1 === i.nodeType && !p._data(i, "parsedAttrs")) {
f = i.attributes;
for (h = f.length; j < h; j++) g = f[j].name, g.indexOf("data-") || (g = p.camelCase(g.substring(5)),
J(i, g, k[g]));
p._data(i, "parsedAttrs", !0);
}
}
return k;
}
return "object" == typeof a ? this.each(function() {
p.data(this, a);
}) : (d = a.split(".", 2), d[1] = d[1] ? "." + d[1] : "", e = d[1] + "!", p.access(this, function(c) {
if (c === b) return k = this.triggerHandler("getData" + e, [ d[0] ]), k === b && i && (k = p.data(i, a),
k = J(i, a, k)), k === b && d[1] ? this.data(d[0]) : k;
d[1] = c, this.each(function() {
var b = p(this);
b.triggerHandler("setData" + e, d), p.data(this, a, c), b.triggerHandler("changeData" + e, d);
});
}, null, c, arguments.length > 1, null, !1));
},
removeData: function(a) {
return this.each(function() {
p.removeData(this, a);
});
}
}), p.extend({
queue: function(a, b, c) {
var d;
if (a) return b = (b || "fx") + "queue", d = p._data(a, b), c && (!d || p.isArray(c) ? d = p._data(a, b, p.makeArray(c)) : d.push(c)),
d || [];
},
dequeue: function(a, b) {
b = b || "fx";
var c = p.queue(a, b), d = c.length, e = c.shift(), f = p._queueHooks(a, b), g = function() {
p.dequeue(a, b);
};
"inprogress" === e && (e = c.shift(), d--), e && ("fx" === b && c.unshift("inprogress"),
delete f.stop, e.call(a, g, f)), !d && f && f.empty.fire();
},
_queueHooks: function(a, b) {
var c = b + "queueHooks";
return p._data(a, c) || p._data(a, c, {
empty: p.Callbacks("once memory").add(function() {
p.removeData(a, b + "queue", !0), p.removeData(a, c, !0);
})
});
}
}), p.fn.extend({
queue: function(a, c) {
var d = 2;
return "string" != typeof a && (c = a, a = "fx", d--), arguments.length < d ? p.queue(this[0], a) : c === b ? this : this.each(function() {
var b = p.queue(this, a, c);
p._queueHooks(this, a), "fx" === a && "inprogress" !== b[0] && p.dequeue(this, a);
});
},
dequeue: function(a) {
return this.each(function() {
p.dequeue(this, a);
});
},
delay: function(a, b) {
return a = p.fx ? p.fx.speeds[a] || a : a, b = b || "fx", this.queue(b, function(b, c) {
var d = setTimeout(b, a);
c.stop = function() {
clearTimeout(d);
};
});
},
clearQueue: function(a) {
return this.queue(a || "fx", []);
},
promise: function(a, c) {
var d, e = 1, f = p.Deferred(), g = this, h = this.length, i = function() {
--e || f.resolveWith(g, [ g ]);
};
"string" != typeof a && (c = a, a = b), a = a || "fx";
while (h--) d = p._data(g[h], a + "queueHooks"), d && d.empty && (e++, d.empty.add(i));
return i(), f.promise(c);
}
});
var L, M, N, O = /[\t\r\n]/g, P = /\r/g, Q = /^(?:button|input)$/i, R = /^(?:button|input|object|select|textarea)$/i, S = /^a(?:rea|)$/i, T = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, U = p.support.getSetAttribute;
p.fn.extend({
attr: function(a, b) {
return p.access(this, p.attr, a, b, arguments.length > 1);
},
removeAttr: function(a) {
return this.each(function() {
p.removeAttr(this, a);
});
},
prop: function(a, b) {
return p.access(this, p.prop, a, b, arguments.length > 1);
},
removeProp: function(a) {
return a = p.propFix[a] || a, this.each(function() {
try {
this[a] = b, delete this[a];
} catch (c) {}
});
},
addClass: function(a) {
var b, c, d, e, f, g, h;
if (p.isFunction(a)) return this.each(function(b) {
p(this).addClass(a.call(this, b, this.className));
});
if (a && "string" == typeof a) {
b = a.split(s);
for (c = 0, d = this.length; c < d; c++) {
e = this[c];
if (1 === e.nodeType) if (!e.className && 1 === b.length) e.className = a; else {
f = " " + e.className + " ";
for (g = 0, h = b.length; g < h; g++) f.indexOf(" " + b[g] + " ") < 0 && (f += b[g] + " ");
e.className = p.trim(f);
}
}
}
return this;
},
removeClass: function(a) {
var c, d, e, f, g, h, i;
if (p.isFunction(a)) return this.each(function(b) {
p(this).removeClass(a.call(this, b, this.className));
});
if (a && "string" == typeof a || a === b) {
c = (a || "").split(s);
for (h = 0, i = this.length; h < i; h++) {
e = this[h];
if (1 === e.nodeType && e.className) {
d = (" " + e.className + " ").replace(O, " ");
for (f = 0, g = c.length; f < g; f++) while (d.indexOf(" " + c[f] + " ") >= 0) d = d.replace(" " + c[f] + " ", " ");
e.className = a ? p.trim(d) : "";
}
}
}
return this;
},
toggleClass: function(a, b) {
var c = typeof a, d = "boolean" == typeof b;
return p.isFunction(a) ? this.each(function(c) {
p(this).toggleClass(a.call(this, c, this.className, b), b);
}) : this.each(function() {
if ("string" === c) {
var e, f = 0, g = p(this), h = b, i = a.split(s);
while (e = i[f++]) h = d ? h : !g.hasClass(e), g[h ? "addClass" : "removeClass"](e);
} else if ("undefined" === c || "boolean" === c) this.className && p._data(this, "__className__", this.className),
this.className = this.className || a === !1 ? "" : p._data(this, "__className__") || "";
});
},
hasClass: function(a) {
var b = " " + a + " ", c = 0, d = this.length;
for (;c < d; c++) if (1 === this[c].nodeType && (" " + this[c].className + " ").replace(O, " ").indexOf(b) >= 0) return !0;
return !1;
},
val: function(a) {
var c, d, e, f = this[0];
if (!arguments.length) {
if (f) return c = p.valHooks[f.type] || p.valHooks[f.nodeName.toLowerCase()], c && "get" in c && (d = c.get(f, "value")) !== b ? d : (d = f.value,
"string" == typeof d ? d.replace(P, "") : null == d ? "" : d);
return;
}
return e = p.isFunction(a), this.each(function(d) {
var f, g = p(this);
if (1 !== this.nodeType) return;
e ? f = a.call(this, d, g.val()) : f = a, null == f ? f = "" : "number" == typeof f ? f += "" : p.isArray(f) && (f = p.map(f, function(a) {
return null == a ? "" : a + "";
})), c = p.valHooks[this.type] || p.valHooks[this.nodeName.toLowerCase()];
if (!c || !("set" in c) || c.set(this, f, "value") === b) this.value = f;
});
}
}), p.extend({
valHooks: {
option: {
get: function(a) {
var b = a.attributes.value;
return !b || b.specified ? a.value : a.text;
}
},
select: {
get: function(a) {
var b, c, d, e, f = a.selectedIndex, g = [], h = a.options, i = "select-one" === a.type;
if (f < 0) return null;
c = i ? f : 0, d = i ? f + 1 : h.length;
for (;c < d; c++) {
e = h[c];
if (e.selected && (p.support.optDisabled ? !e.disabled : null === e.getAttribute("disabled")) && (!e.parentNode.disabled || !p.nodeName(e.parentNode, "optgroup"))) {
b = p(e).val();
if (i) return b;
g.push(b);
}
}
return i && !g.length && h.length ? p(h[f]).val() : g;
},
set: function(a, b) {
var c = p.makeArray(b);
return p(a).find("option").each(function() {
this.selected = p.inArray(p(this).val(), c) >= 0;
}), c.length || (a.selectedIndex = -1), c;
}
}
},
attrFn: {},
attr: function(a, c, d, e) {
var f, g, h, i = a.nodeType;
if (!a || 3 === i || 8 === i || 2 === i) return;
if (e && p.isFunction(p.fn[c])) return p(a)[c](d);
if ("undefined" == typeof a.getAttribute) return p.prop(a, c, d);
h = 1 !== i || !p.isXMLDoc(a), h && (c = c.toLowerCase(), g = p.attrHooks[c] || (T.test(c) ? M : L));
if (d !== b) {
if (null === d) {
p.removeAttr(a, c);
return;
}
return g && "set" in g && h && (f = g.set(a, d, c)) !== b ? f : (a.setAttribute(c, d + ""),
d);
}
return g && "get" in g && h && null !== (f = g.get(a, c)) ? f : (f = a.getAttribute(c),
null === f ? b : f);
},
removeAttr: function(a, b) {
var c, d, e, f, g = 0;
if (b && 1 === a.nodeType) {
d = b.split(s);
for (;g < d.length; g++) e = d[g], e && (c = p.propFix[e] || e, f = T.test(e), f || p.attr(a, e, ""),
a.removeAttribute(U ? e : c), f && c in a && (a[c] = !1));
}
},
attrHooks: {
type: {
set: function(a, b) {
if (Q.test(a.nodeName) && a.parentNode) p.error("type property can't be changed"); else if (!p.support.radioValue && "radio" === b && p.nodeName(a, "input")) {
var c = a.value;
return a.setAttribute("type", b), c && (a.value = c), b;
}
}
},
value: {
get: function(a, b) {
return L && p.nodeName(a, "button") ? L.get(a, b) : b in a ? a.value : null;
},
set: function(a, b, c) {
if (L && p.nodeName(a, "button")) return L.set(a, b, c);
a.value = b;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function(a, c, d) {
var e, f, g, h = a.nodeType;
if (!a || 3 === h || 8 === h || 2 === h) return;
return g = 1 !== h || !p.isXMLDoc(a), g && (c = p.propFix[c] || c, f = p.propHooks[c]),
d !== b ? f && "set" in f && (e = f.set(a, d, c)) !== b ? e : a[c] = d : f && "get" in f && null !== (e = f.get(a, c)) ? e : a[c];
},
propHooks: {
tabIndex: {
get: function(a) {
var c = a.getAttributeNode("tabindex");
return c && c.specified ? parseInt(c.value, 10) : R.test(a.nodeName) || S.test(a.nodeName) && a.href ? 0 : b;
}
}
}
}), M = {
get: function(a, c) {
var d, e = p.prop(a, c);
return e === !0 || "boolean" != typeof e && (d = a.getAttributeNode(c)) && d.nodeValue !== !1 ? c.toLowerCase() : b;
},
set: function(a, b, c) {
var d;
return b === !1 ? p.removeAttr(a, c) : (d = p.propFix[c] || c, d in a && (a[d] = !0),
a.setAttribute(c, c.toLowerCase())), c;
}
}, U || (N = {
name: !0,
id: !0,
coords: !0
}, L = p.valHooks.button = {
get: function(a, c) {
var d;
return d = a.getAttributeNode(c), d && (N[c] ? "" !== d.value : d.specified) ? d.value : b;
},
set: function(a, b, c) {
var d = a.getAttributeNode(c);
return d || (d = e.createAttribute(c), a.setAttributeNode(d)), d.value = b + "";
}
}, p.each([ "width", "height" ], function(a, b) {
p.attrHooks[b] = p.extend(p.attrHooks[b], {
set: function(a, c) {
if ("" === c) return a.setAttribute(b, "auto"), c;
}
});
}), p.attrHooks.contenteditable = {
get: L.get,
set: function(a, b, c) {
"" === b && (b = "false"), L.set(a, b, c);
}
}), p.support.hrefNormalized || p.each([ "href", "src", "width", "height" ], function(a, c) {
p.attrHooks[c] = p.extend(p.attrHooks[c], {
get: function(a) {
var d = a.getAttribute(c, 2);
return null === d ? b : d;
}
});
}), p.support.style || (p.attrHooks.style = {
get: function(a) {
return a.style.cssText.toLowerCase() || b;
},
set: function(a, b) {
return a.style.cssText = b + "";
}
}), p.support.optSelected || (p.propHooks.selected = p.extend(p.propHooks.selected, {
get: function(a) {
var b = a.parentNode;
return b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex), null;
}
})), p.support.enctype || (p.propFix.enctype = "encoding"), p.support.checkOn || p.each([ "radio", "checkbox" ], function() {
p.valHooks[this] = {
get: function(a) {
return null === a.getAttribute("value") ? "on" : a.value;
}
};
}), p.each([ "radio", "checkbox" ], function() {
p.valHooks[this] = p.extend(p.valHooks[this], {
set: function(a, b) {
if (p.isArray(b)) return a.checked = p.inArray(p(a).val(), b) >= 0;
}
});
});
var V = /^(?:textarea|input|select)$/i, W = /^([^\.]*|)(?:\.(.+)|)$/, X = /(?:^|\s)hover(\.\S+|)\b/, Y = /^key/, Z = /^(?:mouse|contextmenu)|click/, $ = /^(?:focusinfocus|focusoutblur)$/, _ = function(a) {
return p.event.special.hover ? a : a.replace(X, "mouseenter$1 mouseleave$1");
};
p.event = {
add: function(a, c, d, e, f) {
var g, h, i, j, k, l, m, n, o, q, r;
if (3 === a.nodeType || 8 === a.nodeType || !c || !d || !(g = p._data(a))) return;
d.handler && (o = d, d = o.handler, f = o.selector), d.guid || (d.guid = p.guid++),
i = g.events, i || (g.events = i = {}), h = g.handle, h || (g.handle = h = function(a) {
return "undefined" != typeof p && (!a || p.event.triggered !== a.type) ? p.event.dispatch.apply(h.elem, arguments) : b;
}, h.elem = a), c = p.trim(_(c)).split(" ");
for (j = 0; j < c.length; j++) {
k = W.exec(c[j]) || [], l = k[1], m = (k[2] || "").split(".").sort(), r = p.event.special[l] || {},
l = (f ? r.delegateType : r.bindType) || l, r = p.event.special[l] || {}, n = p.extend({
type: l,
origType: k[1],
data: e,
handler: d,
guid: d.guid,
selector: f,
needsContext: f && p.expr.match.needsContext.test(f),
namespace: m.join(".")
}, o), q = i[l];
if (!q) {
q = i[l] = [], q.delegateCount = 0;
if (!r.setup || r.setup.call(a, e, m, h) === !1) a.addEventListener ? a.addEventListener(l, h, !1) : a.attachEvent && a.attachEvent("on" + l, h);
}
r.add && (r.add.call(a, n), n.handler.guid || (n.handler.guid = d.guid)), f ? q.splice(q.delegateCount++, 0, n) : q.push(n),
p.event.global[l] = !0;
}
a = null;
},
global: {},
remove: function(a, b, c, d, e) {
var f, g, h, i, j, k, l, m, n, o, q, r = p.hasData(a) && p._data(a);
if (!r || !(m = r.events)) return;
b = p.trim(_(b || "")).split(" ");
for (f = 0; f < b.length; f++) {
g = W.exec(b[f]) || [], h = i = g[1], j = g[2];
if (!h) {
for (h in m) p.event.remove(a, h + b[f], c, d, !0);
continue;
}
n = p.event.special[h] || {}, h = (d ? n.delegateType : n.bindType) || h, o = m[h] || [],
k = o.length, j = j ? new RegExp("(^|\\.)" + j.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
for (l = 0; l < o.length; l++) q = o[l], (e || i === q.origType) && (!c || c.guid === q.guid) && (!j || j.test(q.namespace)) && (!d || d === q.selector || "**" === d && q.selector) && (o.splice(l--, 1),
q.selector && o.delegateCount--, n.remove && n.remove.call(a, q));
0 === o.length && k !== o.length && ((!n.teardown || n.teardown.call(a, j, r.handle) === !1) && p.removeEvent(a, h, r.handle),
delete m[h]);
}
p.isEmptyObject(m) && (delete r.handle, p.removeData(a, "events", !0));
},
customEvent: {
getData: !0,
setData: !0,
changeData: !0
},
trigger: function(c, d, f, g) {
if (!f || 3 !== f.nodeType && 8 !== f.nodeType) {
var h, i, j, k, l, m, n, o, q, r, s = c.type || c, t = [];
if ($.test(s + p.event.triggered)) return;
s.indexOf("!") >= 0 && (s = s.slice(0, -1), i = !0), s.indexOf(".") >= 0 && (t = s.split("."),
s = t.shift(), t.sort());
if ((!f || p.event.customEvent[s]) && !p.event.global[s]) return;
c = "object" == typeof c ? c[p.expando] ? c : new p.Event(s, c) : new p.Event(s),
c.type = s, c.isTrigger = !0, c.exclusive = i, c.namespace = t.join("."), c.namespace_re = c.namespace ? new RegExp("(^|\\.)" + t.join("\\.(?:.*\\.|)") + "(\\.|$)") : null,
m = s.indexOf(":") < 0 ? "on" + s : "";
if (!f) {
h = p.cache;
for (j in h) h[j].events && h[j].events[s] && p.event.trigger(c, d, h[j].handle.elem, !0);
return;
}
c.result = b, c.target || (c.target = f), d = null != d ? p.makeArray(d) : [], d.unshift(c),
n = p.event.special[s] || {};
if (n.trigger && n.trigger.apply(f, d) === !1) return;
q = [ [ f, n.bindType || s ] ];
if (!g && !n.noBubble && !p.isWindow(f)) {
r = n.delegateType || s, k = $.test(r + s) ? f : f.parentNode;
for (l = f; k; k = k.parentNode) q.push([ k, r ]), l = k;
l === (f.ownerDocument || e) && q.push([ l.defaultView || l.parentWindow || a, r ]);
}
for (j = 0; j < q.length && !c.isPropagationStopped(); j++) k = q[j][0], c.type = q[j][1],
o = (p._data(k, "events") || {})[c.type] && p._data(k, "handle"), o && o.apply(k, d),
o = m && k[m], o && p.acceptData(k) && o.apply && o.apply(k, d) === !1 && c.preventDefault();
return c.type = s, !g && !c.isDefaultPrevented() && (!n._default || n._default.apply(f.ownerDocument, d) === !1) && ("click" !== s || !p.nodeName(f, "a")) && p.acceptData(f) && m && f[s] && ("focus" !== s && "blur" !== s || 0 !== c.target.offsetWidth) && !p.isWindow(f) && (l = f[m],
l && (f[m] = null), p.event.triggered = s, f[s](), p.event.triggered = b, l && (f[m] = l)),
c.result;
}
return;
},
dispatch: function(c) {
c = p.event.fix(c || a.event);
var d, e, f, g, h, i, j, l, m, n, o = (p._data(this, "events") || {})[c.type] || [], q = o.delegateCount, r = k.call(arguments), s = !c.exclusive && !c.namespace, t = p.event.special[c.type] || {}, u = [];
r[0] = c, c.delegateTarget = this;
if (t.preDispatch && t.preDispatch.call(this, c) === !1) return;
if (q && (!c.button || "click" !== c.type)) for (f = c.target; f != this; f = f.parentNode || this) if (f.disabled !== !0 || "click" !== c.type) {
h = {}, j = [];
for (d = 0; d < q; d++) l = o[d], m = l.selector, h[m] === b && (h[m] = l.needsContext ? p(m, this).index(f) >= 0 : p.find(m, this, null, [ f ]).length),
h[m] && j.push(l);
j.length && u.push({
elem: f,
matches: j
});
}
o.length > q && u.push({
elem: this,
matches: o.slice(q)
});
for (d = 0; d < u.length && !c.isPropagationStopped(); d++) {
i = u[d], c.currentTarget = i.elem;
for (e = 0; e < i.matches.length && !c.isImmediatePropagationStopped(); e++) {
l = i.matches[e];
if (s || !c.namespace && !l.namespace || c.namespace_re && c.namespace_re.test(l.namespace)) c.data = l.data,
c.handleObj = l, g = ((p.event.special[l.origType] || {}).handle || l.handler).apply(i.elem, r),
g !== b && (c.result = g, g === !1 && (c.preventDefault(), c.stopPropagation()));
}
}
return t.postDispatch && t.postDispatch.call(this, c), c.result;
},
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(a, b) {
return null == a.which && (a.which = null != b.charCode ? b.charCode : b.keyCode),
a;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function(a, c) {
var d, f, g, h = c.button, i = c.fromElement;
return null == a.pageX && null != c.clientX && (d = a.target.ownerDocument || e,
f = d.documentElement, g = d.body, a.pageX = c.clientX + (f && f.scrollLeft || g && g.scrollLeft || 0) - (f && f.clientLeft || g && g.clientLeft || 0),
a.pageY = c.clientY + (f && f.scrollTop || g && g.scrollTop || 0) - (f && f.clientTop || g && g.clientTop || 0)),
!a.relatedTarget && i && (a.relatedTarget = i === a.target ? c.toElement : i), !a.which && h !== b && (a.which = 1 & h ? 1 : 2 & h ? 3 : 4 & h ? 2 : 0),
a;
}
},
fix: function(a) {
if (a[p.expando]) return a;
var b, c, d = a, f = p.event.fixHooks[a.type] || {}, g = f.props ? this.props.concat(f.props) : this.props;
a = p.Event(d);
for (b = g.length; b; ) c = g[--b], a[c] = d[c];
return a.target || (a.target = d.srcElement || e), 3 === a.target.nodeType && (a.target = a.target.parentNode),
a.metaKey = !!a.metaKey, f.filter ? f.filter(a, d) : a;
},
special: {
load: {
noBubble: !0
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function(a, b, c) {
p.isWindow(this) && (this.onbeforeunload = c);
},
teardown: function(a, b) {
this.onbeforeunload === b && (this.onbeforeunload = null);
}
}
},
simulate: function(a, b, c, d) {
var e = p.extend(new p.Event(), c, {
type: a,
isSimulated: !0,
originalEvent: {}
});
d ? p.event.trigger(e, null, b) : p.event.dispatch.call(b, e), e.isDefaultPrevented() && c.preventDefault();
}
}, p.event.handle = p.event.dispatch, p.removeEvent = e.removeEventListener ? function(a, b, c) {
a.removeEventListener && a.removeEventListener(b, c, !1);
} : function(a, b, c) {
var d = "on" + b;
a.detachEvent && ("undefined" == typeof a[d] && (a[d] = null), a.detachEvent(d, c));
}, p.Event = function(a, b) {
if (this instanceof p.Event) a && a.type ? (this.originalEvent = a, this.type = a.type,
this.isDefaultPrevented = a.defaultPrevented || a.returnValue === !1 || a.getPreventDefault && a.getPreventDefault() ? bb : ba) : this.type = a,
b && p.extend(this, b), this.timeStamp = a && a.timeStamp || p.now(), this[p.expando] = !0; else return new p.Event(a, b);
}, p.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = bb;
var a = this.originalEvent;
if (!a) return;
a.preventDefault ? a.preventDefault() : a.returnValue = !1;
},
stopPropagation: function() {
this.isPropagationStopped = bb;
var a = this.originalEvent;
if (!a) return;
a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = bb, this.stopPropagation();
},
isDefaultPrevented: ba,
isPropagationStopped: ba,
isImmediatePropagationStopped: ba
}, p.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function(a, b) {
p.event.special[a] = {
delegateType: b,
bindType: b,
handle: function(a) {
var c, d = this, e = a.relatedTarget, f = a.handleObj, g = f.selector;
if (!e || e !== d && !p.contains(d, e)) a.type = f.origType, c = f.handler.apply(this, arguments),
a.type = b;
return c;
}
};
}), p.support.submitBubbles || (p.event.special.submit = {
setup: function() {
if (p.nodeName(this, "form")) return !1;
p.event.add(this, "click._submit keypress._submit", function(a) {
var c = a.target, d = p.nodeName(c, "input") || p.nodeName(c, "button") ? c.form : b;
d && !p._data(d, "_submit_attached") && (p.event.add(d, "submit._submit", function(a) {
a._submit_bubble = !0;
}), p._data(d, "_submit_attached", !0));
});
},
postDispatch: function(a) {
a._submit_bubble && (delete a._submit_bubble, this.parentNode && !a.isTrigger && p.event.simulate("submit", this.parentNode, a, !0));
},
teardown: function() {
if (p.nodeName(this, "form")) return !1;
p.event.remove(this, "._submit");
}
}), p.support.changeBubbles || (p.event.special.change = {
setup: function() {
if (V.test(this.nodeName)) {
if ("checkbox" === this.type || "radio" === this.type) p.event.add(this, "propertychange._change", function(a) {
"checked" === a.originalEvent.propertyName && (this._just_changed = !0);
}), p.event.add(this, "click._change", function(a) {
this._just_changed && !a.isTrigger && (this._just_changed = !1), p.event.simulate("change", this, a, !0);
});
return !1;
}
p.event.add(this, "beforeactivate._change", function(a) {
var b = a.target;
V.test(b.nodeName) && !p._data(b, "_change_attached") && (p.event.add(b, "change._change", function(a) {
this.parentNode && !a.isSimulated && !a.isTrigger && p.event.simulate("change", this.parentNode, a, !0);
}), p._data(b, "_change_attached", !0));
});
},
handle: function(a) {
var b = a.target;
if (this !== b || a.isSimulated || a.isTrigger || "radio" !== b.type && "checkbox" !== b.type) return a.handleObj.handler.apply(this, arguments);
},
teardown: function() {
return p.event.remove(this, "._change"), !V.test(this.nodeName);
}
}), p.support.focusinBubbles || p.each({
focus: "focusin",
blur: "focusout"
}, function(a, b) {
var c = 0, d = function(a) {
p.event.simulate(b, a.target, p.event.fix(a), !0);
};
p.event.special[b] = {
setup: function() {
0 === c++ && e.addEventListener(a, d, !0);
},
teardown: function() {
0 === --c && e.removeEventListener(a, d, !0);
}
};
}), p.fn.extend({
on: function(a, c, d, e, f) {
var g, h;
if ("object" == typeof a) {
"string" != typeof c && (d = d || c, c = b);
for (h in a) this.on(h, c, d, a[h], f);
return this;
}
null == d && null == e ? (e = c, d = c = b) : null == e && ("string" == typeof c ? (e = d,
d = b) : (e = d, d = c, c = b));
if (e === !1) e = ba; else if (!e) return this;
return 1 === f && (g = e, e = function(a) {
return p().off(a), g.apply(this, arguments);
}, e.guid = g.guid || (g.guid = p.guid++)), this.each(function() {
p.event.add(this, a, e, d, c);
});
},
one: function(a, b, c, d) {
return this.on(a, b, c, d, 1);
},
off: function(a, c, d) {
var e, f;
if (a && a.preventDefault && a.handleObj) return e = a.handleObj, p(a.delegateTarget).off(e.namespace ? e.origType + "." + e.namespace : e.origType, e.selector, e.handler),
this;
if ("object" == typeof a) {
for (f in a) this.off(f, c, a[f]);
return this;
}
if (c === !1 || "function" == typeof c) d = c, c = b;
return d === !1 && (d = ba), this.each(function() {
p.event.remove(this, a, d, c);
});
},
bind: function(a, b, c) {
return this.on(a, null, b, c);
},
unbind: function(a, b) {
return this.off(a, null, b);
},
live: function(a, b, c) {
return p(this.context).on(a, this.selector, b, c), this;
},
die: function(a, b) {
return p(this.context).off(a, this.selector || "**", b), this;
},
delegate: function(a, b, c, d) {
return this.on(b, a, c, d);
},
undelegate: function(a, b, c) {
return 1 === arguments.length ? this.off(a, "**") : this.off(b, a || "**", c);
},
trigger: function(a, b) {
return this.each(function() {
p.event.trigger(a, b, this);
});
},
triggerHandler: function(a, b) {
if (this[0]) return p.event.trigger(a, b, this[0], !0);
},
toggle: function(a) {
var b = arguments, c = a.guid || p.guid++, d = 0, e = function(c) {
var e = (p._data(this, "lastToggle" + a.guid) || 0) % d;
return p._data(this, "lastToggle" + a.guid, e + 1), c.preventDefault(), b[e].apply(this, arguments) || !1;
};
e.guid = c;
while (d < b.length) b[d++].guid = c;
return this.click(e);
},
hover: function(a, b) {
return this.mouseenter(a).mouseleave(b || a);
}
}), p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function(a, b) {
p.fn[b] = function(a, c) {
return null == c && (c = a, a = null), arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b);
}, Y.test(b) && (p.event.fixHooks[b] = p.event.keyHooks), Z.test(b) && (p.event.fixHooks[b] = p.event.mouseHooks);
}), function(a, b) {
function bc(a, b, c, d) {
c = c || [], b = b || r;
var e, f, i, j, k = b.nodeType;
if (!a || "string" != typeof a) return c;
if (1 !== k && 9 !== k) return [];
i = g(b);
if (!i && !d) if (e = P.exec(a)) if (j = e[1]) {
if (9 === k) {
f = b.getElementById(j);
if (!f || !f.parentNode) return c;
if (f.id === j) return c.push(f), c;
} else if (b.ownerDocument && (f = b.ownerDocument.getElementById(j)) && h(b, f) && f.id === j) return c.push(f),
c;
} else {
if (e[2]) return w.apply(c, x.call(b.getElementsByTagName(a), 0)), c;
if ((j = e[3]) && _ && b.getElementsByClassName) return w.apply(c, x.call(b.getElementsByClassName(j), 0)),
c;
}
return bp(a.replace(L, "$1"), b, c, d, i);
}
function bd(a) {
return function(b) {
var c = b.nodeName.toLowerCase();
return "input" === c && b.type === a;
};
}
function be(a) {
return function(b) {
var c = b.nodeName.toLowerCase();
return ("input" === c || "button" === c) && b.type === a;
};
}
function bf(a) {
return z(function(b) {
return b = +b, z(function(c, d) {
var e, f = a([], c.length, b), g = f.length;
while (g--) c[e = f[g]] && (c[e] = !(d[e] = c[e]));
});
});
}
function bg(a, b, c) {
if (a === b) return c;
var d = a.nextSibling;
while (d) {
if (d === b) return -1;
d = d.nextSibling;
}
return 1;
}
function bh(a, b) {
var c, d, f, g, h, i, j, k = C[o][a];
if (k) return b ? 0 : k.slice(0);
h = a, i = [], j = e.preFilter;
while (h) {
if (!c || (d = M.exec(h))) d && (h = h.slice(d[0].length)), i.push(f = []);
c = !1;
if (d = N.exec(h)) f.push(c = new q(d.shift())), h = h.slice(c.length), c.type = d[0].replace(L, " ");
for (g in e.filter) (d = W[g].exec(h)) && (!j[g] || (d = j[g](d, r, !0))) && (f.push(c = new q(d.shift())),
h = h.slice(c.length), c.type = g, c.matches = d);
if (!c) break;
}
return b ? h.length : h ? bc.error(a) : C(a, i).slice(0);
}
function bi(a, b, d) {
var e = b.dir, f = d && "parentNode" === b.dir, g = u++;
return b.first ? function(b, c, d) {
while (b = b[e]) if (f || 1 === b.nodeType) return a(b, c, d);
} : function(b, d, h) {
if (!h) {
var i, j = t + " " + g + " ", k = j + c;
while (b = b[e]) if (f || 1 === b.nodeType) {
if ((i = b[o]) === k) return b.sizset;
if ("string" == typeof i && 0 === i.indexOf(j)) {
if (b.sizset) return b;
} else {
b[o] = k;
if (a(b, d, h)) return b.sizset = !0, b;
b.sizset = !1;
}
}
} else while (b = b[e]) if (f || 1 === b.nodeType) if (a(b, d, h)) return b;
};
}
function bj(a) {
return a.length > 1 ? function(b, c, d) {
var e = a.length;
while (e--) if (!a[e](b, c, d)) return !1;
return !0;
} : a[0];
}
function bk(a, b, c, d, e) {
var f, g = [], h = 0, i = a.length, j = null != b;
for (;h < i; h++) if (f = a[h]) if (!c || c(f, d, e)) g.push(f), j && b.push(h);
return g;
}
function bl(a, b, c, d, e, f) {
return d && !d[o] && (d = bl(d)), e && !e[o] && (e = bl(e, f)), z(function(f, g, h, i) {
if (f && e) return;
var j, k, l, m = [], n = [], o = g.length, p = f || bo(b || "*", h.nodeType ? [ h ] : h, [], f), q = a && (f || !b) ? bk(p, m, a, h, i) : p, r = c ? e || (f ? a : o || d) ? [] : g : q;
c && c(q, r, h, i);
if (d) {
l = bk(r, n), d(l, [], h, i), j = l.length;
while (j--) if (k = l[j]) r[n[j]] = !(q[n[j]] = k);
}
if (f) {
j = a && r.length;
while (j--) if (k = r[j]) f[m[j]] = !(g[m[j]] = k);
} else r = bk(r === g ? r.splice(o, r.length) : r), e ? e(null, g, r, i) : w.apply(g, r);
});
}
function bm(a) {
var b, c, d, f = a.length, g = e.relative[a[0].type], h = g || e.relative[" "], i = g ? 1 : 0, j = bi(function(a) {
return a === b;
}, h, !0), k = bi(function(a) {
return y.call(b, a) > -1;
}, h, !0), m = [ function(a, c, d) {
return !g && (d || c !== l) || ((b = c).nodeType ? j(a, c, d) : k(a, c, d));
} ];
for (;i < f; i++) if (c = e.relative[a[i].type]) m = [ bi(bj(m), c) ]; else {
c = e.filter[a[i].type].apply(null, a[i].matches);
if (c[o]) {
d = ++i;
for (;d < f; d++) if (e.relative[a[d].type]) break;
return bl(i > 1 && bj(m), i > 1 && a.slice(0, i - 1).join("").replace(L, "$1"), c, i < d && bm(a.slice(i, d)), d < f && bm(a = a.slice(d)), d < f && a.join(""));
}
m.push(c);
}
return bj(m);
}
function bn(a, b) {
var d = b.length > 0, f = a.length > 0, g = function(h, i, j, k, m) {
var n, o, p, q = [], s = 0, u = "0", x = h && [], y = null != m, z = l, A = h || f && e.find.TAG("*", m && i.parentNode || i), B = t += null == z ? 1 : Math.E;
y && (l = i !== r && i, c = g.el);
for (;null != (n = A[u]); u++) {
if (f && n) {
for (o = 0; p = a[o]; o++) if (p(n, i, j)) {
k.push(n);
break;
}
y && (t = B, c = ++g.el);
}
d && ((n = !p && n) && s--, h && x.push(n));
}
s += u;
if (d && u !== s) {
for (o = 0; p = b[o]; o++) p(x, q, i, j);
if (h) {
if (s > 0) while (u--) !x[u] && !q[u] && (q[u] = v.call(k));
q = bk(q);
}
w.apply(k, q), y && !h && q.length > 0 && s + b.length > 1 && bc.uniqueSort(k);
}
return y && (t = B, l = z), x;
};
return g.el = 0, d ? z(g) : g;
}
function bo(a, b, c, d) {
var e = 0, f = b.length;
for (;e < f; e++) bc(a, b[e], c, d);
return c;
}
function bp(a, b, c, d, f) {
var g, h, j, k, l, m = bh(a), n = m.length;
if (!d && 1 === m.length) {
h = m[0] = m[0].slice(0);
if (h.length > 2 && "ID" === (j = h[0]).type && 9 === b.nodeType && !f && e.relative[h[1].type]) {
b = e.find.ID(j.matches[0].replace(V, ""), b, f)[0];
if (!b) return c;
a = a.slice(h.shift().length);
}
for (g = W.POS.test(a) ? -1 : h.length - 1; g >= 0; g--) {
j = h[g];
if (e.relative[k = j.type]) break;
if (l = e.find[k]) if (d = l(j.matches[0].replace(V, ""), R.test(h[0].type) && b.parentNode || b, f)) {
h.splice(g, 1), a = d.length && h.join("");
if (!a) return w.apply(c, x.call(d, 0)), c;
break;
}
}
}
return i(a, m)(d, b, f, c, R.test(a)), c;
}
function bq() {}
var c, d, e, f, g, h, i, j, k, l, m = !0, n = "undefined", o = ("sizcache" + Math.random()).replace(".", ""), q = String, r = a.document, s = r.documentElement, t = 0, u = 0, v = [].pop, w = [].push, x = [].slice, y = [].indexOf || function(a) {
var b = 0, c = this.length;
for (;b < c; b++) if (this[b] === a) return b;
return -1;
}, z = function(a, b) {
return a[o] = null == b || b, a;
}, A = function() {
var a = {}, b = [];
return z(function(c, d) {
return b.push(c) > e.cacheLength && delete a[b.shift()], a[c] = d;
}, a);
}, B = A(), C = A(), D = A(), E = "[\\x20\\t\\r\\n\\f]", F = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", G = F.replace("w", "w#"), H = "([*^$|!~]?=)", I = "\\[" + E + "*(" + F + ")" + E + "*(?:" + H + E + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + G + ")|)|)" + E + "*\\]", J = ":(" + F + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + I + ")|[^:]|\\\\.)*|.*))\\)|)", K = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + E + "*((?:-\\d)?\\d*)" + E + "*\\)|)(?=[^-]|$)", L = new RegExp("^" + E + "+|((?:^|[^\\\\])(?:\\\\.)*)" + E + "+$", "g"), M = new RegExp("^" + E + "*," + E + "*"), N = new RegExp("^" + E + "*([\\x20\\t\\r\\n\\f>+~])" + E + "*"), O = new RegExp(J), P = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, Q = /^:not/, R = /[\x20\t\r\n\f]*[+~]/, S = /:not\($/, T = /h\d/i, U = /input|select|textarea|button/i, V = /\\(?!\\)/g, W = {
ID: new RegExp("^#(" + F + ")"),
CLASS: new RegExp("^\\.(" + F + ")"),
NAME: new RegExp("^\\[name=['\"]?(" + F + ")['\"]?\\]"),
TAG: new RegExp("^(" + F.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + I),
PSEUDO: new RegExp("^" + J),
POS: new RegExp(K, "i"),
CHILD: new RegExp("^:(only|nth|first|last)-child(?:\\(" + E + "*(even|odd|(([+-]|)(\\d*)n|)" + E + "*(?:([+-]|)" + E + "*(\\d+)|))" + E + "*\\)|)", "i"),
needsContext: new RegExp("^" + E + "*[>+~]|" + K, "i")
}, X = function(a) {
var b = r.createElement("div");
try {
return a(b);
} catch (c) {
return !1;
} finally {
b = null;
}
}, Y = X(function(a) {
return a.appendChild(r.createComment("")), !a.getElementsByTagName("*").length;
}), Z = X(function(a) {
return a.innerHTML = "<a href='#'></a>", a.firstChild && typeof a.firstChild.getAttribute !== n && "#" === a.firstChild.getAttribute("href");
}), $ = X(function(a) {
a.innerHTML = "<select></select>";
var b = typeof a.lastChild.getAttribute("multiple");
return "boolean" !== b && "string" !== b;
}), _ = X(function(a) {
return a.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !a.getElementsByClassName || !a.getElementsByClassName("e").length ? !1 : (a.lastChild.className = "e",
2 === a.getElementsByClassName("e").length);
}), ba = X(function(a) {
a.id = o + 0, a.innerHTML = "<a name='" + o + "'></a><div name='" + o + "'></div>",
s.insertBefore(a, s.firstChild);
var b = r.getElementsByName && r.getElementsByName(o).length === 2 + r.getElementsByName(o + 0).length;
return d = !r.getElementById(o), s.removeChild(a), b;
});
try {
x.call(s.childNodes, 0)[0].nodeType;
} catch (bb) {
x = function(a) {
var b, c = [];
for (;b = this[a]; a++) c.push(b);
return c;
};
}
bc.matches = function(a, b) {
return bc(a, null, null, b);
}, bc.matchesSelector = function(a, b) {
return bc(b, null, null, [ a ]).length > 0;
}, f = bc.getText = function(a) {
var b, c = "", d = 0, e = a.nodeType;
if (e) {
if (1 === e || 9 === e || 11 === e) {
if ("string" == typeof a.textContent) return a.textContent;
for (a = a.firstChild; a; a = a.nextSibling) c += f(a);
} else if (3 === e || 4 === e) return a.nodeValue;
} else for (;b = a[d]; d++) c += f(b);
return c;
}, g = bc.isXML = function(a) {
var b = a && (a.ownerDocument || a).documentElement;
return b ? "HTML" !== b.nodeName : !1;
}, h = bc.contains = s.contains ? function(a, b) {
var c = 9 === a.nodeType ? a.documentElement : a, d = b && b.parentNode;
return a === d || !!(d && 1 === d.nodeType && c.contains && c.contains(d));
} : s.compareDocumentPosition ? function(a, b) {
return b && !!(16 & a.compareDocumentPosition(b));
} : function(a, b) {
while (b = b.parentNode) if (b === a) return !0;
return !1;
}, bc.attr = function(a, b) {
var c, d = g(a);
return d || (b = b.toLowerCase()), (c = e.attrHandle[b]) ? c(a) : d || $ ? a.getAttribute(b) : (c = a.getAttributeNode(b),
c ? "boolean" == typeof a[b] ? a[b] ? b : null : c.specified ? c.value : null : null);
}, e = bc.selectors = {
cacheLength: 50,
createPseudo: z,
match: W,
attrHandle: Z ? {} : {
href: function(a) {
return a.getAttribute("href", 2);
},
type: function(a) {
return a.getAttribute("type");
}
},
find: {
ID: d ? function(a, b, c) {
if (typeof b.getElementById !== n && !c) {
var d = b.getElementById(a);
return d && d.parentNode ? [ d ] : [];
}
} : function(a, c, d) {
if (typeof c.getElementById !== n && !d) {
var e = c.getElementById(a);
return e ? e.id === a || typeof e.getAttributeNode !== n && e.getAttributeNode("id").value === a ? [ e ] : b : [];
}
},
TAG: Y ? function(a, b) {
if (typeof b.getElementsByTagName !== n) return b.getElementsByTagName(a);
} : function(a, b) {
var c = b.getElementsByTagName(a);
if ("*" === a) {
var d, e = [], f = 0;
for (;d = c[f]; f++) 1 === d.nodeType && e.push(d);
return e;
}
return c;
},
NAME: ba && function(a, b) {
if (typeof b.getElementsByName !== n) return b.getElementsByName(name);
},
CLASS: _ && function(a, b, c) {
if (typeof b.getElementsByClassName !== n && !c) return b.getElementsByClassName(a);
}
},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(a) {
return a[1] = a[1].replace(V, ""), a[3] = (a[4] || a[5] || "").replace(V, ""), "~=" === a[2] && (a[3] = " " + a[3] + " "),
a.slice(0, 4);
},
CHILD: function(a) {
return a[1] = a[1].toLowerCase(), "nth" === a[1] ? (a[2] || bc.error(a[0]), a[3] = +(a[3] ? a[4] + (a[5] || 1) : 2 * ("even" === a[2] || "odd" === a[2])),
a[4] = +(a[6] + a[7] || "odd" === a[2])) : a[2] && bc.error(a[0]), a;
},
PSEUDO: function(a) {
var b, c;
if (W.CHILD.test(a[0])) return null;
if (a[3]) a[2] = a[3]; else if (b = a[4]) O.test(b) && (c = bh(b, !0)) && (c = b.indexOf(")", b.length - c) - b.length) && (b = b.slice(0, c),
a[0] = a[0].slice(0, c)), a[2] = b;
return a.slice(0, 3);
}
},
filter: {
ID: d ? function(a) {
return a = a.replace(V, ""), function(b) {
return b.getAttribute("id") === a;
};
} : function(a) {
return a = a.replace(V, ""), function(b) {
var c = typeof b.getAttributeNode !== n && b.getAttributeNode("id");
return c && c.value === a;
};
},
TAG: function(a) {
return "*" === a ? function() {
return !0;
} : (a = a.replace(V, "").toLowerCase(), function(b) {
return b.nodeName && b.nodeName.toLowerCase() === a;
});
},
CLASS: function(a) {
var b = B[o][a];
return b || (b = B(a, new RegExp("(^|" + E + ")" + a + "(" + E + "|$)"))), function(a) {
return b.test(a.className || typeof a.getAttribute !== n && a.getAttribute("class") || "");
};
},
ATTR: function(a, b, c) {
return function(d, e) {
var f = bc.attr(d, a);
return null == f ? "!=" === b : b ? (f += "", "=" === b ? f === c : "!=" === b ? f !== c : "^=" === b ? c && 0 === f.indexOf(c) : "*=" === b ? c && f.indexOf(c) > -1 : "$=" === b ? c && f.substr(f.length - c.length) === c : "~=" === b ? (" " + f + " ").indexOf(c) > -1 : "|=" === b ? f === c || f.substr(0, c.length + 1) === c + "-" : !1) : !0;
};
},
CHILD: function(a, b, c, d) {
return "nth" === a ? function(a) {
var b, e, f = a.parentNode;
if (1 === c && 0 === d) return !0;
if (f) {
e = 0;
for (b = f.firstChild; b; b = b.nextSibling) if (1 === b.nodeType) {
e++;
if (a === b) break;
}
}
return e -= d, e === c || 0 === e % c && e / c >= 0;
} : function(b) {
var c = b;
switch (a) {
case "only":
case "first":
while (c = c.previousSibling) if (1 === c.nodeType) return !1;
if ("first" === a) return !0;
c = b;
case "last":
while (c = c.nextSibling) if (1 === c.nodeType) return !1;
return !0;
}
};
},
PSEUDO: function(a, b) {
var c, d = e.pseudos[a] || e.setFilters[a.toLowerCase()] || bc.error("unsupported pseudo: " + a);
return d[o] ? d(b) : d.length > 1 ? (c = [ a, a, "", b ], e.setFilters.hasOwnProperty(a.toLowerCase()) ? z(function(a, c) {
var e, f = d(a, b), g = f.length;
while (g--) e = y.call(a, f[g]), a[e] = !(c[e] = f[g]);
}) : function(a) {
return d(a, 0, c);
}) : d;
}
},
pseudos: {
not: z(function(a) {
var b = [], c = [], d = i(a.replace(L, "$1"));
return d[o] ? z(function(a, b, c, e) {
var f, g = d(a, null, e, []), h = a.length;
while (h--) if (f = g[h]) a[h] = !(b[h] = f);
}) : function(a, e, f) {
return b[0] = a, d(b, null, f, c), !c.pop();
};
}),
has: z(function(a) {
return function(b) {
return bc(a, b).length > 0;
};
}),
contains: z(function(a) {
return function(b) {
return (b.textContent || b.innerText || f(b)).indexOf(a) > -1;
};
}),
enabled: function(a) {
return a.disabled === !1;
},
disabled: function(a) {
return a.disabled === !0;
},
checked: function(a) {
var b = a.nodeName.toLowerCase();
return "input" === b && !!a.checked || "option" === b && !!a.selected;
},
selected: function(a) {
return a.parentNode && a.parentNode.selectedIndex, a.selected === !0;
},
parent: function(a) {
return !e.pseudos.empty(a);
},
empty: function(a) {
var b;
a = a.firstChild;
while (a) {
if (a.nodeName > "@" || 3 === (b = a.nodeType) || 4 === b) return !1;
a = a.nextSibling;
}
return !0;
},
header: function(a) {
return T.test(a.nodeName);
},
text: function(a) {
var b, c;
return "input" === a.nodeName.toLowerCase() && "text" === (b = a.type) && (null == (c = a.getAttribute("type")) || c.toLowerCase() === b);
},
radio: bd("radio"),
checkbox: bd("checkbox"),
file: bd("file"),
password: bd("password"),
image: bd("image"),
submit: be("submit"),
reset: be("reset"),
button: function(a) {
var b = a.nodeName.toLowerCase();
return "input" === b && "button" === a.type || "button" === b;
},
input: function(a) {
return U.test(a.nodeName);
},
focus: function(a) {
var b = a.ownerDocument;
return a === b.activeElement && (!b.hasFocus || b.hasFocus()) && (!!a.type || !!a.href);
},
active: function(a) {
return a === a.ownerDocument.activeElement;
},
first: bf(function(a, b, c) {
return [ 0 ];
}),
last: bf(function(a, b, c) {
return [ b - 1 ];
}),
eq: bf(function(a, b, c) {
return [ c < 0 ? c + b : c ];
}),
even: bf(function(a, b, c) {
for (var d = 0; d < b; d += 2) a.push(d);
return a;
}),
odd: bf(function(a, b, c) {
for (var d = 1; d < b; d += 2) a.push(d);
return a;
}),
lt: bf(function(a, b, c) {
for (var d = c < 0 ? c + b : c; --d >= 0; ) a.push(d);
return a;
}),
gt: bf(function(a, b, c) {
for (var d = c < 0 ? c + b : c; ++d < b; ) a.push(d);
return a;
})
}
}, j = s.compareDocumentPosition ? function(a, b) {
return a === b ? (k = !0, 0) : (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : 4 & a.compareDocumentPosition(b)) ? -1 : 1;
} : function(a, b) {
if (a === b) return k = !0, 0;
if (a.sourceIndex && b.sourceIndex) return a.sourceIndex - b.sourceIndex;
var c, d, e = [], f = [], g = a.parentNode, h = b.parentNode, i = g;
if (g === h) return bg(a, b);
if (!g) return -1;
if (!h) return 1;
while (i) e.unshift(i), i = i.parentNode;
i = h;
while (i) f.unshift(i), i = i.parentNode;
c = e.length, d = f.length;
for (var j = 0; j < c && j < d; j++) if (e[j] !== f[j]) return bg(e[j], f[j]);
return j === c ? bg(a, f[j], -1) : bg(e[j], b, 1);
}, [ 0, 0 ].sort(j), m = !k, bc.uniqueSort = function(a) {
var b, c = 1;
k = m, a.sort(j);
if (k) for (;b = a[c]; c++) b === a[c - 1] && a.splice(c--, 1);
return a;
}, bc.error = function(a) {
throw new Error("Syntax error, unrecognized expression: " + a);
}, i = bc.compile = function(a, b) {
var c, d = [], e = [], f = D[o][a];
if (!f) {
b || (b = bh(a)), c = b.length;
while (c--) f = bm(b[c]), f[o] ? d.push(f) : e.push(f);
f = D(a, bn(e, d));
}
return f;
}, r.querySelectorAll && function() {
var a, b = bp, c = /'|\\/g, d = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, e = [ ":focus" ], f = [ ":active", ":focus" ], h = s.matchesSelector || s.mozMatchesSelector || s.webkitMatchesSelector || s.oMatchesSelector || s.msMatchesSelector;
X(function(a) {
a.innerHTML = "<select><option selected=''></option></select>", a.querySelectorAll("[selected]").length || e.push("\\[" + E + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),
a.querySelectorAll(":checked").length || e.push(":checked");
}), X(function(a) {
a.innerHTML = "<p test=''></p>", a.querySelectorAll("[test^='']").length && e.push("[*^$]=" + E + "*(?:\"\"|'')"),
a.innerHTML = "<input type='hidden'/>", a.querySelectorAll(":enabled").length || e.push(":enabled", ":disabled");
}), e = new RegExp(e.join("|")), bp = function(a, d, f, g, h) {
if (!g && !h && (!e || !e.test(a))) {
var i, j, k = !0, l = o, m = d, n = 9 === d.nodeType && a;
if (1 === d.nodeType && "object" !== d.nodeName.toLowerCase()) {
i = bh(a), (k = d.getAttribute("id")) ? l = k.replace(c, "\\$&") : d.setAttribute("id", l),
l = "[id='" + l + "'] ", j = i.length;
while (j--) i[j] = l + i[j].join("");
m = R.test(a) && d.parentNode || d, n = i.join(",");
}
if (n) try {
return w.apply(f, x.call(m.querySelectorAll(n), 0)), f;
} catch (p) {} finally {
k || d.removeAttribute("id");
}
}
return b(a, d, f, g, h);
}, h && (X(function(b) {
a = h.call(b, "div");
try {
h.call(b, "[test!='']:sizzle"), f.push("!=", J);
} catch (c) {}
}), f = new RegExp(f.join("|")), bc.matchesSelector = function(b, c) {
c = c.replace(d, "='$1']");
if (!g(b) && !f.test(c) && (!e || !e.test(c))) try {
var i = h.call(b, c);
if (i || a || b.document && 11 !== b.document.nodeType) return i;
} catch (j) {}
return bc(c, null, null, [ b ]).length > 0;
});
}(), e.pseudos.nth = e.pseudos.eq, e.filters = bq.prototype = e.pseudos, e.setFilters = new bq(),
bc.attr = p.attr, p.find = bc, p.expr = bc.selectors, p.expr[":"] = p.expr.pseudos,
p.unique = bc.uniqueSort, p.text = bc.getText, p.isXMLDoc = bc.isXML, p.contains = bc.contains;
}(a);
var bc = /Until$/, bd = /^(?:parents|prev(?:Until|All))/, be = /^.[^:#\[\.,]*$/, bf = p.expr.match.needsContext, bg = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
p.fn.extend({
find: function(a) {
var b, c, d, e, f, g, h = this;
if ("string" != typeof a) return p(a).filter(function() {
for (b = 0, c = h.length; b < c; b++) if (p.contains(h[b], this)) return !0;
});
g = this.pushStack("", "find", a);
for (b = 0, c = this.length; b < c; b++) {
d = g.length, p.find(a, this[b], g);
if (b > 0) for (e = d; e < g.length; e++) for (f = 0; f < d; f++) if (g[f] === g[e]) {
g.splice(e--, 1);
break;
}
}
return g;
},
has: function(a) {
var b, c = p(a, this), d = c.length;
return this.filter(function() {
for (b = 0; b < d; b++) if (p.contains(this, c[b])) return !0;
});
},
not: function(a) {
return this.pushStack(bj(this, a, !1), "not", a);
},
filter: function(a) {
return this.pushStack(bj(this, a, !0), "filter", a);
},
is: function(a) {
return !!a && ("string" == typeof a ? bf.test(a) ? p(a, this.context).index(this[0]) >= 0 : p.filter(a, this).length > 0 : this.filter(a).length > 0);
},
closest: function(a, b) {
var c, d = 0, e = this.length, f = [], g = bf.test(a) || "string" != typeof a ? p(a, b || this.context) : 0;
for (;d < e; d++) {
c = this[d];
while (c && c.ownerDocument && c !== b && 11 !== c.nodeType) {
if (g ? g.index(c) > -1 : p.find.matchesSelector(c, a)) {
f.push(c);
break;
}
c = c.parentNode;
}
}
return f = f.length > 1 ? p.unique(f) : f, this.pushStack(f, "closest", a);
},
index: function(a) {
return a ? "string" == typeof a ? p.inArray(this[0], p(a)) : p.inArray(a.jquery ? a[0] : a, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1;
},
add: function(a, b) {
var c = "string" == typeof a ? p(a, b) : p.makeArray(a && a.nodeType ? [ a ] : a), d = p.merge(this.get(), c);
return this.pushStack(bh(c[0]) || bh(d[0]) ? d : p.unique(d));
},
addBack: function(a) {
return this.add(null == a ? this.prevObject : this.prevObject.filter(a));
}
}), p.fn.andSelf = p.fn.addBack, p.each({
parent: function(a) {
var b = a.parentNode;
return b && 11 !== b.nodeType ? b : null;
},
parents: function(a) {
return p.dir(a, "parentNode");
},
parentsUntil: function(a, b, c) {
return p.dir(a, "parentNode", c);
},
next: function(a) {
return bi(a, "nextSibling");
},
prev: function(a) {
return bi(a, "previousSibling");
},
nextAll: function(a) {
return p.dir(a, "nextSibling");
},
prevAll: function(a) {
return p.dir(a, "previousSibling");
},
nextUntil: function(a, b, c) {
return p.dir(a, "nextSibling", c);
},
prevUntil: function(a, b, c) {
return p.dir(a, "previousSibling", c);
},
siblings: function(a) {
return p.sibling((a.parentNode || {}).firstChild, a);
},
children: function(a) {
return p.sibling(a.firstChild);
},
contents: function(a) {
return p.nodeName(a, "iframe") ? a.contentDocument || a.contentWindow.document : p.merge([], a.childNodes);
}
}, function(a, b) {
p.fn[a] = function(c, d) {
var e = p.map(this, b, c);
return bc.test(a) || (d = c), d && "string" == typeof d && (e = p.filter(d, e)),
e = this.length > 1 && !bg[a] ? p.unique(e) : e, this.length > 1 && bd.test(a) && (e = e.reverse()),
this.pushStack(e, a, k.call(arguments).join(","));
};
}), p.extend({
filter: function(a, b, c) {
return c && (a = ":not(" + a + ")"), 1 === b.length ? p.find.matchesSelector(b[0], a) ? [ b[0] ] : [] : p.find.matches(a, b);
},
dir: function(a, c, d) {
var e = [], f = a[c];
while (f && 9 !== f.nodeType && (d === b || 1 !== f.nodeType || !p(f).is(d))) 1 === f.nodeType && e.push(f),
f = f[c];
return e;
},
sibling: function(a, b) {
var c = [];
for (;a; a = a.nextSibling) 1 === a.nodeType && a !== b && c.push(a);
return c;
}
});
var bl = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", bm = / jQuery\d+="(?:null|\d+)"/g, bn = /^\s+/, bo = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, bp = /<([\w:]+)/, bq = /<tbody/i, br = /<|&#?\w+;/, bs = /<(?:script|style|link)/i, bt = /<(?:script|object|embed|option|style)/i, bu = new RegExp("<(?:" + bl + ")[\\s/>]", "i"), bv = /^(?:checkbox|radio)$/, bw = /checked\s*(?:[^=]|=\s*.checked.)/i, bx = /\/(java|ecma)script/i, by = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, bz = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
}, bA = bk(e), bB = bA.appendChild(e.createElement("div"));
bz.optgroup = bz.option, bz.tbody = bz.tfoot = bz.colgroup = bz.caption = bz.thead,
bz.th = bz.td, p.support.htmlSerialize || (bz._default = [ 1, "X<div>", "</div>" ]),
p.fn.extend({
text: function(a) {
return p.access(this, function(a) {
return a === b ? p.text(this) : this.empty().append((this[0] && this[0].ownerDocument || e).createTextNode(a));
}, null, a, arguments.length);
},
wrapAll: function(a) {
if (p.isFunction(a)) return this.each(function(b) {
p(this).wrapAll(a.call(this, b));
});
if (this[0]) {
var b = p(a, this[0].ownerDocument).eq(0).clone(!0);
this[0].parentNode && b.insertBefore(this[0]), b.map(function() {
var a = this;
while (a.firstChild && 1 === a.firstChild.nodeType) a = a.firstChild;
return a;
}).append(this);
}
return this;
},
wrapInner: function(a) {
return p.isFunction(a) ? this.each(function(b) {
p(this).wrapInner(a.call(this, b));
}) : this.each(function() {
var b = p(this), c = b.contents();
c.length ? c.wrapAll(a) : b.append(a);
});
},
wrap: function(a) {
var b = p.isFunction(a);
return this.each(function(c) {
p(this).wrapAll(b ? a.call(this, c) : a);
});
},
unwrap: function() {
return this.parent().each(function() {
p.nodeName(this, "body") || p(this).replaceWith(this.childNodes);
}).end();
},
append: function() {
return this.domManip(arguments, !0, function(a) {
(1 === this.nodeType || 11 === this.nodeType) && this.appendChild(a);
});
},
prepend: function() {
return this.domManip(arguments, !0, function(a) {
(1 === this.nodeType || 11 === this.nodeType) && this.insertBefore(a, this.firstChild);
});
},
before: function() {
if (!bh(this[0])) return this.domManip(arguments, !1, function(a) {
this.parentNode.insertBefore(a, this);
});
if (arguments.length) {
var a = p.clean(arguments);
return this.pushStack(p.merge(a, this), "before", this.selector);
}
},
after: function() {
if (!bh(this[0])) return this.domManip(arguments, !1, function(a) {
this.parentNode.insertBefore(a, this.nextSibling);
});
if (arguments.length) {
var a = p.clean(arguments);
return this.pushStack(p.merge(this, a), "after", this.selector);
}
},
remove: function(a, b) {
var c, d = 0;
for (;null != (c = this[d]); d++) if (!a || p.filter(a, [ c ]).length) !b && 1 === c.nodeType && (p.cleanData(c.getElementsByTagName("*")),
p.cleanData([ c ])), c.parentNode && c.parentNode.removeChild(c);
return this;
},
empty: function() {
var a, b = 0;
for (;null != (a = this[b]); b++) {
1 === a.nodeType && p.cleanData(a.getElementsByTagName("*"));
while (a.firstChild) a.removeChild(a.firstChild);
}
return this;
},
clone: function(a, b) {
return a = null == a ? !1 : a, b = null == b ? a : b, this.map(function() {
return p.clone(this, a, b);
});
},
html: function(a) {
return p.access(this, function(a) {
var c = this[0] || {}, d = 0, e = this.length;
if (a === b) return 1 === c.nodeType ? c.innerHTML.replace(bm, "") : b;
if ("string" == typeof a && !bs.test(a) && (p.support.htmlSerialize || !bu.test(a)) && (p.support.leadingWhitespace || !bn.test(a)) && !bz[(bp.exec(a) || [ "", "" ])[1].toLowerCase()]) {
a = a.replace(bo, "<$1></$2>");
try {
for (;d < e; d++) c = this[d] || {}, 1 === c.nodeType && (p.cleanData(c.getElementsByTagName("*")),
c.innerHTML = a);
c = 0;
} catch (f) {}
}
c && this.empty().append(a);
}, null, a, arguments.length);
},
replaceWith: function(a) {
return bh(this[0]) ? this.length ? this.pushStack(p(p.isFunction(a) ? a() : a), "replaceWith", a) : this : p.isFunction(a) ? this.each(function(b) {
var c = p(this), d = c.html();
c.replaceWith(a.call(this, b, d));
}) : ("string" != typeof a && (a = p(a).detach()), this.each(function() {
var b = this.nextSibling, c = this.parentNode;
p(this).remove(), b ? p(b).before(a) : p(c).append(a);
}));
},
detach: function(a) {
return this.remove(a, !0);
},
domManip: function(a, c, d) {
a = [].concat.apply([], a);
var e, f, g, h, i = 0, j = a[0], k = [], l = this.length;
if (!p.support.checkClone && l > 1 && "string" == typeof j && bw.test(j)) return this.each(function() {
p(this).domManip(a, c, d);
});
if (p.isFunction(j)) return this.each(function(e) {
var f = p(this);
a[0] = j.call(this, e, c ? f.html() : b), f.domManip(a, c, d);
});
if (this[0]) {
e = p.buildFragment(a, this, k), g = e.fragment, f = g.firstChild, 1 === g.childNodes.length && (g = f);
if (f) {
c = c && p.nodeName(f, "tr");
for (h = e.cacheable || l - 1; i < l; i++) d.call(c && p.nodeName(this[i], "table") ? bC(this[i], "tbody") : this[i], i === h ? g : p.clone(g, !0, !0));
}
g = f = null, k.length && p.each(k, function(a, b) {
b.src ? p.ajax ? p.ajax({
url: b.src,
type: "GET",
dataType: "script",
async: !1,
global: !1,
"throws": !0
}) : p.error("no ajax") : p.globalEval((b.text || b.textContent || b.innerHTML || "").replace(by, "")),
b.parentNode && b.parentNode.removeChild(b);
});
}
return this;
}
}), p.buildFragment = function(a, c, d) {
var f, g, h, i = a[0];
return c = c || e, c = !c.nodeType && c[0] || c, c = c.ownerDocument || c, 1 === a.length && "string" == typeof i && i.length < 512 && c === e && "<" === i.charAt(0) && !bt.test(i) && (p.support.checkClone || !bw.test(i)) && (p.support.html5Clone || !bu.test(i)) && (g = !0,
f = p.fragments[i], h = f !== b), f || (f = c.createDocumentFragment(), p.clean(a, c, f, d),
g && (p.fragments[i] = h && f)), {
fragment: f,
cacheable: g
};
}, p.fragments = {}, p.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(a, b) {
p.fn[a] = function(c) {
var d, e = 0, f = [], g = p(c), h = g.length, i = 1 === this.length && this[0].parentNode;
if ((null == i || i && 11 === i.nodeType && 1 === i.childNodes.length) && 1 === h) return g[b](this[0]),
this;
for (;e < h; e++) d = (e > 0 ? this.clone(!0) : this).get(), p(g[e])[b](d), f = f.concat(d);
return this.pushStack(f, a, g.selector);
};
}), p.extend({
clone: function(a, b, c) {
var d, e, f, g;
p.support.html5Clone || p.isXMLDoc(a) || !bu.test("<" + a.nodeName + ">") ? g = a.cloneNode(!0) : (bB.innerHTML = a.outerHTML,
bB.removeChild(g = bB.firstChild));
if ((!p.support.noCloneEvent || !p.support.noCloneChecked) && (1 === a.nodeType || 11 === a.nodeType) && !p.isXMLDoc(a)) {
bE(a, g), d = bF(a), e = bF(g);
for (f = 0; d[f]; ++f) e[f] && bE(d[f], e[f]);
}
if (b) {
bD(a, g);
if (c) {
d = bF(a), e = bF(g);
for (f = 0; d[f]; ++f) bD(d[f], e[f]);
}
}
return d = e = null, g;
},
clean: function(a, b, c, d) {
var f, g, h, i, j, k, l, m, n, o, q, r, s = b === e && bA, t = [];
if (!b || "undefined" == typeof b.createDocumentFragment) b = e;
for (f = 0; null != (h = a[f]); f++) {
"number" == typeof h && (h += "");
if (!h) continue;
if ("string" == typeof h) if (!br.test(h)) h = b.createTextNode(h); else {
s = s || bk(b), l = b.createElement("div"), s.appendChild(l), h = h.replace(bo, "<$1></$2>"),
i = (bp.exec(h) || [ "", "" ])[1].toLowerCase(), j = bz[i] || bz._default, k = j[0],
l.innerHTML = j[1] + h + j[2];
while (k--) l = l.lastChild;
if (!p.support.tbody) {
m = bq.test(h), n = "table" === i && !m ? l.firstChild && l.firstChild.childNodes : "<table>" === j[1] && !m ? l.childNodes : [];
for (g = n.length - 1; g >= 0; --g) p.nodeName(n[g], "tbody") && !n[g].childNodes.length && n[g].parentNode.removeChild(n[g]);
}
!p.support.leadingWhitespace && bn.test(h) && l.insertBefore(b.createTextNode(bn.exec(h)[0]), l.firstChild),
h = l.childNodes, l.parentNode.removeChild(l);
}
h.nodeType ? t.push(h) : p.merge(t, h);
}
l && (h = l = s = null);
if (!p.support.appendChecked) for (f = 0; null != (h = t[f]); f++) p.nodeName(h, "input") ? bG(h) : "undefined" != typeof h.getElementsByTagName && p.grep(h.getElementsByTagName("input"), bG);
if (c) {
q = function(a) {
if (!a.type || bx.test(a.type)) return d ? d.push(a.parentNode ? a.parentNode.removeChild(a) : a) : c.appendChild(a);
};
for (f = 0; null != (h = t[f]); f++) if (!p.nodeName(h, "script") || !q(h)) c.appendChild(h),
"undefined" != typeof h.getElementsByTagName && (r = p.grep(p.merge([], h.getElementsByTagName("script")), q),
t.splice.apply(t, [ f + 1, 0 ].concat(r)), f += r.length);
}
return t;
},
cleanData: function(a, b) {
var c, d, e, f, g = 0, h = p.expando, i = p.cache, j = p.support.deleteExpando, k = p.event.special;
for (;null != (e = a[g]); g++) if (b || p.acceptData(e)) {
d = e[h], c = d && i[d];
if (c) {
if (c.events) for (f in c.events) k[f] ? p.event.remove(e, f) : p.removeEvent(e, f, c.handle);
i[d] && (delete i[d], j ? delete e[h] : e.removeAttribute ? e.removeAttribute(h) : e[h] = null,
p.deletedIds.push(d));
}
}
}
}), function() {
var a, b;
p.uaMatch = function(a) {
a = a.toLowerCase();
var b = /(chrome)[ \/]([\w.]+)/.exec(a) || /(webkit)[ \/]([\w.]+)/.exec(a) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a) || /(msie) ([\w.]+)/.exec(a) || a.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a) || [];
return {
browser: b[1] || "",
version: b[2] || "0"
};
}, a = p.uaMatch(g.userAgent), b = {}, a.browser && (b[a.browser] = !0, b.version = a.version),
b.chrome ? b.webkit = !0 : b.webkit && (b.safari = !0), p.browser = b, p.sub = function() {
function a(b, c) {
return new a.fn.init(b, c);
}
p.extend(!0, a, this), a.superclass = this, a.fn = a.prototype = this(), a.fn.constructor = a,
a.sub = this.sub, a.fn.init = function c(c, d) {
return d && d instanceof p && !(d instanceof a) && (d = a(d)), p.fn.init.call(this, c, d, b);
}, a.fn.init.prototype = a.fn;
var b = a(e);
return a;
};
}();
var bH, bI, bJ, bK = /alpha\([^)]*\)/i, bL = /opacity=([^)]*)/, bM = /^(top|right|bottom|left)$/, bN = /^(none|table(?!-c[ea]).+)/, bO = /^margin/, bP = new RegExp("^(" + q + ")(.*)$", "i"), bQ = new RegExp("^(" + q + ")(?!px)[a-z%]+$", "i"), bR = new RegExp("^([-+])=(" + q + ")", "i"), bS = {}, bT = {
position: "absolute",
visibility: "hidden",
display: "block"
}, bU = {
letterSpacing: 0,
fontWeight: 400
}, bV = [ "Top", "Right", "Bottom", "Left" ], bW = [ "Webkit", "O", "Moz", "ms" ], bX = p.fn.toggle;
p.fn.extend({
css: function(a, c) {
return p.access(this, function(a, c, d) {
return d !== b ? p.style(a, c, d) : p.css(a, c);
}, a, c, arguments.length > 1);
},
show: function() {
return b$(this, !0);
},
hide: function() {
return b$(this);
},
toggle: function(a, b) {
var c = "boolean" == typeof a;
return p.isFunction(a) && p.isFunction(b) ? bX.apply(this, arguments) : this.each(function() {
(c ? a : bZ(this)) ? p(this).show() : p(this).hide();
});
}
}), p.extend({
cssHooks: {
opacity: {
get: function(a, b) {
if (b) {
var c = bH(a, "opacity");
return "" === c ? "1" : c;
}
}
}
},
cssNumber: {
fillOpacity: !0,
fontWeight: !0,
lineHeight: !0,
opacity: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
cssProps: {
"float": p.support.cssFloat ? "cssFloat" : "styleFloat"
},
style: function(a, c, d, e) {
if (!a || 3 === a.nodeType || 8 === a.nodeType || !a.style) return;
var f, g, h, i = p.camelCase(c), j = a.style;
c = p.cssProps[i] || (p.cssProps[i] = bY(j, i)), h = p.cssHooks[c] || p.cssHooks[i];
if (d === b) return h && "get" in h && (f = h.get(a, !1, e)) !== b ? f : j[c];
g = typeof d, "string" === g && (f = bR.exec(d)) && (d = (f[1] + 1) * f[2] + parseFloat(p.css(a, c)),
g = "number");
if (null == d || "number" === g && isNaN(d)) return;
"number" === g && !p.cssNumber[i] && (d += "px");
if (!h || !("set" in h) || (d = h.set(a, d, e)) !== b) try {
j[c] = d;
} catch (k) {}
},
css: function(a, c, d, e) {
var f, g, h, i = p.camelCase(c);
return c = p.cssProps[i] || (p.cssProps[i] = bY(a.style, i)), h = p.cssHooks[c] || p.cssHooks[i],
h && "get" in h && (f = h.get(a, !0, e)), f === b && (f = bH(a, c)), "normal" === f && c in bU && (f = bU[c]),
d || e !== b ? (g = parseFloat(f), d || p.isNumeric(g) ? g || 0 : f) : f;
},
swap: function(a, b, c) {
var d, e, f = {};
for (e in b) f[e] = a.style[e], a.style[e] = b[e];
d = c.call(a);
for (e in b) a.style[e] = f[e];
return d;
}
}), a.getComputedStyle ? bH = function(b, c) {
var d, e, f, g, h = a.getComputedStyle(b, null), i = b.style;
return h && (d = h[c], "" === d && !p.contains(b.ownerDocument, b) && (d = p.style(b, c)),
bQ.test(d) && bO.test(c) && (e = i.width, f = i.minWidth, g = i.maxWidth, i.minWidth = i.maxWidth = i.width = d,
d = h.width, i.width = e, i.minWidth = f, i.maxWidth = g)), d;
} : e.documentElement.currentStyle && (bH = function(a, b) {
var c, d, e = a.currentStyle && a.currentStyle[b], f = a.style;
return null == e && f && f[b] && (e = f[b]), bQ.test(e) && !bM.test(b) && (c = f.left,
d = a.runtimeStyle && a.runtimeStyle.left, d && (a.runtimeStyle.left = a.currentStyle.left),
f.left = "fontSize" === b ? "1em" : e, e = f.pixelLeft + "px", f.left = c, d && (a.runtimeStyle.left = d)),
"" === e ? "auto" : e;
}), p.each([ "height", "width" ], function(a, b) {
p.cssHooks[b] = {
get: function(a, c, d) {
if (c) return 0 === a.offsetWidth && bN.test(bH(a, "display")) ? p.swap(a, bT, function() {
return cb(a, b, d);
}) : cb(a, b, d);
},
set: function(a, c, d) {
return b_(a, c, d ? ca(a, b, d, p.support.boxSizing && "border-box" === p.css(a, "boxSizing")) : 0);
}
};
}), p.support.opacity || (p.cssHooks.opacity = {
get: function(a, b) {
return bL.test((b && a.currentStyle ? a.currentStyle.filter : a.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : b ? "1" : "";
},
set: function(a, b) {
var c = a.style, d = a.currentStyle, e = p.isNumeric(b) ? "alpha(opacity=" + 100 * b + ")" : "", f = d && d.filter || c.filter || "";
c.zoom = 1;
if (b >= 1 && "" === p.trim(f.replace(bK, "")) && c.removeAttribute) {
c.removeAttribute("filter");
if (d && !d.filter) return;
}
c.filter = bK.test(f) ? f.replace(bK, e) : f + " " + e;
}
}), p(function() {
p.support.reliableMarginRight || (p.cssHooks.marginRight = {
get: function(a, b) {
return p.swap(a, {
display: "inline-block"
}, function() {
if (b) return bH(a, "marginRight");
});
}
}), !p.support.pixelPosition && p.fn.position && p.each([ "top", "left" ], function(a, b) {
p.cssHooks[b] = {
get: function(a, c) {
if (c) {
var d = bH(a, b);
return bQ.test(d) ? p(a).position()[b] + "px" : d;
}
}
};
});
}), p.expr && p.expr.filters && (p.expr.filters.hidden = function(a) {
return 0 === a.offsetWidth && 0 === a.offsetHeight || !p.support.reliableHiddenOffsets && "none" === (a.style && a.style.display || bH(a, "display"));
}, p.expr.filters.visible = function(a) {
return !p.expr.filters.hidden(a);
}), p.each({
margin: "",
padding: "",
border: "Width"
}, function(a, b) {
p.cssHooks[a + b] = {
expand: function(c) {
var d, e = "string" == typeof c ? c.split(" ") : [ c ], f = {};
for (d = 0; d < 4; d++) f[a + bV[d] + b] = e[d] || e[d - 2] || e[0];
return f;
}
}, bO.test(a) || (p.cssHooks[a + b].set = b_);
});
var cd = /%20/g, ce = /\[\]$/, cf = /\r?\n/g, cg = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, ch = /^(?:select|textarea)/i;
p.fn.extend({
serialize: function() {
return p.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function() {
return this.elements ? p.makeArray(this.elements) : this;
}).filter(function() {
return this.name && !this.disabled && (this.checked || ch.test(this.nodeName) || cg.test(this.type));
}).map(function(a, b) {
var c = p(this).val();
return null == c ? null : p.isArray(c) ? p.map(c, function(a, c) {
return {
name: b.name,
value: a.replace(cf, "\r\n")
};
}) : {
name: b.name,
value: c.replace(cf, "\r\n")
};
}).get();
}
}), p.param = function(a, c) {
var d, e = [], f = function(a, b) {
b = p.isFunction(b) ? b() : null == b ? "" : b, e[e.length] = encodeURIComponent(a) + "=" + encodeURIComponent(b);
};
c === b && (c = p.ajaxSettings && p.ajaxSettings.traditional);
if (p.isArray(a) || a.jquery && !p.isPlainObject(a)) p.each(a, function() {
f(this.name, this.value);
}); else for (d in a) ci(d, a[d], c, f);
return e.join("&").replace(cd, "+");
};
var cj, ck, cl = /#.*$/, cm = /^(.*?):[ \t]*([^\r\n]*)\r?$/gm, cn = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, co = /^(?:GET|HEAD)$/, cp = /^\/\//, cq = /\?/, cr = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, cs = /([?&])_=[^&]*/, ct = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, cu = p.fn.load, cv = {}, cw = {}, cx = [ "*/" ] + [ "*" ];
try {
ck = f.href;
} catch (cy) {
ck = e.createElement("a"), ck.href = "", ck = ck.href;
}
cj = ct.exec(ck.toLowerCase()) || [], p.fn.load = function(a, c, d) {
if ("string" != typeof a && cu) return cu.apply(this, arguments);
if (!this.length) return this;
var e, f, g, h = this, i = a.indexOf(" ");
return i >= 0 && (e = a.slice(i, a.length), a = a.slice(0, i)), p.isFunction(c) ? (d = c,
c = b) : c && "object" == typeof c && (f = "POST"), p.ajax({
url: a,
type: f,
dataType: "html",
data: c,
complete: function(a, b) {
d && h.each(d, g || [ a.responseText, b, a ]);
}
}).done(function(a) {
g = arguments, h.html(e ? p("<div>").append(a.replace(cr, "")).find(e) : a);
}), this;
}, p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a, b) {
p.fn[b] = function(a) {
return this.on(b, a);
};
}), p.each([ "get", "post" ], function(a, c) {
p[c] = function(a, d, e, f) {
return p.isFunction(d) && (f = f || e, e = d, d = b), p.ajax({
type: c,
url: a,
data: d,
success: e,
dataType: f
});
};
}), p.extend({
getScript: function(a, c) {
return p.get(a, b, c, "script");
},
getJSON: function(a, b, c) {
return p.get(a, b, c, "json");
},
ajaxSetup: function(a, b) {
return b ? cB(a, p.ajaxSettings) : (b = a, a = p.ajaxSettings), cB(a, b), a;
},
ajaxSettings: {
url: ck,
isLocal: cn.test(cj[1]),
global: !0,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: !0,
async: !0,
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": cx
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
converters: {
"* text": a.String,
"text html": !0,
"text json": p.parseJSON,
"text xml": p.parseXML
},
flatOptions: {
context: !0,
url: !0
}
},
ajaxPrefilter: cz(cv),
ajaxTransport: cz(cw),
ajax: function(a, c) {
function y(a, c, f, i) {
var k, s, t, u, w, y = c;
if (2 === v) return;
v = 2, h && clearTimeout(h), g = b, e = i || "", x.readyState = a > 0 ? 4 : 0, f && (u = cC(l, x, f));
if (a >= 200 && a < 300 || 304 === a) l.ifModified && (w = x.getResponseHeader("Last-Modified"),
w && (p.lastModified[d] = w), w = x.getResponseHeader("Etag"), w && (p.etag[d] = w)),
304 === a ? (y = "notmodified", k = !0) : (k = cD(l, u), y = k.state, s = k.data,
t = k.error, k = !t); else {
t = y;
if (!y || a) y = "error", a < 0 && (a = 0);
}
x.status = a, x.statusText = (c || y) + "", k ? o.resolveWith(m, [ s, y, x ]) : o.rejectWith(m, [ x, y, t ]),
x.statusCode(r), r = b, j && n.trigger("ajax" + (k ? "Success" : "Error"), [ x, l, k ? s : t ]),
q.fireWith(m, [ x, y ]), j && (n.trigger("ajaxComplete", [ x, l ]), --p.active || p.event.trigger("ajaxStop"));
}
"object" == typeof a && (c = a, a = b), c = c || {};
var d, e, f, g, h, i, j, k, l = p.ajaxSetup({}, c), m = l.context || l, n = m !== l && (m.nodeType || m instanceof p) ? p(m) : p.event, o = p.Deferred(), q = p.Callbacks("once memory"), r = l.statusCode || {}, t = {}, u = {}, v = 0, w = "canceled", x = {
readyState: 0,
setRequestHeader: function(a, b) {
if (!v) {
var c = a.toLowerCase();
a = u[c] = u[c] || a, t[a] = b;
}
return this;
},
getAllResponseHeaders: function() {
return 2 === v ? e : null;
},
getResponseHeader: function(a) {
var c;
if (2 === v) {
if (!f) {
f = {};
while (c = cm.exec(e)) f[c[1].toLowerCase()] = c[2];
}
c = f[a.toLowerCase()];
}
return c === b ? null : c;
},
overrideMimeType: function(a) {
return v || (l.mimeType = a), this;
},
abort: function(a) {
return a = a || w, g && g.abort(a), y(0, a), this;
}
};
o.promise(x), x.success = x.done, x.error = x.fail, x.complete = q.add, x.statusCode = function(a) {
if (a) {
var b;
if (v < 2) for (b in a) r[b] = [ r[b], a[b] ]; else b = a[x.status], x.always(b);
}
return this;
}, l.url = ((a || l.url) + "").replace(cl, "").replace(cp, cj[1] + "//"), l.dataTypes = p.trim(l.dataType || "*").toLowerCase().split(s),
null == l.crossDomain && (i = ct.exec(l.url.toLowerCase()) || !1, l.crossDomain = i && i.join(":") + (i[3] ? "" : "http:" === i[1] ? 80 : 443) !== cj.join(":") + (cj[3] ? "" : "http:" === cj[1] ? 80 : 443)),
l.data && l.processData && "string" != typeof l.data && (l.data = p.param(l.data, l.traditional)),
cA(cv, l, c, x);
if (2 === v) return x;
j = l.global, l.type = l.type.toUpperCase(), l.hasContent = !co.test(l.type), j && 0 === p.active++ && p.event.trigger("ajaxStart");
if (!l.hasContent) {
l.data && (l.url += (cq.test(l.url) ? "&" : "?") + l.data, delete l.data), d = l.url;
if (l.cache === !1) {
var z = p.now(), A = l.url.replace(cs, "$1_=" + z);
l.url = A + (A === l.url ? (cq.test(l.url) ? "&" : "?") + "_=" + z : "");
}
}
(l.data && l.hasContent && l.contentType !== !1 || c.contentType) && x.setRequestHeader("Content-Type", l.contentType),
l.ifModified && (d = d || l.url, p.lastModified[d] && x.setRequestHeader("If-Modified-Since", p.lastModified[d]),
p.etag[d] && x.setRequestHeader("If-None-Match", p.etag[d])), x.setRequestHeader("Accept", l.dataTypes[0] && l.accepts[l.dataTypes[0]] ? l.accepts[l.dataTypes[0]] + ("*" !== l.dataTypes[0] ? ", " + cx + "; q=0.01" : "") : l.accepts["*"]);
for (k in l.headers) x.setRequestHeader(k, l.headers[k]);
if (!l.beforeSend || l.beforeSend.call(m, x, l) !== !1 && 2 !== v) {
w = "abort";
for (k in {
success: 1,
error: 1,
complete: 1
}) x[k](l[k]);
g = cA(cw, l, c, x);
if (!g) y(-1, "No Transport"); else {
x.readyState = 1, j && n.trigger("ajaxSend", [ x, l ]), l.async && l.timeout > 0 && (h = setTimeout(function() {
x.abort("timeout");
}, l.timeout));
try {
v = 1, g.send(t, y);
} catch (B) {
if (v < 2) y(-1, B); else throw B;
}
}
return x;
}
return x.abort();
},
active: 0,
lastModified: {},
etag: {}
});
var cE = [], cF = /\?/, cG = /(=)\?(?=&|$)|\?\?/, cH = p.now();
p.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var a = cE.pop() || p.expando + "_" + cH++;
return this[a] = !0, a;
}
}), p.ajaxPrefilter("json jsonp", function(c, d, e) {
var f, g, h, i = c.data, j = c.url, k = c.jsonp !== !1, l = k && cG.test(j), m = k && !l && "string" == typeof i && !(c.contentType || "").indexOf("application/x-www-form-urlencoded") && cG.test(i);
if ("jsonp" === c.dataTypes[0] || l || m) return f = c.jsonpCallback = p.isFunction(c.jsonpCallback) ? c.jsonpCallback() : c.jsonpCallback,
g = a[f], l ? c.url = j.replace(cG, "$1" + f) : m ? c.data = i.replace(cG, "$1" + f) : k && (c.url += (cF.test(j) ? "&" : "?") + c.jsonp + "=" + f),
c.converters["script json"] = function() {
return h || p.error(f + " was not called"), h[0];
}, c.dataTypes[0] = "json", a[f] = function() {
h = arguments;
}, e.always(function() {
a[f] = g, c[f] && (c.jsonpCallback = d.jsonpCallback, cE.push(f)), h && p.isFunction(g) && g(h[0]),
h = g = b;
}), "script";
}), p.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function(a) {
return p.globalEval(a), a;
}
}
}), p.ajaxPrefilter("script", function(a) {
a.cache === b && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1);
}), p.ajaxTransport("script", function(a) {
if (a.crossDomain) {
var c, d = e.head || e.getElementsByTagName("head")[0] || e.documentElement;
return {
send: function(f, g) {
c = e.createElement("script"), c.async = "async", a.scriptCharset && (c.charset = a.scriptCharset),
c.src = a.url, c.onload = c.onreadystatechange = function(a, e) {
if (e || !c.readyState || /loaded|complete/.test(c.readyState)) c.onload = c.onreadystatechange = null,
d && c.parentNode && d.removeChild(c), c = b, e || g(200, "success");
}, d.insertBefore(c, d.firstChild);
},
abort: function() {
c && c.onload(0, 1);
}
};
}
});
var cI, cJ = a.ActiveXObject ? function() {
for (var a in cI) cI[a](0, 1);
} : !1, cK = 0;
p.ajaxSettings.xhr = a.ActiveXObject ? function() {
return !this.isLocal && cL() || cM();
} : cL, function(a) {
p.extend(p.support, {
ajax: !!a,
cors: !!a && "withCredentials" in a
});
}(p.ajaxSettings.xhr()), p.support.ajax && p.ajaxTransport(function(c) {
if (!c.crossDomain || p.support.cors) {
var d;
return {
send: function(e, f) {
var g, h, i = c.xhr();
c.username ? i.open(c.type, c.url, c.async, c.username, c.password) : i.open(c.type, c.url, c.async);
if (c.xhrFields) for (h in c.xhrFields) i[h] = c.xhrFields[h];
c.mimeType && i.overrideMimeType && i.overrideMimeType(c.mimeType), !c.crossDomain && !e["X-Requested-With"] && (e["X-Requested-With"] = "XMLHttpRequest");
try {
for (h in e) i.setRequestHeader(h, e[h]);
} catch (j) {}
i.send(c.hasContent && c.data || null), d = function(a, e) {
var h, j, k, l, m;
try {
if (d && (e || 4 === i.readyState)) {
d = b, g && (i.onreadystatechange = p.noop, cJ && delete cI[g]);
if (e) 4 !== i.readyState && i.abort(); else {
h = i.status, k = i.getAllResponseHeaders(), l = {}, m = i.responseXML, m && m.documentElement && (l.xml = m);
try {
l.text = i.responseText;
} catch (a) {}
try {
j = i.statusText;
} catch (n) {
j = "";
}
!h && c.isLocal && !c.crossDomain ? h = l.text ? 200 : 404 : 1223 === h && (h = 204);
}
}
} catch (o) {
e || f(-1, o);
}
l && f(h, j, l, k);
}, c.async ? 4 === i.readyState ? setTimeout(d, 0) : (g = ++cK, cJ && (cI || (cI = {},
p(a).unload(cJ)), cI[g] = d), i.onreadystatechange = d) : d();
},
abort: function() {
d && d(0, 1);
}
};
}
});
var cN, cO, cP = /^(?:toggle|show|hide)$/, cQ = new RegExp("^(?:([-+])=|)(" + q + ")([a-z%]*)$", "i"), cR = /queueHooks$/, cS = [ cY ], cT = {
"*": [ function(a, b) {
var c, d, e = this.createTween(a, b), f = cQ.exec(b), g = e.cur(), h = +g || 0, i = 1, j = 20;
if (f) {
c = +f[2], d = f[3] || (p.cssNumber[a] ? "" : "px");
if ("px" !== d && h) {
h = p.css(e.elem, a, !0) || c || 1;
do i = i || ".5", h /= i, p.style(e.elem, a, h + d); while (i !== (i = e.cur() / g) && 1 !== i && --j);
}
e.unit = d, e.start = h, e.end = f[1] ? h + (f[1] + 1) * c : c;
}
return e;
} ]
};
p.Animation = p.extend(cW, {
tweener: function(a, b) {
p.isFunction(a) ? (b = a, a = [ "*" ]) : a = a.split(" ");
var c, d = 0, e = a.length;
for (;d < e; d++) c = a[d], cT[c] = cT[c] || [], cT[c].unshift(b);
},
prefilter: function(a, b) {
b ? cS.unshift(a) : cS.push(a);
}
}), p.Tween = cZ, cZ.prototype = {
constructor: cZ,
init: function(a, b, c, d, e, f) {
this.elem = a, this.prop = c, this.easing = e || "swing", this.options = b, this.start = this.now = this.cur(),
this.end = d, this.unit = f || (p.cssNumber[c] ? "" : "px");
},
cur: function() {
var a = cZ.propHooks[this.prop];
return a && a.get ? a.get(this) : cZ.propHooks._default.get(this);
},
run: function(a) {
var b, c = cZ.propHooks[this.prop];
return this.options.duration ? this.pos = b = p.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration) : this.pos = b = a,
this.now = (this.end - this.start) * b + this.start, this.options.step && this.options.step.call(this.elem, this.now, this),
c && c.set ? c.set(this) : cZ.propHooks._default.set(this), this;
}
}, cZ.prototype.init.prototype = cZ.prototype, cZ.propHooks = {
_default: {
get: function(a) {
var b;
return null == a.elem[a.prop] || !!a.elem.style && null != a.elem.style[a.prop] ? (b = p.css(a.elem, a.prop, !1, ""),
!b || "auto" === b ? 0 : b) : a.elem[a.prop];
},
set: function(a) {
p.fx.step[a.prop] ? p.fx.step[a.prop](a) : a.elem.style && (null != a.elem.style[p.cssProps[a.prop]] || p.cssHooks[a.prop]) ? p.style(a.elem, a.prop, a.now + a.unit) : a.elem[a.prop] = a.now;
}
}
}, cZ.propHooks.scrollTop = cZ.propHooks.scrollLeft = {
set: function(a) {
a.elem.nodeType && a.elem.parentNode && (a.elem[a.prop] = a.now);
}
}, p.each([ "toggle", "show", "hide" ], function(a, b) {
var c = p.fn[b];
p.fn[b] = function(d, e, f) {
return null == d || "boolean" == typeof d || !a && p.isFunction(d) && p.isFunction(e) ? c.apply(this, arguments) : this.animate(c$(b, !0), d, e, f);
};
}), p.fn.extend({
fadeTo: function(a, b, c, d) {
return this.filter(bZ).css("opacity", 0).show().end().animate({
opacity: b
}, a, c, d);
},
animate: function(a, b, c, d) {
var e = p.isEmptyObject(a), f = p.speed(b, c, d), g = function() {
var b = cW(this, p.extend({}, a), f);
e && b.stop(!0);
};
return e || f.queue === !1 ? this.each(g) : this.queue(f.queue, g);
},
stop: function(a, c, d) {
var e = function(a) {
var b = a.stop;
delete a.stop, b(d);
};
return "string" != typeof a && (d = c, c = a, a = b), c && a !== !1 && this.queue(a || "fx", []),
this.each(function() {
var b = !0, c = null != a && a + "queueHooks", f = p.timers, g = p._data(this);
if (c) g[c] && g[c].stop && e(g[c]); else for (c in g) g[c] && g[c].stop && cR.test(c) && e(g[c]);
for (c = f.length; c--; ) f[c].elem === this && (null == a || f[c].queue === a) && (f[c].anim.stop(d),
b = !1, f.splice(c, 1));
(b || !d) && p.dequeue(this, a);
});
}
}), p.each({
slideDown: c$("show"),
slideUp: c$("hide"),
slideToggle: c$("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(a, b) {
p.fn[a] = function(a, c, d) {
return this.animate(b, a, c, d);
};
}), p.speed = function(a, b, c) {
var d = a && "object" == typeof a ? p.extend({}, a) : {
complete: c || !c && b || p.isFunction(a) && a,
duration: a,
easing: c && b || b && !p.isFunction(b) && b
};
d.duration = p.fx.off ? 0 : "number" == typeof d.duration ? d.duration : d.duration in p.fx.speeds ? p.fx.speeds[d.duration] : p.fx.speeds._default;
if (null == d.queue || d.queue === !0) d.queue = "fx";
return d.old = d.complete, d.complete = function() {
p.isFunction(d.old) && d.old.call(this), d.queue && p.dequeue(this, d.queue);
}, d;
}, p.easing = {
linear: function(a) {
return a;
},
swing: function(a) {
return .5 - Math.cos(a * Math.PI) / 2;
}
}, p.timers = [], p.fx = cZ.prototype.init, p.fx.tick = function() {
var a, b = p.timers, c = 0;
for (;c < b.length; c++) a = b[c], !a() && b[c] === a && b.splice(c--, 1);
b.length || p.fx.stop();
}, p.fx.timer = function(a) {
a() && p.timers.push(a) && !cO && (cO = setInterval(p.fx.tick, p.fx.interval));
}, p.fx.interval = 13, p.fx.stop = function() {
clearInterval(cO), cO = null;
}, p.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
}, p.fx.step = {}, p.expr && p.expr.filters && (p.expr.filters.animated = function(a) {
return p.grep(p.timers, function(b) {
return a === b.elem;
}).length;
});
var c_ = /^(?:body|html)$/i;
p.fn.offset = function(a) {
if (arguments.length) return a === b ? this : this.each(function(b) {
p.offset.setOffset(this, a, b);
});
var c, d, e, f, g, h, i, j = {
top: 0,
left: 0
}, k = this[0], l = k && k.ownerDocument;
if (!l) return;
return (d = l.body) === k ? p.offset.bodyOffset(k) : (c = l.documentElement, p.contains(c, k) ? ("undefined" != typeof k.getBoundingClientRect && (j = k.getBoundingClientRect()),
e = da(l), f = c.clientTop || d.clientTop || 0, g = c.clientLeft || d.clientLeft || 0,
h = e.pageYOffset || c.scrollTop, i = e.pageXOffset || c.scrollLeft, {
top: j.top + h - f,
left: j.left + i - g
}) : j);
}, p.offset = {
bodyOffset: function(a) {
var b = a.offsetTop, c = a.offsetLeft;
return p.support.doesNotIncludeMarginInBodyOffset && (b += parseFloat(p.css(a, "marginTop")) || 0,
c += parseFloat(p.css(a, "marginLeft")) || 0), {
top: b,
left: c
};
},
setOffset: function(a, b, c) {
var d = p.css(a, "position");
"static" === d && (a.style.position = "relative");
var e = p(a), f = e.offset(), g = p.css(a, "top"), h = p.css(a, "left"), i = ("absolute" === d || "fixed" === d) && p.inArray("auto", [ g, h ]) > -1, j = {}, k = {}, l, m;
i ? (k = e.position(), l = k.top, m = k.left) : (l = parseFloat(g) || 0, m = parseFloat(h) || 0),
p.isFunction(b) && (b = b.call(a, c, f)), null != b.top && (j.top = b.top - f.top + l),
null != b.left && (j.left = b.left - f.left + m), "using" in b ? b.using.call(a, j) : e.css(j);
}
}, p.fn.extend({
position: function() {
if (!this[0]) return;
var a = this[0], b = this.offsetParent(), c = this.offset(), d = c_.test(b[0].nodeName) ? {
top: 0,
left: 0
} : b.offset();
return c.top -= parseFloat(p.css(a, "marginTop")) || 0, c.left -= parseFloat(p.css(a, "marginLeft")) || 0,
d.top += parseFloat(p.css(b[0], "borderTopWidth")) || 0, d.left += parseFloat(p.css(b[0], "borderLeftWidth")) || 0,
{
top: c.top - d.top,
left: c.left - d.left
};
},
offsetParent: function() {
return this.map(function() {
var a = this.offsetParent || e.body;
while (a && !c_.test(a.nodeName) && "static" === p.css(a, "position")) a = a.offsetParent;
return a || e.body;
});
}
}), p.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(a, c) {
var d = /Y/.test(c);
p.fn[a] = function(e) {
return p.access(this, function(a, e, f) {
var g = da(a);
if (f === b) return g ? c in g ? g[c] : g.document.documentElement[e] : a[e];
g ? g.scrollTo(d ? p(g).scrollLeft() : f, d ? f : p(g).scrollTop()) : a[e] = f;
}, a, e, arguments.length, null);
};
}), p.each({
Height: "height",
Width: "width"
}, function(a, c) {
p.each({
padding: "inner" + a,
content: c,
"": "outer" + a
}, function(d, e) {
p.fn[e] = function(e, f) {
var g = arguments.length && (d || "boolean" != typeof e), h = d || (e === !0 || f === !0 ? "margin" : "border");
return p.access(this, function(c, d, e) {
var f;
return p.isWindow(c) ? c.document.documentElement["client" + a] : 9 === c.nodeType ? (f = c.documentElement,
Math.max(c.body["scroll" + a], f["scroll" + a], c.body["offset" + a], f["offset" + a], f["client" + a])) : e === b ? p.css(c, d, e, h) : p.style(c, d, e, h);
}, c, g ? e : b, g, null);
};
});
}), a.jQuery = a.$ = p, "function" == typeof define && define.amd && define.amd.jQuery && define("jquery", [], function() {
return p;
});
})(window);
(function() {
var _cache = {};
String.format = function(str) {
if ("object" != typeof arguments[1]) {
for (var i = 1; i < arguments.length; i++) {
var regexp = _cache[i] || (_cache[i] = new RegExp("%" + i, "g"));
str = str.replace(regexp, arguments[i]);
}
return str;
}
var output = "", lastIndex = 0, obj = arguments[1];
while (1) {
var index = str.indexOf("#{", lastIndex);
if (index == -1) break;
output += str.substring(lastIndex, index);
var end = str.indexOf("}", index);
output += Object.getProperty(obj, str.substring(index + 2, end));
lastIndex = ++end;
}
output += str.substring(lastIndex);
return output;
};
Object.defaults = function(obj, def) {
for (var key in def) if (null == obj[key]) obj[key] = def[key];
return obj;
};
Object.clear = function(obj, arg) {
if (arg instanceof Array) for (var i = 0, x, length = arg.length; i < length; i++) {
x = arg[i];
if (x in obj) delete obj[x];
} else if ("object" === typeof arg) for (var key in arg) if (key in obj) delete obj[key];
return obj;
};
Object.extend = function(target, source) {
if (null == target) target = {};
if (null == source) return target;
for (var key in source) if (null != source[key]) target[key] = source[key];
return target;
};
Object.getProperty = function(o, chain) {
if ("." === chain) return o;
var value = o, props = chain.split("."), i = -1, length = props.length;
while (null != value && ++i < length) value = value[props[i]];
return value;
};
Object.setProperty = function(o, xpath, value) {
var arr = xpath.split("."), obj = o, key = arr[arr.length - 1];
while (arr.length > 1) {
var prop = arr.shift();
obj = obj[prop] || (obj[prop] = {});
}
obj[key] = value;
};
Object.lazyProperty = function(o, xpath, fn) {
if ("object" === typeof xpath) {
for (var key in xpath) Object.lazyProperty(o, key, xpath[key]);
return;
}
var arr = xpath.split("."), obj = o, lazy = arr[arr.length - 1];
while (arr.length > 1) {
var prop = arr.shift();
obj = obj[prop] || (obj[prop] = {});
}
arr = null;
obj.__defineGetter__(lazy, function() {
delete obj[lazy];
obj[lazy] = fn();
fn = null;
return obj[lazy];
});
};
Object.observe = function(obj, property, callback) {
if (null == obj.__observers) Object.defineProperty(obj, "__observers", {
value: {},
enumerable: false
});
if (obj.__observers[property]) {
obj.__observers[property].push(callback);
return;
}
(obj.__observers[property] || (obj.__observers[property] = [])).push(callback);
var chain = property.split("."), parent = obj, key = property;
if (chain.length > 1) {
key = chain.pop();
parent = Object.getProperty(obj, chain);
}
var value = parent[key];
Object.defineProperty(parent, key, {
get: function() {
return value;
},
set: function(x) {
value = x;
var observers = obj.__observers[property];
for (var i = 0, length = observers.length; i < length; i++) observers[i](x);
}
});
};
Date.format = function(date, format) {
if (!format) format = "MM/dd/yyyy";
function pad(value) {
return value > 9 ? value : "0" + value;
}
format = format.replace("MM", pad(date.getMonth() + 1));
var _year = date.getFullYear();
if (format.indexOf("yyyy") > -1) format = format.replace("yyyy", _year); else if (format.indexOf("yy") > -1) format = format.replace("yy", _year.toString().substr(2, 2));
format = format.replace("dd", pad(date.getDate()));
if (format.indexOf("HH") > -1) format = format.replace("HH", pad(date.getHours()));
if (format.indexOf("mm") > -1) format = format.replace("mm", pad(date.getMinutes()));
if (format.indexOf("ss") > -1) format = format.replace("ss", pad(date.getSeconds()));
return format;
};
Function.invoke = function() {
var arr = Array.prototype.slice.call(arguments), obj = arr.shift(), fn = arr.shift();
return function() {
return obj[fn].apply(obj, arr);
};
};
})();
(function(global) {
"use strict";
var r = global.ruqq || (global.ruqq = {});
function getProperty(o, chain) {
if ("object" !== typeof o || null == chain) return o;
var value = o, props = chain.split("."), length = props.length, i = 0, key;
for (;i < length; i++) {
key = props[i];
value = value[key];
if (null == value) return value;
}
return value;
}
function extend(target, source) {
for (var key in source) if (source[key]) target[key] = source[key];
return target;
}
function check(item, arg1, arg2, arg3) {
if ("function" === typeof arg1) return arg1(item) ? item : null;
if ("undefined" === typeof arg2) return item == arg1 ? item : null;
var value = null != arg1 ? getProperty(item, arg1) : item, comparer = arg2, compareToValue = arg3;
switch (comparer) {
case ">":
return value > compareToValue ? item : null;
case "<":
return value < compareToValue ? item : null;
case ">=":
return value >= compareToValue ? item : null;
case "<=":
return value <= compareToValue ? item : null;
case "!=":
return value != compareToValue ? item : null;
case "==":
return value == compareToValue ? item : null;
}
console.error("InvalidArgumentException: arr.js:check", arguments);
return null;
}
var arr = {
where: function(items, arg1, arg2, arg3) {
var array = [];
if (null == items) return array;
var i = 0, length = items.length, item;
for (;i < length; i++) {
item = items[i];
if (null != check(item, arg1, arg2, arg3)) array.push(item);
}
return array;
},
each: "undefined" !== typeof Array.prototype.forEach ? function(items, fn) {
if (null == items) return items;
items.forEach(fn);
return items;
} : function(items, func) {
if (null == items) return items;
for (var i = 0, length = items.length; i < length; i++) func(items[i]);
return items;
},
remove: function(items, arg1, arg2, arg3) {
for (var i = 0, length = items.length; i < length; i++) if (null != check(items[i], arg1, arg2, arg3)) {
items.splice(i, 1);
i--;
length--;
}
return items;
},
invoke: function() {
var args = Array.prototype.slice.call(arguments);
var items = args.shift(), method = args.shift(), results = [];
for (var i = 0; i < items.length; i++) if ("function" === typeof items[i][method]) results.push(items[i][method].apply(items[i], args)); else results.push(null);
return results;
},
last: function(items, arg1, arg2, arg3) {
if (null == items) return null;
if (null == arg1) return items[items.length - 1];
for (var i = items.length; i > -1; --i) if (null != check(items[i], arg1, arg2, arg3)) return items[i];
return null;
},
first: function(items, arg1, arg2, arg3) {
if (null == arg1) return items[0];
for (var i = 0, length = items.length; i < length; i++) if (null != check(items[i], arg1, arg2, arg3)) return items[i];
return null;
},
any: function(items, arg1, arg2, arg3) {
for (var i = 0, length = items.length; i < length; i++) if (null != check(items[i], arg1, arg2, arg3)) return true;
return false;
},
isIn: function(items, checkValue) {
for (var i = 0; i < items.length; i++) if (checkValue == items[i]) return true;
return false;
},
map: "undefined" !== typeof Array.prototype.map ? function(items, func) {
if (null == items) return [];
return items.map(func);
} : function(items, func) {
var agg = [];
if (null == items) return agg;
for (var i = 0, length = items.length; i < length; i++) agg.push(func(items[i], i));
return agg;
},
aggr: function(items, aggr, fn) {
for (var i = 0, length = items.length; i < length; i++) {
var result = fn(items[i], aggr, i);
if (null != result) aggr = result;
}
return aggr;
},
select: function(items, arg) {
if (null == items) return [];
var arr = [];
for (var item, i = 0, length = items.length; i < length; i++) {
item = items[i];
if ("string" === typeof arg) arr.push(item[arg]); else if ("function" === typeof arg) arr.push(arg(item)); else if (arg instanceof Array) {
var obj = {};
for (var j = 0; j < arg.length; j++) obj[arg[j]] = items[i][arg[j]];
arr.push(obj);
}
}
return arr;
},
indexOf: function(items, arg1, arg2, arg3) {
for (var i = 0, length = items.length; i < length; i++) if (null != check(items[i], arg1, arg2, arg3)) return i;
return -1;
},
count: function(items, arg1, arg2, arg3) {
var count = 0, i = 0, length = items.length;
for (;i < length; i++) if (null != check(items[i], arg1, arg2, arg3)) count++;
return count;
},
distinct: function(items, compareF) {
var array = [];
if (null == items) return array;
var i = 0, length = items.length;
for (;i < length; i++) {
var unique = true;
for (var j = 0; j < array.length; j++) if (compareF && compareF(items[i], array[j]) || null == compareF && items[i] == array[j]) {
unique = false;
break;
}
if (unique) array.push(items[i]);
}
return array;
}
};
arr.each([ "min", "max" ], function(x) {
arr[x] = function(array, property) {
if (null == array) return null;
var number = null;
for (var i = 0, length = array.length; i < length; i++) {
var prop = getProperty(array[i], property);
if (null == number) {
number = prop;
continue;
}
if ("max" === x && prop > number) {
number = prop;
continue;
}
if ("min" === x && prop < number) {
number = prop;
continue;
}
}
return number;
};
});
r.arr = function(items) {
return new Expression(items);
};
extend(r.arr, arr);
function Expression(items) {
this.items = items;
}
function extendClass(method) {
Expression.prototype[method] = function() {
var l = arguments.length, result = arr[method](this.items, l > 0 ? arguments[0] : null, l > 1 ? arguments[1] : null, l > 2 ? arguments[2] : null, l > 3 ? arguments[3] : null);
if (result instanceof Array) {
this.items = result;
return this;
}
return result;
};
}
for (var method in arr) extendClass(method);
})("undefined" !== typeof window ? window : global);
if ("undefined" === typeof Function.prototype.bind) Function.prototype.bind = function() {
if (arguments.length < 2 && "undefined" == typeof arguments[0]) return this;
var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
if ("undefined" === typeof Object.defineProperty) if ("undefined" !== {}.__defineGetter__) Object.defineProperty = function(obj, prop, data) {
if (data.set) obj.__defineSetter__(prop, data.set);
if (data.get) obj.__defineGetter__(prop, data.get);
};
if ("undefined" === typeof Date.now) Date.now = function() {
return new Date().getTime();
};
if ("undefined" === typeof window.requestAnimationFrame) {
window.requestAnimationFrame = function() {
var w = window;
return w.webkitRequestAnimationFrame || w.mozRequestAnimationFrame || function(callback) {
return setTimeout(callback, 17);
};
}();
window.cancelAnimationFrame = function() {
var w = window;
return w.webkitCancelAnimationFrame || w.mozCancelAnimationFrame || function(timeout) {
clearTimeout(timeout);
};
}();
}
if ("undefined" === typeof String.prototype.trim) String.prototype.trim = function() {
return this.replace(/(^\s)|(\s$)/g, "");
};
if ("undefined" === typeof Array.prototype.indexOf) Array.prototype.indexOf = function(value) {
for (var i = 0; i < this.length; i++) if (value === this[i]) return i;
return -1;
};
include.setCurrent({
id: "/.reference/libjs/mask/lib/mask.js",
namespace: "lib.mask",
url: "/.reference/libjs/mask/lib/mask.js"
});
(function(root, factory) {
"use strict";
var doc = "undefined" === typeof document ? null : document, construct = function() {
return factory(doc);
};
if ("object" === typeof exports) module.exports = construct(); else if ("function" === typeof define && define.amd) define(construct); else root.mask = construct();
})(this, function(document) {
"use strict";
var regexpWhitespace = /\s/g, regexpEscapedChar = {
"'": /\\'/g,
'"': /\\"/g,
"{": /\\\{/g,
">": /\\>/g,
";": /\\>/g
}, hasOwnProp = {}.hasOwnProperty, listeners = null;
function util_extend(target, source) {
if (null == target) target = {};
for (var key in source) {
if (false === hasOwnProp.call(source, key)) continue;
target[key] = source[key];
}
return target;
}
function util_getProperty(o, chain) {
if ("." === chain) return o;
var value = o, props = chain.split("."), i = -1, length = props.length;
while (null != value && ++i < length) value = value[props[i]];
return value;
}
function util_interpolate(arr, model, type, cntx, element, name) {
var length = arr.length, i = 0, array = null, string = "", even = true, utility, value, index, key;
for (;i < length; i++) {
if (true === even) if (null == array) string += arr[i]; else array.push(arr[i]); else {
key = arr[i];
value = null;
index = key.indexOf(":");
if (index === -1) value = util_getProperty(model, key); else {
utility = index > 0 ? key.substring(0, index).replace(regexpWhitespace, "") : "";
if ("" === utility) utility = "condition";
key = key.substring(index + 1);
if ("function" === typeof ModelUtils[utility]) value = ModelUtils[utility](key, model, type, cntx, element, name);
}
if (null != value) {
if ("object" === typeof value && null == array) array = [ string ];
if (null == array) string += value; else array.push(value);
}
}
even = !even;
}
return null == array ? string : array;
}
function Template(template) {
this.template = template;
this.index = 0;
this.length = template.length;
}
Template.prototype = {
skipWhitespace: function() {
var template = this.template, index = this.index, length = this.length;
for (;index < length; index++) if (template.charCodeAt(index) > 32) break;
this.index = index;
return this;
},
skipToAttributeBreak: function() {
var template = this.template, index = this.index, length = this.length, c;
do {
c = template.charCodeAt(++index);
if (35 === c && 123 === template.charCodeAt(index + 1)) {
this.index = index;
this.sliceToChar("}");
this.index++;
return;
}
} while (46 !== c && 35 !== c && 62 !== c && 123 !== c && 32 !== c && 59 !== c && index < length);
this.index = index;
},
sliceToChar: function(c) {
var template = this.template, index = this.index, start = index, isEscaped = false, value, nindex;
while ((nindex = template.indexOf(c, index)) > -1) {
index = nindex;
if (92 !== template.charCodeAt(index - 1)) break;
isEscaped = true;
index++;
}
value = template.substring(start, index);
this.index = index;
return isEscaped ? value.replace(regexpEscapedChar[c], c) : value;
}
};
var ConditionUtil = function() {
function parseDirective(T, currentChar) {
var c = currentChar, start = T.index, token;
if (null == c) {
T.skipWhitespace();
start = T.index;
currentChar = c = T.template.charCodeAt(T.index);
}
if (34 === c || 39 === c) {
T.index++;
token = T.sliceToChar(39 === c ? "'" : '"');
T.index++;
return token;
}
do c = T.template.charCodeAt(++T.index); while (T.index < T.length && 32 !== c && 33 !== c && 60 !== c && 61 !== c && 62 !== c && 40 !== c && 41 !== c && 38 !== c && 124 !== c);
token = T.template.substring(start, T.index);
c = currentChar;
if (45 === c || c > 47 && c < 58) return token - 0;
if (116 === c && "true" === token) return true;
if (102 === c && "false" === token) return false;
return {
value: token
};
}
function parseAssertion(T, output) {
var current = {
assertions: null,
join: null,
left: null,
right: null
}, c;
if (null == output) output = [];
if ("string" === typeof T) T = new Template(T);
outer: while (1) {
T.skipWhitespace();
if (T.index >= T.length) break;
c = T.template.charCodeAt(T.index);
switch (c) {
case 61:
case 60:
case 62:
case 33:
var start = T.index;
do c = T.template.charCodeAt(++T.index); while (T.index < T.length && (60 === c || 61 === c || 62 === c));
current.sign = T.template.substring(start, T.index);
continue;
case 38:
case 124:
if (T.template.charCodeAt(++T.index) !== c) console.error("Unary operation not valid");
current.join = 38 === c ? "&&" : "||";
output.push(current);
current = {
assertions: null,
join: null,
left: null,
right: null
};
++T.index;
continue;
case 40:
T.index++;
parseAssertion(T, current.assertions = []);
break;
case 41:
T.index++;
break outer;
default:
current[null == current.left ? "left" : "right"] = parseDirective(T, c);
continue;
}
}
if (current.left || current.assertions) output.push(current);
return output;
}
var _cache = [];
function parseLinearCondition(line) {
if (null != _cache[line]) return _cache[line];
var length = line.length, ternary = {
assertions: null,
case1: null,
case2: null
}, questionMark = line.indexOf("?"), T = new Template(line);
if (questionMark !== -1) T.length = questionMark;
ternary.assertions = parseAssertion(T);
if (questionMark !== -1) {
T.length = length;
T.index = questionMark + 1;
ternary.case1 = parseDirective(T);
T.skipWhitespace();
if (58 === T.template.charCodeAt(T.index)) {
T.index++;
ternary.case2 = parseDirective(T);
}
}
return _cache[line] = ternary;
}
function isCondition(assertions, model) {
if ("string" === typeof assertions) assertions = parseLinearCondition(assertions).assertions;
if (null != assertions.assertions) assertions = assertions.assertions;
var current = false, a, value1, value2, i, length;
for (i = 0, length = assertions.length; i < length; i++) {
a = assertions[i];
if (a.assertions) current = isCondition(a.assertions, model); else {
value1 = "object" === typeof a.left ? util_getProperty(model, a.left.value) : a.left;
if (null == a.right) {
current = value1;
if ("!" === a.sign) current = !current;
} else {
value2 = "object" === typeof a.right ? util_getProperty(model, a.right.value) : a.right;
switch (a.sign) {
case "<":
current = value1 < value2;
break;
case "<=":
current = value1 <= value2;
break;
case ">":
current = value1 > value2;
break;
case ">=":
current = value1 >= value2;
break;
case "!=":
current = value1 !== value2;
break;
case "==":
current = value1 === value2;
}
}
}
if (current) {
if ("&&" === a.join) continue;
break;
}
if ("||" === a.join) continue;
if ("&&" === a.join) for (++i; i < length; i++) if ("||" === assertions[i].join) break;
}
return current;
}
return {
condition: function(line, model) {
var con = parseLinearCondition(line), result = isCondition(con.assertions, model);
if (null != con.case1) result = result ? con.case1 : con.case2;
if (null == result) return "";
if ("object" === typeof result && result.value) return util_getProperty(model, result.value);
return result;
},
isCondition: isCondition,
parse: parseLinearCondition,
out: {
isCondition: isCondition,
parse: parseLinearCondition
}
};
}();
var ModelUtils = {
condition: ConditionUtil.condition
}, CustomAttributes = {
"class": null,
id: null,
style: null,
name: null,
type: null
}, CustomTags = {
div: null,
span: null,
input: null,
button: null,
textarea: null,
select: null,
option: null,
h1: null,
h2: null,
h3: null,
h4: null,
h5: null,
h6: null,
a: null,
p: null,
img: null,
table: null,
td: null,
tr: null,
pre: null,
ul: null,
li: null,
ol: null,
i: null,
b: null,
strong: null,
form: null
};
var Dom = {
NODE: 1,
TEXTNODE: 2,
FRAGMENT: 3,
COMPONENT: 4,
CONTROLLER: 9,
SET: 10,
Node: Node,
TextNode: TextNode,
Fragment: Fragment,
Component: Component
};
function Node(tagName, parent) {
this.type = Dom.NODE;
this.tagName = tagName;
this.parent = parent;
this.attr = {};
}
Node.prototype = {
constructor: Node,
type: Dom.NODE,
tagName: null,
parent: null,
attr: null,
nodes: null,
__single: null
};
function TextNode(text, parent) {
this.content = text;
this.parent = parent;
this.type = Dom.TEXTNODE;
}
TextNode.prototype = {
type: Dom.TEXTNODE,
content: null,
parent: null
};
function Fragment() {
this.nodes = [];
}
Fragment.prototype = {
constructor: Fragment,
type: Dom.FRAGMENT,
nodes: null
};
function Component(compoName, parent, controller) {
this.tagName = compoName;
this.parent = parent;
this.controller = controller;
this.attr = {};
}
Component.prototype = {
constructor: Component,
type: Dom.COMPONENT,
parent: null,
attr: null,
controller: null,
nodes: null,
components: null
};
var Parser = function(Node, TextNode, Fragment, Component) {
var interp_START = "~", interp_CLOSE = "]", interp_code_START = 126, interp_code_OPEN = 91, interp_code_CLOSE = 93, _serialize;
function ensureTemplateFunction(template) {
var index = -1;
while ((index = template.indexOf(interp_START, index)) !== -1) {
if (template.charCodeAt(index + 1) === interp_code_OPEN) break;
index++;
}
if (index === -1) return template;
var array = [], lastIndex = 0, i = 0, end = 0;
while (true) {
var end = template.indexOf(interp_CLOSE, index + 2);
if (end === -1) break;
array[i++] = lastIndex === index ? "" : template.substring(lastIndex, index);
array[i++] = template.substring(index + 2, end);
lastIndex = index = end + 1;
while ((index = template.indexOf(interp_START, index)) !== -1) {
if (template.charCodeAt(index + 1) === interp_code_OPEN) break;
index++;
}
if (index === -1) break;
}
if (lastIndex < template.length) array[i] = template.substring(lastIndex);
template = null;
return function(model, type, cntx, element, name) {
if (null == type) {
var string = "";
for (var i = 0, x, length = array.length; i < length; i++) {
x = array[i];
if (1 === i % 2) string += "~[" + x + "]"; else string += x;
}
return string;
}
return util_interpolate(array, model, type, cntx, element, name);
};
}
function _throw(template, index, state, token) {
var i = 0, line = 0, row = 0, newLine = /[\r\n]+/g, match, parsing = {
2: "tag",
3: "tag",
5: "attribute key",
6: "attribute value",
8: "literal"
}[state];
while (true) {
match = newLine.exec(template);
if (null == match) break;
if (match.index > index) break;
line++;
i = match.index;
}
row = index - i;
var message = [ "Mask - Unexpected", token, "at(", line, ":", row, ") [ in", parsing, "]" ];
console.error(message.join(" "), {
template: template,
stopped: template.substring(index)
});
}
return {
parse: function(template) {
var current = new Fragment(), fragment = current, state = 2, last = 3, index = 0, length = template.length, classNames, token, key, value, next, c, start;
var go_tag = 2, state_tag = 3, state_attr = 5, go_attrVal = 6, go_attrHeadVal = 7, state_literal = 8, go_up = 9;
while (1) {
if (index < length && (c = template.charCodeAt(index)) < 33) {
index++;
continue;
}
if (last === state_attr) {
if (null != classNames) {
current.attr["class"] = ensureTemplateFunction(classNames);
classNames = null;
}
if (null != key) {
current.attr[key] = key;
key = null;
token = null;
}
}
if (null != token) {
if (state === state_attr) {
if (null == key) key = token; else value = token;
if (null != key && null != value) {
if ("class" !== key) current.attr[key] = value; else classNames = null == classNames ? value : classNames + " " + value;
key = null;
value = null;
}
} else if (last === state_tag) {
next = null != CustomTags[token] ? new Component(token, current, CustomTags[token]) : new Node(token, current);
if (null == current.nodes) current.nodes = [ next ]; else current.nodes.push(next);
current = next;
state = state_attr;
} else if (last === state_literal) {
next = new TextNode(token, current);
if (null == current.nodes) current.nodes = [ next ]; else current.nodes.push(next);
if (true === current.__single) do current = current.parent; while (null != current && null != current.__single);
state = go_tag;
}
token = null;
}
if (index >= length) {
if (state === state_attr) {
if (null != classNames) current.attr["class"] = ensureTemplateFunction(classNames);
if (null != key) current.attr[key] = key;
}
break;
}
if (state === go_up) {
current = current.parent;
while (null != current && null != current.__single) current = current.parent;
state = go_tag;
}
if (123 === c) {
last = state;
state = go_tag;
index++;
continue;
}
if (62 === c) {
last = state;
state = go_tag;
index++;
current.__single = true;
continue;
}
if (59 === c) if (null != current.nodes) {
index++;
continue;
}
if (59 === c || 125 === c) {
index++;
last = state;
state = go_up;
continue;
}
if (39 === c || 34 === c) {
if (state === go_attrVal) state = state_attr; else last = state = state_literal;
index++;
var isEscaped = false, nindex, _char = 39 === c ? "'" : '"';
start = index;
while ((nindex = template.indexOf(_char, index)) > -1) {
index = nindex;
if (92 !== template.charCodeAt(nindex - 1)) break;
isEscaped = true;
index++;
}
token = template.substring(start, index);
if (true === isEscaped) token = token.replace(regexpEscapedChar[_char], _char);
token = ensureTemplateFunction(token);
index++;
continue;
}
if (state === go_tag) {
last = state_tag;
state = state_tag;
if (46 === c || 35 === c) {
token = "div";
continue;
}
}
if (state === state_attr) if (46 === c) {
index++;
key = "class";
state = go_attrHeadVal;
} else if (35 === c) {
index++;
key = "id";
state = go_attrHeadVal;
} else if (61 === c) {
index++;
state = go_attrVal;
continue;
} else if (null != key) {
token = key;
continue;
}
if (state === go_attrVal || state === go_attrHeadVal) {
last = state;
state = state_attr;
}
if (47 === c && 47 === template.charCodeAt(index + 1)) {
index++;
while (10 !== c && 13 !== c && index < length) c = template.charCodeAt(++index);
while (c < 33 && index < length) c = template.charCodeAt(++index);
}
var isInterpolated = null;
start = index;
while (index < length) {
c = template.charCodeAt(index);
if (c === interp_code_START && template.charCodeAt(index + 1) === interp_code_OPEN) {
isInterpolated = true;
++index;
do c = template.charCodeAt(++index); while (c !== interp_code_CLOSE && index < length);
}
if (39 === c || 34 === c || 47 === c || 60 === c) {
_throw(template, index, state, String.fromCharCode(c));
break;
}
if (last !== go_attrVal && (46 === c || 35 === c || 61 === c)) break;
if (62 === c || 123 === c || c < 33 || 59 === c) break;
index++;
}
token = template.substring(start, index);
if (!token) {
_throw(template, index, state, "*EMPTY*");
break;
}
if (true === isInterpolated && false === (state === state_attr && "class" === key)) token = ensureTemplateFunction(token);
}
if (isNaN(c)) {
console.log(c, _index, _length);
throw "";
}
if (null != current.parent && current.parent !== fragment && null != current.nodes) console.warn("Mask - ", current.parent.tagName, JSON.stringify(current.parent.attr), "was not proper closed.");
return 1 === fragment.nodes.length ? fragment.nodes[0] : fragment;
},
cleanObject: function(obj) {
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i++) this.cleanObject(obj[i]);
return obj;
}
delete obj.parent;
delete obj.__single;
if (null != obj.nodes) this.cleanObject(obj.nodes);
return obj;
},
setInterpolationQuotes: function(start, end) {
if (!start || 2 !== start.length) {
console.error("Interpolation Start must contain 2 Characters");
return;
}
if (!end || 1 !== end.length) {
console.error("Interpolation End must be of 1 Character");
return;
}
interp_code_START = start.charCodeAt(0);
interp_code_OPEN = start.charCodeAt(1);
interp_code_CLOSE = end.charCodeAt(0);
interp_CLOSE = end;
interp_START = start.charAt(0);
}
};
}(Node, TextNode, Fragment, Component);
function builder_build(node, model, cntx, container, controller, childs) {
if (null == node) return container;
var type = node.type, elements;
if (null == container && 1 !== type) container = create_container();
if (null == controller) controller = new Component();
if (10 === type || node instanceof Array) {
for (var j = 0, jmax = node.length; j < jmax; j++) builder_build(node[j], model, cntx, container, controller, childs);
return container;
}
if (null == type) if (null != node.tagName) type = 1; else if (null != node.content) type = 2;
if (1 === type || 2 === type) {
var child = create_node(node, model, cntx, container, controller);
if (null == child) return container || child;
if (null != childs) {
childs.push(child);
childs = null;
}
container = child;
}
if (4 === type) {
var Handler = node.controller, handler = "function" === typeof Handler ? new Handler(model) : Handler;
if (null != handler) {
handler.compoName = node.tagName;
handler.attr = util_extend(handler.attr, node.attr);
for (var key in handler.attr) if ("function" === typeof handler.attr[key]) handler.attr[key] = handler.attr[key](model, "attr", cntx);
handler.nodes = node.nodes;
handler.parent = controller;
if (null != listeners && null != listeners["compoCreated"]) {
var fns = listeners.compoCreated, jmax = fns.length, j = 0;
for (;j < jmax; j++) fns[j](handler, model, cntx, container);
}
if ("function" === typeof handler.render) {
handler.render(model, cntx, container);
return container;
}
if ("function" === typeof handler.renderStart) handler.renderStart(model, cntx, container);
if (null != handler.tagName && handler.tagName !== node.compoName) handler.nodes = {
tagName: handler.tagName,
attr: handler.attr,
nodes: handler.nodes,
type: 1
};
node = handler;
}
(controller.components || (controller.components = [])).push(node);
controller = node;
elements = [];
if (null != node.model) model = node.model;
}
var nodes = node.nodes;
if (null != nodes) {
if (null != childs && null == elements) elements = childs;
var isarray = nodes instanceof Array, length = true === isarray ? nodes.length : 1, i = 0;
for (;i < length; i++) builder_build(true === isarray ? nodes[i] : nodes, model, cntx, container, controller, elements);
}
if (4 === type && "function" === typeof node.renderEnd) node.renderEnd(elements, model, cntx, container);
if (null != childs && childs !== elements) {
var il = childs.length, jl = elements.length, j = -1;
while (++j < jl) childs[il + j] = elements[j];
}
return container;
}
var cache = {}, Mask = {
render: function(template, model, cntx, container, controller) {
if (null != container && "function" !== typeof container.appendChild) {
console.error(".render(template[, model, cntx, container, controller]", "Container should implement .appendChild method");
console.warn("Args:", arguments);
}
if ("string" === typeof template) if (hasOwnProp.call(cache, template)) template = cache[template]; else template = cache[template] = Parser.parse(template);
return builder_build(template, model, cntx, container, controller);
},
compile: Parser.parse,
parse: Parser.parse,
registerHandler: function(tagName, TagHandler) {
CustomTags[tagName] = TagHandler;
},
getHandler: function(tagName) {
return null != tagName ? CustomTags[tagName] : CustomTags;
},
registerAttrHandler: function(attrName, Handler) {
CustomAttributes[attrName] = Handler;
},
registerUtility: function(utilityName, fn) {
ModelUtils[utilityName] = fn;
},
clearCache: function(key) {
if ("string" === typeof key) delete cache[key]; else cache = {};
},
ValueUtils: {
condition: ConditionUtil.condition,
out: ConditionUtil
},
Utils: {
Condition: ConditionUtil,
getProperty: util_getProperty
},
Dom: Dom,
plugin: function(source) {
eval(source);
},
on: function(event, fn) {
if (null == listeners) listeners = {};
(listeners[event] || (listeners[event] = [])).push(fn);
},
delegateReload: function() {},
setInterpolationQuotes: Parser.setInterpolationQuotes
};
Mask.renderDom = Mask.render;
function create_container() {
return document.createDocumentFragment();
}
function create_node(node, model, cntx, container, controller) {
var tagName = node.tagName, attr = node.attr, type = node.type, j, jmax, x, content;
if (2 === type) {
content = node.content;
if ("function" !== typeof content) {
container.appendChild(document.createTextNode(content));
return null;
}
var result = content(model, "node", cntx, container), text = "";
if ("string" === typeof result) {
container.appendChild(document.createTextNode(result));
return null;
}
for (j = 0, jmax = result.length; j < jmax; j++) {
x = result[j];
if ("object" === typeof x) {
if ("" !== text) {
container.appendChild(document.createTextNode(text));
text = "";
}
if (null == x.nodeType) {
console.warn("Not a HTMLElement", x, node, model);
text += x.toString();
continue;
}
container.appendChild(x);
continue;
}
text += x;
}
if ("" !== text) container.appendChild(document.createTextNode(text));
return null;
}
var tag = document.createElement(tagName), key, value;
for (key in attr) {
if (false === hasOwnProp.call(attr, key)) continue;
if ("function" === typeof attr[key]) {
value = attr[key](model, "attr", cntx, tag, key);
if (value instanceof Array) value = value.join("");
} else value = attr[key];
if (value) if ("function" === typeof CustomAttributes[key]) CustomAttributes[key](node, value, tag, model, cntx, controller); else tag.setAttribute(key, value);
}
if (null != container) container.appendChild(tag);
return tag;
}
(function(mask) {
var stringify = function() {
var _minimizeAttributes, _indent, Dom = mask.Dom;
function doindent(count) {
var output = "";
while (count--) output += " ";
return output;
}
function run(node, indent, output) {
var outer, i;
if (null == indent) indent = 0;
if (null == output) {
outer = true;
output = [];
}
var index = output.length;
if (node.type === Dom.FRAGMENT) node = node.nodes;
if (node instanceof Array) for (i = 0; i < node.length; i++) processNode(node[i], indent, output); else processNode(node, indent, output);
var spaces = doindent(indent);
for (i = index; i < output.length; i++) output[i] = spaces + output[i];
if (outer) return output.join(0 === _indent ? "" : "\n");
}
function processNode(node, currentIndent, output) {
if ("string" === typeof node.content) {
output.push(wrapString(node.content));
return;
}
if ("function" === typeof node.content) {
output.push(wrapString(node.content()));
return;
}
if (isEmpty(node)) {
output.push(processNodeHead(node) + ";");
return;
}
if (isSingle(node)) {
output.push(processNodeHead(node) + " > ");
run(getSingle(node), _indent, output);
return;
}
output.push(processNodeHead(node) + "{");
run(node.nodes, _indent, output);
output.push("}");
return;
}
function processNodeHead(node) {
var tagName = node.tagName, _id = node.attr.id || "", _class = node.attr["class"] || "";
if ("function" === typeof _id) _id = _id();
if ("function" === typeof _class) _class = _class();
if (_id) if (_id.indexOf(" ") !== -1) _id = ""; else _id = "#" + _id;
if (_class) _class = "." + _class.split(" ").join(".");
var attr = "";
for (var key in node.attr) {
if ("id" === key || "class" === key) continue;
var value = node.attr[key];
if ("function" === typeof value) value = value();
if (false === _minimizeAttributes || /\s/.test(value)) value = wrapString(value);
attr += " " + key + "=" + value;
}
if ("div" === tagName && (_id || _class)) tagName = "";
return tagName + _id + _class + attr;
}
function isEmpty(node) {
return null == node.nodes || node.nodes instanceof Array && 0 === node.nodes.length;
}
function isSingle(node) {
return node.nodes && (false === node.nodes instanceof Array || 1 === node.nodes.length);
}
function getSingle(node) {
if (node.nodes instanceof Array) return node.nodes[0];
return node.nodes;
}
function wrapString(str) {
if (str.indexOf('"') === -1) return '"' + str.trim() + '"';
if (str.indexOf("'") === -1) return "'" + str.trim() + "'";
return '"' + str.replace(/"/g, '\\"').trim() + '"';
}
return function(input, settings) {
if ("string" === typeof input) input = mask.parse(input);
if ("number" === typeof settings) {
_indent = settings;
_minimizeAttributes = 0 === _indent;
} else {
_indent = settings && settings.indent || 4;
_minimizeAttributes = 0 === _indent || settings && settings.minimizeAttributes;
}
return run(input);
};
}();
Mask.stringify = stringify;
})(Mask);
(function(mask) {
mask.registerHandler("%", Sys);
function Sys() {}
Sys.prototype = {
constructor: Sys,
renderStart: function(model, cntx, container) {
var attr = this.attr;
if (null != attr["use"]) {
this.model = util_getProperty(model, attr["use"]);
return;
}
if (null != attr["debugger"]) {
debugger;
return;
}
if (null != attr["log"]) {
var key = attr.log, value = util_getProperty(model, key);
console.log("Key: %s, Value: %s", key, value);
return;
}
this.model = model;
if (null != attr["if"]) {
var check = attr["if"];
this.state = ConditionUtil.isCondition(check, model);
if (!this.state) this.nodes = null;
return;
}
if (null != attr["else"]) {
var compos = this.parent.components, prev = compos && compos[compos.length - 1];
if (null != prev && "%" === prev.compoName && null != prev.attr["if"]) {
if (prev.state) this.nodes = null;
return;
}
console.error("Previous Node should be \"% if='condition'\"", prev, this.parent);
return;
}
if (null != attr["foreach"] || null != attr["each"]) each(this, model, cntx, container);
},
render: null
};
function each(compo, model, cntx, container) {
if (null == compo.nodes && "undefined" !== typeof Compo) Compo.ensureTemplate(compo);
var array = util_getProperty(model, compo.attr.foreach || compo.attr.each), nodes = compo.nodes, item = null;
compo.nodes = [];
compo.template = nodes;
if (false === array instanceof Array) return;
for (var i = 0, x, length = array.length; i < length; i++) {
x = array[i];
item = new Component();
item.nodes = nodes;
item.model = x;
item.container = container;
compo.nodes[i] = item;
}
}
})(Mask);
(function(mask) {
var TemplateCollection = {};
mask.templates = TemplateCollection;
mask.registerHandler(":template", TemplateHandler);
function TemplateHandler() {}
TemplateHandler.prototype.render = function() {
if (null != this.attr.id) {
console.warn("Template Should be defined with ID attribute for future lookup");
return;
}
TemplateCollection[this.attr.id] = this;
};
mask.registerHandler(":html", HTMLHandler);
function HTMLHandler() {}
HTMLHandler.prototype.render = function(model, cntx, container) {
var source = null;
if (null != this.attr.template) {
var c = this.attr.template[0];
if ("#" === c) source = document.getElementById(this.attr.template.substring(1)).innerHTML;
}
if (this.nodes) source = this.nodes[0].content;
if (null == source) {
console.warn("No HTML for node", this);
return;
}
container.innerHTML = source;
};
})(Mask);
(function(mask) {
var $ = window.jQuery || window.Zepto || window.$;
if (null == $) console.warn("Without jQuery/Zepto etc. binder is limited (mouse dom event bindings)");
function ensureObject(obj, chain) {
for (var i = 0, length = chain.length - 1; i < length; i++) {
var key = chain.shift();
if (null == obj[key]) obj[key] = {};
obj = obj[key];
}
return obj;
}
function extendObject(obj, source) {
if (null == source) return obj;
if (null == obj) obj = {};
for (var key in source) obj[key] = source[key];
return obj;
}
function getProperty(obj, property) {
var chain = property.split("."), length = chain.length, i = 0;
for (;i < length; i++) {
if (null == obj) return null;
obj = obj[chain[i]];
}
return obj;
}
function setProperty(obj, property, value) {
var chain = property.split("."), length = chain.length, i = 0, key = null;
for (;i < length - 1; i++) {
key = chain[i];
if (null == obj[key]) obj[key] = {};
obj = obj[key];
}
obj[chain[i]] = value;
}
function addObjectObserver(obj, property, callback) {
if (null == obj.__observers) Object.defineProperty(obj, "__observers", {
value: {},
enumerable: false
});
var observers = obj.__observers[property] || (obj.__observers[property] = []), chain = property.split("."), parent = chain.length > 1 ? ensureObject(obj, chain) : obj, key = chain[0], currentValue = parent[key];
observers.push(callback);
Object.defineProperty(parent, key, {
get: function() {
return currentValue;
},
set: function(x) {
currentValue = x;
for (var i = 0, length = observers.length; i < length; i++) observers[i](x);
}
});
}
function removeObjectObserver(obj, property, callback) {
if (null == obj.__observers || null == obj.__observers[property]) return;
var currentValue = getProperty(obj, property);
if (2 === arguments.length) {
setProperty(obj, property, currentValue);
delete obj.__observers[property];
return;
}
var arr = obj.__observers[property], length = arr.length, i = 0;
for (;i < length; i++) if (callback === arr[i]) {
arr.split(i, 1);
i--;
length--;
}
}
function observeArray(arr, callback) {
Object.defineProperty(arr, "hasObserver", {
value: true,
enumerable: false,
writable: false
});
function wrap(method) {
arr[method] = function() {
Array.prototype[method].apply(this, arguments);
callback(this, method, arguments);
};
}
var i = 0, fns = [ "push", "unshift", "splice", "pop", "shift", "reverse", "sort" ], length = fns.length;
for (;i < length; i++) wrap(fns[i]);
}
function addEventListener(element, event, listener) {
if ("function" === typeof $) {
$(element).on(event, listener);
return;
}
if (null != element.addEventListener) {
element.addEventListener(event, listener, false);
return;
}
if (element.attachEvent) element.attachEvent("on" + event, listener);
}
function VisibleHandler() {}
mask.registerHandler(":visible", VisibleHandler);
VisibleHandler.prototype = {
constructor: VisibleHandler,
refresh: function(model, container) {
container.style.display = mask.Utils.Condition.isCondition(this.attr.check, model) ? "" : "none";
},
renderStart: function(model, cntx, container) {
this.refresh(model, container);
if (this.attr.bind) addObjectObserver(model, this.attr.bind, this.refresh.bind(this, model, container));
}
};
function Bind() {}
mask.registerHandler(":bind", Bind);
Bind.prototype.renderStart = function(model, cntx, container) {
new BindingProvider(model, container, this, "single");
};
mask.registerUtility("bind", function(property, model, type, cntx, element, attrName) {
var current = getProperty(model, property);
switch (type) {
case "node":
var node = document.createTextNode(current);
addObjectObserver(model, property, function(value) {
node.textContent = value;
});
return node;
case "attr":
addObjectObserver(model, property, function(value) {
var attrValue = element.getAttribute(attrName);
element.setAttribute(attrName, attrValue.replace(current, value));
current = value;
});
return current;
}
console.error("Unknown binding type", arguments);
return "Unknown";
});
var Providers = {};
mask.registerBinding = function(type, binding) {
Providers[type] = binding;
};
mask.BindingProvider = BindingProvider;
function BindingProvider(model, element, node, bindingType) {
if (this.constructor === BindingProvider) {
var type = node.attr.bindingProvider || element.tagName.toLowerCase();
if (Providers[type] instanceof Function) return new Providers[type](model, element, node); else extendObject(this, Providers[type]);
}
if (null == bindingType) bindingType = ":bind" === node.compoName ? "single" : "dual";
this.node = node;
this.model = model;
this.element = element;
this.property = node.attr.property || ("single" === bindingType ? "element.innerHTML" : "element.value");
this.setter = node.attr.setter;
this.getter = node.attr.getter;
this.dismiss = 0;
addObjectObserver(model, node.attr.value, this.objectChanged.bind(this));
if ("single" !== bindingType) addEventListener(element, node.attr.changeEvent || "change", this.domChanged.bind(this));
this.objectChanged();
return this;
}
BindingProvider.prototype = {
constructor: BindingProvider,
objectChanged: function(x) {
if (this.dismiss-- > 0) return;
if (null == x) x = this.objectWay.get(this.model, this.node.attr.value);
this.domWay.set(this, x);
if (x instanceof Array && true !== x.hasObserver) observeArray(x, this.objectChanged.bind(this));
},
domChanged: function() {
var x = this.domWay.get(this);
if (this.node.validations) for (var i = 0, validation, length = this.node.validations.length; i < length; i++) {
validation = this.node.validations[i];
if (false === validation.validate(x, this.element, this.objectChanged.bind(this))) return;
}
this.dismiss = 1;
this.objectWay.set(this.model, this.node.attr.value, x);
this.dismiss = 0;
},
objectWay: {
get: function(obj, property) {
if (":" === property[0]) return mask.Utils.ConditionUtil.condition(property.substring(1));
return getProperty(obj, property);
},
set: function(obj, property, value) {
setProperty(obj, property, value);
}
},
domWay: {
get: function(provider) {
if (provider.getter) return provider.node.parent[provider.getter]();
return getProperty(provider, provider.property);
},
set: function(provider, value) {
if (provider.setter) provider.node.parent[provider.setter](value); else setProperty(provider, provider.property, value);
}
}
};
function DualbindHandler() {}
mask.registerHandler(":dualbind", DualbindHandler);
DualbindHandler.prototype.renderEnd = function(elements, model, cntx, container) {
if (this.components) for (var i = 0, x, length = this.components.length; i < length; i++) {
x = this.components[i];
if (":validate" === x.compoName) (this.validations || (this.validations = [])).push(x);
}
new BindingProvider(model, container, this);
};
(function() {
mask.registerValidator = function(type, validator) {
Validators[type] = validator;
};
function Validate() {}
mask.registerHandler(":validate", Validate);
Validate.prototype = {
constructor: Validate,
renderStart: function(model, cntx, container) {
this.element = container;
this.model = model;
},
validate: function(input, element, oncancel) {
if (null == element) element = this.element;
if (this.attr.getter) input = getProperty({
node: this,
element: element
}, this.attr.getter);
if (null == this.validators) this.initValidators();
for (var i = 0, x, length = this.validators.length; i < length; i++) {
x = this.validators[i];
if (false === x.validate(this, input)) {
notifyInvalid(element, this.message, oncancel);
return false;
}
}
isValid(element);
return true;
},
initValidators: function() {
this.validators = [];
this.message = this.attr.message;
delete this.attr.message;
for (var key in this.attr) {
if (false === key in Validators) {
console.error("Unknown Validator:", key, this);
continue;
}
var Validator = Validators[key];
if ("function" === typeof Validator) Validator = new Validator(this);
this.validators.push(Validator);
}
}
};
function notifyInvalid(element, message, oncancel) {
console.warn("Validate Notification:", element, message);
var next = $(element).next(".-validate-invalid");
if (0 === next.length) next = $("<div>").addClass("-validate-invalid").html("<span></span><button>cancel</button>").insertAfter(element);
next.children("button").off().on("click", function() {
next.hide();
oncancel && oncancel();
}).end().children("span").text(message).end().show();
}
function isValid(element) {
$(element).next(".-validate-invalid").hide();
}
var Validators = {
match: {
validate: function(node, str) {
return new RegExp(node.attr.match).test(str);
}
},
unmatch: {
validate: function(node, str) {
return !new RegExp(node.attr.unmatch).test(str);
}
},
minLength: {
validate: function(node, str) {
return str.length >= parseInt(node.attr.minLength, 10);
}
},
maxLength: {
validate: function(node, str) {
return str.length <= parseInt(node.attr.maxLength, 10);
}
}
};
})();
function ValidateGroup() {}
mask.registerHandler(":validate:group", ValidateGroup);
ValidateGroup.prototype = {
constructor: ValidateGroup,
validate: function() {
var validations = getValidations(this);
for (var i = 0, x, length = validations.length; i < length; i++) {
x = validations[i];
if (!x.validate()) return false;
}
return true;
}
};
function getValidations(component, out) {
if (null == out) out = [];
if (null == component.components) return out;
var compos = component.components;
for (var i = 0, x, length = compos.length; i < length; i++) {
x = compos[i];
if ("validate" === x.compoName) {
out.push(x);
continue;
}
getValidations(x);
}
return out;
}
mask.registerAttrHandler("x-signal", function(node, attrValue, element, model, cntx, controller) {
var arr = attrValue.split(";");
for (var i = 0, x, length = arr.length; i < length; i++) {
x = arr[i];
var event = x.substring(0, x.indexOf(":")), handler = x.substring(x.indexOf(":") + 1).trim(), Handler = getHandler(controller, handler);
if (Handler) addEventListener(element, event, Handler);
!Handler && console.warn("No slot found for signal", handler, controller);
}
});
function getHandler(controller, name) {
if (null == controller) return null;
if (null != controller.slots && "undefined" !== typeof controller.slots[name]) {
var slot = controller.slots[name];
if ("string" === typeof slot) slot = controller[slot];
"function" !== typeof slot && console.error("Controller defines slot, but that is not a function", controller, name);
return slot.bind(controller);
}
return getHandler(controller.parent, name);
}
})(Mask);
return Mask;
});
include.getResource("/.reference/libjs/mask/lib/mask.js", "js").readystatechanged(3);
include.setCurrent({
id: "/.reference/libjs/compo/lib/compo.js",
namespace: "lib.compo",
url: "/.reference/libjs/compo/lib/compo.js"
});
(function(root, factory) {
"use strict";
if (null == root && "undefined" !== typeof global) root = global;
var doc = "undefined" === typeof document ? null : document, construct = function() {
return factory(root, mask);
};
if ("object" === typeof exports) module.exports = construct(); else if ("function" === typeof define && define.amd) define(construct); else {
var lib = construct();
for (var key in lib) root[key] = lib[key];
}
})(this, function(global, mask) {
"use strict";
var domLib = global.jQuery || global.Zepto || global.$;
if (!domLib) console.warn("jQuery / Zepto etc. was not loaded before compo.js, please use Compo.config.setDOMLibrary to define dom engine");
if ("undefined" === typeof Array.prototype.indexOf) Array.prototype.indexOf = function(value) {
var i = -1, length = this.length;
while (++i < length) if (this[i] === value) return i;
return -1;
};
function arr_each(array, fn) {
for (var i = 0, length = array.length; i < length; i++) fn(array[i], i);
}
function arr_remove(array, child) {
if (null == array) {
console.error("Can not remove myself from parent", child);
return;
}
var index = array.indexOf(child);
if (index === -1) {
console.error("Can not remove myself from parent", child, index);
return;
}
array.splice(index, 1);
}
function util_extend(target, source) {
if (null == target) target = {};
if (null == source) return target;
for (var key in source) target[key] = source[key];
return target;
}
var Dom = mask.Dom;
function selector_parse(selector, type, direction) {
var key, prop, nextKey;
if (null == key) switch (selector[0]) {
case "#":
key = "id";
selector = selector.substring(1);
prop = "attr";
break;
case ".":
key = "class";
selector = new RegExp("\\b" + selector.substring(1) + "\\b");
prop = "attr";
break;
default:
key = type == Dom.SET ? "tagName" : "compoName";
}
if ("up" == direction) nextKey = "parent"; else nextKey = type == Dom.SET ? "nodes" : "components";
return {
key: key,
prop: prop,
selector: selector,
nextKey: nextKey
};
}
function selector_match(node, selector, type) {
if ("string" === typeof selector) {
if (null == type) type = Dom[node.compoName ? "CONTROLLER" : "SET"];
selector = parseSelector(selector, type);
}
var obj = selector.prop ? node[selector.prop] : node;
if (null == obj) return false;
if (null != selector.selector.test) {
if (selector.selector.test(obj[selector.key])) return true;
} else if (obj[selector.key] == selector.selector) return true;
return false;
}
function find_findSingle(node, matcher) {
if (node instanceof Array) {
for (var i = 0, x, length = node.length; i < length; i++) {
x = node[i];
var r = find_findSingle(x, matcher);
if (null != r) return r;
}
return null;
}
if (true === selector_match(node, matcher)) return node;
return (node = node[matcher.nextKey]) && find_findSingle(node, matcher);
}
var jMask = function() {
var _mask_parse = mask.parse, _mask_render = mask.render;
function jMask(mix) {
if (false === this instanceof jMask) return new jMask(mix);
if (null == mix) return this;
if (mix.type === Dom.SET) return mix;
return this.add(mix);
}
jMask.prototype = {
constructor: jMask,
type: Dom.SET,
length: 0,
components: null,
add: function(mix) {
if ("string" === typeof mix) mix = _mask_parse(mix);
if (mix instanceof Array) {
for (var i = 0, length = mix.length; i < length; i++) this.add(mix[i]);
return this;
}
if ("function" === typeof mix && null != mix.prototype.type) mix = {
controller: mix,
type: Dom.COMPONENT
};
var type = mix.type;
if (!type) {
console.error("Only Mask Node/Component/NodeText/Fragment can be added to jmask set", mix);
return this;
}
if (type === Dom.FRAGMENT) {
var nodes = mix.nodes, i = 0, length = nodes.length;
while (i < length) this[this.length++] = nodes[i++];
return this;
}
if (type === Dom.CONTROLLER && null != mix.nodes) {
var i = mix.nodes.length;
while (0 !== i, --i) mix.nodes[i].parent = mix;
}
this[this.length++] = mix;
return this;
},
toArray: function() {
return Array.prototype.slice.call(this);
},
render: function(model, cntx, container) {
this.components = [];
if (1 === this.length) return _mask_render(this[0], model, cntx, container, this);
if (null == container) container = document.createDocumentFragment();
for (var i = 0, x, length = this.length; i < length; i++) _mask_render(this[i], model, cntx, container, this);
return container;
},
prevObject: null,
end: function() {
return this.prevObject || this;
},
pushStack: function(nodes) {
var next;
next = jMask(nodes);
next.prevObject = this;
return next;
},
controllers: function(selector) {
if (null == this.components) console.warn("Set was not rendered");
return this.pushStack(this.components || []);
},
mask: function(template) {
if (null != template) return this.empty().append(template);
if (arguments.length) return this;
var node;
if (0 === this.length) node = new Dom.Node(); else if (1 === this.length) node = this[0]; else {
node = new Dom.Fragment();
for (var i = 0, x, length = this.length; i < length; i++) node.nodes[i] = this[i];
}
return mask.stringify(node);
}
};
arr_each([ "append", "prepend" ], function(method) {
jMask.prototype[method] = function(mix) {
var $mix = jMask(mix), i = 0, length = this.length, arr, node;
for (;i < length; i++) {
node = this[i];
arr = $mix.toArray();
for (var j = 0, jmax = arr.length; j < jmax; j++) arr[j].parent = node;
if (null == node.nodes) {
node.nodes = arr;
continue;
}
node.nodes = "append" === method ? node.nodes.concat(arr) : arr.concat(node.nodes);
}
return this;
};
});
arr_each([ "appendTo" ], function(method) {
jMask.prototype[method] = function(mix, model, cntx) {
if (null != mix.nodeType && "function" === typeof mix.appendChild) {
mix.appendChild(this.render(model, cntx));
Compo.shots.emit(this, "DOMInsert");
return this;
}
jMask(mix).append(this);
return this;
};
});
function jmask_filter(arr, matcher) {
if (null == matcher) return arr;
var result = [];
for (var i = 0, x, length = arr.length; i < length; i++) {
x = arr[i];
if (selector_match(x, matcher)) result.push(x);
}
return result;
}
function jmask_find(mix, matcher, output) {
if (null == output) output = [];
if (mix instanceof Array) {
for (var i = 0, length = mix.length; i < length; i++) jmask_find(mix[i], matcher, output);
return output;
}
if (selector_match(mix, matcher)) output.push(mix);
var next = mix[matcher.nextKey];
if (null != next) jmask_find(next, matcher, output);
return output;
}
function jmask_clone(node, parent) {
var copy = {
type: 1,
tagName: 1,
compoName: 1,
controller: 1
};
var clone = {
parent: parent
};
for (var key in node) if (1 === copy[key]) clone[key] = node[key];
if (node.attr) clone.attr = util_extend({}, node.attr);
var nodes = node.nodes;
if (null != nodes && nodes.length > 0) {
clone.nodes = [];
var isarray = nodes instanceof Array, length = true === isarray ? nodes.length : 1, i = 0, x;
for (;i < length; i++) clone.nodes[i] = jmask_clone(true === isarray ? nodes[i] : nodes, clone);
}
return clone;
}
function jmask_deepest(node) {
var current = node, prev;
while (null != current) {
prev = current;
current = current.nodes && current.nodes[0];
}
return prev;
}
function jmask_initHandlers($$, parent) {
var instance;
for (var i = 0, x, length = $$.length; i < length; i++) {
x = $$[i];
if (x.type === Dom.COMPONENT) if ("function" === typeof x.controller) {
instance = new x.controller();
instance.nodes = x.nodes;
instance.attr = util_extend(instance.attr, x.attr);
instance.compoName = x.compoName;
instance.parent = parent;
x = $$[i] = instance;
}
if (null != x.nodes) jmask_initHandlers(x.nodes, x);
}
}
(function() {
arr_each([ "add", "remove", "toggle", "has" ], function(method) {
jMask.prototype[method + "Class"] = function(klass) {
var length = this.length, i = 0, classNames, j, jmax, node, current;
if ("string" !== typeof klass) {
if ("remove" === method) for (;i < length; i++) this[0].attr["class"] = null;
return this;
}
for (;i < length; i++) {
node = this[i];
if (null == node.attr) continue;
current = node.attr["class"];
if (null == current) current = klass; else {
current = " " + current + " ";
if (null == classNames) {
classNames = klass.split(" ");
jmax = classNames.length;
}
for (j = 0; j < jmax; j++) {
if (!classNames[j]) continue;
var hasClass = current.indexOf(" " + classNames[j] + " ") > -1;
if ("has" === method) if (hasClass) return true; else continue;
if (false === hasClass && ("add" === method || "toggle" === method)) current += classNames[j] + " "; else if (true === hasClass && ("remove" === method || "toggle" === method)) current = current.replace(" " + classNames[j] + " ", " ");
}
current = current.trim();
}
if ("has" !== method) node.attr["class"] = current;
}
if ("has" === method) return false;
return this;
};
});
arr_each([ "attr", "removeAttr", "prop", "removeProp" ], function(method) {
jMask.prototype[method] = function(key, value) {
if (!key) return this;
var length = this.length, i = 0, args = arguments.length, node;
for (;i < length; i++) {
node = this[i];
switch (method) {
case "attr":
case "prop":
if (1 === args) if ("string" === typeof key) return node.attr[key]; else for (var x in key) node.attr[x] = key[x]; else if (2 === args) node.attr[key] = value;
break;
case "removeAttr":
case "removeProp":
node.attr[key] = null;
}
}
return this;
};
});
util_extend(jMask.prototype, {
tag: function(arg) {
if ("string" === typeof arg) {
for (var i = 0, length = this.length; i < length; i++) this[i].tagName = arg;
return this;
}
return this[0] && this[0].tagName;
},
css: function(mix, value) {
var args = arguments.length, length = this.length, i = 0, node, css, j, jmax, index, key, style;
if (1 === args && "string" === typeof mix) {
if (0 === length) return null;
if ("string" === typeof this[0].attr.style) return css_toObject(this[0].attr.style)[mix]; else return null;
}
for (;i < length; i++) {
style = this[i].attr.style;
if ("function" === typeof style) continue;
if (1 === args && "object" === typeof mix) {
if (null == style) {
this[i].attr.style = css_toString(mix);
continue;
}
css = css_toObject(style);
for (key in mix) css[key] = mix[key];
this[i].attr.style = css_toString(css);
}
if (2 === args) {
if (null == style) {
this[i].attr.style = mix + ":" + value;
continue;
}
css = css_toObject(style);
css[mix] = value;
this[i].attr.style = css_toString(css);
}
}
return this;
}
});
function css_toObject(style) {
var arr = style.split(";"), obj = {}, index;
for (var i = 0, x, length = arr.length; i < length; i++) {
x = arr[i];
index = x.indexOf(":");
obj[x.substring(0, index).trim()] = x.substring(index + 1).trim();
}
return obj;
}
function css_toString(css) {
var output = [], i = 0;
for (var key in css) output[i++] = key + ":" + css[key];
return output.join(";");
}
})();
util_extend(jMask.prototype, {
clone: function() {
var result = [];
for (var i = 0, length = this.length; i < length; i++) result[i] = jmask_clone(this[0]);
return jMask(result);
},
wrap: function(wrapper) {
var $mask = jMask(wrapper), result = [], $wrapper, deepest;
if (0 === $mask.length) {
console.log("Not valid wrapper", wrapper);
return this;
}
for (var i = 0, x, length = this.length; i < length; i++) {
$wrapper = length > 0 ? $mask.clone() : $mask;
jmask_deepest($wrapper[0]).nodes = [ this[i] ];
result[i] = $wrapper[0];
if (null != this[i].parent) this[i].parent.nodes = result[i];
}
return jMask(result);
},
wrapAll: function(wrapper) {
var $wrapper = jMask(wrapper);
if (0 === $wrapper.length) {
console.error("Not valid wrapper", wrapper);
return this;
}
this.parent().mask($wrapper);
jmask_deepest($wrapper[0]).nodes = this.toArray();
return this.pushStack($wrapper);
}
});
arr_each([ "empty", "remove" ], function(method) {
jMask.prototype[method] = function(mix) {
var i = 0, length = this.length, arr, node;
for (;i < length; i++) {
node = this[i];
if ("empty" === method) {
node.nodes = null;
continue;
}
if ("remove" === method) {
if (null != node.parent) arr_remove(node.parent.nodes, node);
continue;
}
}
return this;
};
});
util_extend(jMask.prototype, {
each: function(fn) {
for (var i = 0, x, length = this.length; i < length; i++) fn(this[i], i);
return this;
},
eq: function(i) {
return i === -1 ? this.slice(i) : this.slice(i, i + 1);
},
get: function(i) {
return i < 0 ? this[this.length - i] : this[i];
},
slice: function() {
return this.pushStack(Array.prototype.slice.apply(this, arguments));
}
});
arr_each([ "filter", "children", "closest", "parent", "find", "first", "last" ], function(method) {
jMask.prototype[method] = function(selector) {
var result = [], matcher = null == selector ? null : selector_parse(selector, this.type, "closest" === method ? "up" : "down");
switch (method) {
case "filter":
return jMask(jmask_filter(this, matcher));
case "children":
for (var i = 0, x, length = this.length; i < length; i++) {
x = this[i];
if (null == x.nodes) continue;
result = result.concat(null == matcher ? x.nodes : jmask_filter(x.nodes, matcher));
}
break;
case "parent":
for (var i = 0, x, length = this.length; i < length; i++) {
x = this[i].parent;
if (!x || x.type === Dom.FRAGMENT || matcher && selector_match(x, matcher)) continue;
result.push(x);
}
break;
case "closest":
case "find":
if (null == matcher) break;
for (var i = 0, length = this.length; i < length; i++) jmask_find(this[i][matcher.nextKey], matcher, result);
break;
case "first":
case "last":
var index;
for (var i = 0, x, length = this.length; i < length; i++) {
index = "first" === method ? i : length - i - 1;
x = this[index];
if (null == matcher || selector_match(x, matcher)) {
result[0] = x;
break;
}
}
}
return this.pushStack(result);
};
});
return jMask;
}();
var Children_ = {
select: function(component, compos) {
for (var name in compos) {
var data = compos[name], events = null, selector = null;
if (data instanceof Array) {
selector = data[0];
events = data.splice(1);
}
if ("string" == typeof data) selector = data;
if (null == data) {
console.error("Unknown component child", name, compos[name]);
return;
}
var index = selector.indexOf(":"), engine = selector.substring(0, index);
engine = Compo.config.selectors[engine];
if (null == engine) component.compos[name] = component.$[0].querySelector(selector); else {
selector = selector.substring(++index).trim();
component.compos[name] = engine(component, selector);
}
var element = component.compos[name];
if (null != events) {
if (element instanceof Compo) element = element.$;
Events_.on(component, events, element);
}
}
}
};
var Shots = {
emit: function(component, event, args) {
if (null != component.listeners && event in component.listeners) {
component.listeners[event].apply(component, args);
delete component.listeners[event];
}
if (component.components instanceof Array) for (var i = 0; i < component.components.length; i++) Shots.emit(component.components[i], event, args);
},
on: function(component, event, fn) {
if (null == component.listeners) component.listeners = {};
component.listeners[event] = fn;
}
}, Events_ = {
on: function(component, events, $element) {
if (null == $element) $element = component.$;
var isarray = events instanceof Array, length = isarray ? events.length : 1;
for (var i = 0, x; isarray ? i < length : i < 1; i++) {
x = isarray ? events[i] : events;
if (x instanceof Array) {
$element.on.apply($element, x);
continue;
}
for (var key in x) {
var fn = "string" === typeof x[key] ? component[x[key]] : x[key], parts = key.split(":");
$element.on(parts[0] || "click", parts.splice(1).join(":").trim() || null, fn.bind(component));
}
}
}
};
var Anchor = function() {
var _cache = {}, _counter = 0;
return {
create: function(compo, elements) {
_cache[++_counter] = compo;
for (var i = 0, x, length = elements.length; i < length; i++) elements[i].setAttribute("x-compo-id", _counter);
},
resolveCompo: function(element) {
do {
var id = element.getAttribute("x-compo-id");
if (null != id) {
var compo = _cache[id];
if (null == compo) console.warn("No component in cache for id", id);
return compo;
}
element = element.parentNode;
} while (element && 1 === element.nodeType);
return null;
},
removeCompo: function(compo) {
for (var key in _cache) if (_cache[key] === compo) {
delete _cache[key];
return;
}
}
};
}();
var Compo = function() {
function Compo(controller) {
var klass;
if (null == controller) controller = {};
if (controller.hasOwnProperty("constructor")) klass = controller.constructor;
if (null == klass) klass = function CompoBase() {};
for (var key in Proto) {
if (null == controller[key]) controller[key] = Proto[key];
controller["base_" + key] = Proto[key];
}
klass.prototype = controller;
return klass;
}
function compo_dispose(compo) {
if (null != compo.dispose) compo.dispose();
Anchor.removeCompo(compo);
var i = 0, compos = compo.components, length = compos && compos.length;
if (length) for (;i < length; i++) compo_dispose(compos[i]);
}
function compo_ensureTemplate(compo) {
if (null != compo.nodes) return;
var template = compo.attr.template;
if ("string" === typeof template) {
if ("#" === template[0]) {
var node = document.getElementById(template.substring(1));
if (null == node) {
console.error("Template holder not found by id:", template);
return;
}
template = node.innerHTML;
}
template = mask.compile(template);
}
if ("undefined" !== typeof template) {
compo.nodes = template;
delete compo.attr.template;
}
}
function compo_containerArray() {
var arr = [];
arr.appendChild = function(child) {
this.push(child);
};
return arr;
}
util_extend(Compo, {
render: function(compo, model, cntx, container) {
compo_ensureTemplate(compo);
var elements = [];
mask.render(null == compo.tagName ? compo.nodes : compo, model, cntx, container, compo, elements);
compo.$ = domLib(elements);
if (null != compo.events) Events_.on(compo, compo.events);
if (null != compo.compos) Children_.select(compo, compo.compos);
return compo;
},
initialize: function(compo, model, cntx, container, parent) {
if (null == container) if (cntx && null != cntx.nodeType) {
cntx = null;
container = cntx;
} else if (model && null != model.nodeType) {
model = null;
container = cntx;
}
if ("string" === typeof compo) {
compo = mask.getHandler(compo);
if (!compo) console.error("Compo not found:", compo);
}
var node = {
controller: compo,
type: Dom.COMPONENT
};
if (null == parent && null != container) parent = Anchor.resolveCompo(container);
if (null == parent) parent = {};
var dom = mask.render(node, model, cntx, null, parent), instance = parent.components[parent.components.length - 1];
if (null != container) {
container.appendChild(dom);
Compo.shots.emit(instance, "DOMInsert");
}
return instance;
},
dispose: function(compo) {
compo.dispose && compo.dispose();
var i = 0, compos = compo.components, length = compos && compos.length;
if (length) for (;i < length; i++) Compo.dispose(compos[i]);
},
find: function(compo, selector) {
return find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, "down"));
},
closest: function(compo, selector) {
return find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, "up"));
},
ensureTemplate: compo_ensureTemplate,
config: {
selectors: {
$: function(compo, selector) {
var r = compo.$.find(selector);
if (r.length > 0) return r;
r = compo.$.filter(selector);
if (0 === r.length) console.error("Compo Selector - element not found -", selector, compo);
return r;
},
compo: function(compo, selector) {
var r = Compo.find(compo, selector);
if (null == r) console.error("Compo Selector - component not found -", selector, compo);
return r;
}
},
setDOMLibrary: function(lib) {
domLib = lib;
}
},
shots: Shots
});
var Proto = {
type: Dom.CONTROLLER,
tagName: null,
compoName: null,
nodes: null,
attr: null,
onRenderStart: null,
onRenderEnd: null,
render: null,
renderStart: function(model, cntx, container) {
if (1 === arguments.length && false === model instanceof Array && null != model[0]) {
model = arguments[0][0];
cntx = arguments[0][1];
container = arguments[0][2];
}
if ("function" === typeof this.onRenderStart) this.onRenderStart(model, cntx, container);
if (null == this.model) this.model = model;
if (null == this.nodes) compo_ensureTemplate(this);
},
renderEnd: function(elements, model, cntx, container) {
if (1 === arguments.length && false === elements instanceof Array) {
elements = arguments[0][0];
model = arguments[0][1];
cntx = arguments[0][2];
container = arguments[0][3];
}
Anchor.create(this, elements);
this.$ = domLib(elements);
if (null != this.events) Events_.on(this, this.events);
if (null != this.compos) Children_.select(this, this.compos);
if ("function" === typeof this.onRenderEnd) this.onRenderEnd(elements, model, cntx, container);
},
appendTo: function(arg, cntx) {
var element;
if ("string" === typeof arg) element = document.querySelector(arg); else element = arg;
if (null == element) {
console.warn("Compo.appendTo: parent is undefined. Args:", arguments);
return this;
}
for (var i = 0; i < this.$.length; i++) element.appendChild(this.$[i]);
Shots.emit(this, "DOMInsert");
return this;
},
append: function(template, model, selector) {
var parent;
if (null == this.$) {
var dom = "string" == typeof template ? mask.compile(template) : template;
parent = selector ? jmask(this).find(selector).get(0) : this;
if (null == parent.nodes) {
this.nodes = dom;
return this;
}
parent.nodes = [ this.nodes, dom ];
return this;
}
var array = mask.render(template, model, null, compo_containerArray(), this);
parent = selector ? this.$.find(selector) : this.$;
for (var i = 0; i < array.length; i++) parent.append(array[i]);
Shots.emit(this, "DOMInsert");
return this;
},
find: function(selector) {
return find_findSingle(this, selector_parse(selector, Dom.CONTROLLER, "down"));
},
closest: function(selector) {
return find_findSingle(this, selector_parse(selector, Dom.CONTROLLER, "up"));
},
on: function() {
var x = Array.prototype.slice.call(arguments);
if (arguments.length < 3) {
console.error("Invalid Arguments Exception @use .on(type,selector,fn)");
return this;
}
if (null != this.$) Events_.on(this, [ x ]);
if (null == this.events) this.events = [ x ]; else if (this.events instanceof Array) this.events.push(x); else this.events = [ x, this.events ];
return this;
},
remove: function() {
if (null != this.$) {
this.$.remove();
this.$ = null;
}
compo_dispose(this);
var components = this.parent && this.parent.components;
if (null != components) {
var i = components.indexOf(this);
if (i === -1) {
console.warn("Compo::remove - parent doesnt contains me", this);
return this;
}
components.splice(i, 1);
}
return this;
}
};
Compo.prototype = Proto;
return Compo;
}();
(function() {
if (null == domLib || null == domLib.fn) return;
domLib.fn.compo = function(selector) {
if (0 === this.length) return null;
var compo = Anchor.resolveCompo(this[0]);
if (null == selector) return compo;
return find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, "up"));
};
domLib.fn.model = function(selector) {
var compo = this.compo(selector);
if (null == compo) return null;
var model = compo.model;
while (null == model && compo.parent) {
compo = compo.parent;
model = compo.model;
}
return model;
};
})();
return {
jmask: jMask,
Compo: Compo
};
});
include.getResource("/.reference/libjs/compo/lib/compo.js", "js").readystatechanged(3);
(function() {
"use strict";
var w = window, r = "undefined" === typeof w.ruqq ? w.ruqq = {} : ruqq;
r.doNothing = function() {
return false;
};
(function(r) {
var div = document.createElement("div"), I = r.info || {};
r.info = I;
I.hasTouchSupport = function() {
if ("createTouch" in document) return true;
try {
return !!document.createEvent("TouchEvent").initTouchEvent;
} catch (error) {
return false;
}
}();
I.prefix = function() {
if ("transition" in div.style) return "";
if ("webkitTransition" in div.style) return "webkit";
if ("MozTransition" in div.style) return "Moz";
if ("OTransition" in div.style) return "O";
if ("msTransition" in div.style) return "ms";
return "";
}();
I.cssprefix = I.prefix ? "-" + I.prefix.toLowerCase() + "-" : "";
I.supportTransitions = I.prefix + "TransitionProperty" in div.style;
})(r);
return r;
})();
(function() {
"use strict";
var w = window, r = ruqq, prfx = r.info.cssprefix, vendorPrfx = r.info.prefix, getTransitionEndEvent = function() {
var el = document.createElement("fakeelement"), transitions = {
transition: "transitionend",
OTransition: "oTransitionEnd",
MSTransition: "msTransitionEnd",
MozTransition: "transitionend",
WebkitTransition: "webkitTransitionEnd"
}, event = null;
for (var t in transitions) if (void 0 !== el.style[t]) {
event = transitions[t];
break;
}
getTransitionEndEvent = function() {
return event;
};
el = null;
transitions = null;
return getTransitionEndEvent();
}, I = {
prop: prfx + "transition-property",
duration: prfx + "transition-duration",
timing: prfx + "transition-timing-function",
delay: prfx + "transition-delay"
};
var Animate = function(element, property, valueTo, duration, callback, valueFrom, timing) {
var data = "string" === typeof property ? {
property: property,
valueFrom: valueFrom,
valueTo: valueTo,
duration: duration,
timing: timing,
callback: callback
} : property, $this = $(element);
if (null == data.timing) data.timing = "linear";
if (null == data.duration) data.duration = 300;
if (null != data.valueFrom) {
var css = {};
css[data.property] = data.valueFrom;
css[prfx + "transition-property"] = "none";
css[prfx + "transition-duration"] = "0ms";
$this.css(css);
}
setTimeout(function() {
var css = {};
css[data.property] = data.valueTo;
css[prfx + "transition-property"] = data.property;
css[prfx + "transition-duration"] = data.duration + "ms";
css[prfx + "transition-timing-function"] = data.timing;
$this.css(css);
if (data.callback) {
var callback = function() {
$this.off(getTransitionEndEvent());
data.callback();
};
$this.on(getTransitionEndEvent(), callback);
}
}, 0);
return this;
};
var TransformModel = function() {
var regexp = /([\w]+)\([^\)]+\)/g;
function extract(str) {
var props = null;
regexp.lastIndex = 0;
while (1) {
var match = regexp.exec(str);
if (!match) return props;
(props || (props = {}))[match[1]] = match[0];
}
}
function stringify(props) {
var keys = Object.keys(props).sort().reverse();
for (var i = 0; i < keys.length; i++) keys[i] = props[keys[i]];
return keys.join(" ");
}
return Class({
Construct: function() {
this.transforms = {};
},
handle: function(data) {
var start = extract(data.from), end = extract(data.to), prop = null;
if (start) {
for (prop in this.transforms) if (false === prop in start) start[prop] = this.transforms[prop];
data.from = stringify(start);
for (prop in start) this.transforms[prop] = start[prop];
}
for (prop in this.transforms) if (false === prop in end) end[prop] = this.transforms[prop];
data.to = stringify(end);
for (prop in end) this.transforms[prop] = end[prop];
}
});
}();
var ModelData = function() {
var vendorProperties = {
transform: null
};
function parse(model) {
var arr = model.split(/ *\| */g), data = {}, length = arr.length;
data.prop = arr[0] in vendorProperties ? prfx + arr[0] : arr[0];
var vals = arr[1].split(/ *> */);
if (vals[0]) data.from = vals[0];
data.to = vals[vals.length - 1];
if (length > 2) {
var info = /(\d+m?s)?\s*([a-z]+[^\s]*)?\s*(\d+m?s)?/.exec(arr[2]);
if (null != info) {
data.duration = info[1] || "200ms";
data.timing = info[2] || "linear";
data.delay = info[3] || "0";
return data;
}
}
data.duration = "200ms";
data.timing = "linear";
data.delay = "0";
return data;
}
return Class({
Construct: function(data, parent) {
this.parent = parent;
this.transformModel = parent && parent.transformModel || new TransformModel();
var model = data.model || data;
if (model instanceof Array) {
this.model = [];
for (var i = 0, length = model.length; i < length; i++) this.model.push(new ModelData(model[i], this));
} else if (model instanceof Object) this.model = [ new ModelData(model, this) ]; else if ("string" === typeof model) {
this.model = parse(model);
if (~this.model.prop.indexOf("transform")) this.transformModel.handle(this.model);
}
if (null != data.next) this.next = new ModelData(data.next, this);
this.state = 0;
this.modelCount = this.model instanceof Array ? this.model.length : 1;
this.nextCount = 0;
if (null != this.next) this.nextCount = this.next instanceof Array ? this.next.length : 1;
},
reset: function() {
this.state = 0;
this.modelCount = this.model instanceof Array ? this.model.length : 1;
this.nextCount = 0;
if (null != this.next) this.nextCount = this.next instanceof Array ? this.next.length : 1;
var isarray = this.model instanceof Array, length = isarray ? this.model.length : 1, x = null;
for (var i = 0; isarray ? i < length : i < 1; i++) {
x = isarray ? this.model[i] : this.model;
x.reset && x.reset();
}
},
getNext: function() {
if (0 === this.state) {
this.state = 1;
return this;
}
if (1 == this.state && this.modelCount > 0) --this.modelCount;
if (1 == this.state && 0 === this.modelCount) {
this.state = 2;
if (this.next) return this.next;
}
if (2 == this.state && this.nextCount > 0) --this.nextCount;
if (2 == this.state && 0 === this.nextCount && this.parent) return this.parent.getNext && this.parent.getNext();
return null;
}
});
}();
var Stack = Class({
Construct: function() {
this.arr = [];
},
put: function(modelData) {
if (null == modelData) return false;
var next = modelData.getNext(), result = false, length, i;
if (null == next) return false;
if (next instanceof Array) {
for (i = 0, length = next.length; i < length; i++) if (true === this.put(next[i])) r = true;
return r;
}
if (0 === next.state) next.state = 1;
if (next.model instanceof Array) {
r = false;
for (i = 0, length = next.model.length; i < length; i++) if (true === this.put(next.model[i])) r = true;
return r;
}
this.resolve(next.model.prop);
this.arr.push(next);
return true;
},
resolve: function(prop) {
for (var i = 0, x, length = this.arr.length; i < length; i++) {
x = this.arr[i];
if (x.model.prop == prop) {
this.arr.splice(i, 1);
return this.put(x);
}
}
return false;
},
getCss: function(startCss, css) {
var i, length, key, x;
for (i = 0, length = this.arr.length; i < length; i++) {
x = this.arr[i];
if ("from" in x.model) startCss[x.model.prop] = x.model.from;
css[x.model.prop] = x.model.to;
for (key in I) (css[I[key]] || (css[I[key]] = [])).push(x.model[key]);
}
for (key in I) css[I[key]] = css[I[key]].join(",");
},
clear: function() {
this.arr = [];
}
});
var TransitionEvent = window.WebKitTransitionEvent || window.mozTransitionEvent || window.oTransitionEvent || window.TransitionEvent;
var Model = Class({
Construct: function(models) {
this.stack = new Stack();
this.model = new ModelData(models);
this.transitionEnd = this.transitionEnd.bind(this);
},
start: function(element, onComplete) {
this.onComplete = onComplete;
var startCss = {}, css = {};
this.model.reset();
this.stack.clear();
this.stack.put(this.model);
this.stack.getCss(startCss, css);
element.addEventListener(getTransitionEndEvent(), this.transitionEnd, false);
this.element = element;
this.apply(startCss, css);
},
transitionEnd: function(event) {
if (true === this.stack.resolve(event.propertyName)) {
var startCss = {}, css = {};
this.stack.getCss(startCss, css);
this.apply(startCss, css);
} else if (this.stack.arr.length < 1) {
this.element.removeEventListener(getTransitionEndEvent(), this.transitionEnd, false);
this.onComplete && this.onComplete();
}
},
apply: function(startCss, css) {
startCss[prfx + "transition"] = "none";
var style = this.element.style, element = this.element;
if (null != startCss) for (var key in startCss) style.setProperty(key, startCss[key], "");
setTimeout(function() {
var fire;
for (var key in css) {
style.setProperty(key, css[key], "");
if (key in ImmediatCss) (fire || (fire = [])).push(key);
}
if (null == fire || null == TransitionEvent) return;
var eventName = getTransitionEndEvent();
for (var i = 0; i < fire.length; i++) {
var event = new TransitionEvent(eventName, {
propertyName: fire[i],
bubbles: true,
cancelable: true
});
element.dispatchEvent(event);
}
}, 0);
}
});
var ImmediatCss = {
display: 1,
"font-family": 1,
visibility: 1
};
var Sprite = function() {
var keyframes = {}, vendor = null, initVendorStrings = function() {
vendor = {
keyframes: "@" + vendorPrfx + "keyframes",
AnimationIterationCount: vendorPrfx + "AnimationIterationCount",
AnimationDuration: vendorPrfx + "AnimationDuration",
AnimationTimingFunction: vendorPrfx + "AnimationTimingFunction",
AnimationFillMode: vendorPrfx + "AnimationFillMode",
AnimationName: vendorPrfx + "AnimationName"
};
};
return {
create: function(data) {
if (null == vendor) initVendorStrings();
if (null == keyframes[data.id]) {
var pos = document.styleSheets[0].insertRule(vendor.keyframes + " " + data.id + " {}", 0), keyFrameAnimation = document.styleSheets[0].cssRules[pos], frames = data.frames - (data.frameStart || 0), step = 0 | 100 / frames, property = data.property || "background-position-x";
for (var i = 0; i < frames; i++) {
var rule = step * (i + 1) + "% { " + property + ": " + -data.frameWidth * (i + (data.frameStart || 0)) + "px}";
keyFrameAnimation.insertRule(rule);
}
keyFrameAnimation.iterationCount = data.iterationCount;
keyFrameAnimation.frameToStop = data.frameToStop;
keyframes[data.id] = keyFrameAnimation;
}
},
start: function($element, animationId, msperframe) {
var style = $element.get(0).style;
style[vendor.AnimationName] = "none";
setTimeout(function() {
var keyframe = keyframes[animationId];
if ("forwards" == style[vendor.AnimationFillMode]) {
Sprite.stop($element);
return;
}
$element.on(vendor + "AnimationEnd", function() {
var css;
if (keyframe.frameToStop) {
var styles = keyframe.cssRules[keyframe.cssRules.length - 1].style;
css = {};
for (var i = 0; i < styles.length; i++) css[styles[i]] = styles[styles[i]];
}
Sprite.stop($element, css);
});
style[vendor.AnimationIterationCount] = keyframe.iterationCount || 1;
style[vendor.AnimationDuration] = keyframe.cssRules.length * msperframe + "ms";
style[vendor.AnimationTimingFunction] = "step-start";
style[vendor.AnimationFillMode] = keyframe.frameToStop ? "forwards" : "none";
style[vendor.AnimationName] = animationId;
}, 0);
},
stop: function($element, css) {
var style = $element.get(0).style;
style[vendor.AnimationFillMode] = "none";
style[vendor.AnimationName] = "";
if (null != css) $element.css(css);
}
};
}();
r.animate = Animate;
r.animate.Model = Model;
r.animate.sprite = Sprite;
})();
include.setCurrent({
id: "/.reference/libjs/mask/lib/formatter.js",
namespace: "lib.mask/formatter",
url: "/.reference/libjs/mask/lib/formatter.js"
});
(function(root, factory) {
"use strict";
function construct(mask) {
if (null == mask) throw "MaskJS Core is not Loaded";
return factory(mask);
}
if ("object" === typeof exports) module.exports = construct(require("maskjs")); else if ("function" === typeof define && define.amd) define([ "mask" ], construct); else construct(root.mask);
})(this, function(mask) {
var stringify = function() {
var _minimizeAttributes, _indent, Dom = mask.Dom;
function doindent(count) {
var output = "";
while (count--) output += " ";
return output;
}
function run(node, indent, output) {
var outer, i;
if (null == indent) indent = 0;
if (null == output) {
outer = true;
output = [];
}
var index = output.length;
if (node.type === Dom.FRAGMENT) node = node.nodes;
if (node instanceof Array) for (i = 0; i < node.length; i++) processNode(node[i], indent, output); else processNode(node, indent, output);
var spaces = doindent(indent);
for (i = index; i < output.length; i++) output[i] = spaces + output[i];
if (outer) return output.join(0 === _indent ? "" : "\n");
}
function processNode(node, currentIndent, output) {
if ("string" === typeof node.content) {
output.push(wrapString(node.content));
return;
}
if ("function" === typeof node.content) {
output.push(wrapString(node.content()));
return;
}
if (isEmpty(node)) {
output.push(processNodeHead(node) + ";");
return;
}
if (isSingle(node)) {
output.push(processNodeHead(node) + " > ");
run(getSingle(node), _indent, output);
return;
}
output.push(processNodeHead(node) + "{");
run(node.nodes, _indent, output);
output.push("}");
return;
}
function processNodeHead(node) {
var tagName = node.tagName, _id = node.attr.id || "", _class = node.attr["class"] || "";
if ("function" === typeof _id) _id = _id();
if ("function" === typeof _class) _class = _class();
if (_id) if (_id.indexOf(" ") !== -1) _id = ""; else _id = "#" + _id;
if (_class) _class = "." + _class.split(" ").join(".");
var attr = "";
for (var key in node.attr) {
if ("id" === key || "class" === key) continue;
var value = node.attr[key];
if ("function" === typeof value) value = value();
if (false === _minimizeAttributes || /\s/.test(value)) value = wrapString(value);
attr += " " + key + "=" + value;
}
if ("div" === tagName && (_id || _class)) tagName = "";
return tagName + _id + _class + attr;
}
function isEmpty(node) {
return null == node.nodes || node.nodes instanceof Array && 0 === node.nodes.length;
}
function isSingle(node) {
return node.nodes && (false === node.nodes instanceof Array || 1 === node.nodes.length);
}
function getSingle(node) {
if (node.nodes instanceof Array) return node.nodes[0];
return node.nodes;
}
function wrapString(str) {
if (str.indexOf('"') === -1) return '"' + str.trim() + '"';
if (str.indexOf("'") === -1) return "'" + str.trim() + "'";
return '"' + str.replace(/"/g, '\\"').trim() + '"';
}
return function(input, settings) {
if ("string" === typeof input) input = mask.parse(input);
if ("number" === typeof settings) {
_indent = settings;
_minimizeAttributes = 0 === _indent;
} else {
_indent = settings && settings.indent || 4;
_minimizeAttributes = 0 === _indent || settings && settings.minimizeAttributes;
}
return run(input);
};
}();
var HTMLtoMask = function() {
var startTag = /^<([\w:]+)((?:\s+[\w\-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/, endTag = /^<\/([\w:]+)[^>]*>/, attr = /([\w\-]+)(?:\s*=\s*(?:(?:"((?:\\"|[^"])*)")|(?:'((?:\\'|[^'])*)')|([^>\s]+)))?/g;
var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");
var block = makeMap("a, address,applet,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");
var inline = makeMap("");
var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var special = makeMap("script,style");
var htmlParser = function(html, handler) {
var index, chars, match, text, stack = [], last = html;
stack.last = function() {
return this[this.length - 1];
};
while (html) {
chars = true;
if (!special[stack.last()]) {
if (0 === html.indexOf("<!--")) {
index = html.indexOf("-->");
if (index >= 0) {
if (handler.comment) handler.comment(html.substring(4, index));
html = html.substring(index + 3);
chars = false;
}
} else if (0 === html.indexOf("</")) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
}
} else if (0 === html.indexOf("<")) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf("<");
text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(text);
}
} else {
match = new RegExp("</\\s*" + stack.last() + "[^>]*>").exec(html);
if (!match) {
handler.chars(html);
html = "";
break;
}
text = html.substring(0, match.index);
if (text) handler.chars(text);
html = html.substring(match.index + match[0].length);
handler.end(stack.pop());
}
if (html === last) throw "Parse Error: " + html;
last = html;
}
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
if (block[tagName]) while (stack.last() && inline[stack.last()]) parseEndTag("", stack.last());
if (closeSelf[tagName] && stack.last() === tagName) parseEndTag("", tagName);
unary = empty[tagName] || !!unary;
if (!unary) stack.push(tagName);
if (handler.start) {
var attrs = [];
rest.replace(attr, function(match, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : "";
attrs.push({
name: name,
value: value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\"')
});
});
if (handler.start) handler.start(tagName, attrs, unary);
}
}
function parseEndTag(tag, tagName) {
var pos;
if (!tagName) pos = 0; else {
pos = stack.length - 1;
while (pos >= 0 && stack[pos] !== tagName) pos--;
}
if (pos >= 0) {
for (var i = stack.length - 1; i >= pos; i--) if (handler.end) handler.end(stack[i]);
stack.length = pos;
}
}
};
function makeMap(str) {
var obj = {}, items = str.split(",");
for (var i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
return function HTMLtoMask(html) {
var results = "";
htmlParser(html, {
start: function(tag, attrs, unary) {
results += tag;
for (var i = 0; i < attrs.length; i++) results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
results += unary ? ";" : "{";
},
end: function() {
results += "}";
},
chars: function(text) {
results += '"' + text.replace(/"/g, '\\"') + '"';
},
comment: function() {}
});
return stringify(results.replace(/"[\s]+"/g, ""));
};
}();
return {
beautify: mask.stringify = stringify,
stringify: mask.stringify = stringify,
HtmlToMask: mask.HtmlToMask = HTMLtoMask
};
});
include.getResource("/.reference/libjs/mask/lib/formatter.js", "js").readystatechanged(3);
include.setCurrent({
id: "/script/preview/preview.js",
namespace: "component.preview",
url: "/script/preview/preview.js"
});
(function(resp) {
var _window, _document, _body, _iframe, _style;
var Window = function() {
return {
init: function(iframe) {
if (null != {}.__proto__ && 0) {
_window = iframe.contentWindow;
_window.Function.prototype.apply.prototype = Function.prototype.apply.bind(Function);
_window.Function.prototype.call = Function.prototype.call.bind(Function);
Object.extend(_window, {
Class: Class,
Compo: Compo,
mask: mask,
include: include.instance(),
ruqq: ruqq,
Object: Object
});
} else _window = window;
_document = iframe.contentDocument || iframe.contentWindow.contentDocument;
_document.open();
_document.write("<html><head><style></style><style>body{font-family:sans-serif;}</style></head><body><pre><code></code></pre></body></html>");
_document.close();
_style = _document.getElementsByTagName("style")[0];
},
eval: function(code) {
_window.eval(code);
},
reload: function() {
if (_window == window) return;
_window.location = "about:blank";
},
setStyle: function(preview, style) {
if (preview._style == style && _window == window) return;
_style.innerHTML = preview._style = style;
},
setCode: function(preview, code) {
if (preview._code == code && _window == window) return;
if (_window.dispose instanceof Function) try {
_window.dispose();
} catch (error) {
console.error("dispose:", error.toString());
}
_window.eval(code);
preview._code = code;
},
setTemplate: function(preview, template) {
if (preview._compo) preview._compo.remove();
preview._template = template;
preview._compo = new Compo(template).render(_window.model || {}).insert(_document.body);
},
setHTML: function(preview, template) {
var div = document.createElement("div");
div.appendChild(mask.render(template, _window.model));
_document.body.innerHTML = "<pre><code></code></pre>";
var $code = _document.body.getElementsByTagName("code")[0], html = style_html(div.innerHTML);
$code.textContent = html;
}
};
}();
mask.registerHandler("preview", Compo({
constructor: function() {
this.compos = {
$notification: "$: .notification"
};
},
onRenderStart: function(model, cntx, container) {
this.tagName = "div";
this.nodes = mask.compile('.notification; iframe src="about:blank";');
Compo.shots.on(this, "DOMInsert", this.DOMInsert);
},
DOMInsert: function() {
Window.init(_iframe = this.$.find("iframe")[0]);
this.element = _document.getElementsByTagName("code")[0];
},
prepair: function(code, style, template, callback) {
if (_document) {
if (code || template) _document.body.innerHTML = "";
if (_window == window) {
callback && callback();
return;
}
}
Window.reload();
setTimeout(function() {
Window.init(_iframe);
callback && callback();
});
},
resolveHTML: function() {},
update: function(html) {
var error;
this.element.innerText = mask.HtmlToMask(html);
this.notify(error);
},
notify: function(error) {
error && console.error(error.toString());
var klass = error ? "red" : "green", $notification = this.compos.$notification;
clearTimeout(this.timeout);
$notification.removeClass("red green").addClass(klass);
this.timeout = setTimeout(function() {
$notification.removeClass(klass);
}, 1e3);
}
}));
})();
include.getResource("/script/preview/preview.js", "js").readystatechanged(3);
(function(resp) {
function activate($this, name) {
$this.compos.$panels.removeClass("active").filter('[name="' + name + '"]').addClass("active");
$this.compos.$buttons.removeClass("active").filter('[name="' + name + '"]').addClass("active");
var editor = editors[name];
editor.renderer.updateFull();
editor.focus();
}
mask.registerHandler("tabs", Compo({
constructor: function() {
this.attr = {
"class": "tabs"
};
this.compos = {
$panels: "$: .panels > div",
$buttons: "$: .header > button"
};
Class.bind(this, "next");
this.tagName = "div";
},
events: {
"click: .header > button:not(.active)": function(event) {
activate(this, $(event.currentTarget).attr("name"));
}
},
next: function() {
var $next = this.compos.$buttons.filter(".active").next("button");
if (0 == $next.length) $next = this.compos.$buttons.first();
activate(this, $next.attr("name"));
},
current: function() {
return this.compos.$buttons.filter(".active").attr("name");
}
}));
})();
(function(resp) {
var itemTemplate = '% each="." > .-ddmenu.item data-item="~[id]" > "~[title]"';
mask.registerHandler("dropdownMenu", Compo({
constructor: function() {
this.attr = {
"class": "dropdownMenu"
};
this.compos = {
button: "$: .caption"
};
},
events: {
"click: .caption": function() {
this.$.addClass("visible");
this.compos.button.addClass("active");
$(document).on("mousedown", function(e) {
if ($(e.target).closest(".dropdownMenu").length) return;
this.hide();
}.bind(this));
},
"click: .item": function(e) {
this.hide();
this.$.trigger("selected", [ $(e.currentTarget).data("id") ]);
}
},
hide: function() {
this.$.removeClass("visible");
this.compos.button.removeClass("active");
$(document).off("mousedown");
},
onRenderStart: function(model, cntx, container) {
this.tagName = "div";
},
add: function(items) {
var dom = mask.render(itemTemplate, items, null, null, this);
this.$.find(".items").append(dom);
}
}));
})();
include.setCurrent({
id: "/script/shortend-dialog/shortend-dialog.js",
namespace: "component.shortend-dialog",
url: "/script/shortend-dialog/shortend-dialog.js"
});
include.load("shortend-dialog.mask::Template").done(function(resp) {
var animations = {};
Object.lazyProperty(animations, "model", function() {
var Model = ruqq.animate.Model;
return {
show: {
overlay: new Model({
model: [ "display | block", "opacity | 0 > 1 | 200ms" ]
}),
panel: new Model({
model: [ "transform | translate(0px,130%) > translate(0px, 0px) | 300ms ease-in 150ms", "opacity | 0 > 1 | 300ms linear 200 ms" ]
})
},
hide: {
panel: new Model({
model: [ "transform | translate(0px,0px) > translate3d(0px, 120%) | 300ms ease-in", "opacity | 1 > 0 | 300ms ease-in" ]
}),
overlay: new Model({
model: "opacity | 1 > 0 | 400ms linear 450ms",
next: "display | > none"
})
}
};
});
Object.lazyProperty(include.promise("compo"), "shortendDialog", function() {
return Compo.initialize(Dialog, null, null, document.body);
});
var cache = {};
var Dialog = Compo({
compos: {
panel: [ "$: .modalOverlay", {
"click:": function(e) {
var _class = $(e.target).attr("class");
if (!_class) return;
if (_class.indexOf("modalOverlay") > -1 || _class.indexOf("cell") > -1) this.hide();
}
} ],
container: "$: .shortend-container"
},
attr: {
template: resp.load.Template
},
show: function(date) {
animations.model.show.overlay.start(this.$.filter(".modalOverlay").get(0));
animations.model.show.panel.start(this.$.find(".shortend-container").get(0));
return this;
},
hide: function() {
animations.model.hide.panel.start(this.$.find(".shortend-container").get(0));
animations.model.hide.overlay.start(this.$.filter(".modalOverlay").get(0));
},
state: function(state) {
this.compos.container.children(".active").removeClass("active");
this.compos.container.children("." + state).addClass("active");
},
process: function(url) {
var cached = cache[url];
if (cached) {
this.$.find("input").val(cached);
this.state("result");
return;
}
this.state("progress");
var that = this;
setTimeout(function() {
UrlCode.getShortend(url, function(response) {
if (!response) {
alert("Sorry, could not resolve the shortend url");
that.hide();
return;
}
cache[url] = response;
that.process(url);
});
}, 200);
return this;
}
});
});
include.getResource("/script/shortend-dialog/shortend-dialog.js", "js").readystatechanged(3);
(function(e) {
function a(e, t) {
var n = e.length;
while (n--) if (e[n] === t) return n;
return -1;
}
function f(e, t) {
var i, o, f, l, c;
i = e.keyCode, a(u, i) == -1 && u.push(i);
if (93 == i || 224 == i) i = 91;
if (i in r) {
r[i] = !0;
for (f in s) s[f] == i && (h[f] = !0);
return;
}
if (!h.filter.call(this, e)) return;
if (!(i in n)) return;
for (l = 0; l < n[i].length; l++) {
o = n[i][l];
if (o.scope == t || "all" == o.scope) {
c = o.mods.length > 0;
for (f in r) if (!r[f] && a(o.mods, +f) > -1 || r[f] && a(o.mods, +f) == -1) c = !1;
(0 == o.mods.length && !r[16] && !r[18] && !r[17] && !r[91] || c) && o.method(e, o) === !1 && (e.preventDefault ? e.preventDefault() : e.returnValue = !1,
e.stopPropagation && e.stopPropagation(), e.cancelBubble && (e.cancelBubble = !0));
}
}
}
function l(e) {
var t = e.keyCode, n, i = a(u, t);
i >= 0 && u.splice(i, 1);
if (93 == t || 224 == t) t = 91;
if (t in r) {
r[t] = !1;
for (n in s) s[n] == t && (h[n] = !1);
}
}
function c() {
for (t in r) r[t] = !1;
for (t in s) h[t] = !1;
}
function h(e, t, r) {
var i, u, a, f;
void 0 === r && (r = t, t = "all"), e = e.replace(/\s/g, ""), i = e.split(","),
"" == i[i.length - 1] && (i[i.length - 2] += ",");
for (a = 0; a < i.length; a++) {
u = [], e = i[a].split("+");
if (e.length > 1) {
u = e.slice(0, e.length - 1);
for (f = 0; f < u.length; f++) u[f] = s[u[f]];
e = [ e[e.length - 1] ];
}
e = e[0], e = o[e] || e.toUpperCase().charCodeAt(0), e in n || (n[e] = []), n[e].push({
shortcut: i[a],
scope: t,
method: r,
key: i[a],
mods: u
});
}
}
function p(e) {
if ("string" == typeof e) {
if (1 != e.length) return !1;
e = e.toUpperCase().charCodeAt(0);
}
return a(u, e) != -1;
}
function d() {
return u;
}
function v(e) {
var t = (e.target || e.srcElement).tagName;
return "INPUT" != t && "SELECT" != t && "TEXTAREA" != t;
}
function m(e) {
i = e || "all";
}
function g() {
return i || "all";
}
function y(e) {
var t, r, i;
for (t in n) {
r = n[t];
for (i = 0; i < r.length; ) r[i].scope === e ? r.splice(i, 1) : i++;
}
}
function b(e, t, n) {
e.addEventListener ? e.addEventListener(t, n, !1) : e.attachEvent && e.attachEvent("on" + t, function() {
n(window.event);
});
}
function E() {
var t = e.key;
return e.key = w, t;
}
var t, n = {}, r = {
16: !1,
18: !1,
17: !1,
91: !1
}, i = "all", s = {
"⇧": 16,
shift: 16,
"⌥": 18,
alt: 18,
option: 18,
"⌃": 17,
ctrl: 17,
control: 17,
"⌘": 91,
command: 91
}, o = {
backspace: 8,
tab: 9,
clear: 12,
enter: 13,
"return": 13,
esc: 27,
escape: 27,
space: 32,
left: 37,
up: 38,
right: 39,
down: 40,
del: 46,
"delete": 46,
home: 36,
end: 35,
pageup: 33,
pagedown: 34,
",": 188,
".": 190,
"/": 191,
"`": 192,
"-": 189,
"=": 187,
";": 186,
"'": 222,
"[": 219,
"]": 221,
"\\": 220
}, u = [];
for (t = 1; t < 20; t++) s["f" + t] = 111 + t;
for (t in s) h[t] = !1;
b(document, "keydown", function(e) {
f(e, i);
}), b(document, "keyup", l), b(window, "focus", c);
var w = e.key;
e.key = h, e.key.setScope = m, e.key.getScope = g, e.key.deleteScope = y, e.key.filter = v,
e.key.isPressed = p, e.key.getPressedKeyCodes = d, e.key.noConflict = E, "undefined" != typeof module && (module.exports = key);
})(this);
(function() {
window.UrlCode = new (Class({
parse: function() {
var hash = window.location.hash.replace(/^[#\/]+/, "");
hash = decodeURIComponent(hash);
if (0 !== hash.indexOf("html:")) return "";
return {
html: hash.substring("html:".length)
};
},
set: function(html) {
var line = "html:" + html;
window.location.hash = encodeURIComponent(line);
},
getShortend: function(url, callback) {
$.getJSON("http://api.bitly.com/v3/shorten?callback=?", {
format: "json",
longUrl: url,
apiKey: "R_76ebf1167111bc97cdd1a4486fef729c",
login: "tenbits"
}, function(response) {
callback && callback(response.data && response.data.url);
});
}
}))();
})();
include.setCurrent({
id: "/script/main.js",
namespace: "",
url: "/script/main.js"
});
include.routes({
component: "/script/{0}/{1}.js",
vendor: "/.reference/libjs/vendor-lib/{0}/{1}.js",
script: "/script/{0}.js"
}).instance().js({
component: [ "preview", "shortend-dialog" ]
}).ready(function(resp) {
var App = Compo({
attr: {
template: document.getElementById("layout").innerHTML
},
compos: {
preview: "compo: preview",
tabs: "compo: tabs",
btnSetLink: "$: #setLink",
btnShortend: "$: #getShortend"
}
});
window.app = Compo.initialize(App, {
presets: resp.presets
}, null, document.body);
window.editors = {};
function createEditor(type, highlight) {
editors[type] = ace.edit("editor-" + type);
editors[type].setTheme("ace/theme/monokai");
editors[type].getSession().setMode("ace/mode/" + (highlight || type));
}
createEditor("html");
(function() {
var editors = window.editors, preview = app.compos.preview, deferredTimer, types;
function getSource(type) {
return editors[type].getValue();
}
function deferUpdate(type) {
if (types && !types.push) debugger;
types = types ? types.concat([ type ]) : [ type ];
cancelAnimationFrame(deferredTimer);
deferredTimer = requestAnimationFrame(update);
}
function update() {
if (null == types) return;
var source = {};
for (var i = 0, x, length = types.length; i < length; i++) {
x = types[i];
source[x] = getSource(x);
}
types = null;
preview.update(source.html);
}
function setValues(source) {
for (var key in editors) {
if (!source[key]) continue;
editors[key].setValue(source[key], 1);
}
editors[app.compos.tabs.current()].focus();
}
var command = {
name: "nextTab",
bindKey: {
mac: "Shift-Tab",
win: "Shift-Tab"
},
exec: app.compos.tabs.next
};
for (var x in editors) {
editors[x].on("change", deferUpdate.bind(this, x));
editors[x].commands.addCommand(command);
editors[x].setHighlightActiveLine(false);
editors[x].setShowPrintMargin(false);
}
key("shift+tab", function(e) {
app.compos.tabs.next();
e.preventDefault();
return false;
});
var code = UrlCode.parse();
if (code) setValues(code);
app.compos.btnSetLink.on("click", function() {
UrlCode.set(getSource("html"));
});
app.compos.btnShortend.on("click", function() {
UrlCode.set(getSource("html"));
window.compo.shortendDialog.show().process(window.location.toString());
});
})();
window.app = app;
});
include.getResource("/script/main.js", "js").readystatechanged(3); | mit |
nowireless/MiscMath | src/main/java/org/nowireless/miscmath/RunningVector.java | 785 | package org.nowireless.miscmath;
public class RunningVector implements Vector {
private double x;
private double y;
public RunningVector(double x, double y) {
this.x = x;
this.y = y;
}
public RunningVector() {
this(0,0);
}
@Override
public double getX() {
return this.x;
}
@Override
public double getY() {
return this.y;
}
@Override
public double getMagnitude() {
return Math.sqrt((x*x) + (y*y));
}
@Override
public double getAngle() {
return Math.atan2(y, x);
}
@Override
public void reset() {
this.x = 0;
this.y = 0;
}
@Override
public void add(Vector vector) {
this.x += vector.getX();
this.y += vector.getY();
}
@Override
public void subtract(Vector vector) {
this.x -= vector.getX();
this.y -= vector.getY();
}
}
| mit |
ua-ql/node-opcua | test/misc/test_utils_normalize_require_file.js | 316 | import should from "should";
import {normalizeRequireFile} from "lib/misc/utils";
describe("normalizeRequireFile", function () {
it("should normalizeRequireFile", function () {
normalizeRequireFile("/home/bob/folder1/", "/home/bob/folder1/folder2/toto.js").should.eql("./folder2/toto");
});
});
| mit |
lannocctech/iovar | usr/include/iovar/frame.js | 5118 | /*
* Copyright (C) 2016 Virgo Venture, Inc.
* @%@~LICENSE~@%@
*
* depends on: common.js, ajax.js
*/
function turnme (node1, node2, node3)
{
node1.className += ' rotated';
node2.className += ' rotated';
loadFrame (node3, 'http://localhost:8080/app/work/open?=9', true);
}
function turnem (node1, node2, node3)
{
node1.className = node1.className.replace (/(?:^|\s)rotated(?!\S)/g, '');
node2.className = node2.className.replace (/(?:^|\s)rotated(?!\S)/g, '');
}
var _frames = new Map (); // keyed by frame node
/*
* arguments:
* frame - node to load content into
* url - url to load
* replace - if true, replace's any existing contents in target node
* callback - optional callback function after successful frame load
*/
function loadFrame (frame, url, replace, callback)
{
frame.className = frame.className.replace (/(?:^|\s)ready(?!\S)/g, '');
var ajax = ajaxLoad (url, _frameReady (frame, replace, callback));
if (ajax)
{
_frames.set (frame, ajax);
}
}
/*
* returns reference to call-back function for ajax state changes
*/
function _frameReady (frame, replace, callback)
{
return function ()
{
//alert ('yo: ' + frame);
var ajax = _frames.get (frame);
if (! ajax)
{
return;
}
if (ajax.readyState != 4)
{
return;
}
if (replace)
{
while (frame.firstChild)
{
frame.removeChild (frame.firstChild);
}
}
frame.className += ' ready';
if (ajax.status == 0)
{
// aborted?
return;
}
else if (ajax.status != 200)
{
frame.innerHTML = 'frame: unexpected status: '+ajax.status;
return;
}
var xml = ajax.responseXML;
if (xml)
{
var doc = xml.documentElement;
if ('HTML' === doc.nodeName.toUpperCase ())
{
var body = xml.getElementById ('body');
if (! body)
{
body = doc.getElementsByTagName ('body')[0];
}
if (body)
{
for (var node = body.firstChild; node; node = node.nextSibling)
{
frame.appendChild (document.importNode (node, true));
}
}
else
{
frame.innerHTML = 'frame: html response with no body';
return;
}
}
else
{
frame.appendChild (document.importNode (doc, true));
}
}
else
{
var data = document.createElement ('div');
if (ajax.responseText)
{
/* FIXME: very hacky */
if (ajax.responseText.lastIndexOf ('<html', 0) === 0 || ajax.responseText.lastIndexOf ('\n<html', 0) === 0)
{
/*
var resp = document.createElement ('div');
resp.innerHTML = ajax.responseText;
var body = resp.getElementsByTagName ('body');
if (body.length === 1)
{
for (var node = body[0].firstChild; node; node = node.nextSibling)
{
alert ('append child: '+node);
data.appendChild (node);
}
}
else
{
data.innerHTML = '(html response with inappropriate body count: '+body.length+')';
}
resp = null;
*/
var idx = ajax.responseText.indexOf ('<body', 6);
if (idx>=0) idx = ajax.responseText.indexOf ('>', idx+5);
if (idx >= 0)
{
var eidx = ajax.responseText.indexOf ('</body>', idx+1);
if (eidx >= 0)
{
data.innerHTML = ajax.responseText.substring (idx+1, eidx);
}
else
{
data.innerHTML = ajax.responseText.substring (idx+1);
}
}
else
{
data.innerHTML = '(html response without body)';
return;
}
}
else
{
data.innerHTML = htmlSafe (ajax.responseText);
}
}
else
{
data.innerHTML = '(empty response)';
return;
}
frame.appendChild (data);
}
if (callback)
{
callback();
}
};
}
| mit |
netcredit/NetCreditHub | src/NetCreditHub.Web.Common/Web/Auditing/AuditingInterceptorRegistrar.cs | 1302 | namespace NetCreditHub.Web.Auditing
{
using System;
using System.Linq;
using Castle.Core;
using Dependency;
internal static class AuditingInterceptorRegistrar
{
public static void Initialize(IIocManager iocManager)
{
var auditingConfiguration = iocManager.Resolve<IAuditingConfiguration>();
iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
{
if (ShouldIntercept(auditingConfiguration, handler.ComponentModel.Implementation))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
}
};
}
private static bool ShouldIntercept(IAuditingConfiguration auditingConfiguration, Type type)
{
//if (auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
//{
// return true;
//}
if (type.IsDefined(typeof(AuditedAttribute), true))
{
return true;
}
if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true)))
{
return true;
}
return false;
}
}
} | mit |
Ptimagos/swarmui | app/components/hosts/hostsController.js | 3313 | angular.module('hosts', [])
.controller('HostsController', ['$scope', '$routeParams', 'Swarm', 'Container',
'ConsulPrimarySwarm', 'SettingsConsul', 'Settings', 'Messages', 'ViewSpinner',
function ($scope, $routeParams, Swarm, Container, ConsulPrimarySwarm, SettingsConsul, Settings, Messages, ViewSpinner) {
$scope.swarms = [];
$scope.toggle = false;
$scope.dashboard = '1';
$scope.containers = [];
$scope.predicate = 'nodename';
$scope.reverse = false;
$scope.order = function(predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
$scope.setAlarm = function (node,entry,warning) {
var setAlarmTo = "";
if ( warning === "1" ){
entry.warning = "0";
setAlarmTo = "to activate";
} else {
entry.warning = "1";
setAlarmTo = "to desactivate";
}
ConsulNodes.setalarm(entry, function (d) {
Messages.send("Udpdate alarm for " + node, setAlarmTo);
}, function (e) {
Messages.error("Update alarm failed for " + node, setAlarmTo);
});
};
var containersStatus = function (url,node) {
Container.query({all: 1, node: url}, function (d) {
for (var n = 0; n < node.length; n++) {
var running = 0;
var stopped = 0;
var created = 0;
for (var i = 0; i < d.length; i++) {
var item = d[i];
var splitedNames = item.Names[0].split("/");
if (node[n].nodename === splitedNames[1]) {
if (item.Status === '') {
created++;
} else if (item.Status.indexOf('Exit') !== -1 && item.Status !== 'Exit 0') {
stopped++;
} else {
running++;
}
}
}
if (stopped === 0 ){
stopped = "";
}
if (created === 0 ){
created = "";
}
$scope.swarms[n].running = running;
$scope.swarms[n].stopped = stopped;
$scope.swarms[n].created = created;
}
});
};
var update = function (data) {
ViewSpinner.spin();
ConsulPrimarySwarm.get({}, function (d){
var url = atob(d[0].Value);
Swarm.info({node: url}, function (d) {
var k = 5;
var l = 9;
var j = 0;
var values = [];
for (var i = 4; i < d['SystemStatus'].length;i += 8){
var version = d['SystemStatus'][l][1].split(" ");
var nodename = d['SystemStatus'][i][0].split(" ");
var value = '{"nodename":"' + nodename[1] + '","url":"' + d['SystemStatus'][i][1] + '","health":"' + d['SystemStatus'][k][1] + '","version":"' + version[3] + '"}';
k += 8;
l += 8;
values[j] = JSON.parse(value);
j++;
}
$scope.swarms = values.map(function (item) {
return new SwarmViewModel(item);
});
containersStatus(url, $scope.swarms);
ViewSpinner.stop();
});
});
};
$scope.toggleSelectAll = function () {
angular.forEach($scope.swarms, function (i) {
i.Checked = $scope.toggle;
});
};
update();
}]);
| mit |
ibestvina/multithread-centiscape | CentiScaPe2.1/src/main/java/org/cytoscape/centiscape/internal/Betweenness/FinalResultBetweenness.java | 1759 | /*
* FinalResultBetweenness.java
*
* Created on 15 marzo 2007, 18.06
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
/**
*
* @author scardoni
*/
package org.cytoscape.centiscape.internal.Betweenness;
import org.cytoscape.model.CyNode;
public class FinalResultBetweenness implements Comparable {
private long nodesuid;;
private double Betweenness;
private CyNode node;
/**
* Creates a new instance of FinalResultBetweenness
*/
public FinalResultBetweenness() {
}
public FinalResultBetweenness(CyNode node, double btw) {
this.nodesuid = node.getSUID();
this.node = node;
this.Betweenness = btw;
}
public void update(double btwvalue) {
Betweenness = Betweenness + btwvalue;
}
public boolean Nameequals(long secondnodesuid) {
System.out.println("node name= " + nodesuid + " secondo node = " + secondnodesuid);
return this.nodesuid == secondnodesuid;
}
public String toString(){
String result= "node name= " + nodesuid + " betweenness =" + Betweenness;
return result;
}
/*public String getName() {
return nodename;
}*/
public long getSUID() {
return nodesuid;
}
public double getBetweenness() {
return Betweenness;
}
public CyNode getNode() {
return node;
}
public int compareTo(Object c) {
FinalResultBetweenness c2 = (FinalResultBetweenness)c;
if (this.getBetweenness() > c2.getBetweenness())
return -1;
else if (this.getBetweenness() < c2.getBetweenness())
return 1;
else return 0;
}
}
| mit |
murex/murex-coding-dojo | Beirut/2016/2016-04-27-apu-codingame/src/main/java/APUPlayer.java | 1939 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Don't let the machines win. You are humanity's last hope...
**/
class APUPlayer {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int width = in.nextInt(); // the number of cells on the X axis
int height = in.nextInt(); // the number of cells on the Y axis
in.nextLine();
List<List<Boolean>> matrix = new ArrayList();
for (int i = 0; i < height; i++) {
String line = in.nextLine(); // width characters, each either 0 or .
List<Boolean> row = new ArrayList<Boolean>();
for (int i1 = 0; i1 < line.length(); i1++) {
row.add(line.charAt(i1) == '0');
// True is for a power node
}
matrix.add(row);
}
for (int rowIndex = 0; rowIndex < matrix.size(); rowIndex++) {
for (int columnIndex = 0; columnIndex < matrix.get(rowIndex).size(); columnIndex++) {
if (matrix.get(rowIndex).get(columnIndex)) {
String neighbours = columnIndex + " " + rowIndex;
neighbours += (horizontalNeighbours(matrix.get(rowIndex), columnIndex, rowIndex));
neighbours += (verticalNeighbours(matrix, rowIndex, columnIndex));
System.out.println(neighbours);
}
}
}
}
static String verticalNeighbours(List<List<Boolean>> matrix, int row, int columnIndex) {
for (int i = row + 1; i < matrix.size(); ++i) {
if (matrix.get(i).get(columnIndex)) {
return " " + columnIndex + " " + i;
}
}
return " -1 -1";
}
static String horizontalNeighbours(List<Boolean> row, int columnIndex, int rowIndex) {
for (int i = columnIndex + 1; i < row.size(); ++i) {
if (row.get(i)) {
return " " + i + " " + rowIndex;
}
}
return " -1 -1";
}
}
| mit |
tlainevool/eatspection | geo/geoconfig.py | 31 | google_key_file='~/.google_key' | mit |
stanchev/Telerik-Academy | OOP/Defining Classes Part I/MobilePhone/GSMTest.cs | 1041 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MobilePhone
{
class GSMTest
{
private static List<GSM> CreateHandys()
{
List<GSM> handys = new List<GSM>();
handys.Add(new GSM("One mini","HTC",400,"Ivan",new Battery(BatteryType.LiPol,null,400,60),new Display(4.3,"16M")));
handys.Add(new GSM("Lumia 720", "Nokia", 300, "Stamat", new Battery(BatteryType.LiPol, null, 350, 50), new Display(4.2, "16M")));
handys.Add(new GSM("A820", "Lenovo", 150, "Jivko", new Battery(BatteryType.LiPol, null, 500, 100)));
return handys;
}
public static void PrintHandysInformation()
{
List<GSM> handys = CreateHandys();
foreach (GSM item in handys)
{
Console.WriteLine(item);
}
}
public static void PrintIPhone4S()
{
Console.WriteLine(GSM.IPhone4S);
}
}
}
| mit |
kompakt/b3d | lib/Details/Populator/Endpoint/Populator.php | 1171 | <?php
/*
* This file is part of the kompakt/b3d package.
*
* (c) Christian Hoegl <chrigu@sirprize.me>
*
*/
namespace Kompakt\B3d\Details\Populator\Endpoint;
use Kompakt\B3d\Details\Graph\PopulatorInterface;
use Kompakt\B3d\Details\Populator\DataMapperInterface;
use Kompakt\B3d\Details\Populator\Endpoint\EndpointInterface;
use Kompakt\B3d\Details\Populator\RepositoryInterface;
use Kompakt\B3d\Util\File\Reader;
class Populator implements PopulatorInterface
{
protected $dataMapper = null;
protected $repository = null;
protected $endpoint = null;
public function __construct(
DataMapperInterface $dataMapper,
RepositoryInterface $repository,
EndpointInterface $endpoint
)
{
$this->dataMapper = $dataMapper;
$this->repository = $repository;
$this->endpoint = $endpoint;
}
/**
* @see PopulatorInterface::populate()
*/
public function populate()
{
foreach ($this->endpoint->fetchAll() as $item)
{
$entity = $this->dataMapper->map($item);
$this->repository->add($entity);
}
return $this->repository;
}
} | mit |
skukit/mobac | src/Mobac/Entity/Property/DefaultValue.php | 1105 | <?php
namespace Mobac\Entity\Property;
use Mobac\Entity\AbstractEntity;
use Mobac\Transformer\Property\DefaultValueTransformer;
class DefaultValue extends AbstractEntity
{
/**
* Gets data transformer.
*
* @return DefaultValueTransformer
*/
public function getTransformer()
{
return new DefaultValueTransformer($this);
}
/**
* @return array
*/
public function getSchema()
{
$returnValue = [
'root' => [
'_id' => [
'_type' => 'mongoid',
],
'name' => [
'_type' => 'required_string',
],
'i18n' => [
'_type' => 'array'
]
],
];
foreach ($this->getClient()->getAvailableLocales() as $locale) {
$returnValue['root']['i18n'][$locale] = [
'_type' => 'array',
'name' => [
'_type' => 'string'
]
];
}
return $returnValue;
}
}
| mit |
Azure/azure-sdk-for-go | sdk/resourcemanager/quantum/armquantum/build.go | 388 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// This file enables 'go generate' to regenerate this specific SDK
//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/quantum/armquantum
package armquantum
| mit |
awto/effectfuljs | packages/debugger/test/regenerator-time-travel.test.js | 218 | require("./setup-time-travel");
const { describe, run, opts } = require("./setup-regenerator");
describe("regenerator run", function() {
opts.debug = false;
run(require("./es-time-travel/links/regenerator"));
});
| mit |
InseeFr/Pogues-Back-Office | src/main/java/fr/insee/pogues/transforms/PipeLine.java | 1521 | package fr.insee.pogues.transforms;
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PipeLine {
private String output;
private List<Runnable> transforms = new ArrayList<>();
public PipeLine from(InputStream input) throws Exception {
output = IOUtils.toString(input, Charset.forName("UTF-8"));
return this;
}
public PipeLine from(String input) {
this.output = input;
return this;
}
public PipeLine map(Transform<String, String> t, Map<String, Object> params, String surveyName) throws Exception {
transforms.add(() -> {
try {
output = t.apply(output, params, surveyName);
} catch (Exception e) {
throw new RuntimeException(
String.format("Exception occured while executing mapping function: %s", e.getMessage())
);
}
});
return this;
}
public String transform() throws Exception {
for (Runnable t : transforms) {
try {
t.run();
} catch (Exception e) {
throw e;
}
}
return output;
}
/// [marker0]
@FunctionalInterface
public interface Transform<I, O> {
O apply(I i, Map<String, Object> params, String surveyName) throws Exception;
}
/// [marker0]
}
| mit |
pillfill/pf-java-client | src/main/java/com/apothesource/pillfill/datamodel/rxnorm/interaction/InteractionPair.java | 3907 | /*
* The MIT License
*
* Copyright 2015 Apothesource, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.apothesource.pillfill.datamodel.rxnorm.interaction;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Java class for InteractionPair complex type.
* <p>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <complexType name="InteractionPair">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="interactionConcept" type="{}InteractionConcept" maxOccurs="unbounded"/>
* <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
public class InteractionPair {
protected String description;
protected List<InteractionConcept> interactionConcept;
protected String severity;
/**
* Gets the value of the description property.
*
* @return possible object is
* {@link String }
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value allowed object is
* {@link String }
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the interactionConcept property.
* <p>
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the interactionConcept property.
* <p>
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInteractionConcept().add(newItem);
* </pre>
* <p>
* <p>
* <p>
* Objects of the following type(s) are allowed in the list
* {@link InteractionConcept }
*/
public List<InteractionConcept> getInteractionConcept() {
if (interactionConcept == null) {
interactionConcept = new ArrayList<InteractionConcept>();
}
return this.interactionConcept;
}
/**
* Gets the value of the severity property.
*
* @return possible object is
* {@link String }
*/
public String getSeverity() {
return severity;
}
/**
* Sets the value of the severity property.
*
* @param value allowed object is
* {@link String }
*/
public void setSeverity(String value) {
this.severity = value;
}
}
| mit |
Evrika/Vidal | src/Vidal/VeterinarBundle/Entity/InfoPageRepository.php | 3417 | <?php
namespace Vidal\VeterinarBundle\Entity;
use Doctrine\ORM\EntityRepository;
class InfoPageRepository extends EntityRepository
{
public function findByLetter($l)
{
return $this->_em->createQuery('
SELECT i.InfoPageID, i.RusName, c.RusName Country, i.Name, i.photo
FROM VidalVeterinarBundle:InfoPage i
LEFT JOIN VidalVeterinarBundle:Country c WITH i.CountryCode = c
WHERE i.RusName LIKE :letter
ORDER BY i.RusName ASC
')->setParameter('letter', $l . '%')
->getResult();
}
public function findByQuery($q)
{
$qb = $this->_em->createQueryBuilder();
$qb
->select('i.InfoPageID, i.RusName, country.RusName Country, i.Name, i.photo')
->from('VidalVeterinarBundle:InfoPage', 'i')
->leftJoin('VidalVeterinarBundle:Country', 'country', 'WITH', 'country.CountryCode = i.CountryCode')
->orderBy('i.RusName', 'ASC');
$where = '';
$words = explode(' ', $q);
# поиск по всем словам вместе
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i];
if ($i > 0) {
$where .= ' AND ';
}
$where .= "(i.RusName LIKE '$word%' OR i.RusName LIKE '% $word%')";
}
$qb->where($where);
$results = $qb->getQuery()->getResult();
# поиск по одному слову
if (empty($results)) {
$where = '';
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i];
if ($i > 0) {
$where .= ' OR ';
}
$where .= "(i.RusName LIKE '$word%' OR i.RusName LIKE '% $word%')";
}
$qb->where($where);
return $qb->getQuery()->getResult();
}
return $results;
}
public function findByInfoPageID($InfoPageID)
{
return $this->_em->createQuery('
SELECT i.InfoPageID, i.RusName, i.RusAddress, c.RusName Country, i.Name, i.photo
FROM VidalVeterinarBundle:InfoPage i
LEFT JOIN VidalVeterinarBundle:Country c WITH i.CountryCode = c
WHERE i = :InfoPageID
')->setParameter('InfoPageID', $InfoPageID)
->getOneOrNullResult();
}
public function findByDocumentID($DocumentID)
{
return $this->_em->createQuery('
SELECT i.InfoPageID, i.RusName, c.RusName Country, i.Name
FROM VidalVeterinarBundle:InfoPage i
LEFT JOIN i.documents d
LEFT JOIN VidalVeterinarBundle:Country c WITH i.CountryCode = c
WHERE d.DocumentID = :DocumentID
')->setParameter('DocumentID', $DocumentID)
->getResult();
}
public function findOneByName($name)
{
return $this->_em->createQuery('
SELECT i.InfoPageID, i.RusName, i.RusAddress, c.RusName Country, i.Name, i.photo
FROM VidalVeterinarBundle:InfoPage i
LEFT JOIN VidalVeterinarBundle:Country c WITH i.CountryCode = c
WHERE i.Name = :name
')->setParameter('name', $name)
->getOneOrNullResult();
}
public function findAllOrdered()
{
return $this->_em->createQuery('
SELECT i.Name, i.RusName, c.RusName Country, i.photo
FROM VidalVeterinarBundle:InfoPage i
LEFT JOIN VidalVeterinarBundle:Country c WITH i.CountryCode = c
ORDER BY i.RusName
')->getResult();
}
public function findPortfolios($InfoPageID)
{
return $this->_em->createQuery('
SELECT DISTINCT p
FROM VidalVeterinarBundle:PharmPortfolio p
JOIN p.DocumentID d
JOIN d.infoPages i
WHERE i.InfoPageID = :InfoPageID
ORDER BY p.title ASC
')->setParameter('InfoPageID', $InfoPageID)
->getResult();
}
} | mit |
openstate/ori-search | app/components/constants/constants.js | 4117 | 'use strict';
angular.module('oriApp.constants', ['ngRoute'])
.run(['ConstantsService', '$location', '$rootScope', function (ConstantsService, $location, $rootScope) {
console.log('now in the run block of the constants module!');
$rootScope.title = 'Blah';
ConstantsService.init();
}])
.factory("ConstantsService", ['BrandingService', 'ORIAPIService', '$q', function (BrandingService, ORIAPIService, $q) {
var svc = {};
var promise;
var sources;
var municipalities;
var classifications = [];
var doc_types = {
'events': 'Activiteiten',
'motions': 'Moties',
'vote_events': 'Stemmingen'
};
var governing_body_types = {
"Municipality": 'Gemeente',
"Province": 'Provincie'
};
var start_year = 2006;
svc.get_branding = function() {
return BrandingService.get_branding();
}
svc.get_years = function() {
var years = [];
var current_date = new Date();
for(var i = start_year; i<= current_date.getFullYear(); i++) {
years.push(i);
}
return years;
};
svc.get_promise = function() {
return promise;
};
svc.get_doc_types = function() {
return doc_types;
};
svc.get_doc_types_as_keys = function() {
return Object.keys(doc_types);
};
svc.get_sources = function() {
return sources;
};
svc.get_classifications = function() {
return classifications;
};
var load_sources = function() {
return ORIAPIService.sources().then(function (data) {
console.log('Got api sources data ...');
console.log(data);
sources = data.data;
});
};
svc.get_municipalities = function() {
return municipalities;
};
svc.get_branded_governing_bodies = function() {
var gb_types = svc.get_branding()['governing_body_types'];
return svc.get_municipalities().organizations.filter(function (m) {
return (gb_types.indexOf(m.classification) >= 0);
});
}
svc.get_governing_body_types = function() {
return governing_body_types;
};
svc.get_municipality_by_collection = function (name) {
for (var muni in municipalities.organizations) {
if (municipalities.organizations[muni].meta.collection.toLowerCase() == name.toLowerCase()) {
return municipalities.organizations[muni];
}
}
};
var load_governing_bodies = function() {
return ORIAPIService.governing_bodies(Object.keys(governing_body_types)).then(function (data) {
console.log('Got municipalities data:');
console.dir(data);
municipalities = data.data;
});
};
svc.load_classifications = function() {
console.log('loading classifications!');
var search_options = {
filters: {
types: {terms: svc.get_doc_types_as_keys()}
},
size: 0
};
return ORIAPIService.simple_search(undefined, 1, search_options).then(function (result) {
console.log('doing base search to get all terms for facets!');
console.dir(result);
classifications = result.data.facets.classification.buckets.map(function (t) { return t.key; });
});
};
svc.load_classifications_for_municipality = function(municipality) {
console.log('loading classifications for ' + municipality + ' !');
var search_options = {
filters: {
collection:{terms: [municipality]},
types: {terms: svc.get_doc_types_as_keys()}
},
size: 0
};
return ORIAPIService.simple_search(undefined, 1, search_options).then(function (result) {
console.log('doing base search to get all terms for facets!');
console.dir(result);
classifications = result.data.facets.classification.buckets.map(function (t) { return t.key; });
});
};
svc.init = function() {
promise = $q.all([load_sources(), load_governing_bodies()]);
};
return svc;
}])
.controller('ConstantsCtrl', ['$scope', '$location', 'ConstantsService',
function($scope, $location, ConstantsService) {
console.log('In the constants controller!');
$scope.municipalities = ConstantsService.get_municipalities();
console.dir($scope.municipalities);
$scope.sources = ConstantsService.get_sources();
}]);
| mit |
Tekstove/Tekstove-api | src/HttpFoundation/RequestIdentificator.php | 588 | <?php
namespace App\HttpFoundation;
use Symfony\Component\HttpFoundation\Request;
/**
* Return hash, identifying current request
*
* @author po_taka <angel.koilov@gmail.com>
*/
class RequestIdentificator
{
public function identify(Request $request)
{
$ips = $request->getClientIps();
$ipsAsString = implode('|', $ips);
$userAgent = $request->headers->get('user-agent');
if (is_array($userAgent)) {
$userAgent = implode('|', $userAgent);
}
$hash = sha1($ipsAsString . $userAgent);
return $hash;
}
}
| mit |
msemys/esjc | src/test/java/com/github/msemys/esjc/ITReadEventOfLinkToToDeletedEvent.java | 1043 | package com.github.msemys.esjc;
import org.junit.Test;
import static org.junit.Assert.*;
public class ITReadEventOfLinkToToDeletedEvent extends AbstractEventStoreTest {
public ITReadEventOfLinkToToDeletedEvent(EventStore eventstore) {
super(eventstore);
}
@Test
public void readsLinkedEvent() {
final String deletedStreamName = generateStreamName();
final String linkedStreamName = generateStreamName();
eventstore.appendToStream(deletedStreamName, ExpectedVersion.ANY, newTestEvent()).join();
eventstore.appendToStream(linkedStreamName, ExpectedVersion.ANY, newLinkEvent(deletedStreamName, 0)).join();
eventstore.deleteStream(deletedStreamName, ExpectedVersion.ANY).join();
EventReadResult result = eventstore.readEvent(linkedStreamName, 0, true).join();
assertNotNull("Missing linked event", result.event.link);
assertNull("Deleted event was resolved", result.event.event);
assertEquals(EventReadStatus.Success, result.status);
}
}
| mit |
G-CorpDev/project | doc/doxygen/html/search/classes_4.js | 101 | var searchData=
[
['idatabasesource',['iDatabaseSource',['../classiDatabaseSource.html',1,'']]]
];
| mit |
Dainius14/twinder | Settings.cs | 1228 | namespace Twinder.Properties {
// This class allows you to handle specific events on the settings class:
// The SettingChanging event is raised before a setting's value is changed.
// The PropertyChanged event is raised after a setting's value is changed.
// The SettingsLoaded event is raised after the setting values are loaded.
// The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings {
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
// Add code to handle the SettingsSaving event here.
}
}
}
| mit |
morzhovets/momo | test/tests/libcxx/unord.set/contains.transparent.pass.cpp | 2236 | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <unordered_set>
// template <class Value, class Hash = hash<Value>, class Pred = equal_to<Value>,
// class Alloc = allocator<Value>>
// class unordered_multiset
// template <typename K>
// bool contains(const K& x) const;
// UNSUPPORTED: c++03, c++11, c++14, c++17
//#include <unordered_set>
//#include "test_transparent_unordered.h"
void main()
{
using key_type = StoredType<int>;
{
// Make sure conversions don't happen for transparent non-final hasher and key_equal
using set_type = const unord_set_type<unordered_set, transparent_hash, std::equal_to<> >;
test_transparent_contains<set_type>(key_type(1), key_type(2));
}
{
// Make sure conversions don't happen for transparent final hasher and key_equal
using set_type = const unord_set_type<unordered_set, transparent_hash_final, transparent_equal_final>;
test_transparent_contains<set_type>(key_type(1), key_type(2));
}
{
// Make sure conversions do happen for non-transparent hasher
using set_type = const unord_set_type<unordered_set, non_transparent_hash,
std::equal_to<> >;
test_non_transparent_contains<set_type>(key_type(1), key_type(2));
}
{
// Make sure conversions do happen for non-transparent key_equal
using set_type = const unord_set_type<unordered_set, transparent_hash,
std::equal_to<key_type> >;
test_non_transparent_contains<set_type>(key_type(1), key_type(2));
}
{
// Make sure conversions do happen for both non-transparent hasher and key_equal
using set_type = const unord_set_type<unordered_set, non_transparent_hash,
std::equal_to<key_type> >;
test_non_transparent_contains<set_type>(key_type(1), key_type(2));
}
}
| mit |
nexylan/paybox-direct | src/Response/AbstractResponse.php | 4129 | <?php
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <contact@nexylan.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\PayboxDirect\Response;
/**
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
abstract class AbstractResponse implements ResponseInterface
{
/**
* @var int
*/
private $code;
/**
* @var string
*/
private $comment;
/**
* @var string
*/
private $site;
/**
* @var string
*/
private $rank;
/**
* @var int
*/
private $callNumber;
/**
* @var int
*/
private $questionNumber;
/**
* @var int
*/
private $transactionNumber;
/**
* @var string|null|false
*/
private $authorization = null;
/**
* @var string|null|false
*/
private $country = null;
/**
* @var string|null|false
*/
private $sha1 = null;
/**
* @var string|null|false
*/
private $cardType = null;
/**
* @var mixed[]
*/
protected $filteredParameters;
/**
* @param string[] $parameters
*/
public function __construct(array $parameters)
{
// Cleanup array to set false for empty/invalid values.
$this->filteredParameters = array_map(function ($value) {
if (in_array($value, ['', '???'], true)) {
return false;
}
return $value;
}, $parameters);
$this->code = intval($this->filteredParameters['CODEREPONSE']);
$this->comment = $this->filteredParameters['COMMENTAIRE'];
$this->site = $this->filteredParameters['SITE'];
$this->rank = $this->filteredParameters['RANG'];
$this->callNumber = intval($this->filteredParameters['NUMAPPEL']);
$this->questionNumber = intval($this->filteredParameters['NUMQUESTION']);
$this->transactionNumber = intval($this->filteredParameters['NUMTRANS']);
if (array_key_exists('AUTORISATION', $this->filteredParameters)) {
$this->authorization = $this->filteredParameters['AUTORISATION'];
}
if (array_key_exists('PAYS', $this->filteredParameters)) {
$this->country = $this->filteredParameters['PAYS'];
}
if (array_key_exists('SHA-1', $this->filteredParameters)) {
$this->sha1 = $this->filteredParameters['SHA-1'];
}
if (array_key_exists('TYPECARTE', $this->filteredParameters)) {
$this->cardType = $this->filteredParameters['TYPECARTE'];
}
}
/**
* {@inheritdoc}
*/
final public function isSuccessful()
{
return 0 === $this->code;
}
/**
* {@inheritdoc}
*/
final public function getCode()
{
return $this->code;
}
/**
* {@inheritdoc}
*/
final public function getComment()
{
return $this->comment;
}
/**
* {@inheritdoc}
*/
final public function getSite()
{
return $this->site;
}
/**
* {@inheritdoc}
*/
final public function getRank()
{
return $this->rank;
}
/**
* {@inheritdoc}
*/
final public function getCallNumber()
{
return $this->callNumber;
}
/**
* {@inheritdoc}
*/
final public function getQuestionNumber()
{
return $this->questionNumber;
}
/**
* {@inheritdoc}
*/
final public function getTransactionNumber()
{
return $this->transactionNumber;
}
/**
* {@inheritdoc}
*/
public function getAuthorization()
{
return $this->authorization;
}
/**
* {@inheritdoc}
*/
public function getCountry()
{
return $this->country;
}
/**
* {@inheritdoc}
*/
final public function getSha1()
{
return $this->sha1;
}
/**
* {@inheritdoc}
*/
public function getCardType()
{
return $this->cardType;
}
}
| mit |
geocoder-php/Geocoder | src/Provider/OpenCage/Tests/OpenCageTest.php | 17326 | <?php
declare(strict_types=1);
/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Geocoder\Provider\OpenCage\Tests;
use Geocoder\Collection;
use Geocoder\IntegrationTest\BaseTestCase;
use Geocoder\Model\AddressCollection;
use Geocoder\Model\Bounds;
use Geocoder\Provider\OpenCage\Model\OpenCageAddress;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Geocoder\Provider\OpenCage\OpenCage;
/**
* @author mtm <mtm@opencagedata.com>
*/
class OpenCageTest extends BaseTestCase
{
protected function getCacheDir()
{
return __DIR__.'/.cached_responses';
}
public function testGetName()
{
$provider = new OpenCage($this->getMockedHttpClient(), 'api_key');
$this->assertEquals('opencage', $provider->getName());
}
public function testSslSchema()
{
$provider = new OpenCage($this->getMockedHttpClient('{}'), 'api_key');
$result = $provider->geocodeQuery(GeocodeQuery::create('foobar'));
$this->assertInstanceOf(Collection::class, $result);
$this->assertEquals(0, $result->count());
}
public function testGeocodeWithRealAddress()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('10 avenue Gambetta, Paris, France'));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(2, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(48.866205, $result->getCoordinates()->getLatitude(), 0.01);
$this->assertEqualsWithDelta(2.389089, $result->getCoordinates()->getLongitude(), 0.01);
$this->assertNotNull($result->getBounds());
$this->assertEquals(48.863142699999997, $result->getBounds()->getSouth());
$this->assertEquals(2.3890394000000001, $result->getBounds()->getWest());
$this->assertEquals(48.863242700000001, $result->getBounds()->getNorth());
$this->assertEquals(2.3891393999999999, $result->getBounds()->getEast());
$this->assertEquals(10, $result->getStreetNumber());
$this->assertEquals('Avenue Gambetta', $result->getStreetName());
$this->assertEquals(75020, $result->getPostalCode());
$this->assertEquals('Paris', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Paris', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Ile-de-France', $result->getAdminLevels()->get(1)->getName());
$this->assertEquals('France', $result->getCountry()->getName());
$this->assertEquals('FR', $result->getCountry()->getCode());
$this->assertEquals('Europe/Paris', $result->getTimezone());
$this->assertEquals('31UDQ5519412427', $result->getMGRS());
$this->assertEquals('JN18eu67qd', $result->getMaidenhead());
$this->assertEquals('u09tyr78tz64jdcgfnhe', $result->getGeohash());
$this->assertEquals('listed.emphasis.greeting', $result->getWhat3words());
$this->assertEquals('10 Avenue Gambetta, 75020 Paris, France', $result->getFormattedAddress());
}
public function testReverseWithRealCoordinates()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->reverseQuery(ReverseQuery::fromCoordinates(54.0484068, -2.7990345));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(1, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(54.0484068, $result->getCoordinates()->getLatitude(), 0.001);
$this->assertEqualsWithDelta(-2.7990345, $result->getCoordinates()->getLongitude(), 0.001);
$this->assertNotNull($result->getBounds());
$this->assertEqualsWithDelta(54.0484068, $result->getBounds()->getSouth(), 0.001);
$this->assertEqualsWithDelta(-2.7998815, $result->getBounds()->getWest(), 0.001);
$this->assertEqualsWithDelta(54.049472, $result->getBounds()->getNorth(), 0.001);
$this->assertEqualsWithDelta(-2.7980925, $result->getBounds()->getEast(), 0.001);
$this->assertNull($result->getStreetNumber());
$this->assertEquals('Lancaster Gate', $result->getStreetName());
$this->assertEquals('LA1 1LZ', $result->getPostalCode());
$this->assertEquals('Lancaster', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Lancashire', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('England', $result->getAdminLevels()->get(1)->getName());
$this->assertEquals('United Kingdom', $result->getCountry()->getName());
$this->assertEquals('GB', $result->getCountry()->getCode());
$this->assertEquals('Europe/London', $result->getTimezone());
$this->assertEquals('30UWE1316588979', $result->getMGRS());
$this->assertEquals('IO84ob41dr', $result->getMaidenhead());
$this->assertEquals('gcw52r3csd02c23bwucn', $result->getGeohash());
$this->assertEquals('heave.dock.wage', $result->getWhat3words());
$this->assertEquals('Saint Nicholas Arcades, Lancaster Gate, Lancaster LA1 1LZ, United Kingdom', $result->getFormattedAddress());
}
public function testReverseWithVillage()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->reverseQuery(ReverseQuery::fromCoordinates(49.1390924, 1.6572462));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(1, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEquals('Bray-et-Lû', $result->getLocality());
}
public function testGeocodeWithCity()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('Hanover'));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(5, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(52.374478, $result->getCoordinates()->getLatitude(), 0.01);
$this->assertEqualsWithDelta(9.738553, $result->getCoordinates()->getLongitude(), 0.01);
$this->assertEquals('Hanover', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Region Hannover', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Lower Saxony', $result->getAdminLevels()->get(1)->getName());
$this->assertEquals('Germany', $result->getCountry()->getName());
/** @var OpenCageAddress $result */
$result = $results->get(1);
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(18.3840489, $result->getCoordinates()->getLatitude(), 0.01);
$this->assertEqualsWithDelta(-78.131485, $result->getCoordinates()->getLongitude(), 0.01);
$this->assertNull($result->getLocality());
$this->assertTrue($result->getAdminLevels()->has(2));
$this->assertEquals('Hanover', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Jamaica', $result->getCountry()->getName());
/** @var OpenCageAddress $result */
$result = $results->get(2);
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(43.7033073, $result->getCoordinates()->getLatitude(), 0.01);
$this->assertEqualsWithDelta(-72.2885663, $result->getCoordinates()->getLongitude(), 0.01);
$this->assertEquals('Hanover', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Grafton County', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('New Hampshire', $result->getAdminLevels()->get(1)->getName());
$this->assertEquals('United States of America', $result->getCountry()->getName());
}
public function testGeocodeWithCityDistrict()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('Kalbacher Hauptstraße 10, 60437 Frankfurt, Germany'));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(2, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEqualsWithDelta(50.189062, $result->getCoordinates()->getLatitude(), 0.01);
$this->assertEqualsWithDelta(8.636567, $result->getCoordinates()->getLongitude(), 0.01);
$this->assertEquals(10, $result->getStreetNumber());
$this->assertEquals('Kalbacher Hauptstraße', $result->getStreetName());
$this->assertEquals(60437, $result->getPostalCode());
$this->assertEquals('Frankfurt', $result->getLocality());
$this->assertCount(1, $result->getAdminLevels());
$this->assertEquals('Hesse', $result->getAdminLevels()->get(1)->getName());
$this->assertNull($result->getAdminLevels()->get(1)->getCode());
$this->assertEquals('Germany', $result->getCountry()->getName());
$this->assertEquals('DE', $result->getCountry()->getCode());
$this->assertEquals('Europe/Berlin', $result->getTimezone());
}
public function testGeocodeWithLocale()
{
if (!isset($_SERVER['OPENCAGE_API_KEY'])) {
$this->markTestSkipped('You need to configure the OPENCAGE_API_KEY value in phpunit.xml');
}
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('London')->withLocale('es'));
$this->assertInstanceOf(AddressCollection::class, $results);
$this->assertCount(5, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertInstanceOf(OpenCageAddress::class, $result);
$this->assertEquals('Londres', $result->getLocality());
$this->assertCount(2, $result->getAdminLevels());
$this->assertEquals('Londres', $result->getAdminLevels()->get(2)->getName());
$this->assertEquals('Inglaterra', $result->getAdminLevels()->get(1)->getName());
$this->assertEquals('Reino Unido', $result->getCountry()->getName());
$this->assertEquals('GB', $result->getCountry()->getCode());
}
public function testAmbiguousResultCountryCode()
{
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('Gera-Ost Gera 07546 DE'));
$this->assertCount(2, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('ID', $result->getCountry()->getCode());
$results = $provider->geocodeQuery(GeocodeQuery::create('Gera-Ost Gera 07546 DE')->withData('countrycode', 'DE'));
$this->assertCount(1, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('DE', $result->getCountry()->getCode());
}
public function testAmbiguousResultBounds()
{
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('Gera-Ost Gera 07546 DE'));
$this->assertCount(2, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('ID', $result->getCountry()->getCode());
$bounds = new Bounds(50.8613807, 11.7525627, 50.8850706, 12.511183);
$results = $provider->geocodeQuery(GeocodeQuery::create('Gera-Ost Gera 07546 DE')->withBounds($bounds));
$this->assertCount(1, $results);
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('DE', $result->getCountry()->getCode());
}
public function testAmbiguousResultProximity()
{
$provider = new OpenCage($this->getHttpClient($_SERVER['OPENCAGE_API_KEY']), $_SERVER['OPENCAGE_API_KEY']);
$results = $provider->geocodeQuery(GeocodeQuery::create('odessa'));
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('UA', $result->getCountry()->getCode());
$results = $provider->geocodeQuery(GeocodeQuery::create('odessa')->withData('proximity', '31.918807,-102.474021'));
/** @var OpenCageAddress $result */
$result = $results->first();
$this->assertEquals('US', $result->getCountry()->getCode());
}
public function testGeocodeQuotaExceeded()
{
$this->expectException(\Geocoder\Exception\QuotaExceeded::class);
$this->expectExceptionMessage('Valid request but quota exceeded.');
$provider = new OpenCage(
$this->getMockedHttpClient(
'{
"status": {
"code": 402,
"message": "quota exceeded"
}
}'
),
'api_key'
);
$provider->geocodeQuery(GeocodeQuery::create('New York'));
}
public function testGeocodeInvalidApiKey()
{
$this->expectException(\Geocoder\Exception\InvalidCredentials::class);
$this->expectExceptionMessage('Invalid or missing api key.');
$provider = new OpenCage(
$this->getMockedHttpClient(
'{
"status": {
"code": 403,
"message": "invalid API key"
}
}'
),
'api_key'
);
$provider->geocodeQuery(GeocodeQuery::create('New York'));
}
public function testGeocodeWithLocalhostIPv4()
{
$this->expectException(\Geocoder\Exception\UnsupportedOperation::class);
$this->expectExceptionMessage('The OpenCage provider does not support IP addresses, only street addresses.');
$provider = new OpenCage($this->getMockedHttpClient(), 'api_key');
$provider->geocodeQuery(GeocodeQuery::create('127.0.0.1'));
}
public function testGeocodeWithLocalhostIPv6()
{
$this->expectException(\Geocoder\Exception\UnsupportedOperation::class);
$this->expectExceptionMessage('The OpenCage provider does not support IP addresses, only street addresses.');
$provider = new OpenCage($this->getMockedHttpClient(), 'api_key');
$provider->geocodeQuery(GeocodeQuery::create('::1'));
}
public function testGeocodeWithRealIPv4()
{
$this->expectException(\Geocoder\Exception\UnsupportedOperation::class);
$this->expectExceptionMessage('The OpenCage provider does not support IP addresses, only street addresses.');
$provider = new OpenCage($this->getHttpClient(), 'api_key');
$provider->geocodeQuery(GeocodeQuery::create('74.200.247.59'));
}
public function testGeocodeWithRealIPv6()
{
$this->expectException(\Geocoder\Exception\UnsupportedOperation::class);
$this->expectExceptionMessage('The OpenCage provider does not support IP addresses, only street addresses.');
$provider = new OpenCage($this->getHttpClient(), 'api_key');
$provider->geocodeQuery(GeocodeQuery::create('::ffff:74.200.247.59'));
}
}
| mit |
Squidex/squidex | backend/src/Squidex.Domain.Apps.Core.Model/Schemas/BooleanFieldEditor.cs | 498 | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Domain.Apps.Core.Schemas
{
public enum BooleanFieldEditor
{
Checkbox,
Toggle
}
}
| mit |
jonaustin/craigslist-housing-mapper | cake/console/libs/templates/skel/config/routes.php | 1786 | <?php
/* SVN FILE: $Id: routes.php 6311 2008-01-02 06:33:52Z phpnut $ */
/**
* Short description for file.
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different urls to chosen controllers and their actions (functions).
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework <http://www.cakephp.org/>
* Copyright 2005-2008, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.2.9
* @version $Revision: 6311 $
* @modifiedby $LastChangedBy: phpnut $
* @lastmodified $Date: 2008-01-01 22:33:52 -0800 (Tue, 01 Jan 2008) $
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.thtml)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
/**
* Then we connect url '/test' to our test controller. This is helpfull in
* developement.
*/
Router::connect('/tests', array('controller' => 'tests', 'action' => 'index'));
?> | mit |
kashif/chainer | chainer/functions/array/reshape.py | 2875 | import chainer
from chainer import function_node
from chainer.utils import type_check
def _count_unknown_dims(shape):
cnt = 0
for dim in shape:
cnt += dim < 0
return cnt
class Reshape(function_node.FunctionNode):
"""Reshapes an input array without copy."""
def __init__(self, shape):
self.shape = shape
self._cnt = _count_unknown_dims(shape)
assert self._cnt <= 1
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
)
x_type, = in_types
if self._cnt == 0:
type_check.expect(
type_check.prod(x_type.shape) == type_check.prod(self.shape))
else:
known_size = 1
for s in self.shape:
if s > 0:
known_size *= s
size_var = type_check.make_variable(
known_size, 'known_size(=%d)' % known_size)
type_check.expect(
type_check.prod(x_type.shape) % size_var == 0)
def forward(self, inputs):
x, = inputs
return x.reshape(self.shape),
def backward(self, indexes, grad_outputs):
gx, = grad_outputs
return reshape(gx, self.inputs[0].shape),
def reshape(x, shape):
"""Reshapes an input variable without copy.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Input variable.
shape (:class:`tuple` of :class:`int` s):
Expected shape of the output array. The number of elements which
the array of ``shape`` contains must be equal to that of input
array. One shape dimension can be -1. In this case, the value is
inferred from the length of the array and remaining dimensions.
Returns:
~chainer.Variable:
Variable that holds a reshaped version of the input variable.
.. seealso:: :func:`numpy.reshape`, :func:`cupy.reshape`
.. admonition:: Example
>>> x = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> y = F.reshape(x, (8,))
>>> y.shape
(8,)
>>> y.data
array([1, 2, 3, 4, 5, 6, 7, 8])
>>> y = F.reshape(x, (4, -1)) # the shape of output is inferred
>>> y.shape
(4, 2)
>>> y.data
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
>>> y = F.reshape(x, (4, 3)) \
# the shape of input and output are not consistent
Traceback (most recent call last):
...
chainer.utils.type_check.InvalidType:
Invalid operation is performed in: Reshape (Forward)
Expect: prod(in_types[0].shape) == prod((4, 3))
Actual: 8 != 12
"""
if x.shape == shape:
return chainer.as_variable(x)
y, = Reshape(shape).apply((x,))
return y
| mit |
locnguyen/reactjsoc-examples | index.js | 594 | var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({
port: 9000
});
server.start(function () {
console.log('Hapi server has started at %S' + server.info.uri);
});
server.route({
path: '/',
method: 'GET',
handler: function (request, reply) {
reply.redirect('/examples');
}
});
server.route({
path: '/examples/{path*}',
method: 'GET',
config: {
handler: {
directory: {
path: './examples/',
listing: false,
index: true
}
}
}
});
| mit |
seekmas/fun | src/Mc/AdminBundle/DependencyInjection/Configuration.php | 871 | <?php
namespace Mc\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mc_admin');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| mit |
stingchang/CS_Java | src/CC150/Ch2_LinkedList/Q2_Return_Kth_to_Last.java | 433 | package CC150.Ch2_LinkedList;
public class Q2_Return_Kth_to_Last {
public Node kLast(Node node, int k) {
Node tmp = node;
for (int i = 0; i < k; i++) {
if (tmp != null)
tmp = tmp.next;
else break;
}
if (tmp == null) return null;
while (tmp != null) {
tmp = tmp.next;
node = node.next;
}
return node;
}
}
| mit |
AerisG222/SizePhotos | src/SizePhotos/Minification/StripMetadataPhotoProcessor.cs | 732 | using System.Threading.Tasks;
namespace SizePhotos.Minification
{
public class StripMetadataPhotoProcessor
: IPhotoProcessor
{
public IPhotoProcessor Clone()
{
return (IPhotoProcessor) MemberwiseClone();
}
public Task<IProcessingResult> ProcessPhotoAsync(ProcessingContext context)
{
if(context.Wand != null)
{
context.Wand.StripImage();
return Task.FromResult((IProcessingResult) new StripMetadataProcessingResult(true));
}
return Task.FromResult((IProcessingResult) new StripMetadataProcessingResult("Error stripping metadata as the image/wand was null."));
}
}
}
| mit |
umbc-hackafe/sign-drivers | python/fontdemo.py | 1765 | #!/usr/bin/env python3
import sys, argparse, json
def render(dimensions, tflist):
strmatrix = []
# Split the flat tflist up into a matrix
for rownum, row in enumerate((tflist[i:i+dimensions[0]]
for i in range(0, len(tflist), dimensions[0]))):
strmatrix.append([])
for colnum, pixel in enumerate(row):
if pixel == 1:
strmatrix[rownum].append("#")
else:
strmatrix[rownum].append(" ")
return strmatrix
def printletter(fontspec, letter):
dimensions = fontspec['__dimensions__']
if letter in fontspec:
strmatrix = render(dimensions, fontspec[letter])
for row in strmatrix:
print(" %s" % ''.join(row))
else:
print("%s: letter missing!" % letter)
def main(args):
with open(args.file, 'r') as f:
fontspec = json.load(f)
if args.string:
for letter in args.string:
printletter(fontspec, letter)
elif args.letter:
for letter in args.letter:
print("%s:" % letter)
printletter(fontspec, letter)
else:
for letter, tflist in fontspec.items():
# Skip "private" fields
if letter.startswith("__"):
continue
else:
print("%s:" % letter)
printletter(fontpsec, letter)
def parse(args):
parser = argparse.ArgumentParser()
parser.add_argument("--file", "-f", type=str, default="font/4x4.json")
parser.add_argument("--letter", "-l", type=str, default=None, nargs="*")
parser.add_argument("--string", "-s", type=str, default=None, nargs="?")
return parser.parse_args(args)
if __name__ == "__main__":
sys.exit(main(parse(sys.argv[1:])))
| mit |
raelcun/rust_tutorials | embed/src/embed.js | 122 | var ffi = require('ffi');
var lib = ffi.Library('target/release/libembed', {
'process': ['void', []]
});
lib.process(); | mit |
Armature/Server | Handlers/Main.php | 943 | <?php
/*
+----------------------------------------------------------------------+
| Armature |
+----------------------------------------------------------------------+
| Website: http://armature.pw |
| Github: https://github.com/Armature |
| License: http://creativecommons.org/licenses/by-nc-sa/4.0/ |
+----------------------------------------------------------------------+
| Author: Oleg Budrin (Mofsy) <support@mofsy.ru> <https://mofsy.ru> |
+----------------------------------------------------------------------+
*/
namespace Armature\Handlers;
use Armature\Core\Handler as Handler;
class Main extends Handler {
public function index()
{
$this->hello();
}
private function hello()
{
echo 'Hello World by Armature.Server';
}
} | mit |
qlik-oss/halyard.js | src/table.js | 4476 | import defaultConnectionMatcher from './default-connection-matcher';
import formatSpecification from './utils/format-specification';
import { escapeText, validFieldType, indentation } from './utils/utils';
class Table {
/**
* Table definition
* @public
* @class
* @param {Connection} connection
* @param {object} options - Table options
* @param {string} options.name - Table name
* @param {Field[]} options.fields - Array of field objects
* @param {string} options.prefix - Add prefix before the table
* @param {string} options.section - Section to add table to
* @constructor
*/
constructor(connection, options) {
this.connection = defaultConnectionMatcher.findMatch(connection);
options = options || {};
if (typeof options === 'string') {
this.name = options;
options = {};
} else {
this.name = options.name;
this.fields = options.fields;
this.prefix = options.prefix;
if (options.section) {
this.section = options.section;
}
}
this.options = options;
}
/**
* @typedef {object} Field
* @public
* @property {string} src - Name in the data source of the field
* @property {string} name - Name after reload
* @property {string} type - Date, Time, TimeStamp
* @property {string} inputFormat - Input format to explain how a field should be parsed.
* @property {string} displayFormat - Display format that should be used after reload.
* @property {string} expr - Customize how this field should be loaded with Qlik Script.
*/
/**
* Get the fields from a table
* @public
* @returns {Field[]} Array of fields
*/
getFields() {
return this.fields;
}
/**
* Get the script representation of the field list. If nothing is specified than all the fields will be returned.
* @public
* @returns {string}
*/
getFieldList() {
if (this.fields) {
return this.fields.map((field) => {
let formattedInput = `"${escapeText(field.src || '')}"`;
if (validFieldType(field.type)) {
const format = field.type.toUpperCase();
if (field.inputFormat) {
formattedInput = `${format}#(${formattedInput}, '${field.inputFormat}')`;
}
if (field.displayFormat) {
formattedInput = `${format}(${formattedInput}, '${field.displayFormat}')`;
} else {
formattedInput = `${format}(${formattedInput})`;
}
}
if (field.expr) {
formattedInput = field.expr;
}
if (!(field.name || field.src)) {
throw (new Error(`A name or src needs to specified on the field: ${JSON.stringify(field)}`));
}
return `${indentation() + formattedInput} AS "${escapeText(field.name || field.src)}"`;
}).join(',\n');
}
return '*';
}
/**
* Is the table used as a proceeding load
* @public
* @returns {boolean}
*/
isProceedingLoad() {
return this.connection instanceof Table;
}
/**
* Returns the specified prefix of the table if it exists.
* The prefix can be for instance be a Qlik script snippet that always should be executed before the table is loaded.
* @public
* @returns {string}
*/
getPrefix() {
if (this.prefix) {
return `${this.prefix}\n`;
}
return '';
}
/**
* Get the script representation of the table
* @public
* @returns {string}
*/
getScript() {
// In the future this could be moved into a connectionMatcher
// but for sake of clarity it is kept inline.
if (this.isProceedingLoad()) {
return `${this.getPrefix()}LOAD\n${this.getFieldList()};\n${this.connection.getScript()}`;
}
// Hack!
if (this.connection.getFileExtension) {
this.options.fileExtension = this.connection.getFileExtension();
}
return `${this.getPrefix()}LOAD\n${this.getFieldList()}\n${this.connection.getScript()}${formatSpecification(this.options)};`;
}
/**
* Get the name of the table
* @public
* @returns {string}
*/
getName() {
return this.name || '';
}
/**
* Get the section that the table belongs to
* @public
* @returns {string}
*/
getSection() {
return this.section;
}
/**
* Returns the connection or table that the table uses.
* @public
* @returns {(Connection|Table)} Connection or Table
*/
getConnection() {
return this.connection;
}
}
export default Table;
| mit |
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_nottheonion/app.py | 145 | #encoding:utf-8
subreddit = 'nottheonion'
t_channel = '@r_nottheonion'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| mit |
Miz85/react-boilerplate | src/actions/actions.js | 139 | import * as types from '../constants/ActionTypes';
export function exampleActionCreator(){
return { type: types.EXAMPLE_ACTION_TYPE }
}
| mit |
benoror/ag-grid | src/ts/filter/filterManager.ts | 16470 | /// <reference path="../utils.ts" />
/// <reference path="textFilter.ts" />
/// <reference path="numberFilter.ts" />
/// <reference path="setFilter.ts" />
/// <reference path="../widgets/agPopupService.ts" />
/// <reference path="../widgets/agPopupService.ts" />
/// <reference path="../grid.ts" />
/// <reference path="../entities/rowNode.ts" />
module ag.grid {
var _ = Utils;
export class FilterManager {
private $compile: any;
private $scope: any;
private gridOptionsWrapper: GridOptionsWrapper;
private grid: any;
private allFilters: any;
private rowModel: any;
private popupService: PopupService;
private valueService: ValueService;
private columnController: ColumnController;
private quickFilter: string;
private advancedFilterPresent: boolean;
private externalFilterPresent: boolean;
public init(grid: Grid, gridOptionsWrapper: GridOptionsWrapper, $compile: any, $scope: any,
columnController: ColumnController, popupService: PopupService, valueService: ValueService) {
this.$compile = $compile;
this.$scope = $scope;
this.gridOptionsWrapper = gridOptionsWrapper;
this.grid = grid;
this.allFilters = {};
this.columnController = columnController;
this.popupService = popupService;
this.valueService = valueService;
this.columnController = columnController;
this.quickFilter = null;
}
public setFilterModel(model: any) {
if (model) {
// mark the filters as we set them, so any active filters left over we stop
var modelKeys = Object.keys(model);
_.iterateObject(this.allFilters, (colId, filterWrapper) => {
_.removeFromArray(modelKeys, colId);
var newModel = model[colId];
this.setModelOnFilterWrapper(filterWrapper.filter, newModel);
});
// at this point, processedFields contains data for which we don't have a filter working yet
_.iterateArray(modelKeys, (colId) => {
var column = this.columnController.getColumn(colId);
if (!column) {
console.warn('Warning ag-grid setFilterModel - no column found for colId ' + colId);
return;
}
var filterWrapper = this.getOrCreateFilterWrapper(column);
this.setModelOnFilterWrapper(filterWrapper.filter, model[colId]);
});
} else {
_.iterateObject(this.allFilters, (key, filterWrapper) => {
this.setModelOnFilterWrapper(filterWrapper.filter, null);
});
}
this.grid.onFilterChanged();
}
private setModelOnFilterWrapper(filter: { getApi: () => { setModel: Function }}, newModel: any) {
// because user can provide filters, we provide useful error checking and messages
if (typeof filter.getApi !== 'function') {
console.warn('Warning ag-grid - filter missing getApi method, which is needed for getFilterModel');
return;
}
var filterApi = filter.getApi();
if (typeof filterApi.setModel !== 'function') {
console.warn('Warning ag-grid - filter API missing setModel method, which is needed for setFilterModel');
return;
}
filterApi.setModel(newModel);
}
public getFilterModel() {
var result = <any>{};
_.iterateObject(this.allFilters, function (key: any, filterWrapper: any) {
// because user can provide filters, we provide useful error checking and messages
if (typeof filterWrapper.filter.getApi !== 'function') {
console.warn('Warning ag-grid - filter missing getApi method, which is needed for getFilterModel');
return;
}
var filterApi = filterWrapper.filter.getApi();
if (typeof filterApi.getModel !== 'function') {
console.warn('Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel');
return;
}
var model = filterApi.getModel();
if (model) {
result[key] = model;
}
});
return result;
}
public setRowModel(rowModel: any) {
this.rowModel = rowModel;
}
// returns true if any advanced filter (ie not quick filter) active
public isAdvancedFilterPresent() {
var atLeastOneActive = false;
_.iterateObject(this.allFilters, function (key, filterWrapper) {
if (!filterWrapper.filter.isFilterActive) { // because users can do custom filters, give nice error message
console.error('Filter is missing method isFilterActive');
}
if (filterWrapper.filter.isFilterActive()) {
atLeastOneActive = true;
}
});
return atLeastOneActive;
}
// returns true if quickFilter or advancedFilter
public isAnyFilterPresent(): boolean {
return this.isQuickFilterPresent() || this.advancedFilterPresent || this.externalFilterPresent;
}
// returns true if given col has a filter active
public isFilterPresentForCol(colId: any) {
var filterWrapper = this.allFilters[colId];
if (!filterWrapper) {
return false;
}
if (!filterWrapper.filter.isFilterActive) { // because users can do custom filters, give nice error message
console.error('Filter is missing method isFilterActive');
}
var filterPresent = filterWrapper.filter.isFilterActive();
return filterPresent;
}
private doesFilterPass(node: RowNode, filterToSkip?: any) {
var data = node.data;
var colKeys = Object.keys(this.allFilters);
for (var i = 0, l = colKeys.length; i < l; i++) { // critical code, don't use functional programming
var colId = colKeys[i];
var filterWrapper = this.allFilters[colId];
// if no filter, always pass
if (filterWrapper === undefined) {
continue;
}
if (filterWrapper.filter === filterToSkip) {
continue
}
if (!filterWrapper.filter.doesFilterPass) { // because users can do custom filters, give nice error message
console.error('Filter is missing method doesFilterPass');
}
var params = {
node: node,
data: data
};
if (!filterWrapper.filter.doesFilterPass(params)) {
return false;
}
}
// all filters passed
return true;
}
// returns true if it has changed (not just same value again)
public setQuickFilter(newFilter: any): boolean {
if (newFilter === undefined || newFilter === "") {
newFilter = null;
}
if (this.quickFilter !== newFilter) {
if (this.gridOptionsWrapper.isVirtualPaging()) {
console.warn('ag-grid: cannot do quick filtering when doing virtual paging');
return;
}
//want 'null' to mean to filter, so remove undefined and empty string
if (newFilter === undefined || newFilter === "") {
newFilter = null;
}
if (newFilter !== null) {
newFilter = newFilter.toUpperCase();
}
this.quickFilter = newFilter;
return true;
} else {
return false;
}
}
public onFilterChanged(): void {
this.advancedFilterPresent = this.isAdvancedFilterPresent();
this.externalFilterPresent = this.gridOptionsWrapper.isExternalFilterPresent();
_.iterateObject(this.allFilters, function (key, filterWrapper) {
if (filterWrapper.filter.onAnyFilterChanged) {
filterWrapper.filter.onAnyFilterChanged();
}
});
}
public isQuickFilterPresent(): boolean {
return this.quickFilter !== null;
}
public doesRowPassOtherFilters(filterToSkip: any, node: any): boolean {
return this.doesRowPassFilter(node, filterToSkip);
}
public doesRowPassFilter(node: any, filterToSkip?: any): boolean {
//first up, check quick filter
if (this.isQuickFilterPresent()) {
if (!node.quickFilterAggregateText) {
this.aggregateRowForQuickFilter(node);
}
if (node.quickFilterAggregateText.indexOf(this.quickFilter) < 0) {
//quick filter fails, so skip item
return false;
}
}
//secondly, give the client a chance to reject this row
if (this.externalFilterPresent) {
if (!this.gridOptionsWrapper.doesExternalFilterPass(node)) {
return false;
}
}
//lastly, check our internal advanced filter
if (this.advancedFilterPresent) {
if (!this.doesFilterPass(node, filterToSkip)) {
return false;
}
}
//got this far, all filters pass
return true;
}
private aggregateRowForQuickFilter(node: RowNode) {
var aggregatedText = '';
var that = this;
this.columnController.getAllColumns().forEach(function (column: Column) {
var data = node.data;
var value = that.valueService.getValue(column.getColDef(), data, node);
if (value && value !== '') {
aggregatedText = aggregatedText + value.toString().toUpperCase() + "_";
}
});
node.quickFilterAggregateText = aggregatedText;
}
public onNewRowsLoaded() {
var that = this;
Object.keys(this.allFilters).forEach(function (field) {
var filter = that.allFilters[field].filter;
if (filter.onNewRowsLoaded) {
filter.onNewRowsLoaded();
}
});
}
private createValueGetter(column: Column) {
var that = this;
return function valueGetter(node: any) {
return that.valueService.getValue(column.getColDef(), node.data, node);
};
}
public getFilterApi(column: Column) {
var filterWrapper = this.getOrCreateFilterWrapper(column);
if (filterWrapper) {
if (typeof filterWrapper.filter.getApi === 'function') {
return filterWrapper.filter.getApi();
}
}
}
private getOrCreateFilterWrapper(column: Column) {
var filterWrapper = this.allFilters[column.getColId()];
if (!filterWrapper) {
filterWrapper = this.createFilterWrapper(column);
this.allFilters[column.getColId()] = filterWrapper;
}
return filterWrapper;
}
private createFilterWrapper(column: Column) {
var colDef = column.getColDef();
var filterWrapper = {
column: column,
filter: <any> null,
scope: <any> null,
gui: <any> null
};
if (typeof colDef.filter === 'function') {
// if user provided a filter, just use it
// first up, create child scope if needed
if (this.gridOptionsWrapper.isAngularCompileFilters()) {
filterWrapper.scope = this.$scope.$new();;
}
// now create filter (had to cast to any to get 'new' working)
this.assertMethodHasNoParameters(colDef.filter);
filterWrapper.filter = new (<any>colDef.filter)();
} else if (colDef.filter === 'text') {
filterWrapper.filter = new TextFilter();
} else if (colDef.filter === 'number') {
filterWrapper.filter = new NumberFilter();
} else {
filterWrapper.filter = new SetFilter();
}
var filterChangedCallback = this.grid.onFilterChanged.bind(this.grid);
var filterModifiedCallback = this.grid.onFilterModified.bind(this.grid);
var doesRowPassOtherFilters = this.doesRowPassOtherFilters.bind(this, filterWrapper.filter);
var filterParams = colDef.filterParams;
var params = {
colDef: colDef,
rowModel: this.rowModel,
filterChangedCallback: filterChangedCallback,
filterModifiedCallback: filterModifiedCallback,
filterParams: filterParams,
localeTextFunc: this.gridOptionsWrapper.getLocaleTextFunc(),
valueGetter: this.createValueGetter(column),
doesRowPassOtherFilter: doesRowPassOtherFilters,
context: this.gridOptionsWrapper.getContext,
$scope: filterWrapper.scope
};
if (!filterWrapper.filter.init) { // because users can do custom filters, give nice error message
throw 'Filter is missing method init';
}
filterWrapper.filter.init(params);
if (!filterWrapper.filter.getGui) { // because users can do custom filters, give nice error message
throw 'Filter is missing method getGui';
}
var eFilterGui = document.createElement('div');
eFilterGui.className = 'ag-filter';
var guiFromFilter = filterWrapper.filter.getGui();
if (_.isNodeOrElement(guiFromFilter)) {
//a dom node or element was returned, so add child
eFilterGui.appendChild(guiFromFilter);
} else {
//otherwise assume it was html, so just insert
var eTextSpan = document.createElement('span');
eTextSpan.innerHTML = guiFromFilter;
eFilterGui.appendChild(eTextSpan);
}
if (filterWrapper.scope) {
filterWrapper.gui = this.$compile(eFilterGui)(filterWrapper.scope)[0];
} else {
filterWrapper.gui = eFilterGui;
}
return filterWrapper;
}
private assertMethodHasNoParameters(theMethod: any) {
var getRowsParams = _.getFunctionParameters(theMethod);
if (getRowsParams.length > 0) {
console.warn('ag-grid: It looks like your filter is of the old type and expecting parameters in the constructor.');
console.warn('ag-grid: From ag-grid 1.14, the constructor should take no parameters and init() used instead.');
}
}
public showFilter(column: Column, eventSource: any) {
var filterWrapper = this.getOrCreateFilterWrapper(column);
// need to show filter before positioning, as only after filter
// is visible can we find out what the width of it is
var hidePopup = this.popupService.addAsModalPopup(filterWrapper.gui, true);
this.popupService.positionPopup(eventSource, filterWrapper.gui, true);
if (filterWrapper.filter.afterGuiAttached) {
var params = {
hidePopup: hidePopup,
eventSource: eventSource
};
filterWrapper.filter.afterGuiAttached(params);
}
}
}
}
| mit |
tjuscs/english | src/com/demo/biz/interceptors/TeacherAuthInterceptor.java | 627 | package com.demo.biz.interceptors;
import com.demo.biz.teacher.TeacherController;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
/**
* Created by YanZ on 16/10/4.
*/
public class TeacherAuthInterceptor implements Interceptor {
@Override
public void intercept(Invocation inv) {
Controller controller = inv.getController();
Object sessionAttr = controller.getSessionAttr(TeacherController.TEACHER_KEY);
if (sessionAttr != null) {
inv.invoke();
} else {
controller.render("login.ftl");
}
}
}
| mit |
leonardoporro/Detached | src/Detached/Model/Types/Dictionary/DictionaryOptionsFactory.cs | 697 | using AgileObjects.ReadableExpressions.Extensions;
using Detached.Reflection;
using System;
namespace Detached.Model.Types.Dictionary
{
public class DictionaryOptionsFactory : ITypeOptionsFactory
{
readonly DictionaryTypeOptions _typeOptions = new DictionaryTypeOptions();
public ITypeOptions Create(MapperModelOptions options, Type type)
{
ITypeOptions result = null;
if (type.IsDictionary(out Type keyType, out Type valueType)
&& keyType == typeof(string)
&& valueType == typeof(object))
{
result = _typeOptions;
}
return result;
}
}
} | mit |
robotdongs/robotdongs.github.io | rsvp.js | 3433 |
//Builds the overlay to show the RSVP form. Could be a seperate web page but this was more fun.
$(document).ready(function(){
buildRSVP();
$('#cancel').click(function(){
ccForm();
})
$("#sbmtBtn").click(function(){
validate();
})
});
function buildRSVP(){
var i, div, fc, x, y, iNames, input, lbls, label, form
var btn, clr, sbmt, form
var f = '<form id=rsvpForm></form>'
form = $(f).attr('onsubmit',"return validate()");
div = '<div></div>'
input = '<input required="Yes">'
label = '<label></label>'
fc = $(div).attr('class','float-container');
fc.hide();
//Id values of input fields and labels
iNames = ["fname", "lName","phone","email"];
//label text for inputs
lbls = ["First Name", "Last Name", "Phone Number", "Email"]
$('body').append(fc);
fc.append(form);
//Builds and Adds inpout and label Elements
for (var i = 0; i < iNames.length; i++) {
x = $(input).attr('class','inputField');
x.attr('name',iNames[i]);
y = $(label).attr('class','inputLabel');
y.attr('id',iNames[i]);
y.text(lbls[i]);
$('#rsvpForm').append(y);
$('#rsvpForm').append(x);
} //end for loop
//build button holder
var btnHolder = $(div).attr('id','buttonHolder');
$('#rsvpForm').append(btnHolder);
//create template button
var btn = '<button></button>';
//Create clear button
clr = $(btn).attr('type','reset');
clr.attr('id','clrBtn'); clr.attr('value','Clear');
clr.text('Clear');
sbmt = $(btn).attr('type','button');
sbmt.attr('value','submit'); sbmt.attr('id','sbmtBtn');
sbmt.text('Submit');
//add clear buttons to button holder
$('#buttonHolder').append(clr);
$('#buttonHolder').append(sbmt);
$('#rsvpForm').prepend('<button id="cancel" name="cancel" type="button" style="align-self: flex-end;">x</button>')
}
//clear and cancel form.
function ccForm(){
var arrInputs = $("label~input");
for (var i = 0; i < arrInputs.length; i++) {
arrInputs[i].value = "";
}
$(".float-container").hide();
}
function showRSVP(){
$(".float-container").fadeIn(500);
}
function validate(){
var inputArray, i, reg, booMatch, s,
inputArray = $('.inputField');
for (i = 0; i < inputArray.length;i++){
var y = inputArray[i].value
var z = inputArray[i].name
if (z == "fname" | z == "lname") {
var ltrsOnly = new RegExp(/[0-9~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?@]/);
if (ltrsOnly.test(y)) {
alert("Invalid Entry");
inputArray[i].focus();
break;
}
submit();
}else if (z == "phone"){
var numOnly = new RegExp(/[A-z~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?@]/);
if (numOnly.test(y)){
alert("Invalid Entry");
inputArray[i].focus();
break;
}
submit();
}else if (z == "email"){
var e = new RegExp(/[@]/);
alert(e.test(y));
if(e.test(y) == true){
submit();
}else {
inputArray[i].focus();
break;
}
}
}
}
function submit(){
//I actually won't have an RSVP form on my final site, so I didn't write any server side scripts.
//but we can pretend that this is a php or ASPx
ccForm();
}
| mit |
afreewill333/PAT-Basic-Level-PractiseCode | PAT1011.java | 496 | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for(int i=1;i<=T;i++)
{
BigDecimal A,B,C;
A = in.nextBigDecimal();
B = in.nextBigDecimal();
C = in.nextBigDecimal();
System.out.print("Case #"+i+": ");
if(A.add(B).compareTo(C)>0)
System.out.println("true");
else
System.out.println("false");
}
}
} | mit |
depsir/motorcontrolboard | lib/motorcontrolboard/mcb_connection.rb | 2602 | #!/usr/bin/env ruby
require "serialport"
class MotorControlBoard
# Descriptor of the vid/pid of the board. Something like '10c4:ea60'.
# Can be obtained through a command like 'lsusb'.
#
# Setting this variable allow to discover the port where the board is conencted automatically
attr_accessor :vidpid
# String describing the port where the board is connected.
# Usually is something like '/dev/ttyUSB0'. Can be auto-discovered, setting the #vidpid variable if the vid:pid of the board is known
attr_accessor :port
# Baud rate of the connection. In the actual firmware version it should be 57600
attr_accessor :baud_rate
# attr_reader :sp
# Shortcut to set a '/dev/ttyUSBx' port. It also connects to that port
#
# Params:
# +num+:: number of the ttyUSB port to be set
def setPort(num)
@port = '/dev/ttyUSB' + num.to_s
connect
end
# Connect to serial port specified by @port member
#
# If @vidpid is set, it checks if that device is connected to a serial port and that port is chosen, regardless of the @port value.
# If block given it closes the connection at the end of the block
def connect
if findPort()
puts "Automatically selected port #{@port}"
end
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
begin
@sp = SerialPort.new(@port, @baud_rate, data_bits, stop_bits, parity)
@open = true
rescue
puts 'ERROR: Unable to find serial port ' + @port
@open = false
end
if block_given?
yield
self.disconnect
p "port closed"
end
@open
end
# Disconnect from serial port
def disconnect
if @open
@open = false
@sp.close
end
end
# Find the port to which the board is connected, looking for the specified @vidpid
def findPort
begin
if @vidpid
busNumber = Integer(`lsusb|grep #{@vidpid}`[4..6])
port = `ls /sys/bus/usb-serial/devices/ -ltrah |grep usb#{busNumber}`.chop
@port = '/dev/'+port.gsub(/ttyUSB[0-9]+/).first
else
false
end
rescue
false
end
end
# Send a single char
def sendC(char)
if (!@open)
connect()
end
@sp.putc char.chr
end
# Send a string of char
def sendS(string)
string.each_char do |char|
sendC(char)
end
end
def startByte()
sendC(0x55)
sleep 0.1
end
end
| mit |
amecky/breakout | TMP/MainGameState.cpp | 9673 | #include "MainGameState.h"
#include <core\log\Log.h>
#include "..\Constants.h"
#include <core\math\Bitset.h>
#include <core\io\FileRepository.h>
#include "..\WarpingGrid.h"
MainGameState::MainGameState(GameContext* context) : ds::GameState("MainGameState") , _context(context) {
_paddle = (Paddle*)ds::game::get_game_object(SID("Paddle"));
_ball = (Ball*)ds::game::get_game_object(SID("Ball"));
_bricks = (Bricks*)ds::game::get_game_object(SID("Bricks"));
_indicator = (DirectionIndicator*)ds::game::get_game_object(SID("DirectionIndicator"));
_messages = (Messages*)ds::game::get_game_object(SID("Messages"));
_hud = (HUD*)ds::game::get_game_object(SID("HUD"));
_sticky = false;
_numBricks = 0;
_killedBricks = 0;
_level = 0;
}
// -------------------------------------------------------
// destructor
// -------------------------------------------------------
MainGameState::~MainGameState(void) {
}
// -------------------------------------------------------
// activate
// -------------------------------------------------------
void MainGameState::activate() {
_sticky = false;
_paddle->activate();
_bricks->activate();
_killedBricks = 0;
_messages->showLevel(1);
_messages->activate();
_hud->activate();
_hud->setLevel(1);
//_hud->addScore(1234);
_running = false;
}
// -------------------------------------------------------
// restart game
// -------------------------------------------------------
void MainGameState::restart() {
setSticky();
//_grid->clear();
//_grid->buildLevel(0);
}
// -------------------------------------------------------
// on button up
// -------------------------------------------------------
int MainGameState::onButtonUp(int button, int x, int y) {
if (_sticky) {
_ball->start(_indicator->getAngle());
_indicator->deactivate();
_sticky = false;
}
return 0;
}
// -------------------------------------------------------
// update
// -------------------------------------------------------
int MainGameState::update(float dt) {
_context->world->tick(dt);
_hud->tick(dt);
if (_running) {
if (_sticky) {
v3 p = _context->world->getPosition(_paddle->getID());
p.y += 30;
_context->world->setPosition(_ball->getID(), p);
}
else {
v3 p = _context->world->getPosition(_ball->getID());
if (p.y < 60.0f) {
setSticky();
}
handleCollisions(dt);
}
}
if (ds::events::containsType(MESSAGE_DISPLAYED)) {
_numBricks = _bricks->setLevel(_level);
}
if (ds::events::containsType(BRICKS_MOVED)) {
_messages->deactivate();
_running = true;
_ball->activate();
setSticky();
}
return 0;
}
// -------------------------------------------------------
// handle collisions
// -------------------------------------------------------
void MainGameState::handleCollisions(float dt) {
int num = _context->world->numCollisions();
if (num > 0) {
LOG << "collisions: " << num;
for (int i = 0; i < num; ++i) {
ZoneTracker z1("MainGameState:collision");
const ds::Collision& c = _context->world->getCollision(i);
if (c.isBetween(OT_PLAYER, OT_BALL)) {
//FIXME: push ball away
_ball->bounceY();
}
else if (c.isBetween(OT_BRICK, OT_BALL)) {
v3 bp = _context->world->getPosition(c.getIDByType(OT_BRICK));
v3 pp = _context->world->getPosition(c.getIDByType(OT_BALL));
// http://gamedev.stackexchange.com/questions/29786/a-simple-2d-rectangle-collision-algorithm-that-also-determines-which-sides-that
float w = 0.5 * (100.0f + 18.0f);
float h = 0.5 * (30.0f + 18.0f);
float dx = bp.x - pp.x;
float dy = bp.y - pp.y;
if (abs(dx) <= w && abs(dy) <= h) {
float wy = w * dy;
float hx = h * dx;
LOG << "dx: " << dx << " dy: " << dy << " wy: " << wy << " hx: " << hx;
if (wy > hx) {
if (wy > -hx) {
LOG << "BOTTOM";
_ball->bounceY();
}
else {
LOG << "LEFT";
_ball->bounceX();
}
}
else {
if (wy > -hx) {
LOG << "RIGHT";
_ball->bounceX();
}
else {
LOG << "TOP";
_ball->bounceY();
}
}
}
_context->grid->applyForce(pp.xy(), 0.3f, 5.0f, 40.0f);
if (_bricks->handleCollision(c.getIDByType(OT_BRICK))) {
_context->world->remove(c.getIDByType(OT_BRICK));
_context->particles->start(2, bp.xy());
++_killedBricks;
if (_killedBricks == _numBricks) {
LOG << "we are done - NEXT LEVEL!";
}
}
}
}
}
/*
// collisions
int numCollisions = _world->getNumCollisions();
if (numCollisions > 0) {
LOG << "--------------- num: " << numCollisions;
for (int i = 0; i < numCollisions; ++i) {
ZoneTracker z1("MainGameState:collision");
const ds::Collision& c = _world->getCollision(i);
if (c.containsType(OT_LEFT_WALL) && c.containsType(OT_BALL)) {
ds::SID bid = c.getSIDByType(OT_LEFT_WALL);
_world->bounce(_ball_id, ds::BD_X, dt);
_world->startBehavior(bid, "wall_impact");
_world->startBehavior(_ball_id, "ball_impact");
v2 ballPos = _world->getPosition(_ball_id);
ballPos.x = LEFT_WALL_POS.x + 26.0f;
_world->setPosition(_ball_id, ballPos);
}
else if (c.containsType(OT_RIGHT_WALL) && c.containsType(OT_BALL)) {
ds::SID bid = c.getSIDByType(OT_RIGHT_WALL);
_world->bounce(_ball_id, ds::BD_X, dt);
_world->startBehavior(bid, "wall_impact");
_world->startBehavior(_ball_id, "ball_impact");
v2 ballPos = _world->getPosition(_ball_id);
ballPos.x = RIGHT_WALL_POS.x - 26.0f;
_world->setPosition(_ball_id, ballPos);
}
else if (c.containsType(OT_TOP_WALL) && c.containsType(OT_BALL)) {
ds::SID bid = c.getSIDByType(OT_TOP_WALL);
_world->startBehavior(bid, "top_wall_impact");
_world->bounce(_ball_id, ds::BD_Y, dt);
_world->startBehavior(_ball_id, "ball_impact");
v2 ballPos = _world->getPosition(_ball_id);
ballPos.y = TOP_WALL_POS.y - 16.0f;
_world->setPosition(_ball_id, ballPos);
}
else if (c.containsType(OT_PLAYER) && c.containsType(OT_BALL)) {
handleBallPlayerCollision();
}
else if (c.containsType(OT_BALL) && c.containsType(OT_BRICK)) {
ds::SID bid = c.getSIDByType(OT_BRICK);
int ret = ds::physics::testLineBox(_world->getPosition(_ball_id), _world->getPosition(bid), v2(60, 30));
/*
v2 bp = _world->getPosition(bid);
v2 pp = _world->getPosition(_ball_id);
// http://gamedev.stackexchange.com/questions/29786/a-simple-2d-rectangle-collision-algorithm-that-also-determines-which-sides-that
float w = 0.5 * (120.0f + 18.0f);
float h = 0.5 * (30.0f + 18.0f);
float dx = bp.x - pp.x;
float dy = bp.y - pp.y;
if (abs(dx) <= w && abs(dy) <= h) {
float wy = w * dy;
float hx = h * dx;
LOG << "dx: " << dx << " dy: " << dy << " wy: " << wy << " hx: " << hx;
if (wy > hx) {
if (wy > -hx) {
LOG << "BOTTOM";
}
else {
LOG << "LEFT";
}
}
else {
if (wy > -hx) {
LOG << "RIGHT";
}
else {
LOG << "TOP";
}
}
}
LOG << "RET: " << ret;// << " brick: " << DBG_V2(bp) << " ball: " << DBG_V2(pp);
if (ds::bit::is_set(ret, 0) || ds::bit::is_set(ret, 2)) {
_world->bounce(_ball_id, ds::BD_Y, dt);
}
if (ds::bit::is_set(ret, 1) || ds::bit::is_set(ret, 3)) {
_world->bounce(_ball_id, ds::BD_X, dt);
}
int hit = _grid->handleHit(c.getSIDByType(OT_BRICK));
if (hit > 0) {
_context->particles->start(PST_BRICK_EXPLOSION, _world->getPosition(bid));
_world->remove(bid);
}
else {
_world->startBehavior(_ball_id, "ball_impact");
}
}
}
}
*/
}
// -------------------------------------------------------
// ball player collision
// -------------------------------------------------------
void MainGameState::handleBallPlayerCollision() {
/*
v2 pp = _world->getPosition(_player_id);
v2 bp = _world->getPosition(_ball_id);
v2 diff = bp - pp;
float xdir = 1.0f + diff.x / 60.0f;
float angle = DEGTORAD(135.0f) - xdir * DEGTORAD(45.0f);
_world->stopAction(_ball_id, ds::AT_MOVE_BY);
_world->moveBy(_ball_id, ds::vector::getRadialVelocity(angle, 500.0f));
bp.y = 95.0f;
_world->setPosition(_ball_id, bp);
_world->startBehavior(_ball_id, "wiggle_scale");
_world->startBehavior(_player_id, "wiggle_player");
*/
}
// -------------------------------------------------------
// render
// -------------------------------------------------------
void MainGameState::render() {
}
// -------------------------------------------------------
// set sticky
// -------------------------------------------------------
void MainGameState::setSticky() {
if (!_sticky) {
_sticky = true;
_indicator->activate();
_ball->setMoving(false);
}
}
// -------------------------------------------------------
// on char
// -------------------------------------------------------
int MainGameState::onChar(int ascii) {
if (ascii == 's') {
setSticky();
}
if (ascii == 't') {
_ball->start(_indicator->getAngle());
_indicator->deactivate();
_sticky = false;
}
if (ascii == 'r') {
_context->particles->start(1, v2(512, 384));
}
if (ascii == 'n') {
_bricks->setLevel(0);
}
if (ascii == '1') {
_hud->addScore(20);
}
if (ascii == '2') {
_hud->addScore(50);
}
if (ascii == '3') {
_hud->addScore(100);
}
/*
if (ascii == 'd') {
_showPanel = !_showPanel;
}
if (ascii == 'e') {
_world->startBehavior(_ball_id, "ball_impact");
}
if (ascii == 'g') {
if (_effect->isActive()) {
_effect->deactivate();
}
else {
_effect->activate();
}
}
if (ascii == 'q') {
_grid->moveDown();
_grid->createNewLine(4);
}
if (ascii == 'w') {
_grid->createNewLine(3);
}
*/
return 0;
}
| mit |
Eptwalabha/shmup | MysteryBazookaDisaster/src/main/java/src/components/Friction.java | 421 | package src.components;
import com.artemis.Component;
/**
* User: Eptwalabha
* Date: 07/02/14
* Time: 14:53
*/
public class Friction extends Component {
private float friction;
public Friction(float friction) {
this.friction = friction;
}
public float getFriction() {
return friction;
}
public void setFriction(float friction) {
this.friction = friction;
}
}
| mit |
fcc-joemcintyre/pinster | app/client/src/lib/Form/FormFieldGroup.js | 111 | import styled from 'styled-components';
export const FormFieldGroup = styled.div`
display: inline-block;
`;
| mit |
bzquan/GherkinEditor | GherkinEditor/ReoGrid/Utility/ZipFileArchive.cs | 11276 | /*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* http://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* This software released under LGPLv3 license.
*
* Author: Jing Lu <lujing at unvell.com>
* Contributors: Rick Meyer
*
* Copyright (c) 2012-2016 unvell.com, All rights reserved.
* Copyright (c) 2014 Rick Meyer, All rights reserved.
*
****************************************************************************/
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
namespace unvell.ReoGrid.Utility
{
internal interface IZipArchive
{
IZipEntry GetFile(string path);
IZipEntry AddFile(string path, Stream stream = null);
bool IsFileExist(string path);
void Flush();
void Close();
}
internal interface IZipEntry
{
Stream GetStream();
Stream CreateStream();
}
internal class NET35ZipArchive : IZipArchive, IDisposable
{
internal object external;
public enum CompressionMethodEnum { Stored, Deflated };
public enum DeflateOptionEnum { Normal, Maximum, Fast, SuperFast };
internal static CachedTypeWrapper zipArchiveWrapper;
internal static Type msCompressionMethodEnumType;
internal static Type msDeflateOptionEnumType;
public NET35ZipFileEntry AddFile(string path,
CompressionMethodEnum compmeth = CompressionMethodEnum.Deflated,
DeflateOptionEnum option = DeflateOptionEnum.Normal)
{
var comp = msCompressionMethodEnumType.GetField(compmeth.ToString()).GetValue(null);
var opti = msDeflateOptionEnumType.GetField(option.ToString()).GetValue(null);
return new NET35ZipFileEntry(zipArchiveWrapper.Invoke(this.external, "AddFile", path, comp, opti));
}
public IZipEntry AddFile(string path, Stream stream = null)
{
return this.AddFile(path, CompressionMethodEnum.Deflated, DeflateOptionEnum.Normal);
}
public void DeleteFile(string name)
{
zipArchiveWrapper.StaticInvoke("DeleteFile", external, name);
}
public void Dispose()
{
((IDisposable)external).Dispose();
}
public bool IsFileExist(string path)
{
return (bool)zipArchiveWrapper.Invoke(this.external, "FileExists", path);
}
public IZipEntry GetFile(string path)
{
if (path.StartsWith("/"))
{
path = path.Substring(1);
}
return new NET35ZipFileEntry(zipArchiveWrapper.Invoke(this.external, "GetFile", path));
}
public IEnumerable<NET35ZipFileEntry> Files
{
get
{
var coll = zipArchiveWrapper.Invoke(external, "GetFiles") as System.Collections.IEnumerable; //ZipFileInfoCollection
if (coll != null)
{
foreach (var p in coll)
{
yield return new NET35ZipFileEntry(p);
}
}
}
}
public IEnumerable<string> FileNames
{
get { return Files.Select(p => p.Name).OrderBy(p => p); }
}
public void Flush()
{
zipArchiveWrapper.Invoke(this.external, "Flush");
}
public void Close()
{
zipArchiveWrapper.Invoke(this.external, "Close");
}
}
#if WINFORM || WPF
/// <summary>
/// Original Document: http://www.codeproject.com/Articles/209731/Csharp-use-Zip-archives-without-external-libraries
/// </summary>
internal class NET35ZipArchiveFactory
{
// prevent construct from outside
private NET35ZipArchiveFactory() { }
static NET35ZipArchiveFactory()
{
Type msZipArchiveType = typeof(System.IO.Packaging.Package).Assembly.GetType("MS.Internal.IO.Zip.ZipArchive");
NET35ZipArchive.zipArchiveWrapper = new CachedTypeWrapper(msZipArchiveType);
NET35ZipArchive.msCompressionMethodEnumType = msZipArchiveType.Assembly.GetType("MS.Internal.IO.Zip.CompressionMethodEnum");
NET35ZipArchive.msDeflateOptionEnumType = msZipArchiveType.Assembly.GetType("MS.Internal.IO.Zip.DeflateOptionEnum");
}
public static IZipArchive OpenOnFile(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read,
FileShare share = FileShare.Read, bool streaming = false)
{
return new NET35ZipArchive
{
external = NET35ZipArchive.zipArchiveWrapper.StaticInvoke("OpenOnFile", path, mode, access, share, streaming),
};
}
public static IZipArchive OpenOnStream(Stream stream, FileMode mode = FileMode.Open,
FileAccess access = FileAccess.Read, bool streaming = false)
{
return new NET35ZipArchive
{
external = NET35ZipArchive.zipArchiveWrapper.StaticInvoke("OpenOnStream", stream, mode, access, streaming),
};
}
}
#endif // WINFORM || WPF
internal class MZipArchiveFactory
{
public static IZipArchive OpenOnStream(Stream stream)
{
return MZipArchive.OpenOnStream(stream);
}
public static IZipArchive CreateOnStream(Stream stream)
{
return MZipArchive.CreateOnStream(stream);
}
}
internal class MZipArchive : IZipArchive
{
private ZipFile zip;
private Stream stream;
private MZipArchive()
{
}
internal static MZipArchive OpenOnStream(Stream stream)
{
return new MZipArchive()
{
zip = ZipFile.Read(stream),
stream = stream,
};
}
internal static MZipArchive CreateOnStream(Stream stream)
{
var mzip = new MZipArchive()
{
zip = new ZipFile(),
stream = stream,
};
return mzip;
}
public IZipEntry GetFile(string path)
{
var entry = zip.SingleOrDefault(e => e.FileName == path);
if (entry == null) return null;
return new MZipEntry(entry);
}
public IZipEntry AddFile(string path, Stream stream)
{
return new MZipEntry(zip.AddEntry(path, stream));
}
public bool IsFileExist(string path)
{
return zip.Any(entry => entry.FileName == path);
}
public void Flush()
{
zip.Save(this.stream);
}
public void Close()
{
zip.Dispose();
}
}
internal class MZipEntry : IZipEntry
{
private ZipEntry entry;
internal MZipEntry(ZipEntry entry)
{
this.entry = entry;
}
public Stream CreateStream()
{
return null;
}
public Stream GetStream()
{
var ms = new MemoryStream();
entry.Extract(ms);
ms.Position = 0;
return ms;
}
}
internal class NET35ZipFileEntry : IZipEntry
{
static CachedTypeWrapper zipEntry = null;
private object external;
internal NET35ZipFileEntry(object external)
{
if (zipEntry == null)
{
zipEntry = new CachedTypeWrapper(external.GetType());
}
this.external = external;
}
private object GetProperty(string name)
{
return zipEntry.GetProperty(this.external, name);
}
private void SetProperty(string name, object value)
{
zipEntry.SetProperty(this.external, name, value);
}
public override string ToString()
{
return Name;// base.ToString();
}
public string Name
{
get { return (string)GetProperty("Name"); }
}
public DateTime LastModFileDateTime
{
get { return (DateTime)GetProperty("LastModFileDateTime"); }
}
public bool FolderFlag
{
get { return (bool)GetProperty("FolderFlag"); }
}
public bool VolumeLabelFlag
{
get { return (bool)GetProperty("VolumeLabelFlag"); }
}
public object CompressionMethod
{
get { return GetProperty("CompressionMethod"); }
set { SetProperty("CompressionMethod", value); }
}
public object DeflateOption
{
get { return GetProperty("DeflateOption"); }
}
public Stream GetStream(FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read)
{
return zipEntry.Invoke(this.external, "GetStream", mode, access) as Stream;
}
public Stream GetStream()
{
return GetStream(FileMode.Open, FileAccess.Read) as Stream;
}
public Stream CreateStream()
{
return GetStream(FileMode.Create, FileAccess.Write) as Stream;
}
}
internal class CachedTypeWrapper
{
public Type Type { get; private set; }
private Dictionary<string, MethodInfo> cachedMethods = new Dictionary<string, MethodInfo>();
private Dictionary<string, PropertyInfo> cachedProperties = new Dictionary<string, PropertyInfo>();
public CachedTypeWrapper(Type type)
{
this.Type = type;
}
public object StaticInvoke(string name, params object[] args)
{
return Invoke(null, name, args);
}
public object Invoke(object instance, string name, params object[] args)
{
MethodInfo mi = null;
if (!this.cachedMethods.TryGetValue(name, out mi))
{
mi = this.Type.GetMethod(name,
(instance == null ? BindingFlags.Static : BindingFlags.Instance) | BindingFlags.NonPublic);
}
return mi == null ? null : mi.Invoke(instance, args);
}
public object GetProperty(object instance, string name)
{
PropertyInfo pi = null;
if (!this.cachedProperties.TryGetValue(name, out pi))
{
pi = this.Type.GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic);
this.cachedProperties[name] = pi;
}
return pi == null ? null : pi.GetValue(instance, null);
}
public void SetProperty(object instance, string name, object value)
{
PropertyInfo pi = null;
if (!this.cachedProperties.TryGetValue(name, out pi))
{
pi = this.Type.GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic);
this.cachedProperties[name] = pi;
}
if (pi != null)
{
pi.SetValue(instance, name, null);
}
}
}
/// <summary>
/// Helper class for compress and decompress zip stream
/// </summary>
/// <remarks>Provided by Rick Meyer</remarks>
public class ZipStreamHelper
{
/// <summary>
/// Decompress a byte array
/// </summary>
/// <param name="zippedData">Compressed Byte Array</param>
/// <returns>Decompressed Byte Array</returns>
public static byte[] Decompress(byte[] zippedData)
{
using (var outputStream = new MemoryStream())
{
using (var inputStream = new MemoryStream(zippedData))
{
using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
{
//zip.CopyTo(outputStream); // cannot be used in .NET 3.5
int readBytes = 0;
byte[] buf = new byte[4096];
while ((readBytes = zip.Read(buf, 0, buf.Length)) > 0)
{
outputStream.Write(buf, 0, readBytes);
}
return outputStream.ToArray();
}
}
}
}
/// <summary>
/// Compress a byte Array using Gzip
/// </summary>
/// <param name="plainData">The byte array to compress</param>
/// <returns>Returns a compressed byte array</returns>
public static byte[] Compress(byte[] plainData)
{
if (plainData == null) throw new ArgumentNullException("Tried to compress null byte array - can't get smaller than zero!");
byte[] compressesData = null;
using (var outputStream = new MemoryStream())
{
using (var zip = new GZipStream(outputStream, CompressionMode.Compress))
{
zip.Write(plainData, 0, plainData.Length);
}
//Dont get the MemoryStream data before the GZipStream is closed
//since it doesn’t yet contain complete compressed data.
//GZipStream writes additional data including footer information when its been disposed
compressesData = outputStream.ToArray();
}
return compressesData;
}
}
}
| mit |
NikiStanchev/SoftUni | AngularFundamentals/Angular2/Redux/node_modules/@angular/cli/commands/serve.js | 4602 | "use strict";
const denodeify = require('denodeify');
const build_1 = require('./build');
const config_1 = require('../models/config');
const version_1 = require('../upgrade/version');
const SilentError = require('silent-error');
const PortFinder = require('portfinder');
const Command = require('../ember-cli/lib/models/command');
const getPort = denodeify(PortFinder.getPort);
PortFinder.basePort = 49152;
const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal();
const defaultPort = process.env.PORT || config.get('defaults.serve.port');
const defaultHost = config.get('defaults.serve.host');
// Expose options unrelated to live-reload to other commands that need to run serve
exports.baseServeCommandOptions = build_1.baseBuildCommandOptions.concat([
{ name: 'port', type: Number, default: defaultPort, aliases: ['p'] },
{
name: 'host',
type: String,
default: defaultHost,
aliases: ['H'],
description: `Listens only on ${defaultHost} by default`
},
{ name: 'proxy-config', type: 'Path', aliases: ['pc'] },
{ name: 'ssl', type: Boolean, default: false },
{ name: 'ssl-key', type: String, default: 'ssl/server.key' },
{ name: 'ssl-cert', type: String, default: 'ssl/server.crt' },
{
name: 'open',
type: Boolean,
default: false,
aliases: ['o'],
description: 'Opens the url in default browser',
}
]);
const ServeCommand = Command.extend({
name: 'serve',
description: 'Builds and serves your app, rebuilding on file changes.',
aliases: ['server', 's'],
availableOptions: exports.baseServeCommandOptions.concat([
{ name: 'live-reload', type: Boolean, default: true, aliases: ['lr'] },
{
name: 'live-reload-host',
type: String,
aliases: ['lrh'],
description: 'Defaults to host'
},
{
name: 'live-reload-base-url',
type: String,
aliases: ['lrbu'],
description: 'Defaults to baseURL'
},
{
name: 'live-reload-port',
type: Number,
aliases: ['lrp'],
description: '(Defaults to port number within [49152...65535])'
},
{
name: 'live-reload-live-css',
type: Boolean,
default: true,
description: 'Whether to live reload CSS (default true)'
},
{
name: 'hmr',
type: Boolean,
default: false,
description: 'Enable hot module replacement',
}
]),
run: function (commandOptions) {
const ServeTask = require('../tasks/serve').default;
version_1.Version.assertAngularVersionIs2_3_1OrHigher(this.project.root);
commandOptions.liveReloadHost = commandOptions.liveReloadHost || commandOptions.host;
return checkExpressPort(commandOptions)
.then(() => autoFindLiveReloadPort(commandOptions))
.then((opts) => {
const serve = new ServeTask({
ui: this.ui,
project: this.project,
});
return serve.run(opts);
});
}
});
function checkExpressPort(commandOptions) {
return getPort({ port: commandOptions.port, host: commandOptions.host })
.then((foundPort) => {
if (commandOptions.port !== foundPort && commandOptions.port !== 0) {
throw new SilentError(`Port ${commandOptions.port} is already in use. Use '--port' to specify a different port.`);
}
// otherwise, our found port is good
commandOptions.port = foundPort;
return commandOptions;
});
}
function autoFindLiveReloadPort(commandOptions) {
return getPort({ port: commandOptions.liveReloadPort, host: commandOptions.liveReloadHost })
.then((foundPort) => {
// if live reload port matches express port, try one higher
if (foundPort === commandOptions.port) {
commandOptions.liveReloadPort = foundPort + 1;
return autoFindLiveReloadPort(commandOptions);
}
// port was already open
if (foundPort === commandOptions.liveReloadPort) {
return commandOptions;
}
// use found port as live reload port
commandOptions.liveReloadPort = foundPort;
return commandOptions;
});
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ServeCommand;
//# sourceMappingURL=/Users/hansl/Sources/angular-cli/packages/@angular/cli/commands/serve.js.map | mit |
planbcoin/planbcoin | test/functional/decodescript.py | 13471 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The PlanBcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test decoding scripts via decodescript RPC command."""
from test_framework.test_framework import PlanbcoinTestFramework
from test_framework.util import *
from test_framework.mininode import *
from io import BytesIO
class DecodeScriptTest(PlanbcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
def decodescript_script_sig(self):
signature = '304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
push_signature = '48' + signature
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
# below are test cases for all of the standard transaction types
# 1) P2PK scriptSig
# the scriptSig of a public key scriptPubKey simply pushes a signature onto the stack
rpc_result = self.nodes[0].decodescript(push_signature)
assert_equal(signature, rpc_result['asm'])
# 2) P2PKH scriptSig
rpc_result = self.nodes[0].decodescript(push_signature + push_public_key)
assert_equal(signature + ' ' + public_key, rpc_result['asm'])
# 3) multisig scriptSig
# this also tests the leading portion of a P2SH multisig scriptSig
# OP_0 <A sig> <B sig>
rpc_result = self.nodes[0].decodescript('00' + push_signature + push_signature)
assert_equal('0 ' + signature + ' ' + signature, rpc_result['asm'])
# 4) P2SH scriptSig
# an empty P2SH redeemScript is valid and makes for a very simple test case.
# thus, such a spending scriptSig would just need to pass the outer redeemScript
# hash test and leave true on the top of the stack.
rpc_result = self.nodes[0].decodescript('5100')
assert_equal('1 0', rpc_result['asm'])
# 5) null data scriptSig - no such thing because null data scripts can not be spent.
# thus, no test case for that standard transaction type is here.
def decodescript_script_pub_key(self):
public_key = '03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2'
push_public_key = '21' + public_key
public_key_hash = '11695b6cd891484c2d49ec5aa738ec2b2f897777'
push_public_key_hash = '14' + public_key_hash
# below are test cases for all of the standard transaction types
# 1) P2PK scriptPubKey
# <pubkey> OP_CHECKSIG
rpc_result = self.nodes[0].decodescript(push_public_key + 'ac')
assert_equal(public_key + ' OP_CHECKSIG', rpc_result['asm'])
# 2) P2PKH scriptPubKey
# OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
rpc_result = self.nodes[0].decodescript('76a9' + push_public_key_hash + '88ac')
assert_equal('OP_DUP OP_HASH160 ' + public_key_hash + ' OP_EQUALVERIFY OP_CHECKSIG', rpc_result['asm'])
# 3) multisig scriptPubKey
# <m> <A pubkey> <B pubkey> <C pubkey> <n> OP_CHECKMULTISIG
# just imagine that the pub keys used below are different.
# for our purposes here it does not matter that they are the same even though it is unrealistic.
rpc_result = self.nodes[0].decodescript('52' + push_public_key + push_public_key + push_public_key + '53ae')
assert_equal('2 ' + public_key + ' ' + public_key + ' ' + public_key + ' 3 OP_CHECKMULTISIG', rpc_result['asm'])
# 4) P2SH scriptPubKey
# OP_HASH160 <Hash160(redeemScript)> OP_EQUAL.
# push_public_key_hash here should actually be the hash of a redeem script.
# but this works the same for purposes of this test.
rpc_result = self.nodes[0].decodescript('a9' + push_public_key_hash + '87')
assert_equal('OP_HASH160 ' + public_key_hash + ' OP_EQUAL', rpc_result['asm'])
# 5) null data scriptPubKey
# use a signature look-alike here to make sure that we do not decode random data as a signature.
# this matters if/when signature sighash decoding comes along.
# would want to make sure that no such decoding takes place in this case.
signature_imposter = '48304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c509001'
# OP_RETURN <data>
rpc_result = self.nodes[0].decodescript('6a' + signature_imposter)
assert_equal('OP_RETURN ' + signature_imposter[2:], rpc_result['asm'])
# 6) a CLTV redeem script. redeem scripts are in-effect scriptPubKey scripts, so adding a test here.
# OP_NOP2 is also known as OP_CHECKLOCKTIMEVERIFY.
# just imagine that the pub keys used below are different.
# for our purposes here it does not matter that they are the same even though it is unrealistic.
#
# OP_IF
# <receiver-pubkey> OP_CHECKSIGVERIFY
# OP_ELSE
# <lock-until> OP_CHECKLOCKTIMEVERIFY OP_DROP
# OP_ENDIF
# <sender-pubkey> OP_CHECKSIG
#
# lock until block 500,000
rpc_result = self.nodes[0].decodescript('63' + push_public_key + 'ad670320a107b17568' + push_public_key + 'ac')
assert_equal('OP_IF ' + public_key + ' OP_CHECKSIGVERIFY OP_ELSE 500000 OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF ' + public_key + ' OP_CHECKSIG', rpc_result['asm'])
def decoderawtransaction_asm_sighashtype(self):
"""Test decoding scripts via RPC command "decoderawtransaction".
This test is in with the "decodescript" tests because they are testing the same "asm" script decodes.
"""
# this test case uses a random plain vanilla mainnet transaction with a single P2PKH input and output
tx = '0100000001696a20784a2c70143f634e95227dbdfdf0ecd51647052e70854512235f5986ca010000008a47304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb014104d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536ffffffff0100e1f505000000001976a914eb6c6e0cdb2d256a32d97b8df1fc75d1920d9bca88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb[ALL] 04d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536', rpc_result['vin'][0]['scriptSig']['asm'])
# this test case uses a mainnet transaction that has a P2SH input and both P2PKH and P2SH outputs.
# it's from James D'Angelo's awesome introductory videos about multisig: https://www.youtube.com/watch?v=zIbUSaZBJgU and https://www.youtube.com/watch?v=OSA1pwlaypc
# verify that we have not altered scriptPubKey decoding.
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914dc863734a218bfe83ef770ee9d41a27f824a6e5688acee2a02000000000017a9142a5edea39971049a540474c6a99edf0aa4074c588700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('8e3730608c3b0bb5df54f09076e196bc292a8e39a78e73b44b6ba08c78f5cbb0', rpc_result['txid'])
assert_equal('0 3045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea[ALL] 3045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75[ALL] 5221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53ae', rpc_result['vin'][0]['scriptSig']['asm'])
assert_equal('OP_DUP OP_HASH160 dc863734a218bfe83ef770ee9d41a27f824a6e56 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 2a5edea39971049a540474c6a99edf0aa4074c58 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
txSave = CTransaction()
txSave.deserialize(BytesIO(hex_str_to_bytes(tx)))
# make sure that a specifically crafted op_return value will not pass all the IsDERSignature checks and then get decoded as a sighash type
tx = '01000000015ded05872fdbda629c7d3d02b194763ce3b9b1535ea884e3c8e765d42e316724020000006b48304502204c10d4064885c42638cbff3585915b322de33762598321145ba033fc796971e2022100bb153ad3baa8b757e30a2175bd32852d2e1cb9080f84d7e32fcdfd667934ef1b012103163c0ff73511ea1743fb5b98384a2ff09dd06949488028fd819f4d83f56264efffffffff0200000000000000000b6a0930060201000201000180380100000000001976a9141cabd296e753837c086da7a45a6c2fe0d49d7b7b88ac00000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_RETURN 300602010002010001', rpc_result['vout'][0]['scriptPubKey']['asm'])
# verify that we have not altered scriptPubKey processing even of a specially crafted P2PKH pubkeyhash and P2SH redeem script hash that is made to pass the der signature checks
tx = '01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914301102070101010101010102060101010101010188acee2a02000000000017a91430110207010101010101010206010101010101018700000000'
rpc_result = self.nodes[0].decoderawtransaction(tx)
assert_equal('OP_DUP OP_HASH160 3011020701010101010101020601010101010101 OP_EQUALVERIFY OP_CHECKSIG', rpc_result['vout'][0]['scriptPubKey']['asm'])
assert_equal('OP_HASH160 3011020701010101010101020601010101010101 OP_EQUAL', rpc_result['vout'][1]['scriptPubKey']['asm'])
# some more full transaction tests of varying specific scriptSigs. used instead of
# tests in decodescript_script_sig because the decodescript RPC is specifically
# for working on scriptPubKeys (argh!).
push_signature = bytes_to_hex_str(txSave.vin[0].scriptSig)[2:(0x48*2+4)]
signature = push_signature[2:]
der_signature = signature[:-2]
signature_sighash_decoded = der_signature + '[ALL]'
signature_2 = der_signature + '82'
push_signature_2 = '48' + signature_2
signature_2_sighash_decoded = der_signature + '[NONE|ANYONECANPAY]'
# 1) P2PK scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# make sure that the sighash decodes come out correctly for a more complex / lesser used case.
txSave.vin[0].scriptSig = hex_str_to_bytes(push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal(signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 2) multisig scriptSig
txSave.vin[0].scriptSig = hex_str_to_bytes('00' + push_signature + push_signature_2)
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('0 ' + signature_sighash_decoded + ' ' + signature_2_sighash_decoded, rpc_result['vin'][0]['scriptSig']['asm'])
# 3) test a scriptSig that contains more than push operations.
# in fact, it contains an OP_RETURN with data specially crafted to cause improper decode if the code does not catch it.
txSave.vin[0].scriptSig = hex_str_to_bytes('6a143011020701010101010101020601010101010101')
rpc_result = self.nodes[0].decoderawtransaction(bytes_to_hex_str(txSave.serialize()))
assert_equal('OP_RETURN 3011020701010101010101020601010101010101', rpc_result['vin'][0]['scriptSig']['asm'])
def run_test(self):
self.decodescript_script_sig()
self.decodescript_script_pub_key()
self.decoderawtransaction_asm_sighashtype()
if __name__ == '__main__':
DecodeScriptTest().main()
| mit |
sped-br/python-sped | sped/__init__.py | 228 | # -*- coding: utf-8 -*-
from .escrituracao import ECD
from .escrituracao import ECF
from .escrituracao import EFD_ICMS_IPI
from .escrituracao import EFD_PIS_COFINS
from .escrituracao import Escrituracao
__version__ = '1.0.2'
| mit |
ShadowLordAlpha/EchoEngine | src/main/java/io/github/cybernetic_shadow/echo/graphics/RawModel.java | 335 | package io.github.cybernetic_shadow.echo.graphics;
public class RawModel {
private int vaoID;
private int vertexCount;
public RawModel(int vaoID, int vertexCount) {
this.vaoID = vaoID;
this.vertexCount = vertexCount;
}
public int getVaoID() {
return vaoID;
}
public int getVertexCount() {
return vertexCount;
}
}
| mit |
skyarch-networks/skyhopper | db/migrate/20141002020942_relation_projects_cloud_provider.rb | 145 | class RelationProjectsCloudProvider < ActiveRecord::Migration[4.2]
def change
add_column :projects, :cloud_provider_id, :integer
end
end
| mit |
AvaIre/AvaIre | src/main/java/com/avairebot/Main.java | 4840 | /*
* Copyright (c) 2018.
*
* This file is part of AvaIre.
*
* AvaIre is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AvaIre is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AvaIre. If not, see <https://www.gnu.org/licenses/>.
*
*
*/
package com.avairebot;
import ch.qos.logback.classic.util.ContextInitializer;
import com.avairebot.chat.ConsoleColor;
import com.avairebot.exceptions.InvalidApplicationEnvironmentException;
import com.avairebot.shared.ExitCodes;
import org.apache.commons.cli.*;
import java.io.IOException;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws IOException, SQLException, InvalidApplicationEnvironmentException {
Options options = new Options();
options.addOption(new Option("h", "help", false, "Displays this help menu."));
options.addOption(new Option("v", "version", false, "Displays the current version of the application."));
options.addOption(new Option("sc", "shard-count", true, "Sets the amount of shards the bot should start up."));
options.addOption(new Option("s", "shards", true, "Sets the shard IDs that should be started up, the shard IDs should be formatted by the lowest shard ID to start up, and the highest shard ID to start up, separated by a dash.\nExample: \"--shards=4-9\" would start up shard 4, 5, 6, 7, 8, and 9."));
options.addOption(new Option("m", "music", false, "Enables music-only mode, disabling any feature that is not related to the music features."));
options.addOption(new Option("upi", "use-plugin-index", false, "Enables the use of the plugin index, this will automatically re-download any plugin that is registered in the plugin index, but is not found in the plugins directory."));
options.addOption(new Option("env", "use-environment-variables", false, "Enables environment variables override for the config options, this allows for setting up environment variables like \"AVA_DISCORD_TOKEN\" to override the \"discord.token\" option in the config. Every option in the config can be overwritten with an environment variable called \"AVA_\" plus the path to the config option in all uppercase, and any special characters replaced with an underscore(_), for example \"database.type\" would be \"AVA_DATABASE_TYPE\".\nNote: None of the values are stored in the config permanently, removing the environment variable will make the bot use the config option again(after a restart)."));
options.addOption(new Option("nocolor", "no-colors", false, "Disables colors for commands and AI actions in the terminal."));
options.addOption(new Option("d", "debug", false, "Enables debugging mode, this will log extra information to the terminal."));
options.addOption(new Option("gsf", "generate-json-file", false, "Enters command generation mode, when this flag is enabled, the bot won't actually start, but will instead generate a \"commandMap.json\" file containing information about all the registered commands. This file is used for avairebot.com to generate the commands page."));
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
try {
CommandLine cmd = parser.parse(options, args);
Settings settings = new Settings(cmd, args);
ConsoleColor.setSettings(settings);
if (!settings.useColors()) {
System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "logback_nocolor" + (
settings.useDebugging() ? "_debug" : ""
) + ".xml");
} else if (settings.useDebugging()) {
System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "logback_debug.xml");
}
if (cmd.hasOption("help")) {
formatter.printHelp("Help Menu", options);
System.exit(ExitCodes.EXIT_CODE_NORMAL);
} else if (cmd.hasOption("version")) {
System.out.println(AvaIre.getVersionInfo(settings));
System.exit(ExitCodes.EXIT_CODE_NORMAL);
}
AvaIre.avaire = new AvaIre(settings);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("", options);
System.exit(ExitCodes.EXIT_CODE_NORMAL);
}
}
}
| mit |
risetechnologies/fela | benchmarks/dom-comparison/src/index.js | 1747 | import App from './app/App'
import impl from './impl'
import Tree from './cases/Tree'
import SierpinskiTriangle from './cases/SierpinskiTriangle'
import React from 'react'
import ReactDOM from 'react-dom'
const implementations = impl
const packageNames = Object.keys(implementations)
const createTestBlock = fn => {
return packageNames.reduce((testSetups, packageName) => {
const { name, components, version } = implementations[packageName]
const {
Component,
getComponentProps,
sampleCount,
Provider,
benchmarkType,
} = fn(components)
testSetups[packageName] = {
Component,
getComponentProps,
sampleCount,
Provider,
benchmarkType,
version,
name,
}
return testSetups
}, {})
}
const tests = {
'Mount deep tree': createTestBlock(components => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({
breadth: 2,
components,
depth: 7,
id: 0,
wrap: 1,
}),
Provider: components.Provider,
sampleCount: 50,
})),
'Mount wide tree': createTestBlock(components => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({
breadth: 6,
components,
depth: 3,
id: 0,
wrap: 2,
}),
Provider: components.Provider,
sampleCount: 50,
})),
'Update dynamic styles': createTestBlock(components => ({
benchmarkType: 'update',
Component: SierpinskiTriangle,
getComponentProps: ({ cycle }) => {
return { components, s: 200, renderCount: cycle, x: 0, y: 0 }
},
Provider: components.Provider,
sampleCount: 100,
})),
}
ReactDOM.render(<App tests={tests} />, document.querySelector('.root'))
| mit |
jlenoble/wupjs | src/components/list/proptypes.js | 1685 | import PropTypes from 'prop-types';
// Schema: {_id: 'string'}
// Shape: {_id: PropTypes.string}
// Checker: PropTypes.shape(Shape)
// Helpers
const getChecker = type => {
switch (type) {
case 'funcs':
case 'strings':
case 'bools':
case 'elements':
const cut = type.length - 1;
return PropTypes.arrayOf(PropTypes[type.slice(0, cut)].isRequired);
default:
return PropTypes[type];
}
};
const schemaToShape = schema => {
const shape = {};
Object.keys(schema).forEach(key => {
shape[key] = getChecker(schema[key]).isRequired;
});
return shape;
};
const shapeToChecker = shape => PropTypes.shape(shape);
const mergeObjects = (...objects) => objects.reduce((o1, o2) => {
return Object.assign(o1, o2);
}, {});
const makeCheckerFromShapes = (...shapes) => {
return shapeToChecker(mergeObjects(...shapes));
};
const makeCheckerFromSchemas = (...schemas) => {
return makeCheckerFromShapes(...schemas.map(schemaToShape));
};
// Item
const itemSchema = {
title: 'string',
_id: 'string',
};
export const itemPropType = makeCheckerFromSchemas(itemSchema);
// export const extendItemPropType = schema => makeCheckerFromSchemas(
// itemSchema, schema);
// List of Items
export const itemsPropType = PropTypes.arrayOf(itemPropType.isRequired);
// export const extendItemsPropType = schema => PropTypes.arrayOf(
// extendItemPropType(schema).isRequired);
//
// // Item UI
//
// const itemUiSchema = {
// buttons: 'funcs',
// checkboxes: 'funcs',
// };
//
// export const itemUiPropType = makeCheckerFromSchemas(itemUiSchema);
// export const itemUiDefaultProps = {
// ui: {
// buttons: [],
// checkboxes: [],
// },
// };
| mit |
chrisvanmook/generator-web-initium | app/src/install.js | 963 | 'use strict';
var wiredep = require('wiredep'),
yosay = require('yosay'),
fs = require('fs');
module.exports = function (WebInitiumGenerator) {
WebInitiumGenerator.prototype.writeFiles = function writeFiles() {
// perform a npm install
if (!this.options['skip-install']) {
this.installDependencies({
bower: false, // package should contain postinstall: bower install,
skipMessage: this.options['skip-install-message']
});
}
this.on('end', function () {
// wire Bower packages to html file
wiredep({
directory: this.destinationPath('/src/bower_components'),
bowerJson: JSON.parse(fs.readFileSync(this.destinationPath('/bower.json'))),
ignorePath: /^(\.\.\/)*\.\./,
src: this.destinationPath('/src/views/layout.twig'),
exclude: []
});
this.log(yosay("All done! Please run `gulp serve` to serve your brand new web app!"));
}.bind(this));
}
};
| mit |
noelstieglitz/BreezeCRM | BreezeCRM/Models/OrderSubtotal.cs | 228 | using System;
using System.Collections.Generic;
namespace BreezeCRM.Models
{
public partial class OrderSubtotal
{
public int OrderID { get; set; }
public Nullable<decimal> Subtotal { get; set; }
}
}
| mit |
SVGN/BullsAndCows | BullsAndCows/BullsAndCows/GameEngine.cs | 6960 | //-----------------------------------------------------------------------
// <copyright file="GameEngine.cs" company="Team Osmium">
// All rights reserved © Team Osmium 2013
// </copyright>
//-----------------------------------------------------------------------
namespace BullsAndCows
{
using System;
using System.Text.RegularExpressions;
/// <summary>
/// The class is used to simulate the game.
/// </summary>
public class GameEngine
{
private const int MaxHelpsCount = 5;
private const int SecretNumberLength = 4;
private readonly ScoreBoard scoreBoard;
private readonly IPrinter consolePrinter;
private Command currentCommand;
private string secretNumber;
private int attemptsCount;
private int helpsCount;
private bool exitFromGame;
/// <summary>
/// Initializes a new instance of the <see cref="GameEngine"/> class.
/// </summary>
public GameEngine()
{
this.scoreBoard = new ScoreBoard();
this.consolePrinter = new ConsolePrinter();
this.secretNumber = Generator.SecretNumber(SecretNumberLength);
this.attemptsCount = 0;
this.helpsCount = 0;
this.exitFromGame = false;
}
/// <summary>
/// Runs the game.
/// </summary>
public void Run()
{
this.consolePrinter.PrintWelcomeMessage();
while (!this.exitFromGame)
{
this.consolePrinter.PrintGuessOrCommandAskingMessage();
string input = Console.ReadLine().Trim();
this.ReadAction(input);
}
}
private void ReadAction(string input)
{
if (this.IsGuess(input))
{
string guess = input;
this.ProcessGuess(guess);
}
else if (this.IsCommand(input))
{
switch (this.currentCommand)
{
case Command.Top:
{
this.consolePrinter.PrintScoreBoard(this.scoreBoard);
break;
}
case Command.Restart:
{
this.StartNewGame();
break;
}
case Command.Help:
{
this.Help();
break;
}
case Command.Exit:
{
this.exitFromGame = true;
break;
}
}
}
else
{
this.consolePrinter.PrintWrongGuessOrCommandMessage();
}
}
private void StartNewGame()
{
this.consolePrinter.Clear();
this.consolePrinter.PrintWelcomeMessage();
this.secretNumber = Generator.SecretNumber(SecretNumberLength);
this.attemptsCount = 0;
this.helpsCount = 0;
}
private bool IsGuess(string input)
{
if (input == null || input.Length != SecretNumberLength)
{
return false;
}
Regex pattern = new Regex("[1-9][0-9][0-9][0-9]");
return pattern.IsMatch(input);
}
private bool IsCommand(string input)
{
//check input
if (input == null || input.Length == 0)
{
return false;
}
string uppedFirstCharWord = string.Empty;
if (char.IsLower(input[0]))
{
uppedFirstCharWord = char.ToUpper(input[0]).ToString() + input.Substring(1);
}
Command newCommand;
bool isCommand = Enum.TryParse(uppedFirstCharWord, out newCommand);
if (isCommand)
{
this.currentCommand = newCommand;
}
return isCommand;
}
private void Help()
{
if (this.helpsCount >= MaxHelpsCount)
{
this.consolePrinter.PrintForbiddenHelpMessage();
return;
}
this.helpsCount++;
int helpIndex = Generator.HelpIndex();
string helpNumber = Generator.HelpNumber(this.secretNumber, helpIndex);
this.consolePrinter.PrintHelpNumberMessage(helpNumber);
this.consolePrinter.PrintRemainingHelpsMessage(MaxHelpsCount, this.helpsCount);
}
private void ProcessGuess(string guessNumber)
{
this.attemptsCount++;
if (guessNumber == this.secretNumber)
{
this.consolePrinter.PrintResultMessage(this.attemptsCount);
if (this.helpsCount > 0)
{
this.consolePrinter.PrintUnsavedResultMessage();
Console.ReadLine();
this.StartNewGame();
return;
}
this.consolePrinter.PrintNicknameMessage();
string nickname = Console.ReadLine().Trim();
this.AddResultToScoreBoard(nickname, this.attemptsCount);
Console.ReadLine();
this.StartNewGame();
}
else
{
int bulls = 0;
int cows = 0;
// Bull counter
bool[] isBull = new bool[SecretNumberLength];
for (int i = 0; i < SecretNumberLength; i++)
{
if (this.secretNumber[i] == guessNumber[i])
{
isBull[i] = true;
bulls++;
}
}
// Cow counter
bool[] isCow = new bool[SecretNumberLength];
for (int i = 0; i < SecretNumberLength; i++)
{
for (int j = 0; j < SecretNumberLength; j++)
{
if (!isBull[j] && !isCow[j] && (guessNumber[i] == this.secretNumber[j]))
{
isCow[j] = true;
cows++;
break;
}
}
}
this.consolePrinter.PrintFailedGuessMessage(bulls, cows);
}
}
private void AddResultToScoreBoard(string nickname, int attempts)
{
Player player = new Player(nickname, attempts);
this.scoreBoard.AddPlayer(player);
this.consolePrinter.PrintScoreBoard(this.scoreBoard);
}
}
}
| mit |
dwo/panicbutton | vendor/gems/bundler-1.1.0/lib/bundler/cli.rb | 25347 | require 'bundler/vendored_thor'
require 'rubygems/user_interaction'
require 'rubygems/config_file'
module Bundler
class CLI < Thor
include Thor::Actions
def initialize(*)
super
the_shell = (options["no-color"] ? Thor::Shell::Basic.new : shell)
Bundler.ui = UI::Shell.new(the_shell)
Bundler.ui.debug! if options["verbose"]
Bundler.rubygems.ui = UI::RGProxy.new(Bundler.ui)
end
check_unknown_options!
default_task :install
class_option "no-color", :type => :boolean, :banner => "Disable colorization in output"
class_option "verbose", :type => :boolean, :banner => "Enable verbose output mode", :aliases => "-V"
def help(cli = nil)
case cli
when "gemfile" then command = "gemfile.5"
when nil then command = "bundle"
else command = "bundle-#{cli}"
end
manpages = %w(
bundle
bundle-config
bundle-exec
bundle-install
bundle-package
bundle-update
gemfile.5)
if manpages.include?(command)
root = File.expand_path("../man", __FILE__)
if have_groff? && root !~ %r{^file:/.+!/META-INF/jruby.home/.+}
groff = "groff -Wall -mtty-char -mandoc -Tascii"
pager = ENV['MANPAGER'] || ENV['PAGER'] || 'less -R'
Kernel.exec "#{groff} #{root}/#{command} | #{pager}"
else
puts File.read("#{root}/#{command}.txt")
end
else
super
end
end
desc "init", "Generates a Gemfile into the current working directory"
long_desc <<-D
Init generates a default Gemfile in the current working directory. When adding a
Gemfile to a gem with a gemspec, the --gemspec option will automatically add each
dependency listed in the gemspec file to the newly created Gemfile.
D
method_option "gemspec", :type => :string, :banner => "Use the specified .gemspec to create the Gemfile"
def init
opts = options.dup
if File.exist?("Gemfile")
Bundler.ui.error "Gemfile already exists at #{Dir.pwd}/Gemfile"
exit 1
end
if opts[:gemspec]
gemspec = File.expand_path(opts[:gemspec])
unless File.exist?(gemspec)
Bundler.ui.error "Gem specification #{gemspec} doesn't exist"
exit 1
end
spec = Gem::Specification.load(gemspec)
puts "Writing new Gemfile to #{Dir.pwd}/Gemfile"
File.open('Gemfile', 'wb') do |file|
file << "# Generated from #{gemspec}\n"
file << spec.to_gemfile
end
else
puts "Writing new Gemfile to #{Dir.pwd}/Gemfile"
FileUtils.cp(File.expand_path('../templates/Gemfile', __FILE__), 'Gemfile')
end
end
desc "check", "Checks if the dependencies listed in Gemfile are satisfied by currently installed gems"
long_desc <<-D
Check searches the local machine for each of the gems requested in the Gemfile. If
all gems are found, Bundler prints a success message and exits with a status of 0.
If not, the first missing gem is listed and Bundler exits status 1.
D
method_option "gemfile", :type => :string, :banner =>
"Use the specified gemfile instead of Gemfile"
method_option "path", :type => :string, :banner =>
"Specify a different path than the system default ($BUNDLE_PATH or $GEM_HOME). Bundler will remember this value for future installs on this machine"
def check
ENV['BUNDLE_GEMFILE'] = File.expand_path(options[:gemfile]) if options[:gemfile]
Bundler.settings[:path] = File.expand_path(options[:path]) if options[:path]
begin
not_installed = Bundler.definition.missing_specs
rescue GemNotFound, VersionConflict
Bundler.ui.error "Your Gemfile's dependencies could not be satisfied"
Bundler.ui.warn "Install missing gems with `bundle install`"
exit 1
end
if not_installed.any?
Bundler.ui.error "The following gems are missing"
not_installed.each { |s| Bundler.ui.error " * #{s.name} (#{s.version})" }
Bundler.ui.warn "Install missing gems with `bundle install`"
exit 1
else
Bundler.load.lock
Bundler.ui.info "The Gemfile's dependencies are satisfied"
end
end
desc "install", "Install the current environment to the system"
long_desc <<-D
Install will install all of the gems in the current bundle, making them available
for use. In a freshly checked out repository, this command will give you the same
gem versions as the last person who updated the Gemfile and ran `bundle update`.
Passing [DIR] to install (e.g. vendor) will cause the unpacked gems to be installed
into the [DIR] directory rather than into system gems.
If the bundle has already been installed, bundler will tell you so and then exit.
D
method_option "without", :type => :array, :banner =>
"Exclude gems that are part of the specified named group."
method_option "gemfile", :type => :string, :banner =>
"Use the specified gemfile instead of Gemfile"
method_option "no-prune", :type => :boolean, :banner =>
"Don't remove stale gems from the cache."
method_option "no-cache", :type => :boolean, :banner =>
"Don't update the existing gem cache."
method_option "quiet", :type => :boolean, :banner =>
"Only output warnings and errors."
method_option "local", :type => :boolean, :banner =>
"Do not attempt to fetch gems remotely and use the gem cache instead"
method_option "binstubs", :type => :string, :lazy_default => "bin", :banner =>
"Generate bin stubs for bundled gems to ./bin"
method_option "shebang", :type => :string, :banner =>
"Specify a different shebang executable name than the default (usually 'ruby')"
method_option "path", :type => :string, :banner =>
"Specify a different path than the system default ($BUNDLE_PATH or $GEM_HOME). Bundler will remember this value for future installs on this machine"
method_option "system", :type => :boolean, :banner =>
"Install to the system location ($BUNDLE_PATH or $GEM_HOME) even if the bundle was previously installed somewhere else for this application"
method_option "frozen", :type => :boolean, :banner =>
"Do not allow the Gemfile.lock to be updated after this install"
method_option "deployment", :type => :boolean, :banner =>
"Install using defaults tuned for deployment environments"
method_option "standalone", :type => :array, :lazy_default => [], :banner =>
"Make a bundle that can work without the Bundler runtime"
method_option "full-index", :type => :boolean, :banner =>
"Use the rubygems modern index instead of the API endpoint"
method_option "clean", :type => :boolean, :banner =>
"Run bundle clean automatically after install"
def install
opts = options.dup
if opts[:without]
opts[:without].map!{|g| g.split(" ") }
opts[:without].flatten!
opts[:without].map!{|g| g.to_sym }
end
# Can't use Bundler.settings for this because settings needs gemfile.dirname
ENV['BUNDLE_GEMFILE'] = File.expand_path(opts[:gemfile]) if opts[:gemfile]
ENV['RB_USER_INSTALL'] = '1' if Bundler::FREEBSD
# Just disable color in deployment mode
Bundler.ui.shell = Thor::Shell::Basic.new if opts[:deployment]
if (opts[:path] || opts[:deployment]) && opts[:system]
Bundler.ui.error "You have specified both a path to install your gems to, \n" \
"as well as --system. Please choose."
exit 1
end
if opts[:deployment] || opts[:frozen]
unless Bundler.default_lockfile.exist?
flag = opts[:deployment] ? '--deployment' : '--frozen'
raise ProductionError, "The #{flag} flag requires a Gemfile.lock. Please make " \
"sure you have checked your Gemfile.lock into version control " \
"before deploying."
end
if Bundler.root.join("vendor/cache").exist?
opts[:local] = true
end
Bundler.settings[:frozen] = '1'
end
# When install is called with --no-deployment, disable deployment mode
if opts[:deployment] == false
Bundler.settings.delete(:frozen)
opts[:system] = true
end
# Can't use Bundler.settings for this because settings needs gemfile.dirname
Bundler.settings[:path] = nil if opts[:system]
Bundler.settings[:path] = "vendor/bundle" if opts[:deployment]
Bundler.settings[:path] = opts[:path] if opts[:path]
Bundler.settings[:path] ||= "bundle" if opts[:standalone]
Bundler.settings[:bin] = opts["binstubs"] if opts[:binstubs]
Bundler.settings[:shebang] = opts["shebang"] if opts[:shebang]
Bundler.settings[:no_prune] = true if opts["no-prune"]
Bundler.settings[:disable_shared_gems] = Bundler.settings[:path] ? '1' : nil
Bundler.settings.without = opts[:without]
Bundler.ui.be_quiet! if opts[:quiet]
Bundler.settings[:clean] = opts[:clean] if opts[:clean]
Bundler::Fetcher.disable_endpoint = opts["full-index"]
# rubygems plugins sometimes hook into the gem install process
Gem.load_env_plugins if Gem.respond_to?(:load_env_plugins)
Installer.install(Bundler.root, Bundler.definition, opts)
Bundler.load.cache if Bundler.root.join("vendor/cache").exist? && !options["no-cache"]
if Bundler.settings[:path]
absolute_path = File.expand_path(Bundler.settings[:path])
relative_path = absolute_path.sub(File.expand_path('.'), '.')
Bundler.ui.confirm "Your bundle is complete! " +
"It was installed into #{relative_path}"
else
Bundler.ui.confirm "Your bundle is complete! " +
"Use `bundle show [gemname]` to see where a bundled gem is installed."
end
Installer.post_install_messages.to_a.each do |name, msg|
Bundler.ui.confirm "Post-install message from #{name}:\n#{msg}"
end
clean if Bundler.settings[:clean] && Bundler.settings[:path]
rescue GemNotFound => e
if opts[:local] && Bundler.app_cache.exist?
Bundler.ui.warn "Some gems seem to be missing from your vendor/cache directory."
end
if Bundler.definition.no_sources?
Bundler.ui.warn "Your Gemfile doesn't have any sources. You can add one with a line like 'source :rubygems'"
end
raise e
end
desc "update", "update the current environment"
long_desc <<-D
Update will install the newest versions of the gems listed in the Gemfile. Use
update when you have changed the Gemfile, or if you want to get the newest
possible versions of the gems in the bundle.
D
method_option "source", :type => :array, :banner => "Update a specific source (and all gems associated with it)"
method_option "local", :type => :boolean, :banner =>
"Do not attempt to fetch gems remotely and use the gem cache instead"
def update(*gems)
sources = Array(options[:source])
if gems.empty? && sources.empty?
# We're doing a full update
Bundler.definition(true)
else
Bundler.definition(:gems => gems, :sources => sources)
end
opts = {"update" => true, "local" => options[:local]}
# rubygems plugins sometimes hook into the gem install process
Gem.load_env_plugins if Gem.respond_to?(:load_env_plugins)
Installer.install Bundler.root, Bundler.definition, opts
Bundler.load.cache if Bundler.root.join("vendor/cache").exist?
clean if Bundler.settings[:clean] && Bundler.settings[:path]
Bundler.ui.confirm "Your bundle is updated! " +
"Use `bundle show [gemname]` to see where a bundled gem is installed."
end
desc "show [GEM]", "Shows all gems that are part of the bundle, or the path to a given gem"
long_desc <<-D
Show lists the names and versions of all gems that are required by your Gemfile.
Calling show with [GEM] will list the exact location of that gem on your machine.
D
method_option "paths", :type => :boolean,
:banner => "List the paths of all gems that are required by your Gemfile."
def show(gem_name = nil)
Bundler.load.lock
if gem_name
Bundler.ui.info locate_gem(gem_name)
elsif options[:paths]
Bundler.load.specs.sort_by { |s| s.name }.each do |s|
Bundler.ui.info locate_gem(s.name)
end
else
Bundler.ui.info "Gems included by the bundle:"
Bundler.load.specs.sort_by { |s| s.name }.each do |s|
Bundler.ui.info " * #{s.name} (#{s.version}#{s.git_version})"
end
end
end
map %w(list) => "show"
desc "outdated [GEM]", "list installed gems with newer versions available"
long_desc <<-D
Outdated lists the names and versions of gems that have a newer version available
in the given source. Calling outdated with [GEM [GEM]] will only check for newer
versions of the given gems. By default, available prerelease gems will be ignored.
D
method_option "pre", :type => :boolean, :banner => "Check for newer pre-release gems"
method_option "source", :type => :array, :banner => "Check against a specific source"
method_option "local", :type => :boolean, :banner =>
"Do not attempt to fetch gems remotely and use the gem cache instead"
def outdated(*gems)
sources = Array(options[:source])
current_specs = Bundler.load.specs
if gems.empty? && sources.empty?
# We're doing a full update
definition = Bundler.definition(true)
else
definition = Bundler.definition(:gems => gems, :sources => sources)
end
options["local"] ? definition.resolve_with_cache! : definition.resolve_remotely!
Bundler.ui.info ""
if options["pre"]
Bundler.ui.info "Outdated gems included in the bundle (including pre-releases):"
else
Bundler.ui.info "Outdated gems included in the bundle:"
end
out_count = 0
# Loop through the current specs
current_specs.each do |current_spec|
next if !gems.empty? && !gems.include?(current_spec.name)
active_spec = definition.index[current_spec.name].sort_by { |b| b.version }
if !current_spec.version.prerelease? && !options[:pre] && active_spec.size > 1
active_spec = active_spec.delete_if { |b| b.respond_to?(:version) && b.version.prerelease? }
end
active_spec = active_spec.last
next if active_spec.nil?
gem_outdated = Gem::Version.new(active_spec.version) > Gem::Version.new(current_spec.version)
git_outdated = current_spec.git_version != active_spec.git_version
if gem_outdated || git_outdated
spec_version = "#{active_spec.version}#{active_spec.git_version}"
current_version = "#{current_spec.version}#{current_spec.git_version}"
Bundler.ui.info " * #{active_spec.name} (#{spec_version} > #{current_version})"
out_count += 1
end
Bundler.ui.debug "from #{active_spec.loaded_from}"
end
Bundler.ui.info " Your bundle is up to date!" if out_count < 1
Bundler.ui.info ""
end
desc "cache", "Cache all the gems to vendor/cache", :hide => true
method_option "no-prune", :type => :boolean, :banner => "Don't remove stale gems from the cache."
def cache
Bundler.definition.resolve_with_cache!
Bundler.load.cache
Bundler.settings[:no_prune] = true if options["no-prune"]
Bundler.load.lock
rescue GemNotFound => e
Bundler.ui.error(e.message)
Bundler.ui.warn "Run `bundle install` to install missing gems."
exit 128
end
desc "package", "Locks and then caches all of the gems into vendor/cache"
method_option "no-prune", :type => :boolean, :banner => "Don't remove stale gems from the cache."
long_desc <<-D
The package command will copy the .gem files for every gem in the bundle into the
directory ./vendor/cache. If you then check that directory into your source
control repository, others who check out your source will be able to install the
bundle without having to download any additional gems.
D
def package
install
# TODO: move cache contents here now that all bundles are locked
Bundler.load.cache
end
map %w(pack) => :package
desc "exec", "Run the command in context of the bundle"
long_desc <<-D
Exec runs a command, providing it access to the gems in the bundle. While using
bundle exec you can require and call the bundled gems as if they were installed
into the systemwide Rubygems repository.
D
def exec(*)
ARGV.shift # remove "exec"
Bundler.load.setup_environment
begin
# Run
Kernel.exec(*ARGV)
rescue Errno::EACCES
Bundler.ui.error "bundler: not executable: #{ARGV.first}"
exit 126
rescue Errno::ENOENT
Bundler.ui.error "bundler: command not found: #{ARGV.first}"
Bundler.ui.warn "Install missing gem executables with `bundle install`"
exit 127
rescue ArgumentError
Bundler.ui.error "bundler: exec needs a command to run"
exit 128
end
end
desc "config NAME [VALUE]", "retrieve or set a configuration value"
long_desc <<-D
Retrieves or sets a configuration value. If only parameter is provided, retrieve the value. If two parameters are provided, replace the
existing value with the newly provided one.
By default, setting a configuration value sets it for all projects
on the machine.
If a global setting is superceded by local configuration, this command
will show the current value, as well as any superceded values and
where they were specified.
D
def config(name = nil, *args)
values = ARGV.dup
values.shift # remove config
values.shift # remove the name
unless name
Bundler.ui.confirm "Settings are listed in order of priority. The top value will be used.\n"
Bundler.settings.all.each do |setting|
Bundler.ui.confirm "#{setting}"
with_padding do
Bundler.settings.pretty_values_for(setting).each do |line|
Bundler.ui.info line
end
end
Bundler.ui.confirm ""
end
return
end
if values.empty?
Bundler.ui.confirm "Settings for `#{name}` in order of priority. The top value will be used"
with_padding do
Bundler.settings.pretty_values_for(name).each { |line| Bundler.ui.info line }
end
else
locations = Bundler.settings.locations(name)
if local = locations[:local]
Bundler.ui.info "Your application has set #{name} to #{local.inspect}. This will override the " \
"system value you are currently setting"
end
if global = locations[:global]
Bundler.ui.info "You are replacing the current system value of #{name}, which is currently #{global}"
end
if env = locations[:env]
Bundler.ui.info "You have set a bundler environment variable for #{env}. This will take precedence " \
"over the system value you are setting"
end
Bundler.settings.set_global(name, values.join(" "))
end
end
desc "open GEM", "Opens the source directory of the given bundled gem"
def open(name)
editor = [ENV['BUNDLER_EDITOR'], ENV['VISUAL'], ENV['EDITOR']].find{|e| !e.nil? && !e.empty? }
if editor
gem_path = locate_gem(name)
Dir.chdir(gem_path) do
command = "#{editor} #{gem_path}"
success = system(command)
Bundler.ui.info "Could not run '#{command}'" unless success
end
else
Bundler.ui.info("To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR")
end
end
desc "console [GROUP]", "Opens an IRB session with the bundle pre-loaded"
def console(group = nil)
group ? Bundler.require(:default, *(group.split.map! {|g| g.to_sym })) : Bundler.require
ARGV.clear
require 'irb'
IRB.start
end
desc "version", "Prints the bundler's version information"
def version
Bundler.ui.info "Bundler version #{Bundler::VERSION}"
end
map %w(-v --version) => :version
desc 'viz', "Generates a visual dependency graph"
long_desc <<-D
Viz generates a PNG file of the current Gemfile as a dependency graph.
Viz requires the ruby-graphviz gem (and its dependencies).
The associated gems must also be installed via 'bundle install'.
D
method_option :file, :type => :string, :default => 'gem_graph', :aliases => '-f', :banner => "The name to use for the generated file. see format option"
method_option :version, :type => :boolean, :default => false, :aliases => '-v', :banner => "Set to show each gem version."
method_option :requirements, :type => :boolean, :default => false, :aliases => '-r', :banner => "Set to show the version of each required dependency."
method_option :format, :type => :string, :default => "png", :aliases => '-F', :banner => "This is output format option. Supported format is png, jpg, svg, dot ..."
def viz
output_file = File.expand_path(options[:file])
output_format = options[:format]
graph = Graph.new(Bundler.load, output_file, options[:version], options[:requirements], options[:format])
begin
graph.viz
rescue LoadError => e
Bundler.ui.error e.inspect
Bundler.ui.warn "Make sure you have the graphviz ruby gem. You can install it with:"
Bundler.ui.warn "`gem install ruby-graphviz`"
rescue StandardError => e
if e.message =~ /GraphViz not installed or dot not in PATH/
Bundler.ui.error e.message
Bundler.ui.warn "The ruby graphviz gem requires GraphViz to be installed"
else
raise
end
end
end
desc "gem GEM", "Creates a skeleton for creating a rubygem"
method_option :bin, :type => :boolean, :default => false, :aliases => '-b', :banner => "Generate a binary for your library."
def gem(name)
name = name.chomp("/") # remove trailing slash if present
target = File.join(Dir.pwd, name)
constant_name = name.split('_').map{|p| p[0..0].upcase + p[1..-1] }.join
constant_name = constant_name.split('-').map{|q| q[0..0].upcase + q[1..-1] }.join('::') if constant_name =~ /-/
constant_array = constant_name.split('::')
FileUtils.mkdir_p(File.join(target, 'lib', name))
git_user_name = `git config user.name`.chomp
git_user_email = `git config user.email`.chomp
opts = {
:name => name,
:constant_name => constant_name,
:constant_array => constant_array,
:author => git_user_name.empty? ? "TODO: Write your name" : git_user_name,
:email => git_user_email.empty? ? "TODO: Write your email address" : git_user_email
}
template(File.join("newgem/Gemfile.tt"), File.join(target, "Gemfile"), opts)
template(File.join("newgem/Rakefile.tt"), File.join(target, "Rakefile"), opts)
template(File.join("newgem/LICENSE.tt"), File.join(target, "LICENSE"), opts)
template(File.join("newgem/README.md.tt"), File.join(target, "README.md"), opts)
template(File.join("newgem/gitignore.tt"), File.join(target, ".gitignore"), opts)
template(File.join("newgem/newgem.gemspec.tt"), File.join(target, "#{name}.gemspec"), opts)
template(File.join("newgem/lib/newgem.rb.tt"), File.join(target, "lib/#{name}.rb"), opts)
template(File.join("newgem/lib/newgem/version.rb.tt"), File.join(target, "lib/#{name}/version.rb"), opts)
if options[:bin]
template(File.join("newgem/bin/newgem.tt"), File.join(target, 'bin', name), opts)
end
Bundler.ui.info "Initializating git repo in #{target}"
Dir.chdir(target) { `git init`; `git add .` }
end
def self.source_root
File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
end
desc "clean", "Cleans up unused gems in your bundler directory"
method_option "force", :type => :boolean, :default => false, :banner =>
"forces clean even if --path is set"
def clean
if Bundler.settings[:path] || options[:force]
Bundler.load.clean
else
Bundler.ui.error "Can only use bundle clean when --path is set or --force is set"
exit 1
end
end
private
def have_groff?
!(`which groff` rescue '').empty?
end
def locate_gem(name)
spec = Bundler.load.specs.find{|s| s.name == name }
raise GemNotFound, "Could not find gem '#{name}' in the current bundle." unless spec
if spec.name == 'bundler'
return File.expand_path('../../../', __FILE__)
end
spec.full_gem_path
end
end
end
| mit |
obsidian-btc/subst-attr | test/bench/replace_attribute_with_its_substitute.rb | 675 | require_relative 'bench_init'
module ReplaceWithSubstitute
class SomeDependency
def self.configure(receiver)
receiver.some_attr = new
end
module Substitute
def self.build
:some_substutute
end
end
end
class Example
extend SubstAttr::Macro
subst_attr :some_attr, SomeDependency
def self.build
new.tap do |instance|
SomeDependency.configure instance
end
end
end
end
context "Replace an Attribute with its Substitute" do
example = ReplaceWithSubstitute::Example.build
SubstAttr::Substitute.(:some_attr, example)
test do
assert(example.some_attr == :some_substutute)
end
end
| mit |
jiaorenyu/learning | python/mylib/hash_util.py | 180 | #!/usr/bin/python
#-*- coding:utf8 -*-
import hashlib
#16进制md5加密,32个大写字符.
def md5(msg):
m = hashlib.md5()
m.update(msg)
return m.hexdigest().upper()
| mit |
Risersoft/GSTN | GSTN.API.Library/Models/GSTR2/B2bInward.cs | 5313 | using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
namespace Risersoft.API.GSTN.GSTR2
{
public class ItmDet
{
[Required]
[Display(Name = "Identifier if Goods or Services")]
[MaxLength(1)]
[MinLength(1)]
[RegularExpression("^(G|S)+$")]
public string ty { get; set; }
[Required]
[Display(Name = "HSN or SAC of Goods or Services as per Invoice line items")]
[MaxLength(10)]
public string hsn_sc { get; set; }
[Required]
[Display(Name = "Taxable value of Goods or Service as per invoice")]
public double? txval { get; set; }
[Required]
[Display(Name = "IGST Rate as per invoice")]
public double? irt { get; set; }
[Required]
[Display(Name = "IGST Amount as per invoice")]
public double? iamt { get; set; }
[Required]
[Display(Name = "CGST Rate as per invoice")]
public double? crt { get; set; }
[Required]
[Display(Name = "CGST Amount as per invoice")]
public double? camt { get; set; }
[Required]
[Display(Name = "SGST Rate as per invoice")]
public double? srt { get; set; }
[Required]
[Display(Name = "SGST Amount as per invoice")]
public double? samt { get; set; }
[Required]
[Display(Name = "CESS Rate as per invoice")]
public double? csrt { get; set; }
[Required]
[Display(Name = "CESS Amount as per invoice")]
public double? csamt { get; set; }
}
public class Itc
{
[Required]
[Display(Name = "Total Tax available as ITC CGST Amount")]
public double? tx_c { get; set; }
[Required]
[Display(Name = "Total Tax available as ITC IGST Amount")]
public double? tx_i { get; set; }
[Required]
[Display(Name = "Total Tax available as ITC SGST Amount")]
public double? tx_s { get; set; }
[Required]
[Display(Name = "Total Tax available as ITC CESS Amount")]
public double? tx_cs { get; set; }
[Required]
[Display(Name = "Total Input Tax Credit available for claim this month based on the Invoices uploaded(CGST Amount)")]
public double? tc_c { get; set; }
[Required]
[Display(Name = "Total Input Tax Credit available for claim this month based on the Invoices uploaded(IGST Amount)")]
public double? tc_i { get; set; }
[Required]
[Display(Name = "Total Input Tax Credit available for claim this month based on the Invoices uploaded(SGST Amount)")]
public double? tc_s { get; set; }
[Required]
[Display(Name = "Total Input Tax Credit available for claim this month based on the Invoices uploaded(SGST Amount)")]
public double? tc_cs { get; set; }
[Required]
[Display(Name = "Eligiblity of Total Tax available as ITC")]
[MaxLength(20)]
public string elg { get; set; }
}
public class Itm
{
[Required]
[Display(Name = "Serial no")]
public int num { get; set; }
[Required]
[Display(Name = "item Details")]
public ItmDet itm_det { get; set; }
[Required]
[Display(Name = "itc")]
public Itc itc { get; set; }
}
public class B2bInv
{
[Required]
[Display(Name = "flag for accepting or rejecting a invoice")]
public string flag { get; set; }
[Required]
[Display(Name = "Supplier Invoice Number")]
[MaxLength(50)]
[RegularExpression("^[a-zA-Z0-9]+$")]
public string inum { get; set; }
[Required]
[Display(Name = "Supplier Invoice Date")]
[RegularExpression("^((0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-]((19|20)\\d\\d))*$")]
public string idt { get; set; }
[Required]
[Display(Name = "Supplier Invoice Value")]
public double? val { get; set; }
[Required]
[Display(Name = "Place of supply")]
[MaxLength(5)]
public string pos { get; set; }
[Required]
[Display(Name = "Reverse Charge")]
public string rchrg { get; set; }
[Required]
[Display(Name = "Invoice Uploader")]
public string updby { get; set; }
[Required]
[Display(Name = "items")]
public List<Itm> itms { get; set; }
[Required]
[Display(Name = "Invoice Check sum value")]
[MaxLength(15)]
[RegularExpression("^[a-zA-Z0-9]+$")]
public string chksum { get; set; }
}
public class B2bInward
{
[Required]
[Display(Name = "GSTIN/UID of the Receiver taxpayer/UN, Govt Bodies")]
public string ctin { get; set; }
[Required]
[Display(Name = "counter party Filing Status")]
public string cfs { get; set; }
[Required]
[Display(Name = "Invoice Details")]
public List<B2bInv> inv { get; set; }
}
} | mit |
kujotx/angular4-template | src/angular4/node_modules/aspnet-prerendering/Prerendering.js | 5472 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/// <reference path="./PrerenderingInterfaces.d.ts" />
var url = require("url");
var domain = require("domain");
var main_1 = require("domain-task/main");
var defaultTimeoutMilliseconds = 30 * 1000;
function createServerRenderer(bootFunc) {
var resultFunc = function (callback, applicationBasePath, bootModule, absoluteRequestUrl, requestPathAndQuery, customDataParameter, overrideTimeoutMilliseconds, requestPathBase) {
// Prepare a promise that will represent the completion of all domain tasks in this execution context.
// The boot code will wait for this before performing its final render.
var domainTaskCompletionPromiseResolve;
var domainTaskCompletionPromise = new Promise(function (resolve, reject) {
domainTaskCompletionPromiseResolve = resolve;
});
var parsedAbsoluteRequestUrl = url.parse(absoluteRequestUrl);
var params = {
// It's helpful for boot funcs to receive the query as a key-value object, so parse it here
// e.g., react-redux-router requires location.query to be a key-value object for consistency with client-side behaviour
location: url.parse(requestPathAndQuery, /* parseQueryString */ true),
origin: parsedAbsoluteRequestUrl.protocol + '//' + parsedAbsoluteRequestUrl.host,
url: requestPathAndQuery,
baseUrl: (requestPathBase || '') + '/',
absoluteUrl: absoluteRequestUrl,
domainTasks: domainTaskCompletionPromise,
data: customDataParameter
};
// Open a new domain that can track all the async tasks involved in the app's execution
main_1.run(/* code to run */ function () {
// Workaround for Node bug where native Promise continuations lose their domain context
// (https://github.com/nodejs/node-v0.x-archive/issues/8648)
// The domain.active property is set by the domain-context module
bindPromiseContinuationsToDomain(domainTaskCompletionPromise, domain['active']);
// Make the base URL available to the 'domain-tasks/fetch' helper within this execution context
main_1.baseUrl(absoluteRequestUrl);
// Begin rendering, and apply a timeout
var bootFuncPromise = bootFunc(params);
if (!bootFuncPromise || typeof bootFuncPromise.then !== 'function') {
callback("Prerendering failed because the boot function in " + bootModule.moduleName + " did not return a promise.", null);
return;
}
var timeoutMilliseconds = overrideTimeoutMilliseconds || defaultTimeoutMilliseconds; // e.g., pass -1 to override as 'never time out'
var bootFuncPromiseWithTimeout = timeoutMilliseconds > 0
? wrapWithTimeout(bootFuncPromise, timeoutMilliseconds, "Prerendering timed out after " + timeoutMilliseconds + "ms because the boot function in '" + bootModule.moduleName + "' "
+ 'returned a promise that did not resolve or reject. Make sure that your boot function always resolves or '
+ 'rejects its promise. You can change the timeout value using the \'asp-prerender-timeout\' tag helper.')
: bootFuncPromise;
// Actually perform the rendering
bootFuncPromiseWithTimeout.then(function (successResult) {
callback(null, successResult);
}, function (error) {
callback(error, null);
});
}, /* completion callback */ function (/* completion callback */ errorOrNothing) {
if (errorOrNothing) {
callback(errorOrNothing, null);
}
else {
// There are no more ongoing domain tasks (typically data access operations), so we can resolve
// the domain tasks promise which notifies the boot code that it can do its final render.
domainTaskCompletionPromiseResolve();
}
});
};
// Indicate to the prerendering code bundled into Microsoft.AspNetCore.SpaServices that this is a serverside rendering
// function, so it can be invoked directly. This flag exists only so that, in its absence, we can run some different
// backward-compatibility logic.
resultFunc['isServerRenderer'] = true;
return resultFunc;
}
exports.createServerRenderer = createServerRenderer;
function wrapWithTimeout(promise, timeoutMilliseconds, timeoutRejectionValue) {
return new Promise(function (resolve, reject) {
var timeoutTimer = setTimeout(function () {
reject(timeoutRejectionValue);
}, timeoutMilliseconds);
promise.then(function (resolvedValue) {
clearTimeout(timeoutTimer);
resolve(resolvedValue);
}, function (rejectedValue) {
clearTimeout(timeoutTimer);
reject(rejectedValue);
});
});
}
function bindPromiseContinuationsToDomain(promise, domainInstance) {
var originalThen = promise.then;
promise.then = (function then(resolve, reject) {
if (typeof resolve === 'function') {
resolve = domainInstance.bind(resolve);
}
if (typeof reject === 'function') {
reject = domainInstance.bind(reject);
}
return originalThen.call(this, resolve, reject);
});
}
| mit |
brideout/gen2 | application/views/login.php | 7627 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="<?php echo base_url() ?>assets/js/jquery-2.1.1.js"></script>
<script src="<?php echo base_url() ?>assets/js/functions.js" type="text/javascript" charset="utf-8"></script>
<!-- <link href="<?php echo base_url() ?>assets/css/plugins/chosen/chosen.css" rel="stylesheet"> -->
<link href="<?php echo base_url() ?>assets/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/css/animate.css" rel="stylesheet">
<link href="<?php echo base_url() ?>assets/css/style.css" rel="stylesheet">
<!-- Sweet Alert -->
<link href="<?php echo base_url() ?>assets/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
<link rel="stylesheet" href="<?php echo base_url()?>assets/js/validationEngine.jquery.css"/>
<script type="text/javascript" src="<?php echo base_url()?>assets/js/jquery.validationEngine.js"></script>
<script src="<?php echo base_url()?>assets/js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
</head>
<script type="text/javascript">
function checkEnter(e) {
var keyCode = (e.keyCode ? e.keyCode : e.which);
if(keyCode == 13 )
{
e.preventDefault();
login();
}
}
function upload() {
jQuery.post('<?php echo base_url(); ?>index.php/login/updateExercises' , function(data)
{
//alert('here');
if (data.success)
{
swal({
title: "Success",
type: "success"
})
}
else
{
// $('#loader').hide();
// $('#logInBox').show();
if(data.error == 1){
swal({
title: "Please enter an username and password"
// text: "You clicked the button!",
// type: "success"
});
} else if (data.error == 2){
swal({
title: "Error",
text: "Your subscription is past due. Please contact your administrator to update your account."
// type: "success"
});
} else if (data.error == 3) {
swal({
title: "Error",
text: "Your subscription has been cancelled. Please contact your administrator to activate your account."
// type: "success"
});
} else {
swal({
title: "Error",
text: "Please contact support at 636-717-0001",
// type: "success"
});
}
}
}, 'json');
return false;
}
function login() {
var formArray = $('#login_form').serialize();
var base_url = "<?php echo base_url(); ?>";
document.login_form.loginButton.value="Logging In...";
document.login_form.loginButton.disabled = true;
// $('#loader').show();
// $('#logInBox').hide();
jQuery.post('<?php echo base_url(); ?>login/login_validation' , formArray, function(data)
{
//alert('here');
if (data.success)
{
var url = data.url;
var index = "index.php/";
top.location = base_url+url;
}
else
{
// $('#loader').hide();
// $('#logInBox').show();
document.login_form.loginButton.disabled = false;
document.login_form.loginButton.value="Log Into Your Account";
if(data.error == 1) {
swal({
title: "Error",
text: data.message
// type: "success"
});
} else if (data.error == 5){
swal({
title: "Error",
text: "Your subscription is past due. Please contact your administrator to update your account."
// type: "success"
});
} else if (data.error == 3) {
swal({
title: "Error",
text: "Your subscription has been cancelled. Please contact your administrator to activate your account."
// type: "success"
});
} else {
swal({
title: "Error",
text: "Please contact support at 636-717-0001"
// type: "success"
});
}
}
}, 'json');
return false;
}
</script>
<style>
#photo{
display:block;
margin:auto;
position: relative;
top: 50px;
}
.middle-box {
margin-top: 50px;
}
</style>
<body class="gray-bg">
<div class="loginscreen animated fadeInDown row">
<img id="photo" src="<?php echo base_url() ?>assets/img/genethixlogo.png" alt="Logo" width="375" height="175" />
</div>
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div>
<!-- <h1 class="logo-name">IN+</h1>-->
<!-- <img id="photo" src="--><?php //echo base_url() ?><!--assets/img/genethixlogo.png" alt="Logo" width="375" height="175" />-->
</div>
<!-- <h3>Welcome to GenEthix</h3>-->
<!-- <p>-->
<!--Continually expanded and constantly improved Inspinia Admin Them (IN+)-->
<!-- </p>-->
<!-- <p>Strength and Conditioning Integration</p>-->
<form class="m-t" name="login_form" id="login_form" method="post" action="">
<div class="form-group">
<input class="form-control" type="text" placeholder="Email" <?php if(@$username){ echo @$username;}else { set_value('username'); }?> id="username" name="username" />
</div>
<div class="form-group">
<input class="form-control" onkeypress="checkEnter(event);" type="password" placeholder="Password" name="password" id="password" <?php if(@$password){ echo @$password;}else { set_value('password'); }?> />
</div>
<input type="button" id="loginButton" name="loginButton" value = "Log Into Your Account" class="btn btn-primary block full-width m-b" onClick="this.disabled=true; login();">
<a href="<?php echo base_url() ?>index.php/forgotpassword/">
<small>Forgot username/password?</small>
</a>
<!-- <p class="text-muted text-center"><small>Do not have an account?</small></p>-->
<hr>
<a class="btn btn-sm btn-white btn-block" <!--href="<?php echo base_url() ?>index.php/register"-->>Create an account</a>
</form>
<p class="m-t"> <small>Phyzion © <?php echo date("Y")?></small> </p>
<!-- <button type="submit" onclick="upload()" class="btn btn-primary">Upload</button>-->
</div>
</div>
<!-- Sweet alert -->
<script src="<?php echo base_url() ?>assets/js/plugins/sweetalert/sweetalert.min.js"></script>
</body>
</html>
| mit |
DarvinStudio/darvin-utils | Command/Cache/Varnish/ClearCommand.php | 1775 | <?php declare(strict_types=1);
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2020, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\Utils\Command\Cache\Varnish;
use Darvin\Utils\Cache\Varnish\VarnishCacheClearerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Varnish cache clear command
*/
class ClearCommand extends Command
{
/**
* @var \Darvin\Utils\Cache\Varnish\VarnishCacheClearerInterface
*/
private $clearer;
/**
* @param string $name Command name
* @param \Darvin\Utils\Cache\Varnish\VarnishCacheClearerInterface $clearer Varnish cache clearer
*/
public function __construct(string $name, VarnishCacheClearerInterface $clearer)
{
parent::__construct($name);
$this->clearer = $clearer;
}
/**
* {@inheritDoc}
*/
protected function configure(): void
{
$this->setDescription('Clears Varnish cache.');
}
/**
* {@inheritDoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$this->clearer->clearCache();
} catch (\RuntimeException $ex) {
$io->error($ex->getMessage());
return $ex->getCode();
}
$io->success('Varnish cache cleared.');
return 0;
}
}
| mit |
gammaker/atom | gameserver/src/main/java/ru/atom/gameserver/model/GameObject.java | 1060 | package ru.atom.gameserver.model;
import ru.atom.gameserver.geometry.Point;
/**
* Created by gammaker on 05.03.2017.
*/
public abstract class GameObject {
public final int id;
public final GameSession session;
// position in 1/1000 of pixels
protected Point pos;
public GameObject(int x, int y, GameSession session) {
pos = new Point(x * 1000, y * 1000);
id = session.getUniqueId();
this.session = session;
}
public Point getPosition() {
return new Point(pos.x / 1000, pos.y / 1000);
}
// x coordinate in pixels
public int getX() {
return (pos.x + 500) / 1000;
}
// y coordinate in pixels
public int getY() {
return (pos.y + 500) / 1000;
}
public abstract void addToReplica(StringBuilder sb);
public int getTileX() {
return (getX() + Level.TILE_WIDTH / 2) / Level.TILE_WIDTH;
}
public int getTileY() {
return (getY() + Level.TILE_HEIGHT / 2) / Level.TILE_HEIGHT;
}
public abstract char getCharCode();
}
| mit |
chilieu/bible-trivia | app/cache/_var_www_html_dev.chilieu.me_app_views_layouts_index.volt.php | 1900 | <!DOCTYPE html>
<html lang="en">
<head>
<?php $this->partial("shared/header") ?>
</head>
<body>
<div class="container-full">
<img src="/img/biblequizbanner.jpg" class="img-responsive" alt="Responsive image">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-xl-4 col-md-3 col-sm-12 visible-lg-* visible-md-*"></div>
<div class="col-xl-4 col-md-6 col-sm-12">
<?php $this->partial("shared/navs") ?>
</div>
<div class="col-xl-4 col-md-3 col-sm-12 visible-lg-* visible-md-*"></div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-xl-4 col-md-3 col-sm-12 visible-lg-* visible-md-*"></div>
<div class="col-xl-4 col-md-6 col-sm-12">
<?php echo $this->getContent(); ?>
</div>
<div class="col-xl-4 col-md-3 col-sm-12 visible-lg-* visible-md-*"></div>
</div>
</div>
<?php $this->partial("shared/footer") ?>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$('.fancybox').fancybox();
$('[data-toggle="popover"]').popover({trigger: 'hover','placement': 'top'});
// cache the id
var navbox = $('.nav-tabs');
// activate tab on click
navbox.on('click', 'a', function (e) {
var $this = $(this);
// prevent the Default behavior
e.preventDefault();
// set the hash to the address bar
window.location.hash = $this.attr('href');
// activate the clicked tab
$this.tab('show');
})
// if we have a hash in the address bar
if(window.location.hash){
// show right tab on load (read hash from address bar)
navbox.find('a[href="'+window.location.hash+'"]').tab('show');
}
});
</script>
| mit |
clair-design/clair | packages/icons/icons/Move.ts | 865 | export const Move = `
<svg viewBox="0 0 28 28">
<g fill="none" fill-rule="evenodd">
<path d="M14 2v8.5" stroke="currentColor" stroke-linecap="round"/>
<polyline stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" transform="rotate(90 14 3)" points="16 -1 12 3 16 7"/>
<polyline stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" transform="rotate(180 25 14)" points="27 10 23 14 27 18"/>
<path d="M14 26v-8.5" stroke="currentColor" stroke-linecap="round"/>
<polyline stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" transform="matrix(0 -1 -1 0 39 39)" points="16 21 12 25 16 29"/>
<path d="M26 14h-8.5M2 14h8.5" stroke="currentColor" stroke-linecap="round"/>
<polyline stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" points="5 10 1 14 5 18"/>
</g>
</svg>`;
| mit |
tom5454/Toms-Mod | src/main/java/com/tom/api/block/BlockContainerTomsMod.java | 6211 | package com.tom.api.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.BlockPistonExtension;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import com.tom.lib.api.tileentity.IOwnable;
import com.tom.util.TomsModUtils;
public abstract class BlockContainerTomsMod extends BlockContainer implements ICustomItemBlock {
public BlockContainerTomsMod(Material material, MapColor mapColor) {
super(material, mapColor);
this.setHardness(5);
this.setResistance(10);
}
public BlockContainerTomsMod(Material material) {
this(material, material.getMaterialMapColor());
this.setHardness(5);
this.setResistance(10);
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
int t = getRenderType();
return (t == -1 ? EnumBlockRenderType.INVISIBLE : (t == 1 ? EnumBlockRenderType.LIQUID : (t == 2 ? EnumBlockRenderType.ENTITYBLOCK_ANIMATED : (t == 3 ? EnumBlockRenderType.MODEL : EnumBlockRenderType.INVISIBLE))));
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity te = worldIn.getTileEntity(pos);
if (te != null && (!(te instanceof IItemTile) || ((IItemTile)te).dropInventory())) {
if (te instanceof IInventory) {
// InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory)
// te);
dropInventory(worldIn, pos, (IInventory) te);
}
/*if(te instanceof IFluidHandler){
IFluidHandler f = (IFluidHandler) te;
spillFluids(f, worldIn, pos);
}*/
}
super.breakBlock(worldIn, pos, state);
}
public int getRenderType() {
return 3;
}
protected AxisAlignedBB setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, EnumFacing dir) {
switch (dir) {
case DOWN:
return new AxisAlignedBB(minX, 1.0F - maxZ, minY, maxX, 1.0F - minZ, maxY);
case UP:
return new AxisAlignedBB(minX, minZ, minY, maxX, maxZ, maxY);
case NORTH:
return new AxisAlignedBB(1.0F - maxX, minY, 1.0F - maxZ, 1.0F - minX, maxY, 1.0F - minZ);
case EAST:
return new AxisAlignedBB(minZ, minY, 1.0F - maxX, maxZ, maxY, 1.0F - minX);
case WEST:
return new AxisAlignedBB(1.0F - maxZ, minY, minX, 1.0F - minZ, maxY, maxX);
default:
return new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ);
}
}
/*protected void spillFluids(IFluidHandler f, World world, BlockPos pos){
FluidTankInfo[] info = f.getTankInfo(EnumFacing.DOWN);
if(info != null && info.length > 0){
for(int i = 0;i<info.length;i++){
if(info[i] != null){
FluidEvent.fireEvent(new FluidSpilledEvent(info[i].fluid, world, pos));
}
}
}
}*/
protected void dropInventory(World worldIn, BlockPos pos, IInventory te) {
InventoryHelper.dropInventoryItems(worldIn, pos, te);
}
@Override
public ItemBlock createItemBlock() {
return new ItemBlock(this);
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
TileEntity tileEntity = world.getTileEntity(pos);
if(tileEntity instanceof IItemTile){
((IItemTile)tileEntity).getDrops(drops, world, pos, state, fortune);
}else
super.getDrops(drops, world, pos, state, fortune);
}
@Override
public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) {
if(willHarvest)return true;
return super.removedByPlayer(state, world, pos, player, willHarvest);
}
@Override
public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te, ItemStack stack) {
super.harvestBlock(worldIn, player, pos, state, te, stack);
worldIn.setBlockToAir(pos);
}
@SuppressWarnings("unchecked")
@Override
public boolean rotateBlock(World world, BlockPos pos, EnumFacing axis) {
IBlockState state = world.getBlockState(pos);
for (IProperty<?> prop : state.getProperties().keySet())
{
if ((prop.getName().equals("facing") || prop.getName().equals("rotation")) && prop.getValueClass() == EnumFacing.class)
{
Block block = state.getBlock();
if (!(block instanceof BlockBed) && !(block instanceof BlockPistonExtension))
{
IBlockState newState;
//noinspection unchecked
IProperty<EnumFacing> facingProperty = (IProperty<EnumFacing>) prop;
EnumFacing facing = state.getValue(facingProperty);
java.util.Collection<EnumFacing> validFacings = facingProperty.getAllowedValues();
// rotate horizontal facings clockwise
if (validFacings.size() == 4 && !validFacings.contains(EnumFacing.UP) && !validFacings.contains(EnumFacing.DOWN))
{
newState = state.withProperty(facingProperty, facing.rotateY());
}
else
{
// rotate other facings about the axis
EnumFacing rotatedFacing = facing.rotateAround(axis.getAxis());
if (validFacings.contains(rotatedFacing))
{
newState = state.withProperty(facingProperty, rotatedFacing);
}
else // abnormal facing property, just cycle it
{
newState = state.cycleProperty(facingProperty);
}
}
TomsModUtils.setBlockState(world, pos, newState);
return true;
}
}
}
return false;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
IOwnable te = (IOwnable) worldIn.getTileEntity(pos);
te.setOwner(placer.getName());
te.updatePlayerHandler();
}
}
| mit |
skaldengine/skald-engine | src/sk/display/Text.js | 490 | const pixi = require('pixi.js')
const FontStyle = require('sk/core/FontStyle')
class Text extends pixi.Text {
constructor(text, style) {
super(text)
this.style = new FontStyle(style)
}
get style() { return this._style }
set style(style) {
style = style || {}
if (style instanceof pixi.TextStyle) {
this._style = style
} else {
this._style = new FontStyle(style)
}
this.localStyleID = -1;
this.dirty = true;
}
}
module.exports = Text | mit |
rkrx/php-streams | src/Kir/Streams/SeekableStream.php | 470 | <?php
namespace Kir\Streams;
use Kir\Streams\Exceptions\IOException;
interface SeekableStream extends InputStream {
/**
* @throws IOException
* @param int $pos
* @return $this
*/
public function setPosition($pos);
/**
* @throws IOException
* @return int
*/
public function getPosition();
/**
* @throws IOException
* @return $this
*/
public function rewind();
/**
* @throws IOException
* @return int
*/
public function getSize();
} | mit |
moviepilot-de/omdb | app/models/votes/user_vote.rb | 25 | class UserVote < Vote
end | mit |
i2bskn/restrict_cache | lib/restrict_cache/railtie.rb | 590 | module RestrictCache
class Railtie < ::Rails::Railtie
initializer "restrict_cache" do
require "restrict_cache/rails_ext/all"
ActiveSupport.on_load(:action_controller) do
::ActionController::Base.send(
:include, RestrictCache::RailsExt::ActionController)
end
ActiveSupport.on_load(:active_record) do
::ActiveRecord::Base.send(
:include, RestrictCache::RailsExt::ActiveRecord::Base)
::ActiveRecord::Relation.send(
:include, RestrictCache::RailsExt::ActiveRecord::Relation)
end
end
end
end
| mit |
ameet007/popin | application/views/admin/contact_request/list.php | 21777 |
<div class="content-page">
<div class="content">
<div class="container">
<!-- BEGIN PAGE BASE CONTENT -->
<!--Module Title-->
<div class="row">
<div class="col-md-12">
<div class="page-title-box">
<?php if($message_notification = $this->session->flashdata('message_notification')) { ?>
<!-- Message Notification Start -->
<div id="message_notification">
<div class="alert alert-<?= $this->session->flashdata('class'); ?>">
<button class="close" data-dismiss="alert" type="button">×</button>
<strong>
<?= $this->session->flashdata('message_notification'); ?>
</strong>
</div>
</div>
<!-- Message Notification End -->
<?php } ?>
<h4 class="page-title"><?= $module_heading; ?></h4>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="portlet light portlet-fit portlet-datatable bordered">
<div class="portlet-body">
<div class="table-container">
<div class="table-actions-wrapper">
<div class="col-sm-12 pull-right">
<div class="col-sm-8"><select class="table-group-action-input form-control" name="status">
<option value="">Select...</option>
<option value="Pending">Pending</option>
<option value="Active">Active</option>
<option value="DeActive">DeActive</option>
<option value="Delete by Admin">Delete</option>
</select></div>
<div class="col-sm-4">
<button class="btn btn-teal btn-bordered waves-light waves-effect m-b-5 table-group-action-submit"> Submit</button>
</div>
</div>
</div>
<table class="table table-striped table-bordered table-hover table-checkable" id="contact_request_list">
<thead>
<tr role="row" class="heading">
<th width="2%">
<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
<input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" />
<span></span>
</label>
</th>
<th width="15%"> Subject </th>
<th width="10%"> Name </th>
<th width="15%">Email</th>
<th width="10%">Number</th>
<th width="12%"> Created Date</th>
<th width="12%"> Updated Date</th>
<th width="10%"> Status </th>
<th width="14%"> Actions </th>
</tr>
<tr role="row" class="filter">
<td> </td>
<td>
<input type="text" class="form-control form-filter input-sm" name="subject">
</td>
<td>
<input type="text" class="form-control form-filter input-sm" name="name">
</td>
<td>
<input type="text" class="form-control form-filter input-sm" name="email">
</td>
<td>
<input type="text" class="form-control form-filter input-sm" name="number">
</td>
<td>
<div class="input-group date date-picker margin-bottom-5" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="order_date_from" placeholder="From">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button">
<i class="fa fa-calendar"></i>
</button>
</span>
</div>
<div class="input-group date date-picker" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="order_date_to" placeholder="To">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button">
<i class="fa fa-calendar"></i>
</button>
</span>
</div>
</td>
<td>
<div class="input-group date date-picker margin-bottom-5" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="order_date_from_updated" placeholder="From">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button">
<i class="fa fa-calendar"></i>
</button>
</span>
</div>
<div class="input-group date date-picker" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="order_date_to_updated" placeholder="To">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button">
<i class="fa fa-calendar"></i>
</button>
</span>
</div>
</td>
<td>
<select name="status" class="form-control form-filter input-sm">
<option value="">Select...</option>
<option value="Active">Active</option>
<option value="DeActive">DeActive</option>
<option value="Delete By Admin">Delete</option>
</select>
</td>
<td>
<div class="m-b-5">
<button class="btn btn-sm btn-success filter-submit margin-bottom">
<i class="fa fa-search"></i> Search</button>
</div>
<button class="btn btn-sm btn-danger filter-cancel">
<i class="fa fa-times"></i> Reset</button>
</td>
</tr>
</thead>
<tbody> </tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
</div>
</div>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Contact Request</h3>
</div>
<div class="modal-body form">
<form action="<?= base_url(ADMIN_DIR.'/contact_request/update_contact_request'); ?>" id="form" name="form" class="form-horizontal" method="post">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Requester Name</label>
<div class="col-md-9 nameBlock">
<input name="name" placeholder="Aliasgar Vanak" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Email</label>
<div class="col-md-9 emailBlock">
<input name="email" placeholder="aliasgar.vanak@gmail.com" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Number</label>
<div class="col-md-9 numberBlock">
<input name="number" placeholder="+917383862385" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Subject</label>
<div class="col-md-9 subjectBlock">
<input name="subject" placeholder="Account Is Not Active" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Message</label>
<div class="col-md-9 messageBlock">
<textarea name="message" id="message" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Status</label>
<div class="col-md-9 statusBlock">
<select class="form-control" name="status">
<option value="Pending">Pending</option>
<option value="Active">Active</option>
<option value="DeActive">DeActive</option>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<input type="hidden" name="id" value="" id="">
<span class="removeSaveButton"> <input type="submit" id="btnSave" name="btnSave" class="btn btn-primary" value="Save"></span>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
<script>
var TableDatatablesAjax = function () {
var initPickers = function () {
//init date pickers
$('.date-picker').datepicker({
rtl: App.isRTL(),
autoclose: true
});
}
var contact_request_list = function () {
var grid = new Datatable();
grid.init({
src: $("#contact_request_list"),
onSuccess: function (grid, response) {
// grid: grid object
// response: json object of server side ajax response
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
onDataLoad: function(grid) {
// execute some code on ajax data load
},
loadingMessage: 'Loading...',
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js).
// So when dropdowns used the scrollable div should be removed.
//"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[10, 20, 50, 100, 150, -1],
[10, 20, 50, 100, 150, "All"] // change per page values here
],
"pageLength": 10, // default record count per page
"ajax": {
"url": "<?= base_url(ADMIN_DIR.'/contact_request/get_all_list'); ?>", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
App.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
App.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
return {
//main function to initiate the module
init: function () {
initPickers();
contact_request_list();
}
};
}();
jQuery(document).ready(function() {
TableDatatablesAjax.init();
$('.btn-group').button();
});
</script>
<!--Customer List Section End-->
<script>
function view_contact_request(id)
{
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url(ADMIN_DIR.'/contact_request/view/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('.nameBlock').html(data.name);
$('.numberBlock').html(data.number);
$('.emailBlock').html(data.email);
$('.subjectBlock').html(data.subject);
$('.messageBlock').html(data.message);
$('.statusBlock').html(data.status);
$('.removeSaveButton').html('');
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('View Contact Request'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
</script> | mit |
dwd/acapd | src/include/infotrope/datastore/datastore.hh | 5185 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/***************************************************************************
* Thu Feb 13 12:53:37 2003
* Copyright 2003 Dave Cridland
* dave@cridland.net
****************************************************************************/
#ifndef INFOTROPE_DATASTORE_DATASTORE_HH
#define INFOTROPE_DATASTORE_DATASTORE_HH
#include <infotrope/utils/magic-ptr.hh>
#include <infotrope/threading/rw-lock.hh>
#include <infotrope/datastore/path.hh>
#include <infotrope/datastore/dataset.hh>
#include <list>
#include <map>
#include <string>
namespace Infotrope {
namespace Data {
class Datastore {
public:
typedef enum {
Normal = 0,
// The path is '/', or there exists a parent dataset which is also normal, and contains an entry named by the last path component with a subdataset value including "."
Virtual = 1,
// The path is effectively a redirection, but always followed by default. The path does not exist if NOINHERIT is specified. A new dataset created at this path should create a dataset which inherits from the real path this points to.
Logical = 1<<1
// The path is produced by following entries with subdataset values which are local, but may not include "."
} path_type_t;
Datastore();
~Datastore();
private:
Datastore( Datastore const & );
public:
Infotrope::Utils::magic_ptr<Dataset> const & top() const;
Infotrope::Utils::magic_ptr<Dataset> const & dataset( Path const & ) const;
Infotrope::Utils::magic_ptr<Dataset> const & dataset( Path const &, path_type_t ) const;
bool exists( Path const & ) const;
private:
bool exists_real( Path const & ) const;
public:
void rename( Path const &, Path const & );
Infotrope::Utils::magic_ptr<Dataset> const & create( Path const &, bool = true );
Infotrope::Utils::magic_ptr<Dataset> const & create_virtual( Path const & );
private:
Infotrope::Utils::magic_ptr<Dataset> const & create( Path const &, Infotrope::Utils::magic_ptr<Subcontext> const &, Infotrope::Utils::magic_ptr<Subcontext> const &, Infotrope::Utils::magic_ptr<Subcontext> const &, bool );
public:
void erase( Path const &, bool = true );
private:
void erase_final( Path const &, bool = true );
public:
static Datastore & datastore();
static Datastore const & datastore_read();
Infotrope::Threading::RWMutex & lock() {
return m_mutex;
}
Infotrope::Threading::RWMutex const & lock() const {
return m_mutex;
}
void rollback();
bool commit(); // Returns true if a complete rewrite is needed.
typedef std::map< Utils::StringRep::entry_type, Infotrope::Utils::magic_ptr < Dataset >, Utils::StringRep::entry_type_less > t_datasets;
/*typedef t_datasets::const_iterator const_iterator;
const_iterator begin() const {
return m_datasets.begin();
}
const_iterator end() const {
return m_datasets.end();
}*/
class const_iterator {
public:
typedef std::pair< Utils::StringRep::entry_type const, Infotrope::Utils::magic_ptr<Dataset> > t_value;
typedef t_datasets::const_iterator t_master;
const_iterator( t_master m, t_datasets const * q );
const_iterator( t_master m, t_datasets const * q, t_datasets const * x );
t_value const & operator *() const;
const_iterator & operator++();
bool operator!=( const_iterator const & x ) const {
if( x.m_intrans==m_intrans ) {
if( x.m_scan_trans==m_scan_trans ) {
return m_master!=x.m_master;
}
}
return true;
}
private:
std::set<Utils::StringRep::entry_type> m_encountered;
t_master m_master;
t_datasets const * m_datasets;
t_datasets const * m_pending;
bool m_intrans;
bool m_scan_trans;
};
const_iterator begin() const;
const_iterator end() const;
private:
void add_subdataset( Path const &, Infotrope::Utils::StringRep::entry_type const & ) const;
void rename_priv( Path const &, Path const & );
Infotrope::Threading::RWMutex m_mutex;
t_datasets m_datasets;
t_datasets m_pending;
typedef std::pair< Utils::StringRep::entry_type, Utils::weak_ptr<Dataset> > t_last_hit;
Infotrope::Utils::magic_ptr<t_last_hit> m_last;
Infotrope::Utils::magic_ptr<t_last_hit> m_last_trans;
//t_datasets m_virtuals;
//t_datasets m_virtuals_pending;
};
}
}
#endif
| mit |
davetimmins/Anywhere.ArcGIS | src/Anywhere.ArcGIS/Operation/ArcGISServerOperation.cs | 1267 | using System;
using Anywhere.ArcGIS.Common;
using System.Runtime.Serialization;
namespace Anywhere.ArcGIS.Operation
{
/// <summary>
/// Base class for calls to an ArcGIS Server operation
/// </summary>
public class ArcGISServerOperation : CommonParameters, IHttpOperation
{
public ArcGISServerOperation(IEndpoint endpoint, Action beforeRequest = null, Action<string> afterRequest = null)
{
Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
BeforeRequest = beforeRequest;
AfterRequest = afterRequest;
}
public ArcGISServerOperation(string endpoint, Action beforeRequest = null, Action<string> afterRequest = null)
: this(new ArcGISServerEndpoint(endpoint), beforeRequest, afterRequest)
{ }
[IgnoreDataMember]
public Action BeforeRequest { get; }
[IgnoreDataMember]
public Action<string> AfterRequest { get; }
[IgnoreDataMember]
public IEndpoint Endpoint { get; }
[IgnoreDataMember]
public string RelativeUrl => Endpoint.RelativeUrl;
public string BuildAbsoluteUrl(string rootUrl) => Endpoint.BuildAbsoluteUrl(rootUrl);
}
}
| mit |
cburgmer/rasterizeHTML.js | test/specs/proxies.test.js | 6720 | describe("XHR Proxies", function () {
"use strict";
var originaLPromise;
var mockPromisesToResolveSynchronously = function () {
window.Promise = testHelper.SynchronousPromise;
};
beforeEach(function () {
originaLPromise = window.Promise;
});
afterEach(function () {
window.Promise = originaLPromise;
});
describe("finishNotifyingXhr", function () {
describe("mocked XHR", function () {
var callback, originalXHRInstance, xhrMockConstructor;
var aXHRMockInstance = function () {
var onloadHandler;
return {
send: function () {},
addEventListener: function (event, handler) {
onloadHandler = handler;
},
mockDone: function () {
onloadHandler();
},
};
};
beforeEach(function () {
callback = jasmine.createSpy("callback");
originalXHRInstance = [];
xhrMockConstructor = function () {
var xhrMockInstance = aXHRMockInstance();
originalXHRInstance.push(xhrMockInstance);
return xhrMockInstance;
};
});
it("should notify when a pending AJAX request has finished", function () {
mockPromisesToResolveSynchronously();
var finishNotifyingXhrProxy =
proxies.finishNotifyingXhr(xhrMockConstructor),
xhr = finishNotifyingXhrProxy();
// Start XHR request
xhr.send();
finishNotifyingXhrProxy
.waitForRequestsToFinish()
.then(callback);
expect(callback).not.toHaveBeenCalled();
originalXHRInstance[0].mockDone();
expect(callback).toHaveBeenCalledWith({ totalCount: 1 });
});
it("should notify when multipel pending AJAX request have finished", function () {
mockPromisesToResolveSynchronously();
var finishNotifyingXhrProxy =
proxies.finishNotifyingXhr(xhrMockConstructor),
xhr1 = finishNotifyingXhrProxy(),
xhr2 = finishNotifyingXhrProxy();
// Start XHR request
xhr1.send();
xhr2.send();
finishNotifyingXhrProxy
.waitForRequestsToFinish()
.then(callback);
originalXHRInstance[0].mockDone();
expect(callback).not.toHaveBeenCalled();
originalXHRInstance[1].mockDone();
expect(callback).toHaveBeenCalledWith({ totalCount: 2 });
});
it("should handle an onload handler attached to the proxied instance", function (done) {
var finishNotifyingXhrProxy =
proxies.finishNotifyingXhr(xhrMockConstructor),
xhr = finishNotifyingXhrProxy();
xhr.onload = function myOwnOnLoadHandler() {};
xhr.send();
finishNotifyingXhrProxy
.waitForRequestsToFinish()
.then(function () {
done();
});
originalXHRInstance[0].mockDone();
expect(true).toBe(true); // work around warning from jasmine that no expectation is given
});
it("should finish when no XHR request has been started", function (done) {
var finishNotifyingXhrProxy =
proxies.finishNotifyingXhr(xhrMockConstructor);
finishNotifyingXhrProxy
.waitForRequestsToFinish()
.then(function () {
done();
});
expect(true).toBe(true); // work around warning from jasmine that no expectation is given
});
it("should notify even if called after all requests resovled", function (done) {
var finishNotifyingXhrProxy =
proxies.finishNotifyingXhr(xhrMockConstructor),
xhr = finishNotifyingXhrProxy();
xhr.send();
originalXHRInstance[0].mockDone();
finishNotifyingXhrProxy
.waitForRequestsToFinish()
.then(function () {
done();
});
expect(true).toBe(true); // work around warning from jasmine that no expectation is given
});
});
describe("integration", function () {
it("should notify after file has loaded", function (done) {
var FinishNotifyingXhrProxy = proxies.finishNotifyingXhr(
window.XMLHttpRequest
),
xhr = new FinishNotifyingXhrProxy(),
called = [],
markDoneInAnyOrder = function (key) {
called.push(key);
if (called.length === 2) {
expect(called).toContain("onload");
expect(called).toContain("waitForRequestsToFinish");
done();
}
};
xhr.onload = function () {
markDoneInAnyOrder("onload");
};
xhr.open("GET", testHelper.fixturesPath + "test.html", true);
xhr.send(null);
FinishNotifyingXhrProxy.waitForRequestsToFinish().then(
function (result) {
expect(result).toEqual({ totalCount: 1 });
markDoneInAnyOrder("waitForRequestsToFinish");
}
);
});
});
});
describe("baseUrlRespectingXhr", function () {
it("should load file relative to given base url", function (done) {
var baseUrl = testHelper.fixturesPath,
BaseUrlRespectingProxy = proxies.baseUrlRespectingXhr(
window.XMLHttpRequest,
baseUrl
),
xhr = new BaseUrlRespectingProxy();
xhr.onload = function () {
expect(xhr.responseText).toMatch(/Test page/);
done();
};
xhr.open("GET", "test.html", true);
xhr.send(null);
});
});
});
| mit |
slavik57/typescript-playground | src/advancedTypes/unionTypes.ts | 775 | // The video for this file
// https://youtu.be/IpP6xbkojy4
export class Cat {
constructor(public name: string, public numberOfLives: number) { }
public eat(): void {
}
}
export class Dog {
constructor(public name: string, public isBarkingOnNeighbors: boolean) { }
public eat(): void {
}
}
export class Person {
constructor(public name: string, age: number) { }
public eat(): void {
}
}
function rename(thing: Cat | Dog | Person, newName: string): void {
thing.name = newName;
}
rename(new Cat('Fluffy', 9), 'Mitzy');
rename(new Dog('Spark', true), 'Speedy');
rename(new Person('Ben', 18), 'John');
function printDate(date: string | number | Date): void {
// Prints the date...
}
printDate(new Date());
printDate('13/05/2017');
printDate(321654321); | mit |
mmkassem/gitlabhq | spec/graphql/types/query_type_spec.rb | 1609 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe GitlabSchema.types['Query'] do
it 'is called Query' do
expect(described_class.graphql_name).to eq('Query')
end
it 'has the expected fields' do
expected_fields = %i[
project
namespace
group
echo
metadata
current_user
snippets
design_management
milestone
user
users
issue
]
expect(described_class).to have_graphql_fields(*expected_fields).at_least
end
describe 'namespace field' do
subject { described_class.fields['namespace'] }
it 'finds namespaces by full path' do
is_expected.to have_graphql_arguments(:full_path)
is_expected.to have_graphql_type(Types::NamespaceType)
is_expected.to have_graphql_resolver(Resolvers::NamespaceResolver)
end
end
describe 'project field' do
subject { described_class.fields['project'] }
it 'finds projects by full path' do
is_expected.to have_graphql_arguments(:full_path)
is_expected.to have_graphql_type(Types::ProjectType)
is_expected.to have_graphql_resolver(Resolvers::ProjectResolver)
end
end
describe 'metadata field' do
subject { described_class.fields['metadata'] }
it 'returns metadata' do
is_expected.to have_graphql_type(Types::MetadataType)
is_expected.to have_graphql_resolver(Resolvers::MetadataResolver)
end
end
describe 'issue field' do
subject { described_class.fields['issue'] }
it 'returns issue' do
is_expected.to have_graphql_type(Types::IssueType)
end
end
end
| mit |
Byron/catchit-rs | src/types.rs | 3070 | use vecmath::{self, vec2_sub, vec2_len};
pub type Scalar = f64;
/// [width, height]
pub type Extent = vecmath::Vector2<Scalar>;
/// [x, y]
pub type Position = vecmath::Vector2<Scalar>;
pub type Velocity = vecmath::Vector2<Scalar>;
use transition::Transition;
/// Points on screen. Usually they correspond to pixels, but might not on a
/// `HiDPI` display
pub type Pt = Scalar;
/// Represents a shape used for collision detection
#[derive(Debug, Clone, PartialEq)]
pub enum CollisionShape {
Square,
Circle,
}
/// A game object which knows a few things about itself
#[derive(Debug, Clone, PartialEq)]
pub struct Object {
pub pos: Position,
pub half_size: Pt,
pub shape: CollisionShape,
}
impl Object {
pub fn left(&self) -> Scalar {
self.pos[0] - self.half_size
}
pub fn right(&self) -> Scalar {
self.pos[0] + self.half_size
}
pub fn top(&self) -> Scalar {
self.pos[1] - self.half_size
}
pub fn bottom(&self) -> Scalar {
self.pos[1] + self.half_size
}
/// Returns true if both objects intersect
pub fn intersects(&self, other: &Object) -> bool {
match (&self.shape, &other.shape) {
(&CollisionShape::Circle, &CollisionShape::Circle) => {
vec2_len(vec2_sub(self.pos, other.pos)) <= self.half_size + other.half_size
}
_ => {
self.left() <= other.right() && self.right() >= other.left() &&
self.top() <= other.bottom() && self.bottom() >= other.top()
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ObstacleKind {
/// Enables a temporary attractive force
AttractiveForceSwitch,
/// Causes all other obstacles to hide themselves for a while
InvisibiltySwitch,
/// Kills the player
Deadly,
}
/// An obstacle the hunter can collide with
#[derive(Debug, Clone, PartialEq)]
pub struct Obstacle {
pub kind: ObstacleKind,
pub object: Object,
pub velocity: Velocity,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Hunter {
pub object: Object,
pub force: Scalar,
pub velocity: Velocity,
}
/// It maintains the state of the game and expects to be updated with
/// time-delta information to compute the next state.
///
/// Please note that the coordinates used in the playing field start at 0
/// and grow
#[derive(Debug, Clone, PartialEq)]
pub struct State {
/// The playing field
pub field: Extent,
/// The player's character
pub hunter: Hunter,
/// Hunted the player's character
pub prey: Object,
/// Obstacles the hunter must avoid to prevent game-over
pub obstacles: Vec<Obstacle>,
/// score of the current game
pub score: u32,
/// multiply prey score with the given value
pub score_coeff: Scalar,
/// transition between opaque and invisible obstacles
pub obstacle_opacity: Transition,
/// transition between no attracting force and maximum one
pub attracting_force: Transition,
/// Last delta-time during update
pub last_dt: f64,
}
| mit |
jumpinjackie/mapguide-react-weblayout | src/containers/selected-feature-count.tsx | 675 | import * as React from "react";
import { SelectedFeatureCount } from "../components/selected-feature-count";
import { useViewerLocale, useActiveMapSelectionSet } from './hooks';
export interface ISelectedFeatureCountContainerProps {
style?: React.CSSProperties;
}
export const SelectedFeatureCountContainer = (props: ISelectedFeatureCountContainerProps) => {
const { style } = props;
const selection = useActiveMapSelectionSet();
const locale = useViewerLocale();
if (selection && selection.FeatureSet) {
return <SelectedFeatureCount locale={locale} style={style} selection={selection.FeatureSet} />;
} else {
return <div />;
}
} | mit |
xizhouhezai/react-app | xizhouhezai/js/component/NavBar.js | 1330 | import React,{ Component } from 'react';
import {
View,
StyleSheet,
Text,
Dimensions
} from 'react-native';
import PropTypes from 'prop-types';
const { width,height } = Dimensions.get('window');
export default class NavBar extends Component{
static propTypes = {
leftItems: PropTypes.element,
titleItems: PropTypes.string,
rightItems: PropTypes.element,
};
constructor(props){
super(props);
}
render() {
return(
<View style = {styles.container}>
// 左边的视图
<View>
{this.props.leftItems}
</View>
{/* 中间的视图 */}
<View>
<Text>
{this.props.titleItems}
</Text>
</View>
{/* 右边的视图 */}
<View>
{this.props.rightItems}
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center',
width: width,
height: 66,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
}
})
| mit |
talyguryn/kohana | public/src/js/main.js | 358 | 'use strict';
var kohana = {};
kohana.init = function () {
'use strict';
/** Instructions to do on load bundle */
};
/**
* Add modules here
* kohana.myplugin = require('./myplugin');
*/
kohana.ajax = require('./modules/ajax');
kohana.transport = require('./modules/transport');
/**
* Export module for Webpack
*/
module.exports = kohana;
| mit |
maehler/seqpoet | seqpoet/tests/test_search.py | 2437 | from collections import defaultdict
import os
from nose.tools import raises
from nose.plugins.skip import SkipTest
from seqpoet.search import search, hamming_distance
from seqpoet import Sequence
from seqpoet import GenBank
from seqpoet.genbank import Location
class TestHammingDistance:
@raises(ValueError)
def test_sequences_of_different_length(self):
hamming_distance('gattaca', 'gatt')
def test_wikipedia_examples(self):
assert hamming_distance('karolin', 'kathrin') == 3
assert hamming_distance('karolin', 'kerstin') == 3
assert hamming_distance('1011101', '1001001') == 2
assert hamming_distance('2173896', '2233796') == 3
def test_exact_matches(self):
assert hamming_distance('karolin', 'karolin') == 0
assert hamming_distance('gattaca', 'gattaca') == 0
def test_one_mismatch(self):
assert hamming_distance('niklas', 'niclas') == 1
class TestSearch:
def setUp(self):
self.haystack = 'accgtgacgggcacgaggcatcattatctagcagcacatg'
self.needle = 'gaggcat'
self.genbankdir = os.path.join(os.path.expanduser('~'), 'Dropbox',
'operon_extractor', 'data_genbank')
self.lmg718 = os.path.join(self.genbankdir, 'LMG718-cremoris.gb')
def test_exact_match(self):
res = search(self.needle, self.haystack)
assert res == [14], 'expected one match in pos 14, found {0}' \
.format(str(res))
def test_one_mismatch(self):
res = search(self.needle, self.haystack, mismatches=1)
assert res == [14], 'expected one match in pos 14, found {0}' \
.format(str(res))
res = search('ggg', self.haystack, mismatches=1)
assert res == [3, 7, 8, 9, 14, 15, 16], 'found {0}'.format(str(res))
def test_search_genbank(self):
if not os.path.exists(self.genbankdir):
raise SkipTest
gb = GenBank(self.lmg718)
with open(os.path.join(self.genbankdir, '..', 'primers.txt')) as f:
probe = Sequence(f.readline().strip())
matches = defaultdict(list)
for locus in gb:
matches[locus.name].extend(search(str(probe), str(locus.seq), mismatches=0))
for locus, starts in matches.iteritems():
for s in starts:
for gbl in gb.get_locus_from_name(locus):
assert gbl.seq[s:s + len(probe)] == probe
| mit |
galpratama/keluhanku-hackathon | application/views/template.php | 12076 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Keluhanku | Admin Panel</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">-->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/font-awesome-4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<!--<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">-->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/ionicons-2.0.1/css/ionicons.min.css">
<!-- DataTables -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/datatables/dataTables.bootstrap.css">
<!-- Theme style -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/dist/css/skins/_all-skins.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-red sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="index2.html" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>KL</b>H</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><small>Keluhanku <b>Admin</b></small></span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?php echo base_url() ?>assets/dist/img/user2-160x160.jpg" class="user-image" alt="User Image">
<span class="hidden-xs"><?php echo $this->session->userdata('nama_lengkap'); ?></span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="<?php echo base_url() ?>assets/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
<p>
<?php echo $this->session->userdata('nama_lengkap'); ?> - Web Developer
<small>Member since October. 2015</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="col-xs-4 text-center">
<a href="#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Friends</a>
</div>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="<?php echo base_url(); ?>auth/logout" class="btn btn-default btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="<?php echo base_url() ?>assets/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p>Sumatera Selatan</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
<!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li>
<?php echo anchor('dashboard', '<i class="fa fa-laptop"></i> <span>DASHBOARD</span>
'); ?>
</li>
<li>
<?php echo anchor('masalah', '<i class="fa fa-object-ungroup"></i> <span>DAFTAR MASALAH</span>
<small class="label pull-right bg-red">6</small>'); ?>
</a>
</li>
<li>
<?php echo anchor('masalah/add', ' <i class="fa fa-pencil-square-o"></i><span>ENTRY ISSUE MASALAH</span>
'); ?>
</li>
<li>
<?php echo anchor('inbox', '<i class="fa fa-newspaper-o"></i> <span>PESAN MASUK</span>
<small class="label pull-right bg-red">9</small>'); ?>
</li>
<li>
<?php echo anchor('instansi', '<i class="fa fa-language"></i> <span>DAFTAR INSTANSI</span>
<small class="label pull-right bg-red">4</small>'); ?>
</li>
<li>
<?php echo anchor('volunteer', '<i class="fa fa-users"></i> <span>DAFTAR VOLUNTEER</span>
<small class="label pull-right bg-red">7</small>'); ?>
</li>
<li>
<?php echo anchor('auth/logout', '<i class="fa fa-sign-out"></i> <span>LOGOUT</span>
'); ?>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Keluhanku
<small>Admin Area</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Beranda</a></li>
<li><a href="#">Admin Area</a></li>
</ol>
</section>
<?php
echo $contents;
?>
</div><!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 0.1.2
</div>
<strong>Copyright © 2015 <a href="#">BelajarKoding.net</a> and <a href="#">Belajar.PHP.net</a> Collaboration.</strong> Made with love at Hackathon Merdeka 2.0
</footer>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->
<!-- jQuery 2.1.4 -->
<script src="<?php echo base_url() ?>assets/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="<?php echo base_url() ?>assets/bootstrap/js/bootstrap.min.js"></script>
<!-- DataTables -->
<script src="<?php echo base_url() ?>assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url() ?>assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- SlimScroll -->
<script src="<?php echo base_url() ?>assets/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="<?php echo base_url() ?>assets/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url() ?>assets/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo base_url() ?>assets/dist/js/demo.js"></script>
<!-- page script -->
<script>
$(function () {
$("#example1").DataTable();
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false
});
});
</script>
</body>
</html>
| mit |
FiB3/pyWebRedis | src/redis.py | 3021 | """Wrapper module for REDIS."""
import aioredis
import logging
ENCODING_UTF = "UTF-8"
class RedisAIO(object):
"""Wrapper class for aioredis."""
def __init__(self, url="localhost", port=6379, password=None):
"""
Constructor for the RedisAIO.
:param url: Url of the server.
:type url: string
:param port: Port of the server
:type port: integer
:param password: password for the authentication.
:type password: string
"""
self.url = url
self.port = port
self.password = password
self.redis = None
async def connect(self):
"""Connect to the REDIS."""
# connect:
self.redis = await aioredis.create_redis((self.url, self.port))
# does the have a pass?
if self.password:
self.redis.auth(self.password)
async def close(self):
"""Close the connection."""
self.redis.close()
async def run_cmd(self, command):
"""
Run a single command in the REDIS and return its outcome.
:param command: Complete command which you want to run.
:type command: string
:return: stringified response.
:rtype: string (not bytes).
"""
# split command into array:
cmd = command.replace(" ", " ").split(" ")
# run the command:
try:
res = await self.redis.execute(*cmd)
except aioredis.ReplyError as err:
res = "{}".format(err)
except aioredis.ConnectionClosedError:
logging.info("Connection was closed - reconnect.")
await self.connect()
res = await self.redis.execute(*cmd) # lets not go into recursion...
# return decoded answer:
if type(res) == list:
# in case of list response, stringify:
res = ['{}) "{}"'.format(res.index(el) + 1, el.decode(ENCODING_UTF)) for el in res]
# that was not very pythonic, I know ;)
res = "<br>".join(res)
elif type(res) == bytes:
# decode bytes to string:
res = res.decode(ENCODING_UTF)
return res
################################################################################
# TESTS: #######################################################################
################################################################################
async def tests(loop):
"""Main method for testing this class."""
logging.basicConfig(level=logging.DEBUG)
redis = RedisAIO()
await redis.connect()
assert (await redis.run_cmd("SET new-key new-value")) == "OK", \
"Error on correct command response test."
assert (await redis.run_cmd("whatever")) == "ERR unknown command 'WHATEVER'", \
"Error on incorrect command response test."
await redis.close()
if __name__ == "__main__":
# just tests going on here:
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(tests(loop))
| mit |