repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
roblayton/mouse-arrow | node_modules/grunt-contrib-jshint/node_modules/jshint/src/state.js | 493 | "use strict";
var state = {
syntax: {},
reset: function () {
this.tokens = {
prev: null,
next: null,
curr: null
};
this.option = {};
this.ignored = {};
this.directive = {};
this.jsonMode = false;
this.jsonWarnings = [];
this.lines = [];
this.tab = "";
this.cache = {}; // Node.JS doesn't have Map. Sniff.
this.ignoreLinterErrors = false; // Blank out non-multi-line-commented
// lines when ignoring linter errors
}
};
exports.state = state;
| bsd-3-clause |
BrennanConroy/corefx | src/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnStatus.cs | 1011 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.SqlServer.TDS.ColInfo
{
/// <summary>
/// Status of the column
/// </summary>
[Flags]
public enum TDSColumnStatus : byte
{
/// <summary>
/// The column was the result of an expression
/// </summary>
Expression = 0x04,
/// <summary>
/// The column is part of a key for the associated table
/// </summary>
Key = 0x08,
/// <summary>
/// The column was not requested, but was added because it was part of a key for the associated table
/// </summary>
Hidden = 0x10,
/// <summary>
/// the column name is different than the requested column name in the case of a column alias
/// </summary>
DifferentName = 0x20
}
}
| mit |
unsiloai/syntaxnet-ops-hack | tensorflow/contrib/learn/python/learn/estimators/multioutput_test.py | 1696 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Multi-output tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
from tensorflow.contrib.learn.python import learn
from tensorflow.contrib.learn.python.learn.estimators._sklearn import mean_squared_error
from tensorflow.python.platform import test
class MultiOutputTest(test.TestCase):
"""Multi-output tests."""
def testMultiRegression(self):
random.seed(42)
rng = np.random.RandomState(1)
x = np.sort(200 * rng.rand(100, 1) - 100, axis=0)
y = np.array([np.pi * np.sin(x).ravel(), np.pi * np.cos(x).ravel()]).T
regressor = learn.LinearRegressor(
feature_columns=learn.infer_real_valued_columns_from_input(x),
label_dimension=2)
regressor.fit(x, y, steps=100)
score = mean_squared_error(np.array(list(regressor.predict_scores(x))), y)
self.assertLess(score, 10, "Failed with score = {0}".format(score))
if __name__ == "__main__":
test.main()
| apache-2.0 |
yxcoin/yxcoin | src/boost_1_55_0/boost/multiprecision/concepts/mp_number_archetypes.hpp | 7882 | ///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
#ifndef BOOST_MATH_CONCEPTS_ER_HPP
#define BOOST_MATH_CONCEPTS_ER_HPP
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <boost/cstdint.hpp>
#include <boost/multiprecision/number.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/mpl/list.hpp>
namespace boost{
namespace multiprecision{
namespace concepts{
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4244)
#endif
struct number_backend_float_architype
{
typedef mpl::list<long long> signed_types;
typedef mpl::list<unsigned long long> unsigned_types;
typedef mpl::list<long double> float_types;
typedef int exponent_type;
number_backend_float_architype()
{
std::cout << "Default construct" << std::endl;
}
number_backend_float_architype(const number_backend_float_architype& o)
{
std::cout << "Copy construct" << std::endl;
m_value = o.m_value;
}
number_backend_float_architype& operator = (const number_backend_float_architype& o)
{
m_value = o.m_value;
std::cout << "Assignment (" << m_value << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator = (unsigned long long i)
{
m_value = i;
std::cout << "UInt Assignment (" << i << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator = (long long i)
{
m_value = i;
std::cout << "Int Assignment (" << i << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator = (long double d)
{
m_value = d;
std::cout << "long double Assignment (" << d << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator = (const char* s)
{
try
{
m_value = boost::lexical_cast<long double>(s);
}
catch(const std::exception&)
{
BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Unable to parse input string: \"") + s + std::string("\" as a valid floating point number.")));
}
std::cout << "const char* Assignment (" << s << ")" << std::endl;
return *this;
}
void swap(number_backend_float_architype& o)
{
std::cout << "Swapping (" << m_value << " with " << o.m_value << ")" << std::endl;
std::swap(m_value, o.m_value);
}
std::string str(std::streamsize digits, std::ios_base::fmtflags f)const
{
std::stringstream ss;
ss.flags(f);
if(digits)
ss.precision(digits);
else
ss.precision(std::numeric_limits<long double>::digits10 + 2);
boost::intmax_t i = m_value;
boost::uintmax_t u = m_value;
if(!(f & std::ios_base::scientific) && m_value == i)
ss << i;
else if(!(f & std::ios_base::scientific) && m_value == u)
ss << u;
else
ss << m_value;
std::string s = ss.str();
std::cout << "Converting to string (" << s << ")" << std::endl;
return s;
}
void negate()
{
std::cout << "Negating (" << m_value << ")" << std::endl;
m_value = -m_value;
}
int compare(const number_backend_float_architype& o)const
{
std::cout << "Comparison" << std::endl;
return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);
}
int compare(long long i)const
{
std::cout << "Comparison with int" << std::endl;
return m_value > i ? 1 : (m_value < i ? -1 : 0);
}
int compare(unsigned long long i)const
{
std::cout << "Comparison with unsigned" << std::endl;
return m_value > i ? 1 : (m_value < i ? -1 : 0);
}
int compare(long double d)const
{
std::cout << "Comparison with long double" << std::endl;
return m_value > d ? 1 : (m_value < d ? -1 : 0);
}
long double m_value;
};
inline void eval_add(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Addition (" << result.m_value << " += " << o.m_value << ")" << std::endl;
result.m_value += o.m_value;
}
inline void eval_subtract(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Subtraction (" << result.m_value << " -= " << o.m_value << ")" << std::endl;
result.m_value -= o.m_value;
}
inline void eval_multiply(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Multiplication (" << result.m_value << " *= " << o.m_value << ")" << std::endl;
result.m_value *= o.m_value;
}
inline void eval_divide(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Division (" << result.m_value << " /= " << o.m_value << ")" << std::endl;
result.m_value /= o.m_value;
}
inline void eval_convert_to(unsigned long long* result, const number_backend_float_architype& val)
{
*result = static_cast<unsigned long long>(val.m_value);
}
inline void eval_convert_to(long long* result, const number_backend_float_architype& val)
{
*result = static_cast<long long>(val.m_value);
}
inline void eval_convert_to(long double* result, number_backend_float_architype& val)
{
*result = val.m_value;
}
inline void eval_frexp(number_backend_float_architype& result, const number_backend_float_architype& arg, int* exp)
{
result = std::frexp(arg.m_value, exp);
}
inline void eval_ldexp(number_backend_float_architype& result, const number_backend_float_architype& arg, int exp)
{
result = std::ldexp(arg.m_value, exp);
}
inline void eval_floor(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::floor(arg.m_value);
}
inline void eval_ceil(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::ceil(arg.m_value);
}
inline void eval_sqrt(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::sqrt(arg.m_value);
}
inline int eval_fpclassify(const number_backend_float_architype& arg)
{
return (boost::math::fpclassify)(arg.m_value);
}
typedef boost::multiprecision::number<number_backend_float_architype> mp_number_float_architype;
} // namespace
template<>
struct number_category<concepts::number_backend_float_architype> : public mpl::int_<number_kind_floating_point>{};
}} // namespaces
namespace std{
template <boost::multiprecision::expression_template_option ExpressionTemplates>
class numeric_limits<boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype, ExpressionTemplates> > : public std::numeric_limits<long double>
{
typedef std::numeric_limits<long double> base_type;
typedef boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype, ExpressionTemplates> number_type;
public:
static number_type (min)() BOOST_NOEXCEPT { return (base_type::min)(); }
static number_type (max)() BOOST_NOEXCEPT { return (base_type::max)(); }
static number_type lowest() BOOST_NOEXCEPT { return -(max)(); }
static number_type epsilon() BOOST_NOEXCEPT { return base_type::epsilon(); }
static number_type round_error() BOOST_NOEXCEPT { return base_type::round_error(); }
static number_type infinity() BOOST_NOEXCEPT { return base_type::infinity(); }
static number_type quiet_NaN() BOOST_NOEXCEPT { return base_type::quiet_NaN(); }
static number_type signaling_NaN() BOOST_NOEXCEPT { return base_type::signaling_NaN(); }
static number_type denorm_min() BOOST_NOEXCEPT { return base_type::denorm_min(); }
};
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
| mit |
dhoehna/corefx | src/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ExtendedClrTypeCode.cs | 3329 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
namespace Microsoft.SqlServer.Server
{
internal enum ExtendedClrTypeCode
{
Invalid = -1,
Boolean, // System.Boolean
Byte, // System.Byte
Char, // System.Char
DateTime, // System.DateTime
DBNull, // System.DBNull
Decimal, // System.Decimal
Double, // System.Double
Empty, // null reference
Int16, // System.Int16
Int32, // System.Int32
Int64, // System.Int64
SByte, // System.SByte
Single, // System.Single
String, // System.String
UInt16, // System.UInt16
UInt32, // System.UInt32
UInt64, // System.UInt64
Object, // System.Object
ByteArray, // System.ByteArray
CharArray, // System.CharArray
Guid, // System.Guid
SqlBinary, // System.Data.SqlTypes.SqlBinary
SqlBoolean, // System.Data.SqlTypes.SqlBoolean
SqlByte, // System.Data.SqlTypes.SqlByte
SqlDateTime, // System.Data.SqlTypes.SqlDateTime
SqlDouble, // System.Data.SqlTypes.SqlDouble
SqlGuid, // System.Data.SqlTypes.SqlGuid
SqlInt16, // System.Data.SqlTypes.SqlInt16
SqlInt32, // System.Data.SqlTypes.SqlInt32
SqlInt64, // System.Data.SqlTypes.SqlInt64
SqlMoney, // System.Data.SqlTypes.SqlMoney
SqlDecimal, // System.Data.SqlTypes.SqlDecimal
SqlSingle, // System.Data.SqlTypes.SqlSingle
SqlString, // System.Data.SqlTypes.SqlString
SqlChars, // System.Data.SqlTypes.SqlChars
SqlBytes, // System.Data.SqlTypes.SqlBytes
SqlXml, // System.Data.SqlTypes.SqlXml
DataTable, // System.Data.DataTable
DbDataReader, // System.Data.DbDataReader (SqlDataReader falls under this category)
IEnumerableOfSqlDataRecord, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>
TimeSpan, // System.TimeSpan
DateTimeOffset, // System.DateTimeOffset
Stream, // System.IO.Stream
TextReader, // System.IO.TextReader
XmlReader, // System.Xml.XmlReader
Last = XmlReader, // end-of-enum marker
First = Boolean, // beginning-of-enum marker
};
}
| mit |
eltondias/SistemaGalenica | vendor/zendframework/zendframework/library/Zend/Session/SaveHandler/MongoDBOptions.php | 5447 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Session\SaveHandler;
use Zend\Session\Exception\InvalidArgumentException;
use Zend\Stdlib\AbstractOptions;
/**
* MongoDB session save handler Options
*/
class MongoDBOptions extends AbstractOptions
{
/**
* Database name
*
* @var string
*/
protected $database;
/**
* Collection name
*
* @var string
*/
protected $collection;
/**
* Save options
*
* @see http://php.net/manual/en/mongocollection.save.php
* @var string
*/
protected $saveOptions = array('safe' => true);
/**
* Name field
*
* @var string
*/
protected $nameField = 'name';
/**
* Data field
*
* @var string
*/
protected $dataField = 'data';
/**
* Lifetime field
*
* @var string
*/
protected $lifetimeField = 'lifetime';
/**
* Modified field
*
* @var string
*/
protected $modifiedField = 'modified';
/**
* Set database name
*
* @param string $database
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setDatabase($database)
{
$database = (string) $database;
if (strlen($database) === 0) {
throw new InvalidArgumentException('$database must be a non-empty string');
}
$this->database = $database;
return $this;
}
/**
* Get database name
*
* @return string
*/
public function getDatabase()
{
return $this->database;
}
/**
* Set collection name
*
* @param string $collection
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setCollection($collection)
{
$collection = (string) $collection;
if (strlen($collection) === 0) {
throw new InvalidArgumentException('$collection must be a non-empty string');
}
$this->collection = $collection;
return $this;
}
/**
* Get collection name
*
* @return string
*/
public function getCollection()
{
return $this->collection;
}
/**
* Set save options
*
* @see http://php.net/manual/en/mongocollection.save.php
* @param array $saveOptions
* @return MongoDBOptions
*/
public function setSaveOptions(array $saveOptions)
{
$this->saveOptions = $saveOptions;
return $this;
}
/**
* Get save options
*
* @return string
*/
public function getSaveOptions()
{
return $this->saveOptions;
}
/**
* Set name field
*
* @param string $nameField
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setNameField($nameField)
{
$nameField = (string) $nameField;
if (strlen($nameField) === 0) {
throw new InvalidArgumentException('$nameField must be a non-empty string');
}
$this->nameField = $nameField;
return $this;
}
/**
* Get name field
*
* @return string
*/
public function getNameField()
{
return $this->nameField;
}
/**
* Set data field
*
* @param string $dataField
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setDataField($dataField)
{
$dataField = (string) $dataField;
if (strlen($dataField) === 0) {
throw new InvalidArgumentException('$dataField must be a non-empty string');
}
$this->dataField = $dataField;
return $this;
}
/**
* Get data field
*
* @return string
*/
public function getDataField()
{
return $this->dataField;
}
/**
* Set lifetime field
*
* @param string $lifetimeField
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setLifetimeField($lifetimeField)
{
$lifetimeField = (string) $lifetimeField;
if (strlen($lifetimeField) === 0) {
throw new InvalidArgumentException('$lifetimeField must be a non-empty string');
}
$this->lifetimeField = $lifetimeField;
return $this;
}
/**
* Get lifetime Field
*
* @return string
*/
public function getLifetimeField()
{
return $this->lifetimeField;
}
/**
* Set Modified Field
*
* @param string $modifiedField
* @return MongoDBOptions
* @throws InvalidArgumentException
*/
public function setModifiedField($modifiedField)
{
$modifiedField = (string) $modifiedField;
if (strlen($modifiedField) === 0) {
throw new InvalidArgumentException('$modifiedField must be a non-empty string');
}
$this->modifiedField = $modifiedField;
return $this;
}
/**
* Get modified Field
*
* @return string
*/
public function getModifiedField()
{
return $this->modifiedField;
}
}
| bsd-3-clause |
dougminhlam/kaldi-hugo-cms-template | src/js/cms-preview-templates/post.js | 667 | import React from "react";
import format from "date-fns/format";
export default class PostPreview extends React.Component {
render() {
const {entry, widgetFor} = this.props;
return <div className="mw6 center ph3 pv4">
<h1 className="f2 lh-title b mb3">{ entry.getIn(["data", "title"])}</h1>
<div className="flex justify-between grey-3">
<div style={{
width: "80px",
height: "80px"
}}></div>
<p>{ format(entry.getIn(["data", "date"]), "ddd, MMM D, YYYY") }</p>
<p>Read in x minutes</p>
</div>
<div className="cms mw6">
{ widgetFor("body") }
</div>
</div>;
}
}
| mit |
rlugojr/cdnjs | ajax/libs/qoopido.js/3.2.7/support/element/canvas/todataurl/png.js | 629 | /*!
* Qoopido.js library v3.2.7, 2014-5-19
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(t){window.qoopido.register("support/element/canvas/todataurl/png",t,["../../../../support","../todataurl"])}(function(t,e,a,n,o,r){"use strict";var s=t.support;return s.addTest("/element/canvas/todataurl/png",function(e){t["support/element/canvas/todataurl"]().then(function(){var t=s.pool?s.pool.obtain("canvas"):r.createElement("canvas");0===t.toDataURL("image/png").indexOf("data:image/png")?e.resolve():e.reject(),t.dispose&&t.dispose()},function(){e.reject()}).done()})}); | mit |
GrantBarnard/PixelsCoffeeCode_Theme | templates/comments.php | 3994 | <?php
if (post_password_required()) {
return;
}
?>
<section id="comments">
<?php if (have_comments()) : ?>
<h3><?php printf(_n('One Response to “%2$s”', '%1$s Responses to “%2$s”', get_comments_number(), 'roots'), number_format_i18n(get_comments_number()), get_the_title()); ?></h3>
<ol class="media-list">
<?php wp_list_comments(array('walker' => new Roots_Walker_Comment)); ?>
</ol>
<?php if (get_comment_pages_count() > 1 && get_option('page_comments')) : ?>
<nav>
<ul class="pager">
<?php if (get_previous_comments_link()) : ?>
<li class="previous"><?php previous_comments_link(__('← Older comments', 'roots')); ?></li>
<?php endif; ?>
<?php if (get_next_comments_link()) : ?>
<li class="next"><?php next_comments_link(__('Newer comments →', 'roots')); ?></li>
<?php endif; ?>
</ul>
</nav>
<?php endif; ?>
<?php if (!comments_open() && !is_page() && post_type_supports(get_post_type(), 'comments')) : ?>
<div class="alert alert-warning">
<?php _e('Comments are closed.', 'roots'); ?>
</div>
<?php endif; ?>
<?php elseif(!comments_open() && !is_page() && post_type_supports(get_post_type(), 'comments')) : ?>
<div class="alert alert-warning">
<?php _e('Comments are closed.', 'roots'); ?>
</div>
<?php endif; ?>
</section><!-- /#comments -->
<section id="respond">
<?php if (comments_open()) : ?>
<h3><?php comment_form_title(__('Leave a Reply', 'roots'), __('Leave a Reply to %s', 'roots')); ?></h3>
<p class="cancel-comment-reply"><?php cancel_comment_reply_link(); ?></p>
<?php if (get_option('comment_registration') && !is_user_logged_in()) : ?>
<p><?php printf(__('You must be <a href="%s">logged in</a> to post a comment.', 'roots'), wp_login_url(get_permalink())); ?></p>
<?php else : ?>
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
<?php if (is_user_logged_in()) : ?>
<p>
<?php printf(__('Logged in as <a href="%s/wp-admin/profile.php">%s</a>.', 'roots'), get_option('siteurl'), $user_identity); ?>
<a href="<?php echo wp_logout_url(get_permalink()); ?>" title="<?php _e('Log out of this account', 'roots'); ?>"><?php _e('Log out »', 'roots'); ?></a>
</p>
<?php else : ?>
<div class="form-group">
<label for="author"><?php _e('Name', 'roots'); if ($req) _e(' (required)', 'roots'); ?></label>
<input type="text" class="form-control" name="author" id="author" value="<?php echo esc_attr($comment_author); ?>" size="22" <?php if ($req) echo 'aria-required="true"'; ?>>
</div>
<div class="form-group">
<label for="email"><?php _e('Email (will not be published)', 'roots'); if ($req) _e(' (required)', 'roots'); ?></label>
<input type="email" class="form-control" name="email" id="email" value="<?php echo esc_attr($comment_author_email); ?>" size="22" <?php if ($req) echo 'aria-required="true"'; ?>>
</div>
<div class="form-group">
<label for="url"><?php _e('Website', 'roots'); ?></label>
<input type="url" class="form-control" name="url" id="url" value="<?php echo esc_attr($comment_author_url); ?>" size="22">
</div>
<?php endif; ?>
<div class="form-group">
<label for="comment"><?php _e('Comment', 'roots'); ?></label>
<textarea name="comment" id="comment" class="form-control" rows="5" aria-required="true"></textarea>
</div>
<p><input name="submit" class="btn btn-primary" type="submit" id="submit" value="<?php _e('Submit Comment', 'roots'); ?>"></p>
<?php comment_id_fields(); ?>
<?php do_action('comment_form', $post->ID); ?>
</form>
<?php endif; ?>
<?php endif; ?>
</section><!-- /#respond -->
| mit |
jackdoyle/cdnjs | ajax/libs/qoopido.js/3.3.9/jquery/plugin/emerge.js | 660 | /*!
* Qoopido.js library v3.3.9, 2014-6-3
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(e){window.qoopido.register("jquery/plugins/emerge",e,["../../dom/element/emerge","jquery"])}(function(e,r,t,n,o){"use strict";var c,i=e.jquery||o.jQuery,u=t.pop(),g="emerged",a="demerged",d="".concat(g,".",u),m="".concat(a,".",u);return i.fn[u]=function(e){return this.each(function(){c.create(this,e)})},c=e["dom/element/emerge"].extend({_constructor:function(e,r){var t=this,n=i(e);c._parent._constructor.call(t,e,r),t.on(g,function(e){n.trigger(d,{priority:e.data})}),t.on(a,function(){n.trigger(m)})}})}); | mit |
esod/paulsodlaw | sites/all/libraries/ckeditor/_samples/php/standalone.php | 2253 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample - CKEditor</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<link href="../sample.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>
CKEditor Sample
</h1>
<!-- This <div> holds alert messages to be display in the sample page. -->
<div id="alerts">
<noscript>
<p>
<strong>CKEditor requires JavaScript to run</strong>. In a browser with no JavaScript
support, like yours, you should still see the contents (HTML data) and you should
be able to edit it normally, without a rich editor interface.
</p>
</noscript>
</div>
<!-- This <fieldset> holds the HTML that you will usually find in your pages. -->
<fieldset title="Output">
<legend>Output</legend>
<form action="../sample_posteddata.php" method="post">
<p>
<label for="editor1">
Editor 1:</label><br/>
</p>
<p>
<?php
// Include CKEditor class.
include_once "../../ckeditor.php";
// The initial value to be displayed in the editor.
$initialValue = '<p>This is some <strong>sample text</strong>.</p>';
// Create class instance.
$CKEditor = new CKEditor();
// Path to CKEditor directory, ideally instead of relative dir, use an absolute path:
// $CKEditor->basePath = '/ckeditor/'
// If not set, CKEditor will try to detect the correct path.
$CKEditor->basePath = '../../';
// Create textarea element and attach CKEditor to it.
$CKEditor->editor("editor1", $initialValue);
?>
<input type="submit" value="Submit"/>
</p>
</form>
</fieldset>
<div id="footer">
<hr />
<p>
CKEditor - The text editor for Internet - <a href="http://ckeditor.com/">http://ckeditor.com</a>
</p>
<p id="copy">
Copyright © 2003-2010, <a href="http://cksource.com/">CKSource</a> - Frederico
Knabben. All rights reserved.
</p>
</div>
</body>
</html>
| gpl-2.0 |
PrimozGodec/Primerjalna_knjizevnost | node_modules/bower/node_modules/mout/number/toUInt.js | 324 |
/**
* "Convert" value into a 32-bit unsigned integer.
* IMPORTANT: Value will wrap at 2^32.
*/
function toUInt(val){
// we do not use lang/toNumber because of perf and also because it
// doesn't break the functionality
return val >>> 0;
}
module.exports = toUInt;
| mit |
richpolis/sf2MalosHabitos | vendor/jms/security-extra-bundle/JMS/SecurityExtraBundle/Tests/Fixtures/Annotation/NonSecurityAnnotation.php | 748 | <?php
/*
* Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\SecurityExtraBundle\Tests\Fixtures\Annotation;
/** @Annotation */
final class NonSecurityAnnotation
{
} | mit |
raphael1981/joomlacmc1234 | administrator/components/com_media/views/imageslist/tmpl/default.php | 817 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_media
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
?>
<?php if (count($this->images) > 0 || count($this->folders) > 0) { ?>
<ul class="manager thumbnails">
<?php for ($i = 0, $n = count($this->folders); $i < $n; $i++) :
$this->setFolder($i);
echo $this->loadTemplate('folder');
endfor; ?>
<?php for ($i = 0, $n = count($this->images); $i < $n; $i++) :
$this->setImage($i);
echo $this->loadTemplate('image');
endfor; ?>
</ul>
<?php } else { ?>
<div id="media-noimages">
<div class="alert alert-info"><?php echo JText::_('COM_MEDIA_NO_IMAGES_FOUND'); ?></div>
</div>
<?php } ?>
| gpl-2.0 |
karim89/mtat | lib/requirejs.php | 5384 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file is serving optimised JS for RequireJS.
*
* @package core
* @copyright 2015 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Disable moodle specific debug messages and any errors in output,
// comment out when debugging or better look into error log!
define('NO_DEBUG_DISPLAY', true);
// We need just the values from config.php and minlib.php.
define('ABORT_AFTER_CONFIG', true);
require('../config.php'); // This stops immediately at the beginning of lib/setup.php.
require_once("$CFG->dirroot/lib/jslib.php");
require_once("$CFG->dirroot/lib/classes/requirejs.php");
$slashargument = min_get_slash_argument();
if (!$slashargument) {
// The above call to min_get_slash_argument should always work.
die('Invalid request');
}
$slashargument = ltrim($slashargument, '/');
if (substr_count($slashargument, '/') < 1) {
header('HTTP/1.0 404 not found');
die('Slash argument must contain both a revision and a file path');
}
// Split into revision and module name.
list($rev, $file) = explode('/', $slashargument, 2);
$rev = min_clean_param($rev, 'INT');
$file = '/' . min_clean_param($file, 'SAFEPATH');
// Only load js files from the js modules folder from the components.
$jsfiles = array();
list($unused, $component, $module) = explode('/', $file, 3);
// No subdirs allowed - only flat module structure please.
if (strpos('/', $module) !== false) {
die('Invalid module');
}
// Some (huge) modules are better loaded lazily (when they are used). If we are requesting
// one of these modules, only return the one module, not the combo.
$lazysuffix = "-lazy.js";
$lazyload = (strpos($module, $lazysuffix) !== false);
if ($lazyload) {
// We are lazy loading a single file - so include the component/filename pair in the etag.
$etag = sha1($rev . '/' . $component . '/' . $module);
} else {
// We loading all (non-lazy) files - so only the rev makes this request unique.
$etag = sha1($rev);
}
// Use the caching only for meaningful revision numbers which prevents future cache poisoning.
if ($rev > 0 and $rev < (time() + 60 * 60)) {
$candidate = $CFG->localcachedir . '/requirejs/' . $etag;
if (file_exists($candidate)) {
if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
// We do not actually need to verify the etag value because our files
// never change in cache because we increment the rev parameter.
js_send_unmodified(filemtime($candidate), $etag);
}
js_send_cached($candidate, $etag, 'requirejs.php');
exit(0);
} else {
$jsfiles = array();
if ($lazyload) {
$jsfiles = core_requirejs::find_one_amd_module($component, $module);
} else {
// Here we respond to the request by returning ALL amd modules. This saves
// round trips in production.
$jsfiles = core_requirejs::find_all_amd_modules();
}
$content = '';
foreach ($jsfiles as $modulename => $jsfile) {
$js = file_get_contents($jsfile) . "\n";
// Inject the module name into the define.
$replace = 'define(\'' . $modulename . '\', ';
$search = 'define(';
// Replace only the first occurrence.
$js = implode($replace, explode($search, $js, 2));
$content .= $js;
}
js_write_cache_file_content($candidate, $content);
// Verify nothing failed in cache file creation.
clearstatcache();
if (file_exists($candidate)) {
js_send_cached($candidate, $etag, 'requirejs.php');
exit(0);
}
}
}
if ($lazyload) {
$jsfiles = core_requirejs::find_one_amd_module($component, $module, true);
} else {
$jsfiles = core_requirejs::find_all_amd_modules(true);
}
$content = '';
foreach ($jsfiles as $modulename => $jsfile) {
$shortfilename = str_replace($CFG->dirroot, '', $jsfile);
$js = "// ---- $shortfilename ----\n";
$js .= file_get_contents($jsfile) . "\n";
// Inject the module name into the define.
$replace = 'define(\'' . $modulename . '\', ';
$search = 'define(';
if (strpos($js, $search) === false) {
// We can't call debugging because we only have minimal config loaded.
header('HTTP/1.0 500 error');
die('JS file: ' . $shortfilename . ' does not contain a javascript module in AMD format. "define()" not found.');
}
// Replace only the first occurrence.
$js = implode($replace, explode($search, $js, 2));
$content .= $js;
}
js_send_uncached($content, $etag, 'requirejs.php');
| gpl-3.0 |
dgoodwin/origin | cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/gogo/protobuf/test/oneof3/combos/unsafeboth/onepb_test.go | 12710 | // Code generated by protoc-gen-gogo.
// source: combos/unsafeboth/one.proto
// DO NOT EDIT!
/*
Package one is a generated protocol buffer package.
It is generated from these files:
combos/unsafeboth/one.proto
It has these top-level messages:
Subby
SampleOneOf
*/
package one
import testing "testing"
import math_rand "math/rand"
import time "time"
import unsafe "unsafe"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb"
import fmt "fmt"
import go_parser "go/parser"
import proto "github.com/gogo/protobuf/proto"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
func TestSubbyProto(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, false)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Subby{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestSubbyMarshalTo(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Subby{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestSampleOneOfProto(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, false)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &SampleOneOf{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestSampleOneOfMarshalTo(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &SampleOneOf{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestSubbyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Subby{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestSampleOneOfJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &SampleOneOf{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestSubbyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, true)
dAtA := github_com_gogo_protobuf_proto.MarshalTextString(p)
msg := &Subby{}
if err := github_com_gogo_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestSubbyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, true)
dAtA := github_com_gogo_protobuf_proto.CompactTextString(p)
msg := &Subby{}
if err := github_com_gogo_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestSampleOneOfProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, true)
dAtA := github_com_gogo_protobuf_proto.MarshalTextString(p)
msg := &SampleOneOf{}
if err := github_com_gogo_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestSampleOneOfProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, true)
dAtA := github_com_gogo_protobuf_proto.CompactTextString(p)
msg := &SampleOneOf{}
if err := github_com_gogo_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestOneDescription(t *testing.T) {
OneDescription()
}
func TestSubbyVerboseEqual(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSubby(popr, false)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
panic(err)
}
msg := &Subby{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
panic(err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err)
}
}
func TestSampleOneOfVerboseEqual(t *testing.T) {
var bigendian uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
t.Skip("unsafe does not work on big endian architectures")
}
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSampleOneOf(popr, false)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
panic(err)
}
msg := &SampleOneOf{}
if err := github_com_gogo_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
panic(err)
}
if err := p.VerboseEqual(msg); err != nil {
t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err)
}
}
func TestSubbyGoString(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSubby(popr, false)
s1 := p.GoString()
s2 := fmt.Sprintf("%#v", p)
if s1 != s2 {
t.Fatalf("GoString want %v got %v", s1, s2)
}
_, err := go_parser.ParseExpr(s1)
if err != nil {
panic(err)
}
}
func TestSampleOneOfGoString(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSampleOneOf(popr, false)
s1 := p.GoString()
s2 := fmt.Sprintf("%#v", p)
if s1 != s2 {
t.Fatalf("GoString want %v got %v", s1, s2)
}
_, err := go_parser.ParseExpr(s1)
if err != nil {
panic(err)
}
}
func TestSubbySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSubby(popr, true)
size2 := github_com_gogo_protobuf_proto.Size(p)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_gogo_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func TestSampleOneOfSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedSampleOneOf(popr, true)
size2 := github_com_gogo_protobuf_proto.Size(p)
dAtA, err := github_com_gogo_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_gogo_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func TestSubbyStringer(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSubby(popr, false)
s1 := p.String()
s2 := fmt.Sprintf("%v", p)
if s1 != s2 {
t.Fatalf("String want %v got %v", s1, s2)
}
}
func TestSampleOneOfStringer(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
p := NewPopulatedSampleOneOf(popr, false)
s1 := p.String()
s2 := fmt.Sprintf("%v", p)
if s1 != s2 {
t.Fatalf("String want %v got %v", s1, s2)
}
}
//These tests are generated by github.com/gogo/protobuf/plugin/testgen
| apache-2.0 |
jepeng-miao/jepeng | wp-admin/includes/class-wp-screen.php | 34417 | <?php
/**
* Screen API: WP_Screen class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Core class used to implement an admin screen API.
*
* @since 3.3.0
*/
final class WP_Screen {
/**
* Any action associated with the screen. 'add' for *-add.php and *-new.php screens. Empty otherwise.
*
* @since 3.3.0
* @var string
* @access public
*/
public $action;
/**
* The base type of the screen. This is typically the same as $id but with any post types and taxonomies stripped.
* For example, for an $id of 'edit-post' the base is 'edit'.
*
* @since 3.3.0
* @var string
* @access public
*/
public $base;
/**
* The number of columns to display. Access with get_columns().
*
* @since 3.4.0
* @var int
* @access private
*/
private $columns = 0;
/**
* The unique ID of the screen.
*
* @since 3.3.0
* @var string
* @access public
*/
public $id;
/**
* Which admin the screen is in. network | user | site | false
*
* @since 3.5.0
* @var string
* @access protected
*/
protected $in_admin;
/**
* Whether the screen is in the network admin.
*
* Deprecated. Use in_admin() instead.
*
* @since 3.3.0
* @deprecated 3.5.0
* @var bool
* @access public
*/
public $is_network;
/**
* Whether the screen is in the user admin.
*
* Deprecated. Use in_admin() instead.
*
* @since 3.3.0
* @deprecated 3.5.0
* @var bool
* @access public
*/
public $is_user;
/**
* The base menu parent.
* This is derived from $parent_file by removing the query string and any .php extension.
* $parent_file values of 'edit.php?post_type=page' and 'edit.php?post_type=post' have a $parent_base of 'edit'.
*
* @since 3.3.0
* @var string
* @access public
*/
public $parent_base;
/**
* The parent_file for the screen per the admin menu system.
* Some $parent_file values are 'edit.php?post_type=page', 'edit.php', and 'options-general.php'.
*
* @since 3.3.0
* @var string
* @access public
*/
public $parent_file;
/**
* The post type associated with the screen, if any.
* The 'edit.php?post_type=page' screen has a post type of 'page'.
* The 'edit-tags.php?taxonomy=$taxonomy&post_type=page' screen has a post type of 'page'.
*
* @since 3.3.0
* @var string
* @access public
*/
public $post_type;
/**
* The taxonomy associated with the screen, if any.
* The 'edit-tags.php?taxonomy=category' screen has a taxonomy of 'category'.
* @since 3.3.0
* @var string
* @access public
*/
public $taxonomy;
/**
* The help tab data associated with the screen, if any.
*
* @since 3.3.0
* @var array
* @access private
*/
private $_help_tabs = array();
/**
* The help sidebar data associated with screen, if any.
*
* @since 3.3.0
* @var string
* @access private
*/
private $_help_sidebar = '';
/**
* The accessible hidden headings and text associated with the screen, if any.
*
* @since 4.4.0
* @access private
* @var array
*/
private $_screen_reader_content = array();
/**
* Stores old string-based help.
*
* @static
* @access private
*
* @var array
*/
private static $_old_compat_help = array();
/**
* The screen options associated with screen, if any.
*
* @since 3.3.0
* @var array
* @access private
*/
private $_options = array();
/**
* The screen object registry.
*
* @since 3.3.0
*
* @static
* @access private
*
* @var array
*/
private static $_registry = array();
/**
* Stores the result of the public show_screen_options function.
*
* @since 3.3.0
* @var bool
* @access private
*/
private $_show_screen_options;
/**
* Stores the 'screen_settings' section of screen options.
*
* @since 3.3.0
* @var string
* @access private
*/
private $_screen_settings;
/**
* Fetches a screen object.
*
* @since 3.3.0
* @access public
*
* @static
*
* @global string $hook_suffix
*
* @param string|WP_Screen $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen.
* Defaults to the current $hook_suffix global.
* @return WP_Screen Screen object.
*/
public static function get( $hook_name = '' ) {
if ( $hook_name instanceof WP_Screen ) {
return $hook_name;
}
$post_type = $taxonomy = null;
$in_admin = false;
$action = '';
if ( $hook_name )
$id = $hook_name;
else
$id = $GLOBALS['hook_suffix'];
// For those pesky meta boxes.
if ( $hook_name && post_type_exists( $hook_name ) ) {
$post_type = $id;
$id = 'post'; // changes later. ends up being $base.
} else {
if ( '.php' == substr( $id, -4 ) )
$id = substr( $id, 0, -4 );
if ( 'post-new' == $id || 'link-add' == $id || 'media-new' == $id || 'user-new' == $id ) {
$id = substr( $id, 0, -4 );
$action = 'add';
}
}
if ( ! $post_type && $hook_name ) {
if ( '-network' == substr( $id, -8 ) ) {
$id = substr( $id, 0, -8 );
$in_admin = 'network';
} elseif ( '-user' == substr( $id, -5 ) ) {
$id = substr( $id, 0, -5 );
$in_admin = 'user';
}
$id = sanitize_key( $id );
if ( 'edit-comments' != $id && 'edit-tags' != $id && 'edit-' == substr( $id, 0, 5 ) ) {
$maybe = substr( $id, 5 );
if ( taxonomy_exists( $maybe ) ) {
$id = 'edit-tags';
$taxonomy = $maybe;
} elseif ( post_type_exists( $maybe ) ) {
$id = 'edit';
$post_type = $maybe;
}
}
if ( ! $in_admin )
$in_admin = 'site';
} else {
if ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN )
$in_admin = 'network';
elseif ( defined( 'WP_USER_ADMIN' ) && WP_USER_ADMIN )
$in_admin = 'user';
else
$in_admin = 'site';
}
if ( 'index' == $id )
$id = 'dashboard';
elseif ( 'front' == $id )
$in_admin = false;
$base = $id;
// If this is the current screen, see if we can be more accurate for post types and taxonomies.
if ( ! $hook_name ) {
if ( isset( $_REQUEST['post_type'] ) )
$post_type = post_type_exists( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : false;
if ( isset( $_REQUEST['taxonomy'] ) )
$taxonomy = taxonomy_exists( $_REQUEST['taxonomy'] ) ? $_REQUEST['taxonomy'] : false;
switch ( $base ) {
case 'post' :
if ( isset( $_GET['post'] ) )
$post_id = (int) $_GET['post'];
elseif ( isset( $_POST['post_ID'] ) )
$post_id = (int) $_POST['post_ID'];
else
$post_id = 0;
if ( $post_id ) {
$post = get_post( $post_id );
if ( $post )
$post_type = $post->post_type;
}
break;
case 'edit-tags' :
case 'term' :
if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) )
$post_type = 'post';
break;
}
}
switch ( $base ) {
case 'post' :
if ( null === $post_type )
$post_type = 'post';
$id = $post_type;
break;
case 'edit' :
if ( null === $post_type )
$post_type = 'post';
$id .= '-' . $post_type;
break;
case 'edit-tags' :
case 'term' :
if ( null === $taxonomy )
$taxonomy = 'post_tag';
// The edit-tags ID does not contain the post type. Look for it in the request.
if ( null === $post_type ) {
$post_type = 'post';
if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) )
$post_type = $_REQUEST['post_type'];
}
$id = 'edit-' . $taxonomy;
break;
}
if ( 'network' == $in_admin ) {
$id .= '-network';
$base .= '-network';
} elseif ( 'user' == $in_admin ) {
$id .= '-user';
$base .= '-user';
}
if ( isset( self::$_registry[ $id ] ) ) {
$screen = self::$_registry[ $id ];
if ( $screen === get_current_screen() )
return $screen;
} else {
$screen = new WP_Screen();
$screen->id = $id;
}
$screen->base = $base;
$screen->action = $action;
$screen->post_type = (string) $post_type;
$screen->taxonomy = (string) $taxonomy;
$screen->is_user = ( 'user' == $in_admin );
$screen->is_network = ( 'network' == $in_admin );
$screen->in_admin = $in_admin;
self::$_registry[ $id ] = $screen;
return $screen;
}
/**
* Makes the screen object the current screen.
*
* @see set_current_screen()
* @since 3.3.0
*
* @global WP_Screen $current_screen
* @global string $taxnow
* @global string $typenow
*/
public function set_current_screen() {
global $current_screen, $taxnow, $typenow;
$current_screen = $this;
$taxnow = $this->taxonomy;
$typenow = $this->post_type;
/**
* Fires after the current screen has been set.
*
* @since 3.0.0
*
* @param WP_Screen $current_screen Current WP_Screen object.
*/
do_action( 'current_screen', $current_screen );
}
/**
* Constructor
*
* @since 3.3.0
* @access private
*/
private function __construct() {}
/**
* Indicates whether the screen is in a particular admin
*
* @since 3.5.0
*
* @param string $admin The admin to check against (network | user | site).
* If empty any of the three admins will result in true.
* @return bool True if the screen is in the indicated admin, false otherwise.
*/
public function in_admin( $admin = null ) {
if ( empty( $admin ) )
return (bool) $this->in_admin;
return ( $admin == $this->in_admin );
}
/**
* Sets the old string-based contextual help for the screen for backward compatibility.
*
* @since 3.3.0
*
* @static
*
* @param WP_Screen $screen A screen object.
* @param string $help Help text.
*/
public static function add_old_compat_help( $screen, $help ) {
self::$_old_compat_help[ $screen->id ] = $help;
}
/**
* Set the parent information for the screen.
* This is called in admin-header.php after the menu parent for the screen has been determined.
*
* @since 3.3.0
*
* @param string $parent_file The parent file of the screen. Typically the $parent_file global.
*/
public function set_parentage( $parent_file ) {
$this->parent_file = $parent_file;
list( $this->parent_base ) = explode( '?', $parent_file );
$this->parent_base = str_replace( '.php', '', $this->parent_base );
}
/**
* Adds an option for the screen.
* Call this in template files after admin.php is loaded and before admin-header.php is loaded to add screen options.
*
* @since 3.3.0
*
* @param string $option Option ID
* @param mixed $args Option-dependent arguments.
*/
public function add_option( $option, $args = array() ) {
$this->_options[ $option ] = $args;
}
/**
* Remove an option from the screen.
*
* @since 3.8.0
*
* @param string $option Option ID.
*/
public function remove_option( $option ) {
unset( $this->_options[ $option ] );
}
/**
* Remove all options from the screen.
*
* @since 3.8.0
*/
public function remove_options() {
$this->_options = array();
}
/**
* Get the options registered for the screen.
*
* @since 3.8.0
*
* @return array Options with arguments.
*/
public function get_options() {
return $this->_options;
}
/**
* Gets the arguments for an option for the screen.
*
* @since 3.3.0
*
* @param string $option Option name.
* @param string $key Optional. Specific array key for when the option is an array.
* Default false.
* @return string The option value if set, null otherwise.
*/
public function get_option( $option, $key = false ) {
if ( ! isset( $this->_options[ $option ] ) )
return null;
if ( $key ) {
if ( isset( $this->_options[ $option ][ $key ] ) )
return $this->_options[ $option ][ $key ];
return null;
}
return $this->_options[ $option ];
}
/**
* Gets the help tabs registered for the screen.
*
* @since 3.4.0
* @since 4.4.0 Help tabs are ordered by their priority.
*
* @return array Help tabs with arguments.
*/
public function get_help_tabs() {
$help_tabs = $this->_help_tabs;
$priorities = array();
foreach ( $help_tabs as $help_tab ) {
if ( isset( $priorities[ $help_tab['priority'] ] ) ) {
$priorities[ $help_tab['priority'] ][] = $help_tab;
} else {
$priorities[ $help_tab['priority'] ] = array( $help_tab );
}
}
ksort( $priorities );
$sorted = array();
foreach ( $priorities as $list ) {
foreach ( $list as $tab ) {
$sorted[ $tab['id'] ] = $tab;
}
}
return $sorted;
}
/**
* Gets the arguments for a help tab.
*
* @since 3.4.0
*
* @param string $id Help Tab ID.
* @return array Help tab arguments.
*/
public function get_help_tab( $id ) {
if ( ! isset( $this->_help_tabs[ $id ] ) )
return null;
return $this->_help_tabs[ $id ];
}
/**
* Add a help tab to the contextual help for the screen.
* Call this on the load-$pagenow hook for the relevant screen.
*
* @since 3.3.0
* @since 4.4.0 The `$priority` argument was added.
*
* @param array $args {
* Array of arguments used to display the help tab.
*
* @type string $title Title for the tab. Default false.
* @type string $id Tab ID. Must be HTML-safe. Default false.
* @type string $content Optional. Help tab content in plain text or HTML. Default empty string.
* @type string $callback Optional. A callback to generate the tab content. Default false.
* @type int $priority Optional. The priority of the tab, used for ordering. Default 10.
* }
*/
public function add_help_tab( $args ) {
$defaults = array(
'title' => false,
'id' => false,
'content' => '',
'callback' => false,
'priority' => 10,
);
$args = wp_parse_args( $args, $defaults );
$args['id'] = sanitize_html_class( $args['id'] );
// Ensure we have an ID and title.
if ( ! $args['id'] || ! $args['title'] )
return;
// Allows for overriding an existing tab with that ID.
$this->_help_tabs[ $args['id'] ] = $args;
}
/**
* Removes a help tab from the contextual help for the screen.
*
* @since 3.3.0
*
* @param string $id The help tab ID.
*/
public function remove_help_tab( $id ) {
unset( $this->_help_tabs[ $id ] );
}
/**
* Removes all help tabs from the contextual help for the screen.
*
* @since 3.3.0
*/
public function remove_help_tabs() {
$this->_help_tabs = array();
}
/**
* Gets the content from a contextual help sidebar.
*
* @since 3.4.0
*
* @return string Contents of the help sidebar.
*/
public function get_help_sidebar() {
return $this->_help_sidebar;
}
/**
* Add a sidebar to the contextual help for the screen.
* Call this in template files after admin.php is loaded and before admin-header.php is loaded to add a sidebar to the contextual help.
*
* @since 3.3.0
*
* @param string $content Sidebar content in plain text or HTML.
*/
public function set_help_sidebar( $content ) {
$this->_help_sidebar = $content;
}
/**
* Gets the number of layout columns the user has selected.
*
* The layout_columns option controls the max number and default number of
* columns. This method returns the number of columns within that range selected
* by the user via Screen Options. If no selection has been made, the default
* provisioned in layout_columns is returned. If the screen does not support
* selecting the number of layout columns, 0 is returned.
*
* @since 3.4.0
*
* @return int Number of columns to display.
*/
public function get_columns() {
return $this->columns;
}
/**
* Get the accessible hidden headings and text used in the screen.
*
* @since 4.4.0
*
* @see set_screen_reader_content() For more information on the array format.
*
* @return array An associative array of screen reader text strings.
*/
public function get_screen_reader_content() {
return $this->_screen_reader_content;
}
/**
* Get a screen reader text string.
*
* @since 4.4.0
*
* @param string $key Screen reader text array named key.
* @return string Screen reader text string.
*/
public function get_screen_reader_text( $key ) {
if ( ! isset( $this->_screen_reader_content[ $key ] ) ) {
return null;
}
return $this->_screen_reader_content[ $key ];
}
/**
* Add accessible hidden headings and text for the screen.
*
* @since 4.4.0
*
* @param array $content {
* An associative array of screen reader text strings.
*
* @type string $heading_views Screen reader text for the filter links heading.
* Default 'Filter items list'.
* @type string $heading_pagination Screen reader text for the pagination heading.
* Default 'Items list navigation'.
* @type string $heading_list Screen reader text for the items list heading.
* Default 'Items list'.
* }
*/
public function set_screen_reader_content( $content = array() ) {
$defaults = array(
'heading_views' => __( 'Filter items list' ),
'heading_pagination' => __( 'Items list navigation' ),
'heading_list' => __( 'Items list' ),
);
$content = wp_parse_args( $content, $defaults );
$this->_screen_reader_content = $content;
}
/**
* Remove all the accessible hidden headings and text for the screen.
*
* @since 4.4.0
*/
public function remove_screen_reader_content() {
$this->_screen_reader_content = array();
}
/**
* Render the screen's help section.
*
* This will trigger the deprecated filters for backward compatibility.
*
* @since 3.3.0
*
* @global string $screen_layout_columns
*/
public function render_screen_meta() {
/**
* Filters the legacy contextual help list.
*
* @since 2.7.0
* @deprecated 3.3.0 Use get_current_screen()->add_help_tab() or
* get_current_screen()->remove_help_tab() instead.
*
* @param array $old_compat_help Old contextual help.
* @param WP_Screen $this Current WP_Screen instance.
*/
self::$_old_compat_help = apply_filters( 'contextual_help_list', self::$_old_compat_help, $this );
$old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : '';
/**
* Filters the legacy contextual help text.
*
* @since 2.7.0
* @deprecated 3.3.0 Use get_current_screen()->add_help_tab() or
* get_current_screen()->remove_help_tab() instead.
*
* @param string $old_help Help text that appears on the screen.
* @param string $screen_id Screen ID.
* @param WP_Screen $this Current WP_Screen instance.
*
*/
$old_help = apply_filters( 'contextual_help', $old_help, $this->id, $this );
// Default help only if there is no old-style block of text and no new-style help tabs.
if ( empty( $old_help ) && ! $this->get_help_tabs() ) {
/**
* Filters the default legacy contextual help text.
*
* @since 2.8.0
* @deprecated 3.3.0 Use get_current_screen()->add_help_tab() or
* get_current_screen()->remove_help_tab() instead.
*
* @param string $old_help_default Default contextual help text.
*/
$default_help = apply_filters( 'default_contextual_help', '' );
if ( $default_help )
$old_help = '<p>' . $default_help . '</p>';
}
if ( $old_help ) {
$this->add_help_tab( array(
'id' => 'old-contextual-help',
'title' => __('Overview'),
'content' => $old_help,
) );
}
$help_sidebar = $this->get_help_sidebar();
$help_class = 'hidden';
if ( ! $help_sidebar )
$help_class .= ' no-sidebar';
// Time to render!
?>
<div id="screen-meta" class="metabox-prefs">
<div id="contextual-help-wrap" class="<?php echo esc_attr( $help_class ); ?>" tabindex="-1" aria-label="<?php esc_attr_e('Contextual Help Tab'); ?>">
<div id="contextual-help-back"></div>
<div id="contextual-help-columns">
<div class="contextual-help-tabs">
<ul>
<?php
$class = ' class="active"';
foreach ( $this->get_help_tabs() as $tab ) :
$link_id = "tab-link-{$tab['id']}";
$panel_id = "tab-panel-{$tab['id']}";
?>
<li id="<?php echo esc_attr( $link_id ); ?>"<?php echo $class; ?>>
<a href="<?php echo esc_url( "#$panel_id" ); ?>" aria-controls="<?php echo esc_attr( $panel_id ); ?>">
<?php echo esc_html( $tab['title'] ); ?>
</a>
</li>
<?php
$class = '';
endforeach;
?>
</ul>
</div>
<?php if ( $help_sidebar ) : ?>
<div class="contextual-help-sidebar">
<?php echo $help_sidebar; ?>
</div>
<?php endif; ?>
<div class="contextual-help-tabs-wrap">
<?php
$classes = 'help-tab-content active';
foreach ( $this->get_help_tabs() as $tab ):
$panel_id = "tab-panel-{$tab['id']}";
?>
<div id="<?php echo esc_attr( $panel_id ); ?>" class="<?php echo $classes; ?>">
<?php
// Print tab content.
echo $tab['content'];
// If it exists, fire tab callback.
if ( ! empty( $tab['callback'] ) )
call_user_func_array( $tab['callback'], array( $this, $tab ) );
?>
</div>
<?php
$classes = 'help-tab-content';
endforeach;
?>
</div>
</div>
</div>
<?php
// Setup layout columns
/**
* Filters the array of screen layout columns.
*
* This hook provides back-compat for plugins using the back-compat
* Filters instead of add_screen_option().
*
* @since 2.8.0
*
* @param array $empty_columns Empty array.
* @param string $screen_id Screen ID.
* @param WP_Screen $this Current WP_Screen instance.
*/
$columns = apply_filters( 'screen_layout_columns', array(), $this->id, $this );
if ( ! empty( $columns ) && isset( $columns[ $this->id ] ) )
$this->add_option( 'layout_columns', array('max' => $columns[ $this->id ] ) );
if ( $this->get_option( 'layout_columns' ) ) {
$this->columns = (int) get_user_option("screen_layout_$this->id");
if ( ! $this->columns && $this->get_option( 'layout_columns', 'default' ) )
$this->columns = $this->get_option( 'layout_columns', 'default' );
}
$GLOBALS[ 'screen_layout_columns' ] = $this->columns; // Set the global for back-compat.
// Add screen options
if ( $this->show_screen_options() )
$this->render_screen_options();
?>
</div>
<?php
if ( ! $this->get_help_tabs() && ! $this->show_screen_options() )
return;
?>
<div id="screen-meta-links">
<?php if ( $this->get_help_tabs() ) : ?>
<div id="contextual-help-link-wrap" class="hide-if-no-js screen-meta-toggle">
<button type="button" id="contextual-help-link" class="button show-settings" aria-controls="contextual-help-wrap" aria-expanded="false"><?php _e( 'Help' ); ?></button>
</div>
<?php endif;
if ( $this->show_screen_options() ) : ?>
<div id="screen-options-link-wrap" class="hide-if-no-js screen-meta-toggle">
<button type="button" id="show-settings-link" class="button show-settings" aria-controls="screen-options-wrap" aria-expanded="false"><?php _e( 'Screen Options' ); ?></button>
</div>
<?php endif; ?>
</div>
<?php
}
/**
*
* @global array $wp_meta_boxes
*
* @return bool
*/
public function show_screen_options() {
global $wp_meta_boxes;
if ( is_bool( $this->_show_screen_options ) )
return $this->_show_screen_options;
$columns = get_column_headers( $this );
$show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' );
switch ( $this->base ) {
case 'widgets':
$nonce = wp_create_nonce( 'widgets-access' );
$this->_screen_settings = '<p><a id="access-on" href="widgets.php?widgets-access=on&_wpnonce=' . urlencode( $nonce ) . '">' . __('Enable accessibility mode') . '</a><a id="access-off" href="widgets.php?widgets-access=off&_wpnonce=' . urlencode( $nonce ) . '">' . __('Disable accessibility mode') . "</a></p>\n";
break;
case 'post' :
$expand = '<fieldset class="editor-expand hidden"><legend>' . __( 'Additional settings' ) . '</legend><label for="editor-expand-toggle">';
$expand .= '<input type="checkbox" id="editor-expand-toggle"' . checked( get_user_setting( 'editor_expand', 'on' ), 'on', false ) . ' />';
$expand .= __( 'Enable full-height editor and distraction-free functionality.' ) . '</label></fieldset>';
$this->_screen_settings = $expand;
break;
default:
$this->_screen_settings = '';
break;
}
/**
* Filters the screen settings text displayed in the Screen Options tab.
*
* This filter is currently only used on the Widgets screen to enable
* accessibility mode.
*
* @since 3.0.0
*
* @param string $screen_settings Screen settings.
* @param WP_Screen $this WP_Screen object.
*/
$this->_screen_settings = apply_filters( 'screen_settings', $this->_screen_settings, $this );
if ( $this->_screen_settings || $this->_options )
$show_screen = true;
/**
* Filters whether to show the Screen Options tab.
*
* @since 3.2.0
*
* @param bool $show_screen Whether to show Screen Options tab.
* Default true.
* @param WP_Screen $this Current WP_Screen instance.
*/
$this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this );
return $this->_show_screen_options;
}
/**
* Render the screen options tab.
*
* @since 3.3.0
*
* @param array $options {
* @type bool $wrap Whether the screen-options-wrap div will be included. Defaults to true.
* }
*/
public function render_screen_options( $options = array() ) {
$options = wp_parse_args( $options, array(
'wrap' => true,
) );
$wrapper_start = $wrapper_end = $form_start = $form_end = '';
// Output optional wrapper.
if ( $options['wrap'] ) {
$wrapper_start = '<div id="screen-options-wrap" class="hidden" tabindex="-1" aria-label="' . esc_attr__( 'Screen Options Tab' ) . '">';
$wrapper_end = '</div>';
}
// Don't output the form and nonce for the widgets accessibility mode links.
if ( 'widgets' !== $this->base ) {
$form_start = "\n<form id='adv-settings' method='post'>\n";
$form_end = "\n" . wp_nonce_field( 'screen-options-nonce', 'screenoptionnonce', false, false ) . "\n</form>\n";
}
echo $wrapper_start . $form_start;
$this->render_meta_boxes_preferences();
$this->render_list_table_columns_preferences();
$this->render_screen_layout();
$this->render_per_page_options();
$this->render_view_mode();
echo $this->_screen_settings;
/**
* Filters whether to show the Screen Options submit button.
*
* @since 4.4.0
*
* @param bool $show_button Whether to show Screen Options submit button.
* Default false.
* @param WP_Screen $this Current WP_Screen instance.
*/
$show_button = apply_filters( 'screen_options_show_submit', false, $this );
if ( $show_button ) {
submit_button( __( 'Apply' ), 'primary', 'screen-options-apply', true );
}
echo $form_end . $wrapper_end;
}
/**
* Render the meta boxes preferences.
*
* @since 4.4.0
*
* @global array $wp_meta_boxes
*/
public function render_meta_boxes_preferences() {
global $wp_meta_boxes;
if ( ! isset( $wp_meta_boxes[ $this->id ] ) ) {
return;
}
?>
<fieldset class="metabox-prefs">
<legend><?php _e( 'Boxes' ); ?></legend>
<?php
meta_box_prefs( $this );
if ( 'dashboard' === $this->id && has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) {
if ( isset( $_GET['welcome'] ) ) {
$welcome_checked = empty( $_GET['welcome'] ) ? 0 : 1;
update_user_meta( get_current_user_id(), 'show_welcome_panel', $welcome_checked );
} else {
$welcome_checked = get_user_meta( get_current_user_id(), 'show_welcome_panel', true );
if ( 2 == $welcome_checked && wp_get_current_user()->user_email != get_option( 'admin_email' ) ) {
$welcome_checked = false;
}
}
echo '<label for="wp_welcome_panel-hide">';
echo '<input type="checkbox" id="wp_welcome_panel-hide"' . checked( (bool) $welcome_checked, true, false ) . ' />';
echo _x( 'Welcome', 'Welcome panel' ) . "</label>\n";
}
?>
</fieldset>
<?php
}
/**
* Render the list table columns preferences.
*
* @since 4.4.0
*/
public function render_list_table_columns_preferences() {
$columns = get_column_headers( $this );
$hidden = get_hidden_columns( $this );
if ( ! $columns ) {
return;
}
$legend = ! empty( $columns['_title'] ) ? $columns['_title'] : __( 'Columns' );
?>
<fieldset class="metabox-prefs">
<legend><?php echo $legend; ?></legend>
<?php
$special = array( '_title', 'cb', 'comment', 'media', 'name', 'title', 'username', 'blogname' );
foreach ( $columns as $column => $title ) {
// Can't hide these for they are special
if ( in_array( $column, $special ) ) {
continue;
}
if ( empty( $title ) ) {
continue;
}
if ( 'comments' == $column ) {
$title = __( 'Comments' );
}
$id = "$column-hide";
echo '<label>';
echo '<input class="hide-column-tog" name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $column . '"' . checked( ! in_array( $column, $hidden ), true, false ) . ' />';
echo "$title</label>\n";
}
?>
</fieldset>
<?php
}
/**
* Render the option for number of columns on the page
*
* @since 3.3.0
*/
public function render_screen_layout() {
if ( ! $this->get_option( 'layout_columns' ) ) {
return;
}
$screen_layout_columns = $this->get_columns();
$num = $this->get_option( 'layout_columns', 'max' );
?>
<fieldset class='columns-prefs'>
<legend class="screen-layout"><?php _e( 'Layout' ); ?></legend><?php
for ( $i = 1; $i <= $num; ++$i ):
?>
<label class="columns-prefs-<?php echo $i; ?>">
<input type='radio' name='screen_columns' value='<?php echo esc_attr( $i ); ?>'
<?php checked( $screen_layout_columns, $i ); ?> />
<?php printf( _n( '%s column', '%s columns', $i ), number_format_i18n( $i ) ); ?>
</label>
<?php
endfor; ?>
</fieldset>
<?php
}
/**
* Render the items per page option
*
* @since 3.3.0
*/
public function render_per_page_options() {
if ( null === $this->get_option( 'per_page' ) ) {
return;
}
$per_page_label = $this->get_option( 'per_page', 'label' );
if ( null === $per_page_label ) {
$per_page_label = __( 'Number of items per page:' );
}
$option = $this->get_option( 'per_page', 'option' );
if ( ! $option ) {
$option = str_replace( '-', '_', "{$this->id}_per_page" );
}
$per_page = (int) get_user_option( $option );
if ( empty( $per_page ) || $per_page < 1 ) {
$per_page = $this->get_option( 'per_page', 'default' );
if ( ! $per_page ) {
$per_page = 20;
}
}
if ( 'edit_comments_per_page' == $option ) {
$comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all';
/** This filter is documented in wp-admin/includes/class-wp-comments-list-table.php */
$per_page = apply_filters( 'comments_per_page', $per_page, $comment_status );
} elseif ( 'categories_per_page' == $option ) {
/** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */
$per_page = apply_filters( 'edit_categories_per_page', $per_page );
} else {
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$per_page = apply_filters( $option, $per_page );
}
// Back compat
if ( isset( $this->post_type ) ) {
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type );
}
// This needs a submit button
add_filter( 'screen_options_show_submit', '__return_true' );
?>
<fieldset class="screen-options">
<legend><?php _e( 'Pagination' ); ?></legend>
<?php if ( $per_page_label ) : ?>
<label for="<?php echo esc_attr( $option ); ?>"><?php echo $per_page_label; ?></label>
<input type="number" step="1" min="1" max="999" class="screen-per-page" name="wp_screen_options[value]"
id="<?php echo esc_attr( $option ); ?>" maxlength="3"
value="<?php echo esc_attr( $per_page ); ?>" />
<?php endif; ?>
<input type="hidden" name="wp_screen_options[option]" value="<?php echo esc_attr( $option ); ?>" />
</fieldset>
<?php
}
/**
* Render the list table view mode preferences.
*
* @since 4.4.0
*/
public function render_view_mode() {
$screen = get_current_screen();
// Currently only enabled for posts lists
if ( 'edit' !== $screen->base ) {
return;
}
$view_mode_post_types = get_post_types( array( 'hierarchical' => false, 'show_ui' => true ) );
/**
* Filters the post types that have different view mode options.
*
* @since 4.4.0
*
* @param array $view_mode_post_types Array of post types that can change view modes.
* Default hierarchical post types with show_ui on.
*/
$view_mode_post_types = apply_filters( 'view_mode_post_types', $view_mode_post_types );
if ( ! in_array( $this->post_type, $view_mode_post_types ) ) {
return;
}
global $mode;
// This needs a submit button
add_filter( 'screen_options_show_submit', '__return_true' );
?>
<fieldset class="metabox-prefs view-mode">
<legend><?php _e( 'View Mode' ); ?></legend>
<label for="list-view-mode">
<input id="list-view-mode" type="radio" name="mode" value="list" <?php checked( 'list', $mode ); ?> />
<?php _e( 'List View' ); ?>
</label>
<label for="excerpt-view-mode">
<input id="excerpt-view-mode" type="radio" name="mode" value="excerpt" <?php checked( 'excerpt', $mode ); ?> />
<?php _e( 'Excerpt View' ); ?>
</label>
</fieldset>
<?php
}
/**
* Render screen reader text.
*
* @since 4.4.0
*
* @param string $key The screen reader text array named key.
* @param string $tag Optional. The HTML tag to wrap the screen reader text. Default h2.
*/
public function render_screen_reader_content( $key = '', $tag = 'h2' ) {
if ( ! isset( $this->_screen_reader_content[ $key ] ) ) {
return;
}
echo "<$tag class='screen-reader-text'>" . $this->_screen_reader_content[ $key ] . "</$tag>";
}
}
| apache-2.0 |
xiuzhifu/go | src/net/http/triv.go | 3236 | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"bytes"
"expvar"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"sync"
)
// hello world, the web server
var helloRequests = expvar.NewInt("hello-requests")
func HelloServer(w http.ResponseWriter, req *http.Request) {
helloRequests.Add(1)
io.WriteString(w, "hello, world!\n")
}
// Simple counter server. POSTing to it will set the value.
type Counter struct {
mu sync.Mutex // protects n
n int
}
// This makes Counter satisfy the expvar.Var interface, so we can export
// it directly.
func (ctr *Counter) String() string {
ctr.mu.Lock()
defer ctr.mu.Unlock()
return fmt.Sprintf("%d", ctr.n)
}
func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctr.mu.Lock()
defer ctr.mu.Unlock()
switch req.Method {
case "GET":
ctr.n++
case "POST":
buf := new(bytes.Buffer)
io.Copy(buf, req.Body)
body := buf.String()
if n, err := strconv.Atoi(body); err != nil {
fmt.Fprintf(w, "bad POST: %v\nbody: [%v]\n", err, body)
} else {
ctr.n = n
fmt.Fprint(w, "counter reset\n")
}
}
fmt.Fprintf(w, "counter = %d\n", ctr.n)
}
// simple flag server
var booleanflag = flag.Bool("boolean", true, "another flag for testing")
func FlagServer(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, "Flags:\n")
flag.VisitAll(func(f *flag.Flag) {
if f.Value.String() != f.DefValue {
fmt.Fprintf(w, "%s = %s [default = %s]\n", f.Name, f.Value.String(), f.DefValue)
} else {
fmt.Fprintf(w, "%s = %s\n", f.Name, f.Value.String())
}
})
}
// simple argument server
func ArgServer(w http.ResponseWriter, req *http.Request) {
for _, s := range os.Args {
fmt.Fprint(w, s, " ")
}
}
// a channel (just for the fun of it)
type Chan chan int
func ChanCreate() Chan {
c := make(Chan)
go func(c Chan) {
for x := 0; ; x++ {
c <- x
}
}(c)
return c
}
func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, fmt.Sprintf("channel send #%d\n", <-ch))
}
// exec a program, redirecting output
func DateServer(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
date, err := exec.Command("/bin/date").Output()
if err != nil {
http.Error(rw, err.Error(), 500)
return
}
rw.Write(date)
}
func Logger(w http.ResponseWriter, req *http.Request) {
log.Print(req.URL)
http.Error(w, "oops", 404)
}
var webroot = flag.String("root", os.Getenv("HOME"), "web root directory")
func main() {
flag.Parse()
// The counter is published as a variable directly.
ctr := new(Counter)
expvar.Publish("counter", ctr)
http.Handle("/counter", ctr)
http.Handle("/", http.HandlerFunc(Logger))
http.Handle("/go/", http.StripPrefix("/go/", http.FileServer(http.Dir(*webroot))))
http.Handle("/chan", ChanCreate())
http.HandleFunc("/flags", FlagServer)
http.HandleFunc("/args", ArgServer)
http.HandleFunc("/go/hello", HelloServer)
http.HandleFunc("/date", DateServer)
log.Fatal(http.ListenAndServe(":12345", nil))
}
| bsd-3-clause |
Swatinem/jsdelivr | files/wordpress/3.8/js/colorpicker.js | 29083 | // ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
/* SOURCE FILE: AnchorPosition.js */
/*
AnchorPosition.js
Author: Matt Kruse
Last modified: 10/11/02
DESCRIPTION: These functions find the position of an <A> tag in a document,
so other elements can be positioned relative to it.
COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform.
FUNCTIONS:
getAnchorPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor. Position is relative to the PAGE.
getAnchorWindowPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor, relative to the WHOLE SCREEN.
NOTES:
1) For popping up separate browser windows, use getAnchorWindowPosition.
Otherwise, use getAnchorPosition
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
*/
// getAnchorPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
// This function will return an Object with x and y properties
var useWindow=false;
var coordinates=new Object();
var x=0,y=0;
// Browser capability sniffing
var use_gebi=false, use_css=false, use_layers=false;
if (document.getElementById) { use_gebi=true; }
else if (document.all) { use_css=true; }
else if (document.layers) { use_layers=true; }
// Logic to find position
if (use_gebi && document.all) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_gebi) {
var o=document.getElementById(anchorname);
x=AnchorPosition_getPageOffsetLeft(o);
y=AnchorPosition_getPageOffsetTop(o);
}
else if (use_css) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_layers) {
var found=0;
for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name==anchorname) { found=1; break; }
}
if (found==0) {
coordinates.x=0; coordinates.y=0; return coordinates;
}
x=document.anchors[i].x;
y=document.anchors[i].y;
}
else {
coordinates.x=0; coordinates.y=0; return coordinates;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// getAnchorWindowPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
var coordinates=getAnchorPosition(anchorname);
var x=0;
var y=0;
if (document.getElementById) {
if (isNaN(window.screenX)) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
}
else if (document.all) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else if (document.layers) {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
var ol=el.offsetLeft;
while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
return ol;
}
function AnchorPosition_getWindowOffsetLeft (el) {
return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop (el) {
var ot=el.offsetTop;
while((el=el.offsetParent) != null) { ot += el.offsetTop; }
return ot;
}
function AnchorPosition_getWindowOffsetTop (el) {
return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
}
/* SOURCE FILE: PopupWindow.js */
/*
PopupWindow.js
Author: Matt Kruse
Last modified: 02/16/04
DESCRIPTION: This object allows you to easily and quickly popup a window
in a certain place. The window can either be a DIV or a separate browser
window.
COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform. Due to bugs in Netscape 4.x, populating the popup
window with <STYLE> tags may cause errors.
USAGE:
// Create an object for a WINDOW popup
var win = new PopupWindow();
// Create an object for a DIV window using the DIV named 'mydiv'
var win = new PopupWindow('mydiv');
// Set the window to automatically hide itself when the user clicks
// anywhere else on the page except the popup
win.autoHide();
// Show the window relative to the anchor name passed in
win.showPopup(anchorname);
// Hide the popup
win.hidePopup();
// Set the size of the popup window (only applies to WINDOW popups
win.setSize(width,height);
// Populate the contents of the popup window that will be shown. If you
// change the contents while it is displayed, you will need to refresh()
win.populate(string);
// set the URL of the window, rather than populating its contents
// manually
win.setUrl("http://www.site.com/");
// Refresh the contents of the popup
win.refresh();
// Specify how many pixels to the right of the anchor the popup will appear
win.offsetX = 50;
// Specify how many pixels below the anchor the popup will appear
win.offsetY = 100;
NOTES:
1) Requires the functions in AnchorPosition.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a PopupWindow object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a PopupWindow object or
the autoHide() will not work correctly.
*/
// Set the position of the popup window based on the anchor
function PopupWindow_getXYPosition(anchorname) {
var coordinates;
if (this.type == "WINDOW") {
coordinates = getAnchorWindowPosition(anchorname);
}
else {
coordinates = getAnchorPosition(anchorname);
}
this.x = coordinates.x;
this.y = coordinates.y;
}
// Set width/height of DIV/popup window
function PopupWindow_setSize(width,height) {
this.width = width;
this.height = height;
}
// Fill the window with contents
function PopupWindow_populate(contents) {
this.contents = contents;
this.populated = false;
}
// Set the URL to go to
function PopupWindow_setUrl(url) {
this.url = url;
}
// Set the window popup properties
function PopupWindow_setWindowProperties(props) {
this.windowProperties = props;
}
// Refresh the displayed contents of the popup
function PopupWindow_refresh() {
if (this.divName != null) {
// refresh the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).innerHTML = this.contents;
}
else if (this.use_css) {
document.all[this.divName].innerHTML = this.contents;
}
else if (this.use_layers) {
var d = document.layers[this.divName];
d.document.open();
d.document.writeln(this.contents);
d.document.close();
}
}
else {
if (this.popupWindow != null && !this.popupWindow.closed) {
if (this.url!="") {
this.popupWindow.location.href=this.url;
}
else {
this.popupWindow.document.open();
this.popupWindow.document.writeln(this.contents);
this.popupWindow.document.close();
}
this.popupWindow.focus();
}
}
}
// Position and show the popup, relative to an anchor object
function PopupWindow_showPopup(anchorname) {
this.getXYPosition(anchorname);
this.x += this.offsetX;
this.y += this.offsetY;
if (!this.populated && (this.contents != "")) {
this.populated = true;
this.refresh();
}
if (this.divName != null) {
// Show the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).style.left = this.x + "px";
document.getElementById(this.divName).style.top = this.y;
document.getElementById(this.divName).style.visibility = "visible";
}
else if (this.use_css) {
document.all[this.divName].style.left = this.x;
document.all[this.divName].style.top = this.y;
document.all[this.divName].style.visibility = "visible";
}
else if (this.use_layers) {
document.layers[this.divName].left = this.x;
document.layers[this.divName].top = this.y;
document.layers[this.divName].visibility = "visible";
}
}
else {
if (this.popupWindow == null || this.popupWindow.closed) {
// If the popup window will go off-screen, move it so it doesn't
if (this.x<0) { this.x=0; }
if (this.y<0) { this.y=0; }
if (screen && screen.availHeight) {
if ((this.y + this.height) > screen.availHeight) {
this.y = screen.availHeight - this.height;
}
}
if (screen && screen.availWidth) {
if ((this.x + this.width) > screen.availWidth) {
this.x = screen.availWidth - this.width;
}
}
var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled );
this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");
}
this.refresh();
}
}
// Hide the popup
function PopupWindow_hidePopup() {
if (this.divName != null) {
if (this.use_gebi) {
document.getElementById(this.divName).style.visibility = "hidden";
}
else if (this.use_css) {
document.all[this.divName].style.visibility = "hidden";
}
else if (this.use_layers) {
document.layers[this.divName].visibility = "hidden";
}
}
else {
if (this.popupWindow && !this.popupWindow.closed) {
this.popupWindow.close();
this.popupWindow = null;
}
}
}
// Pass an event and return whether or not it was the popup DIV that was clicked
function PopupWindow_isClicked(e) {
if (this.divName != null) {
if (this.use_layers) {
var clickX = e.pageX;
var clickY = e.pageY;
var t = document.layers[this.divName];
if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
return true;
}
else { return false; }
}
else if (document.all) { // Need to hard-code this to trap IE for error-handling
var t = window.event.srcElement;
while (t.parentElement != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentElement;
}
return false;
}
else if (this.use_gebi && e) {
var t = e.originalTarget;
while (t.parentNode != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentNode;
}
return false;
}
return false;
}
return false;
}
// Check an onMouseDown event to see if we should hide
function PopupWindow_hideIfNotClicked(e) {
if (this.autoHideEnabled && !this.isClicked(e)) {
this.hidePopup();
}
}
// Call this to make the DIV disable automatically when mouse is clicked outside it
function PopupWindow_autoHide() {
this.autoHideEnabled = true;
}
// This global function checks all PopupWindow objects onmouseup to see if they should be hidden
function PopupWindow_hidePopupWindows(e) {
for (var i=0; i<popupWindowObjects.length; i++) {
if (popupWindowObjects[i] != null) {
var p = popupWindowObjects[i];
p.hideIfNotClicked(e);
}
}
}
// Run this immediately to attach the event listener
function PopupWindow_attachListener() {
if (document.layers) {
document.captureEvents(Event.MOUSEUP);
}
window.popupWindowOldEventListener = document.onmouseup;
if (window.popupWindowOldEventListener != null) {
document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();");
}
else {
document.onmouseup = PopupWindow_hidePopupWindows;
}
}
// CONSTRUCTOR for the PopupWindow object
// Pass it a DIV name to use a DHTML popup, otherwise will default to window popup
function PopupWindow() {
if (!window.popupWindowIndex) { window.popupWindowIndex = 0; }
if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); }
if (!window.listenerAttached) {
window.listenerAttached = true;
PopupWindow_attachListener();
}
this.index = popupWindowIndex++;
popupWindowObjects[this.index] = this;
this.divName = null;
this.popupWindow = null;
this.width=0;
this.height=0;
this.populated = false;
this.visible = false;
this.autoHideEnabled = false;
this.contents = "";
this.url="";
this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";
if (arguments.length>0) {
this.type="DIV";
this.divName = arguments[0];
}
else {
this.type="WINDOW";
}
this.use_gebi = false;
this.use_css = false;
this.use_layers = false;
if (document.getElementById) { this.use_gebi = true; }
else if (document.all) { this.use_css = true; }
else if (document.layers) { this.use_layers = true; }
else { this.type = "WINDOW"; }
this.offsetX = 0;
this.offsetY = 0;
// Method mappings
this.getXYPosition = PopupWindow_getXYPosition;
this.populate = PopupWindow_populate;
this.setUrl = PopupWindow_setUrl;
this.setWindowProperties = PopupWindow_setWindowProperties;
this.refresh = PopupWindow_refresh;
this.showPopup = PopupWindow_showPopup;
this.hidePopup = PopupWindow_hidePopup;
this.setSize = PopupWindow_setSize;
this.isClicked = PopupWindow_isClicked;
this.autoHide = PopupWindow_autoHide;
this.hideIfNotClicked = PopupWindow_hideIfNotClicked;
}
/* SOURCE FILE: ColorPicker2.js */
/*
Last modified: 02/24/2003
DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB
form. It uses a color "swatch" to display the standard 216-color web-safe
palette. The user can then click on a color to select it.
COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js.
Only the latest DHTML-capable browsers will show the color and hex values
at the bottom as your mouse goes over them.
USAGE:
// Create a new ColorPicker object using DHTML popup
var cp = new ColorPicker();
// Create a new ColorPicker object using Window Popup
var cp = new ColorPicker('window');
// Add a link in your page to trigger the popup. For example:
<A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A>
// Or use the built-in "select" function to do the dirty work for you:
<A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A>
// If using DHTML popup, write out the required DIV tag near the bottom
// of your page.
<SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT>
// Write the 'pickColor' function that will be called when the user clicks
// a color and do something with the value. This is only required if you
// want to do something other than simply populate a form field, which is
// what the 'select' function will give you.
function pickColor(color) {
field.value = color;
}
NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a ColorPicker object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a ColorPicker object or
the color picker will not hide itself correctly.
*/
ColorPicker_targetInput = null;
function ColorPicker_writeDiv() {
document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>");
}
function ColorPicker_show(anchorname) {
this.showPopup(anchorname);
}
function ColorPicker_pickColor(color,obj) {
obj.hidePopup();
pickColor(color);
}
// A Default "pickColor" function to accept the color passed back from popup.
// User can over-ride this with their own function.
function pickColor(color) {
if (ColorPicker_targetInput==null) {
alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");
return;
}
ColorPicker_targetInput.value = color;
}
// This function is the easiest way to popup the window, select a color, and
// have the value populate a form field, which is what most people want to do.
function ColorPicker_select(inputobj,linkname) {
if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") {
alert("colorpicker.select: Input object passed is not a valid form input object");
window.ColorPicker_targetInput=null;
return;
}
window.ColorPicker_targetInput = inputobj;
this.show(linkname);
}
// This function runs when you move your mouse over a color block, if you have a newer browser
function ColorPicker_highlightColor(c) {
var thedoc = (arguments.length>1)?arguments[1]:window.document;
var d = thedoc.getElementById("colorPickerSelectedColor");
d.style.backgroundColor = c;
d = thedoc.getElementById("colorPickerSelectedColorValue");
d.innerHTML = c;
}
function ColorPicker() {
var windowMode = false;
// Create a new PopupWindow object
if (arguments.length==0) {
var divname = "colorPickerDiv";
}
else if (arguments[0] == "window") {
var divname = '';
windowMode = true;
}
else {
var divname = arguments[0];
}
if (divname != "") {
var cp = new PopupWindow(divname);
}
else {
var cp = new PopupWindow();
cp.setSize(225,250);
}
// Object variables
cp.currentValue = "#FFFFFF";
// Method Mappings
cp.writeDiv = ColorPicker_writeDiv;
cp.highlightColor = ColorPicker_highlightColor;
cp.show = ColorPicker_show;
cp.select = ColorPicker_select;
// Code to populate color picker window
var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099",
"#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099",
"#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099",
"#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF",
"#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F",
"#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000",
"#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399",
"#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399",
"#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399",
"#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF",
"#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F",
"#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00",
"#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699",
"#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699",
"#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699",
"#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F",
"#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F",
"#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F",
"#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999",
"#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999",
"#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999",
"#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF",
"#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F",
"#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000",
"#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99",
"#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99",
"#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99",
"#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF",
"#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F",
"#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00",
"#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99",
"#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99",
"#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99",
"#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F",
"#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F",
"#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F",
"#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666",
"#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000",
"#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000",
"#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999",
"#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF",
"#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66",
"#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00",
"#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000",
"#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099",
"#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF",
"#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF",
"#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC",
"#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000",
"#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900",
"#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33",
"#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF",
"#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF",
"#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F",
"#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F",
"#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F",
"#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000");
var total = colors.length;
var width = 72;
var cp_contents = "";
var windowRef = (windowMode)?"window.opener.":"";
if (windowMode) {
cp_contents += "<html><head><title>Select Color</title></head>";
cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>";
}
cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>";
var use_highlight = (document.getElementById || document.all)?true:false;
for (var i=0; i<total; i++) {
if ((i % width) == 0) { cp_contents += "<tr>"; }
if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; }
else { mo = ""; }
cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'> </a></td>';
if ( ((i+1)>=total) || (((i+1) % width) == 0)) {
cp_contents += "</tr>";
}
}
// If the browser supports dynamically changing TD cells, add the fancy stuff
if (document.getElementById) {
var width1 = Math.floor(width/2);
var width2 = width = width1;
cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'> </td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>";
}
cp_contents += "</table>";
if (windowMode) {
cp_contents += "</span></body></html>";
}
// end populate code
// Write the contents to the popup object
cp.populate(cp_contents+"\n");
// Move the table down a bit so you can see it
cp.offsetY = 25;
cp.autoHide();
return cp;
}
| mit |
dmonllao/moodle | lib/classes/event/completion_defaults_updated.php | 3067 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Default completion for activity in a course updated event
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\event;
defined('MOODLE_INTERNAL') || die();
/**
* Default completion for activity in a course updated event
*
* @package core
* @since Moodle 3.3
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class completion_defaults_updated extends base {
/**
* Initialise the event data.
*/
protected function init() {
$this->data['objecttable'] = 'course_completion_defaults';
$this->data['crud'] = 'u';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Returns localised general event name.
*
* @return string
*/
public static function get_name() {
return get_string('eventdefaultcompletionupdated', 'completion');
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/course/defaultcompletion.php', array('id' => $this->courseid));
}
/**
* Returns non-localised description of what happened.
*
* @return string
*/
public function get_description() {
return "The user with id '$this->userid' updated the default completion for module " .
"'{$this->other['modulename']}' in course with id '$this->courseid'.";
}
/**
* Custom validation.
*
* @throws \coding_exception
*/
protected function validate_data() {
parent::validate_data();
if ($this->contextlevel != CONTEXT_COURSE) {
throw new \coding_exception('Context passed must be course context.');
}
if (!isset($this->other['modulename'])) {
throw new \coding_exception('The \'modulename\' value must be set in other.');
}
}
/**
* This is used when restoring course logs where it is required that we
* map the objectid to it's new value in the new course.
*
* @return array
*/
public static function get_objectid_mapping() {
parent::get_objectid_mapping();
return array('db' => 'course_completion_defaults', 'restore' => 'course_completion_defaults');
}
}
| gpl-3.0 |
aina1205/virtualliverf1 | vendor/plugins/attachment_fu/test/validation_test.rb | 1623 | require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
class ValidationTest < Test::Unit::TestCase
def test_should_invalidate_big_files
@attachment = SmallAttachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:size)
@attachment.size = 2000
assert !@attachment.valid?
assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence
@attachment.size = 1000
assert !@attachment.valid?
assert_nil @attachment.errors.on(:size)
end
def test_should_invalidate_small_files
@attachment = BigAttachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:size)
@attachment.size = 2000
assert !@attachment.valid?
assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence
@attachment.size = 1.megabyte
assert !@attachment.valid?
assert_nil @attachment.errors.on(:size)
end
def test_should_validate_content_type
@attachment = PdfAttachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:content_type)
@attachment.content_type = 'foo'
assert !@attachment.valid?
assert @attachment.errors.on(:content_type)
@attachment.content_type = 'pdf'
assert !@attachment.valid?
assert_nil @attachment.errors.on(:content_type)
end
def test_should_require_filename
@attachment = Attachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:filename)
@attachment.filename = 'foo'
assert !@attachment.valid?
assert_nil @attachment.errors.on(:filename)
end
end | bsd-3-clause |
freedesktop-unofficial-mirror/gstreamer-sdk__gcc | libjava/classpath/java/security/MessageDigestSpi.java | 5659 | /* MessageDigestSpi.java --- The message digest service provider interface.
Copyright (C) 1999, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.security;
import java.nio.ByteBuffer;
/**
This is the Service Provider Interface (SPI) for MessageDigest
class in java.security. It provides the back end functionality
for the MessageDigest class so that it can compute message
hashes. The default hashes are SHA-1 and MD5. A message hash
takes data of arbitrary length and produces a unique number
representing it.
Cryptography service providers who want to implement their
own message digest hashes need only to subclass this class.
The implementation of a Cloneable interface is left to up to
the programmer of a subclass.
@version 0.0
@author Mark Benvenuto (ivymccough@worldnet.att.net)
*/
public abstract class MessageDigestSpi
{
/**
Default constructor of the MessageDigestSpi class
*/
public MessageDigestSpi()
{
}
/**
Returns the length of the digest. It may be overridden by the
provider to return the length of the digest. Default is to
return 0. It is concrete for backwards compatibility with JDK1.1
message digest classes.
@return Length of Digest in Bytes
@since 1.2
*/
protected int engineGetDigestLength()
{
return 0;
}
/**
Updates the digest with the specified byte.
@param input the byte to update digest with
*/
protected abstract void engineUpdate(byte input);
/**
Updates the digest with the specified bytes starting with the
offset and proceeding for the specified length.
@param input the byte array to update digest with
@param offset the offset of the byte to start with
@param len the number of the bytes to update with
*/
protected abstract void engineUpdate(byte[]input, int offset, int len);
/**
* Updates this digest with the remaining bytes of a byte buffer.
*
* @param input The input buffer.
* @since 1.5
*/
protected void engineUpdate (ByteBuffer input)
{
byte[] buf = new byte[1024];
while (input.hasRemaining())
{
int n = Math.min(input.remaining(), buf.length);
input.get (buf, 0, n);
engineUpdate (buf, 0, n);
}
}
/**
Computes the final digest of the stored bytes and returns
them. It performs any necessary padding. The message digest
should reset sensitive data after performing the digest.
@return An array of bytes containing the digest
*/
protected abstract byte[] engineDigest();
/**
Computes the final digest of the stored bytes and returns
them. It performs any necessary padding. The message digest
should reset sensitive data after performing the digest. This
method is left concrete for backwards compatibility with JDK1.1
message digest classes.
@param buf An array of bytes to store the digest
@param offset An offset to start storing the digest at
@param len The length of the buffer
@return Returns the length of the buffer
@since 1.2
*/
protected int engineDigest(byte[]buf, int offset, int len)
throws DigestException
{
if (engineGetDigestLength() > len)
throw new DigestException("Buffer is too small.");
byte[] tmp = engineDigest();
if (tmp.length > len)
throw new DigestException("Buffer is too small");
System.arraycopy(tmp, 0, buf, offset, tmp.length);
return tmp.length;
}
/**
Resets the digest engine. Reinitializes internal variables
and clears sensitive data.
*/
protected abstract void engineReset();
/**
Returns a clone of this class.
If cloning is not supported, then by default the class throws a
CloneNotSupportedException. The MessageDigestSpi provider
implementation has to overload this class in order to be
cloneable.
*/
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
| gpl-2.0 |
jameskumar/go | src/runtime/zgoos_plan9.go | 336 | // generated by gengoos.go using 'go generate'
package runtime
const theGoos = `plan9`
const goos_android = 0
const goos_darwin = 0
const goos_dragonfly = 0
const goos_freebsd = 0
const goos_linux = 0
const goos_nacl = 0
const goos_netbsd = 0
const goos_openbsd = 0
const goos_plan9 = 1
const goos_solaris = 0
const goos_windows = 0
| bsd-3-clause |
wzzlYwzzl/kdashboard | Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listers.go | 18243 | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache
import (
"fmt"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/labels"
)
// TODO: generate these classes and methods for all resources of interest using
// a script. Can use "go generate" once 1.4 is supported by all users.
// StoreToPodLister makes a Store have the List method of the client.PodInterface
// The Store must contain (only) Pods.
//
// Example:
// s := cache.NewStore()
// lw := cache.ListWatch{Client: c, FieldSelector: sel, Resource: "pods"}
// r := cache.NewReflector(lw, &api.Pod{}, s).Run()
// l := StoreToPodLister{s}
// l.List()
type StoreToPodLister struct {
Store
}
// Please note that selector is filtering among the pods that have gotten into
// the store; there may have been some filtering that already happened before
// that.
//
// TODO: converge on the interface in pkg/client.
func (s *StoreToPodLister) List(selector labels.Selector) (pods []*api.Pod, err error) {
// TODO: it'd be great to just call
// s.Pods(api.NamespaceAll).List(selector), however then we'd have to
// remake the list.Items as a []*api.Pod. So leave this separate for
// now.
for _, m := range s.Store.List() {
pod := m.(*api.Pod)
if selector.Matches(labels.Set(pod.Labels)) {
pods = append(pods, pod)
}
}
return pods, nil
}
// Pods is taking baby steps to be more like the api in pkg/client
func (s *StoreToPodLister) Pods(namespace string) storePodsNamespacer {
return storePodsNamespacer{s.Store, namespace}
}
type storePodsNamespacer struct {
store Store
namespace string
}
// Please note that selector is filtering among the pods that have gotten into
// the store; there may have been some filtering that already happened before
// that.
func (s storePodsNamespacer) List(selector labels.Selector) (pods api.PodList, err error) {
list := api.PodList{}
for _, m := range s.store.List() {
pod := m.(*api.Pod)
if s.namespace == api.NamespaceAll || s.namespace == pod.Namespace {
if selector.Matches(labels.Set(pod.Labels)) {
list.Items = append(list.Items, *pod)
}
}
}
return list, nil
}
// Exists returns true if a pod matching the namespace/name of the given pod exists in the store.
func (s *StoreToPodLister) Exists(pod *api.Pod) (bool, error) {
_, exists, err := s.Store.Get(pod)
if err != nil {
return false, err
}
return exists, nil
}
// NodeConditionPredicate is a function that indicates whether the given node's conditions meet
// some set of criteria defined by the function.
type NodeConditionPredicate func(node api.Node) bool
// StoreToNodeLister makes a Store have the List method of the client.NodeInterface
// The Store must contain (only) Nodes.
type StoreToNodeLister struct {
Store
}
func (s *StoreToNodeLister) List() (machines api.NodeList, err error) {
for _, m := range s.Store.List() {
machines.Items = append(machines.Items, *(m.(*api.Node)))
}
return machines, nil
}
// NodeCondition returns a storeToNodeConditionLister
func (s *StoreToNodeLister) NodeCondition(predicate NodeConditionPredicate) storeToNodeConditionLister {
// TODO: Move this filtering server side. Currently our selectors don't facilitate searching through a list so we
// have the reflector filter out the Unschedulable field and sift through node conditions in the lister.
return storeToNodeConditionLister{s.Store, predicate}
}
// storeToNodeConditionLister filters and returns nodes matching the given type and status from the store.
type storeToNodeConditionLister struct {
store Store
predicate NodeConditionPredicate
}
// List returns a list of nodes that match the conditions defined by the predicate functions in the storeToNodeConditionLister.
func (s storeToNodeConditionLister) List() (nodes api.NodeList, err error) {
for _, m := range s.store.List() {
node := *m.(*api.Node)
if s.predicate(node) {
nodes.Items = append(nodes.Items, node)
} else {
glog.V(5).Infof("Node %s matches none of the conditions", node.Name)
}
}
return
}
// StoreToReplicationControllerLister gives a store List and Exists methods. The store must contain only ReplicationControllers.
type StoreToReplicationControllerLister struct {
Store
}
// Exists checks if the given rc exists in the store.
func (s *StoreToReplicationControllerLister) Exists(controller *api.ReplicationController) (bool, error) {
_, exists, err := s.Store.Get(controller)
if err != nil {
return false, err
}
return exists, nil
}
// StoreToReplicationControllerLister lists all controllers in the store.
// TODO: converge on the interface in pkg/client
func (s *StoreToReplicationControllerLister) List() (controllers []api.ReplicationController, err error) {
for _, c := range s.Store.List() {
controllers = append(controllers, *(c.(*api.ReplicationController)))
}
return controllers, nil
}
func (s *StoreToReplicationControllerLister) ReplicationControllers(namespace string) storeReplicationControllersNamespacer {
return storeReplicationControllersNamespacer{s.Store, namespace}
}
type storeReplicationControllersNamespacer struct {
store Store
namespace string
}
func (s storeReplicationControllersNamespacer) List(selector labels.Selector) (controllers []api.ReplicationController, err error) {
for _, c := range s.store.List() {
rc := *(c.(*api.ReplicationController))
if s.namespace == api.NamespaceAll || s.namespace == rc.Namespace {
if selector.Matches(labels.Set(rc.Labels)) {
controllers = append(controllers, rc)
}
}
}
return
}
// GetPodControllers returns a list of replication controllers managing a pod. Returns an error only if no matching controllers are found.
func (s *StoreToReplicationControllerLister) GetPodControllers(pod *api.Pod) (controllers []api.ReplicationController, err error) {
var selector labels.Selector
var rc api.ReplicationController
if len(pod.Labels) == 0 {
err = fmt.Errorf("no controllers found for pod %v because it has no labels", pod.Name)
return
}
for _, m := range s.Store.List() {
rc = *m.(*api.ReplicationController)
if rc.Namespace != pod.Namespace {
continue
}
labelSet := labels.Set(rc.Spec.Selector)
selector = labels.Set(rc.Spec.Selector).AsSelector()
// If an rc with a nil or empty selector creeps in, it should match nothing, not everything.
if labelSet.AsSelector().Empty() || !selector.Matches(labels.Set(pod.Labels)) {
continue
}
controllers = append(controllers, rc)
}
if len(controllers) == 0 {
err = fmt.Errorf("could not find controller for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return
}
// StoreToDeploymentLister gives a store List and Exists methods. The store must contain only Deployments.
type StoreToDeploymentLister struct {
Store
}
// Exists checks if the given deployment exists in the store.
func (s *StoreToDeploymentLister) Exists(deployment *extensions.Deployment) (bool, error) {
_, exists, err := s.Store.Get(deployment)
if err != nil {
return false, err
}
return exists, nil
}
// StoreToDeploymentLister lists all deployments in the store.
// TODO: converge on the interface in pkg/client
func (s *StoreToDeploymentLister) List() (deployments []extensions.Deployment, err error) {
for _, c := range s.Store.List() {
deployments = append(deployments, *(c.(*extensions.Deployment)))
}
return deployments, nil
}
// GetDeploymentsForReplicaSet returns a list of deployments managing a replica set. Returns an error only if no matching deployments are found.
func (s *StoreToDeploymentLister) GetDeploymentsForReplicaSet(rs *extensions.ReplicaSet) (deployments []extensions.Deployment, err error) {
var d extensions.Deployment
if len(rs.Labels) == 0 {
err = fmt.Errorf("no deployments found for ReplicaSet %v because it has no labels", rs.Name)
return
}
// TODO: MODIFY THIS METHOD so that it checks for the podTemplateSpecHash label
for _, m := range s.Store.List() {
d = *m.(*extensions.Deployment)
if d.Namespace != rs.Namespace {
continue
}
selector, err := unversioned.LabelSelectorAsSelector(d.Spec.Selector)
if err != nil {
return nil, fmt.Errorf("invalid label selector: %v", err)
}
// If a deployment with a nil or empty selector creeps in, it should match nothing, not everything.
if selector.Empty() || !selector.Matches(labels.Set(rs.Labels)) {
continue
}
deployments = append(deployments, d)
}
if len(deployments) == 0 {
err = fmt.Errorf("could not find deployments set for ReplicaSet %s in namespace %s with labels: %v", rs.Name, rs.Namespace, rs.Labels)
}
return
}
// StoreToReplicaSetLister gives a store List and Exists methods. The store must contain only ReplicaSets.
type StoreToReplicaSetLister struct {
Store
}
// Exists checks if the given ReplicaSet exists in the store.
func (s *StoreToReplicaSetLister) Exists(rs *extensions.ReplicaSet) (bool, error) {
_, exists, err := s.Store.Get(rs)
if err != nil {
return false, err
}
return exists, nil
}
// List lists all ReplicaSets in the store.
// TODO: converge on the interface in pkg/client
func (s *StoreToReplicaSetLister) List() (rss []extensions.ReplicaSet, err error) {
for _, rs := range s.Store.List() {
rss = append(rss, *(rs.(*extensions.ReplicaSet)))
}
return rss, nil
}
type storeReplicaSetsNamespacer struct {
store Store
namespace string
}
func (s storeReplicaSetsNamespacer) List(selector labels.Selector) (rss []extensions.ReplicaSet, err error) {
for _, c := range s.store.List() {
rs := *(c.(*extensions.ReplicaSet))
if s.namespace == api.NamespaceAll || s.namespace == rs.Namespace {
if selector.Matches(labels.Set(rs.Labels)) {
rss = append(rss, rs)
}
}
}
return
}
func (s *StoreToReplicaSetLister) ReplicaSets(namespace string) storeReplicaSetsNamespacer {
return storeReplicaSetsNamespacer{s.Store, namespace}
}
// GetPodReplicaSets returns a list of ReplicaSets managing a pod. Returns an error only if no matching ReplicaSets are found.
func (s *StoreToReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []extensions.ReplicaSet, err error) {
var selector labels.Selector
var rs extensions.ReplicaSet
if len(pod.Labels) == 0 {
err = fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name)
return
}
for _, m := range s.Store.List() {
rs = *m.(*extensions.ReplicaSet)
if rs.Namespace != pod.Namespace {
continue
}
selector, err = unversioned.LabelSelectorAsSelector(rs.Spec.Selector)
if err != nil {
err = fmt.Errorf("invalid selector: %v", err)
return
}
// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.
if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
continue
}
rss = append(rss, rs)
}
if len(rss) == 0 {
err = fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return
}
// StoreToDaemonSetLister gives a store List and Exists methods. The store must contain only DaemonSets.
type StoreToDaemonSetLister struct {
Store
}
// Exists checks if the given daemon set exists in the store.
func (s *StoreToDaemonSetLister) Exists(ds *extensions.DaemonSet) (bool, error) {
_, exists, err := s.Store.Get(ds)
if err != nil {
return false, err
}
return exists, nil
}
// List lists all daemon sets in the store.
// TODO: converge on the interface in pkg/client
func (s *StoreToDaemonSetLister) List() (dss extensions.DaemonSetList, err error) {
for _, c := range s.Store.List() {
dss.Items = append(dss.Items, *(c.(*extensions.DaemonSet)))
}
return dss, nil
}
// GetPodDaemonSets returns a list of daemon sets managing a pod.
// Returns an error if and only if no matching daemon sets are found.
func (s *StoreToDaemonSetLister) GetPodDaemonSets(pod *api.Pod) (daemonSets []extensions.DaemonSet, err error) {
var selector labels.Selector
var daemonSet extensions.DaemonSet
if len(pod.Labels) == 0 {
err = fmt.Errorf("no daemon sets found for pod %v because it has no labels", pod.Name)
return
}
for _, m := range s.Store.List() {
daemonSet = *m.(*extensions.DaemonSet)
if daemonSet.Namespace != pod.Namespace {
continue
}
selector, err = unversioned.LabelSelectorAsSelector(daemonSet.Spec.Selector)
if err != nil {
// this should not happen if the DaemonSet passed validation
return nil, err
}
// If a daemonSet with a nil or empty selector creeps in, it should match nothing, not everything.
if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
continue
}
daemonSets = append(daemonSets, daemonSet)
}
if len(daemonSets) == 0 {
err = fmt.Errorf("could not find daemon set for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return
}
// StoreToServiceLister makes a Store that has the List method of the client.ServiceInterface
// The Store must contain (only) Services.
type StoreToServiceLister struct {
Store
}
func (s *StoreToServiceLister) List() (services api.ServiceList, err error) {
for _, m := range s.Store.List() {
services.Items = append(services.Items, *(m.(*api.Service)))
}
return services, nil
}
// TODO: Move this back to scheduler as a helper function that takes a Store,
// rather than a method of StoreToServiceLister.
func (s *StoreToServiceLister) GetPodServices(pod *api.Pod) (services []api.Service, err error) {
var selector labels.Selector
var service api.Service
for _, m := range s.Store.List() {
service = *m.(*api.Service)
// consider only services that are in the same namespace as the pod
if service.Namespace != pod.Namespace {
continue
}
if service.Spec.Selector == nil {
// services with nil selectors match nothing, not everything.
continue
}
selector = labels.Set(service.Spec.Selector).AsSelector()
if selector.Matches(labels.Set(pod.Labels)) {
services = append(services, service)
}
}
if len(services) == 0 {
err = fmt.Errorf("could not find service for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return
}
// StoreToEndpointsLister makes a Store that lists endpoints.
type StoreToEndpointsLister struct {
Store
}
// List lists all endpoints in the store.
func (s *StoreToEndpointsLister) List() (services api.EndpointsList, err error) {
for _, m := range s.Store.List() {
services.Items = append(services.Items, *(m.(*api.Endpoints)))
}
return services, nil
}
// GetServiceEndpoints returns the endpoints of a service, matched on service name.
func (s *StoreToEndpointsLister) GetServiceEndpoints(svc *api.Service) (ep api.Endpoints, err error) {
for _, m := range s.Store.List() {
ep = *m.(*api.Endpoints)
if svc.Name == ep.Name && svc.Namespace == ep.Namespace {
return ep, nil
}
}
err = fmt.Errorf("could not find endpoints for service: %v", svc.Name)
return
}
// StoreToJobLister gives a store List and Exists methods. The store must contain only Jobs.
type StoreToJobLister struct {
Store
}
// Exists checks if the given job exists in the store.
func (s *StoreToJobLister) Exists(job *extensions.Job) (bool, error) {
_, exists, err := s.Store.Get(job)
if err != nil {
return false, err
}
return exists, nil
}
// StoreToJobLister lists all jobs in the store.
func (s *StoreToJobLister) List() (jobs extensions.JobList, err error) {
for _, c := range s.Store.List() {
jobs.Items = append(jobs.Items, *(c.(*extensions.Job)))
}
return jobs, nil
}
// GetPodJobs returns a list of jobs managing a pod. Returns an error only if no matching jobs are found.
func (s *StoreToJobLister) GetPodJobs(pod *api.Pod) (jobs []extensions.Job, err error) {
var selector labels.Selector
var job extensions.Job
if len(pod.Labels) == 0 {
err = fmt.Errorf("no jobs found for pod %v because it has no labels", pod.Name)
return
}
for _, m := range s.Store.List() {
job = *m.(*extensions.Job)
if job.Namespace != pod.Namespace {
continue
}
selector, _ = unversioned.LabelSelectorAsSelector(job.Spec.Selector)
if !selector.Matches(labels.Set(pod.Labels)) {
continue
}
jobs = append(jobs, job)
}
if len(jobs) == 0 {
err = fmt.Errorf("could not find jobs for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
}
return
}
// Typed wrapper around a store of PersistentVolumes
type StoreToPVFetcher struct {
Store
}
// GetPersistentVolumeInfo returns cached data for the PersistentVolume 'id'.
func (s *StoreToPVFetcher) GetPersistentVolumeInfo(id string) (*api.PersistentVolume, error) {
o, exists, err := s.Get(&api.PersistentVolume{ObjectMeta: api.ObjectMeta{Name: id}})
if err != nil {
return nil, fmt.Errorf("error retrieving PersistentVolume '%v' from cache: %v", id, err)
}
if !exists {
return nil, fmt.Errorf("PersistentVolume '%v' is not in cache", id)
}
return o.(*api.PersistentVolume), nil
}
// Typed wrapper around a store of PersistentVolumeClaims
type StoreToPVCFetcher struct {
Store
}
// GetPersistentVolumeClaimInfo returns cached data for the PersistentVolumeClaim 'id'.
func (s *StoreToPVCFetcher) GetPersistentVolumeClaimInfo(namespace string, id string) (*api.PersistentVolumeClaim, error) {
o, exists, err := s.Get(&api.PersistentVolumeClaim{ObjectMeta: api.ObjectMeta{Namespace: namespace, Name: id}})
if err != nil {
return nil, fmt.Errorf("error retrieving PersistentVolumeClaim '%s/%s' from cache: %v", namespace, id, err)
}
if !exists {
return nil, fmt.Errorf("PersistentVolumeClaim '%s/%s' is not in cache", namespace, id)
}
return o.(*api.PersistentVolumeClaim), nil
}
| apache-2.0 |
JoelPub/wordpress-amazon | blog/wp-admin/network/privacy.php | 267 | <?php
/**
* Network Privacy administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 4.9.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/privacy.php' );
| gpl-2.0 |
jhoffjann/aufeinwort | ghost/node_modules/validator/test/validator.test.js | 24348 | var node_validator = require('../lib'),
util = require('util')
Validator = new node_validator.Validator(),
ValidatorError = node_validator.ValidatorError,
assert = require('assert');
function dateFixture() {
return {
tomorrow: new Date(Date.now() + 86400000)
, yesterday: new Date(Date.now() - 86400000)
};
}
var FakeError = function(msg) {
Error.captureStackTrace(this, this);
this.name = 'FakeError';
this.message = msg;
};
util.inherits(FakeError, Error);
module.exports = {
'test #isEmail()': function () {
//Try some invalid emails
var invalid = [
'invalidemail@',
'invalid.com',
'@invalid.com'
];
invalid.forEach(function(email) {
try {
Validator.check(email, 'Invalid').isEmail();
assert.ok(false, 'Invalid email ('+email+') passed validation');
} catch(e) {
assert.equal('Invalid', e.message);
}
});
//Now try some valid ones
var valid = [
'foo@bar.com',
'x@x.x',
'foo@bar.com.au',
'foo+bar@bar.com'
];
try {
valid.forEach(function(email) {
Validator.check(email).isEmail();
});
} catch(e) {
assert.ok(false, 'A valid email did not pass validation');
}
},
'test #isUrl()': function () {
//Try some invalid URLs
var invalid = [
'xyz://foobar.com', //Only http, https and ftp are valid
'invalid/',
'invalid.x',
'invalid.',
'.com',
'http://com/',
'http://300.0.0.1/',
'mailto:foo@bar.com'
];
invalid.forEach(function(url) {
try {
Validator.check(url, 'Invalid').isUrl();
assert.ok(false, 'Invalid url ('+url+') passed validation');
} catch(e) {
assert.equal('Invalid', e.message);
}
});
//Now try some valid ones
var valid = [
'foobar.com',
'www.foobar.com',
'foobar.com/',
'valid.au',
'http://www.foobar.com/',
'https://www.foobar.com/',
'ftp://www.foobar.com/',
'http://www.foobar.com/~foobar',
'http://user:pass@www.foobar.com/',
'http://127.0.0.1/',
'http://10.0.0.0/',
'http://189.123.14.13/',
'http://duckduckgo.com/?q=%2F',
'http://foobar.com/t$-_.+!*\'(),',
'http://localhost:3000/'
];
try {
valid.forEach(function(url) {
Validator.check(url).isUrl();
});
} catch(e) {
assert.ok(false, 'A valid url did not pass validation');
}
},
'test #isIP()': function () {
//Try some invalid IPs
var invalid = [
'abc',
'256.0.0.0',
'0.0.0.256'
];
invalid.forEach(function(ip) {
try {
Validator.check(ip, 'Invalid').isIP();
assert.ok(false, 'Invalid IP ('+ip+') passed validation');
} catch(e) {
assert.equal('Invalid', e.message);
}
});
//Now try some valid ones
var valid = [
'127.0.0.1',
'0.0.0.0',
'255.255.255.255',
'1.2.3.4'
];
try {
valid.forEach(function(ip) {
Validator.check(ip).isIP();
});
} catch(e) {
assert.ok(false, 'A valid IP did not pass validation');
}
},
'test #isAlpha()': function () {
assert.ok(Validator.check('abc').isAlpha());
assert.ok(Validator.check('ABC').isAlpha());
assert.ok(Validator.check('FoObAr').isAlpha());
['123',123,'abc123',' ',''].forEach(function(str) {
try {
Validator.check(str).isAlpha();
assert.ok(false, 'isAlpha failed');
} catch (e) {}
});
},
'test #isAlphanumeric()': function () {
assert.ok(Validator.check('abc13').isAlphanumeric());
assert.ok(Validator.check('123').isAlphanumeric());
assert.ok(Validator.check('F1oO3bAr').isAlphanumeric());
['(*&ASD',' ','.',''].forEach(function(str) {
try {
Validator.check(str).isAlphanumeric();
assert.ok(false, 'isAlphanumeric failed');
} catch (e) {}
});
},
'test #isNumeric()': function () {
assert.ok(Validator.check('123').isNumeric());
assert.ok(Validator.check('00123').isNumeric());
assert.ok(Validator.check('-00123').isNumeric());
assert.ok(Validator.check('0').isNumeric());
assert.ok(Validator.check('-0').isNumeric());
['123.123',' ','.',''].forEach(function(str) {
try {
Validator.check(str).isNumeric();
assert.ok(false, 'isNumeric failed');
} catch (e) {}
});
},
'test #isLowercase()': function () {
assert.ok(Validator.check('abc').isLowercase());
assert.ok(Validator.check('foobar').isLowercase());
assert.ok(Validator.check('a').isLowercase());
assert.ok(Validator.check('123').isLowercase());
assert.ok(Validator.check('abc123').isLowercase());
assert.ok(Validator.check('this is lowercase.').isLowercase());
assert.ok(Validator.check('très über').isLowercase());
['123A','ABC','.',''].forEach(function(str) {
try {
Validator.check(str).isLowercase();
assert.ok(false, 'isLowercase failed');
} catch (e) {}
});
},
'test #isUppercase()': function () {
assert.ok(Validator.check('FOOBAR').isUppercase());
assert.ok(Validator.check('A').isUppercase());
assert.ok(Validator.check('123').isUppercase());
assert.ok(Validator.check('ABC123').isUppercase());
['abc','123aBC','.',''].forEach(function(str) {
try {
Validator.check(str).isUppercase();
assert.ok(false, 'isUpper failed');
} catch (e) {}
});
},
'test #isInt()': function () {
assert.ok(Validator.check('13').isInt());
assert.ok(Validator.check('123').isInt());
assert.ok(Validator.check('0').isInt());
assert.ok(Validator.check(0).isInt());
assert.ok(Validator.check(123).isInt());
assert.ok(Validator.check('-0').isInt());
['01', '-01', '000', '100e10', '123.123', ' ', ''].forEach(function(str) {
try {
Validator.check(str).isInt();
assert.ok(false, 'falsepositive');
} catch (e) {
if (e.message == 'falsepositive') {
e.message = 'isInt had a false positive: ' + str;
throw e;
}
}
});
},
'test #isDecimal()': function () {
assert.ok(Validator.check('123').isDecimal());
assert.ok(Validator.check('123.').isDecimal());
assert.ok(Validator.check('123.123').isDecimal());
assert.ok(Validator.check('-123.123').isDecimal());
assert.ok(Validator.check('0.123').isDecimal());
assert.ok(Validator.check('.123').isDecimal());
assert.ok(Validator.check('.0').isDecimal());
assert.ok(Validator.check('0').isDecimal());
assert.ok(Validator.check('-0').isDecimal());
assert.ok(Validator.check('01.123').isDecimal());
assert.ok(Validator.check('2.2250738585072011e-308').isDecimal());
assert.ok(Validator.check('-0.22250738585072011e-307').isDecimal());
assert.ok(Validator.check('-0.22250738585072011E-307').isDecimal());
['-.123',' ',''].forEach(function(str) {
try {
Validator.check(str).isDecimal();
assert.ok(false, 'falsepositive');
} catch (e) {
if (e.message == 'falsepositive') {
e.message = 'isDecimal had a false positive: ' + str;
throw e;
}
}
});
},
//Alias for isDecimal()
'test #isFloat()': function () {
assert.ok(Validator.check('0.5').isFloat());
},
'test #isNull()': function () {
assert.ok(Validator.check('').isNull());
assert.ok(Validator.check().isNull());
[' ','123','abc'].forEach(function(str) {
try {
Validator.check(str).isNull();
assert.ok(false, 'isNull failed');
} catch (e) {}
});
},
'test #notNull()': function () {
assert.ok(Validator.check('abc').notNull());
assert.ok(Validator.check('123').notNull());
assert.ok(Validator.check(' ').notNull());
[false,''].forEach(function(str) {
try {
Validator.check(str).notNull();
assert.ok(false, 'notNull failed');
} catch (e) {}
});
},
'test #notEmpty()': function () {
assert.ok(Validator.check('abc').notEmpty());
assert.ok(Validator.check('123').notEmpty());
assert.ok(Validator.check(' 123 ').notEmpty());
assert.ok(Validator.check([1,2]).notEmpty());
[false,' ','\r\n',' ','', NaN, []].forEach(function(str) {
try {
Validator.check(str).notEmpty();
assert.ok(false, 'notEmpty failed');
} catch (e) {}
});
},
'test #equals()': function () {
assert.ok(Validator.check('abc').equals('abc'));
assert.ok(Validator.check('123').equals(123));
assert.ok(Validator.check(' ').equals(' '));
assert.ok(Validator.check().equals(''));
try {
Validator.check(123).equals('abc');
assert.ok(false, 'equals failed');
} catch (e) {}
try {
Validator.check('').equals(' ');
assert.ok(false, 'equals failed');
} catch (e) {}
},
'test #contains()': function () {
assert.ok(Validator.check('abc').contains('abc'));
assert.ok(Validator.check('foobar').contains('oo'));
assert.ok(Validator.check('abc').contains('a'));
assert.ok(Validator.check(' ').contains(' '));
try {
Validator.check('abc').contains('');
assert.ok(false, 'contains failed');
} catch (e) {}
try {
Validator.check(123).contains('abc');
assert.ok(false, 'contains failed');
} catch (e) {}
try {
Validator.check('\t').contains('\t\t');
assert.ok(false, 'contains failed');
} catch (e) {}
},
'test #notContains()': function () {
assert.ok(Validator.check('abc').notContains('a '));
assert.ok(Validator.check('foobar').notContains('foobars'));
assert.ok(Validator.check('abc').notContains('123'));
try {
Validator.check(123).notContains(1);
assert.ok(false, 'notContains failed');
} catch (e) {}
try {
Validator.check(' ').contains('');
assert.ok(false, 'notContains failed');
} catch (e) {}
},
'test #regex()': function () {
assert.ok(Validator.check('abc').regex(/a/));
assert.ok(Validator.check('abc').regex(/^abc$/));
assert.ok(Validator.check('abc').regex('abc'));
assert.ok(Validator.check('ABC').regex(/^abc$/i));
assert.ok(Validator.check('ABC').regex('abc', 'i'));
assert.ok(Validator.check(12390947686129).regex(/^[0-9]+$/));
//Check the is() alias
assert.ok(Validator.check(12390947686129).is(/^[0-9]+$/));
try {
Validator.check(123).regex(/^1234$/);
assert.ok(false, 'regex failed');
} catch (e) {}
},
'test #notRegex()': function () {
assert.ok(Validator.check('foobar').notRegex(/e/));
assert.ok(Validator.check('ABC').notRegex('abc'));
assert.ok(Validator.check(12390947686129).notRegex(/a/));
//Check the not() alias
assert.ok(Validator.check(12390947686129).not(/^[a-z]+$/));
try {
Validator.check(123).notRegex(/123/);
assert.ok(false, 'regex failed');
} catch (e) {}
},
'test #len()': function () {
assert.ok(Validator.check('a').len(1));
assert.ok(Validator.check(123).len(2));
assert.ok(Validator.check(123).len(2, 4));
assert.ok(Validator.check(12).len(2,2));
try {
Validator.check('abc').len(4);
assert.ok(false, 'len failed');
} catch (e) {}
try {
Validator.check('abcd').len(1, 3);
assert.ok(false, 'len failed');
} catch (e) {}
},
'test #isUUID()': function () {
////xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
assert.ok(Validator.check('A987FBC9-4BED-3078-CF07-9141BA07C9F3').isUUID());
assert.ok(Validator.check('A987FBC9-4BED-3078-CF07-9141BA07C9F3').isUUID(1));
assert.ok(Validator.check('A987FBC9-4BED-3078-CF07-9141BA07C9F3').isUUID(2));
assert.ok(Validator.check('A987FBC9-4BED-3078-CF07-9141BA07C9F3').isUUID(3));
assert.ok(Validator.check('A987FBC9-4BED-4078-8F07-9141BA07C9F3').isUUID(4));
assert.ok(Validator.check('A987FBC9-4BED-5078-AF07-9141BA07C9F3').isUUID(5));
var badUuids = [
"",
null,
"xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3",
"A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx",
"A987FBC94BED3078CF079141BA07C9F3",
"934859",
"987FBC9-4BED-3078-CF07A-9141BA07C9F3",
"AAAAAAAA-1111-1111-AAAG-111111111111"
]
badUuids.forEach(function (item) {
assert.throws(function() { Validator.check(item).isUUID() }, /not a uuid/i);
assert.throws(function() { Validator.check(item).isUUID(1) }, /not a uuid/i);
assert.throws(function() { Validator.check(item).isUUID(2) }, /not a uuid/i);
assert.throws(function() { Validator.check(item).isUUID(3) }, /not a uuid/i);
assert.throws(function() { Validator.check(item).isUUID(4) }, /not a uuid/i);
assert.throws(function() { Validator.check(item).isUUID(5) }, /not a uuid/i);
});
try {
Validator.check('A987FBC9-4BED-5078-0F07-9141BA07C9F3').isUUID(5);
assert.ok(false, 'isUUID failed');
} catch (e) {}
try {
Validator.check('A987FBC9-4BED-4078-0F07-9141BA07C9F3').isUUID(4);
assert.ok(false, 'isUUID failed');
} catch (e) {}
try {
Validator.check('abc').isUUID();
assert.ok(false, 'isUUID failed');
} catch (e) {}
try {
Validator.check('A987FBC932-4BED-3078-CF07-9141BA07C9').isUUID();
assert.ok(false, 'isUUID failed');
} catch (e) {}
try {
Validator.check('A987FBG9-4BED-3078-CF07-9141BA07C9DE').isUUID();
assert.ok(false, 'isUUID failed');
} catch (e) {}
},
'test #isUUIDv3()': function () {
////xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B
var goodUuidV3s = [
"987FBC97-4BED-3078-AF07-9141BA07C9F3"
]
goodUuidV3s.forEach(function (item) {
assert.ok(Validator.check(item).isUUIDv3());
});
var badUuidV3s = [
"",
null,
"xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3",
"A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx",
"A987FBC94BED3078CF079141BA07C9F3",
"934859",
"987FBC9-4BED-3078-CF07A-9141BA07C9F3",
"AAAAAAAA-1111-1111-AAAG-111111111111"
]
badUuidV3s.forEach(function (item) {
assert.throws(function() { Validator.check(item).isUUIDv3() }, /not a uuid v3/i);
});
},
'test #isUUIDv4()': function () {
////xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B
var goodUuidV4s = [
"713ae7e3-cb32-45f9-adcb-7c4fa86b90c1",
"625e63f3-58f5-40b7-83a1-a72ad31acffb",
"57b73598-8764-4ad0-a76a-679bb6640eb1",
"9c858901-8a57-4791-81fe-4c455b099bc9"
]
goodUuidV4s.forEach(function (item) {
assert.ok(Validator.check(item).isUUIDv4());
});
var badUuidV4s = [
"",
null,
"xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3",
"A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx",
"A987FBC94BED3078CF079141BA07C9F3",
"934859",
"987FBC9-4BED-3078-CF07A-9141BA07C9F3",
"AAAAAAAA-1111-1111-AAAG-111111111111",
"9a47c6fa-e388-1f4f-8c67-77ef5f476ff6"
]
badUuidV4s.forEach(function (item) {
assert.throws(function() { Validator.check(item).isUUIDv4() }, /not a uuid v4/i);
});
},
'test #isUUIDv5()': function () {
////xxxxxxxx-xxxx-5xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B
var goodUuidV5s = [
"987FBC97-4BED-5078-AF07-9141BA07C9F3",
"987FBC97-4BED-5078-BF07-9141BA07C9F3",
"987FBC97-4BED-5078-8F07-9141BA07C9F3",
"987FBC97-4BED-5078-9F07-9141BA07C9F3"
];
goodUuidV5s.forEach(function (item) {
assert.ok(Validator.check(item).isUUIDv5());
});
var badUuidV5s = [
"",
null,
"xxxA987FBC9-4BED-5078-CF07-9141BA07C9F3",
"A987FBC9-4BED-5078-CF07-9141BA07C9F3xxx",
"A987FBC94BED5078CF079141BA07C9F3",
"934859",
"987FBC9-4BED-5078-CF07A-9141BA07C9F3",
"AAAAAAAA-1111-1111-AAAG-111111111111"
];
badUuidV5s.forEach(function (item) {
assert.throws(function() { Validator.check(item).isUUIDv5(); }, /not a uuid v5/i);
});
},
'test #isIn(options)': function () {
assert.ok(Validator.check('foo').isIn('foobar'));
assert.ok(Validator.check('foo').isIn('I love football'));
assert.ok(Validator.check('foo').isIn(['foo', 'bar', 'baz']));
assert.ok(Validator.check('1').isIn([1, 2, 3]));
assert.throws(function() {
Validator.check('foo').isIn(['bar', 'baz']);
}, /unexpected/i
);
assert.throws(function() {
Validator.check('foo').isIn('bar, baz');
}, /unexpected/i
);
assert.throws(function() {
Validator.check('foo').isIn(1234567);
}, /invalid/i
);
assert.throws(function() {
Validator.check('foo').isIn({foo:"foo",bar:"bar"});
}, /invalid/i
);
},
'test #notIn(options)': function () {
assert.ok(Validator.check('foo').notIn('bar'));
assert.ok(Validator.check('foo').notIn('awesome'));
assert.ok(Validator.check('foo').notIn(['foobar', 'bar', 'baz']));
assert.throws(function() {
Validator.check('foo').notIn(['foo', 'bar', 'baz']);
}, /unexpected/i
);
assert.throws(function() {
Validator.check('foo').notIn('foobar');
}, /unexpected/i
);
assert.throws(function() {
Validator.check('1').notIn([1, 2, 3]);
}, /unexpected/i);
assert.throws(function() {
Validator.check('foo').notIn(1234567);
}, /invalid/i
);
assert.throws(function() {
Validator.check('foo').notIn({foo:"foo",bar:"bar"});
}, /invalid/i
);
},
'test #isDate()': function() {
assert.ok(Validator.check('2011-08-04').isDate());
assert.ok(Validator.check('04. 08. 2011.').isDate());
assert.ok(Validator.check('08/04/2011').isDate());
assert.ok(Validator.check('2011.08.04').isDate());
assert.ok(Validator.check('4. 8. 2011. GMT').isDate());
assert.ok(Validator.check('2011-08-04 12:00').isDate());
assert.throws(Validator.check('foo').isDate);
assert.throws(Validator.check('2011-foo-04').isDate);
assert.throws(Validator.check('GMT').isDate);
},
'test #min()': function() {
assert.ok(Validator.check('4').min(2));
assert.ok(Validator.check('5').min(5));
assert.ok(Validator.check('3.2').min(3));
assert.ok(Validator.check('4.2').min(4.2));
assert.throws(function() {
Validator.check('5').min(10);
});
assert.throws(function() {
Validator.check('5.1').min(5.11);
});
},
'test #max()': function() {
assert.ok(Validator.check('4').max(5));
assert.ok(Validator.check('7').max(7));
assert.ok(Validator.check('6.3').max(7));
assert.ok(Validator.check('2.9').max(2.9));
assert.throws(function() {
Validator.check('5').max(2);
});
assert.throws(function() {
Validator.check('4.9').max(4.2);
});
},
'test #isDate()': function() {
assert.ok(Validator.check('2011-08-04').isDate());
assert.ok(Validator.check('04. 08. 2011.').isDate());
assert.ok(Validator.check('08/04/2011').isDate());
assert.ok(Validator.check('2011.08.04').isDate());
assert.ok(Validator.check('4. 8. 2011. GMT').isDate());
assert.ok(Validator.check('2011-08-04 12:00').isDate());
assert.throws(Validator.check('foo').isDate);
assert.throws(Validator.check('2011-foo-04').isDate);
assert.throws(Validator.check('GMT').isDate);
},
'test #isAfter()': function() {
var f = dateFixture();
assert.ok(Validator.check('2011-08-04').isAfter('2011-08-03'));
assert.ok(Validator.check(f.tomorrow).isAfter());
assert.throws(function() {
Validator.check('08/04/2011').isAfter('2011-09-01');
});
assert.throws(function() {
Validator.check(f.yesterday).isAfter();
});
assert.throws(function() {
Validator.check('2011-09-01').isAfter('2011-09-01');
});
},
'test #isBefore()': function() {
var f = dateFixture();
assert.ok(Validator.check('2011-08-04').isBefore('2011-08-06'));
assert.ok(Validator.check(f.yesterday).isBefore());
assert.throws(function() {
Validator.check('08/04/2011').isBefore('2011-07-01');
});
assert.throws(function() {
Validator.check(f.tomorrow).isBefore();
});
assert.throws(function() {
Validator.check('2011-09-01').isBefore('2011-09-01');
});
},
'test #isDivisibleBy()': function() {
assert.ok(Validator.check('10').isDivisibleBy(2));
assert.ok(Validator.check('6').isDivisibleBy(3));
assert.throws(function() {
Validator.check('10').isDivisibleBy('alpha');
});
assert.throws(function() {
Validator.check('alpha').isDivisibleBy(2);
});
assert.throws(function() {
Validator.check('alpha').isDivisibleBy('alpha');
});
assert.throws(function() {
Validator.check('5').isDivisibleBy(2);
});
assert.throws(function() {
Validator.check('6.7').isDivisibleBy(3);
});
},
'test error is instanceof ValidatorError': function() {
try {
Validator.check('not_an_email', 'Invalid').isEmail();
} catch(e) {
assert.strictEqual(true, e instanceof ValidatorError);
assert.strictEqual(true, e instanceof Error);
assert.notStrictEqual(true, e instanceof FakeError);
}
},
'test false as error message': function() {
var v = new node_validator.Validator()
, error = null;
v.error = function (msg) {
error = msg;
};
v.check('not_an_email', false).isEmail();
assert.strictEqual(error, false);
}
}
| mit |
krichter722/gcc | gcc/testsuite/g++.dg/ext/complex7.C | 126 | // { dg-options "" }
class A
{
static const _Complex double x = 1.0 + 2.0i;
};
// { dg-prune-output "constexpr. needed" }
| gpl-2.0 |
kiki091/LintasEbtke | vendor/symfony/console/Exception/InvalidOptionException.php | 508 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Exception;
/**
* Represents an incorrect option name typed in the console.
*
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*/
class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface
{
}
| gpl-3.0 |
driebit/symfony1 | lib/plugins/sfPropelPlugin/lib/vendor/propel/Propel.php | 27256 | <?php
/*
* $Id: Propel.php 1691 2010-04-19 22:01:20Z francois $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://propel.phpdb.org>.
*/
require 'propel/PropelException.php';
require 'propel/adapter/DBAdapter.php';
require 'propel/util/PropelPDO.php';
/**
* Propel's main resource pool and initialization & configuration class.
*
* This static class is used to handle Propel initialization and to maintain all of the
* open database connections and instantiated database maps.
*
* @author Hans Lellelid <hans@xmpl.rg> (Propel)
* @author Daniel Rall <dlr@finemaltcoding.com> (Torque)
* @author Magnús Þór Torfason <magnus@handtolvur.is> (Torque)
* @author Jason van Zyl <jvanzyl@apache.org> (Torque)
* @author Rafal Krzewski <Rafal.Krzewski@e-point.pl> (Torque)
* @author Martin Poeschl <mpoeschl@marmot.at> (Torque)
* @author Henning P. Schmiedehausen <hps@intermeta.de> (Torque)
* @author Kurt Schrader <kschrader@karmalab.org> (Torque)
* @version $Revision: 1691 $
* @package propel
*/
class Propel
{
/**
* A constant for <code>default</code>.
*/
const DEFAULT_NAME = "default";
/**
* A constant defining 'System is unusuable' logging level
*/
const LOG_EMERG = 0;
/**
* A constant defining 'Immediate action required' logging level
*/
const LOG_ALERT = 1;
/**
* A constant defining 'Critical conditions' logging level
*/
const LOG_CRIT = 2;
/**
* A constant defining 'Error conditions' logging level
*/
const LOG_ERR = 3;
/**
* A constant defining 'Warning conditions' logging level
*/
const LOG_WARNING = 4;
/**
* A constant defining 'Normal but significant' logging level
*/
const LOG_NOTICE = 5;
/**
* A constant defining 'Informational' logging level
*/
const LOG_INFO = 6;
/**
* A constant defining 'Debug-level messages' logging level
*/
const LOG_DEBUG = 7;
/**
* The Propel version.
*/
const VERSION = '1.4.2';
/**
* The class name for a PDO object.
*/
const CLASS_PDO = 'PDO';
/**
* The class name for a PropelPDO object.
*/
const CLASS_PROPEL_PDO = 'PropelPDO';
/**
* The class name for a DebugPDO object.
*/
const CLASS_DEBUG_PDO = 'DebugPDO';
/**
* Constant used to request a READ connection (applies to replication).
*/
const CONNECTION_READ = 'read';
/**
* Constant used to request a WRITE connection (applies to replication).
*/
const CONNECTION_WRITE = 'write';
/**
* @var string The db name that is specified as the default in the property file
*/
private static $defaultDBName;
/**
* @var array The global cache of database maps
*/
private static $dbMaps = array();
/**
* @var array The cache of DB adapter keys
*/
private static $adapterMap = array();
/**
* @var array Cache of established connections (to eliminate overhead).
*/
private static $connectionMap = array();
/**
* @var PropelConfiguration Propel-specific configuration.
*/
private static $configuration;
/**
* @var bool flag to set to true once this class has been initialized
*/
private static $isInit = false;
/**
* @var Log optional logger
*/
private static $logger = null;
/**
* @var string The name of the database mapper class
*/
private static $databaseMapClass = 'DatabaseMap';
/**
* @var bool Whether the object instance pooling is enabled
*/
private static $instancePoolingEnabled = true;
/**
* @var bool For replication, whether to force the use of master connection.
*/
private static $forceMasterConnection = false;
/**
* @var array A map of class names and their file paths for autoloading
*/
private static $autoloadMap = array(
'PropelException' => 'propel/PropelException.php',
'DBAdapter' => 'propel/adapter/DBAdapter.php',
'DBMSSQL' => 'propel/adapter/DBMSSQL.php',
'MssqlPropelPDO' => 'propel/adapter/MSSQL/MssqlPropelPDO.php',
'MssqlDebugPDO' => 'propel/adapter/MSSQL/MssqlDebugPDO.php',
'MssqlDateTime' => 'propel/adapter/MSSQL/MssqlDateTime.class.php',
'DBMySQL' => 'propel/adapter/DBMySQL.php',
'DBMySQLi' => 'propel/adapter/DBMySQLi.php',
'DBNone' => 'propel/adapter/DBNone.php',
'DBOracle' => 'propel/adapter/DBOracle.php',
'DBPostgres' => 'propel/adapter/DBPostgres.php',
'DBSQLite' => 'propel/adapter/DBSQLite.php',
'DBSybase' => 'propel/adapter/DBSybase.php',
'BasicLogger' => 'propel/logger/BasicLogger.php',
'MojaviLogAdapter' => 'propel/logger/MojaviLogAdapter.php',
'ColumnMap' => 'propel/map/ColumnMap.php',
'DatabaseMap' => 'propel/map/DatabaseMap.php',
'TableMap' => 'propel/map/TableMap.php',
'RelationMap' => 'propel/map/RelationMap.php',
'ValidatorMap' => 'propel/map/ValidatorMap.php',
'BaseObject' => 'propel/om/BaseObject.php',
'NodeObject' => 'propel/om/NodeObject.php',
'Persistent' => 'propel/om/Persistent.php',
'PreOrderNodeIterator' => 'propel/om/PreOrderNodeIterator.php',
'NestedSetPreOrderNodeIterator' => 'propel/om/NestedSetPreOrderNodeIterator.php',
'NestedSetRecursiveIterator' => 'propel/om/NestedSetRecursiveIterator.php',
'BasePeer' => 'propel/util/BasePeer.php',
'NodePeer' => 'propel/util/NodePeer.php',
'Criteria' => 'propel/util/Criteria.php',
'Join' => 'propel/util/Join.php',
'PeerInfo' => 'propel/util/PeerInfo.php',
'PropelColumnTypes' => 'propel/util/PropelColumnTypes.php',
'PropelConfiguration' => 'propel/util/PropelConfiguration.php',
'PropelConfigurationIterator' => 'propel/util/PropelConfigurationIterator.php',
'PropelPDO' => 'propel/util/PropelPDO.php',
'PropelPager' => 'propel/util/PropelPager.php',
'PropelDateTime' => 'propel/util/PropelDateTime.php',
'DebugPDO' => 'propel/util/DebugPDO.php',
'DebugPDOStatement' => 'propel/util/DebugPDOStatement.php',
'BasicValidator' => 'propel/validator/BasicValidator.php',
'MatchValidator' => 'propel/validator/MatchValidator.php',
'MaxLengthValidator' => 'propel/validator/MaxLengthValidator.php',
'MaxValueValidator' => 'propel/validator/MaxValueValidator.php',
'MinLengthValidator' => 'propel/validator/MinLengthValidator.php',
'MinValueValidator' => 'propel/validator/MinValueValidator.php',
'NotMatchValidator' => 'propel/validator/NotMatchValidator.php',
'RequiredValidator' => 'propel/validator/RequiredValidator.php',
'UniqueValidator' => 'propel/validator/UniqueValidator.php',
'ValidValuesValidator' => 'propel/validator/ValidValuesValidator.php',
'ValidationFailed' => 'propel/validator/ValidationFailed.php',
);
/**
* Initializes Propel
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function initialize()
{
if (self::$configuration === null) {
throw new PropelException("Propel cannot be initialized without a valid configuration. Please check the log files for further details.");
}
self::configureLogging();
// reset the connection map (this should enable runtime changes of connection params)
self::$connectionMap = array();
if (isset(self::$configuration['classmap']) && is_array(self::$configuration['classmap'])) {
self::$autoloadMap = array_merge(self::$configuration['classmap'], self::$autoloadMap);
}
self::$isInit = true;
}
/**
* Configure Propel using a PHP (array) config file.
*
* @param string Path (absolute or relative to include_path) to config file.
*
* @throws PropelException If configuration file cannot be opened.
* (E_WARNING probably will also be raised by PHP)
*/
public static function configure($configFile)
{
$configuration = include($configFile);
if ($configuration === false) {
throw new PropelException("Unable to open configuration file: " . var_export($configFile, true));
}
self::setConfiguration($configuration);
}
/**
* Configure the logging system, if config is specified in the runtime configuration.
*/
protected static function configureLogging()
{
if (self::$logger === null) {
if (isset(self::$configuration['log']) && is_array(self::$configuration['log']) && count(self::$configuration['log'])) {
include_once 'Log.php'; // PEAR Log class
$c = self::$configuration['log'];
$type = isset($c['type']) ? $c['type'] : 'file';
$name = isset($c['name']) ? $c['name'] : './propel.log';
$ident = isset($c['ident']) ? $c['ident'] : 'propel';
$conf = isset($c['conf']) ? $c['conf'] : array();
$level = isset($c['level']) ? $c['level'] : PEAR_LOG_DEBUG;
self::$logger = Log::singleton($type, $name, $ident, $conf, $level);
} // if isset()
}
}
/**
* Initialization of Propel with a PHP (array) configuration file.
*
* @param string $c The Propel configuration file path.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function init($c)
{
self::configure($c);
self::initialize();
}
/**
* Determine whether Propel has already been initialized.
*
* @return bool True if Propel is already initialized.
*/
public static function isInit()
{
return self::$isInit;
}
/**
* Sets the configuration for Propel and all dependencies.
*
* @param mixed The Configuration (array or PropelConfiguration)
*/
public static function setConfiguration($c)
{
if (is_array($c)) {
if (isset($c['propel']) && is_array($c['propel'])) {
$c = $c['propel'];
}
$c = new PropelConfiguration($c);
}
self::$configuration = $c;
}
/**
* Get the configuration for this component.
*
* @param int - PropelConfiguration::TYPE_ARRAY: return the configuration as an array
* (for backward compatibility this is the default)
* - PropelConfiguration::TYPE_ARRAY_FLAT: return the configuration as a flat array
* ($config['name.space.item'])
* - PropelConfiguration::TYPE_OBJECT: return the configuration as a PropelConfiguration instance
* @return mixed The Configuration (array or PropelConfiguration)
*/
public static function getConfiguration($type = PropelConfiguration::TYPE_ARRAY)
{
return self::$configuration->getParameters($type);
}
/**
* Override the configured logger.
*
* This is primarily for things like unit tests / debugging where
* you want to change the logger without altering the configuration file.
*
* You can use any logger class that implements the propel.logger.BasicLogger
* interface. This interface is based on PEAR::Log, so you can also simply pass
* a PEAR::Log object to this method.
*
* @param object The new logger to use. ([PEAR] Log or BasicLogger)
*/
public static function setLogger($logger)
{
self::$logger = $logger;
}
/**
* Returns true if a logger, for example PEAR::Log, has been configured,
* otherwise false.
*
* @return bool True if Propel uses logging
*/
public static function hasLogger()
{
return (self::$logger !== null);
}
/**
* Get the configured logger.
*
* @return object Configured log class ([PEAR] Log or BasicLogger).
*/
public static function logger()
{
return self::$logger;
}
/**
* Logs a message
* If a logger has been configured, the logger will be used, otherwrise the
* logging message will be discarded without any further action
*
* @param string The message that will be logged.
* @param string The logging level.
*
* @return bool True if the message was logged successfully or no logger was used.
*/
public static function log($message, $level = self::LOG_DEBUG)
{
if (self::hasLogger()) {
$logger = self::logger();
switch ($level) {
case self::LOG_EMERG:
return $logger->log($message, $level);
case self::LOG_ALERT:
return $logger->alert($message);
case self::LOG_CRIT:
return $logger->crit($message);
case self::LOG_ERR:
return $logger->err($message);
case self::LOG_WARNING:
return $logger->warning($message);
case self::LOG_NOTICE:
return $logger->notice($message);
case self::LOG_INFO:
return $logger->info($message);
default:
return $logger->debug($message);
}
}
return true;
}
/**
* Returns the database map information. Name relates to the name
* of the connection pool to associate with the map.
*
* The database maps are "registered" by the generated map builder classes.
*
* @param string The name of the database corresponding to the DatabaseMap to retrieve.
*
* @return DatabaseMap The named <code>DatabaseMap</code>.
*
* @throws PropelException - if database map is null or propel was not initialized properly.
*/
public static function getDatabaseMap($name = null)
{
if ($name === null) {
$name = self::getDefaultDB();
if ($name === null) {
throw new PropelException("DatabaseMap name is null!");
}
}
if (!isset(self::$dbMaps[$name])) {
$clazz = self::$databaseMapClass;
self::$dbMaps[$name] = new $clazz($name);
}
return self::$dbMaps[$name];
}
/**
* Sets the database map object to use for specified datasource.
*
* @param string $name The datasource name.
* @param DatabaseMap $map The database map object to use for specified datasource.
*/
public static function setDatabaseMap($name, DatabaseMap $map)
{
if ($name === null) {
$name = self::getDefaultDB();
}
self::$dbMaps[$name] = $map;
}
/**
* For replication, set whether to always force the use of a master connection.
*
* @param boolean $bit True or False
*/
public static function setForceMasterConnection($bit)
{
self::$forceMasterConnection = (bool) $bit;
}
/**
* For replication, whether to always force the use of a master connection.
*
* @return boolean
*/
public static function getForceMasterConnection()
{
return self::$forceMasterConnection;
}
/**
* Sets a Connection for specified datasource name.
*
* @param string $name The datasource name for the connection being set.
* @param PropelPDO $con The PDO connection.
* @param string $mode Whether this is a READ or WRITE connection (Propel::CONNECTION_READ, Propel::CONNECTION_WRITE)
*/
public static function setConnection($name, PropelPDO $con, $mode = Propel::CONNECTION_WRITE)
{
if ($name === null) {
$name = self::getDefaultDB();
}
if ($mode == Propel::CONNECTION_READ) {
self::$connectionMap[$name]['slave'] = $con;
} else {
self::$connectionMap[$name]['master'] = $con;
}
}
/**
* Gets an already-opened PDO connection or opens a new one for passed-in db name.
*
* @param string $name The datasource name that is used to look up the DSN from the runtime configuation file.
* @param string $mode The connection mode (this applies to replication systems).
*
* @return PDO A database connection
*
* @throws PropelException - if connection cannot be configured or initialized.
*/
public static function getConnection($name = null, $mode = Propel::CONNECTION_WRITE)
{
if ($name === null) {
$name = self::getDefaultDB();
}
// IF a WRITE-mode connection was requested
// or Propel is configured to always use the master connection
// or the slave for this connection has already been set to FALSE (indicating no slave)
// THEN return the master connection.
if ($mode != Propel::CONNECTION_READ || self::$forceMasterConnection || (isset(self::$connectionMap[$name]['slave']) && self::$connectionMap[$name]['slave'] === false)) {
if (!isset(self::$connectionMap[$name]['master'])) {
// load connection parameter for master connection
$conparams = isset(self::$configuration['datasources'][$name]['connection']) ? self::$configuration['datasources'][$name]['connection'] : null;
if (empty($conparams)) {
throw new PropelException('No connection information in your runtime configuration file for datasource ['.$name.']');
}
// initialize master connection
$con = Propel::initConnection($conparams, $name);
self::$connectionMap[$name]['master'] = $con;
}
return self::$connectionMap[$name]['master'];
} else {
if (!isset(self::$connectionMap[$name]['slave'])) {
// we've already ensured that the configuration exists, in previous if-statement
$slaveconfigs = isset(self::$configuration['datasources'][$name]['slaves']) ? self::$configuration['datasources'][$name]['slaves'] : null;
if (empty($slaveconfigs)) { // no slaves configured for this datasource
self::$connectionMap[$name]['slave'] = false;
return self::getConnection($name, Propel::CONNECTION_WRITE); // Recurse to get the WRITE connection
} else { // Initialize a new slave
if (isset($slaveconfigs['connection']['dsn'])) { // only one slave connection configured
$conparams = $slaveconfigs['connection'];
} else {
$randkey = array_rand($slaveconfigs['connection']);
$conparams = $slaveconfigs['connection'][$randkey];
if (empty($conparams)) {
throw new PropelException('No connection information in your runtime configuration file for SLAVE ['.$randkey.'] to datasource ['.$name.']');
}
}
// initialize master connection
$con = Propel::initConnection($conparams, $name);
self::$connectionMap[$name]['slave'] = $con;
}
} // if datasource slave not set
return self::$connectionMap[$name]['slave'];
} // if mode == CONNECTION_WRITE
} // getConnection()
/**
* Opens a new PDO connection for passed-in db name.
*
* @param array $conparams Connection paramters.
* @param string $name Datasource name.
* @param string $defaultClass The PDO subclass to instantiate if there is no explicit classname
* specified in the connection params (default is Propel::CLASS_PROPEL_PDO)
*
* @return PDO A database connection of the given class (PDO, PropelPDO, SlavePDO or user-defined)
*
* @throws PropelException - if lower-level exception caught when trying to connect.
*/
public static function initConnection($conparams, $name, $defaultClass = Propel::CLASS_PROPEL_PDO)
{
$dsn = $conparams['dsn'];
if ($dsn === null) {
throw new PropelException('No dsn specified in your connection parameters for datasource ['.$name.']');
}
if (isset($conparams['classname']) && !empty($conparams['classname'])) {
$classname = $conparams['classname'];
if (!class_exists($classname)) {
throw new PropelException('Unable to load specified PDO subclass: ' . $classname);
}
} else {
$classname = $defaultClass;
}
$user = isset($conparams['user']) ? $conparams['user'] : null;
$password = isset($conparams['password']) ? $conparams['password'] : null;
// load any driver options from the config file
// driver options are those PDO settings that have to be passed during the connection construction
$driver_options = array();
if ( isset($conparams['options']) && is_array($conparams['options']) ) {
try {
self::processDriverOptions( $conparams['options'], $driver_options );
} catch (PropelException $e) {
throw new PropelException('Error processing driver options for datasource ['.$name.']', $e);
}
}
try {
$con = new $classname($dsn, $user, $password, $driver_options);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
throw new PropelException("Unable to open PDO connection", $e);
}
// load any connection options from the config file
// connection attributes are those PDO flags that have to be set on the initialized connection
if (isset($conparams['attributes']) && is_array($conparams['attributes'])) {
$attributes = array();
try {
self::processDriverOptions( $conparams['attributes'], $attributes );
} catch (PropelException $e) {
throw new PropelException('Error processing connection attributes for datasource ['.$name.']', $e);
}
foreach ($attributes as $key => $value) {
$con->setAttribute($key, $value);
}
}
// initialize the connection using the settings provided in the config file. this could be a "SET NAMES <charset>" query for MySQL, for instance
$adapter = self::getDB($name);
$adapter->initConnection($con, isset($conparams['settings']) && is_array($conparams['settings']) ? $conparams['settings'] : array());
return $con;
}
/**
* Internal function to handle driver options or conneciton attributes in PDO.
*
* Process the INI file flags to be passed to each connection.
*
* @param array Where to find the list of constant flags and their new setting.
* @param array Put the data into here
*
* @throws PropelException If invalid options were specified.
*/
private static function processDriverOptions($source, &$write_to)
{
foreach ($source as $option => $optiondata) {
if (is_string($option) && strpos($option, '::') !== false) {
$key = $option;
} elseif (is_string($option)) {
$key = 'PropelPDO::' . $option;
}
if (!defined($key)) {
throw new PropelException("Invalid PDO option/attribute name specified: ".$key);
}
$key = constant($key);
$value = $optiondata['value'];
if (is_string($value) && strpos($value, '::') !== false) {
if (!defined($value)) {
throw new PropelException("Invalid PDO option/attribute value specified: ".$value);
}
$value = constant($value);
}
$write_to[$key] = $value;
}
}
/**
* Returns database adapter for a specific datasource.
*
* @param string The datasource name.
*
* @return DBAdapter The corresponding database adapter.
*
* @throws PropelException If unable to find DBdapter for specified db.
*/
public static function getDB($name = null)
{
if ($name === null) {
$name = self::getDefaultDB();
}
if (!isset(self::$adapterMap[$name])) {
if (!isset(self::$configuration['datasources'][$name]['adapter'])) {
throw new PropelException("Unable to find adapter for datasource [" . $name . "].");
}
$db = DBAdapter::factory(self::$configuration['datasources'][$name]['adapter']);
// register the adapter for this name
self::$adapterMap[$name] = $db;
}
return self::$adapterMap[$name];
}
/**
* Sets a database adapter for specified datasource.
*
* @param string $name The datasource name.
* @param DBAdapter $adapter The DBAdapter implementation to use.
*/
public static function setDB($name, DBAdapter $adapter)
{
if ($name === null) {
$name = self::getDefaultDB();
}
self::$adapterMap[$name] = $adapter;
}
/**
* Returns the name of the default database.
*
* @return string Name of the default DB
*/
public static function getDefaultDB()
{
if (self::$defaultDBName === null) {
// Determine default database name.
self::$defaultDBName = isset(self::$configuration['datasources']['default']) ? self::$configuration['datasources']['default'] : self::DEFAULT_NAME;
}
return self::$defaultDBName;
}
/**
* Closes any associated resource handles.
*
* This method frees any database connection handles that have been
* opened by the getConnection() method.
*/
public static function close()
{
foreach (self::$connectionMap as $idx => $cons) {
// Propel::log("Closing connections for " . $idx, Propel::LOG_DEBUG);
unset(self::$connectionMap[$idx]);
}
}
/**
* Autoload function for loading propel dependencies.
*
* @param string The class name needing loading.
*
* @return boolean TRUE if the class was loaded, false otherwise.
*/
public static function autoload($className)
{
if (isset(self::$autoloadMap[$className])) {
require(self::$autoloadMap[$className]);
return true;
}
return false;
}
/**
* Include once a file specified in DOT notation and reutrn unqualified clasname.
*
* Typically, Propel uses autoload is used to load classes and expects that all classes
* referenced within Propel are included in Propel's autoload map. This method is only
* called when a specific non-Propel classname was specified -- for example, the
* classname of a validator in the schema.xml. This method will attempt to include that
* class via autoload and then relative to a location on the include_path.
*
* @param string $class dot-path to clas (e.g. path.to.my.ClassName).
* @return string unqualified classname
*/
public static function importClass($path) {
// extract classname
if (($pos = strrpos($path, '.')) === false) {
$class = $path;
} else {
$class = substr($path, $pos + 1);
}
// check if class exists, using autoloader to attempt to load it.
if (class_exists($class, $useAutoload=true)) {
return $class;
}
// turn to filesystem path
$path = strtr($path, '.', DIRECTORY_SEPARATOR) . '.php';
// include class
$ret = include_once($path);
if ($ret === false) {
throw new PropelException("Unable to import class: " . $class . " from " . $path);
}
// return qualified name
return $class;
}
/**
* Set your own class-name for Database-Mapping. Then
* you can change the whole TableMap-Model, but keep its
* functionality for Criteria.
*
* @param string The name of the class.
*/
public static function setDatabaseMapClass($name)
{
self::$databaseMapClass = $name;
}
/**
* Disable instance pooling.
*/
public static function disableInstancePooling()
{
self::$instancePoolingEnabled = false;
}
/**
* Enable instance pooling (enabled by default).
*/
public static function enableInstancePooling()
{
self::$instancePoolingEnabled = true;
}
/**
* the instance pooling behaviour. True by default.
*
* @return boolean Whether the pooling is enabled or not.
*/
public static function isInstancePoolingEnabled()
{
return self::$instancePoolingEnabled;
}
}
spl_autoload_register(array('Propel', 'autoload'));
| mit |
chriskmanx/qmole | QMOLEDEV/icu4c-4_8_1_1/source/common/schriter.cpp | 3655 | /*
******************************************************************************
* Copyright (C) 1998-2010, International Business Machines Corporation and
* others. All Rights Reserved.
******************************************************************************
*
* File schriter.cpp
*
* Modification History:
*
* Date Name Description
* 05/05/99 stephen Cleaned up.
******************************************************************************
*/
#include <typeinfo> // for 'typeid' to work
#include "unicode/chariter.h"
#include "unicode/schriter.h"
U_NAMESPACE_BEGIN
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(StringCharacterIterator)
StringCharacterIterator::StringCharacterIterator()
: UCharCharacterIterator(),
text()
{
// NEVER DEFAULT CONSTRUCT!
}
StringCharacterIterator::StringCharacterIterator(const UnicodeString& textStr)
: UCharCharacterIterator(textStr.getBuffer(), textStr.length()),
text(textStr)
{
// we had set the input parameter's array, now we need to set our copy's array
UCharCharacterIterator::text = this->text.getBuffer();
}
StringCharacterIterator::StringCharacterIterator(const UnicodeString& textStr,
int32_t textPos)
: UCharCharacterIterator(textStr.getBuffer(), textStr.length(), textPos),
text(textStr)
{
// we had set the input parameter's array, now we need to set our copy's array
UCharCharacterIterator::text = this->text.getBuffer();
}
StringCharacterIterator::StringCharacterIterator(const UnicodeString& textStr,
int32_t textBegin,
int32_t textEnd,
int32_t textPos)
: UCharCharacterIterator(textStr.getBuffer(), textStr.length(), textBegin, textEnd, textPos),
text(textStr)
{
// we had set the input parameter's array, now we need to set our copy's array
UCharCharacterIterator::text = this->text.getBuffer();
}
StringCharacterIterator::StringCharacterIterator(const StringCharacterIterator& that)
: UCharCharacterIterator(that),
text(that.text)
{
// we had set the input parameter's array, now we need to set our copy's array
UCharCharacterIterator::text = this->text.getBuffer();
}
StringCharacterIterator::~StringCharacterIterator() {
}
StringCharacterIterator&
StringCharacterIterator::operator=(const StringCharacterIterator& that) {
UCharCharacterIterator::operator=(that);
text = that.text;
// we had set the input parameter's array, now we need to set our copy's array
UCharCharacterIterator::text = this->text.getBuffer();
return *this;
}
UBool
StringCharacterIterator::operator==(const ForwardCharacterIterator& that) const {
if (this == &that) {
return TRUE;
}
// do not call UCharCharacterIterator::operator==()
// because that checks for array pointer equality
// while we compare UnicodeString objects
if (typeid(*this) != typeid(that)) {
return FALSE;
}
StringCharacterIterator& realThat = (StringCharacterIterator&)that;
return text == realThat.text
&& pos == realThat.pos
&& begin == realThat.begin
&& end == realThat.end;
}
CharacterIterator*
StringCharacterIterator::clone() const {
return new StringCharacterIterator(*this);
}
void
StringCharacterIterator::setText(const UnicodeString& newText) {
text = newText;
UCharCharacterIterator::setText(text.getBuffer(), text.length());
}
void
StringCharacterIterator::getText(UnicodeString& result) {
result = text;
}
U_NAMESPACE_END
| gpl-3.0 |
staugs/blog | node_modules/bower/node_modules/bower-registry-client/node_modules/bower-config/node_modules/mout/lang/inheritPrototype.js | 463 | var createObject = require('./createObject');
/**
* Inherit prototype from another Object.
* - inspired by Nicholas Zackas <http://nczonline.net> Solution
* @param {object} child Child object
* @param {object} parent Parent Object
*/
function inheritPrototype(child, parent){
var p = createObject(parent.prototype);
p.constructor = child;
child.prototype = p;
}
module.exports = inheritPrototype;
| mit |
satishpatil2k13/ODPI-Hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestUGIWithExternalKdc.java | 2560 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.hadoop.security;
import java.io.IOException;
import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import static org.apache.hadoop.security.SecurityUtilTestHelper.isExternalKdcRunning;
import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
/**
* Tests kerberos keytab login using a user-specified external KDC
*
* To run, users must specify the following system properties:
* externalKdc=true
* java.security.krb5.conf
* user.principal
* user.keytab
*/
public class TestUGIWithExternalKdc {
@Before
public void testExternalKdcRunning() {
Assume.assumeTrue(isExternalKdcRunning());
}
@Test
public void testLogin() throws IOException {
String userPrincipal = System.getProperty("user.principal");
String userKeyTab = System.getProperty("user.keytab");
Assert.assertNotNull("User principal was not specified", userPrincipal);
Assert.assertNotNull("User keytab was not specified", userKeyTab);
Configuration conf = new Configuration();
conf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
"kerberos");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation ugi = UserGroupInformation
.loginUserFromKeytabAndReturnUGI(userPrincipal, userKeyTab);
Assert.assertEquals(AuthenticationMethod.KERBEROS,
ugi.getAuthenticationMethod());
try {
UserGroupInformation
.loginUserFromKeytabAndReturnUGI("bogus@EXAMPLE.COM", userKeyTab);
Assert.fail("Login should have failed");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| apache-2.0 |
LaVraiePrimaire/homepage | node_modules/protractor/testapp/bindings/bindings.js | 882 | function BindingsCtrl($scope) {
$scope.planets = [
{ name: 'Mercury',
radius: 1516
},
{ name: 'Venus',
radius: 3760
},
{ name: 'Earth',
radius: 3959,
moons: ['Luna']
},
{ name: 'Mars',
radius: 2106,
moons: ['Phobos', 'Deimos']
},
{ name: 'Jupiter',
radius: 43441,
moons: ['Europa', 'Io', 'Ganymede', 'Castillo']
},
{ name: 'Saturn',
radius: 36184,
moons: ['Titan', 'Rhea', 'Iapetus', 'Dione']
},
{ name: 'Uranus',
radius: 15759,
moons: ['Titania', 'Oberon', 'Umbriel', 'Ariel']
},
{ name: 'Neptune',
radius: 15299,
moons: ['Triton', 'Proteus', 'Nereid', 'Larissa']
}
];
$scope.planet = $scope.planets[0];
$scope.getRadiusKm = function() {
return $scope.planet.radius * 0.6213;
};
}
BindingsCtrl.$inject = ['$scope'];
| apache-2.0 |
freedesktop-unofficial-mirror/gstreamer-sdk__gcc | gcc/testsuite/g++.dg/template/nontype10.C | 246 | // { dg-do compile }
// Contributed by: Giovanni Bajo <giovannibajo at gcc dot gnu dot org>
#include <cstddef>
template <int T> struct A {};
template <void* T> struct B {};
A<NULL> a; // { dg-warning "NULL" }
B<NULL> b; // { dg-error "" }
| gpl-2.0 |
eddyb/servo | tests/wpt/web-platform-tests/tools/pytest/testing/test_collection.py | 23182 | import pytest, py
from _pytest.main import Session, EXIT_NOTESTSCOLLECTED
class TestCollector:
def test_collect_versus_item(self):
from pytest import Collector, Item
assert not issubclass(Collector, Item)
assert not issubclass(Item, Collector)
def test_compat_attributes(self, testdir, recwarn):
modcol = testdir.getmodulecol("""
def test_pass(): pass
def test_fail(): assert 0
""")
recwarn.clear()
assert modcol.Module == pytest.Module
assert modcol.Class == pytest.Class
assert modcol.Item == pytest.Item
assert modcol.File == pytest.File
assert modcol.Function == pytest.Function
def test_check_equality(self, testdir):
modcol = testdir.getmodulecol("""
def test_pass(): pass
def test_fail(): assert 0
""")
fn1 = testdir.collect_by_name(modcol, "test_pass")
assert isinstance(fn1, pytest.Function)
fn2 = testdir.collect_by_name(modcol, "test_pass")
assert isinstance(fn2, pytest.Function)
assert fn1 == fn2
assert fn1 != modcol
if py.std.sys.version_info < (3, 0):
assert cmp(fn1, fn2) == 0
assert hash(fn1) == hash(fn2)
fn3 = testdir.collect_by_name(modcol, "test_fail")
assert isinstance(fn3, pytest.Function)
assert not (fn1 == fn3)
assert fn1 != fn3
for fn in fn1,fn2,fn3:
assert fn != 3
assert fn != modcol
assert fn != [1,2,3]
assert [1,2,3] != fn
assert modcol != fn
def test_getparent(self, testdir):
modcol = testdir.getmodulecol("""
class TestClass:
def test_foo():
pass
""")
cls = testdir.collect_by_name(modcol, "TestClass")
fn = testdir.collect_by_name(
testdir.collect_by_name(cls, "()"), "test_foo")
parent = fn.getparent(pytest.Module)
assert parent is modcol
parent = fn.getparent(pytest.Function)
assert parent is fn
parent = fn.getparent(pytest.Class)
assert parent is cls
def test_getcustomfile_roundtrip(self, testdir):
hello = testdir.makefile(".xxx", hello="world")
testdir.makepyfile(conftest="""
import pytest
class CustomFile(pytest.File):
pass
def pytest_collect_file(path, parent):
if path.ext == ".xxx":
return CustomFile(path, parent=parent)
""")
node = testdir.getpathnode(hello)
assert isinstance(node, pytest.File)
assert node.name == "hello.xxx"
nodes = node.session.perform_collect([node.nodeid], genitems=False)
assert len(nodes) == 1
assert isinstance(nodes[0], pytest.File)
class TestCollectFS:
def test_ignored_certain_directories(self, testdir):
tmpdir = testdir.tmpdir
tmpdir.ensure("_darcs", 'test_notfound.py')
tmpdir.ensure("CVS", 'test_notfound.py')
tmpdir.ensure("{arch}", 'test_notfound.py')
tmpdir.ensure(".whatever", 'test_notfound.py')
tmpdir.ensure(".bzr", 'test_notfound.py')
tmpdir.ensure("normal", 'test_found.py')
for x in tmpdir.visit("test_*.py"):
x.write("def test_hello(): pass")
result = testdir.runpytest("--collect-only")
s = result.stdout.str()
assert "test_notfound" not in s
assert "test_found" in s
def test_custom_norecursedirs(self, testdir):
testdir.makeini("""
[pytest]
norecursedirs = mydir xyz*
""")
tmpdir = testdir.tmpdir
tmpdir.ensure("mydir", "test_hello.py").write("def test_1(): pass")
tmpdir.ensure("xyz123", "test_2.py").write("def test_2(): 0/0")
tmpdir.ensure("xy", "test_ok.py").write("def test_3(): pass")
rec = testdir.inline_run()
rec.assertoutcome(passed=1)
rec = testdir.inline_run("xyz123/test_2.py")
rec.assertoutcome(failed=1)
def test_testpaths_ini(self, testdir, monkeypatch):
testdir.makeini("""
[pytest]
testpaths = gui uts
""")
tmpdir = testdir.tmpdir
tmpdir.ensure("env", "test_1.py").write("def test_env(): pass")
tmpdir.ensure("gui", "test_2.py").write("def test_gui(): pass")
tmpdir.ensure("uts", "test_3.py").write("def test_uts(): pass")
# executing from rootdir only tests from `testpaths` directories
# are collected
items, reprec = testdir.inline_genitems('-v')
assert [x.name for x in items] == ['test_gui', 'test_uts']
# check that explicitly passing directories in the command-line
# collects the tests
for dirname in ('env', 'gui', 'uts'):
items, reprec = testdir.inline_genitems(tmpdir.join(dirname))
assert [x.name for x in items] == ['test_%s' % dirname]
# changing cwd to each subdirectory and running pytest without
# arguments collects the tests in that directory normally
for dirname in ('env', 'gui', 'uts'):
monkeypatch.chdir(testdir.tmpdir.join(dirname))
items, reprec = testdir.inline_genitems()
assert [x.name for x in items] == ['test_%s' % dirname]
class TestCollectPluginHookRelay:
def test_pytest_collect_file(self, testdir):
wascalled = []
class Plugin:
def pytest_collect_file(self, path, parent):
wascalled.append(path)
testdir.makefile(".abc", "xyz")
pytest.main([testdir.tmpdir], plugins=[Plugin()])
assert len(wascalled) == 1
assert wascalled[0].ext == '.abc'
def test_pytest_collect_directory(self, testdir):
wascalled = []
class Plugin:
def pytest_collect_directory(self, path, parent):
wascalled.append(path.basename)
testdir.mkdir("hello")
testdir.mkdir("world")
pytest.main(testdir.tmpdir, plugins=[Plugin()])
assert "hello" in wascalled
assert "world" in wascalled
class TestPrunetraceback:
def test_collection_error(self, testdir):
p = testdir.makepyfile("""
import not_exists
""")
result = testdir.runpytest(p)
assert "__import__" not in result.stdout.str(), "too long traceback"
result.stdout.fnmatch_lines([
"*ERROR collecting*",
"*mport*not_exists*"
])
def test_custom_repr_failure(self, testdir):
p = testdir.makepyfile("""
import not_exists
""")
testdir.makeconftest("""
import pytest
def pytest_collect_file(path, parent):
return MyFile(path, parent)
class MyError(Exception):
pass
class MyFile(pytest.File):
def collect(self):
raise MyError()
def repr_failure(self, excinfo):
if excinfo.errisinstance(MyError):
return "hello world"
return pytest.File.repr_failure(self, excinfo)
""")
result = testdir.runpytest(p)
result.stdout.fnmatch_lines([
"*ERROR collecting*",
"*hello world*",
])
@pytest.mark.xfail(reason="other mechanism for adding to reporting needed")
def test_collect_report_postprocessing(self, testdir):
p = testdir.makepyfile("""
import not_exists
""")
testdir.makeconftest("""
import pytest
def pytest_make_collect_report(__multicall__):
rep = __multicall__.execute()
rep.headerlines += ["header1"]
return rep
""")
result = testdir.runpytest(p)
result.stdout.fnmatch_lines([
"*ERROR collecting*",
"*header1*",
])
class TestCustomConftests:
def test_ignore_collect_path(self, testdir):
testdir.makeconftest("""
def pytest_ignore_collect(path, config):
return path.basename.startswith("x") or \
path.basename == "test_one.py"
""")
sub = testdir.mkdir("xy123")
sub.ensure("test_hello.py").write("syntax error")
sub.join("conftest.py").write("syntax error")
testdir.makepyfile("def test_hello(): pass")
testdir.makepyfile(test_one="syntax error")
result = testdir.runpytest("--fulltrace")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_ignore_collect_not_called_on_argument(self, testdir):
testdir.makeconftest("""
def pytest_ignore_collect(path, config):
return True
""")
p = testdir.makepyfile("def test_hello(): pass")
result = testdir.runpytest(p)
assert result.ret == 0
result.stdout.fnmatch_lines("*1 passed*")
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
result.stdout.fnmatch_lines("*collected 0 items*")
def test_collectignore_exclude_on_option(self, testdir):
testdir.makeconftest("""
collect_ignore = ['hello', 'test_world.py']
def pytest_addoption(parser):
parser.addoption("--XX", action="store_true", default=False)
def pytest_configure(config):
if config.getvalue("XX"):
collect_ignore[:] = []
""")
testdir.mkdir("hello")
testdir.makepyfile(test_world="def test_hello(): pass")
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
assert "passed" not in result.stdout.str()
result = testdir.runpytest("--XX")
assert result.ret == 0
assert "passed" in result.stdout.str()
def test_pytest_fs_collect_hooks_are_seen(self, testdir):
testdir.makeconftest("""
import pytest
class MyModule(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule(path, parent)
""")
testdir.mkdir("sub")
testdir.makepyfile("def test_x(): pass")
result = testdir.runpytest("--collect-only")
result.stdout.fnmatch_lines([
"*MyModule*",
"*test_x*"
])
def test_pytest_collect_file_from_sister_dir(self, testdir):
sub1 = testdir.mkpydir("sub1")
sub2 = testdir.mkpydir("sub2")
conf1 = testdir.makeconftest("""
import pytest
class MyModule1(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule1(path, parent)
""")
conf1.move(sub1.join(conf1.basename))
conf2 = testdir.makeconftest("""
import pytest
class MyModule2(pytest.Module):
pass
def pytest_collect_file(path, parent):
if path.ext == ".py":
return MyModule2(path, parent)
""")
conf2.move(sub2.join(conf2.basename))
p = testdir.makepyfile("def test_x(): pass")
p.copy(sub1.join(p.basename))
p.copy(sub2.join(p.basename))
result = testdir.runpytest("--collect-only")
result.stdout.fnmatch_lines([
"*MyModule1*",
"*MyModule2*",
"*test_x*"
])
class TestSession:
def test_parsearg(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
subdir = testdir.mkdir("sub")
subdir.ensure("__init__.py")
target = subdir.join(p.basename)
p.move(target)
subdir.chdir()
config = testdir.parseconfig(p.basename)
rcol = Session(config=config)
assert rcol.fspath == subdir
parts = rcol._parsearg(p.basename)
assert parts[0] == target
assert len(parts) == 1
parts = rcol._parsearg(p.basename + "::test_func")
assert parts[0] == target
assert parts[1] == "test_func"
assert len(parts) == 2
def test_collect_topdir(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
id = "::".join([p.basename, "test_func"])
# XXX migrate to collectonly? (see below)
config = testdir.parseconfig(id)
topdir = testdir.tmpdir
rcol = Session(config)
assert topdir == rcol.fspath
#rootid = rcol.nodeid
#root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]
#assert root2 == rcol, rootid
colitems = rcol.perform_collect([rcol.nodeid], genitems=False)
assert len(colitems) == 1
assert colitems[0].fspath == p
def test_collect_protocol_single_function(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
id = "::".join([p.basename, "test_func"])
items, hookrec = testdir.inline_genitems(id)
item, = items
assert item.name == "test_func"
newid = item.nodeid
assert newid == id
py.std.pprint.pprint(hookrec.calls)
topdir = testdir.tmpdir # noqa
hookrec.assert_contains([
("pytest_collectstart", "collector.fspath == topdir"),
("pytest_make_collect_report", "collector.fspath == topdir"),
("pytest_collectstart", "collector.fspath == p"),
("pytest_make_collect_report", "collector.fspath == p"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
("pytest_collectreport", "report.nodeid == ''")
])
def test_collect_protocol_method(self, testdir):
p = testdir.makepyfile("""
class TestClass:
def test_method(self):
pass
""")
normid = p.basename + "::TestClass::()::test_method"
for id in [p.basename,
p.basename + "::TestClass",
p.basename + "::TestClass::()",
normid,
]:
items, hookrec = testdir.inline_genitems(id)
assert len(items) == 1
assert items[0].name == "test_method"
newid = items[0].nodeid
assert newid == normid
def test_collect_custom_nodes_multi_id(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
testdir.makeconftest("""
import pytest
class SpecialItem(pytest.Item):
def runtest(self):
return # ok
class SpecialFile(pytest.File):
def collect(self):
return [SpecialItem(name="check", parent=self)]
def pytest_collect_file(path, parent):
if path.basename == %r:
return SpecialFile(fspath=path, parent=parent)
""" % p.basename)
id = p.basename
items, hookrec = testdir.inline_genitems(id)
py.std.pprint.pprint(hookrec.calls)
assert len(items) == 2
hookrec.assert_contains([
("pytest_collectstart",
"collector.fspath == collector.session.fspath"),
("pytest_collectstart",
"collector.__class__.__name__ == 'SpecialFile'"),
("pytest_collectstart",
"collector.__class__.__name__ == 'Module'"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
#("pytest_collectreport",
# "report.fspath == %r" % str(rcol.fspath)),
])
def test_collect_subdir_event_ordering(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
aaa = testdir.mkpydir("aaa")
test_aaa = aaa.join("test_aaa.py")
p.move(test_aaa)
items, hookrec = testdir.inline_genitems()
assert len(items) == 1
py.std.pprint.pprint(hookrec.calls)
hookrec.assert_contains([
("pytest_collectstart", "collector.fspath == test_aaa"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport",
"report.nodeid.startswith('aaa/test_aaa.py')"),
])
def test_collect_two_commandline_args(self, testdir):
p = testdir.makepyfile("def test_func(): pass")
aaa = testdir.mkpydir("aaa")
bbb = testdir.mkpydir("bbb")
test_aaa = aaa.join("test_aaa.py")
p.copy(test_aaa)
test_bbb = bbb.join("test_bbb.py")
p.move(test_bbb)
id = "."
items, hookrec = testdir.inline_genitems(id)
assert len(items) == 2
py.std.pprint.pprint(hookrec.calls)
hookrec.assert_contains([
("pytest_collectstart", "collector.fspath == test_aaa"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),
("pytest_collectstart", "collector.fspath == test_bbb"),
("pytest_pycollect_makeitem", "name == 'test_func'"),
("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),
])
def test_serialization_byid(self, testdir):
testdir.makepyfile("def test_func(): pass")
items, hookrec = testdir.inline_genitems()
assert len(items) == 1
item, = items
items2, hookrec = testdir.inline_genitems(item.nodeid)
item2, = items2
assert item2.name == item.name
assert item2.fspath == item.fspath
def test_find_byid_without_instance_parents(self, testdir):
p = testdir.makepyfile("""
class TestClass:
def test_method(self):
pass
""")
arg = p.basename + ("::TestClass::test_method")
items, hookrec = testdir.inline_genitems(arg)
assert len(items) == 1
item, = items
assert item.nodeid.endswith("TestClass::()::test_method")
class Test_getinitialnodes:
def test_global_file(self, testdir, tmpdir):
x = tmpdir.ensure("x.py")
config = testdir.parseconfigure(x)
col = testdir.getnode(config, x)
assert isinstance(col, pytest.Module)
assert col.name == 'x.py'
assert col.parent.name == testdir.tmpdir.basename
assert col.parent.parent is None
for col in col.listchain():
assert col.config is config
def test_pkgfile(self, testdir):
tmpdir = testdir.tmpdir
subdir = tmpdir.join("subdir")
x = subdir.ensure("x.py")
subdir.ensure("__init__.py")
config = testdir.parseconfigure(x)
col = testdir.getnode(config, x)
assert isinstance(col, pytest.Module)
assert col.name == 'x.py'
assert col.parent.parent is None
for col in col.listchain():
assert col.config is config
class Test_genitems:
def test_check_collect_hashes(self, testdir):
p = testdir.makepyfile("""
def test_1():
pass
def test_2():
pass
""")
p.copy(p.dirpath(p.purebasename + "2" + ".py"))
items, reprec = testdir.inline_genitems(p.dirpath())
assert len(items) == 4
for numi, i in enumerate(items):
for numj, j in enumerate(items):
if numj != numi:
assert hash(i) != hash(j)
assert i != j
def test_example_items1(self, testdir):
p = testdir.makepyfile('''
def testone():
pass
class TestX:
def testmethod_one(self):
pass
class TestY(TestX):
pass
''')
items, reprec = testdir.inline_genitems(p)
assert len(items) == 3
assert items[0].name == 'testone'
assert items[1].name == 'testmethod_one'
assert items[2].name == 'testmethod_one'
# let's also test getmodpath here
assert items[0].getmodpath() == "testone"
assert items[1].getmodpath() == "TestX.testmethod_one"
assert items[2].getmodpath() == "TestY.testmethod_one"
s = items[0].getmodpath(stopatmodule=False)
assert s.endswith("test_example_items1.testone")
print(s)
def test_class_and_functions_discovery_using_glob(self, testdir):
"""
tests that python_classes and python_functions config options work
as prefixes and glob-like patterns (issue #600).
"""
testdir.makeini("""
[pytest]
python_classes = *Suite Test
python_functions = *_test test
""")
p = testdir.makepyfile('''
class MyTestSuite:
def x_test(self):
pass
class TestCase:
def test_y(self):
pass
''')
items, reprec = testdir.inline_genitems(p)
ids = [x.getmodpath() for x in items]
assert ids == ['MyTestSuite.x_test', 'TestCase.test_y']
def test_matchnodes_two_collections_same_file(testdir):
testdir.makeconftest("""
import pytest
def pytest_configure(config):
config.pluginmanager.register(Plugin2())
class Plugin2:
def pytest_collect_file(self, path, parent):
if path.ext == ".abc":
return MyFile2(path, parent)
def pytest_collect_file(path, parent):
if path.ext == ".abc":
return MyFile1(path, parent)
class MyFile1(pytest.Item, pytest.File):
def runtest(self):
pass
class MyFile2(pytest.File):
def collect(self):
return [Item2("hello", parent=self)]
class Item2(pytest.Item):
def runtest(self):
pass
""")
p = testdir.makefile(".abc", "")
result = testdir.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines([
"*2 passed*",
])
res = testdir.runpytest("%s::hello" % p.basename)
res.stdout.fnmatch_lines([
"*1 passed*",
])
class TestNodekeywords:
def test_no_under(self, testdir):
modcol = testdir.getmodulecol("""
def test_pass(): pass
def test_fail(): assert 0
""")
l = list(modcol.keywords)
assert modcol.name in l
for x in l:
assert not x.startswith("_")
assert modcol.name in repr(modcol.keywords)
def test_issue345(self, testdir):
testdir.makepyfile("""
def test_should_not_be_selected():
assert False, 'I should not have been selected to run'
def test___repr__():
pass
""")
reprec = testdir.inline_run("-k repr")
reprec.assertoutcome(passed=1, failed=0)
| mpl-2.0 |
jleonhard/angular2-webpack-jquery-bootstrap | node_modules/@types/lodash/upperCase.d.ts | 57 | import { upperCase } from "./index";
export = upperCase;
| mit |
andyinabox/cdnjs | ajax/libs/mojio-js/3.5.0/mojio-js.js | 87074 | // version 3.5.0
!function(e) {
if ("object" == typeof exports) module.exports = e(); else if ("function" == typeof define && define.amd) define(e); else {
var o;
"undefined" != typeof window ? o = window : "undefined" != typeof global ? o = global : "undefined" != typeof self && (o = self),
o.MojioClient = e();
}
}(function() {
var define, module, exports;
return function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
throw new Error("Cannot find module '" + o + "'");
}
var f = n[o] = {
exports: {}
};
t[o][0].call(f.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e);
}, f, f.exports, e, t, n, r);
}
return n[o].exports;
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
}({
1: [ function(_dereq_, module, exports) {
var formurlencoded = (typeof module === "object" ? module : {}).exports = {
encode: function(data, options) {
function getNestValsArrAsStr(arr) {
return arr.filter(function(e) {
return typeof e === "string" && e.length;
}).join("&");
}
function getKeys(obj) {
var keys = Object.keys(obj);
return options && options.sorted ? keys.sort() : keys;
}
function getObjNestVals(name, obj) {
var objKeyStr = ":name[:prop]";
return getNestValsArrAsStr(getKeys(obj).map(function(key) {
return getNestVals(objKeyStr.replace(/:name/, name).replace(/:prop/, key), obj[key]);
}));
}
function getArrNestVals(name, arr) {
var arrKeyStr = ":name[]";
return getNestValsArrAsStr(arr.map(function(elem) {
return getNestVals(arrKeyStr.replace(/:name/, name), elem);
}));
}
function getNestVals(name, value) {
var whitespaceRe = /%20/g, type = typeof value, f = null;
if (type === "string") {
f = encodeURIComponent(name) + "=" + formEncodeString(value);
} else if (type === "number") {
f = encodeURIComponent(name) + "=" + encodeURIComponent(value).replace(whitespaceRe, "+");
} else if (type === "boolean") {
f = encodeURIComponent(name) + "=" + value;
} else if (Array.isArray(value)) {
f = getArrNestVals(name, value);
} else if (type === "object") {
f = getObjNestVals(name, value);
}
return f;
}
function manuallyEncodeChar(ch) {
return "%" + ("0" + ch.charCodeAt(0).toString(16)).slice(-2).toUpperCase();
}
function formEncodeString(value) {
return value.replace(/[^ !'()~\*]*/g, encodeURIComponent).replace(/ /g, "+").replace(/[!'()~\*]/g, manuallyEncodeChar);
}
return getNestValsArrAsStr(getKeys(data).map(function(key) {
return getNestVals(key, data[key]);
}));
}
};
}, {} ],
2: [ function(_dereq_, module, exports) {
module.exports = _dereq_("./form-urlencoded");
}, {
"./form-urlencoded": 1
} ],
3: [ function(_dereq_, module, exports) {
(function() {
var HttpBrowserWrapper;
module.exports = HttpBrowserWrapper = function() {
function HttpBrowserWrapper(requester) {
if (requester == null) {
requester = null;
}
if (requester != null) {
this.requester = requester;
}
}
HttpBrowserWrapper.prototype.request = function(params, callback) {
var k, url, v, xmlhttp, _ref;
if (params.method == null) {
params.method = "GET";
}
if (params.host == null && params.hostname != null) {
params.host = params.hostname;
}
if (!(params.scheme != null || (typeof window === "undefined" || window === null))) {
params.scheme = window.location.protocol.split(":")[0];
}
if (!params.scheme || params.scheme === "file") {
params.scheme = "https";
}
if (params.data == null) {
params.data = {};
}
if (params.body != null) {
params.data = params.body;
}
if (params.headers == null) {
params.headers = {};
}
url = params.scheme + "://" + params.host + ":" + params.port + params.path;
if (params.method === "GET" && params.data != null && params.data.length > 0) {
url += "?" + Object.keys(params.data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(params.data[k]);
}).join("&");
}
if (typeof XMLHttpRequest !== "undefined" && XMLHttpRequest !== null) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = this.requester;
}
xmlhttp.open(params.method, url, true);
_ref = params.headers;
for (k in _ref) {
v = _ref[k];
xmlhttp.setRequestHeader(k, v);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status >= 200 && xmlhttp.status <= 299) {
return callback(null, JSON.parse(xmlhttp.responseText));
} else {
return callback(xmlhttp.statusText, null);
}
}
};
if (params.method === "GET") {
return xmlhttp.send();
} else {
return xmlhttp.send(params.data);
}
};
return HttpBrowserWrapper;
}();
}).call(this);
}, {} ],
4: [ function(_dereq_, module, exports) {
(function() {
var FormUrlencoded, Http, MojioClient, SignalR;
Http = _dereq_("./HttpBrowserWrapper");
SignalR = _dereq_("./SignalRBrowserWrapper");
FormUrlencoded = _dereq_("form-urlencoded");
module.exports = MojioClient = function() {
var App, Event, Login, Mojio, Observer, Product, Subscription, Trip, User, Vehicle, defaults, mojio_models;
defaults = {
hostname: "api.moj.io",
port: "443",
version: "v1",
scheme: "https",
signalr_scheme: "https",
signalr_port: "443",
signalr_hub: "ObserverHub",
live: true
};
function MojioClient(options) {
var _base, _base1, _base2, _base3, _base4, _base5, _base6, _base7;
this.options = options;
if (this.options == null) {
this.options = {
hostname: this.defaults.hostname,
port: this.defaults.port,
version: this.defaults.version,
scheme: this.defaults.scheme,
live: this.defaults.live
};
}
if ((_base = this.options).hostname == null) {
_base.hostname = defaults.hostname;
}
if ((_base1 = this.options).port == null) {
_base1.port = defaults.port;
}
if ((_base2 = this.options).version == null) {
_base2.version = defaults.version;
}
if ((_base3 = this.options).scheme == null) {
_base3.scheme = defaults.scheme;
}
if ((_base4 = this.options).signalr_port == null) {
_base4.signalr_port = defaults.signalr_port;
}
if ((_base5 = this.options).signalr_scheme == null) {
_base5.signalr_scheme = defaults.signalr_scheme;
}
if ((_base6 = this.options).signalr_hub == null) {
_base6.signalr_hub = defaults.signalr_hub;
}
this.options.application = this.options.application;
this.options.secret = this.options.secret;
this.options.observerTransport = "SingalR";
this.conn = null;
this.hub = null;
this.connStatus = null;
this.auth_token = null;
if ((_base7 = this.options).tokenRequester == null) {
_base7.tokenRequester = function() {
return document.location.hash.match(/access_token=([0-9a-f-]{36})/);
};
}
this.signalr = new SignalR(this.options.signalr_scheme + "://" + this.options.hostname + ":" + this.options.signalr_port + "/v1/signalr", [ this.options.signalr_hub ], $);
}
MojioClient.prototype.getResults = function(type, results) {
var arrlength, objects, result, _i, _j, _len, _len1, _ref;
objects = [];
if (results instanceof Array) {
arrlength = results.length;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
objects.push(new type(result));
}
} else if (results.Data instanceof Array) {
arrlength = results.Data.length;
_ref = results.Data;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
result = _ref[_j];
objects.push(new type(result));
}
} else if (result.Data !== null) {
objects.push(new type(result.Data));
} else {
objects.push(new type(result));
}
return objects;
};
MojioClient._makeParameters = function(params) {
var property, query, value;
if (params.length === 0) {
"";
}
query = "?";
for (property in params) {
value = params[property];
query += "" + encodeURIComponent(property) + "=" + encodeURIComponent(value) + "&";
}
return query.slice(0, -1);
};
MojioClient.prototype.getPath = function(resource, id, action, key) {
if (key && id && action && id !== "" && action !== "") {
return "/" + encodeURIComponent(resource) + "/" + encodeURIComponent(id) + "/" + encodeURIComponent(action) + "/" + encodeURIComponent(key);
} else if (id && action && id !== "" && action !== "") {
return "/" + encodeURIComponent(resource) + "/" + encodeURIComponent(id) + "/" + encodeURIComponent(action);
} else if (id && id !== "") {
return "/" + encodeURIComponent(resource) + "/" + encodeURIComponent(id);
} else if (action && action !== "") {
return "/" + encodeURIComponent(resource) + "/" + encodeURIComponent(action);
}
return "/" + encodeURIComponent(resource);
};
MojioClient.prototype.dataByMethod = function(data, method) {
switch (method.toUpperCase()) {
case "POST" || "PUT":
return this.stringify(data);
default:
return data;
}
};
MojioClient.prototype.stringify = function(data) {
return JSON.stringify(data);
};
MojioClient.prototype.request = function(request, callback, isOauth) {
var http, parts;
if (isOauth == null) {
isOauth = false;
}
parts = {
hostname: this.options.hostname,
host: this.options.hostname,
port: this.options.port,
scheme: this.options.scheme,
path: isOauth ? "" : "/" + this.options.version,
method: request.method,
withCredentials: false
};
parts.path = parts.path + this.getPath(request.resource, request.id, request.action, request.key);
if (request.parameters != null && Object.keys(request.parameters).length > 0) {
parts.path += MojioClient._makeParameters(request.parameters);
}
parts.headers = {};
if (this.getTokenId() != null) {
parts.headers["MojioAPIToken"] = this.getTokenId();
}
if (request.headers != null) {
parts.headers += request.headers;
}
parts.headers["Content-Type"] = "application/json";
if (request.body != null) {
if (isOauth) {
parts.body = FormUrlencoded.encode(request.body);
} else {
parts.body = request.body;
}
}
http = new Http();
return http.request(parts, callback);
};
MojioClient.prototype.login_resource = "Login";
MojioClient.prototype.authorize = function(redirect_url, scope) {
var parts, url;
if (scope == null) {
scope = "full";
}
parts = {
hostname: this.options.hostname,
host: this.options.hostname,
port: this.options.port,
scheme: this.options.scheme,
path: this.options.live ? "/OAuth2/authorize" : "/OAuth2Sandbox/authorize",
method: "Get",
withCredentials: false
};
parts.path += "?response_type=token";
parts.path += "&client_id=" + this.options.application;
parts.path += "&redirect_uri=" + redirect_url;
parts.path += "&scope=" + scope;
parts.headers = {};
if (this.getTokenId() != null) {
parts.headers["MojioAPIToken"] = this.getTokenId();
}
parts.headers["Content-Type"] = "application/json";
url = parts.scheme + "://" + parts.host + ":" + parts.port + parts.path;
return window.location = url;
};
MojioClient.prototype.token = function(callback) {
var match, token;
this.user = null;
match = this.options.tokenRequester();
token = !!match && match[1];
if (!token) {
return callback("token for authorization not found.", null);
} else {
return this.request({
method: "GET",
resource: this.login_resource,
id: token
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
_this.auth_token = result;
return callback(null, _this.auth_token);
}
};
}(this));
}
};
MojioClient.prototype.unauthorize = function(redirect_url) {
var parts, url;
parts = {
hostname: this.options.hostname,
host: this.options.hostname,
port: this.options.port,
scheme: this.options.scheme,
path: "/account/logout",
method: "Get",
withCredentials: false
};
parts.path += "?Guid=" + this.getTokenId();
parts.path += "&client_id=" + this.options.application;
parts.path += "&redirect_uri=" + redirect_url;
parts.headers = {};
if (this.getTokenId() != null) {
parts.headers["MojioAPIToken"] = this.getTokenId();
}
parts.headers["Content-Type"] = "application/json";
url = parts.scheme + "://" + parts.host + ":" + parts.port + parts.path;
return window.location = url;
};
MojioClient.prototype._login = function(username, password, callback) {
return this.request({
method: "POST",
resource: this.options.live ? "/OAuth2/token" : "/OAuth2Sandbox/token",
body: {
username: username,
password: password,
client_id: this.options.application,
client_secret: this.options.secret,
grant_type: "password"
}
}, callback, true);
};
MojioClient.prototype.login = function(username, password, callback) {
return this._login(username, password, function(_this) {
return function(error, result) {
if (result != null) {
_this.auth_token = result.access_token ? result.access_token : result;
}
return callback(error, result);
};
}(this));
};
MojioClient.prototype._logout = function(callback) {
return this.request({
method: "DELETE",
resource: this.login_resource,
id: typeof mojio_token !== "undefined" && mojio_token !== null ? mojio_token : this.getTokenId()
}, callback);
};
MojioClient.prototype.logout = function(callback) {
return this._logout(function(_this) {
return function(error, result) {
_this.auth_token = null;
return callback(error, result);
};
}(this));
};
mojio_models = {};
App = _dereq_("../models/App");
mojio_models["App"] = App;
Login = _dereq_("../models/Login");
mojio_models["Login"] = Login;
Mojio = _dereq_("../models/Mojio");
mojio_models["Mojio"] = Mojio;
Trip = _dereq_("../models/Trip");
mojio_models["Trip"] = Trip;
User = _dereq_("../models/User");
mojio_models["User"] = User;
Vehicle = _dereq_("../models/Vehicle");
mojio_models["Vehicle"] = Vehicle;
Product = _dereq_("../models/Product");
mojio_models["Product"] = Product;
Subscription = _dereq_("../models/Subscription");
mojio_models["Subscription"] = Subscription;
Event = _dereq_("../models/Event");
mojio_models["Event"] = Event;
Observer = _dereq_("../models/Observer");
mojio_models["Observer"] = Observer;
MojioClient.prototype.model = function(type, json) {
var data, object, _i, _len, _ref;
if (json == null) {
json = null;
}
if (json === null) {
return mojio_models[type];
} else if (json.Data != null && json.Data instanceof Array) {
object = json;
object.Objects = new Array();
_ref = json.Data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
object.Objects.push(new mojio_models[type](data));
}
} else if (json.Data != null) {
object = new mojio_models[type](json.Data);
} else {
object = new mojio_models[type](json);
}
object._client = this;
return object;
};
MojioClient.prototype.query = function(model, parameters, callback) {
var property, query_criteria, value, _ref;
if (parameters instanceof Object) {
if (parameters.criteria instanceof Object) {
query_criteria = "";
_ref = parameters.criteria;
for (property in _ref) {
value = _ref[property];
query_criteria += "" + property + "=" + value + ";";
}
parameters.criteria = query_criteria;
}
return this.request({
method: "GET",
resource: model.resource(),
parameters: parameters
}, function(_this) {
return function(error, result) {
return callback(error, _this.model(model.model(), result));
};
}(this));
} else if (typeof parameters === "string") {
return this.request({
method: "GET",
resource: model.resource(),
parameters: {
id: parameters
}
}, function(_this) {
return function(error, result) {
return callback(error, _this.model(model.model(), result));
};
}(this));
} else {
return callback("criteria given is not in understood format, string or object.", null);
}
};
MojioClient.prototype.get = function(model, criteria, callback) {
return this.query(model, criteria, callback);
};
MojioClient.prototype.save = function(model, callback) {
return this.request({
method: "PUT",
resource: model.resource(),
body: model.stringify(),
parameters: {
id: model._id
}
}, callback);
};
MojioClient.prototype.put = function(model, callback) {
return this.save(model, callback);
};
MojioClient.prototype.create = function(model, callback) {
return this.request({
method: "POST",
resource: model.resource(),
body: model.stringify()
}, callback);
};
MojioClient.prototype.post = function(model, callback) {
return this.create(model, callback);
};
MojioClient.prototype["delete"] = function(model, callback) {
return this.request({
method: "DELETE",
resource: model.resource(),
parameters: {
id: model._id
}
}, callback);
};
MojioClient.prototype._schema = function(callback) {
return this.request({
method: "GET",
resource: "Schema"
}, callback);
};
MojioClient.prototype.schema = function(callback) {
return this._schema(function(_this) {
return function(error, result) {
return callback(error, result);
};
}(this));
};
MojioClient.prototype.watch = function(observer, observer_callback, callback) {
return this.request({
method: "POST",
resource: Observer.resource(),
body: observer.stringify()
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
observer = new Observer(result);
_this.signalr.subscribe(_this.options.signalr_hub, "Subscribe", observer.id(), observer.Subject, observer_callback, function(error, result) {
return callback(null, observer);
});
return observer;
}
};
}(this));
};
MojioClient.prototype.ignore = function(observer, observer_callback, callback) {
if (!observer) {
callback("Observer required.");
}
if (observer["subject"] != null) {
if (observer.parent === null) {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), observer.subject.id(), observer_callback, callback);
} else {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), observer.subject.model(), observer_callback, callback);
}
} else {
if (observer.parent === null) {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), observer.SubjectId, observer_callback, callback);
} else {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), observer.Subject, observer_callback, callback);
}
}
};
MojioClient.prototype.observe = function(subject, parent, observer_callback, callback) {
var observer;
if (parent == null) {
parent = null;
}
if (parent === null) {
observer = new Observer({
ObserverType: "Generic",
Status: "Approved",
Name: "Test" + Math.random(),
Subject: subject.model(),
SubjectId: subject.id(),
Transports: "SignalR"
});
return this.request({
method: "PUT",
resource: Observer.resource(),
body: observer.stringify()
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
observer = new Observer(result);
return _this.signalr.subscribe(_this.options.signalr_hub, "Subscribe", observer.id(), observer.SubjectId, observer_callback, function(error, result) {
return callback(null, observer);
});
}
};
}(this));
} else {
observer = new Observer({
ObserverType: "Generic",
Status: "Approved",
Name: "Test" + Math.random(),
Subject: subject.model(),
Parent: parent.model(),
ParentId: parent.id(),
Transports: "SignalR"
});
return this.request({
method: "PUT",
resource: Observer.resource(),
body: observer.stringify()
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
observer = new Observer(result);
return _this.signalr.subscribe(_this.options.signalr_hub, "Subscribe", observer.id(), subject.model(), observer_callback, function(error, result) {
return callback(null, observer);
});
}
};
}(this));
}
};
MojioClient.prototype.unobserve = function(observer, subject, parent, observer_callback, callback) {
if (!observer || subject == null) {
return callback("Observer and subject required.");
} else if (parent === null) {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), subject.id(), observer_callback, callback);
} else {
return this.signalr.unsubscribe(this.options.signalr_hub, "Unsubscribe", observer.id(), subject.model(), observer_callback, callback);
}
};
MojioClient.prototype.store = function(model, key, value, callback) {
if (!model || !model._id) {
return callback("Storage requires an object with a valid id.");
} else {
return this.request({
method: "PUT",
resource: model.resource(),
id: model.id(),
action: "store",
key: key,
body: JSON.stringify(value)
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
return callback(null, result);
}
};
}(this));
}
};
MojioClient.prototype.storage = function(model, key, callback) {
if (!model || !model._id) {
return callback("Get of storage requires an object with a valid id.");
} else {
return this.request({
method: "GET",
resource: model.resource(),
id: model.id(),
action: "store",
key: key
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
return callback(null, result);
}
};
}(this));
}
};
MojioClient.prototype.unstore = function(model, key, callback) {
if (!model || !model._id) {
return callback("Storage requires an object with a valid id.");
} else {
return this.request({
method: "DELETE",
resource: model.resource(),
id: model.id(),
action: "store",
key: key
}, function(_this) {
return function(error, result) {
if (error) {
return callback(error, null);
} else {
return callback(null, result);
}
};
}(this));
}
};
MojioClient.prototype.getTokenId = function() {
if (this.auth_token != null && this.auth_token._id != null) {
return this.auth_token._id;
}
if (this.auth_token != null) {
return this.auth_token;
}
return null;
};
MojioClient.prototype.getUserId = function() {
if (this.auth_token != null && this.auth_token.UserId) {
return this.auth_token.UserId;
}
return null;
};
MojioClient.prototype.isLoggedIn = function() {
return this.getUserId() !== null || typeof this.auth_token === "string";
};
MojioClient.prototype.getCurrentUser = function(callback) {
if (this.user != null) {
callback(null, this.user);
} else if (this.isLoggedIn()) {
this.get(Login, this.auth_token, function(_this) {
return function(error, result) {
if (error != null) {
return callback(error, null);
} else if (result.UserId != null) {
return _this.get(User, result.UserId, function(error, result) {
if (error != null) {
return callback(error, null);
} else {
_this.user = result;
return callback(null, _this.user);
}
});
} else {
return callback("User not found", null);
}
};
}(this));
} else {
callback("User not found", null);
return false;
}
return true;
};
return MojioClient;
}();
}).call(this);
}, {
"../models/App": 6,
"../models/Event": 7,
"../models/Login": 8,
"../models/Mojio": 9,
"../models/Observer": 11,
"../models/Product": 12,
"../models/Subscription": 13,
"../models/Trip": 14,
"../models/User": 15,
"../models/Vehicle": 16,
"./HttpBrowserWrapper": 3,
"./SignalRBrowserWrapper": 5,
"form-urlencoded": 2
} ],
5: [ function(_dereq_, module, exports) {
(function() {
var SignalRBrowserWrapper, __bind = function(fn, me) {
return function() {
return fn.apply(me, arguments);
};
};
module.exports = SignalRBrowserWrapper = function() {
SignalRBrowserWrapper.prototype.observer_callbacks = {};
SignalRBrowserWrapper.prototype.observer_registry = function(entity) {
var callback, _i, _j, _len, _len1, _ref, _ref1, _results, _results1;
if (this.observer_callbacks[entity._id]) {
_ref = this.observer_callbacks[entity._id];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
_results.push(callback(entity));
}
return _results;
} else if (this.observer_callbacks[entity.Type]) {
_ref1 = this.observer_callbacks[entity.Type];
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
callback = _ref1[_j];
_results1.push(callback(entity));
}
return _results1;
}
};
function SignalRBrowserWrapper(url, hubNames, jquery) {
this.observer_registry = __bind(this.observer_registry, this);
this.$ = jquery;
this.url = url;
this.hubs = {};
this.signalr = null;
this.connectionStatus = false;
}
SignalRBrowserWrapper.prototype.getHub = function(which, callback) {
if (this.hubs[which]) {
return callback(null, this.hubs[which]);
} else {
if (this.signalr == null) {
this.signalr = this.$.hubConnection(this.url, {
useDefaultPath: false
});
this.signalr.error(function(error) {
console.log("Connection error" + error);
return callback(error, null);
});
}
this.hubs[which] = this.signalr.createHubProxy(which);
this.hubs[which].on("error", function(data) {
return console.log("Hub '" + which + "' has error" + data);
});
this.hubs[which].on("UpdateEntity", this.observer_registry);
if (this.hubs[which].connection.state !== 1) {
if (!this.connectionStatus) {
return this.signalr.start().done(function(_this) {
return function() {
_this.connectionStatus = true;
return _this.hubs[which].connection.start().done(function() {
return callback(null, _this.hubs[which]);
});
};
}(this));
} else {
return this.hubs[which].connection.start().done(function(_this) {
return function() {
return callback(null, _this.hubs[which]);
};
}(this));
}
} else {
return callback(null, this.hubs[which]);
}
}
};
SignalRBrowserWrapper.prototype.setCallback = function(id, futureCallback) {
if (this.observer_callbacks[id] == null) {
this.observer_callbacks[id] = [];
}
this.observer_callbacks[id].push(futureCallback);
};
SignalRBrowserWrapper.prototype.removeCallback = function(id, pastCallback) {
var callback, temp, _i, _len, _ref;
if (pastCallback === null) {
this.observer_callbacks[id] = [];
} else {
temp = [];
_ref = this.observer_callbacks[id];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
if (callback !== pastCallback) {
temp.push(callback);
}
}
this.observer_callbacks[id] = temp;
}
};
SignalRBrowserWrapper.prototype.subscribe = function(hubName, method, observerId, subject, futureCallback, callback) {
this.setCallback(subject, futureCallback);
return this.getHub(hubName, function(error, hub) {
if (error != null) {
return callback(error, null);
} else {
if (hub != null) {
hub.invoke(method, observerId);
}
return callback(null, hub);
}
});
};
SignalRBrowserWrapper.prototype.unsubscribe = function(hubName, method, observerId, subject, pastCallback, callback) {
this.removeCallback(subject, pastCallback);
if (this.observer_callbacks[subject].length === 0) {
return this.getHub(hubName, function(error, hub) {
if (error != null) {
return callback(error, null);
} else {
if (hub != null) {
hub.invoke(method, observerId);
}
return callback(null, hub);
}
});
} else {
return callback(null, true);
}
};
return SignalRBrowserWrapper;
}();
}).call(this);
}, {} ],
6: [ function(_dereq_, module, exports) {
(function() {
var App, MojioModel, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = App = function(_super) {
__extends(App, _super);
App.prototype._schema = {
Type: "String",
Name: "String",
Description: "String",
CreationDate: "String",
Downloads: "Integer",
RedirectUris: "String",
ApplicationType: "String",
_id: "String",
_deleted: "Boolean"
};
App.prototype._resource = "Apps";
App.prototype._model = "App";
function App(json) {
App.__super__.constructor.call(this, json);
}
App._resource = "Apps";
App._model = "App";
App.resource = function() {
return App._resource;
};
App.model = function() {
return App._model;
};
return App;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
7: [ function(_dereq_, module, exports) {
(function() {
var Event, MojioModel, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Event = function(_super) {
__extends(Event, _super);
Event.prototype._schema = {
Type: "Integer",
MojioId: "String",
VehicleId: "String",
OwnerId: "String",
EventType: "Integer",
Time: "String",
Location: {
Lat: "Float",
Lng: "Float",
FromLockedGPS: "Boolean",
Dilution: "Float"
},
TimeIsApprox: "Boolean",
BatteryVoltage: "Float",
ConnectionLost: "Boolean",
_id: "String",
_deleted: "Boolean",
Accelerometer: {
X: "Float",
Y: "Float",
Z: "Float"
},
TripId: "String",
Altitude: "Float",
Heading: "Float",
Distance: "Float",
FuelLevel: "Float",
FuelEfficiency: "Float",
Speed: "Float",
Acceleration: "Float",
Deceleration: "Float",
Odometer: "Float",
RPM: "Integer",
DTCs: "Array",
MilStatus: "Boolean",
Force: "Float",
MaxSpeed: "Float",
AverageSpeed: "Float",
MovingTime: "Float",
IdleTime: "Float",
StopTime: "Float",
MaxRPM: "Float",
EventTypes: "Array",
Timing: "Integer",
Name: "String",
ObserverType: "Integer",
AppId: "String",
Parent: "String",
ParentId: "String",
Subject: "String",
SubjectId: "String",
Transports: "Integer",
Status: "Integer",
Tokens: "Array",
TimeWindow: "String",
BroadcastOnlyRecent: "Boolean",
Throttle: "String",
NextAllowedBroadcast: "String"
};
Event.prototype._resource = "Events";
Event.prototype._model = "Event";
function Event(json) {
Event.__super__.constructor.call(this, json);
}
Event._resource = "Events";
Event._model = "Event";
Event.resource = function() {
return Event._resource;
};
Event.model = function() {
return Event._model;
};
return Event;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
8: [ function(_dereq_, module, exports) {
(function() {
var Login, MojioModel, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Login = function(_super) {
__extends(Login, _super);
Login.prototype._schema = {
Type: "String",
AppId: "String",
UserId: "String",
ValidUntil: "String",
Scopes: "String",
Sandboxed: "Boolean",
Depricated: "Boolean",
_id: "String",
_deleted: "Boolean"
};
Login.prototype._resource = "Login";
Login.prototype._model = "Login";
function Login(json) {
Login.__super__.constructor.call(this, json);
}
Login._resource = "Login";
Login._model = "Login";
Login.resource = function() {
return Login._resource;
};
Login.model = function() {
return Login._model;
};
return Login;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
9: [ function(_dereq_, module, exports) {
(function() {
var Mojio, MojioModel, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Mojio = function(_super) {
__extends(Mojio, _super);
Mojio.prototype._schema = {
Type: "Integer",
OwnerId: "String",
Name: "String",
Imei: "String",
LastContactTime: "String",
VehicleId: "String",
_id: "String",
_deleted: "Boolean"
};
Mojio.prototype._resource = "Mojios";
Mojio.prototype._model = "Mojio";
function Mojio(json) {
Mojio.__super__.constructor.call(this, json);
}
Mojio._resource = "Mojios";
Mojio._model = "Mojio";
Mojio.resource = function() {
return Mojio._resource;
};
Mojio.model = function() {
return Mojio._model;
};
return Mojio;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
10: [ function(_dereq_, module, exports) {
(function() {
var MojioModel;
module.exports = MojioModel = function() {
MojioModel._resource = "Schema";
MojioModel._model = "Model";
function MojioModel(json) {
this._client = null;
this.validate(json);
}
MojioModel.prototype.setField = function(field, value) {
this[field] = value;
return this[field];
};
MojioModel.prototype.getField = function(field) {
return this[field];
};
MojioModel.prototype.validate = function(json) {
var field, value, _results;
_results = [];
for (field in json) {
value = json[field];
_results.push(this.setField(field, value));
}
return _results;
};
MojioModel.prototype.stringify = function() {
return JSON.stringify(this, this.replacer);
};
MojioModel.prototype.replacer = function(key, value) {
if (key === "_client" || key === "_schema" || key === "_resource" || key === "_model") {
return void 0;
} else {
return value;
}
};
MojioModel.prototype.query = function(criteria, callback) {
var property, query_criteria, value;
if (this._client === null) {
callback("No authorization set for model, use authorize(), passing in a mojio _client where login() has been called successfully.", null);
return;
}
if (criteria instanceof Object) {
if (criteria.criteria == null) {
query_criteria = "";
for (property in criteria) {
value = criteria[property];
query_criteria += "" + property + "=" + value + ";";
}
criteria = {
criteria: query_criteria
};
}
return this._client.request({
method: "GET",
resource: this.resource(),
parameters: criteria
}, function(_this) {
return function(error, result) {
return callback(error, _this._client.model(_this.model(), result));
};
}(this));
} else if (typeof criteria === "string") {
return this._client.request({
method: "GET",
resource: this.resource(),
parameters: {
id: criteria
}
}, function(_this) {
return function(error, result) {
return callback(error, _this._client.model(_this.model(), result));
};
}(this));
} else {
return callback("criteria given is not in understood format, string or object.", null);
}
};
MojioModel.prototype.get = function(criteria, callback) {
return this.query(criteria, callback);
};
MojioModel.prototype.create = function(callback) {
if (this._client === null) {
callback("No authorization set for model, use authorize(), passing in a mojio _client where login() has been called successfully.", null);
return;
}
return this._client.request({
method: "POST",
resource: this.resource(),
body: this.stringify()
}, callback);
};
MojioModel.prototype.post = function(callback) {
return this.create(callback);
};
MojioModel.prototype.save = function(callback) {
if (this._client === null) {
callback("No authorization set for model, use authorize(), passing in a mojio _client where login() has been called successfully.", null);
return;
}
return this._client.request({
method: "PUT",
resource: this.resource(),
body: this.stringify(),
parameters: {
id: this._id
}
}, callback);
};
MojioModel.prototype.put = function(callback) {
return this.save(callback);
};
MojioModel.prototype["delete"] = function(callback) {
return this._client.request({
method: "DELETE",
resource: this.resource(),
parameters: {
id: this._id
}
}, callback);
};
MojioModel.prototype.observe = function(parent, observer_callback, callback, options) {
if (parent == null) {
parent = null;
}
if (parent != null) {
return this._client.observe(this.resource, parent, observer_callback, callback, options = {});
} else {
return this._client.observe(this, null, observer_callback, callback, options);
}
};
MojioModel.prototype.unobserve = function(parent, observer_callback, callback) {
if (parent == null) {
parent = null;
}
if (parent != null) {
return this._client.unobserve(this.resource, parent, observer_callback, callback);
} else {
return this._client.unobserve(this, null, observer_callback, callback);
}
};
MojioModel.prototype.store = function(model, key, value, callback) {
return this._client.store(model, key, value, callback);
};
MojioModel.prototype.storage = function(model, key, callback) {
return this._client.storage(model, key, callback);
};
MojioModel.prototype.unstore = function(model, key, callback) {
return this._client.unstore(model, key, callback);
};
MojioModel.prototype.statistic = function(expression, callback) {
return callback(null, true);
};
MojioModel.prototype.resource = function() {
return this._resource;
};
MojioModel.prototype.model = function() {
return this._model;
};
MojioModel.prototype.schema = function() {
return this._schema;
};
MojioModel.prototype.authorization = function(client) {
this._client = client;
return this;
};
MojioModel.prototype.id = function() {
return this._id;
};
MojioModel.prototype.mock = function(type, withid) {
var field, value, _ref;
if (withid == null) {
withid = false;
}
_ref = this.schema();
for (field in _ref) {
value = _ref[field];
if (field === "Type") {
this.setField(field, this.model());
} else if (field === "UserName") {
this.setField(field, "Tester");
} else if (field === "Email") {
this.setField(field, "test@moj.io");
} else if (field === "Password") {
this.setField(field, "Password007!");
} else if (field !== "_id" || withid) {
switch (value) {
case "Integer":
this.setField(field, "0");
break;
case "Boolean":
this.setField(field, false);
break;
case "String":
this.setField(field, "test" + Math.random());
}
}
}
return this;
};
return MojioModel;
}();
}).call(this);
}, {} ],
11: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, Observer, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Observer = function(_super) {
__extends(Observer, _super);
Observer.prototype._schema = {
Type: "String",
Name: "String",
ObserverType: "String",
EventTypes: "Array",
AppId: "String",
OwnerId: "String",
Parent: "String",
ParentId: "String",
Subject: "String",
SubjectId: "String",
Transports: "Integer",
Status: "Integer",
Tokens: "Array",
TimeWindow: "String",
BroadcastOnlyRecent: "Boolean",
Throttle: "String",
NextAllowedBroadcast: "String",
_id: "String",
_deleted: "Boolean"
};
Observer.prototype._resource = "Observers";
Observer.prototype._model = "Observer";
function Observer(json) {
Observer.__super__.constructor.call(this, json);
}
Observer._resource = "Observers";
Observer._model = "Observer";
Observer.resource = function() {
return Observer._resource;
};
Observer.model = function() {
return Observer._model;
};
return Observer;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
12: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, Product, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Product = function(_super) {
__extends(Product, _super);
Product.prototype._schema = {
Type: "String",
AppId: "String",
Name: "String",
Description: "String",
Shipping: "Boolean",
Taxable: "Boolean",
Price: "Float",
Discontinued: "Boolean",
OwnerId: "String",
CreationDate: "String",
_id: "String",
_deleted: "Boolean"
};
Product.prototype._resource = "Products";
Product.prototype._model = "Product";
function Product(json) {
Product.__super__.constructor.call(this, json);
}
Product._resource = "Products";
Product._model = "Product";
Product.resource = function() {
return Product._resource;
};
Product.model = function() {
return Product._model;
};
return Product;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
13: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, Subscription, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Subscription = function(_super) {
__extends(Subscription, _super);
Subscription.prototype._schema = {
Type: "Integer",
ChannelType: "Integer",
ChannelTarget: "String",
AppId: "String",
OwnerId: "String",
Event: "Integer",
EntityType: "Integer",
EntityId: "String",
Interval: "Integer",
LastMessage: "String",
_id: "String",
_deleted: "Boolean"
};
Subscription.prototype._resource = "Subscriptions";
Subscription.prototype._model = "Subscription";
function Subscription(json) {
Subscription.__super__.constructor.call(this, json);
}
Subscription._resource = "Subscriptions";
Subscription._model = "Subscription";
Subscription.resource = function() {
return Subscription._resource;
};
Subscription.model = function() {
return Subscription._model;
};
return Subscription;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
14: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, Trip, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Trip = function(_super) {
__extends(Trip, _super);
Trip.prototype._schema = {
Type: "Integer",
MojioId: "String",
VehicleId: "String",
StartTime: "String",
LastUpdatedTime: "String",
EndTime: "String",
MaxSpeed: "Float",
MaxAcceleration: "Float",
MaxDeceleration: "Float",
MaxRPM: "Integer",
FuelLevel: "Float",
FuelEfficiency: "Float",
Distance: "Float",
MovingTime: "Float",
IdleTime: "Float",
StopTime: "Float",
StartLocation: {
Lat: "Float",
Lng: "Float",
FromLockedGPS: "Boolean",
Dilution: "Float"
},
LastKnownLocation: {
Lat: "Float",
Lng: "Float",
FromLockedGPS: "Boolean",
Dilution: "Float"
},
EndLocation: {
Lat: "Float",
Lng: "Float",
FromLockedGPS: "Boolean",
Dilution: "Float"
},
StartAddress: {
Address1: "String",
Address2: "String",
City: "String",
State: "String",
Zip: "String",
Country: "String"
},
EndAddress: {
Address1: "String",
Address2: "String",
City: "String",
State: "String",
Zip: "String",
Country: "String"
},
ForcefullyEnded: "Boolean",
StartMilage: "Float",
EndMilage: "Float",
StartOdometer: "Float",
_id: "String",
_deleted: "Boolean"
};
Trip.prototype._resource = "Trips";
Trip.prototype._model = "Trip";
function Trip(json) {
Trip.__super__.constructor.call(this, json);
}
Trip._resource = "Trips";
Trip._model = "Trip";
Trip.resource = function() {
return Trip._resource;
};
Trip.model = function() {
return Trip._model;
};
return Trip;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
15: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, User, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = User = function(_super) {
__extends(User, _super);
User.prototype._schema = {
Type: "Integer",
UserName: "String",
FirstName: "String",
LastName: "String",
Email: "String",
UserCount: "Integer",
Credits: "Integer",
CreationDate: "String",
LastActivityDate: "String",
LastLoginDate: "String",
Locale: "String",
_id: "String",
_deleted: "Boolean"
};
User.prototype._resource = "Users";
User.prototype._model = "User";
function User(json) {
User.__super__.constructor.call(this, json);
}
User._resource = "Users";
User._model = "User";
User.resource = function() {
return User._resource;
};
User.model = function() {
return User._model;
};
return User;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ],
16: [ function(_dereq_, module, exports) {
(function() {
var MojioModel, Vehicle, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
MojioModel = _dereq_("./MojioModel");
module.exports = Vehicle = function(_super) {
__extends(Vehicle, _super);
Vehicle.prototype._schema = {
Type: "Integer",
OwnerId: "String",
MojioId: "String",
Name: "String",
VIN: "String",
LicensePlate: "String",
IgnitionOn: "Boolean",
VehicleTime: "String",
LastTripEvent: "String",
LastLocationTime: "String",
LastLocation: {
Lat: "Float",
Lng: "Float",
FromLockedGPS: "Boolean",
Dilution: "Float"
},
LastSpeed: "Float",
FuelLevel: "Float",
LastAcceleration: "Float",
LastAccelerometer: "Object",
LastAltitude: "Float",
LastBatteryVoltage: "Float",
LastDistance: "Float",
LastHeading: "Float",
LastVirtualOdometer: "Float",
LastOdometer: "Float",
LastRpm: "Float",
LastFuelEfficiency: "Float",
CurrentTrip: "String",
LastTrip: "String",
LastContactTime: "String",
MilStatus: "Boolean",
DiagnosticCodes: "Object",
FaultsDetected: "Boolean",
LastLocationTimes: "Array",
LastLocations: "Array",
LastSpeeds: "Array",
LastHeadings: "Array",
LastAltitudes: "Array",
Viewers: "Array",
_id: "String",
_deleted: "Boolean"
};
Vehicle.prototype._resource = "Vehicles";
Vehicle.prototype._model = "Vehicle";
function Vehicle(json) {
Vehicle.__super__.constructor.call(this, json);
}
Vehicle._resource = "Vehicles";
Vehicle._model = "Vehicle";
Vehicle.resource = function() {
return Vehicle._resource;
};
Vehicle.model = function() {
return Vehicle._model;
};
return Vehicle;
}(MojioModel);
}).call(this);
}, {
"./MojioModel": 10
} ]
}, {}, [ 4 ])(4);
}); | mit |
zhengcq315/TestReportCenter | lib/vendor/symfony/lib/widget/sfWidgetFormSchema.class.php | 22962 | <?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfWidgetFormSchema represents an array of fields.
*
* A field is a named validator.
*
* @package symfony
* @subpackage widget
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfWidgetFormSchema.class.php 26870 2010-01-19 10:34:52Z fabien $
*/
class sfWidgetFormSchema extends sfWidgetForm implements ArrayAccess
{
const
FIRST = 'first',
LAST = 'last',
BEFORE = 'before',
AFTER = 'after';
protected static
$defaultFormatterName = 'table';
protected
$formFormatters = array(),
$fields = array(),
$positions = array(),
$helps = array();
/**
* Constructor.
*
* The first argument can be:
*
* * null
* * an array of sfWidget instances
*
* Available options:
*
* * name_format: The sprintf pattern to use for input names
* * form_formatter: The form formatter name (table and list are bundled)
*
* @param mixed $fields Initial fields
* @param array $options An array of options
* @param array $attributes An array of default HTML attributes
* @param array $labels An array of HTML labels
* @param array $helps An array of help texts
*
* @throws InvalidArgumentException when the passed fields not null or array
*
* @see sfWidgetForm
*/
public function __construct($fields = null, $options = array(), $attributes = array(), $labels = array(), $helps = array())
{
$this->addOption('name_format', '%s');
$this->addOption('form_formatter', null);
parent::__construct($options, $attributes);
if (is_array($fields))
{
foreach ($fields as $name => $widget)
{
$this[$name] = $widget;
}
}
else if (null !== $fields)
{
throw new InvalidArgumentException('sfWidgetFormSchema constructor takes an array of sfWidget objects.');
}
$this->setLabels($labels);
$this->helps = $helps;
}
/**
* Sets the default value for a field.
*
* @param string $name The field name
* @param string $value The default value (required - the default value is here because PHP do not allow signature changes with inheritance)
*
* @return sfWidget The current widget instance
*/
public function setDefault($name, $value = null)
{
$this[$name]->setDefault($value);
return $this;
}
/**
* Gets the default value of a field.
*
* @param string $name The field name (required - the default value is here because PHP do not allow signature changes with inheritance)
*
* @return string The default value
*/
public function getDefault($name = null)
{
return $this[$name]->getDefault();
}
/**
* Sets the default values for the widget.
*
* @param array $values The default values for the widget
*
* @return sfWidget The current widget instance
*/
public function setDefaults(array $values)
{
foreach ($this->fields as $name => $widget)
{
if (array_key_exists($name, $values))
{
$widget->setDefault($values[$name]);
}
}
return $this;
}
/**
* Returns the defaults values for the widget schema.
*
* @return array An array of default values
*/
public function getDefaults()
{
$defaults = array();
foreach ($this->fields as $name => $widget)
{
$defaults[$name] = $widget instanceof sfWidgetFormSchema ? $widget->getDefaults() : $widget->getDefault();
}
return $defaults;
}
/**
* Adds a form formatter.
*
* @param string $name The formatter name
* @param sfWidgetFormSchemaFormatter $formatter An sfWidgetFormSchemaFormatter instance
*
* @return sfWidget The current widget instance
*/
public function addFormFormatter($name, sfWidgetFormSchemaFormatter $formatter)
{
$this->formFormatters[$name] = $formatter;
return $this;
}
/**
* Returns all the form formats defined for this form schema.
*
* @return array An array of named form formats
*/
public function getFormFormatters()
{
return $this->formFormatters;
}
/**
* Sets the generic default formatter name used by the class. If you want all
* of your forms to be generated with the <code>list</code> format, you can
* do it in a project or application configuration class:
*
* <pre>
* class ProjectConfiguration extends sfProjectConfiguration
* {
* public function setup()
* {
* sfWidgetFormSchema::setDefaultFormFormatterName('list');
* }
* }
* </pre>
*
* @param string $name New default formatter name
*/
static public function setDefaultFormFormatterName($name)
{
self::$defaultFormatterName = $name;
}
/**
* Sets the form formatter name to use when rendering the widget schema.
*
* @param string $name The form formatter name
*
* @return sfWidget The current widget instance
*/
public function setFormFormatterName($name)
{
$this->options['form_formatter'] = $name;
return $this;
}
/**
* Gets the form formatter name that will be used to render the widget schema.
*
* @return string The form formatter name
*/
public function getFormFormatterName()
{
return null === $this->options['form_formatter'] ? self::$defaultFormatterName : $this->options['form_formatter'];
}
/**
* Returns the form formatter to use for widget schema rendering
*
* @return sfWidgetFormSchemaFormatter sfWidgetFormSchemaFormatter instance
*
* @throws InvalidArgumentException when the form formatter not exists
*/
public function getFormFormatter()
{
$name = $this->getFormFormatterName();
if (!isset($this->formFormatters[$name]))
{
$class = 'sfWidgetFormSchemaFormatter'.ucfirst($name);
if (!class_exists($class))
{
throw new InvalidArgumentException(sprintf('The form formatter "%s" does not exist.', $name));
}
$this->formFormatters[$name] = new $class($this);
}
return $this->formFormatters[$name];
}
/**
* Sets the format string for the name HTML attribute.
*
* If you are using the form framework with symfony, do not use a reserved word in the
* name format. If you do, symfony may act in an unexpected manner.
*
* For symfony 1.1+, the following words are reserved and must NOT be used as
* the name format:
*
* * module (example: module[%s])
* * action (example: action[%s])
*
* However, you CAN use other variations, such as actions[%s] (note the s).
*
* @param string $format The format string (must contain a %s for the name placeholder)
*
* @return sfWidget The current widget instance
*
* @throws InvalidArgumentException when no %s exists in the format
*/
public function setNameFormat($format)
{
if (false !== $format && false === strpos($format, '%s'))
{
throw new InvalidArgumentException(sprintf('The name format must contain %%s ("%s" given)', $format));
}
$this->options['name_format'] = $format;
return $this;
}
/**
* Gets the format string for the name HTML attribute.
*
* @return string The format string
*/
public function getNameFormat()
{
return $this->options['name_format'];
}
/**
* Sets the label names to render for each field.
*
* @param array $labels An array of label names
*
* @return sfWidget The current widget instance
*/
public function setLabels(array $labels)
{
foreach ($this->fields as $name => $widget)
{
if (array_key_exists($name, $labels))
{
$widget->setLabel($labels[$name]);
}
}
return $this;
}
/**
* Gets the labels.
*
* @return array An array of label names
*/
public function getLabels()
{
$labels = array();
foreach ($this->fields as $name => $widget)
{
$labels[$name] = $widget->getLabel();
}
return $labels;
}
/**
* Sets a label.
*
* @param string $name The field name
* @param string $value The label name (required - the default value is here because PHP do not allow signature changes with inheritance)
*
* @return sfWidget The current widget instance
*
* @throws InvalidArgumentException when you try to set a label on a none existing widget
*/
public function setLabel($name, $value = null)
{
if (2 == func_num_args())
{
if (!isset($this->fields[$name]))
{
throw new InvalidArgumentException(sprintf('Unable to set the label on an unexistant widget ("%s").', $name));
}
$this->fields[$name]->setLabel($value);
}
else
{
// set the label for this widget schema
parent::setLabel($name);
}
return $this;
}
/**
* Gets a label by field name.
*
* @param string $name The field name (required - the default value is here because PHP do not allow signature changes with inheritance)
*
* @return string The label name or an empty string if it is not defined
*
* @throws InvalidArgumentException when you try to get a label for a none existing widget
*/
public function getLabel($name = null)
{
if (1 == func_num_args())
{
if (!isset($this->fields[$name]))
{
throw new InvalidArgumentException(sprintf('Unable to get the label on an unexistant widget ("%s").', $name));
}
return $this->fields[$name]->getLabel();
}
else
{
// label for this widget schema
return parent::getLabel();
}
}
/**
* Sets the help texts to render for each field.
*
* @param array $helps An array of help texts
*
* @return sfWidget The current widget instance
*/
public function setHelps(array $helps)
{
$this->helps = $helps;
return $this;
}
/**
* Sets the help texts.
*
* @return array An array of help texts
*/
public function getHelps()
{
return $this->helps;
}
/**
* Sets a help text.
*
* @param string $name The field name
* @param string $help The help text
*
* @return sfWidget The current widget instance
*/
public function setHelp($name, $help)
{
$this->helps[$name] = $help;
return $this;
}
/**
* Gets a text help by field name.
*
* @param string $name The field name
*
* @return string The help text or an empty string if it is not defined
*/
public function getHelp($name)
{
return array_key_exists($name, $this->helps) ? $this->helps[$name] : '';
}
/**
* Gets the stylesheet paths associated with the widget.
*
* @return array An array of stylesheet paths
*/
public function getStylesheets()
{
$stylesheets = array();
foreach ($this->fields as $field)
{
$stylesheets = array_merge($stylesheets, $field->getStylesheets());
}
return $stylesheets;
}
/**
* Gets the JavaScript paths associated with the widget.
*
* @return array An array of JavaScript paths
*/
public function getJavaScripts()
{
$javascripts = array();
foreach ($this->fields as $field)
{
$javascripts = array_merge($javascripts, $field->getJavaScripts());
}
return array_unique($javascripts);
}
/**
* Returns true if the widget schema needs a multipart form.
*
* @return bool true if the widget schema needs a multipart form, false otherwise
*/
public function needsMultipartForm()
{
foreach ($this->fields as $field)
{
if ($field->needsMultipartForm())
{
return true;
}
}
return false;
}
/**
* Renders a field by name.
*
* @param string $name The field name
* @param string $value The field value
* @param array $attributes An array of HTML attributes to be merged with the current HTML attributes
* @param array $errors An array of errors for the field
*
* @return string An HTML string representing the rendered widget
*
* @throws InvalidArgumentException when the widget not exist
*/
public function renderField($name, $value = null, $attributes = array(), $errors = array())
{
if (null === $widget = $this[$name])
{
throw new InvalidArgumentException(sprintf('The field named "%s" does not exist.', $name));
}
if ($widget instanceof sfWidgetFormSchema && $errors && !$errors instanceof sfValidatorErrorSchema)
{
$errors = new sfValidatorErrorSchema($errors->getValidator(), array($errors));
}
// we clone the widget because we want to change the id format temporarily
$clone = clone $widget;
$clone->setIdFormat($this->options['id_format']);
return $clone->render($this->generateName($name), $value, array_merge($clone->getAttributes(), $attributes), $errors);
}
/**
* Renders the widget.
*
* @param string $name The name of the HTML widget
* @param mixed $values The values of the widget
* @param array $attributes An array of HTML attributes
* @param array $errors An array of errors
*
* @return string An HTML representation of the widget
*
* @throws InvalidArgumentException when values type is not array|ArrayAccess
*/
public function render($name, $values = array(), $attributes = array(), $errors = array())
{
if (null === $values)
{
$values = array();
}
if (!is_array($values) && !$values instanceof ArrayAccess)
{
throw new InvalidArgumentException('You must pass an array of values to render a widget schema');
}
$formFormat = $this->getFormFormatter();
$rows = array();
$hiddenRows = array();
$errorRows = array();
// render each field
foreach ($this->positions as $name)
{
$widget = $this[$name];
$value = isset($values[$name]) ? $values[$name] : null;
$error = isset($errors[$name]) ? $errors[$name] : array();
$widgetAttributes = isset($attributes[$name]) ? $attributes[$name] : array();
if ($widget instanceof sfWidgetForm && $widget->isHidden())
{
$hiddenRows[] = $this->renderField($name, $value, $widgetAttributes);
}
else
{
$field = $this->renderField($name, $value, $widgetAttributes, $error);
// don't add a label tag and errors if we embed a form schema
$label = $widget instanceof sfWidgetFormSchema ? $this->getFormFormatter()->generateLabelName($name) : $this->getFormFormatter()->generateLabel($name);
$error = $widget instanceof sfWidgetFormSchema ? array() : $error;
$rows[] = $formFormat->formatRow($label, $field, $error, $this->getHelp($name));
}
}
if ($rows)
{
// insert hidden fields in the last row
for ($i = 0, $max = count($rows); $i < $max; $i++)
{
$rows[$i] = strtr($rows[$i], array('%hidden_fields%' => $i == $max - 1 ? implode("\n", $hiddenRows) : ''));
}
}
else
{
// only hidden fields
$rows[0] = implode("\n", $hiddenRows);
}
return $this->getFormFormatter()->formatErrorRow($this->getGlobalErrors($errors)).implode('', $rows);
}
/**
* Gets errors that need to be included in global errors.
*
* @param array $errors An array of errors
*
* @return string An HTML representation of global errors for the widget
*/
public function getGlobalErrors($errors)
{
$globalErrors = array();
// global errors and errors for non existent fields
if (null !== $errors)
{
foreach ($errors as $name => $error)
{
if (!isset($this->fields[$name]))
{
$globalErrors[] = $error;
}
}
}
// errors for hidden fields
foreach ($this->positions as $name)
{
if ($this[$name] instanceof sfWidgetForm && $this[$name]->isHidden())
{
if (isset($errors[$name]))
{
$globalErrors[$this->getFormFormatter()->generateLabelName($name)] = $errors[$name];
}
}
}
return $globalErrors;
}
/**
* Generates a name.
*
* @param string $name The name
*
* @return string The generated name
*/
public function generateName($name)
{
$format = $this->getNameFormat();
if ('[%s]' == substr($format, -4) && preg_match('/^(.+?)\[(.+)\]$/', $name, $match))
{
$name = sprintf('%s[%s][%s]', substr($format, 0, -4), $match[1], $match[2]);
}
else if (false !== $format)
{
$name = sprintf($format, $name);
}
if ($parent = $this->getParent())
{
$name = $parent->generateName($name);
}
return $name;
}
/**
* Returns true if the schema has a field with the given name (implements the ArrayAccess interface).
*
* @param string $name The field name
*
* @return bool true if the schema has a field with the given name, false otherwise
*/
public function offsetExists($name)
{
return isset($this->fields[$name]);
}
/**
* Gets the field associated with the given name (implements the ArrayAccess interface).
*
* @param string $name The field name
*
* @return sfWidget|null The sfWidget instance associated with the given name, null if it does not exist
*/
public function offsetGet($name)
{
return isset($this->fields[$name]) ? $this->fields[$name] : null;
}
/**
* Sets a field (implements the ArrayAccess interface).
*
* @param string $name The field name
* @param sfWidget $widget An sfWidget instance
*
* @throws InvalidArgumentException when the field is not instance of sfWidget
*/
public function offsetSet($name, $widget)
{
if (!$widget instanceof sfWidget)
{
throw new InvalidArgumentException('A field must be an instance of sfWidget.');
}
if (!isset($this->fields[$name]))
{
$this->positions[] = (string) $name;
}
$this->fields[$name] = clone $widget;
$this->fields[$name]->setParent($this);
if ($widget instanceof sfWidgetFormSchema)
{
$this->fields[$name]->setNameFormat($name.'[%s]');
}
}
/**
* Removes a field by name (implements the ArrayAccess interface).
*
* @param string $name field name
*/
public function offsetUnset($name)
{
unset($this->fields[$name]);
if (false !== $position = array_search((string) $name, $this->positions))
{
unset($this->positions[$position]);
$this->positions = array_values($this->positions);
}
}
/**
* Returns an array of fields.
*
* @return sfWidget An array of sfWidget instance
*/
public function getFields()
{
return $this->fields;
}
/**
* Gets the positions of the fields.
*
* The field positions are only used when rendering the schema with ->render().
*
* @return array An ordered array of field names
*/
public function getPositions()
{
return $this->positions;
}
/**
* Sets the positions of the fields.
*
* @param array $positions An ordered array of field names
*
* @return sfWidget The current widget instance
*
* @throws InvalidArgumentException when not all fields set in $positions
*
* @see getPositions()
*/
public function setPositions(array $positions)
{
$positions = array_unique(array_values($positions));
$current = array_keys($this->fields);
if ($diff = array_diff($positions, $current))
{
throw new InvalidArgumentException('Widget schema does not include the following field(s): '.implode(', ', $diff));
}
if ($diff = array_diff($current, $positions))
{
throw new InvalidArgumentException('Positions array must include all fields. Missing: '.implode(', ', $diff));
}
foreach ($positions as &$position)
{
$position = (string) $position;
}
$this->positions = $positions;
return $this;
}
/**
* Moves a field in a given position
*
* Available actions are:
*
* * sfWidgetFormSchema::BEFORE
* * sfWidgetFormSchema::AFTER
* * sfWidgetFormSchema::LAST
* * sfWidgetFormSchema::FIRST
*
* @param string $field The field name to move
* @param constant $action The action (see above for all possible actions)
* @param string $pivot The field name used for AFTER and BEFORE actions
*
* @throws InvalidArgumentException when field not exist
* @throws InvalidArgumentException when relative field not exist
* @throws LogicException when you try to move a field without a relative field
* @throws LogicException when the $action not exist
*/
public function moveField($field, $action, $pivot = null)
{
$field = (string) $field;
if (false === $fieldPosition = array_search($field, $this->positions))
{
throw new InvalidArgumentException(sprintf('Field "%s" does not exist.', $field));
}
unset($this->positions[$fieldPosition]);
$this->positions = array_values($this->positions);
if (null !== $pivot)
{
$pivot = (string) $pivot;
if (false === $pivotPosition = array_search($pivot, $this->positions))
{
throw new InvalidArgumentException(sprintf('Field "%s" does not exist.', $pivot));
}
}
switch ($action)
{
case sfWidgetFormSchema::FIRST:
array_unshift($this->positions, $field);
break;
case sfWidgetFormSchema::LAST:
array_push($this->positions, $field);
break;
case sfWidgetFormSchema::BEFORE:
if (null === $pivot)
{
throw new LogicException(sprintf('Unable to move field "%s" without a relative field.', $field));
}
$this->positions = array_merge(
array_slice($this->positions, 0, $pivotPosition),
array($field),
array_slice($this->positions, $pivotPosition)
);
break;
case sfWidgetFormSchema::AFTER:
if (null === $pivot)
{
throw new LogicException(sprintf('Unable to move field "%s" without a relative field.', $field));
}
$this->positions = array_merge(
array_slice($this->positions, 0, $pivotPosition + 1),
array($field),
array_slice($this->positions, $pivotPosition + 1)
);
break;
default:
throw new LogicException(sprintf('Unknown move operation for field "%s".', $field));
}
}
public function __clone()
{
foreach ($this->fields as $name => $field)
{
// offsetSet will clone the field and change the parent
$this[$name] = $field;
}
foreach ($this->formFormatters as &$formFormatter)
{
$formFormatter = clone $formFormatter;
$formFormatter->setWidgetSchema($this);
}
}
}
| lgpl-2.1 |
abenjamin765/cdnjs | ajax/libs/rxjs/2.2.10/rx.virtualtime.js | 13481 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx', 'exports'], function (Rx, exports) {
root.Rx = factory(root, exports, Rx);
return root.Rx;
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('./rx'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// Aliases
var Scheduler = Rx.Scheduler,
PriorityQueue = Rx.Internals.PriorityQueue,
ScheduledItem = Rx.Internals.ScheduledItem,
SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive,
disposableEmpty = Rx.Disposable.empty,
inherits = Rx.Internals.inherits;
function defaultSubComparer(x, y) { return x - y; }
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (_super) {
function notImplemented() {
throw new Error('Not implemented');
}
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, _super);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
var next;
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var next;
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time);
var dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) {
throw new Error(argumentOutOfRange);
}
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
var next;
while (this.queue.length > 0) {
next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this,
run = function (scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
},
si = new ScheduledItem(self, state, run, dueTime, self.comparer);
self.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (_super) {
inherits(HistoricalScheduler, _super);
/**
* Creates a new historical scheduler with the specified initial clock value.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
_super.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
/**
* @private
*/
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
return Rx;
})); | mit |
easyddb/dummy_alma | vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/FooCommand.php | 507 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;
use Symfony\Component\Console\Command\Command;
class FooCommand extends Command
{
protected function configure()
{
$this->setName('foo');
}
}
| mit |
anmoya/anmoya.github.io | core/server/index.js | 7547 | // # Bootup
// This file needs serious love & refactoring
// Module dependencies
var express = require('express'),
hbs = require('express-hbs'),
compress = require('compression'),
fs = require('fs'),
uuid = require('node-uuid'),
_ = require('lodash'),
Promise = require('bluebird'),
i18n = require('./i18n'),
api = require('./api'),
config = require('./config'),
errors = require('./errors'),
helpers = require('./helpers'),
mailer = require('./mail'),
middleware = require('./middleware'),
migrations = require('./data/migration'),
models = require('./models'),
permissions = require('./permissions'),
apps = require('./apps'),
sitemap = require('./data/xml/sitemap'),
xmlrpc = require('./data/xml/xmlrpc'),
GhostServer = require('./ghost-server'),
dbHash;
function initDbHashAndFirstRun() {
return api.settings.read({key: 'dbHash', context: {internal: true}}).then(function (response) {
var hash = response.settings[0].value,
initHash;
dbHash = hash;
if (dbHash === null) {
initHash = uuid.v4();
return api.settings.edit({settings: [{key: 'dbHash', value: initHash}]}, {context: {internal: true}})
.then(function (response) {
dbHash = response.settings[0].value;
return dbHash;
// Use `then` here to do 'first run' actions
});
}
return dbHash;
});
}
// Checks for the existence of the "built" javascript files from grunt concat.
// Returns a promise that will be resolved if all files exist or rejected if
// any are missing.
function builtFilesExist() {
var deferreds = [],
location = config.paths.clientAssets,
fileNames = ['ghost.js', 'vendor.js', 'ghost.css', 'vendor.css'];
if (process.env.NODE_ENV === 'production') {
// Production uses `.min` files
fileNames = fileNames.map(function (file) {
return file.replace('.', '.min.');
});
}
function checkExist(fileName) {
var errorMessage = 'Javascript files have not been built.',
errorHelp = '\nPlease read the getting started instructions at:' +
'\nhttps://github.com/TryGhost/Ghost#getting-started';
return new Promise(function (resolve, reject) {
fs.stat(fileName, function (statErr) {
var exists = (statErr) ? false : true,
err;
if (exists) {
resolve(true);
} else {
err = new Error(errorMessage);
err.help = errorHelp;
reject(err);
}
});
});
}
fileNames.forEach(function (fileName) {
deferreds.push(checkExist(location + fileName));
});
return Promise.all(deferreds);
}
// This is run after every initialization is done, right before starting server.
// Its main purpose is to move adding notifications here, so none of the submodules
// should need to include api, which previously resulted in circular dependencies.
// This is also a "one central repository" of adding startup notifications in case
// in the future apps will want to hook into here
function initNotifications() {
if (mailer.state && mailer.state.usingDirect) {
api.notifications.add({notifications: [{
type: 'info',
message: [
'Ghost is attempting to use a direct method to send e-mail.',
'It is recommended that you explicitly configure an e-mail service.',
'See <a href=\'http://support.ghost.org/mail\' target=\'_blank\'>http://support.ghost.org/mail</a> for instructions'
].join(' ')
}]}, {context: {internal: true}});
}
if (mailer.state && mailer.state.emailDisabled) {
api.notifications.add({notifications: [{
type: 'warn',
message: [
'Ghost is currently unable to send e-mail.',
'See <a href=\'http://support.ghost.org/mail\' target=\'_blank\'>http://support.ghost.org/mail</a> for instructions'
].join(' ')
}]}, {context: {internal: true}});
}
}
// ## Initialise Ghost
// Sets up the express server instances, runs init on a bunch of stuff, configures views, helpers, routes and more
// Finally it returns an instance of GhostServer
function init(options) {
// Get reference to an express app instance.
var blogApp = express(),
adminApp = express();
// ### Initialisation
// The server and its dependencies require a populated config
// It returns a promise that is resolved when the application
// has finished starting up.
// Load our config.js file from the local file system.
return config.load(options.config).then(function () {
return config.checkDeprecated();
}).then(function () {
// Make sure javascript files have been built via grunt concat
return builtFilesExist();
}).then(function () {
// Initialise the models
return models.init();
}).then(function () {
// Initialize migrations
return migrations.init();
}).then(function () {
// Populate any missing default settings
return models.Settings.populateDefaults();
}).then(function () {
// Initialize the settings cache
return api.init();
}).then(function () {
// Initialize the permissions actions and objects
// NOTE: Must be done before initDbHashAndFirstRun calls
return permissions.init();
}).then(function () {
return Promise.join(
// Check for or initialise a dbHash.
initDbHashAndFirstRun(),
// Initialize mail
mailer.init(),
// Initialize apps
apps.init(),
// Initialize sitemaps
sitemap.init(),
// Initialize xmrpc ping
xmlrpc.init()
);
}).then(function () {
var adminHbs = hbs.create();
// Initialize Internationalization
i18n.init();
// Output necessary notifications on init
initNotifications();
// ##Configuration
// return the correct mime type for woff files
express['static'].mime.define({'application/font-woff': ['woff']});
// enabled gzip compression by default
if (config.server.compress !== false) {
blogApp.use(compress());
}
// ## View engine
// set the view engine
blogApp.set('view engine', 'hbs');
// Create a hbs instance for admin and init view engine
adminApp.set('view engine', 'hbs');
adminApp.engine('hbs', adminHbs.express3({}));
// Load helpers
helpers.loadCoreHelpers(adminHbs);
// ## Middleware and Routing
middleware(blogApp, adminApp);
// Log all theme errors and warnings
_.each(config.paths.availableThemes._messages.errors, function (error) {
errors.logError(error.message, error.context, error.help);
});
_.each(config.paths.availableThemes._messages.warns, function (warn) {
errors.logWarn(warn.message, warn.context, warn.help);
});
return new GhostServer(blogApp);
});
}
module.exports = init;
| mit |
dalanmiller/homebrew | Library/Formula/par.rb | 1175 | class Par < Formula
desc "Paragraph reflow for email"
homepage "http://www.nicemice.net/par/"
url "http://www.nicemice.net/par/Par152.tar.gz"
version "1.52"
sha256 "33dcdae905f4b4267b4dc1f3efb032d79705ca8d2122e17efdecfd8162067082"
bottle do
cellar :any_skip_relocation
revision 1
sha256 "2dd2b1808f820354b03927fc30b11eeb33bd5704877756938cb8c5daac18a393" => :el_capitan
sha256 "195a82f58ad34fe5d4e3c061a6d83909017861ede1e8af5668ef2062e0c0bdcb" => :yosemite
sha256 "3d666b815997eda86ee0f96e71ba6fca3193432c5a01affb59918f22408c8dc6" => :mavericks
end
conflicts_with "rancid", :because => "both install `par` binaries"
# A patch by Jérôme Pouiller that adds support for multibyte
# charsets (like UTF-8), plus Debian packaging.
patch do
url "http://sysmic.org/dl/par/par-1.52-i18n.4.patch"
sha256 "2ab2d6039529aa3e7aff4920c1630003b8c97c722c8adc6d7762aa34e795861e"
end
def install
system "make", "-f", "protoMakefile"
bin.install "par"
man1.install gzip("par.1")
end
test do
expected = "homebrew\nhomebrew\n"
assert_equal expected, pipe_output("#{bin}/par 10gqr", "homebrew homebrew")
end
end
| bsd-2-clause |
mu4ddi3/gajdaw-zad-29-01 | vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php | 9464 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\TwigBundle\Tests\DependencyInjection;
use Symfony\Bundle\TwigBundle\DependencyInjection\TwigExtension;
use Symfony\Bundle\TwigBundle\Tests\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
class TwigExtensionTest extends TestCase
{
public function testLoadEmptyConfiguration()
{
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$container->loadFromExtension('twig', array());
$this->compileContainer($container);
$this->assertEquals('Twig_Environment', $container->getParameter('twig.class'), '->load() loads the twig.xml file');
$this->assertContains('form_div_layout.html.twig', $container->getParameter('twig.form.resources'), '->load() includes default template for form resources');
// Twig options
$options = $container->getParameter('twig.options');
$this->assertEquals(__DIR__.'/twig', $options['cache'], '->load() sets default value for cache option');
$this->assertEquals('UTF-8', $options['charset'], '->load() sets default value for charset option');
$this->assertFalse($options['debug'], '->load() sets default value for debug option');
}
/**
* @dataProvider getFormats
*/
public function testLoadFullConfiguration($format)
{
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$this->loadFromFile($container, 'full', $format);
$this->compileContainer($container);
$this->assertEquals('Twig_Environment', $container->getParameter('twig.class'), '->load() loads the twig.xml file');
// Form resources
$resources = $container->getParameter('twig.form.resources');
$this->assertContains('form_div_layout.html.twig', $resources, '->load() includes default template for form resources');
$this->assertContains('MyBundle::form.html.twig', $resources, '->load() merges new templates into form resources');
// Globals
$calls = $container->getDefinition('twig')->getMethodCalls();
$this->assertEquals('app', $calls[0][1][0], '->load() registers services as Twig globals');
$this->assertEquals(new Reference('templating.globals'), $calls[0][1][1]);
$this->assertEquals('foo', $calls[1][1][0], '->load() registers services as Twig globals');
$this->assertEquals(new Reference('bar'), $calls[1][1][1], '->load() registers services as Twig globals');
$this->assertEquals('pi', $calls[2][1][0], '->load() registers variables as Twig globals');
$this->assertEquals(3.14, $calls[2][1][1], '->load() registers variables as Twig globals');
// Yaml and Php specific configs
if (in_array($format, array('yml', 'php'))) {
$this->assertEquals('bad', $calls[3][1][0], '->load() registers variables as Twig globals');
$this->assertEquals(array('key' => 'foo'), $calls[3][1][1], '->load() registers variables as Twig globals');
}
// Twig options
$options = $container->getParameter('twig.options');
$this->assertTrue($options['auto_reload'], '->load() sets the auto_reload option');
$this->assertTrue($options['autoescape'], '->load() sets the autoescape option');
$this->assertEquals('stdClass', $options['base_template_class'], '->load() sets the base_template_class option');
$this->assertEquals('/tmp', $options['cache'], '->load() sets the cache option');
$this->assertEquals('ISO-8859-1', $options['charset'], '->load() sets the charset option');
$this->assertTrue($options['debug'], '->load() sets the debug option');
$this->assertTrue($options['strict_variables'], '->load() sets the strict_variables option');
}
/**
* @dataProvider getFormats
*/
public function testLoadCustomTemplateEscapingGuesserConfiguration($format)
{
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$this->loadFromFile($container, 'customTemplateEscapingGuesser', $format);
$this->compileContainer($container);
$this->assertTemplateEscapingGuesserDefinition($container, 'my_project.some_bundle.template_escaping_guesser', 'guess');
}
/**
* @dataProvider getFormats
*/
public function testLoadDefaultTemplateEscapingGuesserConfiguration($format)
{
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$this->loadFromFile($container, 'empty', $format);
$this->compileContainer($container);
$this->assertTemplateEscapingGuesserDefinition($container, 'templating.engine.twig', 'guessDefaultEscapingStrategy');
}
public function testGlobalsWithDifferentTypesAndValues()
{
$globals = array(
'array' => array(),
'false' => false,
'float' => 2.0,
'integer' => 3,
'null' => null,
'object' => new \stdClass(),
'string' => 'foo',
'true' => true,
);
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$container->loadFromExtension('twig', array('globals' => $globals));
$this->compileContainer($container);
$calls = $container->getDefinition('twig')->getMethodCalls();
foreach (array_slice($calls, 1) as $call) {
list($name, $value) = each($globals);
$this->assertEquals($name, $call[1][0]);
$this->assertSame($value, $call[1][1]);
}
}
/**
* @dataProvider getFormats
*/
public function testTwigLoaderPaths($format)
{
$container = $this->createContainer();
$container->registerExtension(new TwigExtension());
$this->loadFromFile($container, 'full', $format);
$this->compileContainer($container);
$def = $container->getDefinition('twig.loader.filesystem');
$paths = array();
foreach ($def->getMethodCalls() as $call) {
if ('addPath' === $call[0]) {
if (false === strpos($call[1][0], 'Form')) {
$paths[] = $call[1];
}
}
}
$this->assertEquals(array(
array('path1'),
array('path2'),
array('namespaced_path1', 'namespace'),
array('namespaced_path2', 'namespace'),
array(__DIR__.'/Fixtures/Resources/TwigBundle/views', 'Twig'),
array(realpath(__DIR__.'/../..').'/Resources/views', 'Twig'),
array(__DIR__.'/Fixtures/Resources/views'),
), $paths);
}
public function getFormats()
{
return array(
array('php'),
array('yml'),
array('xml'),
);
}
private function createContainer()
{
$container = new ContainerBuilder(new ParameterBag(array(
'kernel.cache_dir' => __DIR__,
'kernel.root_dir' => __DIR__.'/Fixtures',
'kernel.charset' => 'UTF-8',
'kernel.debug' => false,
'kernel.bundles' => array('TwigBundle' => 'Symfony\\Bundle\\TwigBundle\\TwigBundle'),
)));
return $container;
}
private function compileContainer(ContainerBuilder $container)
{
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
}
private function loadFromFile(ContainerBuilder $container, $file, $format)
{
$locator = new FileLocator(__DIR__.'/Fixtures/'.$format);
switch ($format) {
case 'php':
$loader = new PhpFileLoader($container, $locator);
break;
case 'xml':
$loader = new XmlFileLoader($container, $locator);
break;
case 'yml':
$loader = new YamlFileLoader($container, $locator);
break;
default:
throw new \InvalidArgumentException(sprintf('Unsupported format: %s', $format));
}
$loader->load($file.'.'.$format);
}
private function assertTemplateEscapingGuesserDefinition(ContainerBuilder $container, $serviceId, $serviceMethod)
{
$def = $container->getDefinition('templating.engine.twig');
$this->assertCount(1, $def->getMethodCalls());
foreach ($def->getMethodCalls() as $call) {
if ('setDefaultEscapingStrategy' === $call[0]) {
$this->assertSame($serviceId, (string) $call[1][0][0]);
$this->assertSame($serviceMethod, $call[1][0][1]);
}
}
}
}
| mit |
mattfelsen/homebrew-cask | Casks/mongodbpreferencepane.rb | 360 | cask :v1 => 'mongodbpreferencepane' do
version :latest
sha256 :no_check
url 'https://github.com/remysaissy/mongodb-macosx-prefspane/raw/master/download/MongoDB.prefPane.zip'
name 'MongoDB-PrefsPane'
name 'mongodb-macosx-prefspane'
homepage 'https://github.com/remysaissy/mongodb-macosx-prefspane'
license :gpl
prefpane 'MongoDB.prefPane'
end
| bsd-2-clause |
nassafou/serApp | vendor/symfony/symfony/src/Symfony/Component/Finder/Tests/Iterator/FilePathsIteratorTest.php | 2791 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Tests\Iterator;
use Symfony\Component\Finder\Iterator\FilePathsIterator;
class FilePathsIteratorTest extends RealIteratorTestCase
{
/**
* @dataProvider getSubPathData
*/
public function testSubPath($baseDir, array $paths, array $subPaths, array $subPathnames)
{
$iterator = new FilePathsIterator($paths, $baseDir);
foreach ($iterator as $index => $file) {
$this->assertEquals($paths[$index], $file->getPathname());
$this->assertEquals($subPaths[$index], $iterator->getSubPath());
$this->assertEquals($subPathnames[$index], $iterator->getSubPathname());
}
}
public function getSubPathData()
{
$tmpDir = sys_get_temp_dir().'/symfony2_finder';
return array(
array(
$tmpDir,
array( // paths
$tmpDir.DIRECTORY_SEPARATOR.'.git' => $tmpDir.DIRECTORY_SEPARATOR.'.git',
$tmpDir.DIRECTORY_SEPARATOR.'test.py' => $tmpDir.DIRECTORY_SEPARATOR.'test.py',
$tmpDir.DIRECTORY_SEPARATOR.'foo' => $tmpDir.DIRECTORY_SEPARATOR.'foo',
$tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => $tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp',
$tmpDir.DIRECTORY_SEPARATOR.'test.php' => $tmpDir.DIRECTORY_SEPARATOR.'test.php',
$tmpDir.DIRECTORY_SEPARATOR.'toto' => $tmpDir.DIRECTORY_SEPARATOR.'toto'
),
array( // subPaths
$tmpDir.DIRECTORY_SEPARATOR.'.git' => '',
$tmpDir.DIRECTORY_SEPARATOR.'test.py' => '',
$tmpDir.DIRECTORY_SEPARATOR.'foo' => '',
$tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => 'foo',
$tmpDir.DIRECTORY_SEPARATOR.'test.php' => '',
$tmpDir.DIRECTORY_SEPARATOR.'toto' => ''
),
array( // subPathnames
$tmpDir.DIRECTORY_SEPARATOR.'.git' => '.git',
$tmpDir.DIRECTORY_SEPARATOR.'test.py' => 'test.py',
$tmpDir.DIRECTORY_SEPARATOR.'foo' => 'foo',
$tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => 'foo'.DIRECTORY_SEPARATOR.'bar.tmp',
$tmpDir.DIRECTORY_SEPARATOR.'test.php' => 'test.php',
$tmpDir.DIRECTORY_SEPARATOR.'toto' => 'toto'
),
),
);
}
}
| mit |
DiamondLovesYou/skia-sys | src/animator/SkDrawOval.cpp | 536 |
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDrawOval.h"
#include "SkAnimateMaker.h"
#include "SkCanvas.h"
#if SK_USE_CONDENSED_INFO == 0
const SkMemberInfo SkOval::fInfo[] = {
SK_MEMBER_INHERITED,
};
#endif
DEFINE_GET_MEMBER(SkOval);
bool SkOval::draw(SkAnimateMaker& maker) {
SkBoundableAuto boundable(this, maker);
maker.fCanvas->drawOval(fRect, *maker.fPaint);
return false;
}
| bsd-3-clause |
mindprince/test-infra | vendor/k8s.io/code-generator/_examples/apiserver/clientset/internalversion/fake/doc.go | 695 | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
// This package has the automatically generated fake clientset.
package fake
| apache-2.0 |
Chivan/Dirigendo | vendor/symfony/symfony/src/Symfony/Component/Routing/Matcher/Dumper/MatcherDumper.php | 884 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Matcher\Dumper;
use Symfony\Component\Routing\RouteCollection;
/**
* MatcherDumper is the abstract class for all built-in matcher dumpers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class MatcherDumper implements MatcherDumperInterface
{
private $routes;
/**
* Constructor.
*
* @param RouteCollection $routes The RouteCollection to dump
*/
public function __construct(RouteCollection $routes)
{
$this->routes = $routes;
}
/**
* {@inheritdoc}
*/
public function getRoutes()
{
return $this->routes;
}
}
| mit |
phoenixcqcq/mobilbonus-test | vendor/zendframework/zendframework/library/Zend/Mail/Storage/Part/Exception/RuntimeException.php | 530 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mail\Storage\Part\Exception;
use Zend\Mail\Storage\Exception;
/**
* Exception for Zend\Mail component.
*/
class RuntimeException extends Exception\RuntimeException implements
ExceptionInterface
{}
| bsd-3-clause |
BigBoss424/portfolio | v8/development/node_modules/atob/bin/atob.js | 122 | #!/usr/bin/env node
'use strict';
var atob = require('../node-atob');
var str = process.argv[2];
console.log(atob(str));
| apache-2.0 |
monarch-games/engine | source-archive/core/overlay/components/overlay.tsx | 627 |
import {h, Component} from "preact"
import {observer} from "mobx-preact"
import {Stick} from "./stick.js"
import {MenuBar} from "./menu-bar.js"
import {OverlayProps} from "./components-interfaces.js"
@observer
export class Overlay extends Component<OverlayProps> {
render() {
const {overlayStore} = this.props
return (
<div className="overlay">
<MenuBar store={overlayStore.menuBar}/>
{overlayStore.sticksEngaged
? (
<div className="thumbsticks">
<Stick stickStore={overlayStore.stick1}/>
<Stick stickStore={overlayStore.stick2}/>
</div>
)
: null}
</div>
)
}
}
| isc |
adiabat/btcd | wire/msgblock.go | 10511 | // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wire
import (
"bytes"
"fmt"
"io"
"github.com/adiabat/btcd/chaincfg/chainhash"
)
// defaultTransactionAlloc is the default size used for the backing array
// for transactions. The transaction array will dynamically grow as needed, but
// this figure is intended to provide enough space for the number of
// transactions in the vast majority of blocks without needing to grow the
// backing array multiple times.
const defaultTransactionAlloc = 2048
// MaxBlocksPerMsg is the maximum number of blocks allowed per message.
const MaxBlocksPerMsg = 500
// MaxBlockPayload is the maximum bytes a block message can be in bytes.
// After Segregated Witness, the max block payload has been raised to 4MB.
const MaxBlockPayload = 4000000
// maxTxPerBlock is the maximum number of transactions that could
// possibly fit into a block.
const maxTxPerBlock = (MaxBlockPayload / minTxPayload) + 1
// TxLoc holds locator data for the offset and length of where a transaction is
// located within a MsgBlock data buffer.
type TxLoc struct {
TxStart int
TxLen int
}
// MsgBlock implements the Message interface and represents a bitcoin
// block message. It is used to deliver block and transaction information in
// response to a getdata message (MsgGetData) for a given block hash.
type MsgBlock struct {
Header BlockHeader
Transactions []*MsgTx
}
// AddTransaction adds a transaction to the message.
func (msg *MsgBlock) AddTransaction(tx *MsgTx) error {
msg.Transactions = append(msg.Transactions, tx)
return nil
}
// ClearTransactions removes all transactions from the message.
func (msg *MsgBlock) ClearTransactions() {
msg.Transactions = make([]*MsgTx, 0, defaultTransactionAlloc)
}
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.
// See Deserialize for decoding blocks stored to disk, such as in a database, as
// opposed to decoding blocks from the wire.
func (msg *MsgBlock) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error {
err := readBlockHeader(r, pver, &msg.Header)
if err != nil {
return err
}
txCount, err := ReadVarInt(r, pver)
if err != nil {
return err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return messageError("MsgBlock.BtcDecode", str)
}
msg.Transactions = make([]*MsgTx, 0, txCount)
for i := uint64(0); i < txCount; i++ {
tx := MsgTx{}
err := tx.BtcDecode(r, pver, enc)
if err != nil {
return err
}
msg.Transactions = append(msg.Transactions, &tx)
}
return nil
}
// Deserialize decodes a block from r into the receiver using a format that is
// suitable for long-term storage such as a database while respecting the
// Version field in the block. This function differs from BtcDecode in that
// BtcDecode decodes from the bitcoin wire protocol as it was sent across the
// network. The wire encoding can technically differ depending on the protocol
// version and doesn't even really need to match the format of a stored block at
// all. As of the time this comment was written, the encoded block is the same
// in both instances, but there is a distinct difference and separating the two
// allows the API to be flexible enough to deal with changes.
func (msg *MsgBlock) Deserialize(r io.Reader) error {
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of BtcDecode.
//
// Passing an encoding type of WitnessEncoding to BtcEncode for
// indicates that the transactions within the block are expected to be
// serialized according to the new serialization structure defined in
// BIP0141.
return msg.BtcDecode(r, 0, WitnessEncoding)
}
// DeserializeWitness decodes a block from r into the receiver similar to
// Deserialize, however DeserializeWitness strips all (if any) witness data
// from the transactions within the block before encoding them.
func (msg *MsgBlock) DeserializeNoWitness(r io.Reader) error {
return msg.BtcDecode(r, 0, BaseEncoding)
}
// DeserializeTxLoc decodes r in the same manner Deserialize does, but it takes
// a byte buffer instead of a generic reader and returns a slice containing the
// start and length of each transaction within the raw data that is being
// deserialized.
func (msg *MsgBlock) DeserializeTxLoc(r *bytes.Buffer) ([]TxLoc, error) {
fullLen := r.Len()
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of existing wire protocol functions.
err := readBlockHeader(r, 0, &msg.Header)
if err != nil {
return nil, err
}
txCount, err := ReadVarInt(r, 0)
if err != nil {
return nil, err
}
// Prevent more transactions than could possibly fit into a block.
// It would be possible to cause memory exhaustion and panics without
// a sane upper bound on this count.
if txCount > maxTxPerBlock {
str := fmt.Sprintf("too many transactions to fit into a block "+
"[count %d, max %d]", txCount, maxTxPerBlock)
return nil, messageError("MsgBlock.DeserializeTxLoc", str)
}
// Deserialize each transaction while keeping track of its location
// within the byte stream.
msg.Transactions = make([]*MsgTx, 0, txCount)
txLocs := make([]TxLoc, txCount)
for i := uint64(0); i < txCount; i++ {
txLocs[i].TxStart = fullLen - r.Len()
tx := MsgTx{}
err := tx.Deserialize(r)
if err != nil {
return nil, err
}
msg.Transactions = append(msg.Transactions, &tx)
txLocs[i].TxLen = (fullLen - r.Len()) - txLocs[i].TxStart
}
return txLocs, nil
}
// BtcEncode encodes the receiver to w using the bitcoin protocol encoding.
// This is part of the Message interface implementation.
// See Serialize for encoding blocks to be stored to disk, such as in a
// database, as opposed to encoding blocks for the wire.
func (msg *MsgBlock) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error {
err := WriteBlockHeader(w, pver, &msg.Header)
if err != nil {
return err
}
err = WriteVarInt(w, pver, uint64(len(msg.Transactions)))
if err != nil {
return err
}
for _, tx := range msg.Transactions {
err = tx.BtcEncode(w, pver, enc)
if err != nil {
return err
}
}
return nil
}
// Serialize encodes the block to w using a format that suitable for long-term
// storage such as a database while respecting the Version field in the block.
// This function differs from BtcEncode in that BtcEncode encodes the block to
// the bitcoin wire protocol in order to be sent across the network. The wire
// encoding can technically differ depending on the protocol version and doesn't
// even really need to match the format of a stored block at all. As of the
// time this comment was written, the encoded block is the same in both
// instances, but there is a distinct difference and separating the two allows
// the API to be flexible enough to deal with changes.
func (msg *MsgBlock) Serialize(w io.Writer) error {
// At the current time, there is no difference between the wire encoding
// at protocol version 0 and the stable long-term storage format. As
// a result, make use of BtcEncode.
//
// Passing WitnessEncoding as the encoding type here indicates that
// each of the transactions should be serialized using the witness
// serialization structure defined in BIP0141.
return msg.BtcEncode(w, 0, WitnessEncoding)
}
// SerializeWitness encodes a block to w using an identical format to Serialize,
// with all (if any) witness data stripped from all transactions.
// This method is provided in additon to the regular Serialize, in order to
// allow one to selectively encode transaction witness data to non-upgraded
// peers which are unaware of the new encoding.
func (msg *MsgBlock) SerializeNoWitness(w io.Writer) error {
return msg.BtcEncode(w, 0, BaseEncoding)
}
// SerializeSize returns the number of bytes it would take to serialize the
// block, factoring in any witness data within transaction.
func (msg *MsgBlock) SerializeSize() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
for _, tx := range msg.Transactions {
n += tx.SerializeSize()
}
return n
}
// SerializeSizeStripped returns the number of bytes it would take to serialize
// the block, excluding any witness data (if any).
func (msg *MsgBlock) SerializeSizeStripped() int {
// Block header bytes + Serialized varint size for the number of
// transactions.
n := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))
for _, tx := range msg.Transactions {
n += tx.SerializeSizeStripped()
}
return n
}
// Command returns the protocol command string for the message. This is part
// of the Message interface implementation.
func (msg *MsgBlock) Command() string {
return CmdBlock
}
// MaxPayloadLength returns the maximum length the payload can be for the
// receiver. This is part of the Message interface implementation.
func (msg *MsgBlock) MaxPayloadLength(pver uint32) uint32 {
// Block header at 80 bytes + transaction count + max transactions
// which can vary up to the MaxBlockPayload (including the block header
// and transaction count).
return MaxBlockPayload
}
// BlockHash computes the block identifier hash for this block.
func (msg *MsgBlock) BlockHash() chainhash.Hash {
return msg.Header.BlockHash()
}
// TxHashes returns a slice of hashes of all of transactions in this block.
func (msg *MsgBlock) TxHashes() ([]chainhash.Hash, error) {
hashList := make([]chainhash.Hash, 0, len(msg.Transactions))
for _, tx := range msg.Transactions {
hashList = append(hashList, tx.TxHash())
}
return hashList, nil
}
// NewMsgBlock returns a new bitcoin block message that conforms to the
// Message interface. See MsgBlock for details.
func NewMsgBlock(blockHeader *BlockHeader) *MsgBlock {
return &MsgBlock{
Header: *blockHeader,
Transactions: make([]*MsgTx, 0, defaultTransactionAlloc),
}
}
| isc |
sprintly/sprintly-kanban | app/actions/velocity-actions-test.js | 2287 | /*eslint-env node, mocha */
var sinon = require('sinon')
var VelocityActions = require('./velocity-actions')
describe('VelocityActions', function() {
beforeEach(function() {
this.appDispatcher = VelocityActions.__get__('AppDispatcher')
this.sinon = sinon.sandbox.create()
})
afterEach(function() {
this.sinon.restore()
})
describe('getVelocity', function() {
beforeEach(function() {
let internals = VelocityActions.__get__('internals')
this.requestStub = this.sinon.stub(internals, 'request')
})
context('api success', function() {
it('dispatches a PRODUCT_VELOCITY event', function() {
var dispatchStub = this.sinon.stub(this.appDispatcher, 'dispatch')
this.requestStub.callsArgWith(2, null, { body: { average: 1 } })
VelocityActions.getVelocity('id')
sinon.assert.calledWith(dispatchStub, {
actionType: 'PRODUCT_VELOCITY',
payload: { average: 7 },
productId: 'id'
})
})
it('overrides the velocity if less than 1', function() {
var dispatchStub = this.sinon.stub(this.appDispatcher, 'dispatch')
this.requestStub.callsArgWith(2, null, {
body: {
average: 0.025
}
})
VelocityActions.getVelocity('id')
sinon.assert.calledWith(dispatchStub, {
actionType: 'PRODUCT_VELOCITY',
payload: { average: 10 },
productId: 'id'
})
})
})
context('api error', function() {
it('dispatches a PRODUCT_VELOCITY_ERROR event', function() {
var dispatchStub = this.sinon.stub(this.appDispatcher, 'dispatch')
this.requestStub.callsArgWith(2, 'ERROR')
VelocityActions.getVelocity()
sinon.assert.calledWith(dispatchStub, {
actionType: 'PRODUCT_VELOCITY_ERROR'
})
})
})
})
describe('setVelocity', function() {
it('dispatches the a PRODUCT_VELOCITY event', function(done) {
var dispatchStub = this.sinon.stub(this.appDispatcher, 'dispatch')
VelocityActions.setVelocity('id', 100)
sinon.assert.calledWith(dispatchStub, {
actionType: 'PRODUCT_VELOCITY',
payload: { average: 100 },
productId: 'id'
})
done()
})
})
})
| isc |
thelabnyc/django-oscar-cch | src/oscarcch/tests/test_cch_nine_digits_zip.py | 14854 | from unittest import mock
from decimal import Decimal as D
from freezegun import freeze_time
from oscar.core.loading import get_model, get_class
from ..calculator import CCHTaxCalculator
from .base import BaseTest
from .base import p
Basket = get_model("basket", "Basket")
ShippingAddress = get_model("order", "ShippingAddress")
Country = get_model("address", "Country")
PartnerAddress = get_model("partner", "PartnerAddress")
Range = get_model("offer", "Range")
Benefit = get_model("offer", "Benefit")
Condition = get_model("offer", "Condition")
ConditionalOffer = get_model("offer", "ConditionalOffer")
USStrategy = get_class("partner.strategy", "US")
Applicator = get_class("offer.applicator", "Applicator")
class CCHTaxCalculatorRealTest(BaseTest):
@freeze_time("2016-04-13T16:14:44.018599-00:00")
@mock.patch("soap.get_transport")
def test_apply_taxes_five_digits_postal_code(self, get_transport):
basket = self.prepare_basket_full_zip()
to_address = self.get_to_address_ohio_short_zip()
shipping_charge = self.get_shipping_charge()
def test_request(request):
self.assertNodeText(
request.message, p("Body/CalculateRequest/EntityID"), "TESTSANDBOX"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/DivisionID"), "42"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/CustomerType"), "08"
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/InvoiceDate"),
"2016-04-13T12:14:44.018599-04:00",
)
self.assertNodeCount(
request.message, p("Body/CalculateRequest/order/LineItems/LineItem"), 2
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/AvgUnitPrice"),
"10",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/ID"),
str(basket.all_lines()[0].id),
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/City"
),
"Anchorage",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/CountryCode"
),
"US",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/Line1"
),
"325 F st",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/PostalCode"
),
"99501",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/Plus4"
),
"2217",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/StateOrProvince"
),
"AK",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/City"
),
"BRINKHAVEN",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/CountryCode"
),
"US",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/Line1"
),
"33001 STATE ROUTE 206",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/PostalCode"
),
"43006",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/StateOrProvince"
),
"OH",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/Quantity"),
"1",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/SKU"),
"ABC123",
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/ProviderType"), "70"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/SourceSystem"), "Oscar"
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/TestTransaction"),
"true",
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/TransactionID"), "0"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/TransactionType"), "01"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/finalize"), "false"
)
resp = self._get_cch_response_ohio_request_short_zip(basket.all_lines()[0].id)
get_transport.return_value = self._build_transport_with_reply(
resp, test_request=test_request
)
self.assertFalse(basket.is_tax_known)
self.assertEqual(basket.total_excl_tax, D("10.00"))
CCHTaxCalculator().apply_taxes(to_address, basket, shipping_charge)
self.assertTrue(basket.is_tax_known)
self.assertEqual(basket.total_excl_tax, D("10.00"))
self.assertEqual(basket.total_incl_tax, D("10.68"))
self.assertEqual(basket.total_tax, D("0.68"))
purchase_info = basket.all_lines()[0].purchase_info
self.assertEqual(purchase_info.price.excl_tax, D("10.00"))
self.assertEqual(purchase_info.price.incl_tax, D("10.68"))
self.assertEqual(purchase_info.price.tax, D("0.68"))
details = purchase_info.price.taxation_details
self.assertEqual(len(details), 2)
self.assertEqual(details[0].authority_name, "OHIO, STATE OF")
self.assertEqual(details[0].tax_name, "STATE SALES TAX-GENERAL MERCHANDISE")
self.assertEqual(details[0].tax_applied, D("0.58"))
self.assertEqual(details[0].fee_applied, D("0.00"))
self.assertTrue(shipping_charge.is_tax_known)
self.assertEqual(shipping_charge.excl_tax, D("14.99"))
self.assertEqual(shipping_charge.incl_tax, D("14.99"))
self.assertEqual(len(shipping_charge.components[0].taxation_details), 0)
@freeze_time("2016-04-13T16:14:44.018599-00:00")
@mock.patch("soap.get_transport")
def test_apply_taxes_nine_digits_postal_code(self, get_transport):
basket = self.prepare_basket_full_zip()
to_address = self.get_to_address_ohio_full_zip()
shipping_charge = self.get_shipping_charge()
def test_request(request):
self.assertNodeText(
request.message, p("Body/CalculateRequest/EntityID"), "TESTSANDBOX"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/DivisionID"), "42"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/CustomerType"), "08"
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/InvoiceDate"),
"2016-04-13T12:14:44.018599-04:00",
)
self.assertNodeCount(
request.message, p("Body/CalculateRequest/order/LineItems/LineItem"), 2
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/AvgUnitPrice"),
"10",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/ID"),
str(basket.all_lines()[0].id),
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/City"
),
"Anchorage",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/CountryCode"
),
"US",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/Line1"
),
"325 F st",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/PostalCode"
),
"99501",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/Plus4"
),
"2217",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipFromAddress/StateOrProvince"
),
"AK",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/City"
),
"BRINKHAVEN",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/CountryCode"
),
"US",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/Line1"
),
"200 HIGH ST",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/PostalCode"
),
"43006",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/Plus4"
),
"9000",
)
self.assertNodeText(
request.message,
p(
"Body/CalculateRequest/order/LineItems/LineItem[1]/NexusInfo/ShipToAddress/StateOrProvince"
),
"OH",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/Quantity"),
"1",
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/LineItems/LineItem[1]/SKU"),
"ABC123",
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/ProviderType"), "70"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/SourceSystem"), "Oscar"
)
self.assertNodeText(
request.message,
p("Body/CalculateRequest/order/TestTransaction"),
"true",
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/TransactionID"), "0"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/TransactionType"), "01"
)
self.assertNodeText(
request.message, p("Body/CalculateRequest/order/finalize"), "false"
)
resp = self._get_cch_response_ohio_request_full_zip(basket.all_lines()[0].id)
get_transport.return_value = self._build_transport_with_reply(
resp, test_request=test_request
)
self.assertFalse(basket.is_tax_known)
self.assertEqual(basket.total_excl_tax, D("10.00"))
CCHTaxCalculator().apply_taxes(to_address, basket, shipping_charge)
self.assertTrue(basket.is_tax_known)
self.assertEqual(basket.total_excl_tax, D("10.00"))
self.assertEqual(basket.total_incl_tax, D("10.73"))
self.assertEqual(basket.total_tax, D("0.73"))
purchase_info = basket.all_lines()[0].purchase_info
self.assertEqual(purchase_info.price.excl_tax, D("10.00"))
self.assertEqual(purchase_info.price.incl_tax, D("10.73"))
self.assertEqual(purchase_info.price.tax, D("0.73"))
details = purchase_info.price.taxation_details
self.assertEqual(len(details), 2)
self.assertEqual(details[0].authority_name, "OHIO, STATE OF")
self.assertEqual(details[0].tax_name, "STATE SALES TAX-GENERAL MERCHANDISE")
self.assertEqual(details[0].tax_applied, D("0.58"))
self.assertEqual(details[0].fee_applied, D("0.00"))
self.assertTrue(shipping_charge.is_tax_known)
self.assertEqual(shipping_charge.excl_tax, D("14.99"))
self.assertEqual(shipping_charge.incl_tax, D("14.99"))
self.assertEqual(len(shipping_charge.components[0].taxation_details), 0)
| isc |
io7m/jfunctional | com.io7m.jfunctional.core/src/main/java/com/io7m/jfunctional/Failure.java | 2898 | /*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jfunctional;
import com.io7m.jequality.annotations.EqualityStructural;
import com.io7m.jnull.NullCheck;
import com.io7m.jnull.Nullable;
/**
* <p>
* A computation that has failed.
* </p>
*
* @param <F> The type of values returned upon failure.
* @param <S> The type of values returned upon success.
*
* @see TryType
*/
@EqualityStructural
public final class Failure<F, S> implements TryType<F, S>
{
private static final long serialVersionUID = -4218541696685737451L;
private final F x;
private Failure(
final F in_x)
{
this.x = NullCheck.notNull(in_x, "Failure value");
}
/**
* Produce a new failure value.
*
* @param x The actual value
* @param <F> The type of values returned upon failure.
* @param <S> The type of values returned upon success.
*
* @return A new failure value
*
* @since 1.3.0
*/
public static <F, S> Failure<F, S> failure(
final F x)
{
return new Failure<F, S>(x);
}
@Override
public <U> U accept(
final TryVisitorType<F, S, U> v)
{
NullCheck.notNull(v, "Visitor");
return v.failure(this);
}
@Override
public <U, E extends Throwable> U acceptPartial(
final TryPartialVisitorType<F, S, U, E> v)
throws E
{
NullCheck.notNull(v, "Visitor");
return v.failure(this);
}
@Override
public boolean equals(
final @Nullable Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final Failure<?, ?> other = (Failure<?, ?>) obj;
return this.x.equals(other.x);
}
/**
* @return The value contained within.
*/
public F get()
{
return this.x;
}
@Override
public int hashCode()
{
return this.x.hashCode();
}
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("[Failure ");
builder.append(this.x);
builder.append("]");
final String s = builder.toString();
assert s != null;
return s;
}
}
| isc |
loganknecht/GlobalGameJam2015 | Assets/FullInspector2/Serializers/FullSerializer/Samples/FullSerializer/Editor/SampleFullSerializerCustomTypeEditorEditors.cs | 2220 | using UnityEditor;
using UnityEngine;
namespace FullInspector.Samples.FullSerializer {
[CustomPropertyEditor(typeof(CustomTypeEditorNonGeneric))]
public class SampleFullSerializerCustomTypeEditorEditors :
PropertyEditor<CustomTypeEditorNonGeneric> {
public override CustomTypeEditorNonGeneric Edit(Rect region, GUIContent label, CustomTypeEditorNonGeneric element, fiGraphMetadata metadata) {
EditorGUI.HelpBox(region, label.text + ": This is the non-generic editor", MessageType.Info);
return element;
}
public override float GetElementHeight(GUIContent label, CustomTypeEditorNonGeneric element, fiGraphMetadata metadata) {
return 30;
}
}
[CustomPropertyEditor(typeof(CustomTypeEditorGeneric<,>))]
public class SampleFullSerializerCustomTypeEditorEditors<T1, T2> :
PropertyEditor<CustomTypeEditorGeneric<T1, T2>> {
public override CustomTypeEditorGeneric<T1, T2> Edit(Rect region, GUIContent label, CustomTypeEditorGeneric<T1, T2> element, fiGraphMetadata metadata) {
EditorGUI.HelpBox(region, string.Format(label.text + ": This is the non-generic editor (T1={0}, T2={1})", typeof(T1).Name, typeof(T2).Name), MessageType.Info);
return element;
}
public override float GetElementHeight(GUIContent label, CustomTypeEditorGeneric<T1, T2> element, fiGraphMetadata metadata) {
return 30;
}
}
[CustomPropertyEditor(typeof(ICustomTypeEditorInherited), Inherit = true)]
public class ICustomTypeEditorInheritedEditor<TDerived> : PropertyEditor<ICustomTypeEditorInherited> {
public override ICustomTypeEditorInherited Edit(Rect region, GUIContent label, ICustomTypeEditorInherited element, fiGraphMetadata metadata) {
EditorGUI.HelpBox(region, string.Format(label.text + ": This is the inherited editor (TDerived={0})", typeof(TDerived).Name), MessageType.Info);
return element;
}
public override float GetElementHeight(GUIContent label, ICustomTypeEditorInherited element, fiGraphMetadata metadata) {
return 30;
}
}
} | isc |
gilesbradshaw/react-resolver-csp | dist/js-csp/src/impl/process.js | 3488 | "use strict";
var dispatch = require("./dispatch");
var select = require("./select");
var Channel = require("./channels").Channel;
var FnHandler = function FnHandler(f) {
this.f = f;
};
FnHandler.prototype.is_active = function () {
return true;
};
FnHandler.prototype.commit = function () {
return this.f;
};
function put_then_callback(channel, value, callback) {
var result = channel._put(value, new FnHandler(callback));
if (result && callback) {
callback(result.value);
}
}
function take_then_callback(channel, callback) {
var result = channel._take(new FnHandler(callback));
if (result) {
callback(result.value);
}
}
var Process = function Process(gen, onFinish, creator) {
this.gen = gen;
this.creatorFunc = creator;
this.finished = false;
this.onFinish = onFinish;
};
var Instruction = function Instruction(op, data) {
this.op = op;
this.data = data;
};
var TAKE = "take";
var PUT = "put";
var SLEEP = "sleep";
var ALTS = "alts";
// TODO FIX XXX: This is a (probably) temporary hack to avoid blowing
// up the stack, but it means double queueing when the value is not
// immediately available
Process.prototype._continue = function (response) {
var self = this;
dispatch.run(function () {
self.run(response);
});
};
Process.prototype._done = function (value) {
if (!this.finished) {
this.finished = true;
var onFinish = this.onFinish;
if (typeof onFinish === "function") {
dispatch.run(function () {
onFinish(value);
});
}
}
};
Process.prototype.run = function (response) {
if (this.finished) {
return;
}
// TODO: Shouldn't we (optionally) stop error propagation here (and
// signal the error through a channel or something)? Otherwise the
// uncaught exception will crash some runtimes (e.g. Node)
var iter = this.gen.next(response);
if (iter.done) {
this._done(iter.value);
return;
}
var ins = iter.value;
var self = this;
if (ins instanceof Instruction) {
switch (ins.op) {
case PUT:
var data = ins.data;
put_then_callback(data.channel, data.value, function (ok) {
self._continue(ok);
});
break;
case TAKE:
var channel = ins.data;
take_then_callback(channel, function (value) {
self._continue(value);
});
break;
case SLEEP:
var msecs = ins.data;
dispatch.queue_delay(function () {
self.run(null);
}, msecs);
break;
case ALTS:
select.do_alts(ins.data.operations, function (result) {
self._continue(result);
}, ins.data.options);
break;
}
} else if (ins instanceof Channel) {
var channel = ins;
take_then_callback(channel, function (value) {
self._continue(value);
});
} else {
this._continue(ins);
}
};
function take(channel) {
return new Instruction(TAKE, channel);
}
function put(channel, value) {
return new Instruction(PUT, {
channel: channel,
value: value
});
}
function sleep(msecs) {
return new Instruction(SLEEP, msecs);
}
function alts(operations, options) {
return new Instruction(ALTS, {
operations: operations,
options: options
});
}
exports.put_then_callback = put_then_callback;
exports.take_then_callback = take_then_callback;
exports.put = put;
exports.take = take;
exports.sleep = sleep;
exports.alts = alts;
exports.Instruction = Instruction;
exports.Process = Process; | isc |
johnwchadwick/gcmtools | nall/string/trim.hpp | 1330 | #ifdef NALL_STRING_INTERNAL_HPP
namespace nall {
//limit defaults to zero, which will underflow on first compare; equivalent to no limit
template<unsigned Limit> char* ltrim(char *str, const char *key) {
unsigned limit = Limit;
if(!key || !*key) return str;
while(strbegin(str, key)) {
char *dest = str, *src = str + strlen(key);
while(true) {
*dest = *src++;
if(!*dest) break;
dest++;
}
if(--limit == 0) break;
}
return str;
}
template<unsigned Limit> char* rtrim(char *str, const char *key) {
unsigned limit = Limit;
if(!key || !*key) return str;
while(strend(str, key)) {
str[strlen(str) - strlen(key)] = 0;
if(--limit == 0) break;
}
return str;
}
template<unsigned limit> char* trim(char *str, const char *key, const char *rkey) {
if(rkey) return ltrim<limit>(rtrim<limit>(str, rkey), key);
return ltrim<limit>(rtrim<limit>(str, key), key);
}
//remove whitespace characters from both left and right sides of string
char* strip(char *s) {
signed n = 0, p = 0;
while(s[n]) {
if(s[n] != ' ' && s[n] != '\t' && s[n] != '\r' && s[n] != '\n') break;
n++;
}
while(s[n]) s[p++] = s[n++];
s[p--] = 0;
while(p >= 0) {
if(s[p] != ' ' && s[p] != '\t' && s[p] != '\r' && s[p] != '\n') break;
p--;
}
s[++p] = 0;
return s;
}
}
#endif
| isc |
sobstel/golazon | components/Search/hooks/useAsyncDispatch.ts | 148 | import { Dispatch } from "react";
export default function useAsyncDispatch(dispatch: Dispatch<unknown>) {
return (action) => action(dispatch);
}
| isc |
utah-scs/RAMCloud | src/LinearizableObjectRpcWrapper.cc | 8017 | /* Copyright (c) 2014-2015 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ClientLeaseAgent.h"
#include "Logger.h"
#include "LinearizableObjectRpcWrapper.h"
#include "RamCloud.h"
namespace RAMCloud {
/**
* Constructor for ObjectRpcWrapper objects.
* \param ramcloud
* The RAMCloud object that governs this RPC.
* \param linearizable
* RPC will be linearizable if we set this flag true.
* \param tableId
* The table containing the desired object.
* \param key
* Variable length key that uniquely identifies the object within tableId.
* It need not be null terminated. The caller is responsible for ensuring
* that this key remains valid until the call completes.
* \param keyLength
* Size in bytes of key.
* \param responseHeaderLength
* The size of header expected in the response for this RPC;
* incoming responses will be checked here to ensure that they
* contain at least this much data, and a pointer to the header
* will be stored in the responseHeader for the use of wrapper
* subclasses.
* \param response
* Optional client-supplied buffer to use for the RPC's response;
* if NULL then we use a built-in buffer. Any existing contents
* of this buffer will be cleared automatically by the transport.
*/
LinearizableObjectRpcWrapper::LinearizableObjectRpcWrapper(
RamCloud* ramcloud, bool linearizable, uint64_t tableId,
const void* key, uint16_t keyLength, uint32_t responseHeaderLength,
Buffer* response)
: ObjectRpcWrapper(ramcloud->clientContext, tableId, key, keyLength,
responseHeaderLength, response)
, linearizabilityOn(linearizable)
, ramcloud(ramcloud)
, assignedRpcId(0)
{
}
/**
* Alternate constructor for ObjectRpcWrapper objects, in which the desired
* server is specified with a key hash, rather than a key value.
* \param ramcloud
* The RAMCloud object that governs this RPC.
* \param linearizable
* RPC will be linearizable if we set this flag true.
* \param tableId
* The table containing the desired object.
* \param keyHash
* Key hash that identifies a particular tablet (and, hence, the
* server storing that tablet).
* \param responseHeaderLength
* The size of header expected in the response for this RPC;
* incoming responses will be checked here to ensure that they
* contain at least this much data, and a pointer to the header
* will be stored in the responseHeader for the use of wrapper
* subclasses.
* \param response
* Optional client-supplied buffer to use for the RPC's response;
* if NULL then we use a built-in buffer.
*/
LinearizableObjectRpcWrapper::LinearizableObjectRpcWrapper(
RamCloud* ramcloud, bool linearizable, uint64_t tableId,
uint64_t keyHash, uint32_t responseHeaderLength, Buffer* response)
: ObjectRpcWrapper(ramcloud->clientContext, tableId, keyHash,
responseHeaderLength, response)
, linearizabilityOn(linearizable)
, ramcloud(ramcloud)
, assignedRpcId(0)
{
}
/**
* In addition to regular RPC cleanup, it marks the rpc finished in RpcTracker.
*/
LinearizableObjectRpcWrapper::~LinearizableObjectRpcWrapper()
{
if (linearizabilityOn && assignedRpcId) {
ramcloud->rpcTracker->rpcFinished(assignedRpcId);
assignedRpcId = 0;
}
}
/**
* In addition to regular RPC cancel, it marks the rpc finished in RpcTracker.
* Once an RPC is cancelled, it will not be retried nor be finished with wait().
* So we should acknowledge the RPC regardless of receipt of its response.
*/
void
LinearizableObjectRpcWrapper::cancel()
{
RpcWrapper::cancel();
if (linearizabilityOn && assignedRpcId) {
ramcloud->rpcTracker->rpcFinished(assignedRpcId);
assignedRpcId = 0;
}
}
/**
* Indicates whether a response has been received for an RPC. Used for
* asynchronous processing of RPCs. Calling this method will also ensure
* the ClientLease remains valid.
*
* \return
* True means that the RPC has finished or been canceled; #wait will
* not block. False means that the RPC is still being processed.
*/
bool
LinearizableObjectRpcWrapper::isReady()
{
// Poke the client lease to keep it valid.
ramcloud->clientLeaseAgent->poll();
return RpcWrapper::isReady();
}
/**
* Fills request header with linearizability information.
* This function should be invoked in the constructor of every linearizable
* RPC.
* \param reqHdr
* Pointer to request header to be filled with linearizability info.
*/
template <typename RpcRequest>
void
LinearizableObjectRpcWrapper::fillLinearizabilityHeader(RpcRequest* reqHdr)
{
if (linearizabilityOn) {
assignedRpcId = ramcloud->rpcTracker->newRpcId(this);
assert(assignedRpcId);
reqHdr->lease = ramcloud->clientLeaseAgent->getLease();
reqHdr->rpcId = assignedRpcId;
reqHdr->ackId = ramcloud->rpcTracker->ackId();
} else {
reqHdr->rpcId = 0; // rpcId starts from 1. 0 means non-linearizable
reqHdr->ackId = 0;
}
}
/**
* Overrides RpcWrapper::waitInternal.
* Call #RpcWrapper::waitInternal and process linearizability information.
* Marks the current RPC as finished in RpcTracker.
*
* \param dispatch
* Dispatch to use for polling while waiting.
* \param abortTime
* If Cycles::rdtsc() exceeds this time then return even if the
* RPC has not completed. All ones means wait forever.
*
* \return
* The return value is true if the RPC completed or failed, and false if
* abortTime passed with no response yet.
*
* \throw RpcCanceledException
* The RPC has previously been canceled, so it doesn't make sense
* to wait for it.
*/
bool
LinearizableObjectRpcWrapper::waitInternal(Dispatch* dispatch,
uint64_t abortTime)
{
if (!ObjectRpcWrapper::waitInternal(dispatch, abortTime)) {
return false; // Aborted by timeout. Shouldn't process RPC's response.
}
if (!linearizabilityOn || !assignedRpcId) {
return true;
}
#ifdef DEBUG
RpcState state = getState();
assert(state == FINISHED || state == CANCELED);
#endif
ramcloud->rpcTracker->rpcFinished(assignedRpcId);
assignedRpcId = 0;
return true;
}
// See RpcTracker::TrackedRpc for documentation.
void LinearizableObjectRpcWrapper::tryFinish()
{
RAMCLOUD_TEST_LOG("called");
// In this case we might as well wait.
waitInternal(ramcloud->clientContext->dispatch);
}
/*
* Following line is necessary to tell compiler to instantiate the templatized
* method "fillLinearizabilityHeader" with WireFormat::Write::Request, etc.
* This manual instantiation is necessary if the method is defined in cc file.
*/
template void LinearizableObjectRpcWrapper::fillLinearizabilityHeader
<WireFormat::Write::Request>(WireFormat::Write::Request* reqHdr);
template void LinearizableObjectRpcWrapper::fillLinearizabilityHeader
<WireFormat::Increment::Request>(WireFormat::Increment::Request* reqHdr);
template void LinearizableObjectRpcWrapper::fillLinearizabilityHeader
<WireFormat::Remove::Request>(WireFormat::Remove::Request* reqHdr);
} // namespace RAMCloud
| isc |
dcrdata/dcrdata | cmd/dcrdata/api/insight/apiroutes_test.go | 5339 | // Copyright (c) 2019-2021, The Decred developers
// See LICENSE for details.
package insight
import (
"reflect"
"testing"
"time"
apitypes "github.com/decred/dcrdata/v7/api/types"
)
func Test_dateFromStr(t *testing.T) {
ymdFormat := "2006-01-02"
today := time.Now().UTC().Truncate(24 * time.Hour)
tests := []struct {
testName string
dateStr string
wantDate time.Time
wantIsToday bool
wantErr bool
}{
{
testName: "ok not today",
dateStr: "2018-04-18",
wantDate: time.Unix(1524009600, 0).UTC(),
wantIsToday: false,
wantErr: false,
},
{
testName: "ok today",
dateStr: today.Format(ymdFormat),
wantDate: today,
wantIsToday: true,
wantErr: false,
},
{
testName: "invalid date string",
dateStr: "da future",
wantDate: time.Time{},
wantIsToday: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
gotDate, gotIsToday, err := dateFromStr(ymdFormat, tt.dateStr)
if (err != nil) != tt.wantErr {
t.Errorf("dateFromStr() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotDate, tt.wantDate) {
t.Errorf("dateFromStr() gotDate = %v, want %v", gotDate, tt.wantDate)
}
if gotIsToday != tt.wantIsToday {
t.Errorf("dateFromStr() gotIsToday = %v, want %v", gotIsToday, tt.wantIsToday)
}
})
}
}
func Test_fromToForSlice(t *testing.T) {
type args struct {
from int64
to int64
sliceLength int64
txLimit int64
}
tests := []struct {
testName string
args args
wantStart int64
wantEnd int64
wantErr bool
}{
{
testName: "ok",
args: args{
from: 0,
to: 1,
sliceLength: 2,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 2,
wantErr: false,
},
{
testName: "ok, high to",
args: args{
from: 0,
to: 3,
sliceLength: 2,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 2,
wantErr: false,
},
{
testName: "ok, high to (edge)",
args: args{
from: 0,
to: 2,
sliceLength: 2,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 2,
wantErr: false,
},
{
testName: "ok, at limit",
args: args{
from: 0,
to: 999,
sliceLength: 1000,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 1000,
wantErr: false,
},
{
testName: "ok, one element",
args: args{
from: 1,
to: 1,
sliceLength: 2,
txLimit: 1000,
},
wantStart: 1,
wantEnd: 2,
wantErr: false,
},
{
testName: "ok, high from",
args: args{
from: 1,
to: 1,
sliceLength: 1,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 1,
wantErr: false,
},
{
testName: "ok, low to",
args: args{
from: 6,
to: 1,
sliceLength: 20,
txLimit: 1000,
},
wantStart: 6,
wantEnd: 7,
wantErr: false,
},
{
testName: "empty slice",
args: args{
from: 1,
to: 1,
sliceLength: 0,
txLimit: 1000,
},
wantStart: 0,
wantEnd: 0,
wantErr: true,
},
{
testName: "over limit",
args: args{
from: 1,
to: 20,
sliceLength: 200,
txLimit: 10,
},
wantStart: 1,
wantEnd: 21,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
start, end, err := fromToForSlice(tt.args.from, tt.args.to, tt.args.sliceLength, tt.args.txLimit)
if (err != nil) != tt.wantErr {
t.Errorf("fromToForSlice() error = %v, wantErr %v", err, tt.wantErr)
return
}
if start != tt.wantStart {
t.Errorf("fromToForSlice() start = %v, want %v", start, tt.wantStart)
}
if end != tt.wantEnd {
t.Errorf("fromToForSlice() end = %v, want %v", end, tt.wantEnd)
}
})
}
}
func Test_removeSliceElements(t *testing.T) {
type outSlice []*apitypes.AddressTxnOutput
type args struct {
txOuts outSlice
inds []int
}
tests := []struct {
name string
args args
want outSlice
}{
{
name: "ok out of range inds",
args: args{
txOuts: outSlice{{Address: "i0"}},
inds: []int{6},
},
want: outSlice{{Address: "i0"}},
},
{
name: "ok two inds",
args: args{
txOuts: outSlice{{Address: "i0"}, {Address: "i1"}, {Address: "i2"},
{Address: "i3"}, {Address: "i4"}, {Address: "i5"}, {Address: "i6"}},
inds: []int{1, 6},
},
want: outSlice{{Address: "i0"}, {Address: "i5"}, {Address: "i2"},
{Address: "i3"}, {Address: "i4"}}, // [6] removed, then [1] overwritten with [5]
},
{
name: "ok emptied slice",
args: args{
txOuts: outSlice{{Address: "i0"}},
inds: []int{0},
},
want: outSlice{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := removeSliceElements(tt.args.txOuts, tt.args.inds)
if len(got) != len(tt.want) {
t.Errorf("removeSliceElements() = %v, want %v", got, tt.want)
}
for i := range got {
t.Logf("got[i]: %v", got[i])
if got[i].Address != tt.want[i].Address {
t.Errorf("got[%[1]d].Address = %[2]v, want[%[1]d].Address = %[3]v",
i, got[i].Address, tt.want[i].Address)
}
}
})
}
}
| isc |
holizz/lavender | spec/converter_spec.rb | 2837 | require 'spec_helper'
describe Lavender::Converter do
it "should render anything that isn't YAML with the default layout/processor" do
layout = <<END
<body>
<%= yield %>
</body>
END
page = <<END
%p My paragraph
END
c = Lavender::Converter.new(:page => page, :layouts => {:default => {:erb => layout}}, :defaults => {:layout => :default, :processor => :haml})
c.render.should == <<END
<body>
<p>My paragraph</p>
</body>
END
end
it "should render pages with the given template processor" do
page = <<END
---
processor: erb
layout: null
text: content
---
<p>Document <%= text %>.</p>
END
c = Lavender::Converter.new(:page => page)
c.render.should == <<END
<p>Document content.</p>
END
end
it "should render pages with a layout" do
page = <<END
---
processor: haml
layout: default
title: your face
---
%p Document content.
END
layout = <<END
%html
%head
%title= title
%body
= yield
END
c = Lavender::Converter.new(:page => page, :layouts => {:default => {:haml => layout}})
c.render.should == <<END
<html>
<head>
<title>your face</title>
</head>
<body>
<p>Document content.</p>
</body>
</html>
END
end
it "should allow mixing templating languages" do
page = <<END
---
processor: haml
layout: page
title: your face
---
%p Document content.
END
layout = <<END
<html>
<head>
<title><%= title %></title>
</head>
<body>
<%= yield %>
</body>
</html>
END
c = Lavender::Converter.new(:page => page, :layouts => {:page => {:erb => layout}})
c.render.should == <<END
<html>
<head>
<title>your face</title>
</head>
<body>
<p>Document content.</p>
</body>
</html>
END
end
it "should use a default processor and layout" do
page = <<END
---
title: your face
---
%p Document content.
END
layout = <<END
<html>
<head>
<title><%= title %></title>
</head>
<body>
<%= yield %>
</body>
</html>
END
c = Lavender::Converter.new(:page => page, :layouts => {:default => {:erb => layout}}, :defaults => {:layout => :default, :processor => :haml})
c.render.should == <<END
<html>
<head>
<title>your face</title>
</head>
<body>
<p>Document content.</p>
</body>
</html>
END
end
it "should not try to parse HAML as YAML" do
page = <<END
---
layout: null
---
%p
%img{:src => "hamsterdance.gif"}
END
c = Lavender::Converter.new(:page => page, :defaults => {:processor => :haml})
c.render.should == <<END
<p>
<img src='hamsterdance.gif'>
</p>
END
end
it "should not try to parse HAML as YAML (no preamble)" do
page = <<END
%p
%img{:src => "hamsterdance.gif"}
END
c = Lavender::Converter.new(:page => page, :defaults => {:processor => :haml})
c.render.should == <<END
<p>
<img src='hamsterdance.gif'>
</p>
END
end
end
| isc |
xdv/ripple-lib-java | ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/ocsp/Req.java | 2708 | package org.ripple.bouncycastle.ocsp;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import org.ripple.bouncycastle.asn1.ASN1Encoding;
import org.ripple.bouncycastle.asn1.DERObjectIdentifier;
import org.ripple.bouncycastle.asn1.ocsp.Request;
import org.ripple.bouncycastle.asn1.x509.X509Extension;
import org.ripple.bouncycastle.asn1.x509.X509Extensions;
public class Req
implements java.security.cert.X509Extension
{
private Request req;
public Req(
Request req)
{
this.req = req;
}
public CertificateID getCertID()
{
return new CertificateID(req.getReqCert());
}
public X509Extensions getSingleRequestExtensions()
{
return X509Extensions.getInstance(req.getSingleRequestExtensions());
}
/**
* RFC 2650 doesn't specify any critical extensions so we return true
* if any are encountered.
*
* @return true if any critical extensions are present.
*/
public boolean hasUnsupportedCriticalExtension()
{
Set extns = getCriticalExtensionOIDs();
if (extns != null && !extns.isEmpty())
{
return true;
}
return false;
}
private Set getExtensionOIDs(boolean critical)
{
Set set = new HashSet();
X509Extensions extensions = this.getSingleRequestExtensions();
if (extensions != null)
{
Enumeration e = extensions.oids();
while (e.hasMoreElements())
{
DERObjectIdentifier oid = (DERObjectIdentifier)e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (critical == ext.isCritical())
{
set.add(oid.getId());
}
}
}
return set;
}
public Set getCriticalExtensionOIDs()
{
return getExtensionOIDs(true);
}
public Set getNonCriticalExtensionOIDs()
{
return getExtensionOIDs(false);
}
public byte[] getExtensionValue(String oid)
{
X509Extensions exts = this.getSingleRequestExtensions();
if (exts != null)
{
X509Extension ext = exts.getExtension(new DERObjectIdentifier(oid));
if (ext != null)
{
try
{
return ext.getValue().getEncoded(ASN1Encoding.DER);
}
catch (Exception e)
{
throw new RuntimeException("error encoding " + e.toString());
}
}
}
return null;
}
}
| isc |
rolandpoulter/shipster | dashboard/src/machine.js | 1499 | /*jshint esnext:true*/
import {WebAPI} from './web-api';
import {App} from './app';
export class Machine {
static inject() { return [App, WebAPI]; }
constructor(app, api) {
this.app = app;
this.api = api;
}
activate(params, qs, config) {
this.app.selectedMenu = this.app.selectedMenu || 'machines';
this.app.selectedType = 'machines';
this.app.selectedSlug = params.m;
return this.api.getMachineDetails(params.m).then(machine => {
this.app.selectedId = machine.id;
this.machine = machine;
config.navModel.title = machine.name || machine.id;
this.originalJSON = JSON.stringify(machine);
var domainIds = Object.keys(machine.status);
this.linkedDomains = domainIds.map(domainId =>
this.app.domains.filter(x => x.id === domainId)[0]);
this.availableDomains = this.app.domains.filter(domain =>
domainIds.indexOf(domain.id) === -1);
});
}
get canSave() {
return this.machine.id && this.machine.name && !this.api.isRequesting;
}
save() {
this.api.saveMachine(this.machine).then(machine => {
this.machine = machine;
this.originalJSON = JSON.stringify(this.machine);
});
}
canDeactivate() {
if(this.originalJSON != JSON.stringify(this.machine)){
let result = confirm('You have unsaved changes. Are you sure you wish to leave?');
if (!result) {
this.app.selectedId = this.machine.id;
}
return result;
}
return true;
}
}
| isc |
bleepbloop/Pivy | scons/scons-local-1.2.0.d20090919/SCons/Tool/ifl.py | 2814 | """SCons.Tool.ifl
Tool-specific initialization for the Intel Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# 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.
#
__revision__ = "src/engine/SCons/Tool/ifl.py 4369 2009/09/19 15:58:29 scons"
import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
from FortranCommon import add_all_to_env
def generate(env):
"""Add Builders and construction variables for ifl to an Environment."""
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if not env.has_key('FORTRANFILESUFFIXES'):
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if not env.has_key('F90FILESUFFIXES'):
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
env['FORTRAN'] = 'ifl'
env['SHFORTRAN'] = '$FORTRAN'
env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
def exists(env):
return env.Detect('ifl')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| isc |
Martodox/cloudrm-server | src/components/automation-manager/automation-manager.js | 2229 | import { events, eventBus } from '../../services/event-bus';
export class AutomationManager {
autoEventMap = {};
autoEventMapFlat = {};
constructor(SocketServer) {
this.socketServer = SocketServer;
this.socketServer.socketIo.on('connection', socket => {
socket.on('*', payload => {
events.observer.next({payload: payload.data, remoteId: socket.handshake.query.remoteId, internal: false});
this.mapAutoEvent(payload.data, socket.handshake.query.remoteId);
this.tryAutomatedEvent(payload.data[0]);
})
});
eventBus.subscribe(event => {
if (event.payload === 'remoteDisconnected') {
delete this.autoEventMap[event.remoteId];
this.flattenEventMap()
}
});
}
tryAutomatedEvent(eventName) {
try {
if (this.autoEventMapFlat[eventName]) {
console.log(`Triggering auto Switch trigger: ${eventName}`);
const eventToSend = this.autoEventMapFlat[eventName].split(':');
this.socketServer.getRemoteConnection(eventToSend[0]).emit('invokeAction', {
device: eventToSend[1],
action: eventToSend[2]
});
}
} catch (e) {
}
}
mapAutoEvent(payload, remoteId) {
if (payload[0] !== 'availableActions') return;
payload[1]
.filter(device => device.type === 'Switch' && device.config && device.config.trigger)
.forEach(device => this.addAutoTriggerEvent(device, remoteId));
}
flattenEventMap() {
this.autoEventMapFlat = {};
Object.keys(this.autoEventMap)
.forEach(key => {
this.autoEventMapFlat = Object.assign({}, this.autoEventMapFlat, this.autoEventMap[key])
});
console.log(this.autoEventMapFlat);
}
addAutoTriggerEvent(device, remote) {
if (!this.autoEventMap[remote]) this.autoEventMap[remote] = {};
this.autoEventMap[remote][`${remote}:${device.config.trigger}:touch`] = `${remote}:${device.name}:toggleState`;
this.flattenEventMap();
}
} | isc |
sittercity/flagon | spec/flagon/inspector_spec.rb | 1200 | require 'flagon/inspector'
describe Flagon::Inspector do
let(:loader) { double(:loader, get_flag: true, exists?: true) }
subject { described_class.new(loader) }
it "can check a flag" do
expect(subject.enabled?(:a_flag)).to be true
end
it "can execute a block if the flag is enabled" do
test_object = double(:test_object)
expect(test_object).to receive(:hello)
subject.when_enabled(:a_flag) do
test_object.hello
end
end
it "returns false by default if a flag doesn't exist" do
allow(loader).to receive(:exists?).and_return false
expect(subject.enabled?(:a_flag)).to be false
end
it "can ensure a flag exists" do
allow(loader).to receive(:exists?).and_return false
expect{subject.ensure_flags_exist(:missing_flag)}.
to raise_exception described_class::FlagMissing, "The following flags are missing: missing_flag"
end
it "can ensure multiple flags exist" do
allow(loader).to receive(:exists?).and_return false
expect{subject.ensure_flags_exist(:missing_flag, :another_missing_flag)}.
to raise_exception described_class::FlagMissing, "The following flags are missing: missing_flag, another_missing_flag"
end
end
| isc |
io7m/jparasol | io7m-jparasol-tests/src/test/java/com/io7m/jparasol/tests/protobuf/ProtobufCompactedVertexShaderMetaTest.java | 9584 | /*
* Copyright © 2013 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jparasol.tests.protobuf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Assert;
import org.junit.Test;
import com.io7m.jparasol.core.GVersionES;
import com.io7m.jparasol.core.GVersionFull;
import com.io7m.jparasol.core.JPCompactedVertexShaderMeta;
import com.io7m.jparasol.core.JPCompiledShaderMetaType;
import com.io7m.jparasol.core.JPVertexShaderMetaType;
import com.io7m.jparasol.metaserializer.JPMetaDeserializerType;
import com.io7m.jparasol.metaserializer.JPMetaSerializerType;
import com.io7m.jparasol.metaserializer.JPSerializerException;
import com.io7m.jparasol.metaserializer.protobuf.JPProtobufMetaDeserializer;
import com.io7m.jparasol.metaserializer.protobuf.JPProtobufMetaSerializer;
import com.io7m.jparasol.tests.xml.XMLUncompactedFragmentShaderMetaTest;
import com.io7m.junreachable.UnreachableCodeException;
@SuppressWarnings({ "null", "resource", "static-method" }) public final class ProtobufCompactedVertexShaderMetaTest
{
private static JPCompiledShaderMetaType fromStream(
final InputStream stream)
throws JPSerializerException,
IOException
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
return d.metaDeserializeShader(stream);
}
public static JPCompiledShaderMetaType getData(
final String name)
throws JPSerializerException,
IOException
{
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class.getResourceAsStream(name);
return ProtobufCompactedVertexShaderMetaTest.fromStream(stream);
}
private static void serialize(
final OutputStream bao,
final JPCompactedVertexShaderMeta meta)
{
try {
final JPMetaSerializerType s = JPProtobufMetaSerializer.newSerializer();
s.metaSerializeCompactedVertexShader(meta, bao);
bao.flush();
bao.close();
} catch (final IOException e) {
throw new UnreachableCodeException(e);
}
}
@Test public void testGeneral_0()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream0 =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-vertex.ppsm");
final JPVertexShaderMetaType v0 = d.metaDeserializeVertexShader(stream0);
final InputStream stream1 =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-vertex-compacted.ppsm");
final JPVertexShaderMetaType v1 = d.metaDeserializeVertexShader(stream1);
Assert.assertEquals(v0.getName(), v1.getName());
}
@Test public void testRoundTrip_0()
throws Exception
{
final JPCompactedVertexShaderMeta meta0 =
(JPCompactedVertexShaderMeta) ProtobufCompactedVertexShaderMetaTest
.getData("/com/io7m/jparasol/tests/protobuf/t-actual-vertex-compacted.ppsm");
Assert.assertTrue(meta0.isCompacted());
Assert.assertEquals(2, meta0.getDeclaredVertexInputs().size());
Assert.assertEquals(3, meta0.getDeclaredVertexOutputs().size());
Assert.assertEquals(1, meta0.getDeclaredVertexParameters().size());
Assert.assertEquals(
"0cf3b92ad40b9e2a938bd7f2dd2207f067601575292325bdcb8653d6ae7481b4.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_110));
Assert.assertEquals(
"0cf3b92ad40b9e2a938bd7f2dd2207f067601575292325bdcb8653d6ae7481b4.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_120));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_130));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_140));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_150));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_330));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_400));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_410));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_420));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_430));
Assert.assertEquals(
"0f8f29aba4f434708f7b850052d5d423cbbcd59b07b5861a8d17278561e8639a.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionFull.GLSL_440));
Assert.assertEquals(
"535cddb5c74a881501548a6fdf184ef0b8467aab1b603166745d65d6263ec08f.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionES.GLSL_ES_100));
Assert.assertEquals(
"ec62defa1b0b3a48b2725bed74fd6e96fbc24a2a519705d664fa6edab6a42a4e.v",
XMLUncompactedFragmentShaderMetaTest.sourceCodeName(
meta0,
GVersionES.GLSL_ES_300));
JPCompactedVertexShaderMeta meta = meta0;
for (int index = 0; index < 3; ++index) {
final JPCompactedVertexShaderMeta meta_next;
{
final ByteArrayOutputStream bao = new ByteArrayOutputStream(1 << 14);
ProtobufCompactedVertexShaderMetaTest.serialize(bao, meta);
final ByteArrayInputStream bai =
new ByteArrayInputStream(bao.toByteArray());
meta_next =
(JPCompactedVertexShaderMeta) ProtobufCompactedVertexShaderMetaTest
.fromStream(bai);
}
Assert.assertNotSame(meta, meta_next);
Assert.assertEquals(meta, meta_next);
meta = meta_next;
}
}
@Test(expected = JPSerializerException.class) public void testWrongType_0()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-fragment.ppsm");
d.metaDeserializeVertexShaderUncompacted(stream);
}
@Test(expected = JPSerializerException.class) public void testWrongType_1()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-program.ppsm");
d.metaDeserializeVertexShaderUncompacted(stream);
}
@Test(expected = JPSerializerException.class) public void testWrongType_2()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-vertex-compacted.ppsm");
d.metaDeserializeVertexShaderUncompacted(stream);
}
@Test(expected = JPSerializerException.class) public void testWrongType_3()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-fragment-compacted.ppsm");
d.metaDeserializeVertexShaderUncompacted(stream);
}
@Test(expected = JPSerializerException.class) public void testWrongType_4()
throws Exception
{
final JPMetaDeserializerType d =
JPProtobufMetaDeserializer.newDeserializer();
final InputStream stream =
ProtobufCompactedVertexShaderMetaTest.class
.getResourceAsStream("/com/io7m/jparasol/tests/protobuf/t-actual-fragment.ppsm");
d.metaDeserializeVertexShader(stream);
}
}
| isc |
rchodava/datamill | core/src/main/java/foundation/stack/datamill/http/impl/UriTemplate.java | 3790 | package foundation.stack.datamill.http.impl;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
public class UriTemplate {
private static final String TEMPLATE_REGEX = "(:\\s*([^\\}]*)\\s*)?";
private static final String TEMPLATE_VARIABLE = "(\\w[\\w\\.-]*)";
private static final Pattern TEMPLATE_PATTERN = Pattern.compile("\\{\\s*" + TEMPLATE_VARIABLE + "\\s*" + TEMPLATE_REGEX + "\\}");
private static String stripSlashes(String uri) {
int start = 0;
if (uri.charAt(0) == '/') {
start = 1;
}
int end = uri.length() - 1;
if (uri.charAt(end) == '/') {
end--;
}
if (end > start) {
return uri.substring(start, end + 1);
}
return "";
}
private final List<UriTemplateRegion> regions = new ArrayList<>();
public UriTemplate(String template) {
computeTemplateRegions(template);
}
private void computeTemplateRegions(String template) {
template = stripSlashes(template);
int previousRegion = 0;
Matcher matcher = TEMPLATE_PATTERN.matcher(template);
while (matcher.find()) {
int regionStart = matcher.start();
int regionEnd = matcher.end();
if (previousRegion < regionStart) {
regions.add(new UriTemplateRegion(template.substring(previousRegion, regionStart)));
}
addMatchedVariableRegion(matcher);
previousRegion = regionEnd;
}
if (previousRegion < template.length()) {
regions.add(new UriTemplateRegion(template.substring(previousRegion)));
}
}
private static boolean queryStartsAt(String uri, int position) {
while (position < uri.length() && uri.charAt(position) == '/') {
position++;
}
if (position < uri.length() && uri.charAt(position) == '?') {
return true;
}
return false;
}
private void addMatchedVariableRegion(Matcher matcher) {
String variableName = matcher.group(1);
String regex = matcher.group(3);
if (regex == null) {
regions.add(new UriTemplateRegion(variableName, null));
} else {
regions.add(new UriTemplateRegion(variableName, regex));
}
}
public Map<String, String> match(String uri) {
uri = stripSlashes(uri);
HashMap<String, String> matches = null;
int uriLength = uri.length();
int position = 0;
int numberOfRegions = regions.size();
for (int i = 0; i < numberOfRegions; i++) {
UriTemplateRegion region = regions.get(i);
if (position > uriLength) {
return null;
}
int regionEnd = region.match(uri, position, i == numberOfRegions - 1);
if (regionEnd < 0) {
return null;
}
if (!region.isFixedContent()) {
if (matches == null) {
matches = new HashMap<>();
}
matches.put(region.getVariable(), uri.substring(position, regionEnd));
}
position = regionEnd;
}
if (position != uri.length() && !queryStartsAt(uri, position)) {
return null;
}
if (matches == null) {
return Collections.emptyMap();
}
return matches;
}
@Override
public String toString() {
StringBuilder template = new StringBuilder();
for (UriTemplateRegion region : regions) {
template.append(region.toString());
}
return template.toString();
}
}
| isc |
atomantic/buzzphrase | test/methods/node.js | 762 | const assert = require("chai").assert;
const exec = require("child_process").exec;
module.exports = function () {
it("runs as globally installed node app", function (done) {
exec(
"node " + __dirname + "/../../bin.js",
function (error, stdout, stderr) {
assert.isNull(error);
assert(stdout);
assert.equal("", stderr);
done();
}
);
});
it("allows format option as globally installed node app", function (done) {
exec(
"node " + __dirname + '/../../bin.js 1 "{v} {a} {N}"',
function (error, stdout, stderr) {
assert.isNull(error);
assert(stdout);
assert(stdout.split(" ").length > 1);
assert.equal("", stderr);
done();
}
);
});
};
| isc |
dennybritz/neal-react | build/components/navbar.js | 6325 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DropdownMenu = exports.DropdownToggle = exports.NavItem = exports.Navbar = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _classnames = require("classnames");
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Navbar = exports.Navbar = function (_React$Component) {
_inherits(Navbar, _React$Component);
function Navbar() {
_classCallCheck(this, Navbar);
return _possibleConstructorReturn(this, (Navbar.__proto__ || Object.getPrototypeOf(Navbar)).apply(this, arguments));
}
_createClass(Navbar, [{
key: "render",
value: function render() {
var _className = (0, _classnames2.default)("navbar neal-navbar", this.props.className);
return _react2.default.createElement(
"header",
{ className: "neal-navbar-wrapper" },
_react2.default.createElement(
"nav",
{ className: _className },
_react2.default.createElement(
"div",
{ className: "container" },
_react2.default.createElement(
"button",
{ className: "navbar-toggler hidden-md-up", type: "button", "data-toggle": "collapse",
"data-target": "#mobile-nav" },
"\u2630"
),
_react2.default.createElement(
"a",
{ className: "navbar-brand hidden-sm-down", href: "/" },
this.props.brand
),
_react2.default.createElement(
"div",
{ className: "navbar-toggleable-sm hidden-sm-down", id: "header-nav" },
_react2.default.createElement(
"ul",
{ className: "nav navbar-nav pull-right" },
this.props.children
)
),
_react2.default.createElement(
"div",
{ className: "collapse navbar-toggleable-sm hidden-md-up neal-mobile-nav", id: "mobile-nav" },
_react2.default.createElement(
"ul",
{ className: "nav navbar-nav" },
this.props.children
)
)
)
)
);
}
}]);
return Navbar;
}(_react2.default.Component);
Navbar.propTypes = {
brand: _react2.default.PropTypes.node.isRequired
};
var NavItem = exports.NavItem = function (_React$Component2) {
_inherits(NavItem, _React$Component2);
function NavItem() {
_classCallCheck(this, NavItem);
return _possibleConstructorReturn(this, (NavItem.__proto__ || Object.getPrototypeOf(NavItem)).apply(this, arguments));
}
_createClass(NavItem, [{
key: "render",
value: function render() {
var _className = (0, _classnames2.default)("nav-item", { dropdown: this.props.dropdown }, this.props.className);
return _react2.default.createElement(
"li",
_extends({}, this.props, { className: _className }),
this.props.children
);
}
}]);
return NavItem;
}(_react2.default.Component);
NavItem.propTypes = {
dropdown: _react2.default.PropTypes.bool
};
var DropdownToggle = exports.DropdownToggle = function (_React$Component3) {
_inherits(DropdownToggle, _React$Component3);
function DropdownToggle() {
_classCallCheck(this, DropdownToggle);
return _possibleConstructorReturn(this, (DropdownToggle.__proto__ || Object.getPrototypeOf(DropdownToggle)).apply(this, arguments));
}
_createClass(DropdownToggle, [{
key: "render",
value: function render() {
return _react2.default.createElement(
"a",
_extends({ className: "nav-link", "data-toggle": "dropdown", role: "button" }, this.props),
this.props.children
);
}
}]);
return DropdownToggle;
}(_react2.default.Component);
var DropdownMenu = exports.DropdownMenu = function (_React$Component4) {
_inherits(DropdownMenu, _React$Component4);
function DropdownMenu() {
_classCallCheck(this, DropdownMenu);
return _possibleConstructorReturn(this, (DropdownMenu.__proto__ || Object.getPrototypeOf(DropdownMenu)).apply(this, arguments));
}
_createClass(DropdownMenu, [{
key: "render",
value: function render() {
return _react2.default.createElement(
"div",
_extends({ className: "dropdown-menu" }, this.props),
this.props.children
);
}
}]);
return DropdownMenu;
}(_react2.default.Component); | isc |
versatica/mediasoup | node/tests/test-multiopus.js | 5345 | const { toBeType } = require('jest-tobetype');
const mediasoup = require('../lib/');
const { UnsupportedError } = require('../lib/errors');
const { createWorker } = mediasoup;
expect.extend({ toBeType });
let worker;
let router;
let transport;
const mediaCodecs = [
{
kind : 'audio',
mimeType : 'audio/multiopus',
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
];
const audioProducerOptions = {
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
],
headerExtensions :
[
{
uri : 'urn:ietf:params:rtp-hdrext:sdes:mid',
id : 10
},
{
uri : 'urn:ietf:params:rtp-hdrext:ssrc-audio-level',
id : 12
}
]
}
};
const consumerDeviceCapabilities = {
codecs :
[
{
mimeType : 'audio/multiopus',
kind : 'audio',
preferredPayloadType : 100,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
],
headerExtensions :
[
{
kind : 'audio',
uri : 'urn:ietf:params:rtp-hdrext:sdes:mid',
preferredId : 1,
preferredEncrypt : false
},
{
kind : 'audio',
uri : 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time', // eslint-disable-line max-len
preferredId : 4,
preferredEncrypt : false
},
{
kind : 'audio',
uri : 'urn:ietf:params:rtp-hdrext:ssrc-audio-level',
preferredId : 10,
preferredEncrypt : false
}
]
};
beforeAll(async () =>
{
worker = await createWorker();
router = await worker.createRouter({ mediaCodecs });
transport = await router.createWebRtcTransport(
{
listenIps : [ '127.0.0.1' ]
});
});
afterAll(() => worker.close());
test('produce/consume succeeds', async () =>
{
const audioProducer = await transport.produce(audioProducerOptions);
expect(audioProducer.rtpParameters.codecs).toEqual([
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
},
rtcpFeedback : []
}
]);
expect(router.canConsume({
producerId : audioProducer.id,
rtpCapabilities : consumerDeviceCapabilities
}))
.toBe(true);
const audioConsumer = await transport.consume({
producerId : audioProducer.id,
rtpCapabilities : consumerDeviceCapabilities
});
expect(audioConsumer.rtpParameters.codecs).toEqual([
{
mimeType : 'audio/multiopus',
payloadType : 100,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
},
rtcpFeedback : []
}
]);
audioProducer.close();
audioConsumer.close();
}, 2000);
test('fails to produce wrong parameters', async () =>
{
await expect(transport.produce({
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 2,
'coupled_streams' : 2
}
}
]
}
}))
.rejects
.toThrow(UnsupportedError);
await expect(transport.produce({
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 1
}
}
]
}
}))
.rejects
.toThrow(UnsupportedError);
}, 2000);
test('fails to consume wrong channels', async () =>
{
const audioProducer = await transport.produce(audioProducerOptions);
const localConsumerDeviceCapabilities = {
codecs :
[
{
mimeType : 'audio/multiopus',
kind : 'audio',
preferredPayloadType : 100,
clockRate : 48000,
channels : 8,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
]
};
expect(!router.canConsume({
producerId : audioProducer.id,
rtpCapabilities : localConsumerDeviceCapabilities
}))
.toBe(true);
await expect(transport.consume({
producerId : audioProducer.id,
rtpCapabilities : localConsumerDeviceCapabilities
}))
.rejects
.toThrow(Error);
audioProducer.close();
}, 2000);
| isc |
osmlab/osmlint | validators/mixedLayer/map.js | 5984 | 'use strict';
var turf = require('@turf/turf');
var rbush = require('rbush');
var _ = require('underscore');
var flatten = require('geojson-flatten');
module.exports = function(tileLayers, tile, writeData, done) {
var layer = tileLayers.osm.osm;
var listOfHighways = {};
var highwaysBboxes = [];
var majorRoads = {
motorway: true,
trunk: true,
primary: true,
secondary: true,
tertiary: true,
motorway_link: true,
trunk_link: true,
primary_link: true,
secondary_link: true,
tertiary_link: true
};
var minorRoads = {
unclassified: true,
residential: true,
living_street: true,
service: true,
road: true
};
var pathRoads = {
pedestrian: true,
track: true,
footway: true,
path: true,
cycleway: true,
steps: true
};
var preserveType = {};
preserveType = _.extend(preserveType, majorRoads);
preserveType = _.extend(preserveType, minorRoads);
// preserveType = _.extend(preserveType, pathRoads);
var osmlint = 'mixedlayer';
for (var i = 0; i < layer.features.length; i++) {
var val = layer.features[i];
var id = val.properties['@id'];
if (preserveType[val.properties.highway]) {
if (val.geometry.type === 'LineString') {
var idWayL = id + 'L';
var LineBbox = objBbox(val, idWayL);
highwaysBboxes.push(LineBbox);
listOfHighways[idWayL] = val;
} else if (val.geometry.type === 'MultiLineString') {
var arrayWays = flatten(val);
for (var f = 0; f < arrayWays.length; f++) {
if (arrayWays[f].geometry.type === 'LineString') {
var idWayM = id + 'M' + f;
var multiLineBbox = objBbox(arrayWays[f], idWayM);
highwaysBboxes.push(multiLineBbox);
arrayWays[f].properties = val.properties;
listOfHighways[idWayM] = arrayWays[f];
}
}
}
}
}
var highwaysTree = rbush(highwaysBboxes.length);
highwaysTree.load(highwaysBboxes);
var output = {};
for (var j = 0; j < highwaysBboxes.length; j++) {
var highwayToEvaluate = listOfHighways[highwaysBboxes[j].id];
//Check only highways which has layer
if (
highwayToEvaluate.properties.layer &&
highwayToEvaluate.properties.layer !== '0' &&
highwayToEvaluate.geometry.coordinates.length > 2
) {
var overlapHighwaysBboxes = highwaysTree.search(highwaysBboxes[j]);
var coordHighwayToEvaluate = highwayToEvaluate.geometry.coordinates;
coordHighwayToEvaluate.splice(coordHighwayToEvaluate.length - 1, 1);
coordHighwayToEvaluate.splice(0, 1);
var objHighwayToEvaluate = {};
for (var m = 0; m < coordHighwayToEvaluate.length; m++) {
objHighwayToEvaluate[coordHighwayToEvaluate[m].join('-')] = true;
}
for (var k = 0; k < overlapHighwaysBboxes.length; k++) {
var overlapHighway = listOfHighways[overlapHighwaysBboxes[k].id];
//Compare layers between value and overlap highway
if (
highwayToEvaluate.properties['@id'] !==
overlapHighway.properties['@id'] &&
highwayToEvaluate.properties.layer !==
overlapHighway.properties.layer &&
overlapHighway.geometry.coordinates.length > 2
) {
var coordOverlaphighway = overlapHighway.geometry.coordinates;
coordOverlaphighway.splice(coordOverlaphighway.length - 1, 1);
coordOverlaphighway.splice(0, 1);
var coordIntersection = [];
for (var z = 0; z < coordOverlaphighway.length; z++) {
if (objHighwayToEvaluate[coordOverlaphighway[z].join('-')]) {
coordIntersection = coordOverlaphighway[z];
}
}
if (coordIntersection.length > 0) {
var intersectionPoint = turf.point(coordIntersection);
var props = {
_fromWay: highwayToEvaluate.properties['@id'],
_toWay: overlapHighway.properties['@id'],
_osmlint: osmlint,
_type: classification(
majorRoads,
minorRoads,
pathRoads,
highwayToEvaluate.properties.highway,
overlapHighway.properties.highway
)
};
//Add osmlint properties
intersectionPoint.properties = props;
highwayToEvaluate.properties._osmlint = osmlint;
overlapHighway.properties._osmlint = osmlint;
output[highwayToEvaluate.properties['@id']] = highwayToEvaluate;
output[overlapHighway.properties['@id']] = overlapHighway;
output[
highwayToEvaluate.properties['@id'] +
overlapHighway.properties['@id']
] = intersectionPoint;
}
}
}
}
}
var result = _.values(output);
if (result.length > 0) {
var fc = turf.featureCollection(result);
writeData(JSON.stringify(fc) + '\n');
}
done(null, null);
};
function classification(major, minor, path, fromHighway, toHighway) {
if (major[fromHighway] && major[toHighway]) {
return 'major-major';
} else if (
(major[fromHighway] && minor[toHighway]) ||
(minor[fromHighway] && major[toHighway])
) {
return 'major-minor';
} else if (
(major[fromHighway] && path[toHighway]) ||
(path[fromHighway] && major[toHighway])
) {
return 'major-path';
} else if (minor[fromHighway] && minor[toHighway]) {
return 'minor-minor';
} else if (
(minor[fromHighway] && path[toHighway]) ||
(path[fromHighway] && minor[toHighway])
) {
return 'minor-path';
} else if (path[fromHighway] && path[toHighway]) {
return 'path-path';
}
}
function objBbox(obj, id) {
var bboxExtent = ['minX', 'minY', 'maxX', 'maxY'];
var bbox = {};
var valBbox = turf.bbox(obj);
for (var d = 0; d < valBbox.length; d++) {
bbox[bboxExtent[d]] = valBbox[d];
}
bbox.id = id || obj.properties['@id'];
return bbox;
}
| isc |
r3mus/lodash-uuid | index.js | 3145 | (function () {
var isNode = typeof module !== 'undefined' &&
typeof module.exports !== 'undefined',
_;
if (isNode) {
_ = require('lodash').runInContext();
}
else {
// browser environment
_ = window._;
}
var mixins = (function () {
var extendWith = {};
/**
* _.uuid
*
* Usage:
* _.uuid()
* Produces:
* '9716498c-45df-47d2-8099-3f678446d776'
*
* Generates an RFC 4122 version 4 uuid
* @see http://stackoverflow.com/a/8809472
* @returns {String} the generated uuid
*/
extendWith.uuid = function () {
var d = _.now();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + _.random(16)) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
};
/**
* _.isUuid4
*
* Usage:
* _.isUuid4(_.uuid())
* Produces:
* true|false
*
* Validates a version 4 uuid string
* @param {String} uuid - the uuid under test
* @returns {Boolean} true if the uuid under test is a valid uuid
**/
extendWith.isUuid4 = function (uuid) {
var re = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return re.test(uuid);
};
/**
* _.isUuid
*
* Usage:
* _.isUuid(_.uuid())
* Produces:
* true|false
*
* Validates any version uuid string
* @param {String} uuid - the uuid under test
* @returns {Boolean} true if the uuid under test is a valid uuid
**/
extendWith.isUuid = function (uuid) {
var re = /^([a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}?)$/i;
return re.test(uuid);
};
/**
* _.compactObject
*
* Usage:
* var obj = {a: false, b: 3, c: ''};
* _.compactObject(obj)
* Produces:
* {b: 3}
*
* Removes properties from an object where the value is falsy.
* Like _.compact but for objects
* @param {Object} obj - the object to remove falsy properties from
* @returns {Object} the object with falsy properties removed
**/
return extendWith;
})();
/**
* bootstrap mixins for node and the browser
* For the browser: lodash must be explicitly included above
* this library
* For node: this library will wrap lodash so there is no
* need to include lodash
*/
if (isNode) {
_.mixin(mixins, {'chain': true});
module.exports = _;
}
else {
// browser environment
if (typeof _ === 'function') {
_.mixin(mixins, {'chain': true});
}
else {
throw new Error('lodash must be included before lodash-extensions.');
}
}
})();
| isc |
MiguelAngelCifredo/AmigoInvisible | app/src/main/java/utils/Comunicador.java | 242 | package utils;
public class Comunicador {
private static Object objeto = null;
public static void setObjeto(Object newObjeto) {
objeto = newObjeto;
}
public static Object getObjeto() {
return objeto;
}
} | isc |
MirekSz/webpack-es6-ts | app/mods/mod1317.js | 76 | import mod1316 from './mod1316';
var value=mod1316+1;
export default value;
| isc |
jaysoo/react-transact | test/components-test.js | 5599 | require('./setup')
const mount = require('enzyme').mount
const createStore = require('redux').createStore
const connect = require('react-redux').connect
const Provider = require('react-redux').Provider
const React = require('react')
const test = require('tape')
const sinon = require('sinon')
const RunContext = require('../index').RunContext
const transact = require('../index').transact
const Task = require('../index').Task
const taskCreator = require('../index').taskCreator
const h = React.createElement
test('transact decorator (empty)', (t) => {
const resolve = () => {}
const factory = transact((state, props) => [])
t.ok(typeof factory === 'function', 'returns a higher-order component')
const Wrapped = factory(Greeter)
t.ok(typeof Wrapped.displayName === 'string', 'returns a React component')
const result = mount(
h(Wrapped, {
transact: { resolve },
name: 'Alice'
})
)
t.ok(result.find('.message').length > 0)
t.equal(result.find('.message').text(), 'Hello Alice!')
// Guards
t.throws(() => {
mount(
h(Wrapped, {
transact: null,
name: 'Alice'
})
)
}, /RunContext/, 'transact must be present in context')
t.end()
})
test('transact decorator (with tasks)', (t) => {
const resolve = sinon.spy()
const Empty = () => h('p')
const mapTasks = (state, props) => [
Task.resolve({ type: 'GOOD', payload: 42 })
]
const Wrapped = transact(mapTasks)(Empty)
mount(
h('div', {}, [
h(Wrapped, { transact: { resolve } }),
h(Wrapped, { transact: { resolve } })
])
)
t.equal(resolve.callCount, 2, 'calls resolve for each @transact component')
t.equal(resolve.firstCall.args[0], mapTasks, 'calls resolve with task run mapper')
t.equal(resolve.secondCall.args[0], mapTasks, 'calls resolve with task run mapper')
t.end()
})
test('transact decorator (run on mount)', (t) => {
const resolve = sinon.spy()
const Empty = () => h('p')
const mapTasks = (state, props) => [
Task.resolve({ type: 'GOOD', payload: 42 })
]
const Wrapped = transact(mapTasks, { onMount: true })(Empty)
mount(
h('div', {}, [
h(Wrapped, { transact: { resolve } })
])
)
t.equal(resolve.firstCall.args[0], mapTasks, 'calls resolve with task run mapper')
t.deepEqual(resolve.firstCall.args[1], { immediate: true }, 'enables immediate flag')
t.end()
})
test('RunContext with transact decorator (integration)', (t) => {
const store = makeStore({
message: ''
})
const dispatchSpy = sinon.spy(store, 'dispatch')
const Message = ({ message }) => h('p', {}, [ message ])
const mapTasks = (state, props) => [
Task.resolve({ type: MESSAGE, payload: 'Hello Alice!' }),
taskCreator(ERROR, MESSAGE, () => new Promise((res, rej) => {
setTimeout(() => {
rej('Boo-urns')
}, 10)
}))()
]
const Wrapped = transact(mapTasks)(
connect((state) => ({ message: state.message }))(
Message
)
)
const WrappedRunOnMount = transact(() => [
Task.resolve({ type: MESSAGE, payload: 'Bye!' })
], { onMount: true })(
connect((state) => ({ message: state.message }))(
Message
)
)
class Root extends React.Component {
constructor(props) {
super(props)
this.state = { showSecondWrappedElement: false }
}
render() {
return (
h(Provider, { store },
h(RunContext, {
onResolve: (results) => {
if (!this.state.showSecondWrappedElement) {
// This is the first time onResolve is called, which should only dispatch
// the Wrapped component.
t.equal(results.length, 2, 'resolves with results of tasks')
t.equal(wrapper.text(), 'Hello Error!', 'updates state after task completion')
t.equal(dispatchSpy.callCount, 2)
t.deepEqual(dispatchSpy.firstCall.args[0], {
type: MESSAGE,
payload: 'Hello Alice!'
}, 'dispatches first action')
t.deepEqual(dispatchSpy.secondCall.args[0], {
type: ERROR,
payload: 'Boo-urns'
}, 'dispatches second action')
// Now show the second `onMount: true` element
this.setState({ showSecondWrappedElement: true })
} else {
// This is the second time the onResolve is called, which is caused by
// the WrappedRunOnMount being mounted with `transact(..., { onMount: true })`.
t.equal(dispatchSpy.callCount, 3)
t.deepEqual(dispatchSpy.thirdCall.args[0], {
type: MESSAGE,
payload: 'Bye!'
}, 'supports dispatches on mount')
t.end()
}
}
},
h('div', {}, [
h(Wrapped),
this.state.showSecondWrappedElement ? h(WrappedRunOnMount) : null
])
)
)
)
}
}
const element = h(Root)
const wrapper = mount(element)
})
const MESSAGE = 'MESSAGE'
const ERROR = 'ERROR'
const Greeter = ({ name }) => h('p', {
className: 'message'
}, [`Hello ${name}!`])
const makeStore = (initialState = {}) => createStore((state = {}, action) => {
switch (action.type) {
case MESSAGE:
return { message: action.payload }
case ERROR:
return { message: 'Hello Error!', prev: state.message }
default:
return state
}
}, initialState) | isc |
TealCube/strife | src/main/java/land/face/strife/managers/SpawnerManager.java | 3904 | package land.face.strife.managers;
import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils;
import java.util.HashMap;
import java.util.Map;
import land.face.strife.StrifePlugin;
import land.face.strife.data.Spawner;
import land.face.strife.data.StrifeMob;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class SpawnerManager {
private StrifePlugin plugin;
private final Map<String, Spawner> spawnerMap;
public SpawnerManager(StrifePlugin plugin) {
this.plugin = plugin;
spawnerMap = new HashMap<>();
}
public Map<String, Spawner> getSpawnerMap() {
return spawnerMap;
}
public void setSpawnerMap(Map<String, Spawner> spawnerMap) {
this.spawnerMap.clear();
this.spawnerMap.putAll(spawnerMap);
}
public void addSpawner(String id, Spawner spawner) {
this.spawnerMap.put(id, spawner);
}
public void removeSpawner(String id) {
this.spawnerMap.remove(id);
}
public void addRespawnTime(LivingEntity livingEntity) {
for (Spawner spawner : spawnerMap.values()) {
spawner.addRespawnTimeIfApplicable(livingEntity);
}
}
public void spawnSpawners() {
for (Spawner s : spawnerMap.values()) {
if (s.getUniqueEntity() == null || s.getLocation() == null) {
continue;
}
int maxMobs = s.getAmount();
for (long stamp : s.getRespawnTimes()) {
if (System.currentTimeMillis() > stamp) {
s.getRespawnTimes().remove(stamp);
}
}
int existingMobs = s.getRespawnTimes().size() + s.getEntities().size();
if (existingMobs >= maxMobs) {
continue;
}
if (!isChuckLoaded(s)) {
continue;
}
int mobDiff = maxMobs - existingMobs;
while (mobDiff > 0) {
StrifeMob mob = plugin.getUniqueEntityManager()
.spawnUnique(s.getUniqueEntity(), s.getLocation());
if (mob == null || mob.getEntity() == null || !mob.getEntity().isValid()) {
Bukkit.getLogger().warning("Spawner failed to spawn unique! " + s.getId());
continue;
}
if (mob.getMods().size() >= 2) {
announceSpawnToNearbyPlayers(mob, s.getLocation());
}
if (StringUtils.isBlank(s.getUniqueEntity().getMount())
&& mob.getEntity().getVehicle() != null) {
mob.getEntity().getVehicle().remove();
}
mob.setDespawnOnUnload(true);
s.addEntity(mob.getEntity());
// Random displacement to prevent clumping
if (s.getUniqueEntity().getDisplaceMultiplier() != 0) {
Vector vec = new Vector(-1 + Math.random() * 2, 0.1, -1 + Math.random() * 2).normalize();
vec.multiply(s.getUniqueEntity().getDisplaceMultiplier());
mob.getEntity().setVelocity(vec);
mob.getEntity().getLocation().setDirection(mob.getEntity().getVelocity().normalize());
}
mobDiff--;
}
}
}
private void announceSpawnToNearbyPlayers(StrifeMob mob, Location location) {
for (Player p : Bukkit.getOnlinePlayers()) {
if (location.getWorld() != p.getWorld()) {
continue;
}
Vector diff = location.toVector().subtract(p.getLocation().toVector());
if (diff.lengthSquared() < 6400) {
p.playSound(location, Sound.BLOCK_BEACON_AMBIENT, 100, 0.5F);
MessageUtils.sendMessage(p,
"&7&o&lWoah!! &f" + mob.getEntity().getCustomName() + "&f has spawned nearby!");
}
}
}
public void cancelAll() {
for (Spawner spawner : spawnerMap.values()) {
spawner.cancel();
}
}
private boolean isChuckLoaded(Spawner spawner) {
return spawner.getLocation().getWorld().isChunkLoaded(spawner.getChunkX(), spawner.getChunkZ());
}
}
| isc |
memakeit/mmi-form | classes/mmi/form/plugin/jquery/validation.php | 154 | <?php defined('SYSPATH') or die('No direct script access.');
class MMI_Form_Plugin_JQuery_Validation extends Kohana_MMI_Form_Plugin_JQuery_Validation {}
| isc |
tabone/dvc | cli.js | 1435 | #!/usr/bin/env node
'use strict'
const fs = require('fs')
const DVC = require('./index')
const argv = require('minimist')(process.argv.slice(2))
getModuleNames()
.then(getOutdatedDeps)
.catch((err) => {
if (err.code === 'ENOENT') {
console.log('usage:')
console.log(' dvc [--registry <url>] [<pkg-name>[ <pkg-name>]]')
console.log(' or call it within a node module')
}
})
function getModuleNames () {
return new Promise((resolve, reject) => {
if (argv._.length > 0) return resolve(argv._)
fs.readFile(`${process.cwd()}/package.json`, (err, data) => {
if (err) return reject(err)
const packageJSON = JSON.parse(data)
return resolve([packageJSON.name])
})
})
}
function getOutdatedDeps (moduleNames) {
const config = {
registry: argv.registry
}
const dvc = new DVC(config)
console.info(`Checking the dependencies of: ${moduleNames.join(', ')}`)
dvc.check.apply(dvc, moduleNames)
.then((info) => {
const modulesName = Object.keys(info)
modulesName.forEach((moduleName) => {
console.info(`+ ${moduleName}:`)
info[moduleName].forEach((depEntry) => {
const depName = Object.keys(depEntry)
const dep = depEntry[depName]
console.info(`| + ${depName}`)
console.info(`| | + using: ${dep.using}`)
console.info(`| | + latest: ${dep.latest}`)
})
})
})
}
| isc |
Hobbit71/oc-registry | node_modules/oc/client/settings.js | 272 | 'use strict';
module.exports = {
messages: {
componentMissing: 'Configuration is not valid - Component not found',
registryUrlMissing: 'Configuration is not valid - Registry location not found',
serverSideRenderingFail: 'Server-side rendering failed'
}
}; | isc |
mike-burns/libtls.rb | lib/libtls/config.rb | 3854 | require 'libtls/raw'
require 'libtls/exn'
module LibTLS
##
# A TLS configuration
#
# This object is an abstraction over the libtls configuration. It can be used
# as a shorthand for configuring the struct tls context.
#
# config = LibTLS::Config.new(
# ca_path: '/etc/ssl',
# key_mem: [key_ptr, 512]
# )
# LibTLS::Raw.tls_configure(ctx, config.as_raw)
# config.free
class Config
##
# Keys that can be configured
#
# This is derived from the +tls_config_set_*+ functions in {LibTLS::Raw}.
VALID_SET_CONFIGS = %i(
ca_file ca_path ca_mem cert_file cert_mem ciphers dheparams ecdhecurve
key_file key_mem protocols verify_depth
)
##
# Return a new instance of Config
#
# @param [Hash] config_hash the Ruby representation of the configuration. The
# keys are any of {VALID_SET_CONFIGS}; the value is either a scalar value,
# or an array. The array is splatted into the appropriate C function.
#
# @option config_hash [String] ca_file The filename used to load a file containing
# the root certificates. (_Client_)
# @option config_hash [String] ca_path The path (directory) which should be
# searched for root certificates. (_Client_)
# @option config_hash [[FFI::Pointer, Fixnum]] ca_mem Set the root certificates
# directly from memory. (_Client_)
# @option config_hash [String] cert_file Set file from which the public
# certificate will be read. (_Client_ _and_ _server_)
# @option config_hash [[FFI::Pointer, Fixnum]] cert_mem Set the public
# certificate directly from memory. (_Client_ _and_ _server_)
# @option config_hash [String] ciphers Set the list of ciphers that may be
# used. (_Client_ _and_ _server_)
# @option config_hash [String] dheparams Set the dheparams option to either
# "none" (0), "auto" (-1), or "legacy" (1024). The default is "none".
# (_Server_)
# @option config_hash [String] ecdhecurve Set the ecdhecurve option to one of
# "none" (+NID_undef+), "auto" (-1), or any NID value understood by
# OBJ_txt2nid (3). (_Server_)
# @option config_hash [String] keyfile Set the file from which the private
# key will be read. (_Server_)
# @option config_hash [[FFI::Pointer, Fixnum]] key_mem Directly set the
# private key from memory. (_Server_)
# @option config_hash [Fixnum] protocols Sets which versions of the protocol
# may be used, as documented in {LibTLS::Raw#tls_config_set_protocols}.
# (_Client_ _and_ _server_)
# @option config_hash [Fixnum] verify_depth Set the verify depth as
# documented under SSL_CTX_set_verify_depth(3). (_Client_)
def initialize(config_hash)
@config_hash = config_hash
end
##
# Convert this object into the C representation
#
# This builds a struct tls_config pointer, sets the values on it as dictated
# by the hash passed in, and returns the struct tls_config pointer.
#
# The return value must be freed using {#free}.
#
# @return [FFI::Pointer] the completed struct tls_config pointer
# @raise [LibTLS::UnknownCError] if +tls_config_new+ or the appropriate
# +tls_config_set_*+ fails
def as_raw
@raw_config ||= buld_raw_config
end
##
# Release any memory held on to by the C library
#
# This method must be called when finished.
def free
LibTLS::Raw.tls_config_free(as_raw)
end
private
def buld_raw_config
if (raw = LibTLS::Raw.tls_config_new).null?
raise LibTLS::UnknownCError, "tls_config_new"
end
valid_config_hash.each do |key, value|
ret = LibTLS::Raw.send("tls_config_set_#{key}", raw, *value)
if ret && ret < 0
raise LibTLS::UnknownCError, "tls_config_set_#{key}"
end
end
raw
end
def valid_config_hash
@config_hash.select do |key, value|
VALID_SET_CONFIGS.include?(key)
end
end
end
end
| isc |
TMROTV/SocialCG | client/controllers/home.js | 3394 | 'use strict';
module.exports = function (app) {
var c = function ($scope, remoteService, $interval) {
var messages = remoteService.messages;
var approvals = remoteService.approvals;
var onair = remoteService.onair;
$scope.unapproveall = function(){
approvals.remove('all', function (err, message) {
if(err)
alert(err);
});
};
$scope.clearcaspar = function(){
onair.remove('casparclear');
};
$scope.approvemessage = function (id) {
approvals.create({id:id}, function (err, message) {
if(err)
alert(err);
});
};
$scope.unapprovemessage = function (id) {
approvals.remove(id, function (err, message) {
if(err)
alert(err);
});
};
$scope.sendtoair = function(id){
onair.create({id:id}, function (err, message) {
if(err)
alert(err);
});
};
$scope.myData = [];
$scope.gridOpts = {
enableFiltering: true,
showFilter: true,
showFooter: true,
enableRowSelection: false,
multiSelect: false,
//rowHeight: 50,
columnDefs: [
{ field: 'message', displayName: 'Message',width:'*' },
{ field: 'sourcedate', displayName: 'Time',width:'*' },
{ field: 'handle', displayName: 'Handle',width:'*' },
{ field: 'actions', displayName: 'Actions',width:'230'
,cellTemplate: '<div>'
+ '<button class="btn btn-xs btn-primary" ng-disabled="row.entity.approved" ng-click="approvemessage(row.entity._id); $event.stopPropagation();">Approve</button>'
+ ' <button class="btn btn-xs btn-primary" ng-hide="!row.entity.approved" ng-disabled="!row.entity.approved || row.entity.onair" ng-click="unapprovemessage(row.entity._id); $event.stopPropagation();">Unapprove</button>'
+ ' <button class="btn btn-xs btn-warning" ng-hide="!row.entity.approved" ng-disabled="row.entity.onair" ng-click="sendtoair(row.entity._id); $event.stopPropagation();">Send To Air</button>'
+ '</div>'
}
],
data: 'myData'
};
messages.find({}, function (err, messages) {
$scope.$apply(function () {
angular.forEach(messages, function (message) {
$scope.myData.push(message);
});
});
});
messages.on('created', function (message) {
$scope.$apply(function () {
$scope.myData.push(message);
});
});
var update = function (updated) {
angular.forEach($scope.myData, function (message, index) {
if (message._id === updated._id) {
$scope.$apply(function () {
angular.extend(message, updated);
$scope.myData[index] = message;
});
}
});
}
messages.on('updated', update);
messages.on('patched', update);
};
app.controller('homeCtrl', c);
return c;
}; | isc |
thaelina/Screeps-ThaeAI | src/creep/setup/worker.ts | 1406 | 'use strict';
import {CreepSetup} from './base';
let setup: CreepSetup = new CreepSetup('worker');
setup.minRCL = 1;
setup.RCL = {
1: {
maxSpawned: 6,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 0,
minEnergy: 200,
weight: 500
},
2: {
maxSpawned: 8,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 1,
minEnergy: 200,
weight: 500
},
3: {
maxSpawned: 3,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 2,
minEnergy: 200,
weight: 999
},
4: {
maxSpawned: 3,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 9,
minEnergy: 200,
weight: 999
},
5: {
maxSpawned: 2,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 9,
minEnergy: 200,
weight: 999
},
6: {
maxSpawned: 1,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 9,
minEnergy: 200,
weight: 999
},
7: {
maxSpawned: 1,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 9,
minEnergy: 200,
weight: 999
},
8: {
maxSpawned: 1,
baseBody: [WORK, CARRY, MOVE],
multiBody: [WORK, CARRY, MOVE],
maxMulti: 9,
minEnergy: 200,
weight: 999
}
};
CreepSetups['worker'] = setup; | isc |
simple-statistics/simple-statistics | src/logit.d.ts | 118 | /**
* https://simplestatistics.org/docs/#logit
*/
declare function logit(p: number): number;
export default logit;
| isc |
evshiron/ingress-model-viewer | src/orbit-controls.js | 9496 | import { setParams } from './utils';
import { vec3 } from 'gl-matrix';
const PI_HALF = Math.PI / 2.0;
const MIN_LOG_DIST = 5.0;
function cloneTouch(touch)
{
return {identifier: touch.identifier, x: touch.clientX, y: touch.clientY};
}
function getTouchIndex(touches, touch)
{
for(var i = 0; i < touches.length; i++)
{
if(touches[i].identifier == touch.identifier)
{
return i;
}
}
return -1;
}
/**
* Camera controls for controlling a camera that orbits a fixed point,
* with variable position and depth.
*
* This is a port of the THREE.js OrbitControls found with the webgl globe.
*/
class OrbitControls {
/**
* Constructs an orbiting camera control.
* @param {HTMLElement} element Target element to bind listeners to
* @param {Number} distance Starting distance from origin
* @param {Object} options Hash of options for configuration
*/
constructor(element, camera, distance, options) {
options = options || {};
this.element = element;
this.camera = camera;
this.distance = distance || 2;
this.distanceTarget = this.distance;
var params = {
zoomDamp: 0.5,
distanceScale: 0.5,
distanceMax: 1000,
distanceMin: 1,
touchScale: 0.1,
wheelScale: 0.01,
friction: 0.2,
target: vec3.create(),
allowZoom: true
};
this.options = setParams(params, options);
this.camera.lookAt(this.options.target);
this.mouse = {x: 0, y: 0};
this.mouseOnDown = {x: 0, y: 0};
this.rotation = {x: 0, y: 0};
this.target = {x: Math.PI * 3 / 2, y: Math.PI / 6.0};
this.targetOnDown = {x: 0, y: 0};
this.overRenderer = false;
// Pre-bind all these handlers so we can unbind the listeners later.
this.mouseMove = this._onMouseMove.bind(this);
this.mouseUp = this._onMouseUp.bind(this);
this.mouseOut = this._onMouseOut.bind(this);
this.mouseDown = this._onMouseDown.bind(this);
this.mouseWheel = this._onMouseWheel.bind(this);
this.touches = [];
this.touchDelta = 0;
this.touchMove = this._onTouchMove.bind(this);
this.touchEnd = this._onTouchEnd.bind(this);
this.touchLeave = this._onTouchLeave.bind(this);
this.touchStart = this._onTouchStart.bind(this);
this.mouseOver = function() { this.overRenderer = true; }.bind(this);
this.mouseOut = function() { this.overRenderer = false; }.bind(this);
this.enabled = false;
}
/**
* Unbinds all listeners and disables the controls
*/
disable() {
this.element.removeEventListener('mousedown', this.mouseDown, false);
this.element.removeEventListener('mousemove', this.mouseMove, false);
this.element.removeEventListener('mouseup', this.mouseUp, false);
this.element.removeEventListener('mouseout', this.mouseOut, false);
this.element.removeEventListener('touchstart', this.touchStart, false);
this.element.removeEventListener('touchmove', this.touchMove, false);
this.element.removeEventListener('touchend', this.touchEnd, false);
this.element.removeEventListener('touchleave', this.touchLeave, false);
this.element.removeEventListener('mousewheel', this.mouseWheel, false);
this.element.removeEventListener('mouseover', this.mouseOver, false);
this.element.removeEventListener('mouseout', this.mouseOut, false);
this.enabled = false;
}
/**
* Binds all listeners and enables the controls
*/
enable() {
this.element.addEventListener('mousedown', this.mouseDown, false);
if(this.options.allowZoom)
{
this.element.addEventListener('mousewheel', this.mouseWheel, false);
}
this.element.addEventListener('touchstart', this.touchStart, false);
this.element.addEventListener('mouseover', this.mouseOver, false);
this.element.addEventListener('mouseout', this.mouseOut, false);
this.enabled = true;
}
/**
* Update the given camera matrix with new position information, etc
* @param {mat4} view A view matrix
*/
updateView() {
var dx = this.target.x - this.rotation.x,
dy = this.target.y - this.rotation.y,
dz = this.distanceTarget - this.distance,
cameraPosition = vec3.create();
if(Math.abs(dx) > 0.00001 || Math.abs(dy) > 0.00001 || Math.abs(dz) > 0.00001)
{
this.rotation.x += dx * this.options.friction;
this.rotation.y += dy * this.options.friction;
this.distance += dz * this.options.distanceScale;
cameraPosition[0] = this.distance * Math.sin(this.rotation.x) * Math.cos(this.rotation.y) + this.options.target[0];
cameraPosition[1] = this.distance * Math.sin(this.rotation.y) + this.options.target[1];
cameraPosition[2] = this.distance * Math.cos(this.rotation.x) * Math.cos(this.rotation.y) + this.options.target[2];
this.camera.setPosition(cameraPosition);
}
}
_updateTargets() {
var scale = this.distance < MIN_LOG_DIST ? this.distance : Math.log(this.distance);
var zoomDamp = scale / this.options.zoomDamp;
this.target.x = this.targetOnDown.x + (this.mouse.x - this.mouseOnDown.x) * 0.005 * zoomDamp;
this.target.y = this.targetOnDown.y + (this.mouse.y - this.mouseOnDown.y) * 0.005 * zoomDamp;
this.target.y = this.target.y > PI_HALF ? PI_HALF : this.target.y;
this.target.y = this.target.y < - PI_HALF ? - PI_HALF : this.target.y;
}
_onMouseDown(ev) {
ev.preventDefault();
this.element.addEventListener('mousemove', this.mouseMove, false);
this.element.addEventListener('mouseup', this.mouseUp, false);
this.element.addEventListener('mouseout', this.mouseOut, false);
this.mouseOnDown.x = -ev.clientX;
this.mouseOnDown.y = ev.clientY;
this.targetOnDown.x = this.target.x;
this.targetOnDown.y = this.target.y;
this.element.style.cursor = 'move';
}
_onMouseMove(ev) {
this.mouse.x = -ev.clientX;
this.mouse.y = ev.clientY;
this._updateTargets();
}
_onMouseUp(ev) {
this._onMouseOut(ev);
this.element.style.cursor = 'auto';
}
_onMouseOut() {
this.element.removeEventListener('mousemove', this.mouseMove, false);
this.element.removeEventListener('mouseup', this.mouseUp, false);
this.element.removeEventListener('mouseout', this.mouseOut, false);
}
_onMouseWheel(ev) {
if (this.overRenderer) {
this._zoom(ev.wheelDeltaY * this.options.wheelScale * (this.distance < MIN_LOG_DIST ? this.distance : Math.log(this.distance)));
}
return true;
}
_onTouchStart(ev) {
ev.preventDefault();
if(this.touches.length === 0)
{
this.element.addEventListener('touchmove', this.touchMove, false);
this.element.addEventListener('touchend', this.touchEnd, false);
this.element.addEventListener('touchleave', this.touchLeave, false);
}
for(var i = 0; i < ev.changedTouches.length; i++)
{
this.touches.push(cloneTouch(ev.changedTouches[i]));
}
if(this.touches.length === 1)
{
this.mouseOnDown.x = -this.touches[0].x;
this.mouseOnDown.y = this.touches[0].y;
this.targetOnDown.x = this.target.x;
this.targetOnDown.y = this.target.y;
}
else if(this.touches.length === 2 && this.options.allowZoom)
{
var x = Math.abs(this.touches[0].x - this.touches[1].x);
var y = Math.abs(this.touches[0].y - this.touches[1].y);
this.touchDelta = Math.sqrt(x * x + y * y);
}
this.element.style.cursor = 'move';
}
_onTouchMove(ev) {
var changed = ev.changedTouches, l = changed.length;
for(var i = 0; i < l; i++)
{
var idx = getTouchIndex(this.touches, changed[i]);
if(idx >= 0)
{
this.touches.splice(idx, 1, cloneTouch(changed[i]));
}
else
{
console.log('could not find event ', changed[i]);
}
}
if(this.touches.length === 1)
{
this.mouse.x = - this.touches[0].x;
this.mouse.y = this.touches[0].y;
this.updateTargets();
}
else if(this.touches.length === 2 && this.options.allowZoom)
{
var x = this.touches[0].x - this.touches[1].x;
var y = this.touches[0].y - this.touches[1].y;
var newDelta = Math.sqrt(x * x + y * y);
this._zoom((newDelta - this.touchDelta) * this.options.touchScale);
this.touchDelta = newDelta;
}
}
_removeTouches(ev) {
var changed = ev.changedTouches, l = changed.length;
for(var i = 0; i < l; i++)
{
var idx = getTouchIndex(this.touches, changed[i]);
if(idx >= 0)
{
this.touches.splice(idx, 1);
}
}
if(this.touches.length === 0)
{
this.element.removeEventListener('touchmove', this.touchMove, false);
this.element.removeEventListener('touchend', this.touchEnd, false);
this.element.removeEventListener('touchleave', this.touchLeave, false);
}
else if(this.touches.length === 1)
{
this.mouseOnDown.x = -this.touches[0].x;
this.mouseOnDown.y = this.touches[0].y;
this.targetOnDown.x = this.target.x;
this.targetOnDown.y = this.target.y;
}
}
_onTouchEnd(ev) {
this._removeTouches(ev);
this.element.style.cursor = 'auto';
}
_onTouchLeave(ev) {
this._removeTouches(ev);
}
//?
_onTouchCancel(ev) {
this._removeTouches(ev);
}
_zoom(delta) {
this.distanceTarget -= delta;
this.distanceTarget = Math.min(this.distanceTarget, this.options.distanceMax);
this.distanceTarget = Math.max(this.distanceTarget, this.options.distanceMin);
}
}
export default OrbitControls;
| mit |
juanhenriquez/move-rails | app/models/group/group_member.rb | 132 | class Group::GroupMember < ApplicationRecord
self.table_name = "group_members"
belongs_to :group
belongs_to :user
end
| mit |
poooi/plugin-battle-detail | lib/csv-stringify/sync.js | 393 | var StringDecoder,stringify
StringDecoder=require("string_decoder").StringDecoder,stringify=require("./index"),module.exports=function(r,e){var i,n,t,o,g,u
for(null==e&&(e={}),i=[],r instanceof Buffer&&(n=new StringDecoder,r=n.write(r)),u=new stringify.Stringifier(e),u.push=function(r){return r?i.push(r.toString()):void 0},t=0,o=r.length;o>t;t++)g=r[t],u.write(g)
return u.end(),i.join("")}
| mit |
websanova/vue-auth | src/lib/utils.js | 2660 | function isObject(val) {
if (val !== null && typeof val === 'object' && val.constructor !== Array ) {
return true;
}
return false;
}
function toArray(val) {
return (typeof val) === 'string' || (typeof val) === 'number' ? [val] : val;
}
function extend(mainObj, appendObj) {
var i, ii, key, data = {};
appendObj = appendObj || {};
for (key in mainObj) {
if (isObject(mainObj[key]) && mainObj[key].constructor.name !== 'FormData') {
data[key] = extend(mainObj[key], {});
}
else {
data[key] = mainObj[key];
}
}
if (appendObj.constructor !== Array) {
appendObj = [appendObj];
}
for (i = 0, ii = appendObj.length; i < ii; i++) {
for (key in appendObj[i]) {
if (isObject(appendObj[i][key]) && appendObj[i][key].constructor.name !== 'FormData') {
data[key] = extend(mainObj[key] || {}, [appendObj[i][key]]);
}
else {
data[key] = appendObj[i][key];
}
}
}
return data;
}
function compare(one, two) {
var i, ii, key;
if (Object.prototype.toString.call(one) === '[object Object]' && Object.prototype.toString.call(two) === '[object Object]') {
for (key in one) {
if (compare(one[key], two[key])) {
return true;
}
}
return false;
}
one = toArray(one);
two = toArray(two);
if (!one || !two || one.constructor !== Array || two.constructor !== Array) {
return false;
}
for (i = 0, ii = one.length; i < ii; i++) {
if (two.indexOf(one[i]) >= 0) {
return true;
}
}
return false;
}
function isLocalStorage() {
try {
if (!window.localStorage) {
throw 'exception';
}
localStorage.setItem('storage_test', 1);
localStorage.removeItem('storage_test');
return true;
} catch (e) {
return false;
}
}
function isSessionStorage() {
try {
if (!window.sessionStorage) {
throw 'exception';
}
sessionStorage.setItem('storage_test', 1);
sessionStorage.removeItem('storage_test');
return true;
} catch (e) {
return false;
}
}
function isCookieStorage() {
return true;
}
function getProperty (obj, desc) {
var arr = desc.split('.');
while (arr.length) {
obj = obj[arr.shift()];
}
return obj;
}
export {
extend,
compare,
toArray,
isObject,
isLocalStorage,
isCookieStorage,
isSessionStorage,
getProperty,
}; | mit |
DipeshKazi/C-Repository | Problem2.1/Problem2.1/Source.cpp | 1875 | #include <iostream>
#include <String>
double CelsiustoFahrenheit1 (double celsius8am)
{
double fahrenheit8am;
fahrenheit8am = celsius8am * 1.2 + 32;
return fahrenheit8am;
}
double CelsiustoFahrenheit2 (double celsius12am)
{
double fahrenheit12am;
fahrenheit12am = celsius12am * 1.2 + 32;
return fahrenheit12am;
}
double CelsiustoFahrenheit3 (double celsius5pm)
{
double fahrenheit5pam;
fahrenheit5pam = celsius5pm * 1.2 + 32;
return fahrenheit5pam;
}
int main()
{
//input for celsius
double celsius8am, celsius12am, celsius5pm;
//User input for celsium
std::cout << "What is the temperature in celsium at 8:00 am " << std::endl;
std::cin >> celsius8am;
std::cout << "What is the temperature in celsium at 12:00 am " << std::endl;
std::cin >> celsius12am;
std::cout << "What is the temperature in celsium at 5:00 am " << std::endl;
std::cin >> celsius5pm;
//formular for celsius to fahrenheit
//fahrenheit8am = celsius8am * 1.2 + 32;
//fahrenheit12am = celsius12am * 1.2 + 32;
//fahrenheit5pam = celsium5pm * 1.2 + 32;
///std::cout << "The temperatur in fahrenheit at 8: 00 am is" << fahrenheit8am << std:: endl;
/// std::cout << "The temperatur in fahrenheit at 12 :00 am is" << fahrenheit12am <<std:: endl;
/// std::cout << "The temperatur in fahrenheit at 5: 00 am is" << fahrenheit5pam <<std:: endl;
if (celsius8am > celsius12am)
{
std::cout << "Error" << std::endl;
}
else
{
std::cout << "The temperatur in fahrenheit at 8: 00 am is" << CelsiustoFahrenheit1 (celsius8am)<< std::endl;
std::cout << "The temperatur in fahrenheit at 12 :00 am is" << CelsiustoFahrenheit2 (celsius12am) << std::endl;
std::cout << "The temperatur in fahrenheit at 5: 00 am is" << CelsiustoFahrenheit3 (celsius5pm) << std::endl;
}
return 0;
///if (fahrenheit8am > fahrenheit12am)
///std::cout << "Error" << std::endl;
} | mit |
yogeshsaroya/new-cdnjs | ajax/libs/jquery.tablesorter/2.21.2/js/widgets/widget-filter.min.js | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:4d22cea69a37d8289ea4be9a03f9e4d36d32bc358816ef4b91cdac9ba938e620
size 24693
| mit |
samuelCosta/IPUM | application/controllers/utilizador.php | 20861 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Utilizador extends CI_Controller {
// function __construct() {
// parent::__construct();
//
// if($this->session ->userdata('conectado')==false){
// redirect('Welcome');
//
// }
//
// }
public function index() {
// estatistica
$this->load->model('utilizador_m');
$this->load->model('quotas_m');
$data=date('Y');
$totalAtuacoes=$this->utilizador_m->totalAtuacoes($data);
$totalAtividades=$this->utilizador_m->totalAtividades($data);
$totalEnsaios=$this->utilizador_m->totalEnsaios($data);
$totalAtivos=$this->utilizador_m->totalAtivos();
$proximaAtuacao=$this->utilizador_m->proximaAtuacao();
$proximaAtividade=$this->utilizador_m->proximaAtividade();
$proximoEnsaio=$this->utilizador_m->proximoEnsaio();
$quotasEmFalta=$this->quotas_m->quotasEmFalta();
$this->load->view('includes/header_v');
$this->load->view('bemVindo_v',array('totalAtuacoes'=>$totalAtuacoes,
'totalAtividades'=>$totalAtividades,'totalEnsaios'=>$totalEnsaios,
'totalAtivos'=>$totalAtivos,'proximaAtuacao'=>$proximaAtuacao,
'proximaAtividade' => $proximaAtividade,'proximoEnsaio' => $proximoEnsaio ,'quotasEmFalta' => $quotasEmFalta));
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
public function detalheUtilizador($id) {
$this->load->model('utilizador_m');
$totalAtuacoes= $this->utilizador_m->totalAtuacoesElemento($id);
$totalEnsaios= $this->utilizador_m->totalEnsaiosElemento($id);
$dados = $this->utilizador_m->compararIdDetalhes($id);
$traje = $this->utilizador_m->get_traje_id($id);
$instrumento = $this->utilizador_m->get_instrumento_id($id);
$manutencao = $this->utilizador_m->get_manutencoes($id);
$dataPagamento= $this->utilizador_m->proximoPagamento($id);
if($dataPagamento==Null){
$dataPagamento="Não é Socio";
}else{
$dataPagamento=$dataPagamento['dataAviso'];
}
$imprimirOrgaoSocial= $this->utilizador_m->imprimirOrgaoSocial($id);
$this->load->view('includes/header_v');
$this->load->view('utilizador_v',array('totalAtuacoes' => $totalAtuacoes, 'utilizador'=>$dados,
'totalEnsaios'=>$totalEnsaios,'pagamento'=>$dataPagamento,'orgaosSociais'=>$imprimirOrgaoSocial, 'traje'=>$traje, 'instrumento'=>$instrumento, 'manutencao'=>$manutencao));
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
public function criarUtilizador() {
$this->load->view('includes/header_v');
$this->load->view('criarUtilizador_v');
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
// devolve a lista de todos os utilizadores
public function consultarUtilizadoresAtivos($indice=NULL) {
$this->load->model('utilizador_m');
$dados['utilizadoresAtivos'] = $this->utilizador_m->get_utilizadoresAtivos();
if ($indice == 1) {
$data['msg'] = "Utilizador foi Ativado.";
$this->load->view('includes/msgSucesso_v', $data);
} else if ($indice == 2) {
$data['msg'] = "Não foi possível ativar o Utilizador.";
$this->load->view('includes/msgSucesso_v', $data);
}else if ($indice == 3) {
$data['msg'] = "Novo Utilizador Registado com Sucesso.";
$this->load->view('includes/msgSucesso_v', $data);
}else if ($indice == 4) {
$data['msg'] = "Alterado com Sucesso.";
$this->load->view('includes/msgSucesso_v', $data);
}
$this->load->view('includes/header_v');
$this->load->view('ConsultarUtilizadores_v', $dados);
$this->load->view('includes/menu_v');
}
// devolve a lista de todos os utilizadores ativos
public function consultarUtilizadoresInativos() {
$this->load->model('utilizador_m');
$dados['utilizadoresInativos'] = $this->utilizador_m->get_utilizadoresInativos();
$this->load->view('includes/header_v');
$this->load->view('historicoUtilizadores_v', $dados);
$this->load->view('includes/menu_v');
}
// ativar Utilizador
public function ativarUtilizador($id) {
$this->load->model('utilizador_m');
$ativo['ativo']=1;
$result=$this->utilizador_m->ativarUtilizador($id,$ativo);
if($result == 1){
redirect('Utilizador/consultarUtilizadoresAtivos'.'/1');
}else{
redirect('Utilizador/consultarUtilizadoresInativos'.'/2');
}
}
public function registarUtilizador() {
//strtolower-colocar tudo em minusculo
//ucwords-colocar iniciais em maiusculo
$this->form_validation->set_rules('nome', 'Nome', 'required|ucwords|is_unique[utilizador.nome]');
$this->form_validation->set_rules('alcunha', 'Alcunha', 'required|alpha');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strtolower|valid_email|is_unique[utilizador.email]');
$this->form_validation->set_rules('password', 'Password', 'required|strtolower|min_length[6]');
$this->form_validation->set_message('matches', 'O campo %s esta diferente do campo %s');
$this->form_validation->set_rules('password2', 'Repita Password', 'required|strtolower|matches[password]');
$this->form_validation->set_rules('nif', 'NIF', 'required|numeric|exact_length[9]|is_unique[utilizador.nif]');
$this->form_validation->set_rules('bi', 'BI', 'required|numeric|exact_length[8]|is_unique[utilizador.bi]');
$this->form_validation->set_rules('nAluno', 'NUmero Aluno', 'required|numeric');
$this->form_validation->set_rules('dataNascimento', 'Data de Nascimento', 'required');
$this->form_validation->set_rules('dataEntrada', 'Data de Entrada', 'required');
$this->form_validation->set_rules('privilegio', 'Privilégio', 'required');
$this->form_validation->set_rules('foto', 'Imagem', 'callback_validar_foto');
if ($this->form_validation->run() == FALSE) {
$this->load->view('includes/header_v');
$this->load->view('criarUtilizador_v');
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
} else {
//insere os dados na base de dados
$dados = elements(array('ativo','nAluno', 'socio', 'nome', 'alcunha', 'email', 'password', 'nif', 'bi', 'dataNascimento', 'privilegio', 'dataEntrada', 'foto'), $this->input->post());
$dados['password'] = md5($dados['password']);
$this->load->model('utilizador_m');
$this->utilizador_m->do_insert($dados);
redirect('Utilizador/consultarUtilizadoresAtivos'.'/3');
}
}
public function validar_foto() {
//FOTO
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '3000';
$this->load->library('upload', $config);
//isset-Determinar se uma variável está definido e não é NULL
//empty — Informa se a variável é vazia
if (isset($_FILES['foto']) && !empty($_FILES['foto']['name'])) {
if ($this->upload->do_upload('foto')) {
// coloca o nome do ficheiro na variavel
$upload_data = $this->upload->data();
$_POST['foto'] = utf8_encode($upload_data['file_name']);
return true;
} else {
// mostrar os erros
$this->form_validation->set_message('validar_foto', $this->upload->display_errors());
return false;
}
} else {
$_POST['foto'] = 'index.jpg';
return true;
}
}
// vai permitar devolver os dados de um determinado utilizador
public function atualizar($id = null, $indice = null) {
$this->load->model('utilizador_m');
$data['utilizador'] = $this->utilizador_m->compararId($id);
$this->load->view('includes/header_v');
if ($indice == 1) {
$data['msg'] = "Senha atualizada com sucesso.";
$this->load->view('includes/msgSucesso_v', $data);
} else if ($indice == 2) {
$data['msg'] = "Não foi possível atualizar a senha do usuário.";
$this->load->view('includes/msgError_v', $data);
} else if ($indice == 3) {
$data['msg'] = "Atualização para sócio com sucesso.";
$this->load->view('includes/msgSucesso_v', $data);
$data['msg'] = " Primeira Quota Paga Automaticamente";
$this->load->view('includes/msgSucesso_v', $data);
} else if ($indice == 4) {
$data['msg'] = "Não foi possível tornar-se sócio.";
$this->load->view('includes/msgSucesso_v', $data);
}else if ($indice == 5) {
$data['msg'] = "Nova senha gerada.";
$this->load->view('includes/msgSucesso_v', $data);
}else if ($indice == 6) {
$data['msg'] = "Alteraçao para Sócio com Sucesso .";
$this->load->view('includes/msgSucesso_v', $data);
}
$this->load->view('editarUtilizador_v', $data);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
public function guardarAtualizacao() {
//strtolower-colocar tudo em minusculo
//ucwords-colocar iniciais em maiusculo
$this->form_validation->set_rules('alcunha', 'Alcunha', 'required|alpha');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strtolower|valid_email');
$this->form_validation->set_rules('dataNascimento', 'Data Nascimento', 'required');
$this->form_validation->set_rules('privilegio', 'Privilegio', 'required');
$this->form_validation->set_rules('nAluno', 'Numero de Aluno', 'required|numeric');
$id = $this->input->post('idUtilizador');
if ($this->form_validation->run() == FALSE) {
$this->load->model('utilizador_m');
$data['utilizador'] = $this->utilizador_m->compararId($id);
$this->load->view('includes/header_v');
$this->load->view('editarUtilizador_v', $data);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
} else {
//insere os dados na base de dados
$dados = elements(array('nAluno','socio','ativo', 'alcunha', 'email', 'dataNascimento', 'privilegio'), $this->input->post());
$this->load->model('utilizador_m');
$this->utilizador_m->guardarAtualizacao($id, $dados);
redirect('Utilizador/consultarUtilizadoresAtivos'.'/4');
// $this->load->view('includes/footer_v');
}
}
public function salvar_senha() {
$this->load->model('utilizador_m');
$id = $this->input->post('idUtilizador');
if ($this->utilizador_m->salvar_senha()) {
redirect('utilizador/atualizar/' . $id . '/1');
} else {
redirect('utilizador/atualizar/' . $id . '/2');
}
}
public function alterarDataSocio() {
$this->load->model('quotas_m');
$this->load->model('utilizador_m');
$dataSocio = $this->input->post('dataSocio');
$id = $this->input->post('idUtilizador');
if($this->quotas_m->verificaSocio($id) <= 0){
if ($this->utilizador_m->alterarDataSocio() &&$this->quotas_m->do_insert($id,$dataSocio) &&$this->quotas_m->criarLinhaQuota($id,$dataSocio)) {
redirect('utilizador/atualizar/' . $id . '/3');
} else {
redirect('utilizador/atualizar/' . $id . '/4');
}
}else {
$this->utilizador_m->alterarSocio();
redirect('utilizador/atualizar/' . $id . '/6');
}
}
// //botao pesquisar utilizadores ativos(consultarUtilizadores_v)
// public function pesquisarAtivos() {
//
// $this->load->model('utilizador_m');
// $dados['utilizadoresAtivos'] = $this->utilizador_m->pesquisar_utlizadoresAtivos();
//
// $this->load->view('includes/header_v');
// $this->load->view('ConsultarUtilizadores_v', $dados);
// $this->load->view('includes/menu_v');
//// $this->load->view('includes/footer_v');
// }
// //botao pesquisar utilizadores inativos(historicoUtilizadores_v)
// public function pesquisarInativos() {
//
// $this->load->model('utilizador_m');
// $dados['utilizadoresInativos'] = $this->utilizador_m->pesquisar_utlizadoresInativos();
//
// $this->load->view('includes/header_v');
// $this->load->view('historicoUtilizadores_v', $dados);
// $this->load->view('includes/menu_v');
// $this->load->view('includes/footer_v');
// }
//destroi a sessao
public function logout() {
$this->session->sess_destroy();
redirect('Welcome');
}
// manda para a view onde imprime o certificado de socio
public function comprovativoSocio($id) {
$this->load->model('utilizador_m');
$dados['utilizador']=$this->utilizador_m->compararIdDetalhes($id);
$this->load->view('includes/comprovativoSocio_v',$dados);
}
// manda para a view onde imprime o certificado dos seus cargos
public function comprovativoOrgaosSociais($id) {
$this->load->model('utilizador_m');
$dados['utilizador']=$this->utilizador_m->compararIdDetalhes($id);
$dados['comprovativo']=$this->utilizador_m->imprimirOrgaoSocial($id);
$this->load->view('includes/comprovativoOrgaosSociais_v',$dados);
}
public function OrgaosSociais($id) {
$this->load->model('utilizador_m');
$dados['utilizador']=$this->utilizador_m->compararIdDetalhes($id);
$dados['comprovativos']=$this->utilizador_m->imprimirOrgaoSocial($id);
$this->load->view('includes/header_v');
$this->load->view('utilizador_v', $dados);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
public function presencasAtuacoes() {
$dado['tab'] = "tab1";
//
$this->load->view('includes/header_v');
$this->load->view('presencasEventos_v', $dado);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
// a medida que utilizador escreve vai lhe dar opcoes de eventos registados na base de dados
public function searchEventos() {
$this->load->model('utilizador_m');
if (isset($_GET['term'])) {
$result = $this->utilizador_m->searchEventos($_GET['term']);
if (count($result) > 0) {
foreach ($result as $pr)
$arr_result[] = $pr->designacao;
echo json_encode($arr_result);
}
}
}
//tem duas operacoes a base de dados( permite buscar o idEvento atraves da designaçao)( buscar os utilizadores presentes no evento)
public function eventosUtilizadores() {
$designacao = $this->input->post('designacao');
$this->load->model('utilizador_m');
$result = $this->utilizador_m->eventosUtilizadores($designacao);
$dados['tab'] = "tab1";
// if (count($result) > 0) {
foreach ($result as $pr){
$dados['utilizadores'] = $this->utilizador_m->utilizadoresPorEvento($pr->idEventos);
}
$this->load->view('includes/header_v');
$this->load->view('presencasEventos_v', $dados);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
// } else {
//
// redirect('utilizador/presencasAtuacoes');
// }
}
//atuacoes num determinado ano
public function eventosPorAno() {
$ano = $this->input->post('ano');
$this->load->model('utilizador_m');
$result['eventos'] = $this->utilizador_m->eventosPorAno($ano);
$result['tab'] = "tab2";
// if (count($result) > 0) {
$this->load->view('includes/header_v');
$this->load->view('presencasEventos_v', $result);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
// } else {
// redirect('utilizador/presencasAtuacoes');
// }
}
// This function call from AJAX
//vai dando sugestões de atuações registadas na base de dados
public function verDetalhesEvento() {
$this->load->model('utilizador_m');
$data = $this->utilizador_m->utilizadoresPorEvento($this->input->post('name'));
// convertemos em json e colocamos na tela
echo json_encode($data);
}
// a medida que utilizador escreve vai lhe dar opcoes de utilizadores registados na base de dados
public function searchUtilizadores() {
$this->load->model('utilizador_m');
if (isset($_GET['term'])) {
$result = $this->utilizador_m->searchUtilizadores($_GET['term']);
if (count($result) > 0) {
foreach ($result as $pr)
$arr_result[] = $pr->nome;
echo json_encode($arr_result);
}
}
}
//tem duas operacoes a base de dados( permite buscar o idUtilizador atraves do nome)( buscar os eventos onde teve presente o utilizador)
public function utilizadorEventos() {
$nome = $this->input->post('utilizador');
$this->load->model('utilizador_m');
$result = $this->utilizador_m->utilizadorEventos($nome);
$dados['tab'] = "tab3";
foreach ($result as $pr){
$dados['presenca'] = $this->utilizador_m->eventoPorUtilizador($pr->idUtilizador);
}
$this->load->view('includes/header_v');
$this->load->view('presencasEventos_v', $dados);
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
// total de eventos por utilizador
public function totalEventos() {
$this->load->model('utilizador_m');
$ano = $this->input->post('ano');
$utilizadores1=$this->utilizador_m->todosUtilizadores();
foreach ($utilizadores1 as $as){
//total atuacoes por utlizador
$totalAtuacoes[]=$this->utilizador_m->totalAtuacaoPorAnoUtilizador($as->idUtilizador,$ano);
//total de ensaios por utilizador
$totalEnsaios[]=$this->utilizador_m->totalEnsaioPorAnoUtilizador($as->idUtilizador,$ano);// $array=array(
}
$dados = "tab4";
$this->load->view('includes/header_v');
$this->load->view('presencasEventos_v', array("tab"=>$dados,"totalAtuacoes"=>$totalAtuacoes,
"utilizadores1"=>$utilizadores1,"totalEnsaios"=>$totalEnsaios));
$this->load->view('includes/menu_v');
$this->load->view('includes/footer_v');
}
function get_random_password($chars_min=6, $chars_max=8, $use_upper_case=false, $include_numbers=false, $include_special_chars=false)
{
$length = rand($chars_min, $chars_max);
$selection = 'aeuoyibcdfghjklmnpqrstvwxz';
if($include_numbers) {
$selection .= "1234567890";
}
if($include_special_chars) {
$selection .= "!@\"#$%&[]{}?|";
}
$password = "";
for($i=0; $i<$length; $i++) {
$current_letter = $use_upper_case ? (rand(0,1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];
$password .= $current_letter;
}
echo json_encode($password);
// return $password;
}
// edita so a password
public function guardarPassword(){
$this->load->model('utilizador_m');
$id = $this->input->post('idUtilizador');
$this->utilizador_m->guardarPassword();
redirect('utilizador/atualizar/' . $id . '/5');
}
}
| mit |
mickknutson/spring-cloud-config | student_files/code/spring-cloud-configuration-server/solution-code/src/test/java/com/baselogic/cloud/ConfigurationServerApplicationTests.java | 1559 | package com.baselogic.cloud;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
public class ConfigurationServerApplicationTests {
private static final Logger log = LoggerFactory.getLogger(ConfigurationServerApplicationTests.class);
// Note this is required for locally testing Spring Boot Web Applications
// for Integration testing:
@LocalServerPort
private int port;
private String host = "http://localhost";
private TestRestTemplate testRestTemplate = new TestRestTemplate();
@Test
public void test_getCloudDataFromServer(){
String result = testRestTemplate.getForObject(
createURLWithPort("/config-client/development"),
String.class);
log.info("*************************************************************************");
log.info("Results: {}", result);
String expected = "{\"name\":\"config-client\",\"profiles\":[\"development\"]";
assertThat(result, containsString(expected));
}
private String createURLWithPort(String uri) {
return host +":"+ port + uri;
}
} // The End...
| mit |
infazz/Gravity-Forms-Input-data-cache | js/scripts.js | 4698 | (function($){
$(document).ready(function(){
function elementStartsWith(el, str) {
return $(el).map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].substr(0, str.length) == str) return e;
}
}).get(0);
}
function classStartsWith(el, str) {
return $(el).map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].substr(0, str.length) == str) return classes[i];
}
}).get(0);
}
jQuery(document).on('gform_post_render', function(){
gform_post_render();
});
function gform_post_render(){
console.log('input data');
$('.gform_store_input_data').parents('.gform_wrapper').each(function(){
var el = $(this);
///*
var dataSaveCheckbox = $(this).find('.gform_store_input_data');
dataSaveCheckbox.on('change', function(e){
if($(this).is(':checked')){
Cookies.set('cache-savedata', 'true');
}else{
Cookies.set('cache-savedata', 'false');
doDataClear( el );
}
});
//*/
console.log( dataSaveCheckbox.is(':checked') );
if(Cookies.get('cache-savedata') == 'true'){
dataSaveCheckbox.prop('checked', true);
dataSaveCheckbox.trigger('change');
doDataShow( el );
}else{
doDataClear( el );
}
$(this).find('.gform_button').on('click', function(){
doDataSave( el );
});
});
function preg_quote( str ) {
return (str+'').replace(/([\\\.\[\]\"\"])/g, "");
}
function doDataClear( el ){
//console.log('clear');
var id = el.attr('id');
el.find('.gfield').each(function(){
var key = id + '-' + classStartsWith( $(this), 'cache-' );
Cookies.set(key, '');
});
}
function doDataSave( el ){
//console.log('save');
var id = el.attr('id');
el.find('.gfield').each(function(){
var input = $(elementStartsWith( $(this), 'cache-' )).find('input, select, textarea');
var container = input.parents('.ginput_container')
var key = id + '-' + input.attr('id');
var value = input.val();
if(container.hasClass('ginput_container_name')){
input.each(function(k){
var input_id = $(this).attr('id');
key = id + '-' + input_id;
value = $(this).val();
Cookies.set(key, value);
//console.log( k, input, input_id, key, value );
});
}else if( input.attr('type') == 'radio' || input.attr('type') == 'checkbox' ){
input.each(function(k){
var input_id = $(this).attr('id');
key = id + '-' + input_id;
value = '';
if($(this).is(':checked')){
value = '=checked=';
}
Cookies.set(key, value);
//console.log( k, input, input_id, key, value );
});
}else{
if(value != undefined) {
Cookies.set(key, value);
console.log(key, value);
}
}
});
}
function doDataShow( el ){
//console.log('show');
var id = el.attr('id');
el.find('.gfield').each(function(){
//var key = id + '-' + classStartsWith( $(this), 'cache-' );
var input = $(elementStartsWith( $(this), 'cache-' )).find('input, select, textarea');
var container = input.parents('.ginput_container')
var key = id + '-' + input.attr('id');
var value = Cookies.get(key);
if(container.hasClass('ginput_container_name')){
input.each(function(k){
var input_id = $(this).attr('id');
key = id + '-' + input_id
var value = Cookies.get(key);
if(value != ''){
$(this).val(value);
}
});
}else if( input.attr('type') == 'radio' || input.attr('type') == 'checkbox' ){
input.each(function(k){
var input_id = $(this).attr('id');
key = id + '-' + input_id
var value = Cookies.get(key);
if(value == '=checked='){
$(this).prop( 'checked', true ).trigger('change');
}
});
}else{
if(value != ''){
//console.log(value);
if(value != undefined && value.indexOf('["') != -1){
value = preg_quote(value);
value = value.split(',');
//console.log( value );
$(elementStartsWith( $(this), 'cache-' )).find('input, select, textarea').val( value ).trigger('change');
}else{
$(elementStartsWith( $(this), 'cache-' )).find('input, select, textarea').val( value ).trigger('change');
}
}
//console.log( $(elementStartsWith( $(this), 'cache-' )).find('input, select, textarea').val() );
}
});
}
}
gform_post_render();
});
})(window.jQuery); | mit |
juui2/juui | src/app/app.module.ts | 613 | import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {MaterialModule} from '@angular/material';
import {FlexLayoutModule} from '@angular/flex-layout';
import 'hammerjs';
import {AppComponent} from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot(),
FlexLayoutModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
| mit |
easanles/atletismo-edu | src/Easanles/AtletismoBundle/Form/Type/TprmType.php | 1076 | <?php
# Copyright (c) 2016 Eduardo Alonso Sanlés
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
namespace Easanles\AtletismoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TprmType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('sexo', 'choice', array('choices' => array(
'2' => 'Ambos',
'0' => 'Masculino',
'1' => 'Femenino',
),
'expanded' => false,
'label' => 'Sexo', 'required' => true))
->add('entorno', 'text', array('label' => 'Entorno'));
}
public function getName(){
return 'tprm';
}
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'data_class' => 'Easanles\AtletismoBundle\Entity\TipoPruebaModalidad',
));
}
} | mit |
gsterndale/yourkarma | spec/support/vcr.rb | 228 | require 'vcr'
VCR.configure do |c|
c.hook_into :webmock
c.cassette_library_dir = 'spec/cassettes'
c.default_cassette_options = {
record: :none,
allow_playback_repeats: true
}
c.configure_rspec_metadata!
end
| mit |
bmiquel/Site | src/Miquel/SiteBundle/MiquelSiteBundle.php | 128 | <?php
namespace Miquel\SiteBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MiquelSiteBundle extends Bundle
{
}
| mit |
Da-Technomancer/Crossroads | src/main/java/com/Da_Technomancer/crossroads/tileentities/alchemy/TeslaCoilTileEntity.java | 9112 | package com.Da_Technomancer.crossroads.tileentities.alchemy;
import com.Da_Technomancer.crossroads.API.IInfoTE;
import com.Da_Technomancer.crossroads.API.Properties;
import com.Da_Technomancer.crossroads.API.alchemy.LooseArcRenderable;
import com.Da_Technomancer.crossroads.API.packets.ModPackets;
import com.Da_Technomancer.crossroads.API.packets.SendLooseArcToClient;
import com.Da_Technomancer.crossroads.blocks.ModBlocks;
import com.Da_Technomancer.crossroads.items.ModItems;
import com.Da_Technomancer.crossroads.items.alchemy.LeydenJar;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EntitySelectors;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.ITickable;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import javax.annotation.Nonnull;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class TeslaCoilTileEntity extends TileEntity implements IInfoTE, ITickable{
@Override
public void addInfo(ArrayList<String> chat, EntityPlayer player, EnumFacing side){
for(int i = 0; i < 3; i++){
if(linked[i] != null){
chat.add("Linked Position: X=" + (pos.getX() + linked[i].getX()) + " Y=" + (pos.getY() + linked[i].getY()) + " Z=" + (pos.getZ() + linked[i].getZ()));
}
}
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState){
return oldState.getBlock() != newState.getBlock();
}
public static final int[] COLOR_CODES = {new Color(128, 0, 255, 128).getRGB(), new Color(64, 0, 255, 128).getRGB(), new Color(100, 0, 255, 128).getRGB()};
private static final int[] ATTACK_COLOR_CODES = {new Color(255, 32, 0, 128).getRGB(), new Color(255, 0, 32, 128).getRGB(), new Color(255, 32, 32, 128).getRGB()};
private static final int JOLT_CONSERVED = 950;
private int stored = 0;
private Boolean hasJar = null;
private static final int JOLT_AMOUNT = 1000;
private static final int CAPACITY = 2000;
public static final int RANGE = 8;
//Relative to this TileEntity's position
public BlockPos[] linked = new BlockPos[3];
public boolean redstone = false;
@Override
public void update(){
if(world.isRemote){
return;
}
if(hasJar == null){
IBlockState state = world.getBlockState(pos);
if(state.getBlock() != ModBlocks.teslaCoil){
invalidate();
return;
}
hasJar = world.getBlockState(pos).getValue(Properties.ACTIVE);
}
if(!redstone && world.getTotalWorldTime() % 10 == 0 && stored >= JOLT_AMOUNT){
IBlockState state = world.getBlockState(pos);
if(state.getBlock() != ModBlocks.teslaCoil){
invalidate();
return;
}
if(state.getValue(Properties.LIGHT)){
List<EntityLivingBase> ents = world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(pos.getX() - RANGE, pos.getY() - RANGE, pos.getZ() - RANGE, pos.getX() + RANGE, pos.getY() + RANGE, pos.getZ() + RANGE), EntitySelectors.IS_ALIVE);
if(!ents.isEmpty()){
EntityLivingBase ent = ents.get(world.rand.nextInt(ents.size()));
stored -= JOLT_AMOUNT;
markDirty();
ModPackets.network.sendToAllAround(new SendLooseArcToClient(new LooseArcRenderable(pos.getX() + 0.5F, pos.getY() + 2F, pos.getZ() + 0.5F, (float) ent.posX, (float) ent.posY, (float) ent.posZ, 5, 0.6F, 1F, ATTACK_COLOR_CODES[(int) (world.getTotalWorldTime() % 3)])), new TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 512));
world.playSound(null, pos.getX() + 0.5F, pos.getY() + 2F, pos.getZ() + 0.5F, SoundEvents.BLOCK_REDSTONE_TORCH_BURNOUT, SoundCategory.BLOCKS, 0.1F, 0F);
//Sound may need tweaking
ent.onStruckByLightning(new EntityLightningBolt(world, ent.posX, ent.posY, ent.posZ, true));
return;
}
}
for(BlockPos linkPos : linked){
if(linkPos != null){
BlockPos actualPos = linkPos.add(pos);
TileEntity te = world.getTileEntity(actualPos);
if(te instanceof TeslaCoilTileEntity){
TeslaCoilTileEntity tcTe = (TeslaCoilTileEntity) te;
if(tcTe.handlerIn.getMaxEnergyStored() - tcTe.stored > JOLT_CONSERVED){
tcTe.stored += JOLT_CONSERVED;
tcTe.markDirty();
stored -= JOLT_AMOUNT;
markDirty();
ModPackets.network.sendToAllAround(new SendLooseArcToClient(new LooseArcRenderable(pos.getX() + 0.5F, pos.getY() + 2F, pos.getZ() + 0.5F, actualPos.getX() + 0.5F, actualPos.getY() + 2F, actualPos.getZ() + 0.5F, 5, 0.6F, 1F, COLOR_CODES[(int) (world.getTotalWorldTime() % 3)])), new TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 512));
world.playSound(null, pos.getX() + 0.5F, pos.getY() + 2F, pos.getZ() + 0.5F, SoundEvents.BLOCK_REDSTONE_TORCH_BURNOUT, SoundCategory.BLOCKS, 0.1F, 0F);
//Sound may need tweaking
break;
}
}
}
}
}
if(!redstone && stored > 0){
EnumFacing facing = world.getBlockState(pos).getValue(Properties.HORIZONTAL_FACING);
TileEntity te = world.getTileEntity(pos.offset(facing));
if(te != null && te.hasCapability(CapabilityEnergy.ENERGY, facing.getOpposite())){
IEnergyStorage storage = te.getCapability(CapabilityEnergy.ENERGY, facing.getOpposite());
int moved = storage.receiveEnergy(stored, false);
if(moved > 0){
stored -= moved;
markDirty();
}
}
}
}
public void addJar(ItemStack stack){
stored = Math.min(stored + LeydenJar.getCharge(stack), CAPACITY + LeydenJar.MAX_CHARGE);
hasJar = true;
markDirty();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt){
super.writeToNBT(nbt);
nbt.setInteger("stored", stored);
for(int i = 0; i < 3; i++){
if(linked[i] != null){
nbt.setLong("link" + i, linked[i].toLong());
}
}
nbt.setBoolean("reds", redstone);
return nbt;
}
@Override
public void readFromNBT(NBTTagCompound nbt){
super.readFromNBT(nbt);
stored = nbt.getInteger("stored");
for(int i = 0; i < 3; i++){
if(nbt.hasKey("link" + i)){
linked[i] = BlockPos.fromLong(nbt.getLong("link" + i));
}
}
redstone = nbt.getBoolean("reds");
}
@Nonnull
public ItemStack removeJar(){
ItemStack out = new ItemStack(ModItems.leydenJar, 1);
LeydenJar.setCharge(out, Math.min(stored, LeydenJar.MAX_CHARGE));
stored -= Math.min(stored, LeydenJar.MAX_CHARGE);
hasJar = false;
markDirty();
return out;
}
private final EnergyHandlerIn handlerIn = new EnergyHandlerIn();
private final EnergyHandlerOut handlerOut = new EnergyHandlerOut();
public boolean hasCapability(Capability<?> cap, EnumFacing side){
if(cap == CapabilityEnergy.ENERGY && (side == null || side.getAxis() != Axis.Y)){
return true;
}
return super.hasCapability(cap, side);
}
@SuppressWarnings("unchecked")
public <T> T getCapability(Capability<T> cap, EnumFacing side){
if(cap == CapabilityEnergy.ENERGY && (side == null || side.getAxis() != Axis.Y)){
return (T) (side == world.getBlockState(pos).getValue(Properties.HORIZONTAL_FACING) ? handlerOut : handlerIn);
}
return super.getCapability(cap, side);
}
private class EnergyHandlerIn implements IEnergyStorage{
@Override
public int receiveEnergy(int maxReceive, boolean simulate){
int toInsert = Math.min(maxReceive, getMaxEnergyStored() - stored);
if(!simulate){
stored += toInsert;
markDirty();
}
return toInsert;
}
@Override
public int extractEnergy(int maxExtract, boolean simulate){
return 0;
}
@Override
public int getEnergyStored(){
return stored;
}
@Override
public int getMaxEnergyStored(){
return hasJar == Boolean.TRUE ? CAPACITY + LeydenJar.MAX_CHARGE : CAPACITY;
}
@Override
public boolean canExtract(){
return false;
}
@Override
public boolean canReceive(){
return true;
}
}
private class EnergyHandlerOut implements IEnergyStorage{
@Override
public int receiveEnergy(int maxReceive, boolean simulate){
return 0;
}
@Override
public int extractEnergy(int maxExtract, boolean simulate){
int toExtract = Math.min(stored, maxExtract);
if(!simulate){
stored -= toExtract;
markDirty();
}
return toExtract;
}
@Override
public int getEnergyStored(){
return stored;
}
@Override
public int getMaxEnergyStored(){
return hasJar == Boolean.TRUE ? CAPACITY + LeydenJar.MAX_CHARGE : CAPACITY;
}
@Override
public boolean canExtract(){
return true;
}
@Override
public boolean canReceive(){
return false;
}
}
}
| mit |
Biles430/FPF_PIV | FPF_PIV_CODE/Drummonds_Scripts/PIV_Outer.py | 3722 | import pandas as pd
from pandas import DataFrame
import numpy as np
import PIV
import h5py
import matplotlib.pyplot as plt
import hotwire as hw
################################################
# PURPOSE
# 1. Compute Integral Parameters
# 2. Outer Normalize
# 3. Plot
##################################################
#note- vel and axis are flipped to properlly calc delta
def outer(date,num_tests,sizex,sizey,folder):
#Parameter set
#date = '072117'
#read in variables
name = folder + 'data/PIV_' + date + '.h5'
umean_fov = np.array(pd.read_hdf(name, 'umean'))
vmean_fov = np.array(pd.read_hdf(name, 'vmean'))
umean = np.array(pd.read_hdf(name, 'umean_profile_avg'))
vmean = np.array(pd.read_hdf(name, 'vmean_profile_avg'))
urms = np.array(pd.read_hdf(name, 'urms_profile_avg'))
vrms = np.array(pd.read_hdf(name, 'vrms_profile_avg'))
uvprime = np.array(pd.read_hdf(name, 'uvprime_profile_avg'))
x = np.array(pd.read_hdf(name, 'xaxis'))
y = np.array(pd.read_hdf(name, 'yaxis'))
num_tests = len(umean)
###1. Outer Normalize #############
###################################
###2. Outer Normalize #############
###################################
###3. PLOTS ######################
###################################
#mean profiles
#U vs y
plt.figure()
plt.plot(umean, y, '-xb')
plt.xlabel('U (m/sec)')
plt.ylabel('Wall Normal Position (m)')
plt.legend(['400rpm'], loc=0)
plt.show()
#V vs y
plt.figure()
plt.plot(vmean, y, '-xr')
plt.xlabel('V (m/sec)')
plt.ylabel('Wall Normal Position (m)')
plt.legend(['400rpm'], loc=0)
plt.show()
#urms vs y
plt.figure()
plt.plot(urms, y, '-xb')
plt.xlabel('$U_{rms}$ (m/sec)')
plt.ylabel('Wall Normal Position (m)')
plt.legend(['400rpm'], loc=0)
plt.show()
#vrms vs y
plt.figure()
plt.plot(vrms, y, '-xr')
plt.xlabel('$V_{rms}$ (m/sec)')
plt.ylabel('Wall Normal Position (m)')
plt.legend(['400rpm'], loc=0)
plt.show()
#uprime vs y
plt.figure()
plt.plot(uvprime, y, '-xr')
plt.xlabel('$u^,v^,$')
plt.ylabel('Wall Normal Position (m)')
plt.legend(['400rpm'], loc=0)
plt.show()
### Mean Vecotr plot
skip_num = 3
umean_fov2 = umean_fov[:, 0:-1:skip_num]
vmean_fov2 = vmean_fov[:, 0:-1:skip_num]
x2 = x[0:-1:skip_num]
y2 = y
Y = np.tile(y2/.82, (len(x2), 1))
Y = np.transpose(Y)
X = np.tile(x2-.0543, (len(y2), 1))
mean_fov2 = (umean_fov2**2 + vmean_fov2**2)**(1/2)
contour_levels = np.arange(0, 3.3, .05)
plt.figure()
c = plt.contourf(X, Y, mean_fov2, levels = contour_levels, linewidth=40, alpha=.6)
cbar = plt.colorbar(c)
cbar.ax.set_ylabel('Velocity (m/sec)')
plt.hold(True)
q = plt.quiver(X, Y, umean_fov2, vmean_fov2, angles='xy', scale=50, width=.0025)
p = plt.quiverkey(q, .11, -.025, 4,"4 m/s",coordinates='data',color='r')
plt.axis([0, .1, 0, .246])
plt.ylabel('Wall Normal Position, $y/\delta$')
plt.xlabel('Streamwise Position, x (m)')
plt.title('Mean PIV Vector Field')
plt.show()
##need to run readin program before running below plot
#im_num = 768
#Umask2 = Umask[0, im_num, :, 0:-1:skip_num]
#Vmask2 = Vmask[0, im_num, :, 0:-1:skip_num]
#mean_fov1 = (Umask2**2 + Vmask2**2)**(1/2)
#contour_levels = np.arange(0, 4.6, .05)
#plt.figure()
#c = plt.contourf(X, Y, mean_fov1, levels = contour_levels, linewidth=40, alpha=.6)
#cbar = plt.colorbar(c)
#cbar.ax.set_ylabel('Velocity (m/sec)')
#plt.hold(True)
#q = plt.quiver(X, Y, -1*Umask2, Vmask2, angles='xy', scale=50, width=.0025)
#p = plt.quiverkey(q, .11, -.025, 4,"4 m/s",coordinates='data',color='r')
#plt.axis([0, .1, 0, .246])
#plt.ylabel('Wall Normal Position, $y/\delta$')
#plt.xlabel('Streamwise Position (m)')
#plt.title('Instantaneuos PIV Vector Field')
#plt.show()
print('Done!')
return
| mit |