repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
alexstyl/Memento-Calendar | android_mobile/src/main/java/com/alexstyl/specialdates/events/peopleevents/ContactEventsMarshaller.java | 2165 | package com.alexstyl.specialdates.events.peopleevents;
import android.content.ContentValues;
import com.alexstyl.specialdates.Optional;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.date.ContactEvent;
import com.alexstyl.specialdates.events.database.DatabaseContract.AnnualEventsContract;
import java.util.List;
public class ContactEventsMarshaller {
private static final int DEFAULT_VALUES_SIZE = 5;
private static final int IS_VISIBILE = 1;
private final ShortDateLabelCreator dateLabelCreator;
public ContactEventsMarshaller(ShortDateLabelCreator dateLabelCreator) {
this.dateLabelCreator = dateLabelCreator;
}
public ContentValues[] marshall(List<ContactEvent> item) {
ContentValues[] returningValues = new ContentValues[item.size()];
for (int i = 0; i < item.size(); i++) {
ContactEvent event = item.get(i);
returningValues[i] = createValuesFor(event);
}
return returningValues;
}
private ContentValues createValuesFor(ContactEvent event) {
Contact contact = event.getContact();
ContentValues values = new ContentValues(DEFAULT_VALUES_SIZE);
values.put(AnnualEventsContract.CONTACT_ID, contact.getContactID());
values.put(AnnualEventsContract.DISPLAY_NAME, contact.getDisplayName().toString());
values.put(AnnualEventsContract.DATE, dateLabelCreator.createLabelWithYearPreferredFor(event.getDate()));
values.put(AnnualEventsContract.EVENT_TYPE, event.getType().getId());
values.put(AnnualEventsContract.SOURCE, contact.getSource());
values.put(AnnualEventsContract.VISIBLE, IS_VISIBILE);
putDeviceContactIdIfPresent(event, values);
return values;
}
private void putDeviceContactIdIfPresent(ContactEvent event, ContentValues values) {
Optional<Long> deviceEventId = event.getDeviceEventId();
if (deviceEventId.isPresent()) {
values.put(AnnualEventsContract.DEVICE_EVENT_ID, deviceEventId.get());
} else {
values.put(AnnualEventsContract.DEVICE_EVENT_ID, -1);
}
}
}
| mit |
shawnvan/coffee-server-demo | node_modules/consistent-hashing/lib/index.js | 50 | module.exports = require('./consistent_hashing');
| mit |
peepsquest/tutorials | docs/css/normalize.css | 7173 | /*! normalize.css v2.1.2 | MIT License | git.io/normalize */
/* ==========================================================================
HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined in IE 8/9.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* Correct `inline-block` display not defined in IE 8/9.
*/
audio,
canvas,
video {
display: inline-block;
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address styling not present in IE 8/9.
*/
[hidden] {
display: none;
}
/* ==========================================================================
Base
========================================================================== */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-family: sans-serif;
/* 1 */
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
/* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* ==========================================================================
Links
========================================================================== */
/**
* Address `outline` inconsistency between Chrome and other browsers.
*/
a:focus {
outline: thin dotted;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* ==========================================================================
Typography
========================================================================== */
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari 5, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Correct font family set oddly in Safari 5 and Chrome.
*/
code,
kbd,
pre,
samp {
font-family: monospace, serif;
font-size: 1em;
}
/**
* Improve readability of pre-formatted text in all browsers.
*/
pre {
white-space: pre-wrap;
}
/**
* Set consistent quote types.
*/
q {
quotes: "\201C" "\201D" "\2018" "\2019";
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* ==========================================================================
Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9.
*/
img {
border: 0;
}
/**
* Correct overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* ==========================================================================
Figures
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari 5.
*/
figure {
margin: 0;
}
/* ==========================================================================
Forms
========================================================================== */
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0;
/* 1 */
padding: 0;
/* 2 */
}
/**
* 1. Correct font family not being inherited in all browsers.
* 2. Correct font size not being inherited in all browsers.
* 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
*/
button,
input,
select,
textarea {
font-family: inherit;
/* 1 */
font-size: 100%;
/* 2 */
margin: 0;
/* 3 */
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
button,
input {
line-height: normal;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.
* Correct `select` style inheritance in Firefox 4+ and Opera.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
/* 2 */
cursor: pointer;
/* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* 1. Address box sizing set to `content-box` in IE 8/9.
* 2. Remove excess padding in IE 8/9.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield;
/* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
/* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari 5 and Chrome
* on OS X.
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* 1. Remove default vertical scrollbar in IE 8/9.
* 2. Improve readability and alignment in all browsers.
*/
textarea {
overflow: auto;
/* 1 */
vertical-align: top;
/* 2 */
}
/* ==========================================================================
Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
| mit |
spacy-io/spaCy | .github/contributors/b1uec0in.md | 5372 | # spaCy contributor agreement
This spaCy Contributor Agreement (**"SCA"**) is based on the
[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
The SCA applies to any contribution that you make to any product or project
managed by us (the **"project"**), and sets out the intellectual property rights
you grant to us in the contributed materials. The term **"us"** shall mean
[ExplosionAI GmbH](https://explosion.ai/legal). The term
**"you"** shall mean the person or entity identified below.
If you agree to be bound by these terms, fill in the information requested
below and include the filled-in version with your first pull request, under the
folder [`.github/contributors/`](/.github/contributors/). The name of the file
should be your GitHub username, with the extension `.md`. For example, the user
example_user would create the file `.github/contributors/example_user.md`.
Read this agreement carefully before signing. These terms and conditions
constitute a binding legal agreement.
## Contributor Agreement
1. The term "contribution" or "contributed materials" means any source code,
object code, patch, tool, sample, graphic, specification, manual,
documentation, or any other material posted or submitted by you to the project.
2. With respect to any worldwide copyrights, or copyright applications and
registrations, in your contribution:
* you hereby assign to us joint ownership, and to the extent that such
assignment is or becomes invalid, ineffective or unenforceable, you hereby
grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
royalty-free, unrestricted license to exercise all rights under those
copyrights. This includes, at our option, the right to sublicense these same
rights to third parties through multiple levels of sublicensees or other
licensing arrangements;
* you agree that each of us can do all things in relation to your
contribution as if each of us were the sole owners, and if one of us makes
a derivative work of your contribution, the one who makes the derivative
work (or has it made will be the sole owner of that derivative work;
* you agree that you will not assert any moral rights in your contribution
against us, our licensees or transferees;
* you agree that we may register a copyright in your contribution and
exercise all ownership rights associated with it; and
* you agree that neither of us has any duty to consult with, obtain the
consent of, pay or render an accounting to the other for any use or
distribution of your contribution.
3. With respect to any patents you own, or that you can license without payment
to any third party, you hereby grant to us a perpetual, irrevocable,
non-exclusive, worldwide, no-charge, royalty-free license to:
* make, have made, use, sell, offer to sell, import, and otherwise transfer
your contribution in whole or in part, alone or in combination with or
included in any product, work or materials arising out of the project to
which your contribution was submitted, and
* at our option, to sublicense these same rights to third parties through
multiple levels of sublicensees or other licensing arrangements.
4. Except as set out above, you keep all right, title, and interest in your
contribution. The rights that you grant to us under these terms are effective
on the date you first submitted a contribution to us, even if your submission
took place before the date you sign these terms.
5. You covenant, represent, warrant and agree that:
* Each contribution that you submit is and shall be an original work of
authorship and you can legally grant the rights set out in this SCA;
* to the best of your knowledge, each contribution will not violate any
third party's copyrights, trademarks, patents, or other intellectual
property rights; and
* each contribution shall be in compliance with U.S. export control laws and
other applicable export and import laws. You agree to notify us if you
become aware of any circumstance which would make any of the foregoing
representations inaccurate in any respect. We may publicly disclose your
participation in the project, including the fact that you have signed the SCA.
6. This SCA is governed by the laws of the State of California and applicable
U.S. Federal law. Any choice of law rules will not apply.
7. Please place an “x” on one of the applicable statement below. Please do NOT
mark both statements:
* [x] I am signing on behalf of myself as an individual and no other person
or entity, including my employer, has or will have rights with respect to my
contributions.
* [ ] I am signing on behalf of my employer or a legal entity and I have the
actual authority to contractually bind that entity.
## Contributor Details
| Field | Entry |
|------------------------------- | -------------------- |
| Name | Bae, Yong-Ju |
| Company name (if applicable) | |
| Title or role (if applicable) | |
| Date | 2019-07-25 |
| GitHub username | b1uec0in |
| Website (optional) | |
| mit |
dsyme/FSharp.Compiler.Service | README.md | 2304 | F# Compiler Service
===================
The F# compiler services package contains a custom build of the F# compiler that
exposes additional functionality for implementing F# language bindings, additional
tools based on the compiler or refactoring tools. The package also includes F#
interactive service that can be used for embedding F# scripting into your applications.
Documentation
-------------
For more information about the project, see:
* [F# Compiler Service documentation](http://fsharp.github.io/FSharp.Compiler.Service/)
* [Developer notes explain the project structure](http://fsharp.github.io/FSharp.Compiler.Service/devnotes.html)
Build and Test
-----
On Windows:
.\fcs\build.cmd Test
On Linux:
./fcs/build.sh Test
Packages:
build NuGet
build TestAndNuGet
Build Status
------------
Head (branch ``master``):
* Linux/OSX: [](https://travis-ci.org/fsharp/FSharp.Compiler.Service)
* Windows: [](https://ci.appveyor.com/project/fsgit/fsharp-compiler-service)
NuGet [](https://www.nuget.org/packages/FSharp.Compiler.Service)
Stable builds are available in the NuGet Gallery:
[https://www.nuget.org/packages/FSharp.Compiler.Service](https://www.nuget.org/packages/FSharp.Compiler.Service)
All AppVeyor builds are available using the NuGet feed: https://ci.appveyor.com/nuget/fsgit-fsharp-compiler-service
If using Paket, add the source at the top of `paket.dependencies`.
License
-----------
This project is subject to the MIT License. A copy of this license can be found in [License.txt](License.txt) at the root of this repo.
Maintainers
-----------
The maintainers of this repository are:
- [Don Syme](http://github.com/dsyme)
- [Tomas Petricek](http://github.com/tpetricek)
- [Enrico Sada](http://github.com/enricosada)
- Many people have helped including [Robin Neatherway](https://github.com/rneatherway), [Dave Thomas](http://github.com/7sharp9), [Lincoln Atkinson](http://github.com/latkin), [Kevin Ransom](http://github.com/KevinRansom), [Vladimir Matveev](http://github.com/vladima) and others
| mit |
lagerjs/lager | demo/express-app/app.js | 1216 | var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
| mit |
TeamSPoon/logicmoo_workspace | packs_lib/rocksdb/rocksdb/include/rocksdb/utilities/options_util.h | 5753 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
// This file contains utility functions for RocksDB Options.
#pragma once
#ifndef ROCKSDB_LITE
#include <string>
#include <vector>
#include "rocksdb/convenience.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "rocksdb/status.h"
namespace ROCKSDB_NAMESPACE {
struct ConfigOptions;
// Constructs the DBOptions and ColumnFamilyDescriptors by loading the
// latest RocksDB options file stored in the specified rocksdb database.
//
// Note that the all the pointer options (except table_factory, which will
// be described in more details below) will be initialized with the default
// values. Developers can further initialize them after this function call.
// Below is an example list of pointer options which will be initialized
//
// * env
// * memtable_factory
// * compaction_filter_factory
// * prefix_extractor
// * comparator
// * merge_operator
// * compaction_filter
//
// User can also choose to load customized comparator, env, and/or
// merge_operator through object registry:
// * comparator needs to be registered through Registrar<const Comparator>
// * env needs to be registered through Registrar<Env>
// * merge operator needs to be registered through
// Registrar<std::shared_ptr<MergeOperator>>.
//
// For table_factory, this function further supports deserializing
// BlockBasedTableFactory and its BlockBasedTableOptions except the
// pointer options of BlockBasedTableOptions (flush_block_policy_factory,
// block_cache, and block_cache_compressed), which will be initialized with
// default values. Developers can further specify these three options by
// casting the return value of TableFactory::GetOptions() to
// BlockBasedTableOptions and making necessary changes.
//
// ignore_unknown_options can be set to true if you want to ignore options
// that are from a newer version of the db, esentially for forward
// compatibility.
//
// config_options contains a set of options that controls the processing
// of the options. The LoadLatestOptions(ConfigOptions...) should be preferred;
// the alternative signature may be deprecated in a future release. The
// equivalent functionality can be achieved by setting the corresponding options
// in the ConfigOptions parameter.
//
// examples/options_file_example.cc demonstrates how to use this function
// to open a RocksDB instance.
//
// @return the function returns an OK status when it went successfully. If
// the specified "dbpath" does not contain any option file, then a
// Status::NotFound will be returned. A return value other than
// Status::OK or Status::NotFound indicates there're some error related
// to the options file itself.
//
// @see LoadOptionsFromFile
Status LoadLatestOptions(const std::string& dbpath, Env* env,
DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
bool ignore_unknown_options = false,
std::shared_ptr<Cache>* cache = {});
Status LoadLatestOptions(const ConfigOptions& config_options,
const std::string& dbpath, DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
std::shared_ptr<Cache>* cache = {});
// Similar to LoadLatestOptions, this function constructs the DBOptions
// and ColumnFamilyDescriptors based on the specified RocksDB Options file.
//
// The LoadOptionsFile(ConfigOptions...) should be preferred;
// the alternative signature may be deprecated in a future release. The
// equivalent functionality can be achieved by setting the corresponding
// options in the ConfigOptions parameter.
//
// @see LoadLatestOptions
Status LoadOptionsFromFile(const std::string& options_file_name, Env* env,
DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
bool ignore_unknown_options = false,
std::shared_ptr<Cache>* cache = {});
Status LoadOptionsFromFile(const ConfigOptions& config_options,
const std::string& options_file_name,
DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
std::shared_ptr<Cache>* cache = {});
// Returns the latest options file name under the specified db path.
Status GetLatestOptionsFileName(const std::string& dbpath, Env* env,
std::string* options_file_name);
// Returns Status::OK if the input DBOptions and ColumnFamilyDescriptors
// are compatible with the latest options stored in the specified DB path.
//
// If the return status is non-ok, it means the specified RocksDB instance
// might not be correctly opened with the input set of options. Currently,
// changing one of the following options will fail the compatibility check:
//
// * comparator
// * prefix_extractor
// * table_factory
// * merge_operator
Status CheckOptionsCompatibility(
const std::string& dbpath, Env* env, const DBOptions& db_options,
const std::vector<ColumnFamilyDescriptor>& cf_descs,
bool ignore_unknown_options = false);
Status CheckOptionsCompatibility(
const ConfigOptions& config_options, const std::string& dbpath,
const DBOptions& db_options,
const std::vector<ColumnFamilyDescriptor>& cf_descs);
} // namespace ROCKSDB_NAMESPACE
#endif // !ROCKSDB_LITE
| mit |
csae1152/bitcoin | src/bitcoinrpc.cpp | 51032 | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinrpc.h"
#include "base58.h"
#include "init.h"
#include "main.h"
#include "util.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64_t AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 21000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64_t nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64_t amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help ( \"command\" )\n"
"\nList all commands, or get help for a specified command.\n"
"\nArguments:\n"
"1. \"command\" (string, optional) The command to get help on\n"
"\nResult:\n"
"\"text\" (string) The help text\n"
);
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"\nStop Bitcoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Bitcoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "ping", &ping, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getnettotals", &getnettotals, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "getrawchangeaddress", &getrawchangeaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "dumpwallet", &dumpwallet, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "importwallet", &importwallet, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "decodescript", &decodescript, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: bitcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: bitcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use bitcoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=bitcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Bitcoin Alert\" [email protected]\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl", false);
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
deadlineTimers.clear();
rpc_io_service->stop();
if (rpc_worker_group != NULL)
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
{
if (!err)
func();
}
void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
{
assert(rpc_io_service != NULL);
if (deadlineTimers.count(name) == 0)
{
deadlineTimers.insert(make_pair(name,
boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
}
deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl", false);
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
do {
bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
if (fConnected) break;
if (fWait)
MilliSleep(1000);
else
throw runtime_error("couldn't connect to server");
} while (fWait);
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "keypoolrefill" && n > 0) ConvertTo<boost::int64_t>(params[0]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
LogPrintf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| mit |
reinteractive/active_merchant | test/remote/gateways/remote_eway_rapid_test.rb | 6573 | require 'test_helper'
class RemoteEwayRapidTest < Test::Unit::TestCase
def setup
@gateway = EwayRapidGateway.new(fixtures(:eway_rapid))
@amount = 100
@failed_amount = -100
@credit_card = credit_card('4444333322221111')
@options = {
order_id: '1',
invoice: 'I1234',
billing_address: address,
description: 'Store Purchase',
redirect_url: 'http://bogus.com'
}
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_fully_loaded_purchase
response = @gateway.purchase(@amount, @credit_card,
redirect_url: 'http://awesomesauce.com',
ip: '0.0.0.0',
application_id: 'Woohoo',
partner_id: 'Woohoo',
transaction_type: 'Purchase',
description: 'Description',
order_id: 'orderid1',
invoice: 'I1234',
currency: 'AUD',
email: '[email protected]',
billing_address: {
title: 'Mr.',
name: 'Jim Awesome Smith',
company: 'Awesome Co',
address1: '1234 My Street',
address2: 'Apt 1',
city: 'Ottawa',
state: 'ON',
zip: 'K1C2N6',
country: 'CA',
phone: '(555)555-5555',
fax: '(555)555-6666'
},
shipping_address: {
title: 'Ms.',
name: 'Baker',
company: 'Elsewhere Inc.',
address1: '4321 Their St.',
address2: 'Apt 2',
city: 'Chicago',
state: 'IL',
zip: '60625',
country: 'US',
phone: '1115555555',
fax: '1115556666'
}
)
assert_success response
end
def test_successful_purchase_with_overly_long_fields
options = {
order_id: 'OrderId must be less than 50 characters otherwise it fails',
invoice: 'Max 12 chars',
description: 'EWay Rapid transactions fail if the description is more than 64 characters.',
billing_address: {
address1: 'The Billing Address 1 Cannot Be More Than Fifty Characters.',
address2: 'The Billing Address 2 Cannot Be More Than Fifty Characters.',
city: 'TheCityCannotBeMoreThanFiftyCharactersOrItAllFallsApart',
},
shipping_address: {
address1: 'The Shipping Address 1 Cannot Be More Than Fifty Characters.',
address2: 'The Shipping Address 2 Cannot Be More Than Fifty Characters.',
city: 'TheCityCannotBeMoreThanFiftyCharactersOrItAllFallsApart',
}
}
@credit_card.first_name = 'FullNameOnACardMustBeLessThanFiftyCharacters'
@credit_card.last_name = 'LastName'
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_failed_purchase
response = @gateway.purchase(@failed_amount, @credit_card, @options)
assert_failure response
assert_equal 'Invalid Payment TotalAmount', response.message
end
def test_successful_authorize_and_capture
authorize = @gateway.authorize(@amount, @credit_card, @options)
assert_success authorize
assert_equal 'Transaction Approved Successful', authorize.message
capture = @gateway.capture(nil, authorize.authorization)
assert_success capture
end
def test_failed_authorize
response = @gateway.authorize(@failed_amount, @credit_card, @options)
assert_failure response
assert_equal 'Error Failed', response.message
end
def test_failed_capture
response = @gateway.capture(@amount, 'bogus')
assert_failure response
assert_equal 'Invalid Auth Transaction ID for Capture/Void', response.message
end
def test_successful_void
authorize = @gateway.authorize(@amount, @credit_card, @options)
assert_success authorize
void = @gateway.void(authorize.authorization)
assert_success void
end
def test_failed_void
response = @gateway.void('bogus')
assert_failure response
assert_equal 'Invalid Auth Transaction ID for Capture/Void', response.message
end
def test_successful_refund
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
response = @gateway.refund(@amount, response.authorization, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_failed_refund
response = @gateway.refund(@amount, 'fakeid', @options)
assert_failure response
assert_equal 'Invalid DirectRefundRequest, Transaction ID', response.message
end
def test_successful_store
response = @gateway.store(@credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_failed_store
@options[:billing_address].merge!(country: nil)
response = @gateway.store(@credit_card, @options)
assert_failure response
assert_equal 'V6044', response.params['Errors']
assert_equal 'Customer CountryCode Required', response.message
end
def test_successful_update
response = @gateway.store(@credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
response = @gateway.update(response.authorization, @credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_successful_store_purchase
response = @gateway.store(@credit_card, @options)
assert_success response
assert_equal 'Transaction Approved Successful', response.message
response = @gateway.purchase(@amount, response.authorization, transaction_type: 'MOTO')
assert_success response
assert_equal 'Transaction Approved Successful', response.message
end
def test_invalid_login
gateway = EwayRapidGateway.new(
login: 'bogus',
password: 'bogus'
)
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_equal 'Unauthorized', response.message
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(100, @credit_card_success, @params)
end
clean_transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card_success.number, clean_transcript)
assert_scrubbed(@credit_card_success.verification_value.to_s, clean_transcript)
end
end
| mit |
happylixue/LeetCodeSol | problems/word-break/sol.py | 396 | class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
solved = [False for i in range(len(s) + 1)]
solved[0] = True
for i in range(len(s)):
for j in range(i + 1):
if s[j : i + 1] in dict:
solved[i + 1] |= solved[j]
return solved[len(s)]
| mit |
eonum/drg-search | vendor/assets/javascripts/styleguide.js | 24803 | /* ==========================================================
* autocomplete.js
* Deal with the Typeahead.js/Bloodhound library to build the search field autocomplete
*
* Author: Yann, [email protected]
* Date: 2014-05-01 14:23:18
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($, data) {
'use strict';
var $searchFields = $('.form-search .search-field');
if (data) {
// Init the Bloodhound suggestion engine
var bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(data, function(state) { return { value: state }; })
});
bloodhound.initialize();
// Init Typeahead on search-fields
$searchFields.typeahead({
hint: true,
highlight: true,
minLength: 1,
},
{
name: 'search',
displayKey: 'value',
source: bloodhound.ttAdapter()
});
}
// Insert the icons
$searchFields.after('<span class="icon icon--close" data-form-search-clear></span>');
$('.form-search').append('<button class="icon icon--search icon--before"></button>');
$('body').on('click', '[data-form-search-clear]', function () {
$('#search-field').val('').focus(); // clear search field and refocus it
});
}) (jQuery, (typeof searchData === 'undefined' ? false : searchData));
/* ==========================================================
* carousel.js
* Carousel helper
*
* Author: Yann, [email protected]
* Date: 2014-05-15 13:55:53
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(window).load(function () {
carouselInit(jQuery);
});
$(window).resize(function () {
carouselInit(jQuery);
});
// slideshow counter
var slideshow_total = $('.carousel-slideshow .item').length;
$('#carousel-total').text(slideshow_total);
$('.carousel-slideshow').on('slid.bs.carousel', function () {
var carouselData = $(this).data('bs.carousel');
var currentIndex = carouselData.getItemIndex(carouselData.$element.find('.item.active'));
var total = carouselData.$items.length;
var text = (currentIndex + 1);
$('#carousel-index').text(text);
$('#carousel-total').text(total);
});
}) (jQuery);
function carouselInit($) {
'use strict';
var $carousel = $('.carousel:not(.carousel-slideshow)');
$('.carousel .item:first-child').addClass('first');
$('.carousel .item:last-child').addClass('last');
$('.carousel').each(function() {
disableControl($(this));
});
$('.carousel').on('slid.bs.carousel', function () {
disableControl($(this));
});
if($carousel) {
$carousel.each(function () {
var biggestHeight = 0,
titleHeight = $(this).find('.item.active h3:first-child').height(),
imgHeight = $(this).find('.item.active .carousel-img').height();
$(this).find('.carousel-indicators, .carousel-control').css('top', titleHeight + imgHeight + 50);
$(this).find('.item').each(function () {
if ($(this).height() >= biggestHeight) {
biggestHeight = $(this).height();
}
});
$(this).find('.item').height(biggestHeight);
});
}
}
function disableControl(element) {
'use strict';
if (element.find('.first').hasClass('active')) {
element.find('.left').addClass('disabled').attr('aria-disabled', 'true');
} else {
element.find('.left').removeClass('disabled').attr('aria-disabled', 'false');
}
if (element.find('.last').hasClass('active')) {
element.find('.right').addClass('disabled').attr('aria-disabled', 'true');
} else {
element.find('.right').removeClass('disabled').attr('aria-disabled', 'false');
}
}
/* ==========================================================
* collapse.js
* Add class when nav collapse is open
*
* Author: Yann, [email protected]
* Date: 2014-05-06
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Normal Collapse
$('.collapse:not(tbody)').on('show.bs.collapse', function () {
$(this)
.prev()
.addClass('active icon--root')
.removeClass('icon--greater')
.attr({
'aria-selected': 'true',
'aria-expanded': 'true'
});
});
$('.collapse:not(tbody)').on('hide.bs.collapse', function () {
$(this)
.prev()
.removeClass('active icon--root')
.addClass('icon--greater')
.attr( {
'aria-selected': 'false',
'aria-expanded': 'false'
});
});
// Table Collapse
$('tbody.collapse').on('show.bs.collapse', function () {
$(this)
.prev().find('[data-toggle=collapse]')
.addClass('active')
.attr({
'aria-selected': 'true',
'aria-expanded': 'true'
});
});
$('tbody.collapse').on('hide.bs.collapse', function () {
$(this)
.prev().find('[data-toggle=collapse]')
.removeClass('active')
.attr({
'aria-selected': 'false',
'aria-expanded': 'false'
});
});
}) (jQuery);
/* ==========================================================
* drilldown.js
* Drilldown plugin scripts. For page-list-nav element
*
* Author: Toni Fisler, [email protected]
* Date: 2014-05-30 09:02:09
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
var options = {
event: 'click', // * View note below
selector: 'a', // * View note below
speed: 100,
cssClass: {
container: 'drilldown-container',
root: 'nav-page-list',
sub: 'drilldown-sub',
back: 'drilldown-back'
}
};
$('.drilldown').drilldown(options);
}) (jQuery);
/* ==========================================================
* global-nav.js
* Global Navigation syripts
*
* Author: Toni Fisler, [email protected]
* Date: 2014-05-27 16:36:15
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Handle scroll to position nav as fixed
var top = 36;
$(window).scroll(function () {
var y = $(this).scrollTop();
if (y >= top) {
if (!$('.nav-mobile').hasClass('fixed')) {
$('.nav-mobile').addClass('fixed')
.after('<div class="nav-mobile-spacer" id="spacer" style="height:36px;"></div>');
}
}
else {
if ($('.nav-mobile').hasClass('fixed')) {
$('.nav-mobile').removeClass('fixed');
$('#spacer').remove();
}
}
});
}) (jQuery);
// OUTLINE.JS
// https://github.com/lindsayevans/outline.js
//
// Based on http://www.paciellogroup.com/blog/2012/04/how-to-remove-css-outlines-in-an-accessible-manner/
//
// Hide outline on mouse interactions
// Show it on keyboard interactions
(function(doc){
'use strict';
var styleElement = doc.createElement('STYLE'),
domEvents = 'addEventListener' in doc,
addListener = function(type, callback){
// Basic cross-browser event handling
if (domEvents) {
doc.addEventListener(type, callback);
} else {
doc.attachEvent('on' + type, callback);
}
},
setCSS = function(cssText){
!!styleElement.styleSheet ? styleElement.styleSheet.cssText = cssText : styleElement.innerHTML = cssText;
};
doc.getElementsByTagName('HEAD')[0].appendChild(styleElement);
// Using mousedown instead of mouseover, so that previously focused elements don't lose focus ring on mouse move
addListener('mousedown', function(){
setCSS(':focus{outline:0!important}::-moz-focus-inner{border:0!important}');
});
addListener('keydown', function(){
setCSS('');
});
})(document);
/* ==========================================================
* print.js
* Add print preview windows
*
* Author: Yann, [email protected]
* Date: 2015-02-02
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
// Initialization
$.fn.printPreview = function() {
return this;
};
$.printPreview = {
printPreview: function(element) {
var $body = $('body'),
$container = $('.container-main'),
footnoteLinks = "",
linksIndex = 0;
$body.find('.nav-mobile, .drilldown, .nav-main, .header-separator, .nav-service, .nav-lang, .form-search, .yamm--select, header > div:first-child, footer, .alert, .icon--print, .social-sharing, form, .nav-process, .carousel-indicators, .carousel-control, .breadcrumb, .pagination-container').remove();
// if an element is passed, we want it to be the only thing to print out
if (element) {
element = $('[data-print=' + element + ']').clone(); // clone to fix issue with IE render
var header = $('header').clone(), // clone to fix issue with IE render
title = element.attr('data-title') ? '<h1>' + element.attr('data-title') + '</h1>' : '';
$container.addClass('print-element').html('').append(header, title, element);
}
$body.addClass('print-preview');
$container.prepend('<div class="row" id="print-settings">'+
'<div class="col-sm-12">'+
'<nav class="pagination-container clearfix">'+
'<span class="pull-left">'+
'<input type="checkbox" id="footnote-links"> '+
'<label for="footnote-links">Links as footnotes</label>'+
'</span>'+
'<ul class="pull-right">'+
'<li>'+
'<button id="print-button" title="print" class="btn"><span class="icon icon--print"></span></button>'+
' '+
'<button id="close-button" title="close" class="btn btn-secondary"><span class="icon icon--close"></span></button>'+
'</li>'+
'</ul>'+
'</nav>'+
'</div>'+
'</div>');
$('#print-button').click(function () {
$.printPreview.printProcess();
});
$('#close-button').click(function () {
$.printPreview.printClose();
});
$('a').not('.access-keys a').each(function () {
var target = $(this).attr('href');
target = String(target);
if (target !== "undefined" && target.indexOf("http") === 0) {
linksIndex ++;
footnoteLinks += '<li>'+target+'</li>';
$('<sup class="link-ref">('+linksIndex+')</sup>').insertAfter(this);
}
});
$('#footnote-links').change(function(){
if (this.checked) {
$container.append('<div id="footnote-links-wrapper" class="row footnote-links-wrapper">'+
'<div class="col-sm-12">'+
'<h3>Page Links</h3><hr>'+
'<ol>'+
footnoteLinks+
'</ol>'+
'</div>'+
'</div>');
$body.addClass('print-footnotes');
} else {
$('#footnote-links-wrapper').remove();
$body.removeClass('print-footnotes');
}
});
},
printProcess: function() {
window.print();
},
printClose: function() {
window.location.reload();
}
};
}) (jQuery);
/* ==========================================================
* rich-menu.js
* Add overlay when openning a rich yamm menu and define open/close events
*
* Author: Yann Gouffon, [email protected]
* Date: 2014-04-30 11:48:48
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
=========================================================== */
(function($) {
'use strict';
// Keep jQuery object in variables
var $yamm = $('.yamm'),
$yammClose = $('.yamm-close, .yamm-close-bottom'),
$dropdown = $('.yamm .dropdown'),
$dropdownToggle = $('.yamm .dropdown-toggle');
// Toggle dropdown and fix z-index errors
$yamm.each(function () {
var $that = $(this);
$that.on('click', '.dropdown-toggle', function () {
if (!$(this).parent().hasClass('open')){
var dropdownHeight = $(window).height() - 49;
$that.find('.drilldown-container').height( dropdownHeight );
}
});
});
$dropdownToggle.on('click', function() {
$(this).parents($dropdown).trigger('get.hidden');
});
$dropdown.on({
"shown.bs.dropdown": function() { this.closable = false; },
"get.hidden": function() { this.closable = true; }
});
$('.dropdown').on('show.bs.dropdown', function () {
$dropdown.removeClass('open');
$yamm.removeClass('nav-open');
$(this).parents($yamm).addClass('nav-open');
});
$dropdown.on('hide.bs.dropdown', function () {
// only remove the nav-open class if effectively closing dropdown
if (this.closable) {
$yamm.removeClass('nav-open');
}
return this.closable;
});
$(document).on('click', function(e) {
// hide dropdown if dropdown is open and target is not in dropdown
if ($('.dropdown.open').length > 0 && $(e.target).parents('.dropdown').length === 0) {
$('.dropdown.open .dropdown-toggle').trigger('click');
}
});
// Trigger close yamm menu
$dropdown.each(function () {
var $that = $(this);
$that.find($yammClose).click( function (e) {
e.preventDefault();
$that.find($dropdownToggle).trigger("click");
});
});
}) (jQuery);
/* ==========================================================
* select.js
* Scripts handling `select` elements
*
* Author: Toni Fisler, [email protected]
* Date: 2014-04-30 10:20:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(document).ready(function(){
$('select').chosen({
disable_search_threshold: 10
});
});
}) (jQuery);
/* ==========================================================
* shame.js
* DOM rewritting on mobile, issue #160
*
* Author: Yann, [email protected]
* Date: 2014-06-18 15:57:23
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$(document).ready(function () {
var id;
var isCarouselified = false;
var isCollapsified = false;
carouselify();
collapsify();
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(resizeLauncher, 500);
});
function resizeLauncher() {
carouselify();
collapsify();
}
function carouselify() {
var $tabFocus = $('.tab-focus'),
focusIndex = 0;
if($tabFocus && $(window).width() <= 767 && !isCarouselified ) {
isCarouselified = true;
$tabFocus.each(function () {
var $that = $(this),
itemIndex = -1;
focusIndex += 1;
$that.attr('id', 'tab-focus-'+focusIndex);
$that.next('.nav-tabs').hide();
// Prevent those mobile-only carousels from riding automatically by setting interval to 0
$that.addClass('carousel slide').removeClass('tab-content tab-border').attr('data-interval', 0);
$that.wrapInner('<div class="carousel-inner"></div>');
$that.prepend('<ol class="carousel-indicators"></ol>');
$that.find('.tab-pane').each(function () {
itemIndex += 1;
$(this).removeClass('tab-pane in active').addClass('item');
$that.find('.carousel-indicators').append('<li data-target="#tab-focus-' + focusIndex + '" data-slide-to="' + itemIndex + '"></li>');
});
$that.find('.item:first').addClass('active');
$that.find('.carousel-indicators li:first-child').addClass('active');
$that.append('<a class="left carousel-control icon icon--before icon--less" href="#tab-focus-' + focusIndex + '" data-slide="prev"></a><a class="right carousel-control icon icon--before icon--greater" href="#tab-focus-' + focusIndex + '" data-slide="next"></a>');
});
}
else if($tabFocus && $(window).width() > 767 && isCarouselified) {
isCarouselified = false;
$tabFocus.each(function () {
var $that = $(this);
focusIndex -= 1;
$that.attr('id', '');
$that.next('.nav-tabs-focus').css('display', 'flex'); // we can't use .show() because it should be a flex wrapper
$that.removeClass('carousel slide').addClass('tab-content tab-border');
$that.find('ol.carousel-indicators').remove();
$that.find('.item').each(function () {
$(this).addClass('tab-pane').removeClass('item');
$(this).css('height', 'auto');
});
$that.find('.tab-pane:first-child').addClass('active in');
if ( $that.find('.tab-pane').parent().hasClass('carousel-inner') ) {
$that.find('.tab-pane').unwrap();
}
$that.find('.carousel-control').remove();
});
}
}
function collapsify() {
var $navTab = $('.nav-tabs:not(.focus)'),
$collapsify = $('.collapsify'),
linkIndex = 0;
if($navTab && $(window).width() <= 767 && !isCollapsified ) {
isCollapsified = true;
$navTab.not('.tab-focus').each(function (){
var $that = $(this);
$that.removeClass('nav-tabs').addClass('collapsify');
$that.next('.tab-content').hide();
$that.find('a').each(function (){
var $target = $(this).attr('href');
linkIndex += 1;
$(this).unwrap();
$('<div class="collapse" id="collapse-' + linkIndex + '">' + $($target).html() + '</div>').insertAfter(this);
$(this).attr('data-toggle', 'collapse');
$(this).attr('data-target', '#collapse-' + linkIndex);
$(this).addClass('collapse-closed');
$(this).click(function(){
$(this).toggleClass('collapse-closed');
});
});
//$that.find('a:first-child').removeClass('collapse-closed').next('.collapse').addClass('in');
});
}
else if($collapsify && $(window).width() > 767 && isCollapsified) {
isCollapsified = false;
$collapsify.each(function (){
var $that = $(this);
$that.addClass('nav-tabs').removeClass('collapsify');
$that.next('.tab-content').show();
$that.find('a').each(function (){
linkIndex -= 1;
$(this).wrap('<li></li>');
$(this).parent().next('.collapse').remove();
$(this).attr('data-toggle', 'tab');
$(this).attr('data-target', '');
$(this).removeClass('collapse-closed');
});
$that.find('li a').each(function () {
var $tabTarget = $(this).attr('href');
if($($tabTarget).hasClass('active')){
$(this).parent().addClass('active');
}
});
});
}
}
});
}) (jQuery);
/* ==========================================================
* subnavigation.js
* Sub-navigation scripts, handles mainly how the nav-page-list behaves on small
* screens
*
* Author: Toni Fisler, [email protected]
* Date: 2014-09-24 10:18:19
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
subNavInit(jQuery);
$(window).resize(function () {
subNavInit(jQuery);
});
$('a[href=#collapseSubNav]').on('click', function() {
$(this).attr('aria-expanded', ($(this).attr('aria-expanded') === 'true' ? 'false' : 'true') );
});
}) (jQuery);
function subNavInit($) {
'use strict';
var $drilldown = $('.drilldown[class*=col-]');
if ($(window).width() <= 767 && !$drilldown.hasClass('collapse-enabled')) {
$drilldown
.addClass('collapse-enabled')
.find('.drilldown-container')
.addClass('collapse')
.attr('id', 'collapseSubNav');
} else if ($(window).width() > 767 && $drilldown.hasClass('collapse-enabled')) {
$drilldown
.removeClass('collapse-enabled')
.find('.drilldown-container')
.removeClass('collapse in')
.attr('id', '')
.css({
'height': 'auto'
});
}
}
/* ==========================================================
* tablesorter.js
* Control tablesort from markup
*
* Author: Simon Perdrisat, [email protected]
* Date: 2014-05-01 11:11:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$('.table-sort').tablesorter();
}) (jQuery);
/* ==========================================================
* tabs.js
* JS for the tabs and tab-focus elements
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
/**
* @constructor
* @param {Object} domNode
*/
function TabFocus(element) {
this.$wrapper = $(element).parent();
this.domNodes = '.tab-focus, .nav-tabs-focus';
this.delay = 3000;
this.playing = null;
this.interval = null;
this.$wrapper
.on('click', '.nav-tabs-focus', function() {
this.pause(null, true);
}.bind(this))
.on('click', '.tab-focus-control', function() {
if (this.playing) {
this.pause(null, true);
} else {
this.play(null, true);
}
}.bind(this));
this.play(null, true);
}
TabFocus.prototype = {
addListeners: function() {
this.$wrapper
.on('mouseenter.tabfocus focus.tabfocus', this.domNodes, this.pause.bind(this))
.on('mouseleave.tabfocus blur.tabfocus', this.domNodes, this.play.bind(this));
},
removeListeners: function() {
this.$wrapper
.off('mouseenter.tabfocus focus.tabfocus', this.domNodes)
.off('mouseleave.tabfocus blur.tabfocus', this.domNodes);
},
play: function(event, startListening) {
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(this.slide.bind(this), this.delay);
if (startListening) {
this.playing = true;
this.addListeners();
this.$wrapper.find('.tab-focus-control .icon').removeClass('icon--play').addClass('icon--pause');
}
},
pause: function(event, stopListening) {
clearInterval(this.interval);
if (stopListening) {
this.playing = false;
this.removeListeners();
this.$wrapper.find('.tab-focus-control .icon').removeClass('icon--pause').addClass('icon--play');
}
},
slide: function() {
var $nav = this.$wrapper.find('.nav-tabs-focus');
// If the nav is hidden, it means the focus has been changed for a carousel (mobile)
// We don’t want to slide automatically anymore
if ($nav.is(':hidden')) {
return this.pause(null, true);
}
if ($nav.find('> li').length) {
var tabs = this.$wrapper.find('.nav-tabs-focus > li'),
activeTab = tabs.filter('.active'),
nextTab = activeTab.next('li'),
newTab = nextTab.length ? nextTab.find('a') : tabs.eq(0).find('a');
newTab.tab('show');
}
}
};
$.fn.tabFocus = function() {
return this.each(function() {
if (!$.data(this, 'TabFocus')) {
$.data(this, 'TabFocus', new TabFocus(this));
}
});
};
$('.tab-focus').tabFocus();
})(jQuery);
/* ==========================================================
* treecrumb.js
* Change icon class to change the caret direction
*
* Author: Yann Gouffon, [email protected]
* Date: 2014-05-01 11:11:33
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
========================================================== */
(function($) {
'use strict';
$('.treecrumb').each(function() {
var $that = $(this);
$that.on('hide.bs.dropdown', function() {
$that.find('.dropdown-toggle span').removeClass('icon--bottom');
$that.find('.dropdown-toggle span').addClass('icon--right');
});
$that.on('show.bs.dropdown', function(e) {
var target = e.relatedTarget;
$that.find('.dropdown-toggle span').removeClass('icon--bottom');
$that.find('.dropdown-toggle span').addClass('icon--right');
$(target).find('span').removeClass('icon--right');
$(target).find('span').addClass('icon--bottom');
});
});
}) (jQuery);
| mit |
luissancheza/sice | js/jqwidgets/demos/angular/app/textarea/multiplevalues/main.ts | 297 | import { platformBrowser } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppModuleNgFactory } from '../../../temp/app/textarea/multiplevalues/app.module.ngfactory';
enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory); | mit |
nusendra/nusendra-blog | vendor/league/oauth2-server/src/Entities/Traits/AuthCodeTrait.php | 613 | <?php
/**
* @author Alex Bilbie <[email protected]>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
*
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Entities\Traits;
trait AuthCodeTrait
{
/**
* @var null|string
*/
protected $redirectUri;
/**
* @return string|null
*/
public function getRedirectUri()
{
return $this->redirectUri;
}
/**
* @param string $uri
*/
public function setRedirectUri($uri)
{
$this->redirectUri = $uri;
}
}
| mit |
yinchunlong/abelkhan-1 | ext/c++/thirdpart/c++/boost/libs/xpressive/doc/html/boost/xpressive/range_end.html | 5797 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function range_end</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Xpressive">
<link rel="up" href="../../header/boost/xpressive/sub_match_hpp.html" title="Header <boost/xpressive/sub_match.hpp>">
<link rel="prev" href="range_begin.html" title="Function range_begin">
<link rel="next" href="operator_idp13692272.html" title="Function template operator<<">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="range_begin.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/xpressive/sub_match_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_idp13692272.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.xpressive.range_end"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function range_end</span></h2>
<p>boost::xpressive::range_end — <code class="computeroutput">range_end()</code> to make <code class="computeroutput"><a class="link" href="sub_match.html" title="Struct template sub_match">sub_match</a><></code> a valid range </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/xpressive/sub_match_hpp.html" title="Header <boost/xpressive/sub_match.hpp>">boost/xpressive/sub_match.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> BidiIter<span class="special">></span> <span class="identifier">BidiIter</span> <span class="identifier">range_end</span><span class="special">(</span><a class="link" href="sub_match.html" title="Struct template sub_match">sub_match</a><span class="special"><</span> <span class="identifier">BidiIter</span> <span class="special">></span> <span class="special">&</span> sub<span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> BidiIter<span class="special">></span>
<span class="identifier">BidiIter</span> <span class="identifier">range_end</span><span class="special">(</span><a class="link" href="sub_match.html" title="Struct template sub_match">sub_match</a><span class="special"><</span> <span class="identifier">BidiIter</span> <span class="special">></span> <span class="keyword">const</span> <span class="special">&</span> sub<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp49134880"></a><h2>Description</h2>
<p>
</p>
<div class="variablelist"><table border="0">
<col align="left" valign="top">
<tbody>
<tr>
<td><p><span class="term">Parameters:</span></p></td>
<td><div class="variablelist"><table border="0">
<col align="left" valign="top">
<tbody><tr>
<td><p><span class="term"><code class="computeroutput">sub</code></span></p></td>
<td><p>the <code class="computeroutput"><code class="computeroutput"><a class="link" href="sub_match.html" title="Struct template sub_match">sub_match</a></code><></code> object denoting the range </p></td>
</tr></tbody>
</table></div></td>
</tr>
<tr>
<td><p><span class="term">Requires:</span></p></td>
<td><p><code class="computeroutput">sub.second</code> is not singular </p></td>
</tr>
<tr>
<td><p><span class="term">Returns:</span></p></td>
<td><p><code class="computeroutput">sub.second</code> </p></td>
</tr>
</tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="range_begin.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/xpressive/sub_match_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_idp13692272.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
swsglobal/DotSpatial | Source/DotSpatial.Controls/LayoutForm.cs | 3537 | // ********************************************************************************************************
// Product Name: DotSpatial.Forms.LayoutForm
// Description: A form that shows the mapwindow layout
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is by Brian Marchionni Aug 2009
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// ------------------|------------|---------------------------------------------------------------
// Ted Dunsford | 8/28/2009 | Cleaned up some code formatting using resharper
// ********************************************************************************************************
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace DotSpatial.Controls
{
/// <summary>
/// This is the primary form where the print layout content is organized before printing
/// </summary>
public partial class LayoutForm : Form
{
/// <summary>
/// Default constructor for creating a new instance of hte Layout form
/// </summary>
public LayoutForm()
{
InitializeComponent();
if (Mono.Mono.IsRunningOnMono())
{
// On Mac and possibly other Mono platforms, GdipCreateLineBrushFromRect
// in gdiplus native lib returns InvalidParameter in Mono file LinearGradientBrush.cs
// if a StripPanel's Width or Height is 0, so force them to non-0.
_toolStripContainer1.TopToolStripPanel.Size = new Size(_toolStripContainer1.TopToolStripPanel.Size.Width, 1);
_toolStripContainer1.BottomToolStripPanel.Size = new Size(_toolStripContainer1.BottomToolStripPanel.Size.Width, 1);
_toolStripContainer1.LeftToolStripPanel.Size = new Size(1, _toolStripContainer1.LeftToolStripPanel.Size.Height);
_toolStripContainer1.RightToolStripPanel.Size = new Size(1, _toolStripContainer1.RightToolStripPanel.Size.Height);
}
}
/// <summary>
/// Gets or sets the map that will be used in the layout
/// </summary>
public Map MapControl
{
get { return _layoutControl1.MapControl; }
set { _layoutControl1.MapControl = value; }
}
/// <summary>
/// Gets layout control.
/// </summary>
public LayoutControl LayoutControl
{
get { return _layoutControl1; }
}
private void layoutMenuStrip1_CloseClicked(object sender, EventArgs e)
{
this.Close();
}
private void layoutControl1_FilenameChanged(object sender, EventArgs e)
{
Text = !string.IsNullOrEmpty(_layoutControl1.Filename)
? "DotSpatial Print Layout - " + Path.GetFileName(this._layoutControl1.Filename)
: "DotSpatial Print Layout";
}
private void LayoutForm_Load(object sender, EventArgs e)
{
if (MapControl != null)
{
var mapElement = _layoutControl1.CreateMapElement();
mapElement.Size = _layoutControl1.Size;
_layoutControl1.AddToLayout(mapElement);
}
}
}
} | mit |
PrJared/sabbath-school-lessons | src/en/2020-01-cq/01/03.md | 1908 | ---
title: A Deeper Look into Chapter 1
date: 30/12/2019
---
#### inTerpret
What is temperance?
Ellen White stated that temperance is “to dispense entirely with everything hurtful and to use judiciously that which is healthful” (Patriarchs and Prophets, 562). In other words, temperance is abstaining from the bad and moderation in the good.
`What were the issues with the Babylonian diet?`
The drink provided was alcoholic. The word for wine in the Bible can refer to fermented or unfermented grape juice. And the Bible is clear in its stance on the fermented: “Do not look on the wine when it is red, when it sparkles in the cup, when it swirls around smoothly; at the last it bites like a serpent, and stings like a viper” (Prov. 23:31, 32). This text does not refer to regular grape juice!
The food had been offered to idols.
The blood had not been drained in slaughter. “You must not eat meat that still has blood in it” (Lev. 17:12, NIRV).
The Babylonian diet included unclean meat (Leviticus 11).
`What was the Daniel diet?`
“Prove thy servants, I beseech thee, ten days; and let them give us pulse to eat, and water to drink” (Dan. 1:12, KJV). The term pulse has roots from the word for seed and is a reference to the diet in Genesis. “And God said, ‘See, I have given you every herb that yields seed which is on the face of all the earth, and every tree whose fruit yields seed; to you it shall be for food’ ” (Gen. 1:29). The book of Daniel begins with Daniel and his three friends choosing the Edenic diet.
We are not saved through vegetarianism or veganism. However, the book of Daniel does reveal the correlation between diet and spiritual understanding. The key to understanding the prophetic books of Daniel is not limited to the intellectual dimension alone, but also includes the physical dimension—namely, what we choose to ingest into our bodies.
`` | mit |
sanyaade-mobiledev/smart-platform | lib/RSP/JSObject/MediaFile/Mogile.pm | 2311 | package RSP::JSObject::MediaFile::Mogile;
use strict;
use warnings;
use Digest::MD5;
use LWP::UserAgent;
use File::MMagic;
use base 'RSP::JSObject::MediaFile';
sub new {
my $class = shift;
my $mog = shift;
my $name = shift;
my $paths = shift;
my $self = { mog => $mog, paths => $paths, name => $name };
bless $self, $class;
}
sub remove {
my $self = shift;
$self->{mog}->delete( $self->filename );
$self->clearcache( $self->filename );
}
sub clearcache {
my $class = shift;
my $fname = shift;
# XXX = wtf?
foreach my $key ( (keys %{ $class->properties }, 'content')) {
#$tx->cache->delete( $class->cachename( $key, $fname ) );
}
}
sub cachename {
my $self = shift;
my $what = shift;
if (!$what) {
die "no data type key";
}
my $name = shift;
if (!$name) {
if ( ref($self) ) {
$name = $self->{name};
} else {
die "no name";
}
}
if (!$what) { die "no type for cache name" }
return join(":", "__mogilefs__", $what, $name);
}
sub cached_getandset {
my $self = shift;
my $what = shift;
my $gen = shift;
my $cachekey = $self->cachename( $what );
if ( $self->{ $what } ) {
return $self->{ $what };
} else {
$self->{ $what } = $gen->();
}
return $self->{ $what };
}
sub md5 {
my $self = shift;
$self->cached_getandset( 'digest', sub { Digest::MD5::md5_hex( $self->contents ) } );
}
sub filename {
my $self = shift;
return $self->{name};
}
sub mimetype {
my $self = shift;
$self->cached_getandset(
'mimetype', sub {
my $mm = File::MMagic->new;
return $mm->checktype_contents( $self->contents );
}
);
}
sub size {
my $self = shift;
$self->cached_getandset(
'size',
sub {
return bytes::length( $self->contents );
}
);
}
sub contents {
my $self = shift;
$self->cached_getandset(
'content',
sub {
my $ua = LWP::UserAgent->new;
foreach my $path (@{ $self->{paths} }) {
my $response = $ua->get($path);
if ( $response->is_success ) {
return $response->content;
}
}
}
);
}
sub as_string {
my $self = shift;
my $data = $self->contents;
if ( $self->mimetype =~ /text/ ) {
return Encode::decode("utf8", $data);
} else {
return $data;
}
}
1;
| mit |
xiaoliang2016/JRTPLib-for-Android | src/rtpudpv6transmitter.h | 11442 | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2011 Jori Liesenborgs
Contact: [email protected]
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
/**
* \file rtpudpv6transmitter.h
*/
#ifndef RTPUDPV6TRANSMITTER_H
#define RTPUDPV6TRANSMITTER_H
#include "rtpconfig.h"
#ifdef RTP_SUPPORT_IPV6
#include "rtptransmitter.h"
#include "rtpipv6destination.h"
#include "rtphashtable.h"
#include "rtpkeyhashtable.h"
#if ! (defined(WIN32) || defined(_WIN32_WCE))
#include <netinet/in.h>
#endif // WIN32
#include <string.h>
#include <list>
#ifdef RTP_SUPPORT_THREAD
#include <jthread/jmutex.h>
#endif // RTP_SUPPORT_THREAD
#define RTPUDPV6TRANS_HASHSIZE 8317
#define RTPUDPV6TRANS_DEFAULTPORTBASE 5000
#define RTPUDPV6TRANS_RTPRECEIVEBUFFER 32768
#define RTPUDPV6TRANS_RTCPRECEIVEBUFFER 32768
#define RTPUDPV6TRANS_RTPTRANSMITBUFFER 32768
#define RTPUDPV6TRANS_RTCPTRANSMITBUFFER 32768
namespace jrtplib
{
/** Parameters for the UDP over IPv6 transmitter. */
class RTPUDPv6TransmissionParams : public RTPTransmissionParams
{
public:
RTPUDPv6TransmissionParams():RTPTransmissionParams(RTPTransmitter::IPv6UDPProto) { portbase = RTPUDPV6TRANS_DEFAULTPORTBASE; for (int i = 0 ; i < 16 ; i++) bindIP.s6_addr[i] = 0; multicastTTL = 1; mcastifidx = 0; rtpsendbuf = RTPUDPV6TRANS_RTPTRANSMITBUFFER; rtprecvbuf= RTPUDPV6TRANS_RTPRECEIVEBUFFER; rtcpsendbuf = RTPUDPV6TRANS_RTCPTRANSMITBUFFER; rtcprecvbuf = RTPUDPV6TRANS_RTCPRECEIVEBUFFER; }
/** Sets the IP address which is used to bind the sockets to \c ip. */
void SetBindIP(in6_addr ip) { bindIP = ip; }
/** Sets the multicast interface index. */
void SetMulticastInterfaceIndex(unsigned int idx) { mcastifidx = idx; }
/** Sets the RTP portbase to \c pbase. This has to be an even number. */
void SetPortbase(uint16_t pbase) { portbase = pbase; }
/** Sets the multicast TTL to be used to \c mcastTTL. */
void SetMulticastTTL(uint8_t mcastTTL) { multicastTTL = mcastTTL; }
/** Passes a list of IP addresses which will be used as the local IP addresses. */
void SetLocalIPList(std::list<in6_addr> &iplist) { localIPs = iplist; }
/** Clears the list of local IP addresses.
* Clears the list of local IP addresses. An empty list will make the transmission component
* itself determine the local IP addresses.
*/
void ClearLocalIPList() { localIPs.clear(); }
/** Returns the IP address which will be used to bind the sockets. */
in6_addr GetBindIP() const { return bindIP; }
/** Returns the multicast interface index. */
unsigned int GetMulticastInterfaceIndex() const { return mcastifidx; }
/** Returns the RTP portbase which will be used (default is 5000). */
uint16_t GetPortbase() const { return portbase; }
/** Returns the multicast TTL which will be used (default is 1). */
uint8_t GetMulticastTTL() const { return multicastTTL; }
/** Returns the list of local IP addresses. */
const std::list<in6_addr> &GetLocalIPList() const { return localIPs; }
/** Sets the RTP socket's send buffer size. */
void SetRTPSendBuffer(int s) { rtpsendbuf = s; }
/** Sets the RTP socket's receive buffer size. */
void SetRTPReceiveBuffer(int s) { rtprecvbuf = s; }
/** Sets the RTCP socket's send buffer size. */
void SetRTCPSendBuffer(int s) { rtcpsendbuf = s; }
/** Sets the RTCP socket's receive buffer size. */
void SetRTCPReceiveBuffer(int s) { rtcprecvbuf = s; }
/** Returns the RTP socket's send buffer size. */
int GetRTPSendBuffer() const { return rtpsendbuf; }
/** Returns the RTP socket's receive buffer size. */
int GetRTPReceiveBuffer() const { return rtprecvbuf; }
/** Returns the RTCP socket's send buffer size. */
int GetRTCPSendBuffer() const { return rtcpsendbuf; }
/** Returns the RTCP socket's receive buffer size. */
int GetRTCPReceiveBuffer() const { return rtcprecvbuf; }
private:
uint16_t portbase;
in6_addr bindIP;
unsigned int mcastifidx;
std::list<in6_addr> localIPs;
uint8_t multicastTTL;
int rtpsendbuf, rtprecvbuf;
int rtcpsendbuf, rtcprecvbuf;
};
/** Additional information about the UDP over IPv6 transmitter. */
class RTPUDPv6TransmissionInfo : public RTPTransmissionInfo
{
public:
#if ! (defined(WIN32) || defined(_WIN32_WCE))
RTPUDPv6TransmissionInfo(std::list<in6_addr> iplist,int rtpsock,int rtcpsock) : RTPTransmissionInfo(RTPTransmitter::IPv6UDPProto)
#else
RTPUDPv6TransmissionInfo(std::list<in6_addr> iplist,SOCKET rtpsock,SOCKET rtcpsock) : RTPTransmissionInfo(RTPTransmitter::IPv6UDPProto)
#endif // WIN32
{ localIPlist = iplist; rtpsocket = rtpsock; rtcpsocket = rtcpsock; }
~RTPUDPv6TransmissionInfo() { }
/** Returns the list of IPv6 addresses the transmitter considers to be the local IP addresses. */
std::list<in6_addr> GetLocalIPList() const { return localIPlist; }
#if ! (defined(WIN32) || defined(_WIN32_WCE))
/** Returns the socket descriptor used for receiving and transmitting RTP packets. */
int GetRTPSocket() const { return rtpsocket; }
/** Returns the socket descriptor used for receiving and transmitting RTCP packets. */
int GetRTCPSocket() const { return rtcpsocket; }
#else
SOCKET GetRTPSocket() const { return rtpsocket; }
SOCKET GetRTCPSocket() const { return rtcpsocket; }
#endif // WIN32
private:
std::list<in6_addr> localIPlist;
#if ! (defined(WIN32) || defined(_WIN32_WCE))
int rtpsocket,rtcpsocket;
#else
SOCKET rtpsocket,rtcpsocket;
#endif // WIN32
};
class RTPUDPv6Trans_GetHashIndex_IPv6Dest
{
public:
static int GetIndex(const RTPIPv6Destination &d) { in6_addr ip = d.GetIP(); return ((((uint32_t)ip.s6_addr[12])<<24)|(((uint32_t)ip.s6_addr[13])<<16)|(((uint32_t)ip.s6_addr[14])<<8)|((uint32_t)ip.s6_addr[15]))%RTPUDPV6TRANS_HASHSIZE; }
};
class RTPUDPv6Trans_GetHashIndex_in6_addr
{
public:
static int GetIndex(const in6_addr &ip) { return ((((uint32_t)ip.s6_addr[12])<<24)|(((uint32_t)ip.s6_addr[13])<<16)|(((uint32_t)ip.s6_addr[14])<<8)|((uint32_t)ip.s6_addr[15]))%RTPUDPV6TRANS_HASHSIZE; }
};
#define RTPUDPV6TRANS_HEADERSIZE (40+8)
/** An UDP over IPv6 transmitter.
* This class inherits the RTPTransmitter interface and implements a transmission component
* which uses UDP over IPv6 to send and receive RTP and RTCP data. The component's parameters
* are described by the class RTPUDPv6TransmissionParams. The functions which have an RTPAddress
* argument require an argument of RTPIPv6Address. The GetTransmissionInfo member function
* returns an instance of type RTPUDPv6TransmissionInfo.
*/
class RTPUDPv6Transmitter : public RTPTransmitter
{
public:
RTPUDPv6Transmitter(RTPMemoryManager *mgr);
~RTPUDPv6Transmitter();
int Init(bool treadsafe);
int Create(size_t maxpacksize,const RTPTransmissionParams *transparams);
void Destroy();
RTPTransmissionInfo *GetTransmissionInfo();
void DeleteTransmissionInfo(RTPTransmissionInfo *inf);
int GetLocalHostName(uint8_t *buffer,size_t *bufferlength);
bool ComesFromThisTransmitter(const RTPAddress *addr);
size_t GetHeaderOverhead() { return RTPUDPV6TRANS_HEADERSIZE; }
int Poll();
int WaitForIncomingData(const RTPTime &delay,bool *dataavailable = 0);
int AbortWait();
int SendRTPData(const void *data,size_t len);
int SendRTCPData(const void *data,size_t len);
int AddDestination(const RTPAddress &addr);
int DeleteDestination(const RTPAddress &addr);
void ClearDestinations();
bool SupportsMulticasting();
int JoinMulticastGroup(const RTPAddress &addr);
int LeaveMulticastGroup(const RTPAddress &addr);
void LeaveAllMulticastGroups();
int SetReceiveMode(RTPTransmitter::ReceiveMode m);
int AddToIgnoreList(const RTPAddress &addr);
int DeleteFromIgnoreList(const RTPAddress &addr);
void ClearIgnoreList();
int AddToAcceptList(const RTPAddress &addr);
int DeleteFromAcceptList(const RTPAddress &addr);
void ClearAcceptList();
int SetMaximumPacketSize(size_t s);
bool NewDataAvailable();
RTPRawPacket *GetNextPacket();
#ifdef RTPDEBUG
void Dump();
#endif // RTPDEBUG
private:
int CreateLocalIPList();
bool GetLocalIPList_Interfaces();
void GetLocalIPList_DNS();
void AddLoopbackAddress();
void FlushPackets();
int PollSocket(bool rtp);
int ProcessAddAcceptIgnoreEntry(in6_addr ip,uint16_t port);
int ProcessDeleteAcceptIgnoreEntry(in6_addr ip,uint16_t port);
#ifdef RTP_SUPPORT_IPV6MULTICAST
bool SetMulticastTTL(uint8_t ttl);
#endif // RTP_SUPPORT_IPV6MULTICAST
bool ShouldAcceptData(in6_addr srcip,uint16_t srcport);
void ClearAcceptIgnoreInfo();
bool init;
bool created;
bool waitingfordata;
#if (defined(WIN32) || defined(_WIN32_WCE))
SOCKET rtpsock,rtcpsock;
#else // not using winsock
int rtpsock,rtcpsock;
#endif // WIN32
in6_addr bindIP;
unsigned int mcastifidx;
std::list<in6_addr> localIPs;
uint16_t portbase;
uint8_t multicastTTL;
RTPTransmitter::ReceiveMode receivemode;
uint8_t *localhostname;
size_t localhostnamelength;
RTPHashTable<const RTPIPv6Destination,RTPUDPv6Trans_GetHashIndex_IPv6Dest,RTPUDPV6TRANS_HASHSIZE> destinations;
#ifdef RTP_SUPPORT_IPV6MULTICAST
RTPHashTable<const in6_addr,RTPUDPv6Trans_GetHashIndex_in6_addr,RTPUDPV6TRANS_HASHSIZE> multicastgroups;
#endif // RTP_SUPPORT_IPV6MULTICAST
std::list<RTPRawPacket*> rawpacketlist;
bool supportsmulticasting;
size_t maxpacksize;
class PortInfo
{
public:
PortInfo() { all = false; }
bool all;
std::list<uint16_t> portlist;
};
RTPKeyHashTable<const in6_addr,PortInfo*,RTPUDPv6Trans_GetHashIndex_in6_addr,RTPUDPV6TRANS_HASHSIZE> acceptignoreinfo;
// notification descriptors for AbortWait (0 is for reading, 1 for writing)
#if (defined(WIN32) || defined(_WIN32_WCE))
SOCKET abortdesc[2];
#else
int abortdesc[2];
#endif // WIN32
int CreateAbortDescriptors();
void DestroyAbortDescriptors();
void AbortWaitInternal();
#ifdef RTP_SUPPORT_THREAD
jthread::JMutex mainmutex,waitmutex;
int threadsafe;
#endif // RTP_SUPPORT_THREAD
};
} // end namespace
#endif // RTP_SUPPORT_IPV6
#endif // RTPUDPV6TRANSMITTER_H
| mit |
wujuguang/mako | mako/codegen.py | 47892 | # mako/codegen.py
# Copyright 2006-2019 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""provides functionality for rendering a parsetree constructing into module
source code."""
import json
import re
import time
from mako import ast
from mako import compat
from mako import exceptions
from mako import filters
from mako import parsetree
from mako import util
from mako.pygen import PythonPrinter
MAGIC_NUMBER = 10
# names which are hardwired into the
# template and are not accessed via the
# context itself
TOPLEVEL_DECLARED = set(["UNDEFINED", "STOP_RENDERING"])
RESERVED_NAMES = set(["context", "loop"]).union(TOPLEVEL_DECLARED)
def compile( # noqa
node,
uri,
filename=None,
default_filters=None,
buffer_filters=None,
imports=None,
future_imports=None,
source_encoding=None,
generate_magic_comment=True,
disable_unicode=False,
strict_undefined=False,
enable_loop=True,
reserved_names=frozenset(),
):
"""Generate module source code given a parsetree node,
uri, and optional source filename"""
# if on Py2K, push the "source_encoding" string to be
# a bytestring itself, as we will be embedding it into
# the generated source and we don't want to coerce the
# result into a unicode object, in "disable_unicode" mode
if not compat.py3k and isinstance(source_encoding, compat.text_type):
source_encoding = source_encoding.encode(source_encoding)
buf = util.FastEncodingBuffer()
printer = PythonPrinter(buf)
_GenerateRenderMethod(
printer,
_CompileContext(
uri,
filename,
default_filters,
buffer_filters,
imports,
future_imports,
source_encoding,
generate_magic_comment,
disable_unicode,
strict_undefined,
enable_loop,
reserved_names,
),
node,
)
return buf.getvalue()
class _CompileContext(object):
def __init__(
self,
uri,
filename,
default_filters,
buffer_filters,
imports,
future_imports,
source_encoding,
generate_magic_comment,
disable_unicode,
strict_undefined,
enable_loop,
reserved_names,
):
self.uri = uri
self.filename = filename
self.default_filters = default_filters
self.buffer_filters = buffer_filters
self.imports = imports
self.future_imports = future_imports
self.source_encoding = source_encoding
self.generate_magic_comment = generate_magic_comment
self.disable_unicode = disable_unicode
self.strict_undefined = strict_undefined
self.enable_loop = enable_loop
self.reserved_names = reserved_names
class _GenerateRenderMethod(object):
"""A template visitor object which generates the
full module source for a template.
"""
def __init__(self, printer, compiler, node):
self.printer = printer
self.compiler = compiler
self.node = node
self.identifier_stack = [None]
self.in_def = isinstance(node, (parsetree.DefTag, parsetree.BlockTag))
if self.in_def:
name = "render_%s" % node.funcname
args = node.get_argument_expressions()
filtered = len(node.filter_args.args) > 0
buffered = eval(node.attributes.get("buffered", "False"))
cached = eval(node.attributes.get("cached", "False"))
defs = None
pagetag = None
if node.is_block and not node.is_anonymous:
args += ["**pageargs"]
else:
defs = self.write_toplevel()
pagetag = self.compiler.pagetag
name = "render_body"
if pagetag is not None:
args = pagetag.body_decl.get_argument_expressions()
if not pagetag.body_decl.kwargs:
args += ["**pageargs"]
cached = eval(pagetag.attributes.get("cached", "False"))
self.compiler.enable_loop = self.compiler.enable_loop or eval(
pagetag.attributes.get("enable_loop", "False")
)
else:
args = ["**pageargs"]
cached = False
buffered = filtered = False
if args is None:
args = ["context"]
else:
args = [a for a in ["context"] + args]
self.write_render_callable(
pagetag or node, name, args, buffered, filtered, cached
)
if defs is not None:
for node in defs:
_GenerateRenderMethod(printer, compiler, node)
if not self.in_def:
self.write_metadata_struct()
def write_metadata_struct(self):
self.printer.source_map[self.printer.lineno] = max(
self.printer.source_map
)
struct = {
"filename": self.compiler.filename,
"uri": self.compiler.uri,
"source_encoding": self.compiler.source_encoding,
"line_map": self.printer.source_map,
}
self.printer.writelines(
'"""',
"__M_BEGIN_METADATA",
json.dumps(struct),
"__M_END_METADATA\n" '"""',
)
@property
def identifiers(self):
return self.identifier_stack[-1]
def write_toplevel(self):
"""Traverse a template structure for module-level directives and
generate the start of module-level code.
"""
inherit = []
namespaces = {}
module_code = []
self.compiler.pagetag = None
class FindTopLevel(object):
def visitInheritTag(s, node):
inherit.append(node)
def visitNamespaceTag(s, node):
namespaces[node.name] = node
def visitPageTag(s, node):
self.compiler.pagetag = node
def visitCode(s, node):
if node.ismodule:
module_code.append(node)
f = FindTopLevel()
for n in self.node.nodes:
n.accept_visitor(f)
self.compiler.namespaces = namespaces
module_ident = set()
for n in module_code:
module_ident = module_ident.union(n.declared_identifiers())
module_identifiers = _Identifiers(self.compiler)
module_identifiers.declared = module_ident
# module-level names, python code
if (
self.compiler.generate_magic_comment
and self.compiler.source_encoding
):
self.printer.writeline(
"# -*- coding:%s -*-" % self.compiler.source_encoding
)
if self.compiler.future_imports:
self.printer.writeline(
"from __future__ import %s"
% (", ".join(self.compiler.future_imports),)
)
self.printer.writeline("from mako import runtime, filters, cache")
self.printer.writeline("UNDEFINED = runtime.UNDEFINED")
self.printer.writeline("STOP_RENDERING = runtime.STOP_RENDERING")
self.printer.writeline("__M_dict_builtin = dict")
self.printer.writeline("__M_locals_builtin = locals")
self.printer.writeline("_magic_number = %r" % MAGIC_NUMBER)
self.printer.writeline("_modified_time = %r" % time.time())
self.printer.writeline("_enable_loop = %r" % self.compiler.enable_loop)
self.printer.writeline(
"_template_filename = %r" % self.compiler.filename
)
self.printer.writeline("_template_uri = %r" % self.compiler.uri)
self.printer.writeline(
"_source_encoding = %r" % self.compiler.source_encoding
)
if self.compiler.imports:
buf = ""
for imp in self.compiler.imports:
buf += imp + "\n"
self.printer.writeline(imp)
impcode = ast.PythonCode(
buf,
source="",
lineno=0,
pos=0,
filename="template defined imports",
)
else:
impcode = None
main_identifiers = module_identifiers.branch(self.node)
mit = module_identifiers.topleveldefs
module_identifiers.topleveldefs = mit.union(
main_identifiers.topleveldefs
)
module_identifiers.declared.update(TOPLEVEL_DECLARED)
if impcode:
module_identifiers.declared.update(impcode.declared_identifiers)
self.compiler.identifiers = module_identifiers
self.printer.writeline(
"_exports = %r"
% [n.name for n in main_identifiers.topleveldefs.values()]
)
self.printer.write_blanks(2)
if len(module_code):
self.write_module_code(module_code)
if len(inherit):
self.write_namespaces(namespaces)
self.write_inherit(inherit[-1])
elif len(namespaces):
self.write_namespaces(namespaces)
return list(main_identifiers.topleveldefs.values())
def write_render_callable(
self, node, name, args, buffered, filtered, cached
):
"""write a top-level render callable.
this could be the main render() method or that of a top-level def."""
if self.in_def:
decorator = node.decorator
if decorator:
self.printer.writeline(
"@runtime._decorate_toplevel(%s)" % decorator
)
self.printer.start_source(node.lineno)
self.printer.writelines(
"def %s(%s):" % (name, ",".join(args)),
# push new frame, assign current frame to __M_caller
"__M_caller = context.caller_stack._push_frame()",
"try:",
)
if buffered or filtered or cached:
self.printer.writeline("context._push_buffer()")
self.identifier_stack.append(
self.compiler.identifiers.branch(self.node)
)
if (not self.in_def or self.node.is_block) and "**pageargs" in args:
self.identifier_stack[-1].argument_declared.add("pageargs")
if not self.in_def and (
len(self.identifiers.locally_assigned) > 0
or len(self.identifiers.argument_declared) > 0
):
self.printer.writeline(
"__M_locals = __M_dict_builtin(%s)"
% ",".join(
[
"%s=%s" % (x, x)
for x in self.identifiers.argument_declared
]
)
)
self.write_variable_declares(self.identifiers, toplevel=True)
for n in self.node.nodes:
n.accept_visitor(self)
self.write_def_finish(self.node, buffered, filtered, cached)
self.printer.writeline(None)
self.printer.write_blanks(2)
if cached:
self.write_cache_decorator(
node, name, args, buffered, self.identifiers, toplevel=True
)
def write_module_code(self, module_code):
"""write module-level template code, i.e. that which
is enclosed in <%! %> tags in the template."""
for n in module_code:
self.printer.write_indented_block(n.text, starting_lineno=n.lineno)
def write_inherit(self, node):
"""write the module-level inheritance-determination callable."""
self.printer.writelines(
"def _mako_inherit(template, context):",
"_mako_generate_namespaces(context)",
"return runtime._inherit_from(context, %s, _template_uri)"
% (node.parsed_attributes["file"]),
None,
)
def write_namespaces(self, namespaces):
"""write the module-level namespace-generating callable."""
self.printer.writelines(
"def _mako_get_namespace(context, name):",
"try:",
"return context.namespaces[(__name__, name)]",
"except KeyError:",
"_mako_generate_namespaces(context)",
"return context.namespaces[(__name__, name)]",
None,
None,
)
self.printer.writeline("def _mako_generate_namespaces(context):")
for node in namespaces.values():
if "import" in node.attributes:
self.compiler.has_ns_imports = True
self.printer.start_source(node.lineno)
if len(node.nodes):
self.printer.writeline("def make_namespace():")
export = []
identifiers = self.compiler.identifiers.branch(node)
self.in_def = True
class NSDefVisitor(object):
def visitDefTag(s, node):
s.visitDefOrBase(node)
def visitBlockTag(s, node):
s.visitDefOrBase(node)
def visitDefOrBase(s, node):
if node.is_anonymous:
raise exceptions.CompileException(
"Can't put anonymous blocks inside "
"<%namespace>",
**node.exception_kwargs
)
self.write_inline_def(node, identifiers, nested=False)
export.append(node.funcname)
vis = NSDefVisitor()
for n in node.nodes:
n.accept_visitor(vis)
self.printer.writeline("return [%s]" % (",".join(export)))
self.printer.writeline(None)
self.in_def = False
callable_name = "make_namespace()"
else:
callable_name = "None"
if "file" in node.parsed_attributes:
self.printer.writeline(
"ns = runtime.TemplateNamespace(%r,"
" context._clean_inheritance_tokens(),"
" templateuri=%s, callables=%s, "
" calling_uri=_template_uri)"
% (
node.name,
node.parsed_attributes.get("file", "None"),
callable_name,
)
)
elif "module" in node.parsed_attributes:
self.printer.writeline(
"ns = runtime.ModuleNamespace(%r,"
" context._clean_inheritance_tokens(),"
" callables=%s, calling_uri=_template_uri,"
" module=%s)"
% (
node.name,
callable_name,
node.parsed_attributes.get("module", "None"),
)
)
else:
self.printer.writeline(
"ns = runtime.Namespace(%r,"
" context._clean_inheritance_tokens(),"
" callables=%s, calling_uri=_template_uri)"
% (node.name, callable_name)
)
if eval(node.attributes.get("inheritable", "False")):
self.printer.writeline("context['self'].%s = ns" % (node.name))
self.printer.writeline(
"context.namespaces[(__name__, %s)] = ns" % repr(node.name)
)
self.printer.write_blanks(1)
if not len(namespaces):
self.printer.writeline("pass")
self.printer.writeline(None)
def write_variable_declares(self, identifiers, toplevel=False, limit=None):
"""write variable declarations at the top of a function.
the variable declarations are in the form of callable
definitions for defs and/or name lookup within the
function's context argument. the names declared are based
on the names that are referenced in the function body,
which don't otherwise have any explicit assignment
operation. names that are assigned within the body are
assumed to be locally-scoped variables and are not
separately declared.
for def callable definitions, if the def is a top-level
callable then a 'stub' callable is generated which wraps
the current Context into a closure. if the def is not
top-level, it is fully rendered as a local closure.
"""
# collection of all defs available to us in this scope
comp_idents = dict([(c.funcname, c) for c in identifiers.defs])
to_write = set()
# write "context.get()" for all variables we are going to
# need that arent in the namespace yet
to_write = to_write.union(identifiers.undeclared)
# write closure functions for closures that we define
# right here
to_write = to_write.union(
[c.funcname for c in identifiers.closuredefs.values()]
)
# remove identifiers that are declared in the argument
# signature of the callable
to_write = to_write.difference(identifiers.argument_declared)
# remove identifiers that we are going to assign to.
# in this way we mimic Python's behavior,
# i.e. assignment to a variable within a block
# means that variable is now a "locally declared" var,
# which cannot be referenced beforehand.
to_write = to_write.difference(identifiers.locally_declared)
if self.compiler.enable_loop:
has_loop = "loop" in to_write
to_write.discard("loop")
else:
has_loop = False
# if a limiting set was sent, constraint to those items in that list
# (this is used for the caching decorator)
if limit is not None:
to_write = to_write.intersection(limit)
if toplevel and getattr(self.compiler, "has_ns_imports", False):
self.printer.writeline("_import_ns = {}")
self.compiler.has_imports = True
for ident, ns in self.compiler.namespaces.items():
if "import" in ns.attributes:
self.printer.writeline(
"_mako_get_namespace(context, %r)."
"_populate(_import_ns, %r)"
% (
ident,
re.split(r"\s*,\s*", ns.attributes["import"]),
)
)
if has_loop:
self.printer.writeline("loop = __M_loop = runtime.LoopStack()")
for ident in to_write:
if ident in comp_idents:
comp = comp_idents[ident]
if comp.is_block:
if not comp.is_anonymous:
self.write_def_decl(comp, identifiers)
else:
self.write_inline_def(comp, identifiers, nested=True)
else:
if comp.is_root():
self.write_def_decl(comp, identifiers)
else:
self.write_inline_def(comp, identifiers, nested=True)
elif ident in self.compiler.namespaces:
self.printer.writeline(
"%s = _mako_get_namespace(context, %r)" % (ident, ident)
)
else:
if getattr(self.compiler, "has_ns_imports", False):
if self.compiler.strict_undefined:
self.printer.writelines(
"%s = _import_ns.get(%r, UNDEFINED)"
% (ident, ident),
"if %s is UNDEFINED:" % ident,
"try:",
"%s = context[%r]" % (ident, ident),
"except KeyError:",
"raise NameError(\"'%s' is not defined\")" % ident,
None,
None,
)
else:
self.printer.writeline(
"%s = _import_ns.get"
"(%r, context.get(%r, UNDEFINED))"
% (ident, ident, ident)
)
else:
if self.compiler.strict_undefined:
self.printer.writelines(
"try:",
"%s = context[%r]" % (ident, ident),
"except KeyError:",
"raise NameError(\"'%s' is not defined\")" % ident,
None,
)
else:
self.printer.writeline(
"%s = context.get(%r, UNDEFINED)" % (ident, ident)
)
self.printer.writeline("__M_writer = context.writer()")
def write_def_decl(self, node, identifiers):
"""write a locally-available callable referencing a top-level def"""
funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(as_call=True)
if not self.in_def and (
len(self.identifiers.locally_assigned) > 0
or len(self.identifiers.argument_declared) > 0
):
nameargs.insert(0, "context._locals(__M_locals)")
else:
nameargs.insert(0, "context")
self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls)))
self.printer.writeline(
"return render_%s(%s)" % (funcname, ",".join(nameargs))
)
self.printer.writeline(None)
def write_inline_def(self, node, identifiers, nested):
"""write a locally-available def callable inside an enclosing def."""
namedecls = node.get_argument_expressions()
decorator = node.decorator
if decorator:
self.printer.writeline(
"@runtime._decorate_inline(context, %s)" % decorator
)
self.printer.writeline(
"def %s(%s):" % (node.funcname, ",".join(namedecls))
)
filtered = len(node.filter_args.args) > 0
buffered = eval(node.attributes.get("buffered", "False"))
cached = eval(node.attributes.get("cached", "False"))
self.printer.writelines(
# push new frame, assign current frame to __M_caller
"__M_caller = context.caller_stack._push_frame()",
"try:",
)
if buffered or filtered or cached:
self.printer.writelines("context._push_buffer()")
identifiers = identifiers.branch(node, nested=nested)
self.write_variable_declares(identifiers)
self.identifier_stack.append(identifiers)
for n in node.nodes:
n.accept_visitor(self)
self.identifier_stack.pop()
self.write_def_finish(node, buffered, filtered, cached)
self.printer.writeline(None)
if cached:
self.write_cache_decorator(
node,
node.funcname,
namedecls,
False,
identifiers,
inline=True,
toplevel=False,
)
def write_def_finish(
self, node, buffered, filtered, cached, callstack=True
):
"""write the end section of a rendering function, either outermost or
inline.
this takes into account if the rendering function was filtered,
buffered, etc. and closes the corresponding try: block if any, and
writes code to retrieve captured content, apply filters, send proper
return value."""
if not buffered and not cached and not filtered:
self.printer.writeline("return ''")
if callstack:
self.printer.writelines(
"finally:", "context.caller_stack._pop_frame()", None
)
if buffered or filtered or cached:
if buffered or cached:
# in a caching scenario, don't try to get a writer
# from the context after popping; assume the caching
# implemenation might be using a context with no
# extra buffers
self.printer.writelines(
"finally:", "__M_buf = context._pop_buffer()"
)
else:
self.printer.writelines(
"finally:",
"__M_buf, __M_writer = context._pop_buffer_and_writer()",
)
if callstack:
self.printer.writeline("context.caller_stack._pop_frame()")
s = "__M_buf.getvalue()"
if filtered:
s = self.create_filter_callable(
node.filter_args.args, s, False
)
self.printer.writeline(None)
if buffered and not cached:
s = self.create_filter_callable(
self.compiler.buffer_filters, s, False
)
if buffered or cached:
self.printer.writeline("return %s" % s)
else:
self.printer.writelines("__M_writer(%s)" % s, "return ''")
def write_cache_decorator(
self,
node_or_pagetag,
name,
args,
buffered,
identifiers,
inline=False,
toplevel=False,
):
"""write a post-function decorator to replace a rendering
callable with a cached version of itself."""
self.printer.writeline("__M_%s = %s" % (name, name))
cachekey = node_or_pagetag.parsed_attributes.get(
"cache_key", repr(name)
)
cache_args = {}
if self.compiler.pagetag is not None:
cache_args.update(
(pa[6:], self.compiler.pagetag.parsed_attributes[pa])
for pa in self.compiler.pagetag.parsed_attributes
if pa.startswith("cache_") and pa != "cache_key"
)
cache_args.update(
(pa[6:], node_or_pagetag.parsed_attributes[pa])
for pa in node_or_pagetag.parsed_attributes
if pa.startswith("cache_") and pa != "cache_key"
)
if "timeout" in cache_args:
cache_args["timeout"] = int(eval(cache_args["timeout"]))
self.printer.writeline("def %s(%s):" % (name, ",".join(args)))
# form "arg1, arg2, arg3=arg3, arg4=arg4", etc.
pass_args = [
"%s=%s" % ((a.split("=")[0],) * 2) if "=" in a else a for a in args
]
self.write_variable_declares(
identifiers,
toplevel=toplevel,
limit=node_or_pagetag.undeclared_identifiers(),
)
if buffered:
s = (
"context.get('local')."
"cache._ctx_get_or_create("
"%s, lambda:__M_%s(%s), context, %s__M_defname=%r)"
% (
cachekey,
name,
",".join(pass_args),
"".join(
["%s=%s, " % (k, v) for k, v in cache_args.items()]
),
name,
)
)
# apply buffer_filters
s = self.create_filter_callable(
self.compiler.buffer_filters, s, False
)
self.printer.writelines("return " + s, None)
else:
self.printer.writelines(
"__M_writer(context.get('local')."
"cache._ctx_get_or_create("
"%s, lambda:__M_%s(%s), context, %s__M_defname=%r))"
% (
cachekey,
name,
",".join(pass_args),
"".join(
["%s=%s, " % (k, v) for k, v in cache_args.items()]
),
name,
),
"return ''",
None,
)
def create_filter_callable(self, args, target, is_expression):
"""write a filter-applying expression based on the filters
present in the given filter names, adjusting for the global
'default' filter aliases as needed."""
def locate_encode(name):
if re.match(r"decode\..+", name):
return "filters." + name
elif self.compiler.disable_unicode:
return filters.NON_UNICODE_ESCAPES.get(name, name)
else:
return filters.DEFAULT_ESCAPES.get(name, name)
if "n" not in args:
if is_expression:
if self.compiler.pagetag:
args = self.compiler.pagetag.filter_args.args + args
if self.compiler.default_filters and "n" not in args:
args = self.compiler.default_filters + args
for e in args:
# if filter given as a function, get just the identifier portion
if e == "n":
continue
m = re.match(r"(.+?)(\(.*\))", e)
if m:
ident, fargs = m.group(1, 2)
f = locate_encode(ident)
e = f + fargs
else:
e = locate_encode(e)
assert e is not None
target = "%s(%s)" % (e, target)
return target
def visitExpression(self, node):
self.printer.start_source(node.lineno)
if (
len(node.escapes)
or (
self.compiler.pagetag is not None
and len(self.compiler.pagetag.filter_args.args)
)
or len(self.compiler.default_filters)
):
s = self.create_filter_callable(
node.escapes_code.args, "%s" % node.text, True
)
self.printer.writeline("__M_writer(%s)" % s)
else:
self.printer.writeline("__M_writer(%s)" % node.text)
def visitControlLine(self, node):
if node.isend:
self.printer.writeline(None)
if node.has_loop_context:
self.printer.writeline("finally:")
self.printer.writeline("loop = __M_loop._exit()")
self.printer.writeline(None)
else:
self.printer.start_source(node.lineno)
if self.compiler.enable_loop and node.keyword == "for":
text = mangle_mako_loop(node, self.printer)
else:
text = node.text
self.printer.writeline(text)
children = node.get_children()
# this covers the three situations where we want to insert a pass:
# 1) a ternary control line with no children,
# 2) a primary control line with nothing but its own ternary
# and end control lines, and
# 3) any control line with no content other than comments
if not children or (
compat.all(
isinstance(c, (parsetree.Comment, parsetree.ControlLine))
for c in children
)
and compat.all(
(node.is_ternary(c.keyword) or c.isend)
for c in children
if isinstance(c, parsetree.ControlLine)
)
):
self.printer.writeline("pass")
def visitText(self, node):
self.printer.start_source(node.lineno)
self.printer.writeline("__M_writer(%s)" % repr(node.content))
def visitTextTag(self, node):
filtered = len(node.filter_args.args) > 0
if filtered:
self.printer.writelines(
"__M_writer = context._push_writer()", "try:"
)
for n in node.nodes:
n.accept_visitor(self)
if filtered:
self.printer.writelines(
"finally:",
"__M_buf, __M_writer = context._pop_buffer_and_writer()",
"__M_writer(%s)"
% self.create_filter_callable(
node.filter_args.args, "__M_buf.getvalue()", False
),
None,
)
def visitCode(self, node):
if not node.ismodule:
self.printer.write_indented_block(
node.text, starting_lineno=node.lineno
)
if not self.in_def and len(self.identifiers.locally_assigned) > 0:
# if we are the "template" def, fudge locally
# declared/modified variables into the "__M_locals" dictionary,
# which is used for def calls within the same template,
# to simulate "enclosing scope"
self.printer.writeline(
"__M_locals_builtin_stored = __M_locals_builtin()"
)
self.printer.writeline(
"__M_locals.update(__M_dict_builtin([(__M_key,"
" __M_locals_builtin_stored[__M_key]) for __M_key in"
" [%s] if __M_key in __M_locals_builtin_stored]))"
% ",".join([repr(x) for x in node.declared_identifiers()])
)
def visitIncludeTag(self, node):
self.printer.start_source(node.lineno)
args = node.attributes.get("args")
if args:
self.printer.writeline(
"runtime._include_file(context, %s, _template_uri, %s)"
% (node.parsed_attributes["file"], args)
)
else:
self.printer.writeline(
"runtime._include_file(context, %s, _template_uri)"
% (node.parsed_attributes["file"])
)
def visitNamespaceTag(self, node):
pass
def visitDefTag(self, node):
pass
def visitBlockTag(self, node):
if node.is_anonymous:
self.printer.writeline("%s()" % node.funcname)
else:
nameargs = node.get_argument_expressions(as_call=True)
nameargs += ["**pageargs"]
self.printer.writeline(
"if 'parent' not in context._data or "
"not hasattr(context._data['parent'], '%s'):" % node.funcname
)
self.printer.writeline(
"context['self'].%s(%s)" % (node.funcname, ",".join(nameargs))
)
self.printer.writeline("\n")
def visitCallNamespaceTag(self, node):
# TODO: we can put namespace-specific checks here, such
# as ensure the given namespace will be imported,
# pre-import the namespace, etc.
self.visitCallTag(node)
def visitCallTag(self, node):
self.printer.writeline("def ccall(caller):")
export = ["body"]
callable_identifiers = self.identifiers.branch(node, nested=True)
body_identifiers = callable_identifiers.branch(node, nested=False)
# we want the 'caller' passed to ccall to be used
# for the body() function, but for other non-body()
# <%def>s within <%call> we want the current caller
# off the call stack (if any)
body_identifiers.add_declared("caller")
self.identifier_stack.append(body_identifiers)
class DefVisitor(object):
def visitDefTag(s, node):
s.visitDefOrBase(node)
def visitBlockTag(s, node):
s.visitDefOrBase(node)
def visitDefOrBase(s, node):
self.write_inline_def(node, callable_identifiers, nested=False)
if not node.is_anonymous:
export.append(node.funcname)
# remove defs that are within the <%call> from the
# "closuredefs" defined in the body, so they dont render twice
if node.funcname in body_identifiers.closuredefs:
del body_identifiers.closuredefs[node.funcname]
vis = DefVisitor()
for n in node.nodes:
n.accept_visitor(vis)
self.identifier_stack.pop()
bodyargs = node.body_decl.get_argument_expressions()
self.printer.writeline("def body(%s):" % ",".join(bodyargs))
# TODO: figure out best way to specify
# buffering/nonbuffering (at call time would be better)
buffered = False
if buffered:
self.printer.writelines("context._push_buffer()", "try:")
self.write_variable_declares(body_identifiers)
self.identifier_stack.append(body_identifiers)
for n in node.nodes:
n.accept_visitor(self)
self.identifier_stack.pop()
self.write_def_finish(node, buffered, False, False, callstack=False)
self.printer.writelines(None, "return [%s]" % (",".join(export)), None)
self.printer.writelines(
# push on caller for nested call
"context.caller_stack.nextcaller = "
"runtime.Namespace('caller', context, "
"callables=ccall(__M_caller))",
"try:",
)
self.printer.start_source(node.lineno)
self.printer.writelines(
"__M_writer(%s)"
% self.create_filter_callable([], node.expression, True),
"finally:",
"context.caller_stack.nextcaller = None",
None,
)
class _Identifiers(object):
"""tracks the status of identifier names as template code is rendered."""
def __init__(self, compiler, node=None, parent=None, nested=False):
if parent is not None:
# if we are the branch created in write_namespaces(),
# we don't share any context from the main body().
if isinstance(node, parsetree.NamespaceTag):
self.declared = set()
self.topleveldefs = util.SetLikeDict()
else:
# things that have already been declared
# in an enclosing namespace (i.e. names we can just use)
self.declared = (
set(parent.declared)
.union([c.name for c in parent.closuredefs.values()])
.union(parent.locally_declared)
.union(parent.argument_declared)
)
# if these identifiers correspond to a "nested"
# scope, it means whatever the parent identifiers
# had as undeclared will have been declared by that parent,
# and therefore we have them in our scope.
if nested:
self.declared = self.declared.union(parent.undeclared)
# top level defs that are available
self.topleveldefs = util.SetLikeDict(**parent.topleveldefs)
else:
self.declared = set()
self.topleveldefs = util.SetLikeDict()
self.compiler = compiler
# things within this level that are referenced before they
# are declared (e.g. assigned to)
self.undeclared = set()
# things that are declared locally. some of these things
# could be in the "undeclared" list as well if they are
# referenced before declared
self.locally_declared = set()
# assignments made in explicit python blocks.
# these will be propagated to
# the context of local def calls.
self.locally_assigned = set()
# things that are declared in the argument
# signature of the def callable
self.argument_declared = set()
# closure defs that are defined in this level
self.closuredefs = util.SetLikeDict()
self.node = node
if node is not None:
node.accept_visitor(self)
illegal_names = self.compiler.reserved_names.intersection(
self.locally_declared
)
if illegal_names:
raise exceptions.NameConflictError(
"Reserved words declared in template: %s"
% ", ".join(illegal_names)
)
def branch(self, node, **kwargs):
"""create a new Identifiers for a new Node, with
this Identifiers as the parent."""
return _Identifiers(self.compiler, node, self, **kwargs)
@property
def defs(self):
return set(self.topleveldefs.union(self.closuredefs).values())
def __repr__(self):
return (
"Identifiers(declared=%r, locally_declared=%r, "
"undeclared=%r, topleveldefs=%r, closuredefs=%r, "
"argumentdeclared=%r)"
% (
list(self.declared),
list(self.locally_declared),
list(self.undeclared),
[c.name for c in self.topleveldefs.values()],
[c.name for c in self.closuredefs.values()],
self.argument_declared,
)
)
def check_declared(self, node):
"""update the state of this Identifiers with the undeclared
and declared identifiers of the given node."""
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
for ident in node.declared_identifiers():
self.locally_declared.add(ident)
def add_declared(self, ident):
self.declared.add(ident)
if ident in self.undeclared:
self.undeclared.remove(ident)
def visitExpression(self, node):
self.check_declared(node)
def visitControlLine(self, node):
self.check_declared(node)
def visitCode(self, node):
if not node.ismodule:
self.check_declared(node)
self.locally_assigned = self.locally_assigned.union(
node.declared_identifiers()
)
def visitNamespaceTag(self, node):
# only traverse into the sub-elements of a
# <%namespace> tag if we are the branch created in
# write_namespaces()
if self.node is node:
for n in node.nodes:
n.accept_visitor(self)
def _check_name_exists(self, collection, node):
existing = collection.get(node.funcname)
collection[node.funcname] = node
if (
existing is not None
and existing is not node
and (node.is_block or existing.is_block)
):
raise exceptions.CompileException(
"%%def or %%block named '%s' already "
"exists in this template." % node.funcname,
**node.exception_kwargs
)
def visitDefTag(self, node):
if node.is_root() and not node.is_anonymous:
self._check_name_exists(self.topleveldefs, node)
elif node is not self.node:
self._check_name_exists(self.closuredefs, node)
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
# visit defs only one level deep
if node is self.node:
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
def visitBlockTag(self, node):
if node is not self.node and not node.is_anonymous:
if isinstance(self.node, parsetree.DefTag):
raise exceptions.CompileException(
"Named block '%s' not allowed inside of def '%s'"
% (node.name, self.node.name),
**node.exception_kwargs
)
elif isinstance(
self.node, (parsetree.CallTag, parsetree.CallNamespaceTag)
):
raise exceptions.CompileException(
"Named block '%s' not allowed inside of <%%call> tag"
% (node.name,),
**node.exception_kwargs
)
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
if not node.is_anonymous:
self._check_name_exists(self.topleveldefs, node)
self.undeclared.add(node.funcname)
elif node is not self.node:
self._check_name_exists(self.closuredefs, node)
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
def visitTextTag(self, node):
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
def visitIncludeTag(self, node):
self.check_declared(node)
def visitPageTag(self, node):
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
self.check_declared(node)
def visitCallNamespaceTag(self, node):
self.visitCallTag(node)
def visitCallTag(self, node):
if node is self.node:
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
for ident in node.declared_identifiers():
self.argument_declared.add(ident)
for n in node.nodes:
n.accept_visitor(self)
else:
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
self.locally_declared
):
self.undeclared.add(ident)
_FOR_LOOP = re.compile(
r"^for\s+((?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*"
r"(?:\s*,\s*(?:[A-Za-z_][A-Za-z0-9_]*),??)*\s*(?:\)?))\s+in\s+(.*):"
)
def mangle_mako_loop(node, printer):
"""converts a for loop into a context manager wrapped around a for loop
when access to the `loop` variable has been detected in the for loop body
"""
loop_variable = LoopVariable()
node.accept_visitor(loop_variable)
if loop_variable.detected:
node.nodes[-1].has_loop_context = True
match = _FOR_LOOP.match(node.text)
if match:
printer.writelines(
"loop = __M_loop._enter(%s)" % match.group(2),
"try:"
# 'with __M_loop(%s) as loop:' % match.group(2)
)
text = "for %s in loop:" % match.group(1)
else:
raise SyntaxError("Couldn't apply loop context: %s" % node.text)
else:
text = node.text
return text
class LoopVariable(object):
"""A node visitor which looks for the name 'loop' within undeclared
identifiers."""
def __init__(self):
self.detected = False
def _loop_reference_detected(self, node):
if "loop" in node.undeclared_identifiers():
self.detected = True
else:
for n in node.get_children():
n.accept_visitor(self)
def visitControlLine(self, node):
self._loop_reference_detected(node)
def visitCode(self, node):
self._loop_reference_detected(node)
def visitExpression(self, node):
self._loop_reference_detected(node)
| mit |
juniormesquitadandao/xikitita | app/models/i18n.js | 3738 | Xktta.I18n = function(locale, translations){
this.translations[locale] = translations || {};
return this;
}
Xktta.afterInit.push(function(){
var __this__ = Xktta;
eval.call(__this__.window, "var I18n;");
I18n = {
locale: 'en',
translate: function(path, params){
var translation = path;
var translations = __this__.translations[I18n.locale] || {};
path.split('.').forEach(function(key){
translations = translations[key] || {};
});
if(typeof translations === 'string'){
translation = translations;
params = params || {};
translation = translation.interpolate(params, '%');
}else if(typeof translations === 'object' && translations.constructor.name === 'Array'){
translation = translations;
} else {
translation = '#{locale}.#{path}'.interpolate({locale: I18n.locale, path: path});
}
return translation;
},
localize: function(value, options){
options = options || {};
var format = options.format || 'default';
var dateType = options.dateType || 'date';
var formatted = value;
if(typeof value === 'object' && value.constructor.name === 'Date'){
var dayWeak = value.getDay();
var month = value.getMonth() + 1;
var dayMonth = value.getDate();
var year = value.getFullYear();
var hours = value.getHours();
var minutes = value.getMinutes();
var seconds = value.getSeconds();
var meridiem = hours < 12 ? 'am' : 'pm';
var zone = value.toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1];
formatted = __this__.translations[I18n.locale][dateType].formats[format];
var formatBy = {
function: function(){
formatted = formatted(value);
},
string: function(){
var to = {
date: function(){
formatted = formatted
.interpolate({
a: I18n.t('date.abbrDayNames')[dayWeak],
A: I18n.t('date.dayNames')[dayWeak],
m: new String(month + 100).toString().substr(1),
b: I18n.t('date.abbrMonthNames')[month],
B: I18n.t('date.monthNames')[month],
d: new String(dayMonth + 100).toString().substr(1),
Y: year
}, '%', false);
},
time: function(){
formatted = formatted
.interpolate({
h: new String( (hours || 24) - 12 + 100 ).toString().substr(1),
H: new String(hours + 100).toString().substr(1),
M: new String(minutes + 100).toString().substr(1),
S: new String(seconds + 100).toString().substr(1),
p: I18n.t(['time', meridiem].join('.')),
z: zone
}, '%', false);
},
datetime: function(){
this.date();
this.time();
}
}
to[dateType]();
}
}
formatBy[typeof formatted]();
}
else if(typeof value === 'number'){
var functionFormat = __this__.translations[I18n.locale].integer.formats[format];
if(/\./.test(value) || options.forceDecimal){
functionFormat = __this__.translations[I18n.locale].decimal.formats[format];
}
formatted = functionFormat(value);
}
else if(typeof value === 'boolean'){
formatted = __this__.translations[I18n.locale].logic.formats[format][value];
}
return formatted;
}
}
I18n.t = I18n.translate
I18n.l = I18n.localize
}); | mit |
nizox/circuits | examples/web/jsoncontroller.py | 247 | #!/usr/bin/env python
from circuits.web import Server, JSONController
class Root(JSONController):
def index(self):
return {"success": True, "message": "Hello World!"}
app = Server(("0.0.0.0", 8000))
Root().register(app)
app.run()
| mit |
dodheim/atria | src/atria/funken/detail/access.hpp | 2682 | //
// Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.
//
// 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.
//
/*!
* @file
*/
#pragma once
#include <atria/estd/type_traits.hpp>
#include <atria/meta/utils.hpp>
#include <utility>
namespace atria {
namespace funken {
namespace detail {
/*!
* Provides access to the underlying signals of different
* entities. This encapsulates acess to the implementation of
* signal-based objects: don't make access to signals public, instead
* friend this class.
*/
class access
{
public:
/*!
* Returns a smart pointer to the underlying root signal or signals
* of an object, if exist.
*/
template<typename T>
static auto roots(T&& object)
-> ABL_DECLTYPE_RETURN(
std::forward<T>(object).roots())
/*!
* Returns a pointer to th underlying signal of an object, if
* exists.
*/
template<typename T>
static auto signal(T&& object)
-> ABL_DECLTYPE_RETURN(
std::forward<T>(object).signal())
/*!
* Returns a a optional boost.signal to the specific watchers of
* the underlying signal of an object.
*/
template<typename T>
static auto watchers(T&& object)
-> ABL_DECLTYPE_RETURN(
std::forward<T>(object).watchers())
};
/*!
* Returns the signal type for an object
*/
template <typename ObjectT>
struct signal_type
{
using type =
estd::decay_t<
typename estd::decay_t<decltype(
access::signal(std::declval<ObjectT>())
)>::element_type
>;
};
template <typename ObjectT>
using signal_type_t = typename signal_type<ObjectT>::type;
} // namespace detail
} // namespace funken
} // namespace atria
| mit |
alicht/buddybuddy | public/tmp/tree_merger-tmp_dest_dir-KPkHvOkI.tmp/buddybuddy/templates/users/index.js | 1413 | import Ember from 'ember';
export default Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
var buffer = '', stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var buffer = '', helper, options;
data.buffer.push("\n <div class=\"row\">\n <div class=\"col-md-4\"> <span class=\"glyphicon glyphicon-user\"></span> ");
data.buffer.push(escapeExpression((helper = helpers['link-to'] || (depth0 && depth0['link-to']),options={hash:{},hashTypes:{},hashContexts:{},contexts:[depth0,depth0,depth0],types:["ID","STRING","ID"],data:data},helper ? helper.call(depth0, "user.name", "users.user", "user", options) : helperMissing.call(depth0, "link-to", "user.name", "users.user", "user", options))));
data.buffer.push("</div>\n </div>\n ");
return buffer;
}
data.buffer.push("<h2>Buddies</h2>\n\n<div class=\"container\">\n ");
stack1 = helpers.each.call(depth0, "user", "in", "content", {hash:{},hashTypes:{},hashContexts:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0,depth0,depth0],types:["ID","ID","ID"],data:data});
if(stack1 || stack1 === 0) { data.buffer.push(stack1); }
data.buffer.push("\n\n\n</div>\n");
return buffer;
});
| mit |
share/livedb | lib/types.js | 242 |
exports.defaultType = require('ot-json0').type;
exports.map = {};
exports.register = function(type) {
if (type.name) exports.map[type.name] = type;
if (type.uri) exports.map[type.uri] = type;
};
exports.register(exports.defaultType);
| mit |
mirror/grrlib | examples/unlimited2d/source/gfx/ball.c | 33926 | /*
This file was autogenerated by raw2c.
Visit http://www.devkitpro.org
*/
const unsigned char ball[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x06, 0x00, 0x00, 0x00, 0xaa, 0x69, 0x71,
0xde, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,
0x15, 0x45, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xed, 0x5b, 0x79, 0xb4, 0x5d, 0x65, 0x75, 0xff,
0xed, 0xfd, 0x7d, 0xdf, 0x39, 0xe7, 0x0e, 0x6f, 0xc8, 0x7b, 0x2f, 0x21, 0x10, 0x66, 0x08, 0x05,
0xb1, 0xa0, 0x68, 0xad, 0x40, 0xab, 0x76, 0x81, 0xad, 0x14, 0xa5, 0xb5, 0xc3, 0x52, 0x8b, 0x53,
0x59, 0xce, 0x75, 0xb9, 0x5c, 0x1d, 0xa4, 0xd6, 0x65, 0x6d, 0xad, 0x68, 0x43, 0xb1, 0x5a, 0x57,
0xab, 0xcb, 0xa1, 0x2d, 0x28, 0x08, 0x52, 0x83, 0x13, 0x5a, 0xd2, 0x80, 0x18, 0xca, 0x50, 0x20,
0x52, 0x66, 0x19, 0x24, 0x61, 0x08, 0x84, 0x40, 0xf2, 0x32, 0xbc, 0xe1, 0x0e, 0xe7, 0xfb, 0xf6,
0xee, 0x1f, 0xdf, 0x77, 0xce, 0xbd, 0x49, 0x1e, 0x90, 0x00, 0x2a, 0x6b, 0x95, 0xb3, 0x72, 0x72,
0xdf, 0xbd, 0xef, 0xdd, 0x73, 0xcf, 0xfe, 0xed, 0xbd, 0x7f, 0xfb, 0xb7, 0xf7, 0xf7, 0x5d, 0xe0,
0xf9, 0xe3, 0xf9, 0xe3, 0xf9, 0xe3, 0xff, 0xf3, 0x41, 0x3f, 0x8f, 0x0f, 0xf9, 0xf0, 0x3f, 0x7f,
0x6b, 0x71, 0xab, 0xd5, 0x3c, 0x9c, 0x8c, 0x39, 0x50, 0x45, 0xf7, 0x65, 0xa6, 0x06, 0x00, 0x55,
0x8d, 0xff, 0x85, 0x10, 0xa0, 0x1a, 0x36, 0x6b, 0x90, 0x0d, 0x9d, 0xde, 0xfc, 0x86, 0xb3, 0x3f,
0xf0, 0x86, 0x9f, 0x00, 0x08, 0xd5, 0xfb, 0x4f, 0x78, 0xcd, 0x1b, 0x71, 0xed, 0x65, 0x17, 0x3d,
0xf7, 0x01, 0x38, 0xeb, 0xdc, 0xd5, 0xf8, 0xc8, 0xdb, 0x5f, 0x9d, 0x8c, 0xbe, 0x64, 0x72, 0x74,
0x6c, 0xec, 0x0c, 0x26, 0x7e, 0x83, 0x31, 0xbc, 0x2f, 0x80, 0x26, 0x14, 0x0d, 0x05, 0x72, 0x85,
0x22, 0xfe, 0x53, 0xa8, 0x28, 0x44, 0x15, 0x00, 0x02, 0xb3, 0x76, 0x1d, 0x73, 0xc7, 0x30, 0xef,
0xf0, 0xbe, 0xbc, 0xee, 0xf1, 0xcd, 0x9b, 0x2f, 0x5a, 0xf1, 0xc1, 0x37, 0x5d, 0xfa, 0x9c, 0x8e,
0x80, 0x15, 0xe7, 0xad, 0xc6, 0x99, 0x6f, 0x8b, 0x46, 0xaf, 0xf8, 0xda, 0xe5, 0x99, 0x2a, 0x1d,
0xcd, 0x86, 0xff, 0xce, 0x1a, 0x7b, 0x2a, 0x31, 0x57, 0x1f, 0xa0, 0x4a, 0x20, 0x28, 0x00, 0x55,
0x54, 0x00, 0x48, 0xfa, 0x59, 0x35, 0x9e, 0x04, 0x82, 0x61, 0x45, 0x66, 0x0d, 0x32, 0x67, 0x91,
0x39, 0x83, 0xb2, 0x2c, 0xa7, 0xb7, 0x4e, 0x4f, 0x7f, 0xe2, 0xa1, 0x75, 0x77, 0x5f, 0xf4, 0xed,
0x8b, 0x2f, 0xd8, 0xb2, 0xe1, 0x9e, 0x9b, 0xfb, 0xcf, 0x19, 0x00, 0xbe, 0x7b, 0xcd, 0x46, 0x9c,
0x76, 0xe2, 0xbe, 0x00, 0x80, 0x73, 0x2e, 0xb8, 0xf2, 0x0d, 0xcc, 0xfc, 0x0e, 0x36, 0xe6, 0x64,
0x22, 0x06, 0x11, 0x81, 0xa0, 0x0a, 0xa2, 0xfa, 0x33, 0x92, 0xfd, 0x00, 0x01, 0x2a, 0x5a, 0xe5,
0x00, 0x44, 0x05, 0xaa, 0x31, 0x12, 0x48, 0x01, 0x63, 0x08, 0xce, 0x10, 0x1a, 0x99, 0xd3, 0x46,
0xe1, 0xc8, 0x59, 0x46, 0xaf, 0xd7, 0x9f, 0x9e, 0x99, 0x9d, 0x39, 0xf7, 0xc7, 0x6b, 0xd7, 0x7e,
0xe5, 0x5f, 0xcf, 0xfe, 0xf0, 0x4f, 0x0e, 0x38, 0xe8, 0x10, 0x7a, 0xe8, 0x81, 0xf5, 0xfa, 0x0b,
0x03, 0x60, 0xc5, 0x57, 0x57, 0xe3, 0xcc, 0xb7, 0xbe, 0x1a, 0x2b, 0xce, 0xbb, 0x7c, 0x3f, 0x97,
0xe7, 0xdf, 0xb0, 0x86, 0x5f, 0x46, 0x4c, 0x19, 0x13, 0x45, 0x9b, 0x89, 0x40, 0xbb, 0x5c, 0xbe,
0x02, 0x20, 0x7a, 0x1d, 0xc9, 0xf3, 0x52, 0x47, 0x80, 0x88, 0xc4, 0xa8, 0x10, 0x01, 0x31, 0x21,
0x63, 0x42, 0x91, 0x3b, 0xb4, 0x1b, 0x99, 0xb6, 0x1a, 0x19, 0x19, 0x22, 0x74, 0x7a, 0xfd, 0xed,
0x77, 0xdf, 0x7b, 0xef, 0xa7, 0x3e, 0xfa, 0xde, 0x37, 0xae, 0x00, 0x60, 0x98, 0x39, 0x88, 0xc8,
0xd3, 0x06, 0x80, 0xf7, 0xf6, 0x0d, 0xff, 0x78, 0xc1, 0x95, 0xd1, 0x18, 0xee, 0xe3, 0x9c, 0x0b,
0x7e, 0x78, 0x6a, 0xd1, 0xcc, 0xef, 0xcb, 0x32, 0xf3, 0x6b, 0xd6, 0x9a, 0xcc, 0x1a, 0x03, 0x6b,
0x0c, 0x8c, 0x31, 0xb0, 0xcc, 0xb0, 0xc6, 0xc0, 0x59, 0x03, 0x9b, 0x4e, 0x57, 0x3d, 0x37, 0x83,
0xd3, 0x18, 0x1b, 0x4f, 0xe6, 0xf8, 0x1e, 0x66, 0x30, 0x33, 0x54, 0x80, 0x9e, 0x17, 0xcc, 0x75,
0xfb, 0xd8, 0x31, 0xd7, 0xa5, 0xd9, 0xf9, 0x1e, 0x40, 0x8a, 0x45, 0xa3, 0xcd, 0xd1, 0x5f, 0x79,
0xf1, 0x2f, 0xff, 0xfd, 0x97, 0xbe, 0x79, 0xf9, 0x55, 0xaf, 0xfe, 0xfd, 0xb7, 0x2d, 0x17, 0x91,
0xdc, 0x3a, 0xf7, 0xb4, 0x1d, 0x69, 0xf6, 0xf6, 0x0d, 0xab, 0x2e, 0x39, 0x0f, 0x9f, 0xfc, 0xf2,
0x0f, 0x9a, 0x8d, 0x46, 0xfb, 0x6c, 0x97, 0x65, 0x9f, 0x33, 0xc6, 0x58, 0x43, 0x46, 0x99, 0x99,
0x0c, 0x1b, 0xb0, 0x61, 0x18, 0x66, 0x18, 0x63, 0x60, 0x98, 0xc0, 0xe9, 0x24, 0x22, 0x58, 0x26,
0x18, 0x8e, 0x8f, 0xce, 0x50, 0xfc, 0x3b, 0x26, 0x58, 0x06, 0x0c, 0xc7, 0xbf, 0xaf, 0x5e, 0x63,
0x8e, 0xe1, 0x19, 0x44, 0xe0, 0x43, 0x3c, 0x01, 0x42, 0x66, 0x99, 0x9a, 0x45, 0xa6, 0x13, 0x63,
0x23, 0x07, 0x1d, 0x7e, 0xe4, 0xd1, 0xa7, 0x2c, 0x3e, 0xf0, 0x88, 0x07, 0x6f, 0x58, 0xb3, 0xea,
0x9e, 0x45, 0x53, 0x4b, 0xa8, 0x3b, 0x3f, 0xa7, 0x3f, 0x53, 0x00, 0x3e, 0x7b, 0xe1, 0x1a, 0x5c,
0xb6, 0xf2, 0x5c, 0x9c, 0xf6, 0xe6, 0x77, 0x5f, 0x62, 0xad, 0x7b, 0xab, 0x61, 0x03, 0x63, 0x58,
0x0d, 0x33, 0x19, 0x63, 0x60, 0x0c, 0x27, 0x43, 0x18, 0x86, 0xa2, 0x31, 0x9c, 0x0c, 0x73, 0xcc,
0xb0, 0x36, 0x7a, 0x98, 0xd8, 0x80, 0x88, 0x23, 0x1f, 0x80, 0x10, 0x14, 0x10, 0x05, 0x04, 0x04,
0xd5, 0x78, 0x42, 0x01, 0x62, 0x06, 0x71, 0xcc, 0x9b, 0x10, 0x02, 0x4a, 0x2f, 0x10, 0x05, 0x9c,
0x33, 0xd4, 0x2c, 0x72, 0x1d, 0x6b, 0x37, 0x27, 0x96, 0x2d, 0x3b, 0xe0, 0xd4, 0x25, 0x87, 0x1c,
0x3d, 0xb7, 0xe6, 0x07, 0xdf, 0xfc, 0x5f, 0x62, 0x06, 0x54, 0xe5, 0x59, 0x07, 0xe0, 0x33, 0x5f,
0xbf, 0x12, 0xab, 0x56, 0x9e, 0x87, 0xcb, 0x56, 0x9e, 0x8b, 0xcf, 0x5e, 0xb8, 0xe6, 0x32, 0xeb,
0xdc, 0x6f, 0xb3, 0x21, 0x35, 0xc6, 0x90, 0x21, 0x43, 0x96, 0xa3, 0xd7, 0x2d, 0x19, 0x58, 0x4a,
0x11, 0xc0, 0x0c, 0x43, 0x0c, 0xc7, 0x1c, 0xbd, 0x6d, 0x18, 0x4c, 0x06, 0xb2, 0x13, 0x2f, 0x10,
0x00, 0x02, 0x31, 0xd5, 0x1c, 0x01, 0x02, 0x04, 0x0a, 0x49, 0x5c, 0x21, 0x42, 0x03, 0xaa, 0xd2,
0x00, 0x1f, 0x04, 0x0a, 0x20, 0x73, 0x86, 0x1a, 0x79, 0x86, 0x56, 0x33, 0x73, 0x4b, 0x97, 0x2e,
0xfd, 0x8d, 0xd1, 0x25, 0x07, 0x6c, 0x5c, 0x7b, 0xf5, 0x15, 0xeb, 0x41, 0x54, 0x02, 0x90, 0x67,
0x15, 0x80, 0x55, 0x2b, 0xcf, 0xc3, 0x27, 0xbf, 0x74, 0xa9, 0x7d, 0xdd, 0x1f, 0xbd, 0xeb, 0x12,
0x9b, 0xb9, 0x53, 0x99, 0x59, 0x0d, 0x1b, 0x8a, 0xe1, 0x6b, 0x60, 0xd8, 0xc0, 0x31, 0xa7, 0x08,
0xa8, 0x72, 0xd9, 0x20, 0x33, 0x04, 0x6b, 0x19, 0x44, 0x06, 0x00, 0x41, 0x09, 0x60, 0x22, 0x10,
0x33, 0x18, 0x00, 0x51, 0x4c, 0x8f, 0x88, 0x05, 0x81, 0x28, 0xa2, 0x50, 0xd1, 0x67, 0x2c, 0x97,
0xb1, 0x3a, 0x04, 0x01, 0x82, 0x02, 0x50, 0x01, 0x44, 0x40, 0x4a, 0xc8, 0x73, 0x8b, 0x66, 0x9e,
0x51, 0xb3, 0xc8, 0xec, 0xe4, 0x92, 0x7d, 0x4f, 0xee, 0x09, 0xdf, 0x76, 0xf7, 0xad, 0x6b, 0x1f,
0x72, 0x2e, 0xf3, 0x22, 0x41, 0x9e, 0x15, 0x00, 0xce, 0xf9, 0xda, 0x15, 0x38, 0xe1, 0xa4, 0xd7,
0xa1, 0x3d, 0xbe, 0xe8, 0x4c, 0xe7, 0xec, 0x9f, 0x10, 0x1b, 0xb5, 0xcc, 0x64, 0x4c, 0xf4, 0x70,
0x24, 0x33, 0xae, 0xcf, 0x8a, 0x00, 0xf3, 0xe4, 0x71, 0x42, 0xcc, 0x7f, 0x26, 0x02, 0x83, 0xc1,
0xc4, 0x20, 0x0c, 0x78, 0xa1, 0x52, 0x0a, 0x75, 0xc5, 0xa8, 0x9c, 0x4d, 0x80, 0x22, 0x81, 0x92,
0x64, 0xa3, 0xa8, 0x22, 0x04, 0x85, 0x08, 0x40, 0x24, 0x30, 0x4c, 0xc8, 0x33, 0x87, 0x46, 0xee,
0xb4, 0xd5, 0xc8, 0xdd, 0xfe, 0x87, 0x2c, 0xff, 0xad, 0x6b, 0xae, 0xbe, 0xf6, 0xaa, 0x1d, 0xd3,
0x9b, 0xa6, 0x01, 0xf8, 0x3d, 0x89, 0x84, 0x27, 0x05, 0xe0, 0xd3, 0xe7, 0x5f, 0x81, 0x3f, 0x7f,
0xcb, 0x49, 0x38, 0xed, 0xf4, 0xf7, 0x1d, 0x6d, 0xac, 0x59, 0xc9, 0xd1, 0x38, 0x8a, 0x61, 0x9e,
0x58, 0x9c, 0x29, 0x31, 0x7e, 0xf4, 0xbc, 0x03, 0x21, 0x37, 0x06, 0xcc, 0x06, 0x4c, 0x04, 0x4b,
0x9c, 0xa2, 0x84, 0x60, 0x92, 0x3e, 0xa8, 0x40, 0x48, 0xd5, 0x32, 0x69, 0x86, 0x94, 0x02, 0xc9,
0xf8, 0x81, 0x60, 0xa8, 0xd2, 0x9a, 0x22, 0x17, 0x88, 0x20, 0x04, 0x81, 0x6a, 0x14, 0x4d, 0xce,
0x1a, 0x34, 0xb2, 0x8c, 0x8a, 0xcc, 0xa2, 0xc8, 0xb3, 0xfc, 0xc8, 0x17, 0xbf, 0xec, 0x84, 0xef,
0x7f, 0xf3, 0xfc, 0x55, 0x00, 0xe6, 0x01, 0x94, 0x43, 0x97, 0xdd, 0x3b, 0x00, 0x3e, 0xfe, 0xc5,
0xef, 0xe0, 0xc3, 0x67, 0x9c, 0x82, 0xbf, 0xfd, 0xfc, 0xb7, 0xb3, 0x46, 0xab, 0x79, 0xb3, 0xb5,
0xb6, 0x6d, 0x88, 0xd5, 0xb2, 0x21, 0x63, 0x18, 0xae, 0x32, 0xb8, 0x32, 0x9e, 0x0c, 0x32, 0x32,
0x28, 0x6c, 0x22, 0x43, 0xa2, 0xba, 0xac, 0x19, 0x8a, 0x27, 0x27, 0x10, 0x38, 0x19, 0x5d, 0xbb,
0x9c, 0x14, 0x43, 0xae, 0x1e, 0xdc, 0x71, 0xe2, 0x01, 0x54, 0xfa, 0x21, 0xb2, 0x26, 0x82, 0x46,
0x10, 0x08, 0x04, 0x67, 0x19, 0x85, 0xb3, 0x28, 0x72, 0x07, 0x67, 0x8d, 0xe6, 0x59, 0x36, 0x31,
0xb1, 0xec, 0x50, 0xbd, 0x7e, 0xcd, 0xea, 0xdb, 0x13, 0x08, 0xfe, 0x69, 0x01, 0x70, 0xe5, 0xa5,
0xb1, 0xf9, 0x38, 0xed, 0xf4, 0x77, 0xfd, 0xbb, 0xb5, 0xee, 0x04, 0x26, 0x56, 0x63, 0x0c, 0x71,
0xca, 0xef, 0x78, 0x52, 0xac, 0xf5, 0x6c, 0xe0, 0x40, 0x28, 0x2a, 0x0d, 0x40, 0x84, 0x82, 0x19,
0x0d, 0x63, 0x90, 0x1b, 0x86, 0xe3, 0x48, 0x74, 0xa6, 0x56, 0x88, 0x14, 0xed, 0xa6, 0x2a, 0xd6,
0x23, 0x3f, 0x54, 0xce, 0xd2, 0x5a, 0x34, 0x0d, 0x9e, 0xa3, 0x96, 0xcd, 0x55, 0x3a, 0x08, 0xbc,
0x28, 0x2c, 0x33, 0x8a, 0xdc, 0xa2, 0xc8, 0x2d, 0x72, 0x6b, 0xc9, 0x5a, 0x43, 0x8d, 0xf6, 0xd8,
0x51, 0xff, 0x73, 0xdd, 0x35, 0xd7, 0xce, 0x6c, 0xdd, 0x32, 0x0d, 0xa0, 0x3b, 0xdc, 0x58, 0xed,
0x55, 0x0a, 0xfc, 0xc3, 0x57, 0x57, 0xbf, 0x2c, 0x73, 0xd9, 0xc7, 0x99, 0xa9, 0x88, 0xa4, 0xc7,
0x51, 0xcc, 0x24, 0xcf, 0x9b, 0x2a, 0x0a, 0x88, 0x91, 0x1b, 0x83, 0xcc, 0x32, 0x1a, 0xcc, 0x68,
0xdb, 0x18, 0x15, 0x91, 0xe4, 0xe2, 0xdf, 0x34, 0x98, 0x91, 0x33, 0x41, 0x93, 0x52, 0x8c, 0x11,
0x40, 0x55, 0x94, 0xef, 0x14, 0xa9, 0xa2, 0x3a, 0xa4, 0x18, 0x35, 0x95, 0xcb, 0x48, 0x88, 0x51,
0x3e, 0x03, 0xa2, 0x02, 0x91, 0xf8, 0xbb, 0xdc, 0x39, 0x34, 0x73, 0x8b, 0x3c, 0x73, 0xb0, 0xc6,
0xa8, 0xcb, 0xb2, 0xbc, 0x18, 0x5f, 0x32, 0x75, 0xcd, 0xe5, 0xdf, 0xbf, 0x16, 0xc0, 0x1c, 0x80,
0xfe, 0x13, 0xa5, 0xc2, 0x13, 0x02, 0xf0, 0x89, 0xaf, 0x5c, 0x6a, 0xf2, 0x2c, 0x3f, 0x93, 0x0d,
0xbf, 0x92, 0xd9, 0x10, 0x9b, 0xe8, 0x79, 0x97, 0x22, 0xc0, 0xa4, 0xe7, 0x19, 0x33, 0x32, 0x66,
0x34, 0x2d, 0xa3, 0x69, 0x0c, 0xc0, 0x84, 0x40, 0xb1, 0xd6, 0x47, 0x31, 0xc4, 0x00, 0x03, 0x81,
0x18, 0x4a, 0x84, 0x9c, 0x09, 0x86, 0x08, 0x75, 0x75, 0x1b, 0x22, 0xb9, 0x0a, 0x0c, 0x55, 0x8d,
0xec, 0xa5, 0x3b, 0x03, 0x20, 0x12, 0x63, 0xa3, 0x96, 0xd1, 0x12, 0xa3, 0xc2, 0x10, 0xa3, 0xd5,
0xc8, 0xd0, 0xc8, 0x33, 0x64, 0xce, 0x10, 0x00, 0x8c, 0x8c, 0x4d, 0x1c, 0x7a, 0xc3, 0x8d, 0x6b,
0x6f, 0xda, 0xf6, 0xf8, 0xc6, 0x47, 0x53, 0x2a, 0x84, 0x3d, 0x06, 0x60, 0xc5, 0xb9, 0x97, 0xa1,
0xd1, 0x68, 0xb6, 0x08, 0x38, 0xd7, 0xb0, 0x2d, 0xb8, 0x56, 0x6c, 0x1c, 0xc3, 0x3e, 0x29, 0x3d,
0x6b, 0x62, 0x24, 0xb4, 0x0c, 0xa3, 0x69, 0x0d, 0x3c, 0xa2, 0x8c, 0xcd, 0x6d, 0x15, 0x11, 0x06,
0x99, 0x19, 0x92, 0xb8, 0x44, 0x08, 0x44, 0x70, 0x0c, 0x58, 0x06, 0x42, 0x15, 0x04, 0xa4, 0x20,
0x06, 0x94, 0x14, 0xc4, 0xd1, 0x78, 0x09, 0xf1, 0x71, 0x38, 0xec, 0x2b, 0x10, 0xa4, 0xea, 0x1d,
0x34, 0x6a, 0x02, 0x26, 0xa0, 0x55, 0x64, 0x68, 0x15, 0x0e, 0x59, 0x66, 0x61, 0x98, 0x14, 0x00,
0x8d, 0x4c, 0x2d, 0x9d, 0x5c, 0xb3, 0xea, 0xbb, 0x6b, 0x12, 0x00, 0xdd, 0x85, 0xa2, 0x60, 0xb7,
0x5e, 0xe0, 0x23, 0xff, 0xf4, 0x1f, 0x38, 0xf3, 0xed, 0xaf, 0x41, 0xd9, 0xef, 0xbf, 0x99, 0x99,
0xc7, 0x41, 0x50, 0x70, 0xcc, 0xd7, 0xe1, 0xda, 0x6d, 0x08, 0xb0, 0x44, 0xc8, 0x40, 0x68, 0x19,
0x46, 0x5f, 0x23, 0x38, 0xb9, 0x63, 0x14, 0xd6, 0xa0, 0x91, 0x31, 0x9a, 0x99, 0x41, 0x91, 0x59,
0x14, 0xce, 0xa0, 0x91, 0x99, 0xf4, 0x48, 0x60, 0x4b, 0x68, 0x5a, 0x46, 0xdb, 0x12, 0x72, 0x13,
0x01, 0xa5, 0xa4, 0x11, 0x98, 0x19, 0xd6, 0x11, 0x9c, 0x8d, 0xa5, 0x73, 0x50, 0x2d, 0xa8, 0x2e,
0x96, 0x34, 0xd4, 0x70, 0x85, 0x20, 0xe8, 0x96, 0x25, 0x66, 0x3b, 0x7d, 0xf4, 0xbc, 0x87, 0x88,
0xc2, 0x18, 0x43, 0xcd, 0x3c, 0xd3, 0x23, 0x8f, 0x58, 0xfe, 0x82, 0x03, 0x96, 0xbf, 0xf0, 0xc5,
0x00, 0xc6, 0x01, 0xb8, 0x3d, 0x6a, 0x86, 0xde, 0xf3, 0x81, 0x3f, 0x88, 0xbf, 0x30, 0xfc, 0x17,
0x43, 0x12, 0x05, 0x5c, 0xdd, 0x48, 0x75, 0x03, 0xe9, 0xb5, 0x82, 0x09, 0x1e, 0x04, 0x26, 0x20,
0x33, 0x84, 0xc2, 0x32, 0xf2, 0x9c, 0x91, 0x17, 0x16, 0x79, 0x61, 0x50, 0x14, 0x91, 0xa4, 0xb2,
0xdc, 0xa2, 0x91, 0x33, 0x8a, 0x24, 0x87, 0x4b, 0x10, 0x32, 0x22, 0x38, 0xc4, 0xae, 0x2f, 0x23,
0x02, 0x25, 0xff, 0x90, 0x02, 0x6c, 0x00, 0x63, 0xb1, 0x9b, 0x6e, 0xac, 0xc9, 0x73, 0xa8, 0x52,
0x78, 0x2f, 0x98, 0xeb, 0xf5, 0xd1, 0xed, 0x05, 0x88, 0x08, 0x98, 0x08, 0x79, 0xee, 0x68, 0x7c,
0x74, 0x74, 0xe4, 0xc4, 0x57, 0x9e, 0x74, 0x1c, 0x80, 0x29, 0x00, 0x8d, 0x85, 0xec, 0xdd, 0xed,
0x85, 0x03, 0x88, 0xf0, 0xf1, 0x2f, 0x7e, 0xfb, 0x70, 0x66, 0x3e, 0x54, 0x41, 0x5a, 0x19, 0x8d,
0xca, 0xfb, 0xa9, 0x66, 0x33, 0xc7, 0xfc, 0xb1, 0x1c, 0xa7, 0x1d, 0x96, 0x00, 0x67, 0x18, 0xce,
0x31, 0x9c, 0x8d, 0xde, 0x2e, 0x0a, 0x8b, 0x46, 0xd3, 0xa2, 0x68, 0x58, 0x14, 0xb9, 0x81, 0xb5,
0xa9, 0x24, 0xa6, 0xaa, 0x2f, 0x1a, 0xbd, 0x0e, 0x05, 0x2c, 0x13, 0x32, 0xde, 0x39, 0x48, 0x0d,
0x01, 0x64, 0x16, 0x40, 0xa0, 0x7e, 0x4a, 0x90, 0xd4, 0x30, 0xf5, 0xfa, 0x25, 0xba, 0xbd, 0x12,
0x21, 0xc4, 0xc4, 0x71, 0xd6, 0x60, 0xb4, 0xdd, 0x30, 0x87, 0x1d, 0x71, 0xe4, 0xd1, 0xd6, 0xe5,
0xfb, 0x00, 0x18, 0x59, 0x28, 0xe5, 0x17, 0x6c, 0x87, 0xf3, 0xbc, 0x78, 0x3d, 0x0d, 0xf0, 0x4e,
0xa3, 0x9c, 0xa1, 0xb2, 0x9d, 0xbc, 0x44, 0x40, 0x6d, 0x8c, 0xe1, 0x68, 0x84, 0x21, 0x42, 0x66,
0x19, 0x59, 0x61, 0x91, 0x37, 0x2c, 0xb2, 0xc2, 0x21, 0xcf, 0x19, 0xd6, 0xa0, 0x16, 0x3e, 0x86,
0x01, 0x5b, 0x79, 0x5b, 0xd2, 0x78, 0x4c, 0x62, 0x2e, 0xdb, 0xaa, 0x34, 0x56, 0x37, 0x68, 0x00,
0x62, 0xd4, 0x32, 0x79, 0xa1, 0x81, 0x46, 0x10, 0x45, 0xe9, 0x03, 0x7a, 0x7d, 0x8f, 0x32, 0x29,
0x60, 0x26, 0x42, 0xe6, 0x1c, 0xf6, 0x5b, 0xb6, 0xff, 0x21, 0x23, 0x63, 0x63, 0x4b, 0x00, 0x8c,
0x01, 0xb0, 0xbb, 0xce, 0x40, 0x76, 0x02, 0xe0, 0x0b, 0x97, 0xde, 0x52, 0x5d, 0xf6, 0x94, 0xe1,
0x18, 0x1b, 0x08, 0x13, 0x05, 0x69, 0xad, 0xd7, 0x40, 0xd0, 0x5a, 0xc1, 0xc5, 0xd4, 0xa8, 0xf2,
0x98, 0x60, 0x1c, 0xc3, 0x64, 0x16, 0xa6, 0x60, 0xb0, 0x8b, 0x6d, 0xb0, 0x33, 0x80, 0x4b, 0x40,
0x80, 0x09, 0x64, 0x08, 0x6c, 0x86, 0xaa, 0x80, 0x0c, 0xb9, 0x48, 0x87, 0xae, 0xcb, 0x49, 0x18,
0x0e, 0x4f, 0x56, 0x86, 0x87, 0x2c, 0x50, 0xf8, 0x20, 0xe8, 0x7b, 0x8f, 0x10, 0x22, 0x69, 0x12,
0x11, 0x9c, 0x33, 0x58, 0xb2, 0x64, 0x9f, 0x65, 0x79, 0x5e, 0x8c, 0x26, 0x00, 0xf2, 0x27, 0x8d,
0x80, 0xf7, 0xbe, 0xf6, 0x58, 0xfc, 0xce, 0xbb, 0x3f, 0x62, 0x89, 0xe9, 0x30, 0x8d, 0x4d, 0xe9,
0x4e, 0x8a, 0x4c, 0x87, 0x44, 0x09, 0x52, 0x04, 0x68, 0x35, 0xe7, 0xab, 0x98, 0x9a, 0xd2, 0x2d,
0x09, 0x06, 0x8f, 0x32, 0x30, 0x10, 0x94, 0x7a, 0x7d, 0x93, 0xd8, 0xc5, 0xc4, 0x5c, 0xd2, 0x61,
0x83, 0x2b, 0xe6, 0x4f, 0xc0, 0x10, 0x55, 0x8e, 0xd0, 0xa1, 0x47, 0xd4, 0x9a, 0x40, 0x25, 0x56,
0x87, 0x32, 0x08, 0x82, 0xc4, 0x14, 0x60, 0x02, 0x2c, 0xb3, 0x8e, 0x8f, 0xb5, 0xb1, 0xec, 0xb0,
0xa3, 0x0e, 0x04, 0xd0, 0x06, 0x50, 0xec, 0x6a, 0xf3, 0x6e, 0x29, 0xf0, 0xa2, 0x63, 0x5e, 0x32,
0x01, 0x90, 0x81, 0x82, 0xaa, 0x99, 0x5d, 0x0d, 0xf9, 0x90, 0xa1, 0x92, 0x6e, 0x64, 0x50, 0x92,
0x14, 0x12, 0x62, 0xb3, 0x12, 0x82, 0xc0, 0xf7, 0x4b, 0xf8, 0x8e, 0x87, 0xef, 0x94, 0xf0, 0xa5,
0x87, 0x78, 0x0f, 0x11, 0x81, 0xf7, 0x01, 0x54, 0x98, 0x44, 0xa4, 0x06, 0xa2, 0xb1, 0x02, 0x88,
0xa6, 0x3a, 0xaf, 0x00, 0x44, 0x07, 0x4a, 0x50, 0x87, 0x5c, 0xae, 0x43, 0xfd, 0x42, 0xad, 0x12,
0x75, 0x20, 0x9e, 0x64, 0xe8, 0x1a, 0x31, 0x12, 0xc9, 0x59, 0x8b, 0x03, 0x0f, 0x3c, 0x78, 0x0a,
0x40, 0x73, 0x21, 0x22, 0xb4, 0xbb, 0xd7, 0x05, 0x7b, 0xb0, 0x88, 0x36, 0x61, 0x06, 0xd2, 0xb3,
0x36, 0x72, 0x17, 0x91, 0x22, 0x22, 0x08, 0x46, 0x01, 0x8d, 0xe5, 0xa8, 0xf4, 0x02, 0xdb, 0x0b,
0xe8, 0x25, 0x9a, 0x0e, 0x5e, 0xc0, 0x86, 0x10, 0x42, 0x0c, 0x51, 0xef, 0x05, 0xc1, 0x07, 0x74,
0x7a, 0x25, 0x4a, 0x05, 0x48, 0x18, 0x22, 0x11, 0xb0, 0x01, 0xa0, 0x12, 0x3f, 0x53, 0x86, 0x44,
0xd0, 0x50, 0x04, 0xd6, 0x6a, 0x10, 0xa8, 0x67, 0x89, 0xc9, 0x2b, 0xc3, 0xc9, 0x9a, 0xa2, 0x80,
0x60, 0x0d, 0x61, 0xbf, 0x43, 0x0e, 0x3f, 0x34, 0x79, 0xbf, 0x78, 0x4a, 0x00, 0x88, 0x49, 0x91,
0x3c, 0xcb, 0xc3, 0xa1, 0x3f, 0xe4, 0x69, 0x55, 0x45, 0x10, 0x45, 0x20, 0xa0, 0x54, 0x41, 0x06,
0xc0, 0x0b, 0xd0, 0x0f, 0x01, 0x5c, 0x46, 0xe3, 0x25, 0x28, 0x8c, 0x09, 0x30, 0x96, 0xa0, 0xa4,
0x08, 0x1e, 0x28, 0x7d, 0x40, 0x29, 0x0a, 0x2f, 0x8a, 0x00, 0x05, 0x6b, 0x24, 0xad, 0xd2, 0x0b,
0x54, 0xa4, 0x8e, 0xa8, 0x30, 0x34, 0x25, 0x56, 0x8d, 0x83, 0x52, 0xc8, 0x60, 0x80, 0x8a, 0x34,
0x38, 0xdd, 0xb5, 0x77, 0xa8, 0xfe, 0xab, 0xc6, 0xee, 0x55, 0xe7, 0xd9, 0x70, 0x46, 0x00, 0x64,
0xe9, 0xe4, 0x94, 0x69, 0xba, 0x70, 0x04, 0x60, 0x30, 0xa5, 0x8d, 0x1f, 0x48, 0xf5, 0x50, 0x42,
0xea, 0xe1, 0x44, 0xac, 0xb5, 0x41, 0x15, 0x5d, 0x51, 0x64, 0x2c, 0x08, 0x42, 0xe8, 0x79, 0x01,
0xe0, 0x21, 0x00, 0x5c, 0x90, 0x38, 0x1f, 0x34, 0x0a, 0x62, 0x86, 0x57, 0x45, 0xe9, 0x05, 0x65,
0x88, 0xe0, 0x39, 0x16, 0xcc, 0x8a, 0xa2, 0xeb, 0x05, 0xc1, 0x0b, 0x62, 0x52, 0x09, 0x82, 0x28,
0x7c, 0x6d, 0x3c, 0x52, 0xd4, 0x49, 0x1d, 0x0d, 0x35, 0x37, 0x60, 0x10, 0x99, 0x50, 0x4d, 0x64,
0x19, 0x0d, 0x1e, 0x9e, 0x2f, 0x30, 0x01, 0x79, 0xe6, 0x38, 0x95, 0x40, 0xbb, 0x6b, 0x29, 0xdc,
0x0d, 0x80, 0x20, 0x8a, 0xa0, 0x00, 0x57, 0x21, 0x25, 0x8a, 0x40, 0xb1, 0xf5, 0x14, 0x8e, 0xc6,
0x1b, 0xa2, 0x48, 0x3a, 0x24, 0x30, 0x0a, 0xec, 0x10, 0x83, 0x31, 0x0e, 0x10, 0x55, 0xf4, 0x7c,
0x34, 0xb0, 0x34, 0x0c, 0x0e, 0x51, 0xb1, 0x19, 0x1b, 0x41, 0xf1, 0x12, 0xaf, 0x6f, 0x54, 0x30,
0xdb, 0x53, 0x74, 0x24, 0x1a, 0xac, 0x24, 0xd1, 0xd3, 0x41, 0xd1, 0x0d, 0x51, 0xcc, 0x08, 0x04,
0xaa, 0x01, 0x48, 0xaf, 0x8b, 0x48, 0x02, 0x42, 0xd2, 0xcf, 0xc3, 0x0b, 0x2a, 0x35, 0xe9, 0xd5,
0x83, 0x96, 0xba, 0xc7, 0x00, 0x20, 0xb1, 0x89, 0xa0, 0x85, 0x38, 0x6f, 0x37, 0x00, 0xe2, 0x6c,
0x5e, 0x20, 0x12, 0x0d, 0xe6, 0x8a, 0x69, 0x75, 0x60, 0x7c, 0x10, 0x01, 0x83, 0xe0, 0x09, 0xf0,
0x42, 0x10, 0x08, 0x76, 0x28, 0xa1, 0xc5, 0x51, 0xbc, 0xf4, 0x55, 0x51, 0x8a, 0xc6, 0x69, 0x0f,
0x03, 0x14, 0x00, 0x6b, 0x52, 0x9d, 0xd7, 0x68, 0x78, 0x57, 0x81, 0x00, 0x85, 0x90, 0x20, 0x20,
0x1a, 0xdd, 0x0d, 0xb1, 0xc5, 0xad, 0x08, 0x51, 0x92, 0xde, 0x17, 0x3f, 0xe0, 0x22, 0xd9, 0x25,
0x15, 0x53, 0xcd, 0x83, 0x31, 0x9c, 0x46, 0xee, 0x54, 0xcf, 0x1a, 0xaa, 0xd4, 0xed, 0xf6, 0xca,
0x27, 0xec, 0x78, 0x77, 0x03, 0xa0, 0x2c, 0x4b, 0x64, 0x59, 0x0e, 0xa1, 0xb4, 0x50, 0x01, 0x86,
0xe1, 0x38, 0x8d, 0x25, 0x21, 0x78, 0x92, 0x81, 0x1c, 0x56, 0x82, 0x0f, 0x02, 0x62, 0x40, 0x84,
0x10, 0x00, 0xe4, 0xa4, 0x68, 0xb1, 0x01, 0x21, 0xc4, 0x3e, 0xbf, 0x92, 0xd1, 0x50, 0x94, 0x04,
0xf4, 0x45, 0xe0, 0x35, 0x36, 0x3e, 0xaa, 0xd1, 0xd3, 0x22, 0x8a, 0x79, 0x2f, 0xe8, 0x4b, 0xea,
0xf3, 0x35, 0x3a, 0x01, 0xaa, 0x08, 0x5e, 0xd3, 0x04, 0x28, 0x75, 0x7f, 0x32, 0x94, 0x9e, 0x12,
0x13, 0xc7, 0x25, 0x15, 0x9a, 0x3b, 0x07, 0x6b, 0x86, 0x9c, 0xac, 0x31, 0xc2, 0xe6, 0x7b, 0x7d,
0xda, 0x63, 0x00, 0x66, 0x76, 0x6c, 0x5d, 0x57, 0x34, 0x9b, 0x73, 0x2c, 0xbc, 0x28, 0x04, 0x05,
0x91, 0x80, 0x42, 0xaa, 0xd9, 0x2a, 0x08, 0x92, 0x8c, 0x4f, 0xab, 0x31, 0x86, 0x00, 0xa3, 0x14,
0x01, 0x53, 0x85, 0x67, 0x46, 0x57, 0x15, 0x06, 0x04, 0x4b, 0x04, 0x92, 0x28, 0x57, 0x85, 0x00,
0xb5, 0x15, 0x45, 0x45, 0x0f, 0x7b, 0x8d, 0xb5, 0xbb, 0x14, 0x81, 0x4f, 0x11, 0xe6, 0x53, 0x04,
0x2a, 0x52, 0xd5, 0x28, 0x25, 0xf1, 0x4e, 0x88, 0xd1, 0x50, 0xcf, 0x01, 0x52, 0x04, 0x88, 0x80,
0x8d, 0x45, 0xee, 0xa2, 0xdc, 0x36, 0x69, 0x0e, 0x11, 0x4b, 0x63, 0x4c, 0xb9, 0xfb, 0xef, 0xb9,
0x63, 0x7d, 0x0a, 0x7f, 0x79, 0x4a, 0x29, 0xfc, 0x85, 0xbf, 0x7e, 0xcf, 0x16, 0x15, 0xf5, 0xa2,
0xa2, 0xb2, 0xcb, 0x72, 0x95, 0x88, 0xa4, 0x99, 0x5c, 0x80, 0x4f, 0x0b, 0x16, 0x65, 0x08, 0xf0,
0x1a, 0xe0, 0x43, 0x24, 0xb9, 0xbe, 0x0f, 0xe8, 0x85, 0x80, 0xae, 0x04, 0xcc, 0x85, 0x80, 0x59,
0xf1, 0x98, 0x97, 0x80, 0x6e, 0x08, 0xe8, 0xf6, 0xe3, 0x63, 0x27, 0x08, 0x3a, 0x21, 0xa0, 0xe7,
0x43, 0x8a, 0x08, 0x41, 0x90, 0x10, 0xaf, 0x9d, 0x72, 0xdc, 0x97, 0xe9, 0x0c, 0xf1, 0xb9, 0x48,
0x75, 0x0f, 0x29, 0x2d, 0xd2, 0xcf, 0x44, 0x80, 0xb5, 0x8c, 0x46, 0x9e, 0xa1, 0x91, 0xc7, 0x08,
0xa0, 0x44, 0x90, 0x41, 0x44, 0xbb, 0xfd, 0x12, 0xeb, 0xee, 0xbe, 0xe3, 0xb1, 0x64, 0x7c, 0xd8,
0x15, 0x04, 0xbb, 0x50, 0x58, 0x78, 0xef, 0x6f, 0x62, 0xe6, 0x83, 0x83, 0x2a, 0x28, 0x48, 0x3d,
0xb4, 0xac, 0xe6, 0x77, 0x3e, 0x79, 0x5f, 0x4d, 0x9c, 0xb8, 0x55, 0x9c, 0xe3, 0x01, 0x98, 0x40,
0x60, 0xad, 0xa6, 0x3e, 0x3b, 0xb7, 0x6f, 0xaa, 0x0a, 0x0d, 0xa9, 0x5a, 0x53, 0x2c, 0x85, 0x21,
0x95, 0x3d, 0x2f, 0x82, 0xa0, 0xf1, 0xda, 0xbe, 0x1f, 0x2b, 0x83, 0x88, 0xd4, 0xc0, 0xab, 0x46,
0xf0, 0x07, 0xaf, 0x29, 0x14, 0x91, 0x93, 0x8a, 0xcc, 0xa2, 0xdd, 0xc8, 0xd1, 0xc8, 0x2c, 0x98,
0x93, 0xd6, 0x16, 0x85, 0xf7, 0x42, 0xd3, 0xd3, 0x5b, 0x7b, 0x5b, 0x37, 0x3f, 0x36, 0x93, 0xa6,
0x42, 0xfd, 0x04, 0x80, 0x3e, 0x29, 0x00, 0xfd, 0x7e, 0xef, 0x32, 0x6b, 0xec, 0xef, 0x01, 0xa4,
0x64, 0x98, 0x10, 0x02, 0x00, 0x82, 0x25, 0xa9, 0xdb, 0x34, 0x2f, 0x04, 0x20, 0x40, 0x59, 0x41,
0x5e, 0x60, 0x0d, 0xa0, 0x81, 0x10, 0x18, 0x3b, 0x01, 0x50, 0x01, 0x97, 0xaa, 0xe9, 0x40, 0x35,
0x6a, 0x4c, 0x0b, 0x41, 0x88, 0x95, 0x27, 0x28, 0x4a, 0x49, 0x8c, 0x1f, 0x62, 0xa8, 0x87, 0x20,
0x35, 0x21, 0x86, 0x30, 0xf0, 0x7e, 0x48, 0x80, 0x40, 0x15, 0xd6, 0x18, 0xb4, 0x8a, 0x1c, 0x23,
0xad, 0x1c, 0xce, 0xd9, 0xfa, 0x33, 0x83, 0x0a, 0x4a, 0x1f, 0xb0, 0x71, 0xe3, 0x23, 0x1b, 0x3b,
0xf3, 0xb3, 0x7d, 0x00, 0x3d, 0x00, 0x9d, 0x5d, 0x23, 0x60, 0xc1, 0x6e, 0xf0, 0xce, 0xb5, 0xd7,
0x5d, 0x1c, 0x34, 0x44, 0xd4, 0x13, 0x91, 0x04, 0x09, 0xf1, 0x26, 0xaa, 0x53, 0x52, 0xee, 0x06,
0x41, 0xcf, 0x0b, 0xca, 0xe0, 0x11, 0x10, 0x53, 0xa2, 0x5f, 0x9d, 0x29, 0x1d, 0x7a, 0xe9, 0xe7,
0xfa, 0xf5, 0x20, 0x28, 0x25, 0xa0, 0x5f, 0x06, 0xf4, 0xfa, 0x82, 0x7e, 0x4f, 0xd0, 0xf3, 0x21,
0xe6, 0x7c, 0x08, 0xe9, 0x33, 0x43, 0xfd, 0x99, 0x75, 0xfe, 0xcb, 0x20, 0xf4, 0x63, 0xdf, 0x0f,
0xe4, 0xce, 0x62, 0xb4, 0x59, 0xa0, 0xdd, 0xc8, 0xe0, 0xac, 0x01, 0x33, 0x41, 0x11, 0xf9, 0xa4,
0xd3, 0x2f, 0xb1, 0xfe, 0xbe, 0x9f, 0x3e, 0x34, 0x37, 0xb3, 0xa3, 0x93, 0x66, 0x83, 0xdd, 0x3d,
0x02, 0xe0, 0x3f, 0xbf, 0xfe, 0xb9, 0xed, 0x65, 0xe9, 0xaf, 0x12, 0x11, 0x12, 0x1f, 0xbd, 0xe0,
0xd3, 0x4d, 0x57, 0xb9, 0x1f, 0x52, 0xbd, 0x0e, 0x22, 0xe8, 0x87, 0x80, 0x5e, 0x29, 0x08, 0xc1,
0xc3, 0x8b, 0xa2, 0x0c, 0x21, 0x01, 0x21, 0x91, 0xe4, 0xea, 0x33, 0xa0, 0x4c, 0xc0, 0xf5, 0xab,
0xe7, 0x21, 0xa0, 0xd4, 0x00, 0x09, 0x02, 0xad, 0xbc, 0x1c, 0x42, 0xcd, 0xfc, 0x03, 0xa3, 0xd3,
0x99, 0x5e, 0x27, 0x55, 0x58, 0x6b, 0x30, 0xda, 0x2a, 0xb0, 0x68, 0xb4, 0x81, 0x46, 0x9e, 0x45,
0x02, 0x04, 0xc5, 0x95, 0xe5, 0x32, 0x60, 0xfb, 0x8e, 0xd9, 0xf2, 0x8e, 0x5b, 0x6e, 0xba, 0x3f,
0x8d, 0xc4, 0x76, 0x2c, 0x04, 0x80, 0x7d, 0xa2, 0xf2, 0x30, 0x3f, 0xb3, 0xfd, 0x33, 0x76, 0x7c,
0xf2, 0x15, 0x30, 0x91, 0x3a, 0x94, 0xb9, 0x56, 0x16, 0x46, 0x39, 0x2e, 0x4c, 0x20, 0x40, 0x49,
0xc1, 0xcc, 0xe8, 0xab, 0x87, 0x6a, 0x54, 0x7e, 0x69, 0x21, 0x77, 0x28, 0xff, 0x35, 0xf5, 0x78,
0x55, 0x0f, 0x11, 0xab, 0x41, 0x18, 0x12, 0x33, 0x95, 0xce, 0x18, 0x36, 0x3a, 0xd4, 0x86, 0x87,
0xd8, 0x64, 0x55, 0x91, 0x10, 0x04, 0xd6, 0x30, 0x5a, 0x79, 0x8e, 0xc9, 0xd1, 0x16, 0x46, 0x5b,
0x79, 0x9a, 0x05, 0x72, 0x7d, 0x9d, 0x5e, 0xbf, 0xc4, 0xe3, 0x9b, 0xb7, 0xec, 0xb8, 0xf6, 0xca,
0x55, 0xeb, 0x13, 0x00, 0xdb, 0x53, 0x1a, 0xe8, 0x53, 0x02, 0x70, 0xf0, 0x91, 0xc7, 0xe2, 0x81,
0x7b, 0x6e, 0xfb, 0xd1, 0x51, 0xc7, 0x9d, 0xb8, 0x0e, 0xe4, 0x0e, 0x1d, 0x7e, 0x4f, 0x35, 0xae,
0x36, 0x50, 0xa8, 0x32, 0x98, 0x01, 0x16, 0x05, 0x71, 0x44, 0xde, 0xa9, 0x00, 0xc6, 0x20, 0x04,
0x40, 0x2b, 0xce, 0x18, 0xcc, 0xbe, 0xd3, 0xb6, 0x98, 0x58, 0xa3, 0xe3, 0x52, 0xdf, 0x40, 0x62,
0xef, 0xcc, 0xf2, 0x5a, 0xe7, 0x7a, 0x6d, 0x7c, 0x02, 0x84, 0x08, 0x28, 0x32, 0x87, 0xc9, 0xd1,
0x26, 0x26, 0x46, 0x0b, 0xb4, 0x8a, 0x02, 0xce, 0x9a, 0x5a, 0xfc, 0xf4, 0x7d, 0xd0, 0xf9, 0x6e,
0x49, 0xd7, 0x5c, 0x77, 0xed, 0x9d, 0xbd, 0xf9, 0x99, 0x69, 0x00, 0x5b, 0x13, 0x00, 0xbb, 0xad,
0x14, 0x2d, 0x38, 0x15, 0xde, 0xb6, 0x79, 0x13, 0xee, 0xb9, 0xf5, 0x46, 0xff, 0xd2, 0x57, 0x9d,
0x3a, 0x66, 0xac, 0x7d, 0x55, 0xbd, 0x7a, 0x93, 0x1a, 0x8c, 0x41, 0xef, 0x1f, 0x6b, 0xad, 0x26,
0xa3, 0xe2, 0xda, 0x1d, 0x60, 0xd2, 0x5c, 0x40, 0x42, 0xea, 0xea, 0x04, 0x03, 0x55, 0x57, 0xd5,
0xf1, 0x64, 0x60, 0xdd, 0x63, 0x54, 0xe1, 0x0f, 0xad, 0x43, 0xbd, 0xf2, 0x76, 0xd0, 0x41, 0xde,
0x43, 0x15, 0x85, 0xcb, 0x30, 0x35, 0xd6, 0xc4, 0xd2, 0x89, 0x36, 0x26, 0xc6, 0x47, 0xd0, 0x6e,
0x36, 0xe0, 0x6c, 0x6c, 0xb1, 0x4b, 0x11, 0xcc, 0x77, 0x7a, 0xf4, 0xc0, 0xc6, 0xc7, 0xf5, 0xa3,
0xef, 0x7f, 0xeb, 0xbf, 0x01, 0x98, 0x01, 0xb0, 0x1e, 0xc0, 0xc3, 0x89, 0x04, 0x75, 0xcf, 0x76,
0x88, 0xa8, 0xf8, 0xc7, 0x37, 0x6e, 0xf8, 0x46, 0xf0, 0x7e, 0x63, 0xa8, 0x42, 0x50, 0x53, 0xee,
0x87, 0x10, 0x85, 0x4c, 0x18, 0xd6, 0x04, 0x1e, 0x3e, 0x78, 0x94, 0xe2, 0x31, 0xe7, 0x03, 0xbc,
0xf7, 0x40, 0x92, 0xb8, 0xd5, 0xef, 0x7c, 0xf0, 0xf0, 0x3e, 0x20, 0xf8, 0x00, 0x1f, 0x42, 0xad,
0x29, 0x42, 0x08, 0x03, 0xd2, 0xf3, 0x43, 0xcf, 0xd3, 0x80, 0x23, 0x82, 0x13, 0x00, 0x55, 0xe4,
0xd6, 0x61, 0x7c, 0x24, 0xc3, 0xe4, 0x58, 0x81, 0xb1, 0xd1, 0x16, 0x5a, 0xcd, 0x1c, 0xce, 0x46,
0xf1, 0x13, 0x44, 0xd0, 0xef, 0x97, 0xd8, 0x31, 0xdf, 0xc3, 0x77, 0x56, 0x5e, 0x7c, 0x59, 0x22,
0xbe, 0xad, 0x00, 0x36, 0xa7, 0x34, 0x90, 0xbd, 0x5a, 0x19, 0xba, 0xfd, 0xfa, 0x1f, 0x6e, 0x3e,
0xe6, 0xf8, 0x93, 0x5d, 0x9e, 0x17, 0x27, 0xa7, 0x3e, 0x93, 0xea, 0x69, 0x0c, 0x06, 0x6d, 0xd9,
0xf0, 0x0a, 0x4e, 0x25, 0x59, 0x7d, 0x12, 0x2e, 0x5c, 0xf7, 0x18, 0x43, 0x7d, 0x46, 0x35, 0xbc,
0xd0, 0x44, 0xa4, 0x61, 0x10, 0xf2, 0x3b, 0x31, 0x7d, 0x8a, 0x00, 0x95, 0xb8, 0x79, 0xaa, 0x91,
0x3b, 0x8c, 0x35, 0x1d, 0xa6, 0xc6, 0x5b, 0x58, 0x3c, 0x31, 0x8e, 0x89, 0xf1, 0x36, 0x9a, 0x45,
0x16, 0x73, 0x1f, 0x40, 0x19, 0x02, 0x66, 0xe6, 0xfb, 0xb8, 0xf9, 0xb6, 0x3b, 0x1e, 0xf9, 0xfc,
0x8a, 0x8f, 0x7d, 0xdf, 0x97, 0xfd, 0xed, 0xc9, 0xfb, 0x0f, 0x26, 0x30, 0x74, 0x8f, 0x86, 0xa2,
0xc3, 0xe3, 0x81, 0x2f, 0xfe, 0xcd, 0x7b, 0xce, 0xe9, 0x76, 0x3b, 0xb7, 0x4a, 0x10, 0x0a, 0xc1,
0x6b, 0xf4, 0xe8, 0xc0, 0x4b, 0x5e, 0x92, 0x57, 0x83, 0x26, 0x6f, 0x4a, 0xbd, 0x82, 0xdb, 0x0b,
0x82, 0x6e, 0xe9, 0x11, 0x7c, 0x09, 0x22, 0x1f, 0x9b, 0x70, 0x01, 0xc4, 0xc7, 0xd2, 0x16, 0x23,
0xa8, 0xfa, 0x7b, 0x9f, 0xae, 0x99, 0xaa, 0x8c, 0x04, 0x48, 0x50, 0xb0, 0x12, 0xac, 0x61, 0x34,
0x0b, 0x42, 0xbb, 0x30, 0x18, 0x1f, 0x6d, 0x61, 0x6a, 0xd1, 0x18, 0x26, 0xc6, 0x5b, 0x3b, 0x19,
0x1f, 0x44, 0x30, 0xdf, 0x2d, 0x75, 0xd3, 0xe6, 0xad, 0xfe, 0x7b, 0x2b, 0x2f, 0x5e, 0xd3, 0x99,
0x9b, 0x99, 0x01, 0xf0, 0x38, 0x80, 0x47, 0x93, 0xf1, 0xf2, 0x74, 0x37, 0x48, 0x50, 0xd9, 0xef,
0xff, 0xd7, 0x01, 0xcb, 0x5f, 0x70, 0x06, 0x88, 0xf2, 0x6a, 0x69, 0x0a, 0x18, 0x9e, 0x96, 0xa5,
0xcd, 0x8e, 0x43, 0xbb, 0xbd, 0xb4, 0xea, 0xe8, 0xaa, 0x01, 0x48, 0x10, 0x90, 0xfa, 0xd8, 0x5b,
0x54, 0x6b, 0xe0, 0x32, 0xb4, 0x53, 0xac, 0xfe, 0x79, 0xd0, 0xb7, 0x32, 0x01, 0x86, 0x43, 0xdc,
0x32, 0x97, 0x67, 0x58, 0x34, 0xde, 0xc6, 0xd2, 0xa9, 0x71, 0x2c, 0x99, 0x18, 0xc5, 0x48, 0xb3,
0x40, 0x96, 0x88, 0x4f, 0x44, 0xd1, 0xe9, 0x95, 0x3a, 0xbd, 0x63, 0x9e, 0x7e, 0xf4, 0xdf, 0x57,
0xdf, 0x76, 0xfe, 0xe7, 0xcf, 0x5e, 0x0d, 0x60, 0x1b, 0x80, 0x75, 0xc9, 0xfb, 0xb3, 0x7b, 0xbd,
0x36, 0x58, 0x1d, 0x2e, 0x2f, 0xf0, 0xf0, 0xba, 0x9f, 0xcc, 0x1f, 0xfa, 0x82, 0xe3, 0x36, 0x36,
0xdb, 0x63, 0xa7, 0x54, 0x13, 0x95, 0x7a, 0x32, 0x33, 0x34, 0x2d, 0x1a, 0x3e, 0x07, 0xd3, 0x9c,
0xd8, 0xf1, 0x79, 0x15, 0xf8, 0x80, 0xda, 0xeb, 0xaa, 0x1e, 0xd0, 0x00, 0x52, 0x89, 0x27, 0x04,
0x50, 0x01, 0x69, 0x80, 0x4a, 0x88, 0x39, 0x8f, 0x00, 0xc3, 0x16, 0xad, 0x56, 0x03, 0x8b, 0x27,
0x46, 0xb1, 0x6c, 0x6a, 0x1c, 0x8b, 0x27, 0x46, 0x31, 0xd2, 0xcc, 0xe1, 0x4c, 0x54, 0x7d, 0xaa,
0x8a, 0x6e, 0x59, 0xea, 0xf6, 0xb9, 0x1e, 0x5d, 0x73, 0xfd, 0x8d, 0xf7, 0x7d, 0xe2, 0xcf, 0xde,
0x79, 0x51, 0x22, 0xbe, 0x07, 0x00, 0xdc, 0x07, 0x60, 0xcb, 0x93, 0x2d, 0x91, 0x3f, 0x25, 0x00,
0x12, 0x3c, 0x00, 0xc8, 0xed, 0xd7, 0xff, 0xf0, 0xce, 0xa3, 0x5e, 0xfa, 0x8a, 0x7d, 0xb2, 0xbc,
0xf1, 0x52, 0x68, 0x55, 0x03, 0xaa, 0x0d, 0x8f, 0x32, 0x58, 0xd4, 0x4c, 0xa3, 0xad, 0x1a, 0x04,
0x0c, 0xbc, 0x5c, 0x35, 0x57, 0x5e, 0x35, 0x36, 0x4f, 0xa9, 0x13, 0x8c, 0x93, 0xa2, 0x90, 0xc4,
0x52, 0xcc, 0x7d, 0x36, 0x8c, 0x46, 0x9e, 0x63, 0xd1, 0x68, 0x13, 0x4b, 0xa7, 0xc6, 0xb0, 0x6c,
0xf1, 0x38, 0xa6, 0x16, 0xb5, 0x31, 0xd2, 0x28, 0xe0, 0x4c, 0xdc, 0x7c, 0x21, 0xaa, 0xe8, 0xf6,
0x3d, 0xb6, 0xcf, 0x76, 0xe8, 0x96, 0x3b, 0xef, 0xdd, 0x72, 0xd6, 0x87, 0xde, 0xf7, 0xd5, 0x6e,
0x67, 0x7e, 0x3b, 0x80, 0x47, 0x00, 0xdc, 0x0b, 0x60, 0x63, 0x12, 0x3f, 0xcf, 0x78, 0x97, 0x98,
0x8e, 0x2c, 0x9a, 0xc2, 0x0d, 0xab, 0x2f, 0x59, 0xb5, 0xfc, 0x45, 0xc7, 0xef, 0x5b, 0x34, 0xdb,
0xc7, 0x99, 0x34, 0x78, 0xa0, 0xe1, 0x08, 0xa8, 0x9a, 0x24, 0x19, 0x4e, 0x83, 0x8a, 0xd4, 0x10,
0xe7, 0x7e, 0x29, 0x35, 0x74, 0x48, 0xda, 0xaa, 0x54, 0xb3, 0x7c, 0xc0, 0x9a, 0xb8, 0x39, 0x72,
0xac, 0xd5, 0xc0, 0xd4, 0xa2, 0x11, 0xec, 0xb7, 0x78, 0x1c, 0x4b, 0x27, 0x47, 0x31, 0x31, 0x16,
0x09, 0xcf, 0xa6, 0x72, 0x17, 0xc5, 0x8e, 0xd7, 0x6d, 0xb3, 0x1d, 0xba, 0xeb, 0xa7, 0xeb, 0xb7,
0x9c, 0xfd, 0xb1, 0x0f, 0x9d, 0xff, 0xe8, 0x86, 0xfb, 0x1f, 0x03, 0xb0, 0x29, 0x19, 0xff, 0xe0,
0x93, 0xe5, 0xfe, 0x5e, 0x6f, 0x93, 0xeb, 0x77, 0xe7, 0xa5, 0xd1, 0x1e, 0x35, 0x37, 0xfd, 0xe8,
0xd2, 0x6b, 0x0e, 0x7b, 0xe1, 0x4b, 0xb2, 0xb1, 0x45, 0x93, 0x2f, 0xcf, 0x9c, 0x85, 0x31, 0xac,
0xcc, 0x54, 0x8d, 0xee, 0x07, 0xf9, 0x0c, 0xd9, 0x69, 0x17, 0x68, 0x35, 0xce, 0x1a, 0xec, 0x0a,
0xad, 0xa6, 0x39, 0x00, 0x1b, 0x82, 0x73, 0x8c, 0x46, 0xe6, 0x30, 0xda, 0x6a, 0x60, 0x6a, 0xbc,
0x8d, 0xa5, 0x93, 0x63, 0xd8, 0x77, 0xf1, 0x18, 0x96, 0x2c, 0x1a, 0xc5, 0x58, 0xbb, 0x81, 0x22,
0x77, 0x71, 0xa9, 0x1d, 0x40, 0x08, 0x01, 0xf3, 0xbd, 0x18, 0xf6, 0x3f, 0xbe, 0xe5, 0x8e, 0x8d,
0x9f, 0xfe, 0xbb, 0xbf, 0xba, 0xe8, 0xfe, 0x7b, 0x6e, 0x7f, 0x28, 0x91, 0xde, 0x4f, 0x13, 0xf3,
0x6f, 0x7f, 0xb2, 0x8d, 0x11, 0xcf, 0x64, 0xab, 0x6c, 0x0e, 0x60, 0xf2, 0x75, 0x6f, 0xfb, 0xe0,
0x5b, 0x8e, 0x7b, 0xf9, 0xaf, 0x7f, 0xaa, 0xc8, 0x33, 0x02, 0xa0, 0x21, 0x28, 0xf9, 0x10, 0x99,
0xdd, 0xd7, 0x5e, 0xdd, 0x75, 0xbb, 0x4b, 0xd5, 0x3a, 0x13, 0x88, 0x11, 0x77, 0x94, 0xd9, 0x38,
0xc9, 0x69, 0x16, 0x19, 0xda, 0xcd, 0x1c, 0x63, 0xad, 0x06, 0x46, 0xdb, 0x0d, 0x8c, 0xb6, 0xa2,
0xc2, 0xcb, 0x32, 0x0b, 0x9b, 0xe6, 0x7c, 0xa2, 0x8a, 0xbe, 0x0f, 0x98, 0xef, 0xf4, 0x74, 0xeb,
0xcc, 0x3c, 0x5d, 0x75, 0xf5, 0x75, 0x77, 0x7e, 0xee, 0xac, 0xbf, 0xfc, 0xd6, 0xcc, 0xb6, 0xe9,
0xed, 0x00, 0x1e, 0x4b, 0x9e, 0x5f, 0x07, 0x60, 0x3a, 0xb5, 0xbe, 0x3f, 0x9b, 0xbd, 0xc2, 0xd6,
0xe5, 0x85, 0x2f, 0x7b, 0xa3, 0xc7, 0x1c, 0x7f, 0xd2, 0x2b, 0x7f, 0xf7, 0xf4, 0x77, 0x9c, 0x35,
0x35, 0x39, 0xb9, 0xdc, 0x39, 0x0b, 0x55, 0xd1, 0x10, 0x84, 0xbc, 0x8f, 0x79, 0x1d, 0xaa, 0xe9,
0x4e, 0xaa, 0x14, 0xd5, 0xb2, 0x76, 0xdc, 0x63, 0x64, 0x90, 0xbb, 0xb8, 0xab, 0xa3, 0xd5, 0xc8,
0xd0, 0x2c, 0x72, 0xb4, 0x9b, 0x39, 0x9a, 0x8d, 0x1c, 0xcd, 0xdc, 0x21, 0x73, 0x51, 0xdb, 0x47,
0xe5, 0x19, 0x45, 0x57, 0xaf, 0xef, 0x31, 0xdb, 0xe9, 0xe1, 0x91, 0x4d, 0x9b, 0x3b, 0x97, 0x5f,
0xbe, 0x7a, 0xed, 0x97, 0xcf, 0xf9, 0xd8, 0xaa, 0xa4, 0xee, 0x36, 0x25, 0xc2, 0xbb, 0x7f, 0x6f,
0x8c, 0x7f, 0x46, 0x9b, 0xa5, 0x8d, 0xb1, 0x59, 0x08, 0x7e, 0x6c, 0x6c, 0x72, 0x9f, 0x23, 0xfe,
0xf0, 0x8f, 0xdf, 0xff, 0x96, 0xa3, 0x8f, 0x7d, 0xc9, 0xe9, 0xfb, 0x2c, 0x9e, 0x68, 0x1b, 0xa6,
0xc4, 0xce, 0x3b, 0xaf, 0x25, 0x54, 0xab, 0xcb, 0x86, 0xa2, 0xd7, 0x9d, 0x8d, 0x00, 0x64, 0x99,
0x43, 0x91, 0xc5, 0x91, 0x56, 0x66, 0x2d, 0x8c, 0x8d, 0x7b, 0x0d, 0xeb, 0xa9, 0x4e, 0x10, 0xf4,
0x4a, 0xaf, 0x9d, 0x7e, 0x49, 0xd3, 0x3b, 0x3a, 0xf8, 0xf1, 0xda, 0xb5, 0x77, 0xad, 0xbc, 0xf0,
0xdc, 0x35, 0xb7, 0x5e, 0x7f, 0xd5, 0xbd, 0x89, 0xe0, 0x36, 0xa6, 0x90, 0xdf, 0x90, 0xc2, 0x7e,
0xaf, 0xb6, 0xd3, 0x3f, 0xd3, 0xef, 0x0b, 0xb8, 0xb4, 0xe6, 0xb6, 0xef, 0xfe, 0x87, 0x2c, 0x3f,
0xf2, 0xd4, 0x37, 0x9e, 0xf1, 0xe6, 0x97, 0x1f, 0x7f, 0xe2, 0xeb, 0x17, 0x8d, 0xb6, 0x91, 0x3b,
0x03, 0x67, 0xad, 0x1a, 0x26, 0x32, 0xcc, 0xf5, 0xcc, 0x9e, 0x99, 0x60, 0x4c, 0x02, 0xc2, 0x70,
0x5c, 0x3b, 0x48, 0x1b, 0x23, 0x2a, 0x85, 0x29, 0xaa, 0xf0, 0x5e, 0xd0, 0x2f, 0xbd, 0x76, 0x7a,
0x25, 0xcd, 0x75, 0x4b, 0xdc, 0x71, 0xd7, 0xdd, 0x9b, 0x2e, 0xf8, 0xca, 0xbf, 0x7c, 0xef, 0xd6,
0x1b, 0xae, 0x7a, 0x30, 0x78, 0x3f, 0x97, 0x3c, 0xfd, 0x70, 0x22, 0xbb, 0x4a, 0xec, 0xf8, 0x5f,
0xc4, 0x37, 0x46, 0x4c, 0x5a, 0x72, 0x9a, 0x00, 0x30, 0x65, 0x8b, 0xd6, 0x2f, 0xbd, 0xf3, 0x4f,
0x3f, 0xfa, 0xa6, 0x63, 0x8f, 0x39, 0xf6, 0x57, 0x27, 0x27, 0xc6, 0x47, 0xdb, 0xad, 0x56, 0xa3,
0x62, 0x6f, 0x5b, 0x6d, 0xa4, 0x66, 0x52, 0x8a, 0x47, 0xf4, 0x34, 0x54, 0x55, 0x40, 0x41, 0xe2,
0x14, 0xa7, 0x5f, 0x7a, 0xcc, 0xce, 0xcd, 0x87, 0x6d, 0x3b, 0x66, 0x3a, 0xf7, 0xad, 0x7f, 0xe0,
0xd1, 0x4b, 0x2e, 0x3c, 0x6f, 0xcd, 0xcd, 0xd7, 0x5e, 0x71, 0x77, 0x32, 0x70, 0x36, 0xe5, 0xfb,
0xc3, 0xa9, 0xdc, 0x6d, 0x5b, 0xa8, 0xcf, 0xff, 0x79, 0x7f, 0x65, 0x86, 0x00, 0x38, 0x10, 0xb5,
0xa0, 0xba, 0x08, 0xc0, 0x24, 0x8c, 0x3b, 0xe8, 0x15, 0xbf, 0xf9, 0xda, 0x63, 0x0f, 0x3f, 0xe2,
0xa8, 0xe5, 0xfb, 0x1f, 0x78, 0xd0, 0x21, 0x8b, 0x97, 0xec, 0xb3, 0x74, 0x6c, 0x6c, 0x7c, 0xb2,
0x3d, 0x32, 0xd2, 0xca, 0xb3, 0x0c, 0x99, 0xb3, 0x20, 0x22, 0xf8, 0x10, 0x0d, 0xee, 0xcc, 0xcf,
0x87, 0x1d, 0xdb, 0xb7, 0x6f, 0xdd, 0xb2, 0x65, 0xcb, 0xd6, 0x0d, 0x0f, 0xde, 0xbf, 0xf1, 0xbe,
0x7b, 0xef, 0x7a, 0xe4, 0x96, 0x9b, 0x6e, 0x7c, 0xf8, 0x91, 0x75, 0x77, 0x6d, 0x48, 0x6d, 0x6c,
0xe5, 0xf5, 0x4d, 0x09, 0x80, 0xe9, 0xa1, 0xcd, 0x90, 0xcf, 0x99, 0x2f, 0x4d, 0x71, 0x4a, 0x8b,
0x66, 0x5a, 0x8f, 0x9f, 0x00, 0x30, 0xe1, 0xf2, 0x62, 0xaa, 0xd9, 0x6c, 0x8f, 0x67, 0x79, 0xde,
0x76, 0x59, 0x56, 0x30, 0xb3, 0xa3, 0x21, 0x45, 0x29, 0xaa, 0xf0, 0x65, 0x29, 0xfd, 0x5e, 0xd7,
0xf7, 0x7a, 0xdd, 0xb2, 0x33, 0x37, 0xdb, 0x4d, 0x5e, 0xed, 0x24, 0x55, 0xb7, 0x2d, 0x29, 0xba,
0xe9, 0x34, 0xd9, 0x99, 0xdf, 0xd3, 0xad, 0xb0, 0xbf, 0xa8, 0x6f, 0x8d, 0x51, 0x1a, 0xb6, 0xe4,
0x00, 0x5a, 0x89, 0x27, 0x46, 0xd2, 0x63, 0x33, 0xa5, 0x8c, 0x4b, 0xe9, 0x43, 0x43, 0x7b, 0x1d,
0x24, 0x4d, 0x6d, 0xba, 0xc9, 0xe3, 0x73, 0xc9, 0xe0, 0xd9, 0x64, 0x74, 0x3f, 0x19, 0xae, 0xcf,
0xe6, 0x8d, 0xfe, 0xac, 0xbf, 0x94, 0x55, 0x2d, 0x4c, 0xba, 0xa1, 0x33, 0x4b, 0x8f, 0xbb, 0x76,
0xa3, 0x21, 0x19, 0xd8, 0x4f, 0xa1, 0x5d, 0x19, 0x1c, 0xf6, 0x44, 0xd4, 0x3c, 0x17, 0x01, 0x58,
0xe8, 0xb3, 0xe8, 0x89, 0x16, 0x2a, 0x77, 0x89, 0x04, 0xdd, 0x7d, 0x43, 0xcc, 0xf3, 0xc7, 0xf3,
0xc7, 0xf3, 0xc7, 0xb3, 0x7c, 0xfc, 0x1f, 0x61, 0x89, 0x33, 0x27, 0xfc, 0x0e, 0xd8, 0xd3, 0x00,
0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
};
const int ball_size = sizeof(ball);
| mit |
imasaru/sabbath-school-lessons | src/fa/2020-01/07/07.md | 3576 | ---
title: اندیشه هایی فراتر
date: 14/02/2020
---
شرح نجات دانیال در عبرانیان باب ۱۱ آمده است. چه می تواند« سرای مشهور ایمان » نامیده شود، می گوید که نبی، در میان کمالات و فضائل دیگر « دهان شیران را بستند »(عبرانیان ۱۱: ۳۳). این فوق العاده است، اما باید قهرمانانی را در نظر داشته باشیم که مانند دانیال از مرگ نجات نیافتند، بلکه آنها کسانی هستند که شجاعانه رنج کشیدند و مردند، همانطور که در عبرانیان ۱۱ نیز ذکر شده است. خداوند، برخی را فرا می خواند تا با حیاتشان گواه او برای جهانیان باشند و برخی با مرگشان گواه او باشند. بنابراین، حکایت نجات دانیال همیشه به معنای اعطا آزادی به همه نیست، همانطور که ما می دانیم، گروه بسیاری از مردان و زنان به خاطر ایمانشان به مسیح به شهادت رسیده اند. با این حال نجات معجزه آسا دانیال نشان می دهد که احکام خداوند و خود او، در نهایت تمام فرزندان او را از قدرت گناه و مرگ نجات خواهند داد. در فصل های بعدی دانیال این مسئله کاملاً روشن خواهد شد.
**سؤالاتی برای بحث**
`۱. ژان پل سارتر فرانسوی یکبار نوشت که « بهترین راه فهمیدن طرح اصلی حقیقت انسان این است که گفت، انسان موجودی است که هدفش خدا بودن است » (ژان پل سارتر، بودن یا نبودن: مقاله پدیده شناسی در هستی شناسی، کنفرانس واشنگتن). چگونه این کمک می کند، تا حداقل بطور سطحی درک کنیم که چرا شاه در دام افتاد؟ چرا همه ما باید، در هر مرحله از زندگی که هستیم، مراقب باشیم تا در دامی این چنینی یعنی تمایل خطرناک هر چقدر هم که شاید فریبنده باشد، نیفتیم؟ شیوه های دیگری که ممکن است بخواهیم « مانند خدا » باشیم چیست؟`
`۲. در رابطه با وفاوداریمان نسبت به خدا و قانون او، چه گواه و شهادتی می توانیم در برابر دیگران باشیم؟ افرادی که شما را می شناسند، در بارهٔ ایستادگی شما برای ایمانتان چه فکر می کنند، حتی اگر هزینه این ایستادگی به قیمت از دست دادن شغل یا حتی حیات شما تمام شود؟`
`۳. شما در دانیال چه می بینید که او را به شخصی که خدا می توانست از او بطور موثر برای اجرای هدف خود استفاده کند، مبدل می سازد؟ شما چگونه با یاری پروردگار، می توانید ویژگی های مشابه دانیال را در خود رشد دهید؟`
`۴. با توجه به حکم پادشاه، از چه راه هایی دانیال می توانست تصمیم خود، در تغییر شیوه دعا کردنش را توجیه کند؟ یا اینکه این یک سازش خطرناک بوده است؟ اگر بوده، چرا؟` | mit |
titanium007/Titanium | src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs | 2809 | using System;
using System.Threading;
using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Http;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.StreamExtended.Network;
namespace Titanium.Web.Proxy.EventArguments
{
/// <summary>
/// A class that wraps the state when a tunnel connect event happen for Explicit endpoints.
/// </summary>
public class TunnelConnectSessionEventArgs : SessionEventArgsBase
{
private bool? isHttpsConnect;
internal TunnelConnectSessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ConnectRequest connectRequest,
HttpClientStream clientStream, CancellationTokenSource cancellationTokenSource)
: base(server, endPoint, clientStream, connectRequest, connectRequest, cancellationTokenSource)
{
}
/// <summary>
/// Should we decrypt the Ssl or relay it to server?
/// Default is true.
/// </summary>
public bool DecryptSsl { get; set; } = true;
/// <summary>
/// When set to true it denies the connect request with a Forbidden status.
/// </summary>
public bool DenyConnect { get; set; }
/// <summary>
/// Is this a connect request to secure HTTP server? Or is it to some other protocol.
/// </summary>
public bool IsHttpsConnect
{
get => isHttpsConnect ??
throw new Exception("The value of this property is known in the BeforeTunnelConnectResponse event");
internal set => isHttpsConnect = value;
}
/// <summary>
/// Fired when decrypted data is sent within this session to server/client.
/// </summary>
public event EventHandler<DataEventArgs>? DecryptedDataSent;
/// <summary>
/// Fired when decrypted data is received within this session from client/server.
/// </summary>
public event EventHandler<DataEventArgs>? DecryptedDataReceived;
internal void OnDecryptedDataSent(byte[] buffer, int offset, int count)
{
try
{
DecryptedDataSent?.Invoke(this, new DataEventArgs(buffer, offset, count));
}
catch (Exception ex)
{
ExceptionFunc(new Exception("Exception thrown in user event", ex));
}
}
internal void OnDecryptedDataReceived(byte[] buffer, int offset, int count)
{
try
{
DecryptedDataReceived?.Invoke(this, new DataEventArgs(buffer, offset, count));
}
catch (Exception ex)
{
ExceptionFunc(new Exception("Exception thrown in user event", ex));
}
}
}
}
| mit |
ProfilerTeam/Profiler | protected/modules_core/space/messages/it/views_admin_edit.php | 1211 | <?php
/**
* Message translations.
*
* This file is automatically generated by 'yiic message' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE, this file must be saved in UTF-8 encoding.
*/
return array (
'<strong>General</strong> space settings' => 'Impostazioni <strong>Generali</strong> dello space',
'Archive' => 'Archivio',
'Choose the kind of membership you want to provide for this workspace.' => 'Scegli il tipo di membership che vuoi fornire per questo workspace.',
'Choose the security level for this workspace to define the visibleness.' => 'Scegli il livello di sicurezza di questo workspace per definirne la visibilità.',
'Delete' => 'Cancella',
'Save' => 'Salva',
'Unarchive' => 'Non archiviare',
);
| mit |
campagnola/acq4 | acq4/devices/Pipette/tracker.py | 28251 | from __future__ import print_function
import time
import pickle
import time
import numpy as np
import scipy.optimize, scipy.ndimage
from acq4.util import Qt
import acq4.pyqtgraph as pg
from acq4.Manager import getManager
class PipetteTracker(object):
"""Provides functionality for automated tracking and recalibration of pipette tip position
based on camera feedback.
The current implementation uses normalized cross-correlation to do template matching against
a stack of reference images collected with `takeReferenceFrames()`.
"""
def __init__(self, pipette):
self.dev = pipette
fileName = self.dev.configFileName('ref_frames.pk')
try:
self.reference = pickle.load(open(fileName, 'rb'))
except Exception:
self.reference = {}
def takeFrame(self, imager=None):
"""Acquire one frame from an imaging device.
This method guarantees that the frame is exposed *after* this method is called.
"""
imager = self._getImager(imager)
restart = False
if imager.isRunning():
restart = True
imager.stop()
frame = imager.acquireFrames(1)
if restart:
imager.start()
return frame
def getNextFrame(self, imager=None):
"""Return the next frame available from the imager.
Note: the frame may have been exposed before this method was called.
"""
imager = self._getImager(imager)
self.__nextFrame = None
def newFrame(newFrame):
self.__nextFrame = newFrame
imager.sigNewFrame.connect(newFrame)
try:
start = pg.ptime.time()
while pg.ptime.time() < start + 5.0:
Qt.QApplication.processEvents()
frame = self.__nextFrame
if frame is not None:
self.__nextFrame = None
return frame
time.sleep(0.01)
raise RuntimeError("Did not receive frame from imager.")
finally:
pg.disconnect(imager.sigNewFrame, newFrame)
def _getImager(self, imager=None):
if imager is None:
imager = 'Camera'
if isinstance(imager, str):
man = getManager()
imager = man.getDevice('Camera')
return imager
def getTipImageArea(self, frame, padding, pos=None, tipLength=None):
"""Generate coordinates needed to clip a camera frame to include just the
tip of the pipette and some padding.
By default, images will include the tip of the pipette to a length of 100 pixels.
Return a tuple (minImgPos, maxImgPos, tipRelPos), where the first two
items are (x,y) coordinate pairs giving the corners of the image region to
be extracted, and tipRelPos is the subpixel location of the pipette tip
within this region.
"""
img = frame.data()
if img.ndim == 3:
img = img[0]
if tipLength is None:
tipLength = self.suggestTipLength(frame)
# determine bounding rectangle that we would like to acquire from the tip
if pos is not None:
tipPos = pos
else:
tipPos = self.dev.globalPosition()
tipPos = np.array([tipPos[0], tipPos[1]])
angle = self.dev.getYawAngle() * np.pi / 180.
da = 10 * np.pi / 180 # half-angle of the tip
pxw = frame.info()['pixelSize'][0]
# compute back points of a triangle that circumscribes the tip
backPos1 = np.array([-tipLength * np.cos(angle+da), -tipLength * np.sin(angle+da)])
backPos2 = np.array([-tipLength * np.cos(angle-da), -tipLength * np.sin(angle-da)])
# convert to image coordinates
tr = frame.globalTransform().inverted()[0]
originImgPos = tr.map(pg.Vector([0, 0]))
backImgPos1 = tr.map(pg.Vector(backPos1)) - originImgPos
backImgPos2 = tr.map(pg.Vector(backPos2)) - originImgPos
backImgPos1 = np.array([backImgPos1.x(), backImgPos1.y()])
backImgPos2 = np.array([backImgPos2.x(), backImgPos2.y()])
# Pixel positions of bounding corners in the image relative to tip, including padding.
# Note this is all calculated without actual tip position; this ensures the image
# size is constant even as the tip moves.
allPos = np.vstack([[0, 0], backImgPos1, backImgPos2]).astype('int')
padding = int(padding / pxw)
minRelPos = allPos.min(axis=0) - padding
maxRelPos = allPos.max(axis=0) + padding
# Get absolute pixel position of tip within image
tipImgPos = tr.map(pg.Vector(tipPos))
tipImgPos = np.array([tipImgPos.x(), tipImgPos.y()])
tipImgPx = tipImgPos.astype('int')
# clip bounding coordinates
minRelPos = [np.clip(minRelPos[0], -tipImgPx[0], img.shape[0]-1-tipImgPx[0]),
np.clip(minRelPos[1], -tipImgPx[1], img.shape[1]-1-tipImgPx[1])]
maxRelPos = [np.clip(maxRelPos[0], -tipImgPx[0], img.shape[0]-1-tipImgPx[0]),
np.clip(maxRelPos[1], -tipImgPx[1], img.shape[1]-1-tipImgPx[1])]
# absolute image coordinates of bounding rect
minImgPos = tipImgPx + minRelPos
maxImgPos = tipImgPx + maxRelPos
if np.any(maxImgPos - minImgPos < 1):
raise RuntimeError("No part of tip overlaps with camera frame.")
# subpixel location of tip within image
tipRelPos = tipImgPos - tipImgPx - minRelPos
return minImgPos, maxImgPos, tipRelPos
def takeTipImage(self, padding=50e-6):
"""Acquire an image of the pipette tip plus some padding.
Return a tuple (image, tipPosition).
"""
frame = self.takeFrame()
minImgPos, maxImgPos, tipRelPos = self.getTipImageArea(frame, padding)
# clipped image region
subimg = frame.data()[0, minImgPos[0]:maxImgPos[0], minImgPos[1]:maxImgPos[1]]
return subimg, tipRelPos
def suggestTipLength(self, frame):
# return a suggested tip length to image, given the image resolution
# currently just returns the length of 100 pixels in the frame
return frame.info()['pixelSize'][0] * 100
def takeReferenceFrames(self, zRange=None, zStep=None, imager=None, average=8, tipLength=None):
"""Collect a series of images of the pipette tip at various focal depths.
The collected images are used as reference templates for determining the most likely location
and focal depth of the tip after the calibration is no longer valid.
The focus first is moved in +z by half of *zRange*, then stepped downward by *zStep* until the
entire *zRange* is covered. Images of the pipette tip are acquired and stored at each step.
This method assumes that the tip is in focus near the center of the camera frame, and that its
position is well-calibrated. Ideally, the illumination is flat and the area surrounding the tip
is free of any artifacts.
Images are filtered using `self.filterImage` before they are stored.
"""
imager = self._getImager(imager)
# Take an initial frame with the tip in focus.
centerFrame = self.takeFrame()
if tipLength is None:
tipLength = self.suggestTipLength(centerFrame)
if zRange is None:
zRange = tipLength*1.5
if zStep is None:
zStep = zRange / 30.
minImgPos, maxImgPos, tipRelPos = self.getTipImageArea(centerFrame, padding=tipLength*0.15, tipLength=tipLength)
center = centerFrame.data()[0, minImgPos[0]:maxImgPos[0], minImgPos[1]:maxImgPos[1]]
center = self.filterImage(center)
# Decide how many frames to collect and at what z depths
nFrames = (int(zRange / zStep) // 2) * 2
pos = self.dev.globalPosition()
zStart = pos[2] + zStep * (nFrames // 2)
frames = []
bg_frames = []
corr = []
print("Collecting %d frames of %0.2fum tip length at %0.2fum resolution." % (nFrames, tipLength*1e6, zStep*1e6))
# Stop camera if it is currently running
restart = False
if imager.isRunning():
restart = True
imager.stop()
try:
with pg.ProgressDialog('Acquiring reference frames...', 0, nFrames*2+1) as dlg:
# collect 2 stacks of images (second stack is for background subtraction)
for j in range(2):
# Set initial focus above start point to reduce hysteresis in focus mechanism
scope = self.dev.scopeDevice()
scope.setFocusDepth(zStart + 10e-6)
# Acquire multiple frames at different depths
for i in range(nFrames):
#pos[2] = zStart - zStep * i
# self.dev._moveToGlobal(pos, 'slow').wait()
scope.setFocusDepth(zStart - zStep * i).wait()
frame = imager.acquireFrames(average)
img = frame.data()[:, minImgPos[0]:maxImgPos[0], minImgPos[1]:maxImgPos[1]].astype(float).mean(axis=0)
img = self.filterImage(img)
if j == 0:
frames.append(img)
corr.append(self._matchTemplateSingle(img, center)[1])
else:
bg_frames.append(img)
dlg += 1
if dlg.wasCanceled():
return
if j == 0:
# move tip out-of-frame to collect background images
self.dev._moveToLocal([-tipLength*3, 0, 0], 'slow').wait()
else:
self.dev._moveToLocal([tipLength*3, 0, 0], 'slow')
finally:
# restart camera if it was running
if restart:
imager.start()
scope.setFocusDepth(pos[2])
# find the index of the frame that most closely matches the initial, tip-focused frame
maxInd = np.argmax(corr)
# stack all frames into a 3D array
frames = np.dstack(frames).transpose((2, 0, 1))
bg_frames = np.dstack(bg_frames).transpose((2, 0, 1))
# subtract background
# frames -= bg_frame.data()
# generate downsampled frame versions
# (for now we generate these on the fly..)
# ds = [frames] + [pg.downsample(pg.downsample(frames, n, axis=1), n, axis=2) for n in [2, 4, 8]]
key = imager.getDeviceStateKey()
self.reference[key] = {
'frames': frames - bg_frames,
'zStep': zStep,
'centerInd': maxInd,
'centerPos': tipRelPos,
'pixelSize': frame.info()['pixelSize'],
'tipLength': tipLength,
# 'downsampledFrames' = ds,
}
# Store with pickle because configfile does not support arrays
pickle.dump(self.reference, open(self.dev.configFileName('ref_frames.pk'), 'wb'))
def measureTipPosition(self, padding=50e-6, threshold=0.7, frame=None, pos=None, tipLength=None, show=False):
"""Find the pipette tip location by template matching within a region surrounding the
expected tip position.
Return `((x, y, z), corr)`, where *corr* is the normalized cross-correlation value of
the best template match.
If the strength of the match is less than *threshold*, then raise RuntimeError.
"""
# Grab one frame (if it is not already supplied) and crop it to the region around the pipette tip.
if frame is None:
frame = self.takeFrame()
elif frame == 'next':
frame = self.getNextFrame()
# load up template images
reference = self._getReference()
if tipLength is None:
# select a tip length similar to template images
tipLength = reference['tipLength']
minImgPos, maxImgPos, tipRelPos = self.getTipImageArea(frame, padding, pos=pos, tipLength=tipLength)
img = frame.data()
if img.ndim == 3:
img = img[0]
img = img[minImgPos[0]:maxImgPos[0], minImgPos[1]:maxImgPos[1]]
img = self.filterImage(img)
# resample acquired image to match template pixel size
pxr = frame.info()['pixelSize'][0] / reference['pixelSize'][0]
if pxr != 1.0:
img = scipy.ndimage.zoom(img, pxr)
# run template match against all template frames, find the frame with the strongest match
match = [self.matchTemplate(img, t) for t in reference['frames']]
if show:
pg.plot([m[0][0] for m in match], title='x match vs z')
pg.plot([m[0][1] for m in match], title='y match vs z')
pg.plot([m[1] for m in match], title='match correlation vs z')
maxInd = np.argmax([m[1] for m in match])
if match[maxInd][1] < threshold:
raise RuntimeError("Unable to locate pipette tip (correlation %0.2f < %0.2f)" % (match[maxInd][1], threshold))
# measure z error
zErr = (maxInd - reference['centerInd']) * reference['zStep']
# measure xy position
offset = match[maxInd][0]
tipImgPos = (minImgPos[0] + (offset[0] + reference['centerPos'][0]) / pxr,
minImgPos[1] + (offset[1] + reference['centerPos'][1]) / pxr)
tipPos = frame.mapFromFrameToGlobal(pg.Vector(tipImgPos))
return (tipPos.x(), tipPos.y(), tipPos.z() + zErr), match[maxInd][1]
def measureError(self, padding=50e-6, threshold=0.7, frame=None, pos=None):
"""Return an (x, y, z) tuple indicating the error vector from the calibrated tip position to the
measured (actual) tip position.
"""
if pos is None:
expectedTipPos = self.dev.globalPosition()
else:
expectedTipPos = pos
measuredTipPos, corr = self.measureTipPosition(padding, threshold, frame, pos=pos)
return tuple([measuredTipPos[i] - expectedTipPos[i] for i in (0, 1, 2)])
def _getReference(self):
key = self._getImager().getDeviceStateKey()
try:
return self.reference[key]
except KeyError:
raise Exception("No reference frames found for this pipette / objective combination.")
def autoCalibrate(self, **kwds):
"""Automatically calibrate the pipette tip position using template matching on a single camera frame.
Return the offset in pipette-local coordinates and the normalized cross-correlation value of the template match.
All keyword arguments are passed to `measureTipPosition()`.
"""
# If no image padding is given, then use the template tip length as a first guess
if 'padding' not in kwds:
ref = self._getReference()
kwds['padding'] = ref['tipLength']
if 'frame' not in kwds:
kwds['frame'] = 'next'
try:
tipPos, corr = self.measureTipPosition(**kwds)
except RuntimeError:
kwds['padding'] *= 2
tipPos, corr = self.measureTipPosition(**kwds)
localError = self.dev.mapFromGlobal(tipPos)
tr = self.dev.deviceTransform()
tr.translate(pg.Vector(localError))
self.dev.setDeviceTransform(tr)
return localError, corr
def filterImage(self, img):
"""Return a filtered version of an image to be used in template matching.
Currently, no filtering is applied.
"""
# Sobel should reduce background artifacts, but it also seems to increase the noise in the signal
# itself--two images with slightly different focus can have a very bad match.
# import skimage.feature
# return skimage.filter.sobel(img)
img = scipy.ndimage.morphological_gradient(img, size=(3, 3))
return img
def matchTemplate(self, img, template, dsVals=(4, 2, 1)):
"""Match a template to image data.
Return the (x, y) pixel offset of the template and a value indicating the strength of the match.
For efficiency, the input images are downsampled and matched at low resolution before
iteratively re-matching at higher resolutions. The *dsVals* argument lists the downsampling values
that will be used, in order. Each value in this list must be an integer multiple of
the value that follows it.
"""
# Recursively match at increasing image resolution
imgDs = [pg.downsample(pg.downsample(img, n, axis=0), n, axis=1) for n in dsVals]
tmpDs = [pg.downsample(pg.downsample(template, n, axis=0), n, axis=1) for n in dsVals]
offset = np.array([0, 0])
for i, ds in enumerate(dsVals):
pos, val = self._matchTemplateSingle(imgDs[i], tmpDs[i])
pos = np.array(pos)
if i == len(dsVals) - 1:
offset += pos
# [pg.image(imgDs[j], title=str(j)) for j in range(len(dsVals))]
return offset, val
else:
scale = ds // dsVals[i+1]
assert scale == ds / dsVals[i+1], "dsVals must satisfy constraint: dsVals[i] == dsVals[i+1] * int(x)"
offset *= scale
offset += np.clip(((pos-1) * scale), 0, imgDs[i+1].shape)
end = offset + np.array(tmpDs[i+1].shape) + 3
end = np.clip(end, 0, imgDs[i+1].shape)
imgDs[i+1] = imgDs[i+1][offset[0]:end[0], offset[1]:end[1]]
def _matchTemplateSingle(self, img, template, show=False, unsharp=3):
import skimage.feature
if img.shape[0] < template.shape[0] or img.shape[1] < template.shape[1]:
raise ValueError("Image must be larger than template. %s %s" % (img.shape, template.shape))
cc = skimage.feature.match_template(img, template)
# high-pass filter; we're looking for a fairly sharp peak.
if unsharp is not False:
cc_filt = cc - scipy.ndimage.gaussian_filter(cc, (unsharp, unsharp))
else:
cc_filt = cc
if show:
pg.image(cc)
ind = np.argmax(cc_filt)
pos = np.unravel_index(ind, cc.shape)
val = cc[pos[0], pos[1]]
return pos, val
def mapErrors(self, nSteps=(5, 5, 7), stepSize=(50e-6, 50e-6, 50e-6), padding=60e-6,
threshold=0.4, speed='slow', show=False, intermediateDist=60e-6):
"""Move pipette tip randomly to locations in a grid and measure the position error
at each location.
All tip locations must be within the field of view.
"""
startTime = time.time()
start = np.array(self.dev.globalPosition())
npts = nSteps[0] * nSteps[1] * nSteps[2]
inds = np.mgrid[0:nSteps[0], 0:nSteps[1], 0:nSteps[2]].reshape((3, npts)).transpose()
order = np.arange(npts)
np.random.shuffle(order)
err = np.zeros(nSteps + (3,))
stepSize = np.array(stepSize)
if show:
imv = pg.image()
mark1 = Qt.QGraphicsEllipseItem(Qt.QRectF(-5, -5, 10, 10))
mark1.setBrush(pg.mkBrush(255, 255, 0, 100))
mark1.setZValue(100)
imv.addItem(mark1)
mark2 = Qt.QGraphicsEllipseItem(Qt.QRectF(-5, -5, 10, 10))
mark2.setBrush(pg.mkBrush(255, 0, 0, 100))
mark2.setZValue(100)
imv.addItem(mark2)
# loop over all points in random order, and such that we do heavy computation while
# pipette is moving.
images = []
offsets = []
try:
with pg.ProgressDialog("Acquiring error map...", 0, len(order)) as dlg:
for i in range(len(order)+1):
if i > 0:
lastPos = pos
if i < len(order):
ind = inds[order[i]]
pos = start.copy() + (stepSize * ind)
# Jump to position + a random 20um offset to avoid hysteresis
offset = np.random.normal(size=3)
offset *= intermediateDist / (offset**2).sum()**0.5
offsets.append(offset)
mfut = self.dev._moveToGlobal(pos + offset, speed)
ffut = self.dev.scopeDevice().setFocusDepth(pos[2], speed)
if i > 0:
ind = inds[order[i-1]]
print("Frame: %d %s" % (i-1, lastPos))
err[tuple(ind)] = self.measureError(padding=padding, threshold=threshold, frame=frame, pos=lastPos)
print(" error: %s" % err[tuple(ind)])
dlg += 1
if show:
imv.setImage(frame.data()[0])
p1 = frame.globalTransform().inverted()[0].map(pg.Vector(lastPos))
p2 = frame.globalTransform().inverted()[0].map(pg.Vector(lastPos + err[tuple(ind)]))
mark1.setPos(p1.x(), p1.y())
mark2.setPos(p2.x(), p2.y())
# wait for previous moves to complete
mfut.wait(updates=True)
ffut.wait(updates=True)
# step back to actual target position
self.dev._moveToGlobal(pos, speed).wait(updates=True)
frame = self.takeFrame()
if dlg.wasCanceled():
return None
finally:
self.dev._moveToGlobal(start, 'fast')
self.dev.scopeDevice().setFocusDepth(start[2], 'fast')
self.errorMap = {
'err': err,
'nSteps': nSteps,
'stepSize': stepSize,
'order': order,
'inds': inds,
'offsets': offsets,
'time': time.time() - startTime,
}
filename = self.dev.configFileName('error_map.np')
np.save(open(filename, 'wb'), self.errorMap)
return self.errorMap
def showErrorAnalysis(self):
if not hasattr(self, 'errorMap'):
filename = self.dev.configFileName('error_map.np')
self.errorMap = np.load(open(filename, 'rb'))[np.newaxis][0]
err = self.errorMap
imx = pg.image(err['err'][..., 0].transpose(1, 0, 2), title='X error')
imy = pg.image(err['err'][..., 1], title='Y error')
imz = pg.image(err['err'][..., 2], title='Z error')
# get N,3 array of offset values used to randomize hysteresis
off = np.vstack(err['offsets'])
sh = err['err'].shape
# Get N,3 array of measured position errors
errf = err['err'].reshape(sh[0]*sh[1]*sh[2], 3)[err['order']]
# Display histogram of errors
win = pg.GraphicsWindow(title="%s error" % self.dev.name())
# subtract out slow drift
normErr = errf - scipy.ndimage.gaussian_filter(errf, (20, 0))
# calculate magnitude of error
absErr = (normErr**2).sum(axis=1)**0.5
# errPlot.plot(absErr)
title = "Error Histogram (mean=%s)" % pg.siFormat(absErr.mean(), suffix='m')
errPlot = win.addPlot(row=0, col=0, title=title, labels={'bottom': ('Position error', 'm')})
hist = np.histogram(absErr, bins=50)
errPlot.plot(hist[1], hist[0], stepMode=True)
# display drift and hysteresis plots
driftPlot = win.addPlot(row=0, col=1, rowspan=1, colspan=2, title="Pipette Drift",
labels={'left': ('Position error', 'm'), 'bottom': ('Time', 's')})
driftPlot.plot(np.linspace(0, err['time'], errf.shape[0]), errf[:, 0], pen='r')
driftPlot.plot(np.linspace(0, err['time'], errf.shape[0]), errf[:, 1], pen='g')
driftPlot.plot(np.linspace(0, err['time'], errf.shape[0]), errf[:, 2], pen='b')
xhplot = win.addPlot(row=1, col=0, title='X Hysteresis',
labels={'left': ('Position error', 'm'), 'bottom': ('Last pipette movement', 'm')})
xhplot.plot(-off[:, 0], errf[:, 0], pen=None, symbol='o')
yhplot = win.addPlot(row=1, col=1, title='Y Hysteresis',
labels={'left': ('Position error', 'm'), 'bottom': ('Last pipette movement', 'm')})
yhplot.plot(-off[:, 1], errf[:, 1], pen=None, symbol='o')
zhplot = win.addPlot(row=1, col=2, title='Z Hysteresis',
labels={'left': ('Position error', 'm'), 'bottom': ('Last pipette movement', 'm')})
zhplot.plot(-off[:, 2], errf[:, 2], pen=None, symbol='o')
# Print best fit for manipulator axes
expPos = err['inds'] * err['stepSize']
measPos = expPos + off
guess = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]], dtype='float')
def errFn(v):
return ((measPos - np.dot(expPos, v.reshape(3,4))[:,:3])**2).sum()
fit = scipy.optimize.minimize(errFn, guess)
print("Pipette position transform:", fit)
self.errorMapAnalysis = (imx, imy, imz, win)
class DriftMonitor(Qt.QWidget):
def __init__(self, trackers):
self.trackers = trackers
self.nextFrame = None
Qt.QWidget.__init__(self)
self.timer = Qt.QTimer()
self.timer.timeout.connect(self.update)
self.layout = Qt.QGridLayout()
self.setLayout(self.layout)
self.gv = pg.GraphicsLayoutWidget()
self.layout.addWidget(self.gv, 0, 0)
self.plot = self.gv.addPlot(labels={'left': ('Drift distance', 'm'), 'bottom': ('Time', 's')})
self.plot.addLegend()
self.xplot = self.gv.addPlot(labels={'left': ('X position', 'm')}, row=1, col=0)
self.yplot = self.gv.addPlot(labels={'left': ('Y position', 'm')}, row=2, col=0)
self.zplot = self.gv.addPlot(labels={'left': ('Z position', 'm'), 'bottom': ('Time', 's')}, row=3, col=0)
for plt in [self.xplot, self.yplot, self.zplot]:
plt.setYRange(-10e-6, 10e-6)
self.pens = [(i, len(trackers)) for i in range(len(trackers))]
self.lines = [self.plot.plot(pen=self.pens[i], name=trackers[i].dev.name()) for i in range(len(trackers))]
# self.errors = [[] for i in range(len(trackers))]
# self.cumulative = np.zeros((len(trackers), 3))
self.positions = []
self.times = []
self.timer.start(2000)
trackers[0]._getImager().sigNewFrame.connect(self.newFrame)
self.show()
def newFrame(self, frame):
self.nextFrame = frame
def update(self):
try:
if self.nextFrame is None:
return
frame = self.nextFrame
self.nextFrame = None
self.times.append(time.time())
x = np.array(self.times)
x -= x[0]
pos = []
for i, t in enumerate(self.trackers):
try:
err, corr = t.autoCalibrate(frame=frame, padding=50e-6)
# err = np.array(err)
# self.cumulative[i] += err
# err = (self.cumulative[i]**2).sum()**0.5
pos.append(t.dev.globalPosition())
except RuntimeError:
pos.append([np.nan]*3)
# self.errors[i].append(err)
self.positions.append(pos)
pos = np.array(self.positions)
pos -= pos[0]
err = (pos**2).sum(axis=2)**0.5
for i, t in enumerate(self.trackers):
self.lines[i].setData(x, err[:, i])
for ax, plt in enumerate([self.xplot, self.yplot, self.zplot]):
plt.clear()
for i, t in enumerate(self.trackers):
plt.plot(x, pos[:, i, ax], pen=self.pens[i])
except Exception:
self.timer.stop()
raise
def closeEvent(self, event):
self.timer.stop()
return Qt.QWidget.closeEvent(self, event)
| mit |
handiwijoyo/voyager | publishable/lang/zh_CN/error.php | 628 | <?php
return [
'symlink_created_text' => '我们刚刚为您创建了缺失的软连接。',
'symlink_created_title' => '丢失的存储软连接已被重新创建',
'symlink_failed_text' => '我们未能为您的应用程序生成缺失的软连接,似乎您的主机提供商不支持它。',
'symlink_failed_title' => '无法创建丢失的存储软连接',
'symlink_missing_button' => '修复',
'symlink_missing_text' => '我们找不到一个存储软连接,这可能会导致从浏览器加载媒体文件的问题。',
'symlink_missing_title' => '缺失的存储软连接',
];
| mit |
chethanjjj/gentelella | vendors/plotlyjs/lib/heatmapgl.js | 261 | /**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = require('../src/traces/heatmapgl');
| mit |
todiadiyatmo/tiga-framework | src/Response/Header.php | 1011 | <?php
namespace Tiga\Framework\Response;
/**
* HTTP Header class.
*/
class Header
{
/**
* HTTP status code.
*
* @var int
*/
protected $statusCode;
/**
* Response.
*/
protected $response;
/**
* Create header class and init the hook.
*/
public function __construct()
{
$this->hook();
return $this;
}
/**
* Set response instance.
*
* @param Response $response
*/
public function setResponse($response)
{
$this->response = $response;
}
/**
* Hook this class into status_header.
*/
public function hook()
{
add_filter('status_header', array($this, 'sendHeaderResponse'), 100);
}
/**
* Send proper HTTP response.
*/
public function sendHeaderResponse()
{
if ($this->response != false) {
$this->response->sendHeaders();
return $this->response->getWpStatusCodeHeader();
}
}
}
| mit |
huoxudong125/Z.ExtensionMethods | src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Object/Convert/ToValueType/Object.ToNullableDouble.vb | 887 |
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Public Module Extensions_398
''' <summary>
''' An object extension method that converts the @this to a nullable double.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <returns>@this as a double?</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function ToNullableDouble(this As Object) As System.Nullable(Of Double)
If this Is Nothing OrElse this = DBNull.Value Then
Return Nothing
End If
Return Convert.ToDouble(this)
End Function
End Module
| mit |
BclEx/AdamsyncEx | src/System.CoreEx/ComponentModel/DataAnnotations/DataAnnotationsResources.cs | 1841 | #region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.
*/
#endregion
using System.Resources;
using System.Globalization;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// DataAnnotationsResources
/// </summary>
internal class DataAnnotationsResources
{
private static readonly ResourceManager _resourceManager = new ResourceManager("System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources", typeof(RequiredAttribute).Assembly);
internal static string RequiredAttribute_ValidationError
{
get { return _resourceManager.GetString("RequiredAttribute_ValidationError", ResourceCulture); }
}
private static CultureInfo ResourceCulture { get; set; }
}
}
| mit |
thedanpan/toilets_directory_nyc | ar-skeleton/app.rb | 136 | #Your application starts here
require_relative 'config/application'
puts "Put your application code in #{File.expand_path(__FILE__)}"
| mit |
Paulloz/godot | editor/editor_run.cpp | 9100 | /*************************************************************************/
/* editor_run.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_run.h"
#include "core/project_settings.h"
#include "editor_settings.h"
#include "servers/display_server.h"
EditorRun::Status EditorRun::get_status() const {
return status;
}
String EditorRun::get_running_scene() const {
return running_scene;
}
Error EditorRun::run(const String &p_scene, const String &p_custom_args, const List<String> &p_breakpoints, const bool &p_skip_breakpoints) {
List<String> args;
String resource_path = ProjectSettings::get_singleton()->get_resource_path();
String remote_host = EditorSettings::get_singleton()->get("network/debug/remote_host");
int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
if (resource_path != "") {
args.push_back("--path");
args.push_back(resource_path.replace(" ", "%20"));
}
args.push_back("--remote-debug");
args.push_back("tcp://" + remote_host + ":" + String::num(remote_port));
args.push_back("--allow_focus_steal_pid");
args.push_back(itos(OS::get_singleton()->get_process_id()));
bool debug_collisions = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false);
bool debug_navigation = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_navigation", false);
if (debug_collisions) {
args.push_back("--debug-collisions");
}
if (debug_navigation) {
args.push_back("--debug-navigation");
}
int screen = EditorSettings::get_singleton()->get("run/window_placement/screen");
if (screen == 0) {
// Same as editor
screen = DisplayServer::get_singleton()->window_get_current_screen();
} else if (screen == 1) {
// Previous monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() - 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else if (screen == 2) {
// Next monitor (wrap to the other end if needed)
screen = Math::wrapi(
DisplayServer::get_singleton()->window_get_current_screen() + 1,
0,
DisplayServer::get_singleton()->get_screen_count());
} else {
// Fixed monitor ID
// There are 3 special options, so decrement the option ID by 3 to get the monitor ID
screen -= 3;
}
if (OS::get_singleton()->is_disable_crash_handler()) {
args.push_back("--disable-crash-handler");
}
Rect2 screen_rect;
screen_rect.position = DisplayServer::get_singleton()->screen_get_position(screen);
screen_rect.size = DisplayServer::get_singleton()->screen_get_size(screen);
Size2 desired_size;
desired_size.x = ProjectSettings::get_singleton()->get("display/window/size/width");
desired_size.y = ProjectSettings::get_singleton()->get("display/window/size/height");
Size2 test_size;
test_size.x = ProjectSettings::get_singleton()->get("display/window/size/test_width");
test_size.y = ProjectSettings::get_singleton()->get("display/window/size/test_height");
if (test_size.x > 0 && test_size.y > 0) {
desired_size = test_size;
}
int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect");
bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi");
int display_scale = 1;
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) {
if (OS::get_singleton()->is_hidpi_allowed()) {
if (hidpi_proj) {
display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale.
} else {
display_scale = DisplayServer::get_singleton()->screen_get_max_scale(); // Editor is in hiDPI mode, project is not, scale down.
}
} else {
if (hidpi_proj) {
display_scale = (1.f / DisplayServer::get_singleton()->screen_get_max_scale()); // Editor is not in hiDPI mode, project is, scale up.
} else {
display_scale = 1; // Both editor and project runs in lowDPI mode, do not scale.
}
}
screen_rect.position /= display_scale;
screen_rect.size /= display_scale;
}
switch (window_placement) {
case 0: { // top left
args.push_back("--position");
args.push_back(itos(screen_rect.position.x) + "," + itos(screen_rect.position.y));
} break;
case 1: { // centered
Vector2 pos = (screen_rect.position) + ((screen_rect.size - desired_size) / 2).floor();
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 2: { // custom pos
Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
pos += screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
} break;
case 3: { // force maximized
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--maximized");
} break;
case 4: { // force fullscreen
Vector2 pos = screen_rect.position;
args.push_back("--position");
args.push_back(itos(pos.x) + "," + itos(pos.y));
args.push_back("--fullscreen");
} break;
}
if (p_breakpoints.size()) {
args.push_back("--breakpoints");
String bpoints;
for (const List<String>::Element *E = p_breakpoints.front(); E; E = E->next()) {
bpoints += E->get().replace(" ", "%20");
if (E->next()) {
bpoints += ",";
}
}
args.push_back(bpoints);
}
if (p_skip_breakpoints) {
args.push_back("--skip-breakpoints");
}
if (p_scene != "") {
args.push_back(p_scene);
}
if (p_custom_args != "") {
Vector<String> cargs = p_custom_args.split(" ", false);
for (int i = 0; i < cargs.size(); i++) {
args.push_back(cargs[i].replace(" ", "%20"));
}
}
String exec = OS::get_singleton()->get_executable_path();
printf("Running: %s", exec.utf8().get_data());
for (List<String>::Element *E = args.front(); E; E = E->next()) {
printf(" %s", E->get().utf8().get_data());
};
printf("\n");
int instances = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_instances", 1);
for (int i = 0; i < instances; i++) {
OS::ProcessID pid = 0;
Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND_V(err, err);
pids.push_back(pid);
}
status = STATUS_PLAY;
if (p_scene != "") {
running_scene = p_scene;
}
return OK;
}
bool EditorRun::has_child_process(OS::ProcessID p_pid) const {
for (const List<OS::ProcessID>::Element *E = pids.front(); E; E = E->next()) {
if (E->get() == p_pid) {
return true;
}
}
return false;
}
void EditorRun::stop_child_process(OS::ProcessID p_pid) {
if (has_child_process(p_pid)) {
OS::get_singleton()->kill(p_pid);
pids.erase(p_pid);
}
}
void EditorRun::stop() {
if (status != STATUS_STOP && pids.size() > 0) {
for (List<OS::ProcessID>::Element *E = pids.front(); E; E = E->next()) {
OS::get_singleton()->kill(E->get());
}
}
status = STATUS_STOP;
running_scene = "";
}
EditorRun::EditorRun() {
status = STATUS_STOP;
running_scene = "";
}
| mit |
laudaa/bitcoin | src/compat.h | 2175 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_COMPAT_H
#define BITCOIN_COMPAT_H
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifdef FD_SETSIZE
#undef FD_SETSIZE // prevent redefinition compiler warning
#endif
#define FD_SETSIZE 1024 // max number of fds in fd_set
#include <winsock2.h> // Must be included before mswsock.h and windows.h
#include <mswsock.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdint.h>
#else
#include <sys/fcntl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <limits.h>
#include <netdb.h>
#include <unistd.h>
#endif
#ifndef WIN32
typedef unsigned int SOCKET;
#include <errno.h>
#define WSAGetLastError() errno
#define WSAEINVAL EINVAL
#define WSAEALREADY EALREADY
#define WSAEWOULDBLOCK EWOULDBLOCK
#define WSAEMSGSIZE EMSGSIZE
#define WSAEINTR EINTR
#define WSAEINPROGRESS EINPROGRESS
#define WSAEADDRINUSE EADDRINUSE
#define WSAENOTSOCK EBADF
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR -1
#endif
#ifdef WIN32
#ifndef S_IRUSR
#define S_IRUSR 0400
#define S_IWUSR 0200
#endif
#else
#define MAX_PATH 1024
#endif
#ifdef _MSC_VER
#if !defined(ssize_t)
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#endif
#if HAVE_DECL_STRNLEN == 0
size_t strnlen( const char *start, size_t max_len);
#endif // HAVE_DECL_STRNLEN
bool static inline IsSelectableSocket(const SOCKET& s) {
#ifdef WIN32
return true;
#else
return (s < FD_SETSIZE);
#endif
}
#endif // BITCOIN_COMPAT_H
| mit |
Darelbi/Infectorpp | include/Infectorpp/priv/DependencyDAG.hpp | 1969 | /*******************************************************************************
Copyright (C) 2015 Dario Oliveri
See copyright notice in LICENSE.md
*******************************************************************************/
#pragma once
#include <list>
#include <typeindex>
#include <unordered_map>
#include "InfectorTypes.hpp"
namespace Infector {
namespace priv {
class ConcreteContainer;
/** Dependency Direct Acyclic Graph.
This collect dependencies between concrete types only ( A bit pointless
tracing dependencies between interfaces since interfaces has no ctor).
A Dependency DAG lives in one context only (Context inheritance is resolved
by context only by creating a SymbolTable)*/
class DependencyDAG{
public:
DependencyDAG( DependencyDAG * parent);
~DependencyDAG();
void setGuard( TypeInfoP g);
//type resolution is container responsibility
void dependOn( TypeInfoP wired, TypeInfoP abstractDep,
ConcreteContainer * container);
void remove( TypeInfoP concrete);
/** clean memory used by DAG.*/
void clean();
using EdgeMap = std::unordered_map< std::type_index,
std::list< TypeInfoP> >;
std::list<TypeInfoP> getDependencies( TypeInfoP concrete);
//
//when you realize your Typo was "TypO" instead of "TypE" u.u ...
std::list<TypeInfoP> getDependencies( std::type_index & concrete);
private:
using EdgeMapPtr = std::shared_ptr<EdgeMap>;
EdgeMapPtr dependencies = std::make_shared<EdgeMap>();
EdgeMapPtr dependants = std::make_shared<EdgeMap>();
TypeInfoP guard = nullptr;
DependencyDAG* parent = nullptr;
void removeDependant( TypeInfoP wired, TypeInfoP abstractDep);
void addDependency( TypeInfoP wired, TypeInfoP abstractDep);
void addDependant( TypeInfoP wired, TypeInfoP abstractDep);
void checkGuardBreaking( TypeInfoP currentNode,
ConcreteContainer * container,
int HARD_RECURSION_LIMIT);
};
} // namespace priv
} // namespace Infector | mit |
MarimerLLC/csla | Source/Csla.Analyzers/Csla.Analyzers.Tests/IsOperationMethodPublicAnalyzerTests.cs | 4968 | using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Csla.Analyzers.Tests
{
[TestClass]
public sealed class IsOperationMethodPublicAnalyzerTests
{
[TestMethod]
public void VerifySupportedDiagnostics()
{
var analyzer = new IsOperationMethodPublicAnalyzer();
var diagnostics = analyzer.SupportedDiagnostics;
Assert.AreEqual(2, diagnostics.Length);
var diagnostic = diagnostics.Single(_ => _.Id == Constants.AnalyzerIdentifiers.IsOperationMethodPublic);
Assert.AreEqual(IsOperationMethodPublicAnalyzerConstants.Title, diagnostic.Title.ToString(),
nameof(DiagnosticDescriptor.Title));
Assert.AreEqual(IsOperationMethodPublicAnalyzerConstants.Message, diagnostic.MessageFormat.ToString(),
nameof(DiagnosticDescriptor.MessageFormat));
Assert.AreEqual(Constants.Categories.Design, diagnostic.Category,
nameof(DiagnosticDescriptor.Category));
Assert.AreEqual(DiagnosticSeverity.Warning, diagnostic.DefaultSeverity,
nameof(DiagnosticDescriptor.DefaultSeverity));
Assert.AreEqual(HelpUrlBuilder.Build(Constants.AnalyzerIdentifiers.IsOperationMethodPublic, nameof(IsOperationMethodPublicAnalyzer)),
diagnostic.HelpLinkUri,
nameof(DiagnosticDescriptor.HelpLinkUri));
var diagnosticForInterface = diagnostics.Single(_ => _.Id == Constants.AnalyzerIdentifiers.IsOperationMethodPublicForInterface);
Assert.AreEqual(IsOperationMethodPublicAnalyzerConstants.Title, diagnosticForInterface.Title.ToString(),
nameof(DiagnosticDescriptor.Title));
Assert.AreEqual(IsOperationMethodPublicAnalyzerConstants.Message, diagnosticForInterface.MessageFormat.ToString(),
nameof(DiagnosticDescriptor.MessageFormat));
Assert.AreEqual(Constants.Categories.Design, diagnosticForInterface.Category,
nameof(DiagnosticDescriptor.Category));
Assert.AreEqual(DiagnosticSeverity.Warning, diagnosticForInterface.DefaultSeverity,
nameof(DiagnosticDescriptor.DefaultSeverity));
Assert.AreEqual(HelpUrlBuilder.Build(Constants.AnalyzerIdentifiers.IsOperationMethodPublicForInterface, nameof(IsOperationMethodPublicAnalyzer)),
diagnosticForInterface.HelpLinkUri,
nameof(DiagnosticDescriptor.HelpLinkUri));
}
[TestMethod]
public async Task AnalyzeWhenTypeIsNotStereotype()
{
var code =
@"public class A
{
[Fetch]
public void Fetch() { }
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(
code, Array.Empty<string>());
}
[TestMethod]
public async Task AnalyzeWhenTypeIsStereotypeAndMethodIsNotADataPortalOperation()
{
var code =
@"using Csla;
using System;
[Serializable]
public class A : BusinessBase<A>
{
public void AMethod() { }
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(
code, Array.Empty<string>());
}
[TestMethod]
public async Task AnalyzeWhenTypeIsStereotypeAndMethodIsADataPortalOperationThatIsNotPublic()
{
var code =
@"using Csla;
using System;
[Serializable]
public class A : BusinessBase<A>
{
private void DataPortal_Fetch() { }
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(
code, Array.Empty<string>());
}
[TestMethod]
public async Task AnalyzeWhenTypeIsStereotypeAndMethodIsADataPortalOperationThatIsPublicAndClassIsNotSealed()
{
var code =
@"using Csla;
using System;
[Serializable]
public class A : BusinessBase<A>
{
[Fetch]
public void Fetch() { }
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(code,
new[] { Constants.AnalyzerIdentifiers.IsOperationMethodPublic },
diagnostics => Assert.AreEqual(false.ToString(), diagnostics[0].Properties[IsOperationMethodPublicAnalyzerConstants.IsSealed]));
}
[TestMethod]
public async Task AnalyzeWhenTypeIsStereotypeAndMethodIsADataPortalOperationThatIsPublicAndClassIsSealed()
{
var code =
@"using Csla;
using System;
[Serializable]
public sealed class A : BusinessBase<A>
{
[Fetch]
public void Fetch() { }
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(code,
new[] { Constants.AnalyzerIdentifiers.IsOperationMethodPublic },
diagnostics => Assert.AreEqual(true.ToString(), diagnostics[0].Properties[IsOperationMethodPublicAnalyzerConstants.IsSealed]));
}
[TestMethod]
public async Task AnalyzeWhenTypeIsStereotypeAndMethodIsADataPortalOperationThatIsPublicAndTypeIsInterface()
{
var code =
@"using Csla;
using Csla.Core;
public interface A
: IBusinessObject
{
[Fetch]
void Fetch();
}";
await TestHelpers.RunAnalysisAsync<IsOperationMethodPublicAnalyzer>(code,
new[] { Constants.AnalyzerIdentifiers.IsOperationMethodPublicForInterface });
}
}
} | mit |
verycumbersome/the-blue-alliance | tests/test_event_team_status_helper.py | 55040 | import json
import unittest2
from appengine_fixture_loader.loader import load_fixture
from google.appengine.ext import testbed
from google.appengine.ext import ndb
from helpers.event_simulator import EventSimulator
from helpers.event_team_status_helper import EventTeamStatusHelper
from models.event import Event
from models.event_details import EventDetails
from models.match import Match
class TestSimulated2016nytrEventTeamStatusHelper(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
self.testbed.init_taskqueue_stub(root_path=".")
ndb.get_context().clear_cache() # Prevent data from leaking between tests
def tearDown(self):
self.testbed.deactivate()
def testSimulatedEvent(self):
es = EventSimulator()
event = Event.get_by_id('2016nytr')
es.step()
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>Rank 15/36</b> with a record of <b>0-0-0</b> in quals.')
for _ in xrange(5):
es.step()
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>Rank 6/36</b> with a record of <b>1-0-0</b> in quals.')
for _ in xrange(67):
es.step()
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 was <b>Rank 1/36</b> with a record of <b>11-1-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 was <b>Rank 16/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # Alliance selections added
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 was <b>Rank 1/36</b> with a record of <b>11-1-0</b> in quals and will be competing in the playoffs as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals and will be competing in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 was <b>Rank 16/36</b> with a record of <b>6-6-0</b> in quals and will be competing in the playoffs as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # QF schedule added
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>0-0-0</b> in the <b>Quarterfinals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 is <b>0-0-0</b> in the <b>Quarterfinals</b> as the <b>1st Pick</b> of <b>Alliance 4</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>0-0-0</b> in the <b>Quarterfinals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # qf1m1
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>1-0-0</b> in the <b>Quarterfinals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
es.step() # qf2m1
es.step() # qf3m1
es.step() # qf4m1
es.step() # qf1m2
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>0-0-0</b> in the <b>Semifinals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 is <b>0-1-0</b> in the <b>Quarterfinals</b> as the <b>1st Pick</b> of <b>Alliance 4</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>1-0-0</b> in the <b>Quarterfinals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # qf2m2
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 is <b>1-1-0</b> in the <b>Quarterfinals</b> as the <b>1st Pick</b> of <b>Alliance 4</b>.')
es.step() # qf3m2
es.step() # qf4m2
es.step() # qf2m3
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 is <b>0-0-0</b> in the <b>Semifinals</b> as the <b>1st Pick</b> of <b>Alliance 4</b>.')
es.step() # qf4m3
es.step() # sf1m1
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>1-0-0</b> in the <b>Semifinals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 is <b>0-1-0</b> in the <b>Semifinals</b> as the <b>1st Pick</b> of <b>Alliance 4</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>0-0-0</b> in the <b>Semifinals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # sf2m1
es.step() # sf1m2
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>0-0-0</b> in the <b>Finals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>0-1-0</b> in the <b>Semifinals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # sf2m2
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>0-0-0</b> in the <b>Finals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>1-1-0</b> in the <b>Semifinals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 is <b>1-1-0</b> in the <b>Semifinals</b> as the <b>Backup</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # sf2m3
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>0-0-0</b> in the <b>Finals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>0-0-0</b> in the <b>Finals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 is <b>0-0-0</b> in the <b>Finals</b> as the <b>Backup</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # f1m1
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>1-0-0</b> in the <b>Finals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>0-1-0</b> in the <b>Finals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 is <b>0-1-0</b> in the <b>Finals</b> as the <b>Backup</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # f1m2
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 is <b>1-1-0</b> in the <b>Finals</b> as the <b>Captain</b> of <b>Alliance 1</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 is <b>1-1-0</b> in the <b>Finals</b> as the <b>2nd Pick</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 is <b>1-1-0</b> in the <b>Finals</b> as the <b>Backup</b> of <b>Alliance 2</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
es.step() # f1m3
event = Event.get_by_id('2016nytr')
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 was <b>Rank 1/36</b> with a record of <b>11-1-0</b> in quals, competed in the playoffs as the <b>Captain</b> of <b>Alliance 1</b>, and <b>won the event</b> with a playoff record of <b>6-1-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 4/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 was <b>Rank 16/36</b> with a record of <b>6-6-0</b> in quals, competed in the playoffs as the <b>2nd Pick</b> of <b>Alliance 2</b>, and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 15/36</b> with a record of <b>6-6-0</b> in quals, competed in the playoffs as the <b>Backup</b> of <b>Alliance 2</b>, and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', event)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 21/36</b> with a record of <b>6-6-0</b> in quals.')
class Test2016nytrEventTeamStatusHelper(unittest2.TestCase):
status_359 = {
"alliance": {
"backup": None,
"name": "Alliance 1",
"number": 1,
"pick": 0
},
"playoff": {
"current_level_record": {
"losses": 1,
"ties": 0,
"wins": 2
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 1,
"ties": 0,
"wins": 6
},
"status": "won"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": 0,
"matches_played": 12,
"qual_average": None,
"rank": 1,
"record": {
"losses": 1,
"ties": 0,
"wins": 11
},
"sort_orders": [
39.0,
310.0,
165.0,
448.0,
600.0
],
"team_key": "frc359"
},
"sort_order_info": [
{
"name": "Ranking Score",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Scale/Challenge",
"precision": 0
},
{
"name": "Goals",
"precision": 0
},
{
"name": "Defense",
"precision": 0
}
],
"status": "completed"
}
}
status_5240 = {
"alliance": {
"backup": None,
"name": "Alliance 4",
"number": 4,
"pick": 1
},
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 0
},
"level": "sf",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 2
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": 0,
"matches_played": 12,
"qual_average": None,
"rank": 6,
"record": {
"losses": 3,
"ties": 0,
"wins": 9
},
"sort_orders": [
28.0,
260.0,
150.0,
191.0,
575.0
],
"team_key": "frc5240"
},
"sort_order_info": [
{
"name": "Ranking Score",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Scale/Challenge",
"precision": 0
},
{
"name": "Goals",
"precision": 0
},
{
"name": "Defense",
"precision": 0
}
],
"status": "completed"
}
}
status_229 = {
"alliance": {
"backup": {
"in": "frc1665",
"out": "frc229"
},
"name": "Alliance 2",
"number": 2,
"pick": 2
},
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 1
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 5
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": 0,
"matches_played": 12,
"qual_average": None,
"rank": 20,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": [
20.0,
156.0,
130.0,
119.0,
525.0
],
"team_key": "frc229"
},
"sort_order_info": [
{
"name": "Ranking Score",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Scale/Challenge",
"precision": 0
},
{
"name": "Goals",
"precision": 0
},
{
"name": "Defense",
"precision": 0
}
],
"status": "completed"
}
}
status_1665 = {
"alliance": {
"backup": {
"in": "frc1665",
"out": "frc229"
},
"name": "Alliance 2",
"number": 2,
"pick": -1
},
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 1
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 5
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": 0,
"matches_played": 12,
"qual_average": None,
"rank": 18,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": [
20.0,
192.0,
105.0,
146.0,
525.0
],
"team_key": "frc1665"
},
"sort_order_info": [
{
"name": "Ranking Score",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Scale/Challenge",
"precision": 0
},
{
"name": "Goals",
"precision": 0
},
{
"name": "Defense",
"precision": 0
}
],
"status": "completed"
}
}
status_5964 = {
"alliance": None,
"playoff": None,
"qual": {
"num_teams": 36,
"ranking": {
"dq": 0,
"matches_played": 12,
"qual_average": None,
"rank": 23,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": [
19.0,
218.0,
110.0,
159.0,
520.0
],
"team_key": "frc5964"
},
"sort_order_info": [
{
"name": "Ranking Score",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Scale/Challenge",
"precision": 0
},
{
"name": "Goals",
"precision": 0
},
{
"name": "Defense",
"precision": 0
}
],
"status": "completed"
}
}
status_1124 = {
"qual": None,
"playoff": None,
"alliance": None
}
# Because I can't figure out how to get these to generate
def event_key_adder(self, obj):
obj.event = ndb.Key(Event, '2016nytr')
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
ndb.get_context().clear_cache() # Prevent data from leaking between tests
load_fixture('test_data/fixtures/2016nytr_event_team_status.json',
kind={'EventDetails': EventDetails, 'Event': Event, 'Match': Match},
post_processor=self.event_key_adder)
self.event = Event.get_by_id('2016nytr')
self.assertIsNotNone(self.event)
def tearDown(self):
self.testbed.deactivate()
def testEventWinner(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', self.event)
self.assertDictEqual(status, self.status_359)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 was <b>Rank 1/36</b> with a record of <b>11-1-0</b> in quals, competed in the playoffs as the <b>Captain</b> of <b>Alliance 1</b>, and <b>won the event</b> with a playoff record of <b>6-1-0</b>.')
def testElimSemisAndFirstPick(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', self.event)
self.assertDictEqual(status, self.status_5240)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 was <b>Rank 6/36</b> with a record of <b>9-3-0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 4</b>, and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
def testBackupOut(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', self.event)
self.assertDictEqual(status, self.status_229)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 was <b>Rank 20/36</b> with a record of <b>6-6-0</b> in quals, competed in the playoffs as the <b>2nd Pick</b> of <b>Alliance 2</b>, and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
def testBackupIn(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', self.event)
self.assertDictEqual(status, self.status_1665)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 was <b>Rank 18/36</b> with a record of <b>6-6-0</b> in quals, competed in the playoffs as the <b>Backup</b> of <b>Alliance 2</b>, and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
def testTeamNotPicked(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', self.event)
self.assertDictEqual(status, self.status_5964)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 was <b>Rank 23/36</b> with a record of <b>6-6-0</b> in quals.')
class Test2016nytrEventTeamStatusHelperNoEventDetails(unittest2.TestCase):
status_359 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 1,
"ties": 0,
"wins": 2
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 1,
"ties": 0,
"wins": 6
},
"status": "won"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": None,
"matches_played": 12,
"qual_average": None,
"rank": None,
"record": {
"losses": 1,
"ties": 0,
"wins": 11
},
"sort_orders": None,
"team_key": "frc359",
},
"sort_order_info": None,
"status": "completed"
}
}
status_5240 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 0
},
"level": "sf",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 2
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": None,
"matches_played": 12,
"qual_average": None,
"rank": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 9
},
"sort_orders": None,
"team_key": "frc5240",
},
"sort_order_info": None,
"status": "completed"
}
}
status_229 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 1
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 5
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": None,
"matches_played": 12,
"qual_average": None,
"rank": None,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": None,
"team_key": "frc229",
},
"sort_order_info": None,
"status": "completed"
}
}
status_1665 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 2,
"ties": 0,
"wins": 1
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 3,
"ties": 0,
"wins": 5
},
"status": "eliminated"
},
"qual": {
"num_teams": 36,
"ranking": {
"dq": None,
"matches_played": 12,
"qual_average": None,
"rank": None,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": None,
"team_key": "frc1665",
},
"sort_order_info": None,
"status": "completed"
}
}
status_5964 = {
"alliance": None,
"playoff": None,
"qual": {
"num_teams": 36,
"ranking": {
"dq": None,
"matches_played": 12,
"qual_average": None,
"rank": None,
"record": {
"losses": 6,
"ties": 0,
"wins": 6
},
"sort_orders": None,
"team_key": "frc5964",
},
"sort_order_info": None,
"status": "completed"
}
}
status_1124 = {
"qual": None,
"playoff": None,
"alliance": None
}
# Because I can't figure out how to get these to generate
def event_key_adder(self, obj):
obj.event = ndb.Key(Event, '2016nytr')
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
ndb.get_context().clear_cache() # Prevent data from leaking between tests
load_fixture('test_data/fixtures/2016nytr_event_team_status.json',
kind={'EventDetails': EventDetails, 'Event': Event, 'Match': Match},
post_processor=self.event_key_adder)
self.event = Event.get_by_id('2016nytr')
EventDetails.get_by_id('2016nytr').key.delete() # Remove EventDetails
self.assertIsNotNone(self.event)
def tearDown(self):
self.testbed.deactivate()
def testEventWinner(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc359', self.event)
self.assertDictEqual(status, self.status_359)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc359', status),
'Team 359 had a record of <b>11-1-0</b> in quals and <b>won the event</b> with a playoff record of <b>6-1-0</b>.')
def testElimSemisAndFirstPick(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc5240', self.event)
self.assertDictEqual(status, self.status_5240)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5240', status),
'Team 5240 had a record of <b>9-3-0</b> in quals and was <b>eliminated in the Semifinals</b> with a playoff record of <b>2-3-0</b>.')
def testBackupOut(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc229', self.event)
self.assertDictEqual(status, self.status_229)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc229', status),
'Team 229 had a record of <b>6-6-0</b> in quals and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
def testBackupIn(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc1665', self.event)
self.assertDictEqual(status, self.status_1665)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc1665', status),
'Team 1665 had a record of <b>6-6-0</b> in quals and was <b>eliminated in the Finals</b> with a playoff record of <b>5-3-0</b>.')
def testTeamNotPicked(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc5964', self.event)
self.assertDictEqual(status, self.status_5964)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc5964', status),
'Team 5964 had a record of <b>6-6-0</b> in quals.')
class Test2016casjEventTeamStatusHelperNoEventDetails(unittest2.TestCase):
status_254 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 0,
"ties": 0,
"wins": 2
},
"level": "f",
"playoff_average": None,
"record": {
"losses": 0,
"ties": 0,
"wins": 6
},
"status": "won"
},
"qual": {
"num_teams": 64,
"ranking": {
"dq": None,
"matches_played": 8,
"qual_average": None,
"rank": None,
"record": {
"losses": 0,
"ties": 0,
"wins": 8
},
"sort_orders": None,
"team_key": "frc254",
},
"sort_order_info": None,
"status": "completed"
}
}
# Because I can't figure out how to get these to generate
def event_key_adder(self, obj):
obj.event = ndb.Key(Event, '2016casj')
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
ndb.get_context().clear_cache() # Prevent data from leaking between tests
load_fixture('test_data/fixtures/2016casj.json',
kind={'EventDetails': EventDetails, 'Event': Event, 'Match': Match},
post_processor=self.event_key_adder)
self.event = Event.get_by_id('2016casj')
self.assertIsNotNone(self.event)
def tearDown(self):
self.testbed.deactivate()
def testEventSurrogate(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc254', self.event)
self.assertDictEqual(status, self.status_254)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc254', status),
'Team 254 had a record of <b>8-0-0</b> in quals and <b>won the event</b> with a playoff record of <b>6-0-0</b>.')
class Test2015casjEventTeamStatusHelper(unittest2.TestCase):
status_254 = {
"alliance": {
"backup": None,
"name": "Alliance 1",
"number": 1,
"pick": 0
},
"playoff": {
"current_level_record": {
"losses": 0,
"ties": 0,
"wins": 2
},
"level": "f",
"playoff_average": 224.14285714285714,
"record": None,
"status": "won"
},
"qual": {
"num_teams": 57,
"ranking": {
"dq": 0,
"matches_played": 10,
"qual_average": 200.4,
"rank": 1,
"record": None,
"sort_orders": [
200.4,
280.0,
200.0,
836.0,
522.0,
166.0
],
"team_key": "frc254"
},
"sort_order_info": [
{
"name": "Qual Avg.",
"precision": 1
},
{
"name": "Coopertition",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Container",
"precision": 0
},
{
"name": "Tote",
"precision": 0
},
{
"name": "Litter",
"precision": 0
}
],
"status": "completed"
}
}
status_846 = {
"alliance": {
"backup": None,
"name": "Alliance 3",
"number": 3,
"pick": 1
},
"playoff": {
"current_level_record": None,
"level": "sf",
"playoff_average": 133.59999999999999,
"record": None,
"status": "eliminated"
},
"qual": {
"num_teams": 57,
"ranking": {
"dq": 0,
"matches_played": 10,
"qual_average": 97.0,
"rank": 8,
"record": None,
"sort_orders": [
97.0,
200.0,
20.0,
372.0,
294.0,
108.0
],
"team_key": "frc846"
},
"sort_order_info": [
{
"name": "Qual Avg.",
"precision": 1
},
{
"name": "Coopertition",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Container",
"precision": 0
},
{
"name": "Tote",
"precision": 0
},
{
"name": "Litter",
"precision": 0
}
],
"status": "completed"
}
}
status_8 = {
"alliance": None,
"playoff": None,
"qual": {
"num_teams": 57,
"ranking": {
"dq": 0,
"matches_played": 10,
"qual_average": 42.6,
"rank": 53,
"record": None,
"sort_orders": [
42.6,
120.0,
0.0,
84.0,
150.0,
72.0
],
"team_key": "frc8"
},
"sort_order_info": [
{
"name": "Qual Avg.",
"precision": 1
},
{
"name": "Coopertition",
"precision": 0
},
{
"name": "Auto",
"precision": 0
},
{
"name": "Container",
"precision": 0
},
{
"name": "Tote",
"precision": 0
},
{
"name": "Litter",
"precision": 0
}
],
"status": "completed"
}
}
status_1124 = {
"qual": None,
"playoff": None,
"alliance": None
}
# Because I can't figure out how to get these to generate
def event_key_adder(self, obj):
obj.event = ndb.Key(Event, '2015casj')
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
ndb.get_context().clear_cache() # Prevent data from leaking between tests
load_fixture('test_data/fixtures/2015casj.json',
kind={'EventDetails': EventDetails, 'Event': Event, 'Match': Match},
post_processor=self.event_key_adder)
self.event = Event.get_by_id('2015casj')
self.assertIsNotNone(self.event)
def tearDown(self):
self.testbed.deactivate()
def testEventWinner(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc254', self.event)
self.assertDictEqual(status, self.status_254)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc254', status),
'Team 254 was <b>Rank 1/57</b> with an average score of <b>200.4</b> in quals, competed in the playoffs as the <b>Captain</b> of <b>Alliance 1</b>, and <b>won the event</b> with a playoff average of <b>224.1</b>.')
def testElimSemisAndFirstPick(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc846', self.event)
self.assertDictEqual(status, self.status_846)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc846', status),
'Team 846 was <b>Rank 8/57</b> with an average score of <b>97.0</b> in quals, competed in the playoffs as the <b>1st Pick</b> of <b>Alliance 3</b>, and was <b>eliminated in the Semifinals</b> with a playoff average of <b>133.6</b>.')
def testTeamNotPicked(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc8', self.event)
self.assertDictEqual(status, self.status_8)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc8', status),
'Team 8 was <b>Rank 53/57</b> with an average score of <b>42.6</b> in quals.')
class Test2015casjEventTeamStatusHelperNoEventDetails(unittest2.TestCase):
status_254 = {
"alliance": None,
"playoff": {
"current_level_record": {
"losses": 0,
"ties": 0,
"wins": 2
},
"level": "f",
"playoff_average": 224.14285714285714,
"record": None,
"status": "won"
},
"qual": {
"num_teams": 57,
"ranking": {
"dq": None,
"matches_played": 10,
"qual_average": 200.4,
"rank": None,
"record": None,
"sort_orders": None,
"team_key": "frc254",
},
"sort_order_info": None,
"status": "completed"
}
}
status_846 = {
"alliance": None,
"playoff": {
"current_level_record": None,
"level": "sf",
"playoff_average": 133.59999999999999,
"record": None,
"status": "eliminated"
},
"qual": {
"num_teams": 57,
"ranking": {
"dq": None,
"matches_played": 10,
"qual_average": 97.0,
"rank": None,
"record": None,
"sort_orders": None,
"team_key": "frc846",
},
"sort_order_info": None,
"status": "completed"
}
}
status_8 = {
"alliance": None,
"playoff": None,
"qual": {
"num_teams": 57,
"ranking": {
"dq": None,
"matches_played": 10,
"qual_average": 42.6,
"rank": None,
"record": None,
"sort_orders": None,
"team_key": "frc8",
},
"sort_order_info": None,
"status": "completed"
}
}
status_1124 = {
"qual": None,
"playoff": None,
"alliance": None
}
# Because I can't figure out how to get these to generate
def event_key_adder(self, obj):
obj.event = ndb.Key(Event, '2015casj')
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
ndb.get_context().clear_cache() # Prevent data from leaking between tests
load_fixture('test_data/fixtures/2015casj.json',
kind={'EventDetails': EventDetails, 'Event': Event, 'Match': Match},
post_processor=self.event_key_adder)
self.event = Event.get_by_id('2015casj')
EventDetails.get_by_id('2015casj').key.delete() # Remove EventDetails
self.assertIsNotNone(self.event)
def tearDown(self):
self.testbed.deactivate()
def testEventWinner(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc254', self.event)
self.assertDictEqual(status, self.status_254)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc254', status),
'Team 254 had an average score of <b>200.4</b> in quals and <b>won the event</b> with a playoff average of <b>224.1</b>.')
def testElimSemisAndFirstPick(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc846', self.event)
self.assertDictEqual(status, self.status_846)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc846', status),
'Team 846 had an average score of <b>97.0</b> in quals and was <b>eliminated in the Semifinals</b> with a playoff average of <b>133.6</b>.')
def testTeamNotPicked(self):
status = EventTeamStatusHelper.generate_team_at_event_status('frc8', self.event)
self.assertDictEqual(status, self.status_8)
self.assertEqual(
EventTeamStatusHelper.generate_team_at_event_status_string('frc8', status),
'Team 8 had an average score of <b>42.6</b> in quals.')
| mit |
AaronZhangL/neo4j-search-characters | community/browser/app/components/angular-ui-codemirror/README.md | 4505 | # UI.Codemirror directive [](https://travis-ci.org/angular-ui/ui-codemirror)
This directive allows you to add [CodeMirror](http://codemirror.net/) to your textarea elements.
## Requirements
- AngularJS
- [CodeMirror 3.19.x](https://github.com/marijnh/CodeMirror)
## Usage
You can get it from [Bower](http://bower.io/)
```sh
bower install angular-ui-codemirror
```
This will copy the UI.Codemirror files into a `bower_components` folder, along with its dependencies. Load the script files in your application:
```html
<link rel="stylesheet" type="text/css" href="bower_components/codemirror/lib/codemirror.css">
<script type="text/javascript" src="bower_components/codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-codemirror/ui-codemirror.js"></script>
```
Add the UI.Codemirror module as a dependency to your application module:
```javascript
var myAppModule = angular.module('MyApp', ['ui.codemirror']);
```
Finally, add the directive to your html,
as attribute :
```html
<textarea ui-codemirror></textarea>
// or
<div ui-codemirror></div>
```
as element :
```xml
<ui-codemirror></ui-codemirror>
```
## Options
All the [Codemirror configuration options](http://codemirror.net/doc/manual.html#config) can be passed through the directive.
```javascript
myAppModule.controller('MyController', [ '$scope', function($scope) {
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
readOnly: 'nocursor',
mode: 'xml',
};
}]);
```
If you update this variable with the new values, they will be merged and the ui will be updated.
```xml
<textarea ui-codemirror="editorOptions" ng-model="x"></textarea>
// or
<ui-codemirror ui-codemirror-opts="editorOptions"></ui-codemirror>
```
### Working with ng-model
The ui-codemirror directive plays nicely with ng-model.
The ng-model will be watched for to set the CodeMirror document value (by [setValue](http://codemirror.net/doc/manual.html#setValue)).
_The ui-codemirror directive stores and expects the model value to be a standard javascript String._
### ui-refresh directive
If you apply the refresh directive to element then any change to do this scope value will result to a [refresh of the CodeMirror instance](http://codemirror.net/doc/manual.html#refresh).
_The ui-refresh directive expects a scope variable that can be any thing...._
```html
<textarea ui-codemirror ng-model="x" ui-refresh='isSomething'></textarea>
```
Now you can set the _isSomething_ in the controller scope.
```javascript
$scope.isSomething = true;
```
Note: the comparison operator between the old and the new value is "!=="
### CodeMirror instance direct access
For more interaction with the CodeMirror instance in the directive, we provide a direct access to it.
Using
```html
<div ui-codemirror="{ onLoad : codemirrorLoaded }" ></div>
```
the `$scope.codemirrorLoaded` function will be called with the [CodeMirror editor instance](http://codemirror.net/doc/manual.html#CodeMirror) as first argument
```javascript
myAppModule.controller('MyController', [ '$scope', function($scope) {
$scope.codemirrorLoaded = function(_editor){
// Editor part
var _doc = _editor.getDoc();
_editor.focus();
// Options
_editor.setOption('firstLineNumber', 10);
_doc.markClean()
// Events
_editor.on("beforeChange", function(){ ... });
_editor.on("change", function(){ ... });
};
}]);
```
## Testing
We use Karma and jshint to ensure the quality of the code. The easiest way to run these checks is to use grunt:
```sh
npm install -g grunt-cli
npm install && bower install
grunt
```
The karma task will try to open Firefox and Chrome as browser in which to run the tests. Make sure this is available or change the configuration in `test\karma.conf.js`
### Grunt Serve
We have one task to serve them all !
```sh
grunt serve
```
It's equal to run separately:
* `grunt connect:server` : giving you a development server at [http://localhost:8000/](http://localhost:8000/).
* `grunt karma:server` : giving you a Karma server to run tests (at [http://localhost:9876/](http://localhost:9876/) by default). You can force a test on this server with `grunt karma:unit:run`.
* `grunt watch` : will automatically test your code and build your demo. You can demo generation with `grunt build-doc`.
| mit |
tracer99/canjs | view/import/import_test.js | 49 | require('can-view-import/can-view-import_test');
| mit |
yinchunlong/abelkhan-1 | ext/c++/thirdpart/c++/boost/doc/html/boost/hash_long_doub_idp86761312.html | 5445 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct hash<long double></title>
<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../hash/reference.html#header.boost.functional.hash_hpp" title="Header <boost/functional/hash.hpp>">
<link rel="prev" href="hash_double_idp86754624.html" title="Struct hash<double>">
<link rel="next" href="hash_std_strin_idp37837952.html" title="Struct hash<std::string>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td>
<td align="center"><a href="../../../index.html">Home</a></td>
<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="hash_double_idp86754624.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../hash/reference.html#header.boost.functional.hash_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="hash_std_strin_idp37837952.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.hash_long_doub_idp86761312"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct hash<long double></span></h2>
<p>boost::hash<long double></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../hash/reference.html#header.boost.functional.hash_hpp" title="Header <boost/functional/hash.hpp>">boost/functional/hash.hpp</a>>
</span>
<span class="keyword">struct</span> <a class="link" href="hash_long_doub_idp86761312.html" title="Struct hash<long double>">hash</a><span class="special"><</span><span class="keyword">long</span> <span class="keyword">double</span><span class="special">></span> <span class="special">{</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="hash_long_doub_idp86761312.html#idp86763056-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="keyword">long</span> <span class="keyword">double</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp198141216"></a><h2>Description</h2>
<pre class="literallayout"><span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a name="idp86763056-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="keyword">long</span> <span class="keyword">double</span> val<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<div class="variablelist"><table border="0">
<col align="left" valign="top">
<tbody>
<tr>
<td><p><span class="term">Returns:</span></p></td>
<td>
<p>Unspecified in TR1, except that equal arguments yield the same result.</p>
<p><a class="link" href="../hash/reference.html#boost.hash_value_idp64403648">hash_value</a>(val) in Boost.</p>
</td>
</tr>
<tr>
<td><p><span class="term">Throws:</span></p></td>
<td><p>Doesn't throw</p></td>
</tr>
</tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005-2008 Daniel
James<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="hash_double_idp86754624.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../hash/reference.html#header.boost.functional.hash_hpp"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="hash_std_strin_idp37837952.html"><img src="../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
beluchin/jmockit1 | main/src/mockit/internal/expectations/argumentMatching/EqualityMatcher.java | 1866 | /*
* Copyright (c) 2006-2015 Rogério Liesenfeld
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.internal.expectations.argumentMatching;
import java.lang.reflect.Array;
import javax.annotation.*;
public class EqualityMatcher implements ArgumentMatcher<EqualityMatcher>
{
@Nullable final Object object;
EqualityMatcher(@Nullable Object equalArg) { object = equalArg; }
@Override
public boolean same(@Nonnull EqualityMatcher other) { return object == other.object; }
@Override
public boolean matches(@Nullable Object argValue) { return areEqual(argValue, object); }
@Override
public void writeMismatchPhrase(@Nonnull ArgumentMismatch argumentMismatch)
{
argumentMismatch.appendFormatted(object);
}
public static boolean areEqual(@Nullable Object o1, @Nullable Object o2)
{
if (o1 == null) {
return o2 == null;
}
else if (o2 == null) {
return false;
}
else if (o1 == o2) {
return true;
}
return areEqualWhenNonNull(o1, o2);
}
public static boolean areEqualWhenNonNull(@Nonnull Object o1, @Nonnull Object o2)
{
if (isArray(o1)) {
return isArray(o2) && areArraysEqual(o1, o2);
}
return o1.equals(o2);
}
private static boolean isArray(@Nonnull Object o) { return o.getClass().isArray(); }
private static boolean areArraysEqual(@Nonnull Object array1, @Nonnull Object array2)
{
int length1 = Array.getLength(array1);
if (length1 != Array.getLength(array2)) {
return false;
}
for (int i = 0; i < length1; i++) {
Object value1 = Array.get(array1, i);
Object value2 = Array.get(array2, i);
if (!areEqual(value1, value2)) {
return false;
}
}
return true;
}
}
| mit |
yaelduckwen/libriastore | joomla/administrator/components/com_widgetkit/src/Framework/src/Database/DatabaseInterface.php | 2712 | <?php
namespace YOOtheme\Widgetkit\Framework\Database;
interface DatabaseInterface
{
/**
* Fetches all rows of the result as an associative array.
*
* @param string $statement
* @param array $params
* @return array
*/
public function fetchAll($statement, array $params = array());
/**
* Fetches the first row of the result as an associative array.
*
* @param string $statement
* @param array $params
* @return array
*/
public function fetchAssoc($statement, array $params = array());
/**
* Fetches the first row of the result as a numerically indexed array.
*
* @param string $statement
* @param array $params
* @return array
*/
public function fetchArray($statement, array $params = array());
/**
* Prepares and executes an SQL query and returns the first row of the result as an object.
*
* @param string $statement
* @param array $params
* @param string $class
* @param array $args
* @return mixed
*/
public function fetchObject($statement, array $params = array(), $class = 'stdClass', $args = array());
/**
* Prepares and executes an SQL query and returns the result as an array of objects.
*
* @param string $statement
* @param array $params
* @param string $class
* @param array $args
* @return array
*/
public function fetchAllObjects($statement, array $params = array(), $class = 'stdClass', $args = array());
/**
* Executes an, optionally parametrized, SQL query.
*
* @param string $query
* @param array $params
*
* @return int|false
*/
public function executeQuery($query, array $params = array());
/**
* Inserts a table row with specified data.
*
* @param string $table
* @param array $data
* @return int
*/
public function insert($table, array $data);
/**
* Updates a table row with specified data.
*
* @param string $table
* @param array $data
* @param array $identifier
* @return int
*/
public function update($table, array $data, array $identifier);
/**
* Deletes a table row.
*
* @param string $table
* @param array $identifier
* @return int
*/
public function delete($table, array $identifier);
/**
* Escapes a string for usage in an SQL statement.
*
* @param string $text
* @return string
*/
public function escape($text);
/**
* Retrieves the last inserted id.
*
* @return int
*/
public function lastInsertId();
}
| mit |
georgiy-abbasov/testcafe-hammerhead | src/client/sandbox/upload/info-manager.js | 7469 | import COMMAND from '../../../session/command';
import FileListWrapper from './file-list-wrapper';
import nativeMethods from '../native-methods';
import transport from '../../transport';
import settings from '../../settings';
import * as Browser from '../../utils/browser';
import * as HiddenInfo from './hidden-info';
import SHADOW_UI_CLASSNAME from '../../../shadow-ui/class-name';
import Promise from 'pinkie';
// NOTE: https://html.spec.whatwg.org/multipage/forms.html#fakepath-srsly.
const FAKE_PATH_STRING = 'C:\\fakepath\\';
const UPLOAD_IFRAME_FOR_IE9_ID = 'uploadIframeForIE9' + SHADOW_UI_CLASSNAME.postfix;
export default class UploadInfoManager {
constructor (shadowUI) {
this.shadowUI = shadowUI;
this.uploadInfo = [];
}
static _getFileListData (fileList) {
var data = [];
for (var i = 0; i < fileList.length; i++)
data.push(fileList[i].base64);
return data;
}
static _getUploadIframeForIE9 () {
var uploadIframe = nativeMethods.querySelector.call(document, '#' + UPLOAD_IFRAME_FOR_IE9_ID);
if (!uploadIframe) {
uploadIframe = nativeMethods.createElement.call(document, 'iframe');
nativeMethods.setAttribute.call(uploadIframe, 'id', UPLOAD_IFRAME_FOR_IE9_ID);
nativeMethods.setAttribute.call(uploadIframe, 'name', UPLOAD_IFRAME_FOR_IE9_ID);
uploadIframe.style.display = 'none';
nativeMethods.appendChild.call(this.shadowUI.getRoot(), uploadIframe);
}
return uploadIframe;
}
_loadFileListDataForIE9 (input) {
return Promise(resolve => {
var form = input.form;
if (form && input.value) {
var sourceTarget = form.target;
var sourceActionString = form.action;
var sourceMethod = form.method;
var uploadIframe = UploadInfoManager._getUploadIframeForIE9();
var loadHandler = () => {
var fileListWrapper = new FileListWrapper([JSON.parse(uploadIframe.contentWindow.document.body.innerHTML)]);
uploadIframe.removeEventListener('load', loadHandler);
resolve(fileListWrapper);
};
uploadIframe.addEventListener('load', loadHandler);
form.action = settings.get().ie9FileReaderShimUrl + '?input-name=' + input.name + '&filename=' +
input.value;
form.target = UPLOAD_IFRAME_FOR_IE9_ID;
form.method = 'post';
nativeMethods.formSubmit.call(form);
form.action = sourceActionString;
form.target = sourceTarget;
form.method = sourceMethod;
}
else
resolve(new FileListWrapper([]));
});
}
static formatValue (fileNames) {
var value = '';
fileNames = typeof fileNames === 'string' ? [fileNames] : fileNames;
if (fileNames && fileNames.length) {
if (Browser.isWebKit)
value = FAKE_PATH_STRING + fileNames[0].split('/').pop();
else if (Browser.isIE9 || Browser.isIE10) {
var filePaths = [];
for (var i = 0; i < fileNames.length; i++)
filePaths.push(FAKE_PATH_STRING + fileNames[i].split('/').pop());
value = filePaths.join(', ');
}
else
return fileNames[0].split('/').pop();
}
return value;
}
static getFileNames (fileList, value) {
var result = [];
if (fileList) {
for (var i = 0; i < fileList.length; i++)
result.push(fileList[i].name);
}
else if (value.lastIndexOf('\\') !== -1)
result.push(value.substr(value.lastIndexOf('\\') + 1));
return result;
}
static loadFilesInfoFromServer (filePaths) {
return transport.asyncServiceMsg({
cmd: COMMAND.getUploadedFiles,
filePaths: typeof filePaths === 'string' ? [filePaths] : filePaths
});
}
static prepareFileListWrapper (filesInfo) {
var errs = [];
var validFilesInfo = [];
for (var i = 0; i < filesInfo.length; i++) {
if (filesInfo[i].err)
errs.push(filesInfo[i]);
else
validFilesInfo.push(filesInfo[i]);
}
return {
errs: errs,
fileList: new FileListWrapper(validFilesInfo)
};
}
static sendFilesInfoToServer (fileList, fileNames) {
return transport.asyncServiceMsg({
cmd: COMMAND.uploadFiles,
data: UploadInfoManager._getFileListData(fileList),
fileNames: fileNames
});
}
clearUploadInfo (input) {
var inputInfo = this.getUploadInfo(input);
if (inputInfo) {
inputInfo.files = new FileListWrapper([]);
inputInfo.value = '';
return HiddenInfo.removeInputInfo(input);
}
return null;
}
getFiles (input) {
var inputInfo = this.getUploadInfo(input);
return inputInfo ? inputInfo.files : new FileListWrapper([]);
}
getUploadInfo (input) {
for (var i = 0; i < this.uploadInfo.length; i++) {
if (this.uploadInfo[i].input === input)
return this.uploadInfo[i];
}
return null;
}
getValue (input) {
var inputInfo = this.getUploadInfo(input);
return inputInfo ? inputInfo.value : '';
}
loadFileListData (input, fileList) {
/*eslint-disable no-else-return */
if (Browser.isIE9)
return this._loadFileListDataForIE9(input);
else if (!fileList.length)
return Promise.resolve(new FileListWrapper([]));
else {
return new Promise(resolve => {
var index = 0;
var fileReader = new FileReader();
var file = fileList[index];
var readedFiles = [];
fileReader.addEventListener('load', e => {
readedFiles.push({
data: e.target.result.substr(e.target.result.indexOf(',') + 1),
blob: file.slice(0, file.size),
info: {
type: file.type,
name: file.name,
lastModifiedDate: file.lastModifiedDate
}
});
if (fileList[++index]) {
file = fileList[index];
fileReader.readAsDataURL(file);
}
else
resolve(new FileListWrapper(readedFiles));
});
fileReader.readAsDataURL(file);
});
}
/*eslint-enable no-else-return */
}
setUploadInfo (input, fileList, value) {
var inputInfo = this.getUploadInfo(input);
if (!inputInfo) {
inputInfo = { input: input };
this.uploadInfo.push(inputInfo);
}
inputInfo.files = fileList;
inputInfo.value = value;
HiddenInfo.addInputInfo(input, fileList, value);
}
}
| mit |
akatrevorjay/pyrox | pyrox/stock_filters/empty.py | 88 | import pyrox.filtering as filtering
class EmptyFilter(filtering.HttpFilter):
pass
| mit |
wonkishtofu/Tesseract-OCR-Tessa | tessa/orbiturary/pictures/get_text.py | 380 | import subprocess
import os
li = [i for i in os.walk(os.getcwd())]
print(li)
for di in li:
root = di[0]
for fi in di[2]:
lent = len(fi)
if fi[lent-4:lent] == ".jpg":
fi_path = os.path.join(root, fi)
output_file = fi[:lent-4] + "_output"
print(output_file)
subprocess.call(["tesseract", fi, output_file])
| mit |
thecountofzero/canjs | view/node_lists/test.html | 737 | <html>
<head>
<link rel="stylesheet" type="text/css" href="../../bower_components/qunit/qunit/qunit.css"/>
<title>can/view/mustache/live/node_list/test</title>
</head>
<body>
<h1 id="qunit-header">can.view.live.nodeList Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-test-area"></div>
<script type="text/javascript" src="../../bower_components/qunit/qunit/qunit.js"></script>
<script type="text/javascript" src="../../lib/steal/steal.js"></script>
<script type="text/javascript">
QUnit.config.autostart = false;
steal("can/view/node_lists/node_lists_test.js", function() {
QUnit.start();
});
</script>
</body>
</html> | mit |
david415/go-ipfs | Godeps/_workspace/src/github.com/chuckpreslar/inflect/languages/english.go | 1943 | // Package languages provides language rules to use with the inflect package.
package languages
import (
"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/chuckpreslar/inflect/types"
)
// Defines irregular words, uncountables words, and pluralization/singularization rules for the English language.
//
// FIXME: Singular/Plural rules could be better, I went to school for engineering, not English.
var English = types.Language("en").
// Pluralization rules.
Plural(`(auto)$`, `${1}s`).
Plural(`(s|ss|sh|ch|x|to|ro|ho|jo)$`, `${1}es`).
Plural(`(i)fe$`, `${1}ves`).
Plural(`(t|f|g)oo(th|se|t)$`, `${1}ee${2}`).
Plural(`(a|e|i|o|u)y$`, `${1}ys`).
Plural(`(m|l)ouse$`, `${1}ice`).
Plural(`(al|ie|l)f$`, `${1}ves`).
Plural(`(d)ice`, `${1}ie`).
Plural(`y$`, `ies`).
Plural(`$`, `s`).
// Singularization rules.
Singular(`(auto)s$`, `${1}`).
Singular(`(rse)s$`, `${1}`).
Singular(`(s|ss|sh|ch|x|to|ro|ho|jo)es$`, `${1}`).
Singular(`(i)ves$`, `${1}fe`).
Singular(`(t|f|g)ee(th|se|t)$`, `${1}oo${2}`).
Singular(`(a|e|i|o|u)ys$`, `${1}y`).
Singular(`(m|l)ice$`, `${1}ouse`).
Singular(`(al|ie|l)ves$`, `${1}f`).
Singular(`(l)ies`, `${1}ie`).
Singular(`ies$`, `y`).
Singular(`(d)ie`, `${1}ice`).
Singular(`s$`, ``).
// Irregulars words.
Irregular(`person`, `people`).
Irregular(`child`, `children`).
// Uncountables words.
Uncountable(`fish`).
Uncountable(`sheep`).
Uncountable(`deer`).
Uncountable(`tuna`).
Uncountable(`salmon`).
Uncountable(`trout`).
Uncountable(`music`).
Uncountable(`art`).
Uncountable(`love`).
Uncountable(`happiness`).
Uncountable(`advice`).
Uncountable(`information`).
Uncountable(`news`).
Uncountable(`furniture`).
Uncountable(`luggage`).
Uncountable(`rice`).
Uncountable(`sugar`).
Uncountable(`butter`).
Uncountable(`water`).
Uncountable(`electricity`).
Uncountable(`gas`).
Uncountable(`power`).
Uncountable(`money`).
Uncountable(`currency`).
Uncountable(`scenery`)
| mit |
eileencodes/sprockets | test/test_performance.rb | 14649 | # frozen_string_literal: true
require 'sprockets_test'
$file_stat_calls = nil
class << File
alias_method :original_stat, :stat
def stat(filename)
if $file_stat_calls
$file_stat_calls[filename.to_s] ||= []
$file_stat_calls[filename.to_s] << caller
end
original_stat(filename)
end
end
$dir_entires_calls = nil
class << Dir
alias_method :original_entries, :entries
def entries(dirname, **args)
if $dir_entires_calls
$dir_entires_calls[dirname.to_s] ||= []
$dir_entires_calls[dirname.to_s] << caller
end
original_entries(dirname, **args)
end
end
class TestPerformance < Sprockets::TestCase
class Cache
def initialize
@cache = {}
end
def get(key)
$cache_get_calls[key] ||= []
$cache_get_calls[key] << caller
@cache[key]
end
def set(key, value)
$cache_set_calls[key] ||= []
$cache_set_calls[key] << caller
@cache[key] = value
end
end
def setup
@env = new_environment
reset_stats!
end
def teardown
$file_stat_calls = nil
$dir_entires_calls = nil
$processor_calls = nil
$bundle_processor_calls = nil
$cache_get_calls = nil
$cache_set_calls = nil
end
test "simple file" do
@env["gallery.js"].to_s
assert_no_redundant_stat_calls
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
end
test "cached simple file" do
@env.cached["gallery.js"].to_s
assert_no_redundant_stat_calls
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
end
test "file with deps" do
@env["mobile.js"].to_s
assert_no_redundant_stat_calls
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
end
test "cached file with deps" do
@env.cached["mobile.js"].to_s
assert_no_redundant_stat_calls
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
end
test "loading from backend cache" do
env1, env2 = new_environment, new_environment
cache = Cache.new
env1.cache = cache
env2.cache = cache
env1["mobile.js"]
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env2["mobile.js"]
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
test "moving root of project after generation is still freaky fast" do
env1 = new_environment
env1.cache = Cache.new
env1["mobile.js"]
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
Dir.mktmpdir do |dir|
Dir.chdir(dir) do
`cp -R #{File.join(fixture_path("default"), "*")} .`
env2 = new_environment("./default")
env2.cache = env1.cache
reset_stats!
env2["mobile.js"]
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
end
end
test "loading from instance cache" do
env = @env.cached
env["mobile.js"]
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
reset_stats!
env["mobile.js"]
assert_no_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
end
test "loading from cached with backend cache" do
env1, env2 = new_environment, new_environment
cache = Cache.new
env1.cache = cache
env2.cache = cache
env1.cached["mobile.js"]
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env2.cached["mobile.js"]
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
test "rollback version" do
env = new_environment
env.cache = Cache.new
env.version = "1"
assert asset = env["mobile.js"]
id1 = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env.version = "2"
assert asset = env["mobile.js"]
id2 = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env.version = "1"
assert asset = env["mobile.js"]
assert_equal id1, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
reset_stats!
env.version = "2"
assert asset = env["mobile.js"]
assert_equal id2, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
test "rollback path change" do
env = new_environment
env.cache = Cache.new
env.clear_paths
env.append_path(fixture_path('default'))
assert asset = env["mobile.js"]
path1 = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env.clear_paths
env.append_path(fixture_path('asset'))
env.append_path(fixture_path('default'))
assert asset = env["mobile.js"]
path2 = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
reset_stats!
env.clear_paths
env.append_path(fixture_path('default'))
assert asset = env["mobile.js"]
assert_equal path1, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
reset_stats!
env.clear_paths
env.append_path(fixture_path('asset'))
env.append_path(fixture_path('default'))
assert asset = env["mobile.js"]
assert_equal path2, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
test "rollback file change" do
env = new_environment
env.cache = Cache.new
filename = fixture_path("default/tmp.js")
sandbox filename do
write(filename, "a;", 1421000000)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\n", asset.source
ida = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
write(filename, "b;", 1421000001)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "b;\n", asset.source
idb = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
write(filename, "a;", 1421000000)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\n", asset.source
assert_equal ida, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
write(filename, "b;", 1421000001)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "b;\n", asset.source
assert_equal idb, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
end
test "rollback file dependency change" do
env = new_environment
env.cache = Cache.new
main = fixture_path("default/tmp-main.js")
dep = fixture_path("default/tmp-dep.js")
sandbox main, dep do
write(main, "//= require ./tmp-dep", 1421000000)
write(dep, "a;", 1421000000)
reset_stats!
assert asset = env["tmp-main.js"]
assert_equal "a;\n", asset.source
ida = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
write(dep, "b;", 1421000001)
reset_stats!
assert asset = env["tmp-main.js"]
assert_equal "b;\n", asset.source
idb = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
write(dep, "a;", 1421000000)
reset_stats!
assert asset = env["tmp-main.js"]
assert_equal "a;\n", asset.source
assert_equal ida, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
write(dep, "b;", 1421000001)
reset_stats!
assert asset = env["tmp-main.js"]
assert_equal "b;\n", asset.source
assert_equal idb, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_cache_set_calls
end
end
test "rollback file dependency add/remove" do
env = new_environment
env.cache = Cache.new
main = fixture_path("default/tmp.js")
deps = fixture_path("default/tmp")
depa = fixture_path("default/tmp/a.js")
depb = fixture_path("default/tmp/b.js")
sandbox main, deps, depa, depb do
FileUtils.mkdir_p(deps)
write(main, "//= require_directory ./tmp", 1421000000)
write(depa, "a;", 1421000000)
File.utime(1421000000, 1421000000, deps)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\n", asset.source
ida = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
write(depb, "b;", 142100001)
File.utime(1421000001, 1421000001, deps)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\nb;\n", asset.source
idab = asset.id
assert_no_redundant_processor_calls
assert_no_redundant_bundle_processor_calls
assert_no_redundant_cache_set_calls
FileUtils.rm(depb)
File.utime(1421000000, 1421000000, deps)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\n", asset.source
assert_equal ida, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_redundant_cache_set_calls
write(depb, "b;", 142100001)
File.utime(1421000001, 1421000001, deps)
reset_stats!
assert asset = env["tmp.js"]
assert_equal "a;\nb;\n", asset.source
assert_equal idab, asset.id
assert_no_redundant_stat_calls
assert_no_processor_calls
assert_no_bundle_processor_calls
assert_no_redundant_cache_get_calls
assert_no_redundant_cache_set_calls
end
end
def new_environment(path = fixture_path('default'))
Sprockets::Environment.new(".") do |env|
env.cache = Cache.new
env.append_path(path)
env.register_preprocessor 'application/javascript', proc { |input|
$processor_calls[input[:filename]] ||= []
$processor_calls[input[:filename]] << caller
nil
}
env.register_bundle_processor 'application/javascript', proc { |input|
$bundle_processor_calls[input[:filename]] ||= []
$bundle_processor_calls[input[:filename]] << caller
nil
}
end
end
def reset_stats!
$file_stat_calls = {}
$dir_entires_calls = {}
$processor_calls = {}
$bundle_processor_calls = {}
$cache_get_calls = {}
$cache_set_calls = {}
end
def assert_no_stat_calls
$file_stat_calls.each do |path, callers|
assert_equal 0, callers.size, "File.stat(#{path.inspect}) called #{callers.size} times\n\n#{format_callers(callers)}"
end
$dir_entires_calls.each do |path, callers|
assert_equal 0, callers.size, "Dir.entries(#{path.inspect}) called #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_redundant_stat_calls
$file_stat_calls.each do |path, callers|
assert_equal 1, callers.size, "File.stat(#{path.inspect}) called #{callers.size} times\n\n#{format_callers(callers)}"
end
$dir_entires_calls.each do |path, callers|
assert_equal 1, callers.size, "Dir.entries(#{path.inspect}) called #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_processor_calls
$processor_calls.each do |path, callers|
assert_equal 0, callers.size, "Processor ran on #{path.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_redundant_processor_calls
$processor_calls.each do |path, callers|
assert_equal 1, callers.size, "Processor ran on #{path.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_bundle_processor_calls
$bundle_processor_calls.each do |path, callers|
assert_equal 0, callers.size, "Bundle Processor ran on #{path.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_redundant_bundle_processor_calls
$bundle_processor_calls.each do |path, callers|
assert_equal 1, callers.size, "Bundle Processor ran on #{path.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_redundant_cache_get_calls
$cache_get_calls.each do |key, callers|
assert_equal 1, callers.size, "cache get #{key.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_cache_set_calls
$cache_set_calls.each do |key, callers|
assert_equal 0, callers.size, "cache set #{key.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def assert_no_redundant_cache_set_calls
$cache_set_calls.each do |key, callers|
assert_equal 1, callers.size, "cache set #{key.inspect} #{callers.size} times\n\n#{format_callers(callers)}"
end
end
def format_callers(callers)
callers.map { |c| c.join("\n") }.join("\n\n\n")
end
end
| mit |
driftyco/ionic | core/src/utils/animation/test/hooks/e2e.ts | 5554 | import { newE2EPage } from '@stencil/core/testing';
import { listenForEvent, waitForFunctionTestContext } from '../../../test/utils';
test(`animation:web: hooks`, async () => {
const page = await newE2EPage({ url: '/src/utils/animation/test/hooks' });
const screenshotCompares = [];
screenshotCompares.push(await page.compareScreenshot());
const square = await page.$('.square-a');
const styles = await getStyles(page, '.square-a');
expect(styles.paddingBottom).toEqual('20px');
expect(styles.color).toEqual('rgb(0, 0, 0)');
const classList = await getClassList(square);
expect(classList.includes('hello-world')).toEqual(true);
expect(classList.includes('test-class')).toEqual(false);
await waitForEventToBeCalled('afterWrite', page, square, async () => {
await waitForEventToBeCalled('afterRead', page, square, async () => {
await waitForEventToBeCalled('ionAnimationFinished', page, square, async () => {
await waitForEventToBeCalled('beforeWrite', page, square, async () => {
await waitForEventToBeCalled('beforeRead', page, square, async () => {
await page.click('.play');
await page.waitForSelector('.play');
// Test beforeRemoveClass and beforeAddClass
const webClassListAgain = await getClassList(square);
expect(webClassListAgain.includes('hello-world')).toEqual(false);
expect(webClassListAgain.includes('test-class')).toEqual(true);
// Test beforeStyles and beforeClearStyles
const webStylesAgain = await getStyles(page, '.square-a');
expect(webStylesAgain.paddingBottom).toEqual('0px');
expect(webStylesAgain.color).toEqual('rgb(128, 0, 128)');
});
});
});
});
});
// Test afterRemoveClass and afterAddClass
const classListAgain = await getClassList(square);
expect(classListAgain.includes('hello-world')).toEqual(true);
expect(classListAgain.includes('test-class')).toEqual(false);
// Test afterStyles and afterClearStyles
const stylesAgain = await getStyles(page, '.square-a');
expect(stylesAgain.paddingBottom).toEqual('20px');
expect(stylesAgain.color).toEqual('rgb(0, 0, 0)');
screenshotCompares.push(await page.compareScreenshot('end animation'));
});
test(`animation:css: hooks`, async () => {
const page = await newE2EPage({ url: '/src/utils/animation/test/hooks?ionic:_forceCSSAnimations=true' });
const screenshotCompares = [];
screenshotCompares.push(await page.compareScreenshot());
const square = await page.$('.square-a');
const styles = await getStyles(page, '.square-a');
expect(styles.paddingBottom).toEqual('20px');
expect(styles.color).toEqual('rgb(0, 0, 0)');
const classList = await getClassList(square);
expect(classList.includes('hello-world')).toEqual(true);
expect(classList.includes('test-class')).toEqual(false);
await waitForEventToBeCalled('afterWrite', page, square, async () => {
await waitForEventToBeCalled('afterRead', page, square, async () => {
await waitForEventToBeCalled('ionAnimationFinished', page, square, async () => {
await waitForEventToBeCalled('beforeWrite', page, square, async () => {
await waitForEventToBeCalled('beforeRead', page, square, async () => {
await page.click('.play');
await page.waitForSelector('.play');
// Test beforeRemoveClass and beforeAddClass
const cssClassListAgain = await getClassList(square);
expect(cssClassListAgain.includes('hello-world')).toEqual(false);
expect(cssClassListAgain.includes('test-class')).toEqual(true);
// Test beforeStyles and beforeClearStyles
const cssStylesAgain = await getStyles(page, '.square-a');
expect(cssStylesAgain.paddingBottom).toEqual('0px');
expect(cssStylesAgain.color).toEqual('rgb(128, 0, 128)');
});
});
});
});
});
// Test afterRemoveClass and afterAddClass
const classListAgain = await getClassList(square);
expect(classListAgain.includes('hello-world')).toEqual(true);
expect(classListAgain.includes('test-class')).toEqual(false);
// Test afterStyles and afterClearStyles
const stylesAgain = await getStyles(page, '.square-a');
expect(stylesAgain.paddingBottom).toEqual('20px');
expect(stylesAgain.color).toEqual('rgb(0, 0, 0)');
screenshotCompares.push(await page.compareScreenshot('end animation'));
});
const waitForEventToBeCalled = (eventName: string, page: any, el: HTMLElement, fn: any, num = 1) => {
return new Promise(async resolve => {
const EVENT_FIRED = `on${eventName}`;
const eventFiredCount: any = { count: 0 };
await page.exposeFunction(EVENT_FIRED, () => {
eventFiredCount.count += 1;
});
await listenForEvent(page, eventName, el, EVENT_FIRED);
if (fn) {
await fn();
}
await waitForFunctionTestContext((payload: any) => {
return payload.eventFiredCount.count === payload.num;
}, { eventFiredCount, num });
return resolve();
});
};
const getStyles = async (page: any, selector: string) => {
return page.evaluate((payload: any) => {
const el = document.querySelector(payload.selector);
return JSON.parse(JSON.stringify(getComputedStyle(el)));
}, { selector });
};
const getClassList = async (el: HTMLElement) => {
const classListObject = await el.getProperty('classList');
const jsonValue = await classListObject.jsonValue();
return Object.values(jsonValue);
};
| mit |
jrlarsen/GetProgramming | Ch12_Conditions/listing12.04.js | 829 | /* Get Programming with JavaScript
* Listing 12.04
* Guess the random number
*/
var getGuesser = function () {
var secret = Math.floor(Math.random() * 10 + 1);
return function (userNumber) {
if (userNumber === secret) {
return "Well done!";
} else {
return "Unlucky, try again.";
}
};
};
var guess = getGuesser();
/* Further Adventures
*
* 1) Run the program.
*
* 2) Play the game a few times on the console.
* e.g. guess(2)
*
* 3) Change the code so the secret number is
* between 30 and 50.
*
* 4) Test your changes.
*
* CHALLENGE: Create a function called 'between'
* that returns a random whole number between two
* numbers passed as arguments.
*
* e.g. between(1, 5) // 1 <= whole number <= 5
* between(100, 200) // 100 <= whole number <= 200
*
*/ | mit |
javalt/bootstrap | README.md | 6277 | # [Bootstrap](http://getbootstrap.com)
[](http://badge.fury.io/bo/bootstrap)
[](http://badge.fury.io/js/bootstrap)
[](https://travis-ci.org/twbs/bootstrap)
[](https://david-dm.org/twbs/bootstrap#info=devDependencies)
[](https://saucelabs.com/u/bootstrap)
Bootstrap is a sleek, intuitive, and powerful front-end framework for faster and easier web development, created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thornton](https://twitter.com/fat), and maintained by the [core team](https://github.com/orgs/twbs/people) with the massive support and involvement of the community.
To get started, check out <http://getbootstrap.com>!
## Table of contents
- [Quick start](#quick-start)
- [Bugs and feature requests](#bugs-and-feature-requests)
- [Documentation](#documentation)
- [Contributing](#contributing)
- [Community](#community)
- [Versioning](#versioning)
- [Creators](#creators)
- [Copyright and license](#copyright-and-license)
## Quick start
Four quick start options are available:
- [Download the latest release](https://github.com/twbs/bootstrap/archive/v3.3.1.zip).
- Clone the repo: `git clone https://github.com/twbs/bootstrap.git`.
- Install with [Bower](http://bower.io): `bower install bootstrap`.
- Install with [npm](https://www.npmjs.org): `npm install bootstrap`.
Read the [Getting started page](http://getbootstrap.com/getting-started/) for information on the framework contents, templates and examples, and more.
### What's included
Within the download you'll find the following directories and files, logically grouping common assets and providing both compiled and minified variations. You'll see something like this:
```
bootstrap/
├── css/
│ ├── bootstrap.css
│ ├── bootstrap.css.map
│ ├── bootstrap.min.css
│ ├── bootstrap-theme.css
│ ├── bootstrap-theme.css.map
│ └── bootstrap-theme.min.css
├── js/
│ ├── bootstrap.js
│ └── bootstrap.min.js
└── fonts/
├── glyphicons-halflings-regular.eot
├── glyphicons-halflings-regular.svg
├── glyphicons-halflings-regular.ttf
└── glyphicons-halflings-regular.woff
```
We provide compiled CSS and JS (`bootstrap.*`), as well as compiled and minified CSS and JS (`bootstrap.min.*`). CSS [source maps](https://developers.google.com/chrome-developer-tools/docs/css-preprocessors) (`bootstrap.*.map`) are available for use with certain browsers' developer tools. Fonts from Glyphicons are included, as is the optional Bootstrap theme.
## Bugs and feature requests
Have a bug or a feature request? Please first read the [issue guidelines](https://github.com/twbs/bootstrap/blob/master/CONTRIBUTING.md#using-the-issue-tracker) and search for existing and closed issues. If your problem or idea is not addressed yet, [please open a new issue](https://github.com/twbs/bootstrap/issues/new).
## Documentation
Bootstrap's documentation, included in this repo in the root directory, is built with [Jekyll](http://jekyllrb.com) and publicly hosted on GitHub Pages at <http://getbootstrap.com>. The docs may also be run locally.
### Running documentation locally
1. If necessary, [install Jekyll](http://jekyllrb.com/docs/installation) (requires v2.5.x).
- **Windows users:** Read [this unofficial guide](http://jekyll-windows.juthilo.com/) to get Jekyll up and running without problems.
2. Install the Ruby-based syntax highlighter, [Rouge](https://github.com/jneen/rouge), with `gem install rouge`.
3. From the root `/bootstrap` directory, run `jekyll serve` in the command line.
4. Open <http://localhost:9001> in your browser, and voilà.
Learn more about using Jekyll by reading its [documentation](http://jekyllrb.com/docs/home/).
### Documentation for previous releases
Documentation for v2.3.2 has been made available for the time being at <http://getbootstrap.com/2.3.2/> while folks transition to Bootstrap 3.
[Previous releases](https://github.com/twbs/bootstrap/releases) and their documentation are also available for download.
## Contributing
Please read through our [contributing guidelines](https://github.com/twbs/bootstrap/blob/master/CONTRIBUTING.md). Included are directions for opening issues, coding standards, and notes on development.
Moreover, if your pull request contains JavaScript patches or features, you must include relevant unit tests. All HTML and CSS should conform to the [Code Guide](https://github.com/mdo/code-guide), maintained by [Mark Otto](https://github.com/mdo).
Editor preferences are available in the [editor config](https://github.com/twbs/bootstrap/blob/master/.editorconfig) for easy use in common text editors. Read more and download plugins at <http://editorconfig.org>.
## Community
Keep track of development and community news.
- Follow [@twbootstrap on Twitter](https://twitter.com/twbootstrap).
- Read and subscribe to [The Official Bootstrap Blog](http://blog.getbootstrap.com).
- Chat with fellow Bootstrappers in IRC. On the `irc.freenode.net` server, in the `##bootstrap` channel.
- Implementation help may be found at Stack Overflow (tagged [`twitter-bootstrap-3`](http://stackoverflow.com/questions/tagged/twitter-bootstrap-3)).
## Versioning
For transparency into our release cycle and in striving to maintain backward compatibility, Bootstrap is maintained under [the Semantic Versioning guidelines](http://semver.org/). Sometimes we screw up, but we'll adhere to those rules whenever possible.
## Creators
**Mark Otto**
- <https://twitter.com/mdo>
- <https://github.com/mdo>
**Jacob Thornton**
- <https://twitter.com/fat>
- <https://github.com/fat>
## Copyright and license
Code and documentation copyright 2011-2014 Twitter, Inc. Code released under [the MIT license](https://github.com/twbs/bootstrap/blob/master/LICENSE). Docs released under [Creative Commons](https://github.com/twbs/bootstrap/blob/master/docs/LICENSE).
| mit |
gtoonstra/foc_esc | escsim/constants.py | 918 | import math
FREQ = 3000
V = 13.3
REALRPM = 305.6
LIMIT = 2
PWM_IN_MIN = 1100
PWM_IN_MAX = 2000
RPM_MAX = 2000.0 # rpm
RPM_MIN = 300.0 # rpm
# GT: Changed constants?
RPM_SLEW = 10000.0 # rpm/s
DT_LOOP = 0.001 # seconds per slow loop
KP_RPM_UP = 0.3 # mA/rpm
KI_RPM = 0.002 # mA/rpm/s
I_SAT_RPM = 20.0 # mA
KFF_I = 4.000e-5 # mA/rpm^2
# KFF_V = 0.00038 # (0-255)/rpm
KFF_V = 0.0 # (0-255)/rpm
AMAX = 20.0 # max accelerating current [A]
BMAX = 5.0 # max braking current [A]
# RPM controller
KP_EST_RPM = 2
KI_EST_RPM = 0.02
KPQ = 1.000 / 500.0 # [LSB/mA/loop] ~= [1V/A/s at 24VDC]
KPD = 0.3 / 500.0 # [LSB/mA/loop] ~= ??? calculate
CHAR_90_DEG = 64
LOOP_INTERVAL = 4
#iafactor = 0.03
#ibicfactor = 0.02
iafactor = 0.03
ibicfactor = 0.02
SQRT3DIV2 = 0.866025404
ONEDIVSQRT3 = 1.0/math.sqrt(3.0)
TWODIVSQRT3 = 2.0/math.sqrt(3.0)
BEMFK = 0.00537
| mit |
Lab603/PicEncyclopedias | jni-build/jni/include/tensorflow/python/ops/functional_ops.py | 23180 | # Copyright 2015 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.
# =============================================================================
"""Functional operations.
## Higher Order Operators
TensorFlow provides several higher order operators to simplify the common
map-reduce programming patterns.
@@map_fn
@@foldl
@@foldr
@@scan
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope as vs
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_functional_ops import *
# pylint: enable=wildcard-import
# pylint: disable=unused-import
from tensorflow.python.ops.gen_functional_ops import _symbolic_gradient
# pylint: enable=unused-import
from tensorflow.python.util import nest
# TODO(yuanbyu, mrry): Handle stride to support sliding windows.
def foldl(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
swap_memory=False, name=None):
"""foldl on the list of tensors unpacked from `elems` on dimension 0.
This foldl operator repeatedly applies the callable `fn` to a sequence
of elements from first to last. The elements are made of the tensors
unpacked from `elems` on dimension 0. The callable fn takes two tensors as
arguments. The first argument is the accumulated value computed from the
preceding invocation of fn. If `initializer` is None, `elems` must contain
at least one element, and its first element is used as the initializer.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
of the result tensor is fn(initializer, values[0]).shape`.
Args:
fn: The callable to be performed.
elems: A tensor to be unpacked on dimension 0.
initializer: (optional) The initial value for the accumulator.
parallel_iterations: (optional) The number of iterations allowed to run
in parallel.
back_prop: (optional) True enables support for back propagation.
swap_memory: (optional) True enables GPU-CPU memory swapping.
name: (optional) Name prefix for the returned tensors.
Returns:
A tensor resulting from applying `fn` consecutively to the list of tensors
unpacked from `elems`, from first to last.
Raises:
TypeError: if `fn` is not callable.
Example:
```python
elems = [1, 2, 3, 4, 5, 6]
sum = foldl(lambda a, x: a + x, elems)
# sum == 21
```
"""
if not callable(fn):
raise TypeError("fn must be callable.")
with ops.op_scope([elems], name, "foldl"):
# Any get_variable calls in fn will cache the first call locally
# and not issue repeated network I/O requests for each iteration.
varscope = vs.get_variable_scope()
varscope_caching_device_was_none = False
if varscope.caching_device is None:
# TODO(ebrevdo): Change to using colocate_with here and in other methods.
varscope.set_caching_device(lambda op: op.device)
varscope_caching_device_was_none = True
# Convert elems to tensor array.
elems = ops.convert_to_tensor(elems, name="elems")
n = array_ops.shape(elems)[0]
elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
dynamic_size=False,
infer_shape=True)
elems_ta = elems_ta.unpack(elems)
if initializer is None:
a = elems_ta.read(0)
i = constant_op.constant(1)
else:
a = ops.convert_to_tensor(initializer)
i = constant_op.constant(0)
def compute(i, a):
a = fn(a, elems_ta.read(i))
return [i + 1, a]
_, r_a = control_flow_ops.while_loop(
lambda i, a: i < n, compute, [i, a],
parallel_iterations=parallel_iterations,
back_prop=back_prop,
swap_memory=swap_memory)
if varscope_caching_device_was_none:
varscope.set_caching_device(None)
return r_a
def foldr(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
swap_memory=False, name=None):
"""foldr on the list of tensors unpacked from `elems` on dimension 0.
This foldr operator repeatedly applies the callable `fn` to a sequence
of elements from last to first. The elements are made of the tensors
unpacked from `elems`. The callable fn takes two tensors as arguments.
The first argument is the accumulated value computed from the preceding
invocation of fn. If `initializer` is None, `elems` must contain at least
one element, and its first element is used as the initializer.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
of the result tensor is `fn(initializer, values[0]).shape`.
Args:
fn: The callable to be performed.
elems: A tensor that is unpacked into a sequence of tensors to apply `fn`.
initializer: (optional) The initial value for the accumulator.
parallel_iterations: (optional) The number of iterations allowed to run
in parallel.
back_prop: (optional) True enables support for back propagation.
swap_memory: (optional) True enables GPU-CPU memory swapping.
name: (optional) Name prefix for the returned tensors.
Returns:
A tensor resulting from applying `fn` consecutively to the list of tensors
unpacked from `elems`, from last to first.
Raises:
TypeError: if `fn` is not callable.
Example:
```python
elems = [1, 2, 3, 4, 5, 6]
sum = foldr(lambda a, x: a + x, elems)
# sum == 21
```
"""
if not callable(fn):
raise TypeError("fn must be callable.")
with ops.op_scope([elems], name, "foldr"):
# Any get_variable calls in fn will cache the first call locally
# and not issue repeated network I/O requests for each iteration.
varscope = vs.get_variable_scope()
varscope_caching_device_was_none = False
if varscope.caching_device is None:
# TODO(ebrevdo): Change to using colocate_with here and in other methods.
varscope.set_caching_device(lambda op: op.device)
varscope_caching_device_was_none = True
# Convert elems to tensor array.
elems = ops.convert_to_tensor(elems, name="elems")
n = array_ops.shape(elems)[0]
elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
dynamic_size=False,
infer_shape=True)
elems_ta = elems_ta.unpack(elems)
if initializer is None:
i = n - 1
a = elems_ta.read(i)
else:
i = n
a = ops.convert_to_tensor(initializer)
def compute(i, a):
i -= 1
a = fn(a, elems_ta.read(i))
return [i, a]
_, r_a = control_flow_ops.while_loop(
lambda i, a: i > 0, compute, [i, a],
parallel_iterations=parallel_iterations,
back_prop=back_prop,
swap_memory=swap_memory)
if varscope_caching_device_was_none:
varscope.set_caching_device(None)
return r_a
def map_fn(fn, elems, dtype=None, parallel_iterations=10, back_prop=True,
swap_memory=False, infer_shape=True, name=None):
"""map on the list of tensors unpacked from `elems` on dimension 0.
The simplest version of `map` repeatedly applies the callable `fn` to a
sequence of elements from first to last. The elements are made of the
tensors unpacked from `elems`. `dtype` is the data type of the return
value of `fn`. Users must provide `dtype` if it is different from
the data type of `elems`.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
of the result tensor is `[values.shape[0]] + fn(values[0]).shape`.
This method also allows multi-arity `elems` and output of `fn`. If `elems`
is a (possibly nested) list or tuple of tensors, then each of these tensors
must have a matching first (unpack) dimension. The signature of `fn` may
match the structure of `elems`. That is, if `elems` is
`(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is:
`fn = lambda (t1, [t2, t3, [t4, t5]]):`.
Furthermore, `fn` may emit a different structure than its input. For example,
`fn` may look like: `fn = lambda t1: return (t1 + 1, t1 - 1)`. In this case,
the `dtype` parameter is not optional: `dtype` must be a type or (possibly
nested) tuple of types matching the output of `fn`.
Args:
fn: The callable to be performed. It accepts one argument, which will
have the same (possibly nested) structure as `elems`. Its output
must have the same structure as `dtype` if one is provided, otherwise
it must have the same structure as `elems`.
elems: A tensor or (possibly nested) sequence of tensors, each of which
will be unpacked along their first dimension. The nested sequence
of the resulting slices will be applied to `fn`.
dtype: (optional) The output type(s) of `fn`. If `fn` returns a structure
of Tensors differing from the structure of `elems`, then `dtype` is not
optional and must have the same structure as the output of `fn`.
parallel_iterations: (optional) The number of iterations allowed to run
in parallel.
back_prop: (optional) True enables support for back propagation.
swap_memory: (optional) True enables GPU-CPU memory swapping.
infer_shape: (optional) False disables tests for consistent output shapes.
name: (optional) Name prefix for the returned tensors.
Returns:
A tensor or (possibly nested) sequence of tensors. Each tensor packs the
results of applying `fn` to tensors unpacked from `elems` along the first
dimension, from first to last.
Raises:
TypeError: if `fn` is not callable or the structure of the output of
`fn` and `dtype` do not match.
ValueError: if the lengths of the output of `fn` and `dtype` do not match.
Examples:
```python
elems = np.array([1, 2, 3, 4, 5, 6])
squares = map_fn(lambda x: x * x, elems)
# squares == [1, 4, 9, 16, 25, 36]
```
```python
elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
# alternate == [-1, 2, -3]
```
```python
elems = np.array([1, 2, 3])
alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
# alternates[0] == [1, 2, 3]
# alternates[1] == [-1, -2, -3]
```
"""
if not callable(fn):
raise TypeError("fn must be callable.")
input_is_sequence = nest.is_sequence(elems)
input_flatten = lambda x: nest.flatten(x) if input_is_sequence else [x]
def input_pack(x):
return nest.pack_sequence_as(elems, x) if input_is_sequence else x[0]
if dtype is None:
output_is_sequence = input_is_sequence
output_flatten = input_flatten
output_pack = input_pack
else:
output_is_sequence = nest.is_sequence(dtype)
output_flatten = lambda x: nest.flatten(x) if output_is_sequence else [x]
def output_pack(x):
return (nest.pack_sequence_as(dtype, x)
if output_is_sequence else x[0])
elems_flat = input_flatten(elems)
with ops.op_scope(elems_flat, name, "map"):
# Any get_variable calls in fn will cache the first call locally
# and not issue repeated network I/O requests for each iteration.
varscope = vs.get_variable_scope()
varscope_caching_device_was_none = False
if varscope.caching_device is None:
# TODO(ebrevdo): Change to using colocate_with here and in other methods.
varscope.set_caching_device(lambda op: op.device)
varscope_caching_device_was_none = True
elems_flat = [
ops.convert_to_tensor(elem, name="elem") for elem in elems_flat]
dtype = dtype or input_pack([elem.dtype for elem in elems_flat])
dtype_flat = output_flatten(dtype)
# Convert elems to tensor array.
n = array_ops.shape(elems_flat[0])[0]
# TensorArrays are always flat
elems_ta = [
tensor_array_ops.TensorArray(dtype=elem.dtype, size=n,
dynamic_size=False,
infer_shape=True)
for elem in elems_flat]
# Unpack elements
elems_ta = [
elem_ta.unpack(elem) for elem_ta, elem in zip(elems_ta, elems_flat)]
i = constant_op.constant(0)
accs_ta = [
tensor_array_ops.TensorArray(dtype=dt, size=n,
dynamic_size=False,
infer_shape=infer_shape)
for dt in dtype_flat]
def compute(i, tas):
"""The loop body of map_fn.
Args:
i: the loop counter
tas: the flat TensorArray accumulator list
Returns:
(i + 1, tas): the updated counter + updated TensorArrays
Raises:
TypeError: if dtype and packed_fn_values structure do not match
ValueType: if dtype and packed_fn_values lengths do not match
"""
packed_values = input_pack([elem_ta.read(i) for elem_ta in elems_ta])
packed_fn_values = fn(packed_values)
nest.assert_same_structure(dtype or elems, packed_fn_values)
flat_fn_values = output_flatten(packed_fn_values)
tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_fn_values)]
return (i + 1, tas)
_, r_a = control_flow_ops.while_loop(
lambda i, _: i < n, compute, (i, accs_ta),
parallel_iterations=parallel_iterations,
back_prop=back_prop,
swap_memory=swap_memory)
results_flat = [r.pack() for r in r_a]
n_static = elems_flat[0].get_shape().with_rank_at_least(1)[0]
for elem in elems_flat[1:]:
n_static.merge_with(elem.get_shape().with_rank_at_least(1)[0])
for r in results_flat:
r.set_shape(tensor_shape.TensorShape(n_static).concatenate(
r.get_shape()[1:]))
if varscope_caching_device_was_none:
varscope.set_caching_device(None)
return output_pack(results_flat)
def scan(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
swap_memory=False, infer_shape=True, name=None):
"""scan on the list of tensors unpacked from `elems` on dimension 0.
The simplest version of `scan` repeatedly applies the callable `fn` to a
sequence of elements from first to last. The elements are made of the tensors
unpacked from `elems` on dimension 0. The callable fn takes two tensors as
arguments. The first argument is the accumulated value computed from the
preceding invocation of fn. If `initializer` is None, `elems` must contain
at least one element, and its first element is used as the initializer.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`.
This method also allows multi-arity `elems` and accumulator. If `elems`
is a (possibly nested) list or tuple of tensors, then each of these tensors
must have a matching first (unpack) dimension. The second argument of
`fn` must match the structure of `elems`.
If no `initializer` is provided, the output structure and dtypes of `fn`
are assumed to be the same as its input; and in this case, the first
argument of `fn` must match the structure of `elems`.
If an `initializer` is provided, then the output of `fn` must have the same
structure as `initializer`; and the first argument of `fn` must match
this structure.
For example, if `elems` is `(t1, [t2, t3])` and `initializer` is
`[i1, i2]` then an appropriate signature for `fn` in `python2` is:
`fn = lambda (acc_p1, acc_p2), (t1 [t2, t3]):` and `fn` must return a list,
`[acc_n1, acc_n2]`. An alternative correct signature for `fn`, and the
one that works in `python3`, is:
`fn = lambda a, t:`, where `a` and `t` correspond to the input tuples.
Args:
fn: The callable to be performed. It accepts two arguments. The first
will have the same (possibly nested) structure as `elems`. The second
will have the same structure as `initializer` if one is provided,
otherwise it will have the same structure as `elems`. Its output
must have the same structure as `initializer` if one is provided,
otherwise it must have the same structure as `elems`.
elems: A tensor or (possibly nested) sequence of tensors, each of which
will be unpacked along their first dimension. The nested sequence
of the resulting slices will be the first argument to `fn`.
initializer: (optional) A tensor or (possibly nested) sequence of tensors,
initial value for the accumulator, and the expected output type of `fn`.
parallel_iterations: (optional) The number of iterations allowed to run
in parallel.
back_prop: (optional) True enables support for back propagation.
swap_memory: (optional) True enables GPU-CPU memory swapping.
infer_shape: (optional) False disables tests for consistent output shapes.
name: (optional) Name prefix for the returned tensors.
Returns:
A tensor or (possibly nested) sequence of tensors. Each tensor packs the
results of applying `fn` to tensors unpacked from `elems` along the first
dimension, and the previous accumulator value(s), from first to last.
Raises:
TypeError: if `fn` is not callable or the structure of the output of
`fn` and `initializer` do not match.
ValueError: if the lengths of the output of `fn` and `initializer`
do not match.
Examples:
```python
elems = np.array([1, 2, 3, 4, 5, 6])
sum = scan(lambda a, x: a + x, elems)
# sum == [1, 3, 6, 10, 15, 21]
```
```python
elems = np.array([1, 2, 3, 4, 5, 6])
initializer = np.array(0)
sum_one = scan(
lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer)
# sum_one == [1, 2, 3, 4, 5, 6]
```
```python
elems = np.array([1, 0, 0, 0, 0, 0])
initializer = (np.array(0), np.array(1))
fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer)
# fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13])
```
"""
if not callable(fn):
raise TypeError("fn must be callable.")
input_is_sequence = nest.is_sequence(elems)
input_flatten = lambda x: nest.flatten(x) if input_is_sequence else [x]
def input_pack(x):
return nest.pack_sequence_as(elems, x) if input_is_sequence else x[0]
if initializer is None:
output_is_sequence = input_is_sequence
output_flatten = input_flatten
output_pack = input_pack
else:
output_is_sequence = nest.is_sequence(initializer)
output_flatten = lambda x: nest.flatten(x) if output_is_sequence else [x]
def output_pack(x):
return (nest.pack_sequence_as(initializer, x)
if output_is_sequence else x[0])
elems_flat = input_flatten(elems)
with ops.op_scope(elems_flat, name, "scan"):
# Any get_variable calls in fn will cache the first call locally
# and not issue repeated network I/O requests for each iteration.
varscope = vs.get_variable_scope()
varscope_caching_device_was_none = False
if varscope.caching_device is None:
# TODO(ebrevdo): Change to using colocate_with here and in other methods.
varscope.set_caching_device(lambda op: op.device)
varscope_caching_device_was_none = True
# Convert elems to tensor array.
elems_flat = [
ops.convert_to_tensor(elem, name="elem") for elem in elems_flat]
n = array_ops.shape(elems_flat[0])[0]
# TensorArrays are always flat
elems_ta = [
tensor_array_ops.TensorArray(dtype=elem.dtype, size=n,
dynamic_size=False,
infer_shape=True)
for elem in elems_flat]
# Unpack elements
elems_ta = [
elem_ta.unpack(elem) for elem_ta, elem in zip(elems_ta, elems_flat)]
if initializer is None:
a_flat = [elem.read(0) for elem in elems_ta]
i = constant_op.constant(1)
else:
initializer_flat = output_flatten(initializer)
a_flat = [ops.convert_to_tensor(init) for init in initializer_flat]
i = constant_op.constant(0)
# Create a tensor array to store the intermediate values.
accs_ta = [
tensor_array_ops.TensorArray(dtype=init.dtype, size=n,
dynamic_size=False,
infer_shape=infer_shape)
for init in a_flat]
if initializer is None:
accs_ta = [acc_ta.write(0, a) for (acc_ta, a) in zip(accs_ta, a_flat)]
def compute(i, a_flat, tas):
"""The loop body of scan.
Args:
i: the loop counter.
a_flat: the accumulator value(s), flattened.
tas: the output accumulator TensorArray(s), flattened.
Returns:
[i + 1, a_flat, tas]: the updated counter + new accumulator values +
updated TensorArrays
Raises:
TypeError: if initializer and fn() output structure do not match
ValueType: if initializer and fn() output lengths do not match
"""
packed_elems = input_pack([elem_ta.read(i) for elem_ta in elems_ta])
packed_a = output_pack(a_flat)
a_out = fn(packed_a, packed_elems)
nest.assert_same_structure(
elems if initializer is None else initializer, a_out)
flat_a_out = output_flatten(a_out)
tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_a_out)]
return (i + 1, flat_a_out, tas)
_, _, r_a = control_flow_ops.while_loop(
lambda i, _1, _2: i < n, compute, (i, a_flat, accs_ta),
parallel_iterations=parallel_iterations,
back_prop=back_prop, swap_memory=swap_memory)
results_flat = [r.pack() for r in r_a]
n_static = elems_flat[0].get_shape().with_rank_at_least(1)[0]
for elem in elems_flat[1:]:
n_static.merge_with(elem.get_shape().with_rank_at_least(1)[0])
for r in results_flat:
r.set_shape(tensor_shape.TensorShape(n_static).concatenate(
r.get_shape()[1:]))
if varscope_caching_device_was_none:
varscope.set_caching_device(None)
return output_pack(results_flat)
@ops.RegisterShape("SymbolicGradient")
def _symbolic_gradient_shape(op):
# Say, (u, v) = f(x, y, z), _symbolic_gradient(f) is a function of
# (x, y, z, du, dv) -> (dx, dy, dz). Therefore, shapes of its
# outputs (dx, dy, dz) are the same as (x, y, z).
return [op.inputs[i].get_shape() for i in range(len(op.outputs))]
| mit |
froilanq/CursoAngularJS | 10-Configuracion-Cache/client/totalFactory.js | 198 | (function () {
var totalFactory = function ($resource) {
return $resource("/api/priv/total/");
};
controlCajaApp.factory('totalFactory', ['$resource', totalFactory]);
}()); | mit |
jordansite/jekyll-vlog | vendor/ruby/2.3.0/gems/faraday-0.12.0.1/README.md | 10705 | # Faraday
[](https://rubygems.org/gems/faraday)
[](https://travis-ci.org/lostisland/faraday)
[](https://gitter.im/lostisland/faraday?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Faraday is an HTTP client lib that provides a common interface over many
adapters (such as Net::HTTP) and embraces the concept of Rack middleware when
processing the request/response cycle.
Faraday supports these adapters:
* [Net::HTTP][net_http] _(default)_
* [Net::HTTP::Persistent][persistent]
* [Excon][]
* [Patron][]
* [EventMachine][]
* [HTTPClient][]
It also includes a Rack adapter for hitting loaded Rack applications through
Rack::Test, and a Test adapter for stubbing requests by hand.
## API documentation
Available at [rubydoc.info](http://www.rubydoc.info/gems/faraday).
## Usage
### Basic Use
```ruby
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
```
A simple `get` request can be performed by using the syntax described above. This works if you don't need to set up anything; you can roll with just the default middleware
stack and default adapter (see [Faraday::RackBuilder#initialize](https://github.com/lostisland/faraday/blob/master/lib/faraday/rack_builder.rb)).
A more flexible way to use Faraday is to start with a Connection object. If you want to keep the same defaults, you can use this syntax:
```ruby
conn = Faraday.new(:url => 'http://www.example.com')
response = conn.get '/users' # GET http://www.example.com/users'
```
Connections can also take an options hash as a parameter or be configured by using a block. Checkout the section called [Advanced middleware usage](#advanced-middleware-usage) for more details about how to use this block for configurations.
```ruby
conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
faraday.request :url_encoded # form-encode POST params
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
# Filter sensitive information from logs with a regex matcher
conn = Faraday.new(:url => 'http://sushi.com/api_key=s3cr3t') do |faraday|
faraday.response :logger do | logger |
logger.filter(/(api_key=)(\w+)/,'\1[REMOVED]')
end
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
```
Once you have the connection object, use it to make HTTP requests. You can pass paramters to it in a few different ways:
```ruby
## GET ##
response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json
response.body
conn.get '/nigiri', { :name => 'Maguro' } # GET http://sushi.com/nigiri?name=Maguro
conn.get do |req| # GET http://sushi.com/search?page=2&limit=100
req.url '/search', :page => 2
req.params['limit'] = 100
end
## POST ##
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
```
Some configuration options can be adjusted per request:
```ruby
# post payload as JSON instead of "www-form-urlencoded" encoding:
conn.post do |req|
req.url '/nigiri'
req.headers['Content-Type'] = 'application/json'
req.body = '{ "name": "Unagi" }'
end
## Per-request options ##
conn.get do |req|
req.url '/search'
req.options.timeout = 5 # open/read timeout in seconds
req.options.open_timeout = 2 # connection open timeout in seconds
end
```
And you can inject arbitrary data into the request using the `context` option:
```ruby
# Anything you inject using context option will be available in the env on all middlewares
conn.get do |req|
req.url '/search'
req.options.context = {
foo: 'foo',
bar: 'bar'
}
end
```
### Changing how parameters are serialized
Sometimes you need to send the same URL parameter multiple times with different
values. This requires manually setting the parameter encoder and can be done on
either per-connection or per-request basis.
```ruby
# per-connection setting
conn = Faraday.new :request => { :params_encoder => Faraday::FlatParamsEncoder }
conn.get do |req|
# per-request setting:
# req.options.params_encoder = my_encoder
req.params['roll'] = ['california', 'philadelphia']
end
# GET 'http://sushi.com?roll=california&roll=philadelphia'
```
The value of Faraday `params_encoder` can be any object that responds to:
* `encode(hash) #=> String`
* `decode(string) #=> Hash`
The encoder will affect both how query strings are processed and how POST bodies
get serialized. The default encoder is Faraday::NestedParamsEncoder.
## Advanced middleware usage
The order in which middleware is stacked is important. Like with Rack, the
first middleware on the list wraps all others, while the last middleware is the
innermost one, so that must be the adapter.
```ruby
Faraday.new(...) do |conn|
# POST/PUT params encoders:
conn.request :multipart
conn.request :url_encoded
conn.adapter :net_http
end
```
This request middleware setup affects POST/PUT requests in the following way:
1. `Request::Multipart` checks for files in the payload, otherwise leaves
everything untouched;
2. `Request::UrlEncoded` encodes as "application/x-www-form-urlencoded" if not
already encoded or of another type
Swapping middleware means giving the other priority. Specifying the
"Content-Type" for the request is explicitly stating which middleware should
process it.
Examples:
```ruby
# uploading a file:
payload[:profile_pic] = Faraday::UploadIO.new('/path/to/avatar.jpg', 'image/jpeg')
# "Multipart" middleware detects files and encodes with "multipart/form-data":
conn.put '/profile', payload
```
## Writing middleware
Middleware are classes that implement a `call` instance method. They hook into
the request/response cycle.
```ruby
def call(request_env)
# do something with the request
# request_env[:request_headers].merge!(...)
@app.call(request_env).on_complete do |response_env|
# do something with the response
# response_env[:response_headers].merge!(...)
end
end
```
It's important to do all processing of the response only in the `on_complete`
block. This enables middleware to work in parallel mode where requests are
asynchronous.
The `env` is a hash with symbol keys that contains info about the request and,
later, response. Some keys are:
```
# request phase
:method - :get, :post, ...
:url - URI for the current request; also contains GET parameters
:body - POST parameters for :post/:put requests
:request_headers
# response phase
:status - HTTP response status code, such as 200
:body - the response body
:response_headers
```
## Ad-hoc adapters customization
Faraday is intended to be a generic interface between your code and the adapter. However, sometimes you need to access a feature specific to one of the adapters that is not covered in Faraday's interface.
When that happens, you can pass a block when specifying the adapter to customize it. The block parameter will change based on the adapter you're using. See below for some examples.
### NetHttp
```ruby
conn = Faraday.new(...) do |f|
f.adapter :net_http do |http| # yields Net::HTTP
http.idle_timeout = 100
http.verify_callback = lambda do | preverify_ok, cert_store |
# do something here...
end
end
end
```
### NetHttpPersistent
```ruby
conn = Faraday.new(...) do |f|
f.adapter :net_http_persistent do |http| # yields Net::HTTP::Persistent
http.idle_timeout = 100
http.retry_change_requests = true
end
end
```
### Patron
```ruby
conn = Faraday.new(...) do |f|
f.adapter :patron do |session| # yields Patron::Session
session.max_redirects = 10
end
end
```
### HTTPClient
```ruby
conn = Faraday.new(...) do |f|
f.adapter :httpclient do |client| # yields HTTPClient
client.keep_alive_timeout = 20
client.ssl_config.timeout = 25
end
end
```
## Using Faraday for testing
```ruby
# It's possible to define stubbed request outside a test adapter block.
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get('/tamago') { |env| [200, {}, 'egg'] }
end
# You can pass stubbed request to the test adapter or define them in a block
# or a combination of the two.
test = Faraday.new do |builder|
builder.adapter :test, stubs do |stub|
stub.get('/ebi') { |env| [ 200, {}, 'shrimp' ]}
end
end
# It's also possible to stub additional requests after the connection has
# been initialized. This is useful for testing.
stubs.get('/uni') { |env| [ 200, {}, 'urchin' ]}
resp = test.get '/tamago'
resp.body # => 'egg'
resp = test.get '/ebi'
resp.body # => 'shrimp'
resp = test.get '/uni'
resp.body # => 'urchin'
resp = test.get '/else' #=> raises "no such stub" error
# If you like, you can treat your stubs as mocks by verifying that all of
# the stubbed calls were made. NOTE that this feature is still fairly
# experimental: It will not verify the order or count of any stub, only that
# it was called once during the course of the test.
stubs.verify_stubbed_calls
```
## TODO
* support streaming requests/responses
* better stubbing API
## Supported Ruby versions
This library aims to support and is [tested against][travis] the following Ruby
implementations:
* Ruby 1.9.3+
* [JRuby][] 1.7+
* [Rubinius][] 2+
If something doesn't work on one of these Ruby versions, it's a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be responsible for providing patches in a timely
fashion. If critical issues for a particular implementation exist at the time
of a major release, support for that Ruby version may be dropped.
## Copyright
Copyright (c) 2009-2013 [Rick Olson](mailto:[email protected]), Zack Hobson.
See [LICENSE][] for details.
[net_http]: http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/Net/HTTP.html
[persistent]: https://github.com/drbrain/net-http-persistent
[travis]: https://travis-ci.org/lostisland/faraday
[excon]: https://github.com/excon/excon#readme
[patron]: http://toland.github.io/patron/
[eventmachine]: https://github.com/igrigorik/em-http-request#readme
[httpclient]: https://github.com/nahi/httpclient
[jruby]: http://jruby.org/
[rubinius]: http://rubini.us/
[license]: LICENSE.md
| mit |
hoho/dosido | nodejs/deps/v8/src/log.h | 14723 | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_LOG_H_
#define V8_LOG_H_
#include <string>
#include "src/allocation.h"
#include "src/base/compiler-specific.h"
#include "src/base/platform/elapsed-timer.h"
#include "src/base/platform/platform.h"
#include "src/code-events.h"
#include "src/isolate.h"
#include "src/objects.h"
namespace v8 {
struct TickSample;
namespace sampler {
class Sampler;
}
namespace internal {
// Logger is used for collecting logging information from V8 during
// execution. The result is dumped to a file.
//
// Available command line flags:
//
// --log
// Minimal logging (no API, code, or GC sample events), default is off.
//
// --log-all
// Log all events to the file, default is off. This is the same as combining
// --log-api, --log-code, --log-gc, and --log-regexp.
//
// --log-api
// Log API events to the logfile, default is off. --log-api implies --log.
//
// --log-code
// Log code (create, move, and delete) events to the logfile, default is off.
// --log-code implies --log.
//
// --log-gc
// Log GC heap samples after each GC that can be processed by hp2ps, default
// is off. --log-gc implies --log.
//
// --log-regexp
// Log creation and use of regular expressions, Default is off.
// --log-regexp implies --log.
//
// --logfile <filename>
// Specify the name of the logfile, default is "v8.log".
//
// --prof
// Collect statistical profiling information (ticks), default is off. The
// tick profiler requires code events, so --prof implies --log-code.
//
// --prof-sampling-interval <microseconds>
// The interval between --prof samples, default is 1000 microseconds (5000 on
// Android).
// Forward declarations.
class CodeEventListener;
class CpuProfiler;
class Isolate;
class JitLogger;
class Log;
class LowLevelLogger;
class PerfBasicLogger;
class PerfJitLogger;
class Profiler;
class ProfilerListener;
class RuntimeCallTimer;
class Ticker;
#undef LOG
#define LOG(isolate, Call) \
do { \
v8::internal::Logger* logger = (isolate)->logger(); \
if (logger->is_logging()) logger->Call; \
} while (false)
#define LOG_CODE_EVENT(isolate, Call) \
do { \
v8::internal::Logger* logger = (isolate)->logger(); \
if (logger->is_logging_code_events()) logger->Call; \
} while (false)
class Logger : public CodeEventListener {
public:
enum StartEnd { START = 0, END = 1 };
// Acquires resources for logging if the right flags are set.
bool SetUp(Isolate* isolate);
// Sets the current code event handler.
void SetCodeEventHandler(uint32_t options,
JitCodeEventHandler event_handler);
// Sets up ProfilerListener.
void SetUpProfilerListener();
// Tear down ProfilerListener if it has no observers.
void TearDownProfilerListener();
sampler::Sampler* sampler();
ProfilerListener* profiler_listener() { return profiler_listener_.get(); }
// Frees resources acquired in SetUp.
// When a temporary file is used for the log, returns its stream descriptor,
// leaving the file open.
FILE* TearDown();
// Emits an event with a string value -> (name, value).
void StringEvent(const char* name, const char* value);
// Emits an event with an int value -> (name, value).
void IntEvent(const char* name, int value);
void IntPtrTEvent(const char* name, intptr_t value);
// Emits an event with an handle value -> (name, location).
void HandleEvent(const char* name, Object** location);
// Emits memory management events for C allocated structures.
void NewEvent(const char* name, void* object, size_t size);
void DeleteEvent(const char* name, void* object);
// Emits an event with a tag, and some resource usage information.
// -> (name, tag, <rusage information>).
// Currently, the resource usage information is a process time stamp
// and a real time timestamp.
void ResourceEvent(const char* name, const char* tag);
// Emits an event that an undefined property was read from an
// object.
void SuspectReadEvent(Name* name, Object* obj);
// ==== Events logged by --log-api. ====
void ApiSecurityCheck();
void ApiNamedPropertyAccess(const char* tag, JSObject* holder, Object* name);
void ApiIndexedPropertyAccess(const char* tag,
JSObject* holder,
uint32_t index);
void ApiObjectAccess(const char* tag, JSObject* obj);
void ApiEntryCall(const char* name);
// ==== Events logged by --log-code. ====
void addCodeEventListener(CodeEventListener* listener);
void removeCodeEventListener(CodeEventListener* listener);
// Emits a code event for a callback function.
void CallbackEvent(Name* name, Address entry_point);
void GetterCallbackEvent(Name* name, Address entry_point);
void SetterCallbackEvent(Name* name, Address entry_point);
// Emits a code create event.
void CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, const char* source);
void CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, Name* name);
void CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, SharedFunctionInfo* shared,
Name* name);
void CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, SharedFunctionInfo* shared,
Name* source, int line, int column);
void CodeCreateEvent(CodeEventListener::LogEventsAndTags tag,
AbstractCode* code, int args_count);
// Emits a code deoptimization event.
void CodeDisableOptEvent(AbstractCode* code, SharedFunctionInfo* shared);
void CodeMovingGCEvent();
// Emits a code create event for a RegExp.
void RegExpCodeCreateEvent(AbstractCode* code, String* source);
// Emits a code move event.
void CodeMoveEvent(AbstractCode* from, Address to);
// Emits a code line info record event.
void CodeLinePosInfoRecordEvent(AbstractCode* code,
ByteArray* source_position_table);
void SharedFunctionInfoMoveEvent(Address from, Address to);
void CodeNameEvent(Address addr, int pos, const char* code_name);
void CodeDeoptEvent(Code* code, DeoptKind kind, Address pc,
int fp_to_sp_delta);
void ICEvent(const char* type, bool keyed, const Address pc, int line,
int column, Map* map, Object* key, char old_state,
char new_state, const char* modifier,
const char* slow_stub_reason);
void CompareIC(const Address pc, int line, int column, Code* stub,
const char* op, const char* old_left, const char* old_right,
const char* old_state, const char* new_left,
const char* new_right, const char* new_state);
void BinaryOpIC(const Address pc, int line, int column, Code* stub,
const char* old_state, const char* new_state,
AllocationSite* allocation_site);
void ToBooleanIC(const Address pc, int line, int column, Code* stub,
const char* old_state, const char* new_state);
void PatchIC(const Address pc, const Address test, int delta);
// ==== Events logged by --log-gc. ====
// Heap sampling events: start, end, and individual types.
void HeapSampleBeginEvent(const char* space, const char* kind);
void HeapSampleEndEvent(const char* space, const char* kind);
void HeapSampleItemEvent(const char* type, int number, int bytes);
void HeapSampleJSConstructorEvent(const char* constructor,
int number, int bytes);
void HeapSampleJSRetainersEvent(const char* constructor,
const char* event);
void HeapSampleJSProducerEvent(const char* constructor,
Address* stack);
void HeapSampleStats(const char* space, const char* kind,
intptr_t capacity, intptr_t used);
void SharedLibraryEvent(const std::string& library_path, uintptr_t start,
uintptr_t end, intptr_t aslr_slide);
void CurrentTimeEvent();
void TimerEvent(StartEnd se, const char* name);
static void EnterExternal(Isolate* isolate);
static void LeaveExternal(Isolate* isolate);
static void DefaultEventLoggerSentinel(const char* name, int event) {}
INLINE(static void CallEventLogger(Isolate* isolate, const char* name,
StartEnd se, bool expose_to_api));
bool is_logging() {
return is_logging_;
}
bool is_logging_code_events() {
return is_logging() || jit_logger_ != NULL;
}
// Stop collection of profiling data.
// When data collection is paused, CPU Tick events are discarded.
void StopProfiler();
void LogExistingFunction(Handle<SharedFunctionInfo> shared,
Handle<AbstractCode> code);
// Logs all compiled functions found in the heap.
void LogCompiledFunctions();
// Logs all accessor callbacks found in the heap.
void LogAccessorCallbacks();
// Used for logging stubs found in the snapshot.
void LogCodeObjects();
// Used for logging bytecode handlers found in the snapshot.
void LogBytecodeHandlers();
// Converts tag to a corresponding NATIVE_... if the script is native.
INLINE(static CodeEventListener::LogEventsAndTags ToNativeByScript(
CodeEventListener::LogEventsAndTags, Script*));
// Callback from Log, stops profiling in case of insufficient resources.
void LogFailure();
private:
explicit Logger(Isolate* isolate);
~Logger();
// Emits the profiler's first message.
void ProfilerBeginEvent();
// Emits callback event messages.
void CallbackEventInternal(const char* prefix,
Name* name,
Address entry_point);
// Internal configurable move event.
void MoveEventInternal(CodeEventListener::LogEventsAndTags event,
Address from, Address to);
// Used for logging stubs found in the snapshot.
void LogCodeObject(Object* code_object);
// Helper method. It resets name_buffer_ and add tag name into it.
void InitNameBuffer(CodeEventListener::LogEventsAndTags tag);
// Emits a profiler tick event. Used by the profiler thread.
void TickEvent(TickSample* sample, bool overflow);
void RuntimeCallTimerEvent();
PRINTF_FORMAT(2, 3) void ApiEvent(const char* format, ...);
// Logs a StringEvent regardless of whether FLAG_log is true.
void UncheckedStringEvent(const char* name, const char* value);
// Logs an IntEvent regardless of whether FLAG_log is true.
void UncheckedIntEvent(const char* name, int value);
void UncheckedIntPtrTEvent(const char* name, intptr_t value);
Isolate* isolate_;
// The sampler used by the profiler and the sliding state window.
Ticker* ticker_;
// When the statistical profile is active, profiler_
// points to a Profiler, that handles collection
// of samples.
Profiler* profiler_;
// An array of log events names.
const char* const* log_events_;
// Internal implementation classes with access to
// private members.
friend class EventLog;
friend class Isolate;
friend class TimeLog;
friend class Profiler;
template <StateTag Tag> friend class VMState;
friend class LoggerTestHelper;
bool is_logging_;
Log* log_;
PerfBasicLogger* perf_basic_logger_;
PerfJitLogger* perf_jit_logger_;
LowLevelLogger* ll_logger_;
JitLogger* jit_logger_;
std::unique_ptr<ProfilerListener> profiler_listener_;
List<CodeEventListener*> listeners_;
// Guards against multiple calls to TearDown() that can happen in some tests.
// 'true' between SetUp() and TearDown().
bool is_initialized_;
base::ElapsedTimer timer_;
friend class CpuProfiler;
};
#define TIMER_EVENTS_LIST(V) \
V(RecompileSynchronous, true) \
V(RecompileConcurrent, true) \
V(CompileIgnition, true) \
V(CompileFullCode, true) \
V(OptimizeCode, true) \
V(CompileCode, true) \
V(DeoptimizeCode, true) \
V(Execute, true) \
V(External, true)
#define V(TimerName, expose) \
class TimerEvent##TimerName : public AllStatic { \
public: \
static const char* name(void* unused = NULL) { return "V8." #TimerName; } \
static bool expose_to_api() { return expose; } \
};
TIMER_EVENTS_LIST(V)
#undef V
template <class TimerEvent>
class TimerEventScope {
public:
explicit TimerEventScope(Isolate* isolate) : isolate_(isolate) {
LogTimerEvent(Logger::START);
}
~TimerEventScope() { LogTimerEvent(Logger::END); }
private:
void LogTimerEvent(Logger::StartEnd se);
Isolate* isolate_;
};
class CodeEventLogger : public CodeEventListener {
public:
CodeEventLogger();
~CodeEventLogger() override;
void CodeCreateEvent(LogEventsAndTags tag, AbstractCode* code,
const char* comment) override;
void CodeCreateEvent(LogEventsAndTags tag, AbstractCode* code,
Name* name) override;
void CodeCreateEvent(LogEventsAndTags tag, AbstractCode* code,
int args_count) override;
void CodeCreateEvent(LogEventsAndTags tag, AbstractCode* code,
SharedFunctionInfo* shared, Name* name) override;
void CodeCreateEvent(LogEventsAndTags tag, AbstractCode* code,
SharedFunctionInfo* shared, Name* source, int line,
int column) override;
void RegExpCodeCreateEvent(AbstractCode* code, String* source) override;
void CallbackEvent(Name* name, Address entry_point) override {}
void GetterCallbackEvent(Name* name, Address entry_point) override {}
void SetterCallbackEvent(Name* name, Address entry_point) override {}
void SharedFunctionInfoMoveEvent(Address from, Address to) override {}
void CodeMovingGCEvent() override {}
void CodeDeoptEvent(Code* code, DeoptKind kind, Address pc,
int fp_to_sp_delta) override {}
private:
class NameBuffer;
virtual void LogRecordedBuffer(AbstractCode* code, SharedFunctionInfo* shared,
const char* name, int length) = 0;
NameBuffer* name_buffer_;
};
} // namespace internal
} // namespace v8
#endif // V8_LOG_H_
| mit |
hoho/dosido | nodejs/deps/v8/src/futex-emulation.cc | 7269 | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/futex-emulation.h"
#include <limits>
#include "src/base/macros.h"
#include "src/base/platform/time.h"
#include "src/conversions.h"
#include "src/handles-inl.h"
#include "src/isolate.h"
#include "src/list-inl.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
base::LazyMutex FutexEmulation::mutex_ = LAZY_MUTEX_INITIALIZER;
base::LazyInstance<FutexWaitList>::type FutexEmulation::wait_list_ =
LAZY_INSTANCE_INITIALIZER;
void FutexWaitListNode::NotifyWake() {
// Lock the FutexEmulation mutex before notifying. We know that the mutex
// will have been unlocked if we are currently waiting on the condition
// variable.
//
// The mutex may also not be locked if the other thread is currently handling
// interrupts, or if FutexEmulation::Wait was just called and the mutex
// hasn't been locked yet. In either of those cases, we set the interrupted
// flag to true, which will be tested after the mutex is re-locked.
base::LockGuard<base::Mutex> lock_guard(FutexEmulation::mutex_.Pointer());
if (waiting_) {
cond_.NotifyOne();
interrupted_ = true;
}
}
FutexWaitList::FutexWaitList() : head_(nullptr), tail_(nullptr) {}
void FutexWaitList::AddNode(FutexWaitListNode* node) {
DCHECK(node->prev_ == nullptr && node->next_ == nullptr);
if (tail_) {
tail_->next_ = node;
} else {
head_ = node;
}
node->prev_ = tail_;
node->next_ = nullptr;
tail_ = node;
}
void FutexWaitList::RemoveNode(FutexWaitListNode* node) {
if (node->prev_) {
node->prev_->next_ = node->next_;
} else {
head_ = node->next_;
}
if (node->next_) {
node->next_->prev_ = node->prev_;
} else {
tail_ = node->prev_;
}
node->prev_ = node->next_ = nullptr;
}
Object* FutexEmulation::Wait(Isolate* isolate,
Handle<JSArrayBuffer> array_buffer, size_t addr,
int32_t value, double rel_timeout_ms) {
DCHECK(addr < NumberToSize(array_buffer->byte_length()));
void* backing_store = array_buffer->backing_store();
int32_t* p =
reinterpret_cast<int32_t*>(static_cast<int8_t*>(backing_store) + addr);
base::LockGuard<base::Mutex> lock_guard(mutex_.Pointer());
if (*p != value) {
return isolate->heap()->not_equal();
}
FutexWaitListNode* node = isolate->futex_wait_list_node();
node->backing_store_ = backing_store;
node->wait_addr_ = addr;
node->waiting_ = true;
bool use_timeout = rel_timeout_ms != V8_INFINITY;
base::TimeDelta rel_timeout;
if (use_timeout) {
// Convert to nanoseconds.
double rel_timeout_ns = rel_timeout_ms *
base::Time::kNanosecondsPerMicrosecond *
base::Time::kMicrosecondsPerMillisecond;
if (rel_timeout_ns >
static_cast<double>(std::numeric_limits<int64_t>::max())) {
// 2**63 nanoseconds is 292 years. Let's just treat anything greater as
// infinite.
use_timeout = false;
} else {
rel_timeout = base::TimeDelta::FromNanoseconds(
static_cast<int64_t>(rel_timeout_ns));
}
}
base::TimeTicks start_time = base::TimeTicks::Now();
base::TimeTicks timeout_time = start_time + rel_timeout;
base::TimeTicks current_time = start_time;
wait_list_.Pointer()->AddNode(node);
Object* result;
while (true) {
bool interrupted = node->interrupted_;
node->interrupted_ = false;
// Unlock the mutex here to prevent deadlock from lock ordering between
// mutex_ and mutexes locked by HandleInterrupts.
mutex_.Pointer()->Unlock();
// Because the mutex is unlocked, we have to be careful about not dropping
// an interrupt. The notification can happen in three different places:
// 1) Before Wait is called: the notification will be dropped, but
// interrupted_ will be set to 1. This will be checked below.
// 2) After interrupted has been checked here, but before mutex_ is
// acquired: interrupted is checked again below, with mutex_ locked.
// Because the wakeup signal also acquires mutex_, we know it will not
// be able to notify until mutex_ is released below, when waiting on the
// condition variable.
// 3) After the mutex is released in the call to WaitFor(): this
// notification will wake up the condition variable. node->waiting() will
// be false, so we'll loop and then check interrupts.
if (interrupted) {
Object* interrupt_object = isolate->stack_guard()->HandleInterrupts();
if (interrupt_object->IsException(isolate)) {
result = interrupt_object;
mutex_.Pointer()->Lock();
break;
}
}
mutex_.Pointer()->Lock();
if (node->interrupted_) {
// An interrupt occured while the mutex_ was unlocked. Don't wait yet.
continue;
}
if (!node->waiting_) {
result = isolate->heap()->ok();
break;
}
// No interrupts, now wait.
if (use_timeout) {
current_time = base::TimeTicks::Now();
if (current_time >= timeout_time) {
result = isolate->heap()->timed_out();
break;
}
base::TimeDelta time_until_timeout = timeout_time - current_time;
DCHECK(time_until_timeout.InMicroseconds() >= 0);
bool wait_for_result =
node->cond_.WaitFor(mutex_.Pointer(), time_until_timeout);
USE(wait_for_result);
} else {
node->cond_.Wait(mutex_.Pointer());
}
// Spurious wakeup, interrupt or timeout.
}
wait_list_.Pointer()->RemoveNode(node);
node->waiting_ = false;
return result;
}
Object* FutexEmulation::Wake(Isolate* isolate,
Handle<JSArrayBuffer> array_buffer, size_t addr,
uint32_t num_waiters_to_wake) {
DCHECK(addr < NumberToSize(array_buffer->byte_length()));
int waiters_woken = 0;
void* backing_store = array_buffer->backing_store();
base::LockGuard<base::Mutex> lock_guard(mutex_.Pointer());
FutexWaitListNode* node = wait_list_.Pointer()->head_;
while (node && num_waiters_to_wake > 0) {
if (backing_store == node->backing_store_ && addr == node->wait_addr_) {
node->waiting_ = false;
node->cond_.NotifyOne();
if (num_waiters_to_wake != kWakeAll) {
--num_waiters_to_wake;
}
waiters_woken++;
}
node = node->next_;
}
return Smi::FromInt(waiters_woken);
}
Object* FutexEmulation::NumWaitersForTesting(Isolate* isolate,
Handle<JSArrayBuffer> array_buffer,
size_t addr) {
DCHECK(addr < NumberToSize(array_buffer->byte_length()));
void* backing_store = array_buffer->backing_store();
base::LockGuard<base::Mutex> lock_guard(mutex_.Pointer());
int waiters = 0;
FutexWaitListNode* node = wait_list_.Pointer()->head_;
while (node) {
if (backing_store == node->backing_store_ && addr == node->wait_addr_ &&
node->waiting_) {
waiters++;
}
node = node->next_;
}
return Smi::FromInt(waiters);
}
} // namespace internal
} // namespace v8
| mit |
adamdriscoll/TfsIntegrationPlatform | IntegrationPlatform/Shell/EditorFoundation/Source/Extensibility/PluginManager.cs | 11472 | // Copyright © Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.TeamFoundation.Migration.Shell.View;
using Microsoft.TeamFoundation.Migration.Toolkit;
namespace Microsoft.TeamFoundation.Migration.Shell.Extensibility
{
/// <summary>
/// This class discovers and loads Plugins. It also exposes information about
/// the loaded Plugins, and exposes an interface for invoking Plugin commands.
/// </summary>
public class PluginManager : IPluginManager
{
#region Fields
private readonly PluginHandler[] pluginHandlers;
private readonly PluginContextCollection pluginContexts;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <remarks>
/// Plugin probing directories are read from the application configuration file.
/// </remarks>
public PluginManager () : this (PluginManager.GetPluginDirectoriesFromConfig ())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <param name="probingDirectories">
/// Specifies directories to probe for Plugins.
/// </param>
public PluginManager (params DirectoryInfo[] probingDirectories)
{
this.pluginHandlers = PluginManager.DiscoverPlugins (probingDirectories);
this.pluginContexts = new PluginContextCollection (this);
foreach (PluginHandler pluginHandler in this.pluginHandlers)
{
pluginHandler.Loaded += this.OnPluginLoaded;
pluginHandler.Unloaded += this.OnPluginUnloaded;
}
}
public IEnumerable<IMigrationSourceView> GetMigrationSourceViews()
{
List<IMigrationSourceView> migrationSourceViews = new List<IMigrationSourceView>();
foreach (PluginHandler pluginHandler in pluginHandlers)
{
migrationSourceViews.Add(pluginHandler.GetMigrationSourceView());
}
return migrationSourceViews;
}
public IEnumerable<IConflictTypeView> GetConflictTypes(Guid providerId)
{
try
{
foreach (PluginHandler pluginHandler in pluginHandlers)
{
if (pluginHandler.Descriptor.Id.Equals(providerId))
{
return pluginHandler.GetConflictTypeViews();
}
}
}
catch (NotImplementedException)
{ }
return null;
}
public ExecuteFilterStringExtension GetFilterStringExtension(Guid providerId)
{
try
{
foreach (PluginHandler pluginhandler in pluginHandlers)
{
if (pluginhandler.Descriptor.Id.Equals(providerId))
{
return pluginhandler.FilterStringExtension;
}
}
}
catch (Exception)
{
}
return null;
}
#endregion
#region Properties
/// <summary>
/// Gets the Context Provider collection. Context Providers can freely be added and removed at runtime.
/// </summary>
public ICollection<object> PluginContexts
{
get
{
return this.pluginContexts;
}
}
/// <summary>
/// Gets information about all Plugins that have been loaded by the Plugin Manager.
/// </summary>
public IEnumerable<PluginDescriptor> LoadedPlugins
{
get
{
foreach (PluginHandler pluginHandler in this.LoadedPluginHandlers)
{
yield return pluginHandler.Descriptor;
}
}
}
private IEnumerable<PluginHandler> LoadedPluginHandlers
{
get
{
foreach (PluginHandler pluginHandler in this.pluginHandlers)
{
if (pluginHandler.IsLoaded)
{
yield return pluginHandler;
}
}
}
}
#endregion
#region Events
/// <summary>
/// Occurs when a Plugin is loaded.
/// </summary>
public event EventHandler<PluginLoadedEventArgs> PluginLoaded;
/// <summary>
/// Occurs when a Plugin is unloaded.
/// </summary>
public event EventHandler<PluginLoadedEventArgs> PluginUnloaded;
#endregion
#region Private Methods
private void OnPluginContextAdded (object context)
{
foreach (PluginHandler pluginHandler in this.pluginHandlers)
{
if (pluginHandler.SupportsContext (context.GetType ()))
{
pluginHandler.OnContextEnter (context);
}
}
}
private void OnPluginContextRemoved (object context)
{
foreach (PluginHandler pluginHandler in this.LoadedPluginHandlers)
{
if (pluginHandler.SupportsContext (context.GetType ()))
{
pluginHandler.OnContextLeave (context);
}
}
}
private static DirectoryInfo[] GetPluginDirectoriesFromConfig ()
{
List<DirectoryInfo> pluginDirectories = new List<DirectoryInfo> (Properties.Settings.Default.PluginDirectories.Count);
foreach (string pluginDirectory in Properties.Settings.Default.PluginDirectories)
{
// Expand environment variables
string resolvedPluginDirectory = Environment.ExpandEnvironmentVariables (pluginDirectory);
// If the directory is not rooted, make it relative to the application path
if (!Path.IsPathRooted (resolvedPluginDirectory))
{
resolvedPluginDirectory = Path.Combine (System.Windows.Forms.Application.StartupPath, resolvedPluginDirectory);
}
// Add the directory to the running list
pluginDirectories.Add (new DirectoryInfo (resolvedPluginDirectory));
}
return pluginDirectories.ToArray ();
}
private static PluginHandler[] DiscoverPlugins (DirectoryInfo[] probingDirectories)
{
// Initialize a list that will contain all plugin types discovered
List<PluginHandler> pluginHandlers = new List<PluginHandler> ();
if (probingDirectories != null)
{
// Iterate over the probing directories and look for plugins
foreach (DirectoryInfo directory in probingDirectories)
{
if (directory.Exists)
{
// Try to load plugins from each dll
foreach (FileInfo file in directory.GetFiles ("*.dll"))
{
try
{
// Load the dll into an assembly
Assembly assembly = Assembly.LoadFrom (file.FullName);
// Iterate over all types contained in the assembly
foreach (Type type in assembly.GetTypes ())
{
// Only consider public, concrete types that implement IPlugin
if (type.IsPublic && !type.IsAbstract && typeof (IPlugin).IsAssignableFrom (type))
{
PluginHandler pluginHandler = PluginHandler.FromType (type);
if (pluginHandler != null)
{
pluginHandlers.Add (pluginHandler);
}
}
}
}
catch (Exception exception)
{
Utilities.DefaultTraceSource.TraceEvent (TraceEventType.Error, 0, "A failure occurred while trying to load the {0} Plugin: {1}{2}", file.FullName, Environment.NewLine, exception.ToString ());
}
}
}
}
}
// Return the list of plugin types discovered
return pluginHandlers.ToArray ();
}
private void OnPluginLoaded (object sender, EventArgs e)
{
PluginHandler pluginHandler = (PluginHandler)sender;
if (this.PluginLoaded != null)
{
this.PluginLoaded (this, new PluginLoadedEventArgs (pluginHandler.Descriptor));
}
}
private void OnPluginUnloaded (object sender, EventArgs e)
{
PluginHandler pluginHandler = (PluginHandler)sender;
if (this.PluginUnloaded != null)
{
this.PluginUnloaded (this, new PluginLoadedEventArgs (pluginHandler.Descriptor));
}
}
#endregion
#region Classes
private class PluginContextCollection : Collection<object>
{
#region Fields
private PluginManager pluginManager;
#endregion
#region Constructors
public PluginContextCollection (PluginManager pluginManager)
{
this.pluginManager = pluginManager;
}
#endregion
#region Protected Methods
protected override void InsertItem (int index, object context)
{
base.InsertItem (index, context);
this.pluginManager.OnPluginContextAdded (context);
}
protected override void RemoveItem (int index)
{
object context = this[index];
base.RemoveItem (index);
this.pluginManager.OnPluginContextRemoved (context);
}
protected override void SetItem (int index, object newContext)
{
object oldContext = this[index];
base.SetItem (index, newContext);
this.pluginManager.OnPluginContextRemoved (oldContext);
this.pluginManager.OnPluginContextAdded (newContext);
}
protected override void ClearItems ()
{
foreach (object context in this)
{
this.pluginManager.OnPluginContextRemoved (context);
}
base.ClearItems ();
}
#endregion
}
#endregion
}
}
| mit |
lucasallan/concurrent-ruby | docs/1.1.4/Concurrent/Agent.html | 126343 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
Class: Concurrent::Agent
— Concurrent Ruby
</title>
<link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
pathId = "Concurrent::Agent";
relpath = '../';
</script>
<script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/app.js"></script>
</head>
<body>
<div class="nav_wrap">
<iframe id="nav" src="../class_list.html?1"></iframe>
<div id="resizer"></div>
</div>
<div id="main" tabindex="-1">
<div id="header">
<div id="menu">
<a href="../_index.html">Index (A)</a> »
<span class='title'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span>
»
<span class="title">Agent</span>
</div>
<div id="search">
<a class="full_list_link" id="class_list_link"
href="../class_list.html">
<svg width="24" height="24">
<rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
<rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
</svg>
</a>
</div>
<div class="clear"></div>
</div>
<div id="content"><h1>Class: Concurrent::Agent
</h1>
<div class="box_info">
<dl>
<dt>Inherits:</dt>
<dd>
<span class="inheritName"><span class='object_link'>Synchronization::LockableObject</span></span>
<ul class="fullTree">
<li>Object</li>
<li class="next"><span class='object_link'>Synchronization::LockableObject</span></li>
<li class="next">Concurrent::Agent</li>
</ul>
<a href="#" class="inheritanceTree">show all</a>
</dd>
</dl>
<dl>
<dt>Includes:</dt>
<dd><span class='object_link'><a href="Concern/Observable.html" title="Concurrent::Concern::Observable (module)">Concern::Observable</a></span></dd>
</dl>
<dl>
<dt>Defined in:</dt>
<dd>lib/concurrent/agent.rb</dd>
</dl>
</div>
<h2>Overview</h2><div class="docstring">
<div class="discussion">
<p><code>Agent</code> is inspired by Clojure's <a href="http://clojure.org/agents">agent</a>
function. An agent is a shared, mutable variable providing independent,
uncoordinated, <em>asynchronous</em> change of individual values. Best used when
the value will undergo frequent, complex updates. Suitable when the result
of an update does not need to be known immediately. <code>Agent</code> is (mostly)
functionally equivalent to Clojure's agent, except where the runtime
prevents parity.</p>
<p>Agents are reactive, not autonomous - there is no imperative message loop
and no blocking receive. The state of an Agent should be itself immutable
and the <code>#value</code> of an Agent is always immediately available for reading by
any thread without any messages, i.e. observation does not require
cooperation or coordination.</p>
<p>Agent action dispatches are made using the various <code>#send</code> methods. These
methods always return immediately. At some point later, in another thread,
the following will happen:</p>
<ol>
<li>The given <code>action</code> will be applied to the state of the Agent and the
<code>args</code>, if any were supplied.</li>
<li>The return value of <code>action</code> will be passed to the validator lambda,
if one has been set on the Agent.</li>
<li>If the validator succeeds or if no validator was given, the return value
of the given <code>action</code> will become the new <code>#value</code> of the Agent. See
<code>#initialize</code> for details.</li>
<li>If any observers were added to the Agent, they will be notified. See
<code>#add_observer</code> for details.</li>
<li>If during the <code>action</code> execution any other dispatches are made (directly
or indirectly), they will be held until after the <code>#value</code> of the Agent
has been changed.</li>
</ol>
<p>If any exceptions are thrown by an action function, no nested dispatches
will occur, and the exception will be cached in the Agent itself. When an
Agent has errors cached, any subsequent interactions will immediately throw
an exception, until the agent's errors are cleared. Agent errors can be
examined with <code>#error</code> and the agent restarted with <code>#restart</code>.</p>
<p>The actions of all Agents get interleaved amongst threads in a thread pool.
At any point in time, at most one action for each Agent is being executed.
Actions dispatched to an agent from another single agent or thread will
occur in the order they were sent, potentially interleaved with actions
dispatched to the same agent from other sources. The <code>#send</code> method should
be used for actions that are CPU limited, while the <code>#send_off</code> method is
appropriate for actions that may block on IO.</p>
<p>Unlike in Clojure, <code>Agent</code> cannot participate in <code>Concurrent::TVar</code> transactions.</p>
<h2>Example</h2>
<pre class="code ruby"><code class="ruby"><span class='kw'>def</span> <span class='id identifier rubyid_next_fibonacci'>next_fibonacci</span><span class='lparen'>(</span><span class='id identifier rubyid_set'>set</span> <span class='op'>=</span> <span class='kw'>nil</span><span class='rparen'>)</span>
<span class='kw'>return</span> <span class='lbracket'>[</span><span class='int'>0</span><span class='comma'>,</span> <span class='int'>1</span><span class='rbracket'>]</span> <span class='kw'>if</span> <span class='id identifier rubyid_set'>set</span><span class='period'>.</span><span class='id identifier rubyid_nil?'>nil?</span>
<span class='id identifier rubyid_set'>set</span> <span class='op'>+</span> <span class='lbracket'>[</span><span class='id identifier rubyid_set'>set</span><span class='lbracket'>[</span><span class='op'>-</span><span class='int'>2</span><span class='op'>..</span><span class='op'>-</span><span class='int'>1</span><span class='rbracket'>]</span><span class='period'>.</span><span class='id identifier rubyid_reduce'>reduce</span><span class='lbrace'>{</span><span class='op'>|</span><span class='id identifier rubyid_sum'>sum</span><span class='comma'>,</span><span class='id identifier rubyid_x'>x</span><span class='op'>|</span> <span class='id identifier rubyid_sum'>sum</span> <span class='op'>+</span> <span class='id identifier rubyid_x'>x</span> <span class='rbrace'>}</span><span class='rbracket'>]</span>
<span class='kw'>end</span>
<span class='comment'># create an agent with an initial value
</span><span class='id identifier rubyid_agent'>agent</span> <span class='op'>=</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'>Agent</span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="#initialize-instance_method" title="Concurrent::Agent#initialize (method)">new</a></span></span><span class='lparen'>(</span><span class='id identifier rubyid_next_fibonacci'>next_fibonacci</span><span class='rparen'>)</span>
<span class='comment'># send a few update requests
</span><span class='int'>5</span><span class='period'>.</span><span class='id identifier rubyid_times'>times</span> <span class='kw'>do</span>
<span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_send'>send</span><span class='lbrace'>{</span><span class='op'>|</span><span class='id identifier rubyid_set'>set</span><span class='op'>|</span> <span class='id identifier rubyid_next_fibonacci'>next_fibonacci</span><span class='lparen'>(</span><span class='id identifier rubyid_set'>set</span><span class='rparen'>)</span> <span class='rbrace'>}</span>
<span class='kw'>end</span>
<span class='comment'># wait for them to complete
</span><span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_await'>await</span>
<span class='comment'># get the current value
</span><span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span> <span class='comment'>#=> [0, 1, 1, 2, 3, 5, 8]
</span></code></pre>
<h2>Observation</h2>
<p>Agents support observers through the Observable mixin module.
Notification of observers occurs every time an action dispatch returns and
the new value is successfully validated. Observation will <em>not</em> occur if the
action raises an exception, if validation fails, or when a <span class='object_link'><a href="#restart-instance_method" title="Concurrent::Agent#restart (method)">#restart</a></span> occurs.</p>
<p>When notified the observer will receive three arguments: <code>time</code>, <code>old_value</code>,
and <code>new_value</code>. The <code>time</code> argument is the time at which the value change
occurred. The <code>old_value</code> is the value of the Agent when the action began
processing. The <code>new_value</code> is the value to which the Agent was set when the
action completed. Note that <code>old_value</code> and <code>new_value</code> may be the same.
This is not an error. It simply means that the action returned the same
value.</p>
<h2>Nested Actions</h2>
<p>It is possible for an Agent action to post further actions back to itself.
The nested actions will be enqueued normally then processed <em>after</em> the
outer action completes, in the order they were sent, possibly interleaved
with action dispatches from other threads. Nested actions never deadlock
with one another and a failure in a nested action will never affect the
outer action.</p>
<p>Nested actions can be called using the Agent reference from the enclosing
scope or by passing the reference in as a "send" argument. Nested actions
cannot be post using <code>self</code> from within the action block/proc/lambda; <code>self</code>
in this context will not reference the Agent. The preferred method for
dispatching nested actions is to pass the Agent as an argument. This allows
Ruby to more effectively manage the closing scope.</p>
<p>Prefer this:</p>
<pre class="code ruby"><code class="ruby"><span class='id identifier rubyid_agent'>agent</span> <span class='op'>=</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'>Agent</span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="#initialize-instance_method" title="Concurrent::Agent#initialize (method)">new</a></span></span><span class='lparen'>(</span><span class='int'>0</span><span class='rparen'>)</span>
<span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_send'>send</span><span class='lparen'>(</span><span class='id identifier rubyid_agent'>agent</span><span class='rparen'>)</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_value'>value</span><span class='comma'>,</span> <span class='id identifier rubyid_this'>this</span><span class='op'>|</span>
<span class='id identifier rubyid_this'>this</span><span class='period'>.</span><span class='id identifier rubyid_send'>send</span> <span class='lbrace'>{</span><span class='op'>|</span><span class='id identifier rubyid_v'>v</span><span class='op'>|</span> <span class='id identifier rubyid_v'>v</span> <span class='op'>+</span> <span class='int'>42</span> <span class='rbrace'>}</span>
<span class='float'>3.14</span>
<span class='kw'>end</span>
<span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span> <span class='comment'>#=> 45.14
</span></code></pre>
<p>Over this:</p>
<pre class="code ruby"><code class="ruby"><span class='id identifier rubyid_agent'>agent</span> <span class='op'>=</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'>Agent</span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="#initialize-instance_method" title="Concurrent::Agent#initialize (method)">new</a></span></span><span class='lparen'>(</span><span class='int'>0</span><span class='rparen'>)</span>
<span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_send'>send</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_value'>value</span><span class='op'>|</span>
<span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_send'>send</span> <span class='lbrace'>{</span><span class='op'>|</span><span class='id identifier rubyid_v'>v</span><span class='op'>|</span> <span class='id identifier rubyid_v'>v</span> <span class='op'>+</span> <span class='int'>42</span> <span class='rbrace'>}</span>
<span class='float'>3.14</span>
<span class='kw'>end</span>
</code></pre>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
<h2>Thread-safe Variable Classes</h2>
<p>Each of the thread-safe variable classes is designed to solve a different
problem. In general:</p>
<ul>
<li><em><span class='object_link'><a href="" title="Concurrent::Agent (class)">Agent</a></span>:</em> Shared, mutable variable providing independent,
uncoordinated, <em>asynchronous</em> change of individual values. Best used when
the value will undergo frequent, complex updates. Suitable when the result
of an update does not need to be known immediately.</li>
<li><em><span class='object_link'><a href="Atom.html" title="Concurrent::Atom (class)">Atom</a></span>:</em> Shared, mutable variable providing independent,
uncoordinated, <em>synchronous</em> change of individual values. Best used when
the value will undergo frequent reads but only occasional, though complex,
updates. Suitable when the result of an update must be known immediately.</li>
<li><em><span class='object_link'><a href="AtomicReference.html" title="Concurrent::AtomicReference (class)">AtomicReference</a></span>:</em> A simple object reference that can be
atomically. Updates are synchronous but fast. Best used when updates a
simple set operations. Not suitable when updates are complex.
<span class='object_link'><a href="AtomicBoolean.html" title="Concurrent::AtomicBoolean (class)">AtomicBoolean</a></span> and <span class='object_link'><a href="AtomicFixnum.html" title="Concurrent::AtomicFixnum (class)">AtomicFixnum</a></span> are similar
but optimized for the given data type.</li>
<li><em><span class='object_link'><a href="Exchanger.html" title="Concurrent::Exchanger (class)">Exchanger</a></span>:</em> Shared, stateless synchronization point. Used
when two or more threads need to exchange data. The threads will pair then
block on each other until the exchange is complete.</li>
<li><em><span class='object_link'><a href="MVar.html" title="Concurrent::MVar (class)">MVar</a></span>:</em> Shared synchronization point. Used when one thread
must give a value to another, which must take the value. The threads will
block on each other until the exchange is complete.</li>
<li><em><span class='object_link'><a href="ThreadLocalVar.html" title="Concurrent::ThreadLocalVar (class)">ThreadLocalVar</a></span>:</em> Shared, mutable, isolated variable which
holds a different value for each thread which has access. Often used as
an instance variable in objects which must maintain different state
for different threads.</li>
<li><em><span class='object_link'><a href="TVar.html" title="Concurrent::TVar (class)">TVar</a></span>:</em> Shared, mutable variables which provide
<em>coordinated</em>, <em>synchronous</em>, change of <em>many</em> stated. Used when multiple
value must change together, in an all-or-nothing transaction.</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">See Also:</p>
<ul class="see">
<li><a href="http://clojure.org/Agents" target="_parent" title="Clojure Agents">Clojure Agents</a></li>
<li><a href="http://clojure.org/state" target="_parent" title="Values and Change - Clojure's approach to Identity and State">Values and Change - Clojure's approach to Identity and State</a></li>
</ul>
</div><h2>Defined Under Namespace</h2>
<p class="children">
<strong class="classes">Classes:</strong> <span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span>, <span class='object_link'><a href="Agent/ValidationError.html" title="Concurrent::Agent::ValidationError (class)">ValidationError</a></span>
</p>
<h2>Instance Attribute Summary <small><a href="#" class="summary_toggle">collapse</a></small></h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#error_mode-instance_method" title="#error_mode (instance method)">#<strong>error_mode</strong> ⇒ undocumented </a>
</span>
<span class="note title readonly">readonly</span>
<span class="summary_desc"><div class='inline'><p>The error mode this Agent is operating in.</p>
</div></span>
</li>
</ul>
<h2>
Class Method Summary
<small><a href="#" class="summary_toggle">collapse</a></small>
</h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#await-class_method" title="await (class method)">.<strong>await</strong>(*agents) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread (indefinitely!) until all actions dispatched thus far to all the given Agents, from this thread or nested by the given Agents, have occurred.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#await_for-class_method" title="await_for (class method)">.<strong>await_for</strong>(timeout, *agents) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread until all actions dispatched thus far to all the given Agents, from this thread or nested by the given Agents, have occurred, or the timeout (in seconds) has elapsed.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#await_for!-class_method" title="await_for! (class method)">.<strong>await_for!</strong>(timeout, *agents) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread until all actions dispatched thus far to all the given Agents, from this thread or nested by the given Agents, have occurred, or the timeout (in seconds) has elapsed.</p>
</div></span>
</li>
</ul>
<h2>
Instance Method Summary
<small><a href="#" class="summary_toggle">collapse</a></small>
</h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#<<-instance_method" title="#<< (instance method)">#<strong><<</strong>(action) ⇒ Concurrent::Agent </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#add_observer-instance_method" title="#add_observer (instance method)">#<strong>add_observer</strong>(observer = nil, func = :update, &block) ⇒ Object </a>
</span>
<span class="note title not_defined_here">
included
from <span class='object_link'><a href="Concern/Observable.html#add_observer-instance_method" title="Concurrent::Concern::Observable#add_observer (method)">Concern::Observable</a></span>
</span>
<span class="summary_desc"><div class='inline'><p>Adds an observer to this set.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#await-instance_method" title="#await (instance method)">#<strong>await</strong> ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread (indefinitely!) until all actions dispatched thus far, from this thread or nested by the Agent, have occurred.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#await_for-instance_method" title="#await_for (instance method)">#<strong>await_for</strong>(timeout) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread until all actions dispatched thus far, from this thread or nested by the Agent, have occurred, or the timeout (in seconds) has elapsed.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#await_for!-instance_method" title="#await_for! (instance method)">#<strong>await_for!</strong>(timeout) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread until all actions dispatched thus far, from this thread or nested by the Agent, have occurred, or the timeout (in seconds) has elapsed.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#count_observers-instance_method" title="#count_observers (instance method)">#<strong>count_observers</strong> ⇒ Integer </a>
</span>
<span class="note title not_defined_here">
included
from <span class='object_link'><a href="Concern/Observable.html#count_observers-instance_method" title="Concurrent::Concern::Observable#count_observers (method)">Concern::Observable</a></span>
</span>
<span class="summary_desc"><div class='inline'><p>Return the number of observers associated with this object.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#delete_observer-instance_method" title="#delete_observer (instance method)">#<strong>delete_observer</strong>(observer) ⇒ Object </a>
</span>
<span class="note title not_defined_here">
included
from <span class='object_link'><a href="Concern/Observable.html#delete_observer-instance_method" title="Concurrent::Concern::Observable#delete_observer (method)">Concern::Observable</a></span>
</span>
<span class="summary_desc"><div class='inline'><p>Remove <code>observer</code> as an observer on this object so that it will no longer receive notifications.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#delete_observers-instance_method" title="#delete_observers (instance method)">#<strong>delete_observers</strong> ⇒ Observable </a>
</span>
<span class="note title not_defined_here">
included
from <span class='object_link'><a href="Concern/Observable.html#delete_observers-instance_method" title="Concurrent::Concern::Observable#delete_observers (method)">Concern::Observable</a></span>
</span>
<span class="summary_desc"><div class='inline'><p>Remove all observers associated with this object.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#error-instance_method" title="#error (instance method)">#<strong>error</strong> ⇒ nil, Error </a>
(also: #reason)
</span>
<span class="summary_desc"><div class='inline'><p>When <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span> and <span class='object_link'><a href="#error_mode-instance_method" title="Concurrent::Agent#error_mode (method)">#error_mode</a></span> is <code>:fail</code>, returns the error object which caused the failure, else <code>nil</code>.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#failed%3F-instance_method" title="#failed? (instance method)">#<strong>failed?</strong> ⇒ Boolean </a>
(also: #stopped?)
</span>
<span class="summary_desc"><div class='inline'><p>Is the Agent in a failed state?.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#initialize-instance_method" title="#initialize (instance method)">#<strong>initialize</strong>(initial, opts = {}) ⇒ Agent </a>
</span>
<span class="note title constructor">constructor</span>
<span class="summary_desc"><div class='inline'><p>Create a new <code>Agent</code> with the given initial value and options.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#restart-instance_method" title="#restart (instance method)">#<strong>restart</strong>(new_value, opts = {}) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>When an Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>, changes the Agent <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> to <code>new_value</code> then un-fails the Agent so that action dispatches are allowed again.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send-instance_method" title="#send (instance method)">#<strong>send</strong>(*args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send!-instance_method" title="#send! (instance method)">#<strong>send!</strong>(*args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send_off-instance_method" title="#send_off (instance method)">#<strong>send_off</strong>(*args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
(also: #post)
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send_off!-instance_method" title="#send_off! (instance method)">#<strong>send_off!</strong>(*args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send_via-instance_method" title="#send_via (instance method)">#<strong>send_via</strong>(executor, *args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#send_via!-instance_method" title="#send_via! (instance method)">#<strong>send_via!</strong>(executor, *args, &action) {|agent, value, *args| ... } ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Dispatches an action to the Agent and returns immediately.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#value-instance_method" title="#value (instance method)">#<strong>value</strong> ⇒ Object </a>
(also: #deref)
</span>
<span class="summary_desc"><div class='inline'><p>The current value (state) of the Agent, irrespective of any pending or in-progress actions.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#wait-instance_method" title="#wait (instance method)">#<strong>wait</strong>(timeout = nil) ⇒ Boolean </a>
</span>
<span class="summary_desc"><div class='inline'><p>Blocks the current thread until all actions dispatched thus far, from this thread or nested by the Agent, have occurred, or the timeout (in seconds) has elapsed.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#with_observer-instance_method" title="#with_observer (instance method)">#<strong>with_observer</strong>(observer = nil, func = :update, &block) ⇒ Observable </a>
</span>
<span class="note title not_defined_here">
included
from <span class='object_link'><a href="Concern/Observable.html#with_observer-instance_method" title="Concurrent::Concern::Observable#with_observer (method)">Concern::Observable</a></span>
</span>
<span class="summary_desc"><div class='inline'><p>As <code>#add_observer</code> but can be used for chaining.</p>
</div></span>
</li>
</ul>
<div id="constructor_details" class="method_details_list">
<h2>Constructor Details</h2>
<div class="method_details first">
<h3 class="signature first" id="initialize-instance_method">
#<strong>initialize</strong>(initial, opts = {}) ⇒ <tt><span class='object_link'><a href="" title="Concurrent::Agent (class)">Agent</a></span></tt>
</h3><div class="docstring">
<div class="discussion">
<p>Create a new <code>Agent</code> with the given initial value and options.</p>
<p>The <code>:validator</code> option must be <code>nil</code> or a side-effect free proc/lambda
which takes one argument. On any intended value change the validator, if
provided, will be called. If the new value is invalid the validator should
return <code>false</code> or raise an error.</p>
<p>The <code>:error_handler</code> option must be <code>nil</code> or a proc/lambda which takes two
arguments. When an action raises an error or validation fails, either by
returning false or raising an error, the error handler will be called. The
arguments to the error handler will be a reference to the agent itself and
the error object which was raised.</p>
<p>The <code>:error_mode</code> may be either <code>:continue</code> (the default if an error
handler is given) or <code>:fail</code> (the default if error handler nil or not
given).</p>
<p>If an action being run by the agent throws an error or doesn't pass
validation the error handler, if present, will be called. After the
handler executes if the error mode is <code>:continue</code> the Agent will continue
as if neither the action that caused the error nor the error itself ever
happened.</p>
<p>If the mode is <code>:fail</code> the Agent will become <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span> and will stop
accepting new action dispatches. Any previously queued actions will be
held until <span class='object_link'><a href="#restart-instance_method" title="Concurrent::Agent#restart (method)">#restart</a></span> is called. The <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> method will still work,
returning the value of the Agent before the error.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>initial</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the initial value</p>
</div>
</li>
<li>
<span class='name'>opts</span>
<span class='type'>(<tt><span class='object_link'><a href="Hash.html" title="Concurrent::Hash (class)">Hash</a></span></tt>)</span>
<em class="default">(defaults to: <tt>{}</tt>)</em>
—
<div class='inline'><p>the configuration options</p>
</div>
</li>
</ul>
<p class="tag_title">Options Hash (<tt>opts</tt>):</p>
<ul class="option">
<li>
<span class="name">:error_mode</span>
<span class="type">(<tt>Symbol</tt>)</span>
<span class="default">
</span>
— <div class='inline'><p>either <code>:continue</code> or <code>:fail</code></p>
</div>
</li>
<li>
<span class="name">:error_handler</span>
<span class="type">(<tt>nil</tt>, <tt>Proc</tt>)</span>
<span class="default">
</span>
— <div class='inline'><p>the (optional) error handler</p>
</div>
</li>
<li>
<span class="name">:validator</span>
<span class="type">(<tt>nil</tt>, <tt>Proc</tt>)</span>
<span class="default">
</span>
— <div class='inline'><p>the (optional) validation procedure</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
219
220
221
222</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 219</span>
<span class='kw'>def</span> <span class='id identifier rubyid_initialize'>initialize</span><span class='lparen'>(</span><span class='id identifier rubyid_initial'>initial</span><span class='comma'>,</span> <span class='id identifier rubyid_opts'>opts</span> <span class='op'>=</span> <span class='lbrace'>{</span><span class='rbrace'>}</span><span class='rparen'>)</span>
<span class='kw'>super</span><span class='lparen'>(</span><span class='rparen'>)</span>
<span class='id identifier rubyid_synchronize'>synchronize</span> <span class='lbrace'>{</span> <span class='id identifier rubyid_ns_initialize'>ns_initialize</span><span class='lparen'>(</span><span class='id identifier rubyid_initial'>initial</span><span class='comma'>,</span> <span class='id identifier rubyid_opts'>opts</span><span class='rparen'>)</span> <span class='rbrace'>}</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
<div id="instance_attr_details" class="attr_details">
<h2>Instance Attribute Details</h2>
<span id=""></span>
<div class="method_details first">
<h3 class="signature first" id="error_mode-instance_method">
#<strong>error_mode</strong> ⇒ <tt>undocumented</tt> <span class="extras">(readonly)</span>
</h3><div class="docstring">
<div class="discussion">
<p>The error mode this Agent is operating in. See <span class='object_link'><a href="#initialize-instance_method" title="Concurrent::Agent#initialize (method)">#initialize</a></span> for details.</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
183
184
185</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 183</span>
<span class='kw'>def</span> <span class='id identifier rubyid_error_mode'>error_mode</span>
<span class='ivar'>@error_mode</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
<div id="class_method_details" class="method_details_list">
<h2>Class Method Details</h2>
<div class="method_details first">
<h3 class="signature first" id="await-class_method">
.<strong>await</strong>(*agents) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread (indefinitely!) until all actions dispatched
thus far to all the given Agents, from this thread or nested by the
given Agents, have occurred. Will block when any of the agents are
failed. Will never return if a failed Agent is restart with
<code>:clear_actions</code> true.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>agents</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><<span class='object_link'><a href="" title="Concurrent::Agent (class)">Concurrent::Agent</a></span>></tt>)</span>
—
<div class='inline'><p>the Agents on which to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
448
449
450
451</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 448</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await'>await</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_agents'>agents</span><span class='rparen'>)</span>
<span class='id identifier rubyid_agents'>agents</span><span class='period'>.</span><span class='id identifier rubyid_each'>each</span> <span class='lbrace'>{</span> <span class='op'>|</span><span class='id identifier rubyid_agent'>agent</span><span class='op'>|</span> <span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_await'>await</span> <span class='rbrace'>}</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="await_for-class_method">
.<strong>await_for</strong>(timeout, *agents) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread until all actions dispatched thus far to all
the given Agents, from this thread or nested by the given Agents, have
occurred, or the timeout (in seconds) has elapsed.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>timeout</span>
<span class='type'>(<tt>Float</tt>)</span>
—
<div class='inline'><p>the maximum number of seconds to wait</p>
</div>
</li>
<li>
<span class='name'>agents</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><<span class='object_link'><a href="" title="Concurrent::Agent (class)">Concurrent::Agent</a></span>></tt>)</span>
—
<div class='inline'><p>the Agents on which to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if all actions complete before timeout else false</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
462
463
464
465
466
467
468
469</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 462</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await_for'>await_for</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_agents'>agents</span><span class='rparen'>)</span>
<span class='id identifier rubyid_end_at'>end_at</span> <span class='op'>=</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='period'>.</span><span class='id identifier rubyid_monotonic_time'><span class='object_link'><a href="../Concurrent.html#monotonic_time-class_method" title="Concurrent.monotonic_time (method)">monotonic_time</a></span></span> <span class='op'>+</span> <span class='id identifier rubyid_timeout'>timeout</span><span class='period'>.</span><span class='id identifier rubyid_to_f'>to_f</span>
<span class='id identifier rubyid_ok'>ok</span> <span class='op'>=</span> <span class='id identifier rubyid_agents'>agents</span><span class='period'>.</span><span class='id identifier rubyid_length'>length</span><span class='period'>.</span><span class='id identifier rubyid_times'>times</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_i'>i</span><span class='op'>|</span>
<span class='kw'>break</span> <span class='kw'>false</span> <span class='kw'>if</span> <span class='lparen'>(</span><span class='id identifier rubyid_delay'>delay</span> <span class='op'>=</span> <span class='id identifier rubyid_end_at'>end_at</span> <span class='op'>-</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='period'>.</span><span class='id identifier rubyid_monotonic_time'><span class='object_link'><a href="../Concurrent.html#monotonic_time-class_method" title="Concurrent.monotonic_time (method)">monotonic_time</a></span></span><span class='rparen'>)</span> <span class='op'><</span> <span class='int'>0</span>
<span class='kw'>break</span> <span class='kw'>false</span> <span class='kw'>unless</span> <span class='id identifier rubyid_agents'>agents</span><span class='lbracket'>[</span><span class='id identifier rubyid_i'>i</span><span class='rbracket'>]</span><span class='period'>.</span><span class='id identifier rubyid_await_for'>await_for</span><span class='lparen'>(</span><span class='id identifier rubyid_delay'>delay</span><span class='rparen'>)</span>
<span class='kw'>end</span>
<span class='op'>!</span><span class='op'>!</span><span class='id identifier rubyid_ok'>ok</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="await_for!-class_method">
.<strong>await_for!</strong>(timeout, *agents) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread until all actions dispatched thus far to all
the given Agents, from this thread or nested by the given Agents, have
occurred, or the timeout (in seconds) has elapsed.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>timeout</span>
<span class='type'>(<tt>Float</tt>)</span>
—
<div class='inline'><p>the maximum number of seconds to wait</p>
</div>
</li>
<li>
<span class='name'>agents</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><<span class='object_link'><a href="" title="Concurrent::Agent (class)">Concurrent::Agent</a></span>></tt>)</span>
—
<div class='inline'><p>the Agents on which to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if all actions complete before timeout</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt><span class='object_link'><a href="../Concurrent.html#TimeoutError-constant" title="Concurrent::TimeoutError (constant)">Concurrent::TimeoutError</a></span></tt>)</span>
—
<div class='inline'><p>when timout is reached</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
481
482
483
484</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 481</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await_for!'>await_for!</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_agents'>agents</span><span class='rparen'>)</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'><span class='object_link'><a href="../Concurrent.html#TimeoutError-constant" title="Concurrent::TimeoutError (constant)">TimeoutError</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_await_for'>await_for</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_agents'>agents</span><span class='rparen'>)</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
<div id="instance_method_details" class="method_details_list">
<h2>Instance Method Details</h2>
<div class="method_details first">
<h3 class="signature first" id="<<-instance_method">
#<strong><<</strong>(action) ⇒ <tt><span class='object_link'><a href="" title="Concurrent::Agent (class)">Concurrent::Agent</a></span></tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Appropriate for actions that may block on IO.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt><span class='object_link'><a href="" title="Concurrent::Agent (class)">Concurrent::Agent</a></span></tt>)</span>
—
<div class='inline'><p>self</p>
</div>
</li>
</ul>
<p class="tag_title">See Also:</p>
<ul class="see">
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span></li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
330
331
332
333</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 330</span>
<span class='kw'>def</span> <span class='op'><<</span><span class='lparen'>(</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_send_off'>send_off</span><span class='lparen'>(</span><span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='kw'>self</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="add_observer-instance_method">
#<strong>add_observer</strong>(observer = nil, func = :update, &block) ⇒ <tt>Object</tt>
<span class="not_defined_here">
Originally defined in module
<span class='object_link'><a href="Concern/Observable.html#add_observer-instance_method" title="Concurrent::Concern::Observable#add_observer (method)">Concern::Observable</a></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Adds an observer to this set. If a block is passed, the observer will be
created by this method and no other params should be passed.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>observer</span>
<span class='type'>(<tt>Object</tt>)</span>
<em class="default">(defaults to: <tt>nil</tt>)</em>
—
<div class='inline'><p>the observer to add</p>
</div>
</li>
<li>
<span class='name'>func</span>
<span class='type'>(<tt>Symbol</tt>)</span>
<em class="default">(defaults to: <tt>:update</tt>)</em>
—
<div class='inline'><p>the function to call on the observer during notification.
Default is :update</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the added observer</p>
</div>
</li>
</ul>
</div>
</div>
<div class="method_details ">
<h3 class="signature " id="await-instance_method">
#<strong>await</strong> ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread (indefinitely!) until all actions dispatched
thus far, from this thread or nested by the Agent, have occurred. Will
block when <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>. Will never return if a failed Agent is <span class='object_link'><a href="#restart-instance_method" title="Concurrent::Agent#restart (method)">#restart</a></span>
with <code>:clear_actions</code> true.</p>
<p>Returns a reference to <code>self</code> to support method chaining:</p>
<pre class="code ruby"><code class="ruby"><span class='id identifier rubyid_current_value'>current_value</span> <span class='op'>=</span> <span class='id identifier rubyid_agent'>agent</span><span class='period'>.</span><span class='id identifier rubyid_await'>await</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span>
</code></pre>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>self</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
349
350
351
352</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 349</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await'>await</span>
<span class='id identifier rubyid_wait'>wait</span><span class='lparen'>(</span><span class='kw'>nil</span><span class='rparen'>)</span>
<span class='kw'>self</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="await_for-instance_method">
#<strong>await_for</strong>(timeout) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread until all actions dispatched thus far, from this
thread or nested by the Agent, have occurred, or the timeout (in seconds)
has elapsed.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>timeout</span>
<span class='type'>(<tt>Float</tt>)</span>
—
<div class='inline'><p>the maximum number of seconds to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if all actions complete before timeout else false</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
362
363
364</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 362</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await_for'>await_for</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='rparen'>)</span>
<span class='id identifier rubyid_wait'>wait</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='period'>.</span><span class='id identifier rubyid_to_f'>to_f</span><span class='rparen'>)</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="await_for!-instance_method">
#<strong>await_for!</strong>(timeout) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread until all actions dispatched thus far, from this
thread or nested by the Agent, have occurred, or the timeout (in seconds)
has elapsed.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>timeout</span>
<span class='type'>(<tt>Float</tt>)</span>
—
<div class='inline'><p>the maximum number of seconds to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if all actions complete before timeout</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt><span class='object_link'><a href="../Concurrent.html#TimeoutError-constant" title="Concurrent::TimeoutError (constant)">Concurrent::TimeoutError</a></span></tt>)</span>
—
<div class='inline'><p>when timout is reached</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
376
377
378
379</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 376</span>
<span class='kw'>def</span> <span class='id identifier rubyid_await_for!'>await_for!</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='rparen'>)</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'><span class='object_link'><a href="../Concurrent.html#TimeoutError-constant" title="Concurrent::TimeoutError (constant)">TimeoutError</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_wait'>wait</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='period'>.</span><span class='id identifier rubyid_to_f'>to_f</span><span class='rparen'>)</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="count_observers-instance_method">
#<strong>count_observers</strong> ⇒ <tt>Integer</tt>
<span class="not_defined_here">
Originally defined in module
<span class='object_link'><a href="Concern/Observable.html#count_observers-instance_method" title="Concurrent::Concern::Observable#count_observers (method)">Concern::Observable</a></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Return the number of observers associated with this object.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Integer</tt>)</span>
—
<div class='inline'><p>the observers count</p>
</div>
</li>
</ul>
</div>
</div>
<div class="method_details ">
<h3 class="signature " id="delete_observer-instance_method">
#<strong>delete_observer</strong>(observer) ⇒ <tt>Object</tt>
<span class="not_defined_here">
Originally defined in module
<span class='object_link'><a href="Concern/Observable.html#delete_observer-instance_method" title="Concurrent::Concern::Observable#delete_observer (method)">Concern::Observable</a></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Remove <code>observer</code> as an observer on this object so that it will no
longer receive notifications.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>observer</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the observer to remove</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the deleted observer</p>
</div>
</li>
</ul>
</div>
</div>
<div class="method_details ">
<h3 class="signature " id="delete_observers-instance_method">
#<strong>delete_observers</strong> ⇒ <tt><span class='object_link'><a href="Concern/Observable.html" title="Concurrent::Concern::Observable (module)">Observable</a></span></tt>
<span class="not_defined_here">
Originally defined in module
<span class='object_link'><a href="Concern/Observable.html#delete_observers-instance_method" title="Concurrent::Concern::Observable#delete_observers (method)">Concern::Observable</a></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Remove all observers associated with this object.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt><span class='object_link'><a href="Concern/Observable.html" title="Concurrent::Concern::Observable (module)">Observable</a></span></tt>)</span>
—
<div class='inline'><p>self</p>
</div>
</li>
</ul>
</div>
</div>
<div class="method_details ">
<h3 class="signature " id="error-instance_method">
#<strong>error</strong> ⇒ <tt>nil</tt>, <tt><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></tt>
<span class="aliases">Also known as:
<span class="names"><span id='reason-instance_method'>reason</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>When <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span> and <span class='object_link'><a href="#error_mode-instance_method" title="Concurrent::Agent#error_mode (method)">#error_mode</a></span> is <code>:fail</code>, returns the error object
which caused the failure, else <code>nil</code>. When <span class='object_link'><a href="#error_mode-instance_method" title="Concurrent::Agent#error_mode (method)">#error_mode</a></span> is <code>:continue</code>
will <em>always</em> return <code>nil</code>.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>nil</tt>, <tt><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></tt>)</span>
—
<div class='inline'><p>the error which caused the failure when <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
239
240
241</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 239</span>
<span class='kw'>def</span> <span class='id identifier rubyid_error'>error</span>
<span class='ivar'>@error</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="failed?-instance_method">
#<strong>failed?</strong> ⇒ <tt>Boolean</tt>
<span class="aliases">Also known as:
<span class="names"><span id='stopped?-instance_method'>stopped?</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Is the Agent in a failed state?</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
</li>
</ul>
<p class="tag_title">See Also:</p>
<ul class="see">
<li><span class='object_link'><a href="#restart-instance_method" title="Concurrent::Agent#restart (method)">#restart</a></span></li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
401
402
403</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 401</span>
<span class='kw'>def</span> <span class='id identifier rubyid_failed?'>failed?</span>
<span class='op'>!</span><span class='ivar'>@error</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span><span class='period'>.</span><span class='id identifier rubyid_nil?'>nil?</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="restart-instance_method">
#<strong>restart</strong>(new_value, opts = {}) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>When an Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>, changes the Agent <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> to <code>new_value</code>
then un-fails the Agent so that action dispatches are allowed again. If
the <code>:clear_actions</code> option is give and true, any actions queued on the
Agent that were being held while it was failed will be discarded,
otherwise those held actions will proceed. The <code>new_value</code> must pass the
validator if any, or <code>restart</code> will raise an exception and the Agent will
remain failed with its old <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> and <span class='object_link'><a href="#error-instance_method" title="Concurrent::Agent#error (method)">#error</a></span>. Observers, if any, will
not be notified of the new state.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>new_value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value for the Agent once restarted</p>
</div>
</li>
<li>
<span class='name'>opts</span>
<span class='type'>(<tt><span class='object_link'><a href="Hash.html" title="Concurrent::Hash (class)">Hash</a></span></tt>)</span>
<em class="default">(defaults to: <tt>{}</tt>)</em>
—
<div class='inline'><p>the configuration options</p>
</div>
</li>
</ul>
<p class="tag_title">Options Hash (<tt>opts</tt>):</p>
<ul class="option">
<li>
<span class="name">:clear_actions</span>
<span class="type">(<tt>Symbol</tt>)</span>
<span class="default">
</span>
— <div class='inline'><p>true if all enqueued but unprocessed
actions should be discarded on restart, else false (default: false)</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt>Concurrent:AgentError</tt>)</span>
—
<div class='inline'><p>when not failed</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
423
424
425
426
427
428
429
430
431
432
433
434</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 423</span>
<span class='kw'>def</span> <span class='id identifier rubyid_restart'>restart</span><span class='lparen'>(</span><span class='id identifier rubyid_new_value'>new_value</span><span class='comma'>,</span> <span class='id identifier rubyid_opts'>opts</span> <span class='op'>=</span> <span class='lbrace'>{</span><span class='rbrace'>}</span><span class='rparen'>)</span>
<span class='id identifier rubyid_clear_actions'>clear_actions</span> <span class='op'>=</span> <span class='id identifier rubyid_opts'>opts</span><span class='period'>.</span><span class='id identifier rubyid_fetch'>fetch</span><span class='lparen'>(</span><span class='symbol'>:clear_actions</span><span class='comma'>,</span> <span class='kw'>false</span><span class='rparen'>)</span>
<span class='id identifier rubyid_synchronize'>synchronize</span> <span class='kw'>do</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="Agent/Error.html#initialize-instance_method" title="Concurrent::Agent::Error#initialize (method)">new</a></span></span><span class='lparen'>(</span><span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>agent is not failed</span><span class='tstring_end'>'</span></span><span class='rparen'>)</span> <span class='kw'>unless</span> <span class='id identifier rubyid_failed?'>failed?</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="Agent/ValidationError.html" title="Concurrent::Agent::ValidationError (class)">ValidationError</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_ns_validate'>ns_validate</span><span class='lparen'>(</span><span class='id identifier rubyid_new_value'>new_value</span><span class='rparen'>)</span>
<span class='ivar'>@current</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span> <span class='op'>=</span> <span class='id identifier rubyid_new_value'>new_value</span>
<span class='ivar'>@error</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span> <span class='op'>=</span> <span class='kw'>nil</span>
<span class='ivar'>@queue</span><span class='period'>.</span><span class='id identifier rubyid_clear'>clear</span> <span class='kw'>if</span> <span class='id identifier rubyid_clear_actions'>clear_actions</span>
<span class='id identifier rubyid_ns_post_next_job'>ns_post_next_job</span> <span class='kw'>unless</span> <span class='ivar'>@queue</span><span class='period'>.</span><span class='id identifier rubyid_empty?'>empty?</span>
<span class='kw'>end</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send-instance_method">
#<strong>send</strong>(*args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued, false if
the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
277
278
279</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 277</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send'>send</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_enqueue_action_job'>enqueue_action_job</span><span class='lparen'>(</span><span class='id identifier rubyid_action'>action</span><span class='comma'>,</span> <span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='period'>.</span><span class='id identifier rubyid_global_fast_executor'><span class='object_link'><a href="../Concurrent.html#global_fast_executor-class_method" title="Concurrent.global_fast_executor (method)">global_fast_executor</a></span></span><span class='rparen'>)</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send!-instance_method">
#<strong>send!</strong>(*args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Concurrent::Agent::Error</a></span></tt>)</span>
—
<div class='inline'><p>if the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
286
287
288
289</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 286</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send!'>send!</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="Agent/Error.html#initialize-instance_method" title="Concurrent::Agent::Error#initialize (method)">new</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_send'>send</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send_off-instance_method">
#<strong>send_off</strong>(*args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
<span class="aliases">Also known as:
<span class="names"><span id='post-instance_method'>post</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued, false if
the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
293
294
295</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 293</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send_off'>send_off</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_enqueue_action_job'>enqueue_action_job</span><span class='lparen'>(</span><span class='id identifier rubyid_action'>action</span><span class='comma'>,</span> <span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='period'>.</span><span class='id identifier rubyid_global_io_executor'><span class='object_link'><a href="../Concurrent.html#global_io_executor-class_method" title="Concurrent.global_io_executor (method)">global_io_executor</a></span></span><span class='rparen'>)</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send_off!-instance_method">
#<strong>send_off!</strong>(*args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Concurrent::Agent::Error</a></span></tt>)</span>
—
<div class='inline'><p>if the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
301
302
303
304</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 301</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send_off!'>send_off!</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="Agent/Error.html#initialize-instance_method" title="Concurrent::Agent::Error#initialize (method)">new</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_send_off'>send_off</span><span class='lparen'>(</span><span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send_via-instance_method">
#<strong>send_via</strong>(executor, *args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
<li>
<span class='name'>executor</span>
<span class='type'>(<tt><span class='object_link'>Concurrent::ExecutorService</span></tt>)</span>
—
<div class='inline'><p>the executor on which the
action is to be dispatched</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued, false if
the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
310
311
312</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 310</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send_via'>send_via</span><span class='lparen'>(</span><span class='id identifier rubyid_executor'>executor</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_enqueue_action_job'>enqueue_action_job</span><span class='lparen'>(</span><span class='id identifier rubyid_action'>action</span><span class='comma'>,</span> <span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='id identifier rubyid_executor'>executor</span><span class='rparen'>)</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="send_via!-instance_method">
#<strong>send_via!</strong>(executor, *args, &action) {|agent, value, *args| ... } ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Dispatches an action to the Agent and returns immediately. Subsequently,
in a thread from a thread pool, the <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> will be set to the return
value of the action. Action dispatches are only allowed when the Agent
is not <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span>.</p>
<p>The action must be a block/proc/lambda which takes 1 or more arguments.
The first argument is the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent. Any arguments
passed to the send method via the <code>args</code> parameter will be passed to the
action as the remaining arguments. The action must return the new value
of the Agent.</p>
<ul>
<li><span class='object_link'><a href="#send-instance_method" title="Concurrent::Agent#send (method)">#send</a></span> and <span class='object_link'><a href="#send!-instance_method" title="Concurrent::Agent#send! (method)">#send!</a></span> should be used for actions that are CPU limited</li>
<li><span class='object_link'><a href="#send_off-instance_method" title="Concurrent::Agent#send_off (method)">#send_off</a></span>, <span class='object_link'><a href="#send_off!-instance_method" title="Concurrent::Agent#send_off! (method)">#send_off!</a></span>, and <span class='object_link'><a href="#<<-instance_method" title="Concurrent::Agent#<< (method)">#<<</a></span> are appropriate for actions that
may block on IO</li>
<li><span class='object_link'><a href="#send_via-instance_method" title="Concurrent::Agent#send_via (method)">#send_via</a></span> and <span class='object_link'><a href="#send_via!-instance_method" title="Concurrent::Agent#send_via! (method)">#send_via!</a></span> are used when a specific executor is to
be used for the action</li>
</ul>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to be passed to
the action</p>
</div>
</li>
<li>
<span class='name'>action</span>
<span class='type'>(<tt>Proc</tt>)</span>
—
<div class='inline'><p>the action dispatch to be enqueued</p>
</div>
</li>
<li>
<span class='name'>executor</span>
<span class='type'>(<tt><span class='object_link'>Concurrent::ExecutorService</span></tt>)</span>
—
<div class='inline'><p>the executor on which the
action is to be dispatched</p>
</div>
</li>
</ul>
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>agent</tt>, <tt><span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">value</a></span></tt>, <tt>*args</tt>)</span>
—
<div class='inline'><p>process the old value and return the new</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>value</span>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current <span class='object_link'><a href="#value-instance_method" title="Concurrent::Agent#value (method)">#value</a></span> of the Agent</p>
</div>
</li>
<li>
<span class='name'>args</span>
<span class='type'>(<tt><span class='object_link'><a href="Array.html" title="Concurrent::Array (class)">Array</a></span><Object></tt>)</span>
—
<div class='inline'><p>zero or more arguments to pass to the
action</p>
</div>
</li>
</ul>
<p class="tag_title">Yield Returns:</p>
<ul class="yieldreturn">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the new value of the Agent</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if the action is successfully enqueued</p>
</div>
</li>
</ul>
<p class="tag_title">Raises:</p>
<ul class="raise">
<li>
<span class='type'>(<tt><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Concurrent::Agent::Error</a></span></tt>)</span>
—
<div class='inline'><p>if the Agent is <span class='object_link'><a href="#failed%3F-instance_method" title="Concurrent::Agent#failed? (method)">#failed?</a></span></p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
318
319
320
321</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 318</span>
<span class='kw'>def</span> <span class='id identifier rubyid_send_via!'>send_via!</span><span class='lparen'>(</span><span class='id identifier rubyid_executor'>executor</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'><span class='object_link'><a href="Agent/Error.html" title="Concurrent::Agent::Error (class)">Error</a></span></span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="Agent/Error.html#initialize-instance_method" title="Concurrent::Agent::Error#initialize (method)">new</a></span></span> <span class='kw'>unless</span> <span class='id identifier rubyid_send_via'>send_via</span><span class='lparen'>(</span><span class='id identifier rubyid_executor'>executor</span><span class='comma'>,</span> <span class='op'>*</span><span class='id identifier rubyid_args'>args</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_action'>action</span><span class='rparen'>)</span>
<span class='kw'>true</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="value-instance_method">
#<strong>value</strong> ⇒ <tt>Object</tt>
<span class="aliases">Also known as:
<span class="names"><span id='deref-instance_method'>deref</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>The current value (state) of the Agent, irrespective of any pending or
in-progress actions. The value is always available and is non-blocking.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Object</tt>)</span>
—
<div class='inline'><p>the current value</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
228
229
230</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 228</span>
<span class='kw'>def</span> <span class='id identifier rubyid_value'>value</span>
<span class='ivar'>@current</span><span class='period'>.</span><span class='id identifier rubyid_value'>value</span> <span class='comment'># TODO (pitr 12-Sep-2015): broken unsafe read?
</span><span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="wait-instance_method">
#<strong>wait</strong>(timeout = nil) ⇒ <tt>Boolean</tt>
</h3><div class="docstring">
<div class="discussion">
<p>Blocks the current thread until all actions dispatched thus far, from this
thread or nested by the Agent, have occurred, or the timeout (in seconds)
has elapsed. Will block indefinitely when timeout is nil or not given.</p>
<p>Provided mainly for consistency with other classes in this library. Prefer
the various <code>await</code> methods instead.</p>
<p><strong>NOTE</strong> Never, <em>under any circumstances</em>, call any of the "await" methods
(<span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span>, <span class='object_link'><a href="#await_for-instance_method" title="Concurrent::Agent#await_for (method)">#await_for</a></span>, <span class='object_link'><a href="#await_for!-instance_method" title="Concurrent::Agent#await_for! (method)">#await_for!</a></span>, and <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span>) from within an action
block/proc/lambda. The call will block the Agent and will always fail.
Calling either <span class='object_link'><a href="#await-instance_method" title="Concurrent::Agent#await (method)">#await</a></span> or <span class='object_link'><a href="#wait-instance_method" title="Concurrent::Agent#wait (method)">#wait</a></span> (with a timeout of <code>nil</code>) will
hopelessly deadlock the Agent with no possibility of recovery.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>timeout</span>
<span class='type'>(<tt>Float</tt>)</span>
<em class="default">(defaults to: <tt>nil</tt>)</em>
—
<div class='inline'><p>the maximum number of seconds to wait</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
—
<div class='inline'><p>true if all actions complete before timeout else false</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
392
393
394
395
396</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'lib/concurrent/agent.rb', line 392</span>
<span class='kw'>def</span> <span class='id identifier rubyid_wait'>wait</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span> <span class='op'>=</span> <span class='kw'>nil</span><span class='rparen'>)</span>
<span class='id identifier rubyid_latch'>latch</span> <span class='op'>=</span> <span class='const'><span class='object_link'><a href="../Concurrent.html" title="Concurrent (module)">Concurrent</a></span></span><span class='op'>::</span><span class='const'><span class='object_link'><a href="CountDownLatch.html" title="Concurrent::CountDownLatch (class)">CountDownLatch</a></span></span><span class='period'>.</span><span class='id identifier rubyid_new'><span class='object_link'><a href="CountDownLatch.html#initialize-instance_method" title="Concurrent::CountDownLatch#initialize (method)">new</a></span></span><span class='lparen'>(</span><span class='int'>1</span><span class='rparen'>)</span>
<span class='id identifier rubyid_enqueue_await_job'>enqueue_await_job</span><span class='lparen'>(</span><span class='id identifier rubyid_latch'>latch</span><span class='rparen'>)</span>
<span class='id identifier rubyid_latch'>latch</span><span class='period'>.</span><span class='id identifier rubyid_wait'>wait</span><span class='lparen'>(</span><span class='id identifier rubyid_timeout'>timeout</span><span class='rparen'>)</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="with_observer-instance_method">
#<strong>with_observer</strong>(observer = nil, func = :update, &block) ⇒ <tt><span class='object_link'><a href="Concern/Observable.html" title="Concurrent::Concern::Observable (module)">Observable</a></span></tt>
<span class="not_defined_here">
Originally defined in module
<span class='object_link'><a href="Concern/Observable.html#with_observer-instance_method" title="Concurrent::Concern::Observable#with_observer (method)">Concern::Observable</a></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>As <code>#add_observer</code> but can be used for chaining.</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Parameters:</p>
<ul class="param">
<li>
<span class='name'>observer</span>
<span class='type'>(<tt>Object</tt>)</span>
<em class="default">(defaults to: <tt>nil</tt>)</em>
—
<div class='inline'><p>the observer to add</p>
</div>
</li>
<li>
<span class='name'>func</span>
<span class='type'>(<tt>Symbol</tt>)</span>
<em class="default">(defaults to: <tt>:update</tt>)</em>
—
<div class='inline'><p>the function to call on the observer during notification.</p>
</div>
</li>
</ul>
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt><span class='object_link'><a href="Concern/Observable.html" title="Concurrent::Concern::Observable (module)">Observable</a></span></tt>)</span>
—
<div class='inline'><p>self</p>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_blank">yard</a>.
</div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57940973-1', 'auto');
ga('send', 'pageview');
</script>
</div>
</body>
</html> | mit |
colorlight4/flx-grid | docs/values.md | 1584 | # 1. values
## *methodical*
### flx-mode
*type:* keyword
*default:* grid
**grid** - classical grid calculator
**experimental** - supports relative, fix & flexible item widths, but might be buggy
### flx-direction
*type:* keyword
*default:* row
Defines the direction and axis of the grid flow.
Is equal to the flex-direction property (- fixed to ltr).
## *mathematic*
### flx-units
*type:* number
*default:* 12
Defines the number of columns (or rows) within the grid.
### flx-width
*type:* number, length & percentage or keyword
*default:* undefined (have to be defined as argument)
Defines the number of columns a item spans.
*grid mode:* only numbers are valid
*experimental mode:* number, length & percentage or „flex“ as keyword works. „Flex“ set an item to a self sizing flexbox. Notice that in *experimental mode* the *flx-width* must be the first argument given (to a flx-item mixin).
### flx-margin
*type:* length & percentage
*default:* 10px
Defines the margin between two grid items, in direction of grid flow (direction). All valid margin values works.
*Notice that in „column“ and „column-reverse“ percentages break the grid*
### flx-margin-b
*type:* length & percentage
*default:* undefined ( - equals flx-margin if undefined)
Defines the margin between two grid items, parallel to direction of grid flow (direction). All valid margin values works.
### flx-last
*type:* number & keyword
*default:* undefined
Can be given to set a :nth-child() pseudo-class to the flx-last mixin. All valid :nth-child() values works.
| mit |
Synchro/Haraka | plugins/delay_deny.js | 5266 | /*
** delay_deny
**
** This plugin delays all pre-DATA 'deny' results until the recipients are sent
** and all post-DATA commands until all hook_data_post plugins have run.
** This allows relays and authenticated users to bypass pre-DATA rejections.
*/
exports.hook_deny = function (next, connection, params) {
/* params
** [0] = plugin return value (DENY or DENYSOFT)
** [1] = plugin return message
*/
var pi_name = params[2];
var pi_function = params[3];
// var pi_params = params[4];
var pi_hook = params[5];
var plugin = this;
var transaction = connection.transaction;
// Don't delay ourselves...
if (pi_name == 'delay_deny') return next();
// Load config
var cfg = this.config.get('delay_deny.ini');
var skip;
var included;
if (cfg.main.included_plugins) {
included = cfg.main.included_plugins.split(/[;, ]+/);
} else if (cfg.main.excluded_plugins) {
skip = cfg.main.excluded_plugins.split(/[;, ]+/);
}
// 'included' mode: only delay deny plugins in the included list
if (included && included.length) {
if (included.indexOf(pi_name) === -1 &&
included.indexOf(pi_name + ':' + pi_hook) === -1 &&
included.indexOf(pi_name + ':' + pi_hook + ':' + pi_function) === -1) {
return next();
}
} else if (skip && skip.length) { // 'excluded' mode: delay deny everything except in skip list
// Skip by <plugin name>
if (skip.indexOf(pi_name) !== -1) {
connection.logdebug(plugin, 'not delaying excluded plugin: ' + pi_name);
return next();
}
// Skip by <plugin name>:<hook>
if (skip.indexOf(pi_name + ':' + pi_hook) !== -1) {
connection.logdebug(plugin, 'not delaying excluded hook: ' + pi_hook +
' in plugin: ' + pi_name);
return next();
}
// Skip by <plugin name>:<hook>:<function name>
if (skip.indexOf(pi_name + ':' + pi_hook + ':' + pi_function) !== -1) {
connection.logdebug(plugin, 'not delaying excluded function: ' + pi_function +
' on hook: ' + pi_hook + ' in plugin: ' + pi_name);
return next();
}
}
switch (pi_hook) {
// Pre-DATA connection delays
case 'lookup_rdns':
case 'connect':
case 'ehlo':
case 'helo':
if (!connection.notes.delay_deny_pre) {
connection.notes.delay_deny_pre = [];
}
connection.notes.delay_deny_pre.push(params);
if (!connection.notes.delay_deny_pre_fail) {
connection.notes.delay_deny_pre_fail = {};
}
connection.notes.delay_deny_pre_fail[pi_name] = 1;
return next(OK);
// Pre-DATA transaction delays
case 'mail':
case 'rcpt':
case 'rcpt_ok':
if (!transaction.notes.delay_deny_pre) {
transaction.notes.delay_deny_pre = [];
}
transaction.notes.delay_deny_pre.push(params);
if (!transaction.notes.delay_deny_pre_fail) {
transaction.notes.delay_deny_pre_fail = {};
}
transaction.notes.delay_deny_pre_fail[pi_name] = 1;
return next(OK);
// Post-DATA delays
case 'data':
case 'data_post':
// fall through
default:
// No delays
return next();
}
};
exports.hook_rcpt_ok = function (next, connection, rcpt) {
var plugin = this;
var transaction = connection.transaction;
// Bypass all pre-DATA deny for AUTH/RELAY
if (connection.relaying) {
connection.loginfo(plugin, 'bypassing all pre-DATA deny: AUTH/RELAY');
return next();
}
// Apply any delayed rejections
// Check connection level pre-DATA rejections first
if (connection.notes.delay_deny_pre) {
for (let i=0; i<connection.notes.delay_deny_pre.length; i++) {
let params = connection.notes.delay_deny_pre[i];
return next(params[0], params[1]);
}
}
// Then check transaction level pre-DATA
if (transaction.notes.delay_deny_pre) {
for (let i=0; i<transaction.notes.delay_deny_pre.length; i++) {
let params = transaction.notes.delay_deny_pre[i];
// Remove rejection from the array if it was on the rcpt hooks
if (params[5] === 'rcpt' || params[5] === 'rcpt_ok') {
transaction.notes.delay_deny_pre.splice(i, 1);
}
return next(params[0], params[1]);
}
}
return next();
};
exports.hook_data = function (next, connection) {
var transaction = connection.transaction;
// Add a header showing all pre-DATA rejections
var fails = [];
if (connection.notes.delay_deny_pre_fail) {
fails.push.apply(Object.keys(connection.notes.delay_deny_pre_fail));
}
if (transaction.notes.delay_deny_pre_fail) {
fails.push.apply(Object.keys(transaction.notes.delay_deny_pre_fail));
}
if (fails.length) transaction.add_header('X-Haraka-Fail-Pre', fails.join(' '));
return next();
}
| mit |
fastlane/fastlane | fastlane/lib/fastlane/actions/ensure_no_debug_code.rb | 5274 | module Fastlane
module Actions
class EnsureNoDebugCodeAction < Action
def self.run(params)
command = "grep -RE '#{params[:text]}' '#{File.absolute_path(params[:path])}'"
extensions = []
extensions << params[:extension] unless params[:extension].nil?
if params[:extensions]
params[:extensions].each do |extension|
extension.delete!('.') if extension.include?(".")
extensions << extension
end
end
if extensions.count > 1
command << " --include=\\*.{#{extensions.join(',')}}"
elsif extensions.count > 0
command << " --include=\\*.#{extensions.join(',')}"
end
command << " --exclude #{params[:exclude]}" if params[:exclude]
if params[:exclude_dirs]
params[:exclude_dirs].each do |dir|
command << " --exclude-dir #{dir.shellescape}"
end
end
return command if Helper.test?
UI.important(command)
results = `#{command}` # we don't use `sh` as the return code of grep is wrong for some reason
# Example Output
# ./fastlane.gemspec: spec.add_development_dependency 'my_word'
# ./Gemfile.lock: my_word (0.10.1)
found = []
results.split("\n").each do |current_raw|
found << current_raw.strip
end
UI.user_error!("Found debug code '#{params[:text]}': \n\n#{found.join("\n")}") if found.count > 0
UI.message("No debug code found in code base 🐛")
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Ensures the given text is nowhere in the code base"
end
def self.details
[
"You don't want any debug code to slip into production.",
"This can be used to check if there is any debug code still in your codebase or if you have things like `// TO DO` or similar."
].join("\n")
end
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :text,
env_name: "FL_ENSURE_NO_DEBUG_CODE_TEXT",
description: "The text that must not be in the code base"),
FastlaneCore::ConfigItem.new(key: :path,
env_name: "FL_ENSURE_NO_DEBUG_CODE_PATH",
description: "The directory containing all the source files",
default_value: ".",
verify_block: proc do |value|
UI.user_error!("Couldn't find the folder at '#{File.absolute_path(value)}'") unless File.directory?(value)
end),
FastlaneCore::ConfigItem.new(key: :extension,
env_name: "FL_ENSURE_NO_DEBUG_CODE_EXTENSION",
description: "The extension that should be searched for",
optional: true,
verify_block: proc do |value|
value.delete!('.') if value.include?(".")
end),
FastlaneCore::ConfigItem.new(key: :extensions,
env_name: "FL_ENSURE_NO_DEBUG_CODE_EXTENSIONS",
description: "An array of file extensions that should be searched for",
optional: true,
type: Array),
FastlaneCore::ConfigItem.new(key: :exclude,
env_name: "FL_ENSURE_NO_DEBUG_CODE_EXCLUDE",
description: "Exclude a certain pattern from the search",
optional: true),
FastlaneCore::ConfigItem.new(key: :exclude_dirs,
env_name: "FL_ENSURE_NO_DEBUG_CODE_EXCLUDE_DIRS",
description: "An array of dirs that should not be included in the search",
optional: true,
type: Array)
]
end
def self.output
[]
end
def self.authors
["KrauseFx"]
end
def self.example_code
[
'ensure_no_debug_code(text: "// TODO")',
'ensure_no_debug_code(text: "Log.v",
extension: "java")',
'ensure_no_debug_code(text: "NSLog",
path: "./lib",
extension: "m")',
'ensure_no_debug_code(text: "(^#define DEBUG|NSLog)",
path: "./lib",
extension: "m")',
'ensure_no_debug_code(text: "<<<<<<",
extensions: ["m", "swift", "java"])'
]
end
def self.category
:misc
end
def self.is_supported?(platform)
true
end
end
end
end
| mit |
Lysette/Markus | app/helpers/results_helper.rb | 838 | module ResultsHelper
def remark_result_unsubmitted_or_released(remark_result)
remark_result.marking_state == Result::MARKING_STATES[:unmarked] or
remark_result.released_to_students
end
def can_show_remark_request_tab_in_student_pane(assignment, current_user, submission)
if assignment.allow_remarks
if submission.get_remark_result and submission.get_remark_result.released_to_students
return true
else
return (current_user.student?)
end
else
false
end
end
def student_can_edit_remark_request(submission)
!submission.get_remark_result or
submission.get_remark_result.marking_state == Result::MARKING_STATES[:unmarked]
end
def can_show_remark_request_tab_in_marker_pane(submission)
!student_can_edit_remark_request(submission)
end
end
| mit |
ring-lang/ring | extensions/webassembly/ringqt/project/ringqt/include/glineedit.h | 1504 |
/* Copyright (c) 2013-2022 Mahmoud Fayed <[email protected]> */
#ifndef GLINEEDIT_H
#define GLINEEDIT_H
#include "ringqt.h"
#include <QLineEdit>
extern "C" {
#include "ring.h"
}
class GLineEdit : public QLineEdit
{
Q_OBJECT
public:
struct VM *pVM;
struct List *pParaList;
char cTextChangedEvent[RINGQT_EVENT_SIZE];
char ccursorPositionChangedEvent[RINGQT_EVENT_SIZE];
char ceditingFinishedEvent[RINGQT_EVENT_SIZE];
char creturnPressedEvent[RINGQT_EVENT_SIZE];
char cselectionChangedEvent[RINGQT_EVENT_SIZE];
char ctextEditedEvent[RINGQT_EVENT_SIZE];
GLineEdit(QWidget *parent,VM *pVM );
~GLineEdit();
void geteventparameters(void) ;
void setTextChangedEvent(const char *cStr);
void setcursorPositionChangedEvent(const char *cStr);
void seteditingFinishedEvent(const char *cStr);
void setreturnPressedEvent(const char *cStr);
void setselectionChangedEvent(const char *cStr);
void settextEditedEvent(const char *cStr);
const char *getTextChangedEvent(void);
const char *getcursorPositionChangedEvent(void);
const char *geteditingFinishedEvent(void);
const char *getreturnPressedEvent(void);
const char *getselectionChangedEvent(void);
const char *gettextEditedEvent(void);
public slots:
void textChangedSlot();
void cursorPositionChangedSlot();
void editingFinishedSlot();
void returnPressedSlot();
void selectionChangedSlot();
void textEditedSlot();
};
#endif
| mit |
yop0/Temps_Reel | projet_destijl_2016/xenomai/include/nucleus/timebase.h | 8231 | /**
* @file
* @note Copyright (C) 2006,2007 Philippe Gerum <[email protected]>.
*
* Xenomai is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Xenomai 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 Xenomai; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* \ingroup timebase
*/
#ifndef _XENO_NUCLEUS_TIMEBASE_H
#define _XENO_NUCLEUS_TIMEBASE_H
/*! \addtogroup timebase
*@{*/
#include <nucleus/queue.h>
#if defined(__KERNEL__) || defined(__XENO_SIM__)
#include <nucleus/vfile.h>
struct xntimer;
typedef struct xntbops {
int (*start_timer)(struct xntimer *timer,
xnticks_t value,
xnticks_t interval,
xntmode_t mode);
void (*stop_timer)(struct xntimer *timer);
xnticks_t (*get_timer_date)(struct xntimer *timer);
xnticks_t (*get_timer_timeout)(struct xntimer *timer);
xnticks_t (*get_timer_interval)(struct xntimer *timer);
xnticks_t (*get_timer_raw_expiry)(struct xntimer *timer);
void (*move_timer)(struct xntimer *timer);
} xntbops_t;
#define XNTBRUN 0x00000001 /* Time base is running. */
#define XNTBSET 0x00000002 /* Time set in time base. */
#define XNTBLCK 0x00000004 /* Time base is locked. */
#define XNTBISO 0x00000008 /* Time base uses private wallclock offset */
typedef struct xntbase {
struct xntbops *ops; /*!< Time base operations. */
xnticks_t jiffies; /*!< Ticks elapsed since init (remains null if aperiodic). */
void (*hook)(void); /*!< Hook routine called upon tick. */
xnticks_t wallclock_offset; /*!< (Wallclock time - epoch) in ticks. */
u_long tickvalue; /*!< Tick duration (ns, 1 if aperiodic). */
u_long ticks2sec; /*!< Number of ticks per second. */
u_long status; /*!< Status information. */
const char *name; /* !< Name of time base. */
xnholder_t link;
#define link2tbase(ln) container_of(ln, xntbase_t, link)
#ifdef CONFIG_XENO_OPT_STATS
struct xnvfile_snapshot vfile; /* !< Virtual file for access. */
struct xnvfile_rev_tag revtag; /* !< Revision (for non-atomic list walks). */
struct xnqueue timerq; /* !< Timer holder in timebase. */
#endif /* CONFIG_XENO_OPT_STATS */
} xntbase_t;
#ifdef __cplusplus
extern "C" {
#endif
extern xntbase_t nktbase;
extern xnqueue_t nktimebaseq;
static inline u_long xntbase_get_ticks2sec(xntbase_t *base)
{
return base->ticks2sec;
}
static inline u_long xntbase_get_tickval(xntbase_t *base)
{
/* Returns the duration of a tick in nanoseconds */
return base->tickvalue;
}
static inline xnticks_t xntbase_get_wallclock_offset(xntbase_t *base)
{
return base->wallclock_offset;
}
static inline void xntbase_set_hook(xntbase_t *base, void (*hook)(void))
{
base->hook = hook;
}
static inline int xntbase_timeset_p(xntbase_t *base)
{
return !!testbits(base->status, XNTBSET);
}
static inline int xntbase_enabled_p(xntbase_t *base)
{
return !!testbits(base->status, XNTBRUN);
}
static inline int xntbase_isolated_p(xntbase_t *base)
{
return !!testbits(base->status, XNTBISO);
}
static inline const char *xntbase_name(xntbase_t *base)
{
return base->name;
}
#ifdef CONFIG_XENO_OPT_TIMING_PERIODIC
static inline xntime_t xntbase_ticks2ns(xntbase_t *base, xnticks_t ticks)
{
/* Convert a count of ticks in nanoseconds */
return ticks * xntbase_get_tickval(base);
}
static inline xnticks_t xntbase_ns2ticks(xntbase_t *base, xntime_t t)
{
return xnarch_ulldiv(t, xntbase_get_tickval(base), NULL);
}
static inline int xntbase_master_p(xntbase_t *base)
{
return base == &nktbase;
}
static inline int xntbase_periodic_p(xntbase_t *base)
{
return !xntbase_master_p(base);
}
static inline xnticks_t xntbase_get_jiffies(xntbase_t *base)
{
return xntbase_periodic_p(base) ? base->jiffies : xnarch_get_cpu_time();
}
static inline xnticks_t xntbase_get_rawclock(xntbase_t *base)
{
return xntbase_periodic_p(base) ? base->jiffies : xnarch_get_cpu_tsc();
}
int xntbase_alloc(const char *name,
u_long period,
u_long flags,
xntbase_t **basep);
void xntbase_free(xntbase_t *base);
int xntbase_update(xntbase_t *base,
u_long period);
int xntbase_switch(const char *name,
u_long period,
xntbase_t **basep);
void xntbase_start(xntbase_t *base);
void xntbase_stop(xntbase_t *base);
void xntbase_tick(xntbase_t *base);
xnticks_t xntbase_ns2ticks_ceil(xntbase_t *base, xntime_t t);
xnticks_t xntbase_convert(xntbase_t *srcbase,
xnticks_t ticks,
xntbase_t *dstbase);
#else /* !CONFIG_XENO_OPT_TIMING_PERIODIC */
void xntimer_tick_aperiodic(void);
static inline xntime_t xntbase_ticks2ns(xntbase_t *base, xnticks_t ticks)
{
return ticks;
}
static inline xnticks_t xntbase_ns2ticks(xntbase_t *base, xntime_t t)
{
return t;
}
static inline xnticks_t xntbase_ns2ticks_ceil(xntbase_t *base, xntime_t t)
{
return t;
}
static inline int xntbase_master_p(xntbase_t *base)
{
return 1;
}
static inline xnticks_t xntbase_convert(xntbase_t *srcbase, xnticks_t ticks, xntbase_t *dstbase)
{
return ticks;
}
static inline int xntbase_periodic_p(xntbase_t *base)
{
return 0;
}
static inline xnticks_t xntbase_get_jiffies(xntbase_t *base)
{
return xnarch_get_cpu_time();
}
static inline xnticks_t xntbase_get_rawclock(xntbase_t *base)
{
return xnarch_get_cpu_tsc();
}
static inline int xntbase_alloc(const char *name, u_long period, u_long flags, xntbase_t **basep)
{
*basep = &nktbase;
return 0;
}
static inline void xntbase_free(xntbase_t *base)
{
}
static inline int xntbase_update(xntbase_t *base, u_long period)
{
return 0;
}
static inline int xntbase_switch(const char *name, u_long period, xntbase_t **basep)
{
return period == XN_APERIODIC_TICK ? 0 : -ENODEV;
}
static inline void xntbase_start(xntbase_t *base)
{
}
static inline void xntbase_stop(xntbase_t *base)
{
}
static inline void xntbase_tick(xntbase_t *base)
{
xntimer_tick_aperiodic();
}
#endif /* !CONFIG_XENO_OPT_TIMING_PERIODIC */
/*!
* @fn xnticks_t xntbase_get_time(xntbase_t *base)
* @brief Get the clock time for a given time base.
*
* This service returns the (external) clock time as maintained by the
* specified time base. This value is adjusted with the wallclock
* offset as defined by xntbase_adjust_time().
*
* @param base The address of the time base to query.
*
* @return The current time (in jiffies) if the specified time base
* runs in periodic mode, or the machine time (converted to
* nanoseconds) as maintained by the hardware if @a base refers to the
* master time base.
*
* Environments:
*
* This service can be called from:
*
* - Kernel module initialization/cleanup code
* - Interrupt service routine
* - Kernel-based task
* - User-space task
*
* Rescheduling: never.
*/
static inline xnticks_t xntbase_get_time(xntbase_t *base)
{
/* Return an adjusted value of the monotonic time with the
translated system wallclock offset. */
return xntbase_get_jiffies(base) + base->wallclock_offset;
}
void xntbase_adjust_time(xntbase_t *base, xnsticks_t delta);
#ifdef __cplusplus
}
#endif
#define xntbase_mount() \
do { \
inith(&nktbase.link); \
appendq(&nktimebaseq, &nktbase.link); \
xntbase_declare_proc(&nktbase); \
} while (0)
#define xntbase_umount() \
do { \
xntbase_remove_proc(&nktbase); \
removeq(&nktimebaseq, &nktbase.link); \
} while (0)
void xntbase_init_proc(void);
void xntbase_cleanup_proc(void);
#ifdef CONFIG_XENO_OPT_STATS
void xntbase_declare_proc(xntbase_t *base);
void xntbase_remove_proc(xntbase_t *base);
#else /* !CONFIG_XENO_OPT_STATS */
static inline void xntbase_declare_proc(xntbase_t *base) { }
static inline void xntbase_remove_proc(xntbase_t *base) { }
#endif /* !CONFIG_XENO_OPT_STATS */
extern struct xnvfile_rev_tag tbaselist_tag;
#endif /* __KERNEL__ || __XENO_SIM__ */
/*@}*/
#endif /* !_XENO_NUCLEUS_TIMEBASE_H */
| mit |
marlengit/hardfork_prototype_1_mvf-bu | doc/mvf-bu-test-plan.md | 13347 | # MVF-BU test plan
##1. Contents <a id="1-contents"></a>
1. [Contents](#1-contents)
2. [Introduction](#2-introduction)
3. [Test items](#3-test-items)
4. [Test environment](#4-test-environment)
5. [Test procedures](#5-test-procedures)
1. [Verification methods](#5-1=verification-methods)
2. [Test levels](#5-2=test-levels)
3. [Test types](#5-3=test-types)
4. [Test phases](#5-4=test-phases)
6. [Testing of functional changes (fork features)](#6-testing-functional)
1. [TRIG (fork triggering)](#6-1-fork-triggering)
2. [NSEP (network separation)](#6-2-network-separation)
3. [DIAD (difficulty adjustment)](#6-3-difficulty-adjustment)
4. [CSIG (signature change)](#6-4-signature-change)
5. [WABU (wallet backup)](#6-5-wallet-backup)
6. [IDME (system identification)](#6-6-system-identification)
7. [Regression testing](#7-regression-testing)
8. [Features not tested](#8-features-not-tested)
9. [Risks and mitigations](#9-risks-and-mitigations)
##2. Introduction <a id="2-introduction"></a>
This document describes the planned verification and validation (V&V)
activities for the MVF-BU [1], in general and specific terms.
###2.1 Overview
It is the objective of this test plan to provide general information
on V&V activities and procedures planned for the MVF-BU software.
V&V is more than just "testing" - there are other verification methods
such as inspection and analysis that contribute to the process of
verifying that a system conforms to its specifications.
During software development, a variety of additional quality assurance
methods such as code reviews and walkthroughs are employed. For MVF-BU,
these are conducted via public repositories of the [BTCfork organization](https://github.com/BTCfork) [0].
###2.2 Scope
This document focuses only on the verification aspects, not other
quality assurance processes.
###2.3 Intended audience
This document should be of interest to those participating in MVF-BU V&V
activities or generally interested to check that the software will be
adequately verified and validated.
This includes the following persons:
- software developers
- software testers
- integrators from other organizations
###2.4 Context
The MVF-BU is a spin-off (hard fork) client derived from Bitcoin Unlimited.
The changes made to it are intended to be minimal yet sufficient to
produce a viable fork of the Bitcoin network in order to upgrade the
block size from its current 1MB limit.
The MVF-BU design assumes only minimal initial support by existing miners.
TODO: link to development roadmap
###2.5 Related documents
TODO: this is under construction.
1. https://github.com/BTCfork/hardfork_prototype_1_mvf-bu
2. https://github.com/BTCfork
3. [MVF-BU requirements](requirements.md)
4. [MVF-BU design](design.md)
5. [MVF-BU test design](mvf-bu-test-design.md)
6. [MVF-BU roadmap](TODO)
##3. Test items <a id="3-test-items"></a>
###3.1 MVF-BU software
The software is developed in a public repository on GitHub [1].
The `master` branch represents the integration branch.
There may be feature branches for large developments and release branches
for test releases.
###3.2 Operating systems
Unit tests should be conducted on a variety of operating systems.
The following platforms are expected to be covered by official tests:
- Windows (32- and 64-bit builds)
- Windows 7
- Windows 8
- Windows 10
- Linux (32- and 64-bit builds)
- Ubuntu 14.04
- Ubuntu 16.04
- Debian 7
- Debian 8
- Mac OSX
- TODO: versions
It is hoped that developers and testers will provide coverage on
additional operating systems.
##4. Test environment <a id="4-test-environment"></a>
###4.1 Local development environments (regtestnet)
These are any hardware/software platforms that developers on the MVF-BU
project want to use.
They should preferably be capable of building the software with all
functionality (i.e. including GUI, wallet etc), although partial test
results from exotic platforms which only support partial functionality
may still be interesting.
Generally, we find that building with a larger variety of platforms
will highlight problems in the code and thus lead to a more portable
product.
###4.2 Integration test environment (Github-centric)
The integration test environment will consist of continuous integration
services running the unit and regression tests upon updates of the
integration branch.
These integration tests may be run on third-party services such as e.g.
Travis, and also various contributors building and running the
tests in automated ways, e.g. daily runs on their available platform.
###4.3 Isolated (private) testnet / mainnet network clones
Further testing can be done using historic testnet/mainnet blockchain data
on private LANs (IP addresses not routable on from the Internet).
###4.4 Public test network (testnet)
There is an existing public test network (testnet) for Bitcoin which
could be used for initial public network testing.
If deemed necessary, a separate testnet could be deployed.
###4.5 Public operational network (mainnet)
The operational network (mainnet) could be used for a final smoke test
before the MVF-BU is deployed operationally.
##5. Test procedures <a id="5-test-procedures"></a>
The following sections describe verification methods, test types, test
levels and phases. The descriptions are derived from but may deviate
slightly from IEEE software engineering methodology.
###5.1 Verification methods <a id="5-1=verification-methods"></a>
This section describes different verification methods that may be employed.
####5.1.1 Test
Although the most prevalent, testing is just one of several methods
available to verify compliance with requirements. Not all requirements
lend themselves to testing.
Testing is the operation of the system, or a part of the system using
instrumentation or other special test equipment to collect data for later
analysis.
####5.1.2 Demonstration
This refers to the operation of the system, or a part of the system,
that relies on observable functional operation not requiring the use of
instrumentation, special test equipment, or subsequent analysis.
####5.1.3 Inspection
The visual examination of system components, e.g. source code and
documentation.
####5.1.4 Analysis
The processing of accumulated data obtained from other qualification
methods. Examples are reduction, interpolation or extrapolation of
measured data.
###5.2 Test levels <a id="5-2=test-levels"></a>
####5.2.1 Unit test
Also called subunit tests, module test or component test, this refers to
the testing of individual software components or groups of related
components.
A subunit is a piece of software that has a well-defined interface to
its environment and realizes a closed piece of functionality. The
objective of unit testing is to verify that the subunit has been
correctly implemented with regard to its interface definition.
In general, unit testing involves the use of a test harness that allows
artificial input of data and analysis of the subunit output.
In the Bitcoin software, C++ unit tests reside under the src/test/ folder.
TODO: discuss coverage of the unit tests.
For critical subunits, additional software validation methods such as
detailed code walkthroughs may be used.
####5.2.2 Integration test
Integration testing ombines software components and evaluates the
interactions between them.
It is the objective of integration testing to identify interface errors,
in particular to find differences
- between the specification of an interface function and its actual realisation
- between the specification of the interface usage and its actual usage
In general, integration testing proceeds bottom up, i.e. it starts with
the integration of basic software services, and proceeds step by step with
the integration of components of higher software layers.
Integration testing ends with a complete running system, which serves as
starting point for the overall system tests.
####5.2.3 System test
A system test is a test conducted on a complete, integrated system to
evaluate the system's compliance with its specified (system) requirements.
####5.2.3 Acceptance test
The acceptance testing is formal testing conducted to determine whether
or not a system satisfies certain acceptance criteria and to enable the users
to determine whether or not to accept the system.
In traditional development, this is usually done together with the
customer(s) in Factory Acceptance Tests and later Site Acceptance Tests,
once the system has been delivered and installed.
For MVF-BU, this test phase starts with the deployment of the official
spin-off client which is ready for operational use.
These "customers" are all Bitcoin users who accept the MVF-BU by
running it - or not. They may of course elect to run a derivative of the
MVF-BU, or a network-compatible alternative client (MVF-X), or a
completely different client, or stick with the existing popular
implementation (Bitcoin Core) and its network.
###5.3 Test types <a id="5-3=test-types"></a>
The following definitions are provided as a basis for talking about
the kinds of tests.
####5.3.1 Functional test
A test which focuses on a specific functionality.
####5.3.2 Performance test
A test which focuses on performance aspects specified by non-functional
requirements.
####5.3.3 Reliability and availability test
A test which focuses on reliability and availability specified by
non-functional requirements.
####5.3.4 Robustness test
A test which focuses on robustness specified by non-functional requirements.
####5.3.5 Regression test
A test which is executed to verify that there is no regression of the
system w.r.t functional or non-functional requirements.
###5.4 Test phases <a id="5-4=test-phases"></a>
####5.4.1 Unit testing phase
Developers construct unit tests covering the new functionality where
possible and run these in their local development environments.
####5.4.2 Integration testing phase
Functional items are integrated on the `master` branch of the software
repository.
Automated continuous integration (CI) should ensure that
builds and unit tests pass on various operating systems.
####5.4.3 Testnet testing phase
When the functionality has been completed to a satisfactory degree and
local / isolated testnet testing shows that there is little to no risk of
disruption to existing networks, testing may move to the `testnet` public
Bitcoin test network on the Internet.
####5.4.4 Mainnet testing phase
When testing on the testnet shows no significant problems and indicates
that there is no risk of disruption to the network, testing may move to
the `mainnet` public Bitcoin operational network for final testing prior
to deployment.
##6. Testing of functional changes (fork features) <a id="6-testing-functional"></a>
New functionality should be accompanied by unit tests where possible,
and have at least one software test covering the software requirements.
Successful execution of these tests should be visible through logs
produced by public continuous integration test systems.
Any tests which cannot be performed automatically should be conducted
and evidence deposited into a public repository of MVF-BU test results.
Test records there should be electronically signed by the developers or
testers who performed them.
TODO: create a "test records" repository for MVF-BU results, including
especially those for non-automatic tests.
The status of these tests (pass/fail/inconclusive) can be voted on by
the active MVF-BU developers and testers.
##6.1 TRIG (fork triggering) <a id="6-1-fork-triggering"></a>
To be completed.
##6.2 NSEP (network separation) <a id="6-2-network-separation"></a>
To be completed.
##6.3 DIAD (difficulty adjustment) <a id="6-3-difficulty-adjustment"></a>
To be completed.
##6.4 CSIG (signature change) <a id="6-4-signature-change"></a>
To be completed.
##6.5 WABU (wallet backup) <a id="6-5-wallet-backup"></a>
This functionality is quite independent from the rest, and lends itself
well to unit testing.
A single software test can probably cover all the software requirements
for this functionality.
##6.6 IDME (system identification) <a id="6-6-system-identification"></a>
To be completed.
##7. Regression testing <a id="7-regression-testing"></a>
The entire unit test suites and "qa" test suite should be successfully
executed as a regression test.
If there are "qa" tests which do not pass and intended to be waived,
this must be clearly documented, with justification, in drafts and
final versions of the MVF-BU release notes.
##8. Features not tested <a id="8-features-not-tested"></a>
Any features which are implemented but not tested must be clearly
documented in this section, with justification, and mentioned in drafts
and final versions of the MVF-BU release notes.
###8.1 Safe shutdown on failure to backup wallet
Currently the method of exiting (runtime error) cannot be caught by
the qa test framework, making the expected shutdown of a client
not possible to test in the automatic test.
It might be necessary to change how the node exits, or to adapt the
test framework to be able to handle this case.
##9. Risks and mitigations <a id="9-risks-and-mitigations"></a>
To be completed.
| mit |
scalalab/scalalab | source/src/main/scala/scalaExec/scalaLab/qrihrm.html | 3771 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
<TITLE></TITLE>
<META NAME="GENERATOR" CONTENT="OpenOffice.org 3.2 (Unix)">
<META NAME="CREATED" CONTENT="0;0">
<META NAME="CHANGED" CONTENT="20110101;15023800">
<STYLE TYPE="text/css">
<!--
@page {
margin: 0.79in
}
P {
margin-bottom: 0.08in
}
PRE {
font-family: "Times New Roman"
}
-->
</STYLE>
</HEAD>
<BODY LANG="el-GR" DIR="LTR">
<PRE LANG="en-US"><FONT SIZE=5><B>qrihrm</B></FONT>
<FONT SIZE=4><SPAN LANG="en-US"><SPAN STYLE="font-style: normal">for</SPAN> details see book of Hang T. Lau, “A Java Numerical Library for Scientists and engineers|”, Chapman & Hall, 2004</SPAN></FONT>
<FONT SIZE=4><SPAN LANG="en-US"><B>Example: Can be run with F9 within the ScalaLab Editor </B></SPAN></FONT>
<SPAN LANG="en-US">import java.text.DecimalFormat;</SPAN>
<SPAN LANG="en-US">import numal.*;</SPAN>
<SPAN LANG="en-US">public class Test_qrihrm extends Object {</SPAN>
<SPAN LANG="en-US"> </SPAN>
<SPAN LANG="en-US"> public static void main(String args[]) {</SPAN>
<SPAN LANG="en-US">int i;</SPAN>
<SPAN LANG="en-US">double val[] = new double[5]; </SPAN>
<SPAN LANG="en-US">double em[] = new double[6];</SPAN>
<SPAN LANG="en-US">double a[][] = new double[5][5];</SPAN>
<SPAN LANG="en-US">double vr[][] = new double[5][5];</SPAN>
<SPAN LANG="en-US">double vi[][] = new double[5][5];</SPAN>
<SPAN LANG="en-US">Basic.inimat(1,4,1,4,a,0.0);</SPAN>
<SPAN LANG="en-US">a[1][1]=a[2][2]=3.0;</SPAN>
<SPAN LANG="en-US">a[3][2]=2.0; a[4][1] = -2.0;</SPAN>
<SPAN LANG="en-US">a[1][2]=a[3][3]=a[3][4]=a[4][4]=1.0;</SPAN>
<SPAN LANG="en-US">em[0]=em[2]=5.0e-5;</SPAN>
<SPAN LANG="en-US">em[4]=20.0;</SPAN>
<SPAN LANG="en-US">DecimalFormat twoDigit = new DecimalFormat("##");</SPAN>
<SPAN LANG="en-US">DecimalFormat threeDigit = new DecimalFormat("0.000");</SPAN>
<SPAN LANG="en-US">DecimalFormat fiveDigit = new DecimalFormat("0.00000E0");</SPAN>
<SPAN LANG="en-US">System.out.println("QRIHRM: " + </SPAN>
<SPAN LANG="en-US">Linear_algebra.qrihrm(a,4,val,vr,vi,em));</SPAN>
<SPAN LANG="en-US">Basic.sclcom(vr,vi,4,2,3);</SPAN>
<SPAN LANG="en-US">System.out.println("\nEigenvalues:" +</SPAN>
<SPAN LANG="en-US">"\n VAL[1]: " + threeDigit.format(val[1]) +</SPAN>
<SPAN LANG="en-US">"\n VAL[2]: " + threeDigit.format(val[2]) +</SPAN>
<SPAN LANG="en-US">"\n VAL[3]: " + threeDigit.format(val[3]) + </SPAN>
<SPAN LANG="en-US">"\n VAL[4]: " + threeDigit.format(val[4]) + </SPAN>
<SPAN LANG="en-US">"\n\nEigenvectors corresponding to\n VAL[2] VAL[3]");</SPAN>
<SPAN LANG="en-US">for (i=1; i<=4; i++)</SPAN>
<SPAN LANG="en-US">System.out.println(" " +</SPAN>
<SPAN LANG="en-US">twoDigit.format(vr[i][2]) + " " +</SPAN>
<SPAN LANG="en-US">twoDigit.format(vi[i][2]) + "*I" + " " + </SPAN>
<SPAN LANG="en-US">twoDigit.format(vr[i][3]) + " " +</SPAN>
<SPAN LANG="en-US">twoDigit.format(vi[i][3]) + "*I");</SPAN>
<SPAN LANG="en-US">System.out.println("\nEM[1]: " + fiveDigit.format(em[1]) +</SPAN>
<SPAN LANG="en-US">"\nEM[3]: " + fiveDigit.format(em[3]) +</SPAN>
<SPAN LANG="en-US">"\nEM[5]: " + fiveDigit.format(em[5]));</SPAN>
<SPAN LANG="en-US"> }</SPAN>
<SPAN LANG="en-US">}</SPAN>
</PRE>
</BODY>
</HTML> | mit |
stof/repository | src/AbstractPathMappingRepository.php | 6028 | <?php
/*
* This file is part of the puli/repository package.
*
* (c) Bernhard Schussek <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Puli\Repository;
use Puli\Repository\Api\Resource\FilesystemResource;
use Puli\Repository\Api\ResourceCollection;
use Puli\Repository\Api\UnsupportedResourceException;
use Puli\Repository\Resource\DirectoryResource;
use Puli\Repository\Resource\FileResource;
use Puli\Repository\Resource\GenericResource;
use RuntimeException;
use Webmozart\KeyValueStore\Api\CountableStore;
use Webmozart\KeyValueStore\Api\KeyValueStore;
use Webmozart\KeyValueStore\Api\SortableStore;
use Webmozart\KeyValueStore\Decorator\CountableDecorator;
use Webmozart\KeyValueStore\Decorator\SortableDecorator;
use Webmozart\PathUtil\Path;
/**
* Abstract base for Path mapping repositories.
*
* @since 1.0
*
* @author Bernhard Schussek <[email protected]>
* @author Titouan Galopin <[email protected]>
*/
abstract class AbstractPathMappingRepository extends AbstractRepository
{
/**
* @var KeyValueStore
*/
protected $store;
/**
* Creates a new repository.
*
* @param KeyValueStore $store The store of all the paths.
*/
public function __construct(KeyValueStore $store)
{
$this->store = $store;
$this->createRoot();
}
/**
* Add the resource (internal method after checks of add()).
*
* @param string $path
* @param FilesystemResource $resource
*/
abstract protected function addResource($path, FilesystemResource $resource);
/**
* {@inheritdoc}
*/
public function add($path, $resource)
{
$path = $this->sanitizePath($path);
if ($resource instanceof ResourceCollection) {
$this->ensureDirectoryExists($path);
foreach ($resource as $child) {
$this->addResource($path.'/'.$child->getName(), $child);
}
$this->sortStore();
return;
}
if ($resource instanceof FilesystemResource) {
$this->ensureDirectoryExists(Path::getDirectory($path));
$this->addResource($path, $resource);
$this->sortStore();
return;
}
throw new UnsupportedResourceException(sprintf(
'The passed resource must be a FilesystemResource or a ResourceCollection. Got: %s',
is_object($resource) ? get_class($resource) : gettype($resource)
));
}
/**
* {@inheritdoc}
*/
public function clear()
{
// Subtract root
$removed = $this->countStore() - 1;
$this->store->clear();
$this->createRoot();
return $removed;
}
/**
* Recursively creates a directory for a path.
*
* @param string $path A directory path.
*/
protected function ensureDirectoryExists($path)
{
if ($this->store->exists($path)) {
return;
}
// Recursively initialize parent directories
if ('/' !== $path) {
$this->ensureDirectoryExists(Path::getDirectory($path));
}
$this->store->set($path, null);
}
/**
* Create the repository root.
*/
protected function createRoot()
{
if ($this->store->exists('/')) {
return;
}
$this->store->set('/', null);
}
/**
* Count the number of elements in the store.
*
* @return int
*/
protected function countStore()
{
if (!$this->store instanceof CountableStore) {
$this->store = new CountableDecorator($this->store);
}
return $this->store->count();
}
/**
* Sort the store by keys.
*/
protected function sortStore()
{
if (!$this->store instanceof SortableStore) {
$this->store = new SortableDecorator($this->store);
}
$this->store->sort();
}
/**
* Create a filesystem or generic resource.
*
* @param string $filesystemPath
*
* @return DirectoryResource|FileResource|GenericResource
*/
protected function createResource($filesystemPath, $path = null)
{
if ($filesystemPath && file_exists($filesystemPath)) {
return $this->createFilesystemResource($filesystemPath, $path);
}
return $this->createVirtualResource($path);
}
/**
* Create a resource using its filesystem path.
*
* If the filesystem path is a directory, a DirectoryResource will be created.
* If the filesystem path is a file, a FileResource will be created.
* If the filesystem does not exists, a GenericResource will be created.
*
* @param string $filesystemPath The filesystem path.
* @param string $path The repository path.
*
* @return DirectoryResource|FileResource The created resource.
*
* @throws RuntimeException If the file / directory does not exist.
*/
protected function createFilesystemResource($filesystemPath, $path = null)
{
$resource = null;
if (is_dir($filesystemPath)) {
$resource = new DirectoryResource($filesystemPath);
} elseif (is_file($filesystemPath)) {
$resource = new FileResource($filesystemPath);
}
if ($resource) {
$resource->attachTo($this, $path);
return $resource;
}
throw new RuntimeException(sprintf(
'Trying to create a FilesystemResource on a non-existing file or directory "%s"',
$filesystemPath
));
}
/**
* @param string|null $path
*
* @return GenericResource
*/
protected function createVirtualResource($path = null)
{
$resource = new GenericResource();
$resource->attachTo($this, $path);
return $resource;
}
}
| mit |
abhishek1015/schema_design | ulib/test/atomic.cpp | 1184 | #include <assert.h>
#include <stdio.h>
#include <ulib/os_atomic_intel64.h>
int main()
{
atomic_barrier();
uint64_t a = 0;
assert(atomic_cmpswp64(&a, 1, 2) == 0);
assert(a == 0);
assert(atomic_cmpswp64(&a, 0, 2) == 0);
assert(a == 2);
assert(atomic_cmpswp16(&a, 0, 2) == 2);
assert(atomic_cmpswp16(&a, 2, 0) == 2);
assert(atomic_cmpswp16(&a, 0, 2) == 0);
assert(a == 2);
assert(atomic_fetchadd64(&a, 1) == 2);
assert(a == 3);
assert(atomic_fetchadd64(&a, -1) == 3);
assert(a == 2);
assert(atomic_fetchstore64(&a, 5) == 2);
assert(a == 5);
assert(atomic_test_and_set_bit64(&a, 0) == -1);
assert(a == 5);
assert(atomic_test_and_set_bit64(&a, 1) == 0);
assert(a == 7);
atomic_and64(&a, ~7ul);
assert(a == 0);
atomic_or64(&a, (1ull << 63));
assert(a == (1ull << 63));
assert(atomic_test_and_set_bit64(&a, 63) == -1);
atomic_or8(&a, 1);
assert(a == ((1ull << 63) | 1));
atomic_and8(&a, (int8_t)~1u);
assert(a == (1ull << 63));
atomic_and64(&a, ~(1ull << 63));
assert(a == 0);
atomic_inc64(&a);
assert(a == 1);
atomic_dec64(&a);
assert(a == 0);
atomic_add64(&a, -1);
assert(a == (uint64_t)-1);
atomic_cpu_relax();
printf("passed\n");
return 0;
}
| mit |
gt-ros-pkg/humans | src/videoray/catkin_ws/src/videoray/include/boost/numeric/odeint/algebra/range_algebra.hpp | 8358 | /*
[auto_generated]
boost/numeric/odeint/algebra/range_algebra.hpp
[begin_description]
Default algebra, which works with the most state types, like vector< double >, boost::array< double >, boost::range.
Internally is uses boost::range to obtain the begin and end iterator of the according sequence.
[end_description]
Copyright 2009-2011 Karsten Ahnert
Copyright 2009-2011 Mario Mulansky
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_0.txt)
*/
#ifndef BOOST_NUMERIC_ODEINT_ALGEBRA_RANGE_ALGEBRA_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_ALGEBRA_RANGE_ALGEBRA_HPP_INCLUDED
#include <boost/range.hpp>
#include <boost/mpl/size_t.hpp>
#include <boost/numeric/odeint/algebra/detail/macros.hpp>
#include <boost/numeric/odeint/algebra/detail/for_each.hpp>
#include <boost/numeric/odeint/algebra/detail/norm_inf.hpp>
#include <boost/numeric/odeint/algebra/norm_result_type.hpp>
namespace boost {
namespace numeric {
namespace odeint {
struct range_algebra
{
template< class S1 , class Op >
static void for_each1( S1 &s1 , Op op )
{
detail::for_each1( boost::begin( s1 ) , boost::end( s1 ) ,
op );
}
template< class S1 , class S2 , class Op >
static void for_each2( S1 &s1 , S2 &s2 , Op op )
{
detail::for_each2( boost::begin( s1 ) , boost::end( s1 ) ,
boost::begin( s2 ) , op );
}
template< class S1 , class S2 , class S3 , class Op >
static void for_each3( S1 &s1 , S2 &s2 , S3 &s3 , Op op )
{
detail::for_each3( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class Op >
static void for_each4( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , Op op )
{
detail::for_each4( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class Op >
static void for_each5( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , Op op )
{
detail::for_each5( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class Op >
static void for_each6( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , Op op )
{
detail::for_each6( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class Op >
static void for_each7( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , Op op )
{
detail::for_each7( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class Op >
static void for_each8( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , Op op )
{
detail::for_each8( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class Op >
static void for_each9( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , Op op )
{
detail::for_each9( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class Op >
static void for_each10( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , Op op )
{
detail::for_each10( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class S11 , class Op >
static void for_each11( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , Op op )
{
detail::for_each11( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , boost::begin( s11 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class Op >
static void for_each12( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , Op op )
{
detail::for_each12( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , boost::begin( s11 ) , boost::begin( s12 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class S13 , class Op >
static void for_each13( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , S13 &s13 , Op op )
{
detail::for_each13( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , boost::begin( s11 ) , boost::begin( s12 ) , boost::begin( s13 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class S13 , class S14 , class Op >
static void for_each14( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , S13 &s13 , S14 &s14 , Op op )
{
detail::for_each14( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , boost::begin( s11 ) , boost::begin( s12 ) , boost::begin( s13 ) , boost::begin( s14 ) , op );
}
template< class S1 , class S2 , class S3 , class S4 , class S5 , class S6 ,class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class S13 , class S14 , class S15 , class Op >
static void for_each15( S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , S13 &s13 , S14 &s14 , S15 &s15 , Op op )
{
detail::for_each15( boost::begin( s1 ) , boost::end( s1 ) , boost::begin( s2 ) , boost::begin( s3 ) , boost::begin( s4 ) , boost::begin( s5 ) , boost::begin( s6 ) , boost::begin( s7 ) , boost::begin( s8 ) , boost::begin( s9 ) , boost::begin( s10 ) , boost::begin( s11 ) , boost::begin( s12 ) , boost::begin( s13 ) , boost::begin( s14 ) , boost::begin( s15 ) , op );
}
template< typename S >
static typename norm_result_type<S>::type norm_inf( const S &s )
{
return detail::norm_inf( boost::begin( s ) , boost::end( s ) ,
static_cast< typename norm_result_type<S>::type >( 0 ) );
}
};
} // odeint
} // numeric
} // boost
#endif // BOOST_NUMERIC_ODEINT_ALGEBRA_RANGE_ALGEBRA_HPP_INCLUDED
| mit |
Azure/azure-sdk-for-java | sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java | 7681 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.eventgrid.models;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Schema of the Data property of an EventGridEvent for a
* Microsoft.Resources.ResourceActionSuccess event. This is raised when a
* resource action operation succeeds.
*/
public class ResourceActionSuccessData {
/**
* The tenant ID of the resource.
*/
@JsonProperty(value = "tenantId")
private String tenantId;
/**
* The subscription ID of the resource.
*/
@JsonProperty(value = "subscriptionId")
private String subscriptionId;
/**
* The resource group of the resource.
*/
@JsonProperty(value = "resourceGroup")
private String resourceGroup;
/**
* The resource provider performing the operation.
*/
@JsonProperty(value = "resourceProvider")
private String resourceProvider;
/**
* The URI of the resource in the operation.
*/
@JsonProperty(value = "resourceUri")
private String resourceUri;
/**
* The operation that was performed.
*/
@JsonProperty(value = "operationName")
private String operationName;
/**
* The status of the operation.
*/
@JsonProperty(value = "status")
private String status;
/**
* The requested authorization for the operation.
*/
@JsonProperty(value = "authorization")
private String authorization;
/**
* The properties of the claims.
*/
@JsonProperty(value = "claims")
private String claims;
/**
* An operation ID used for troubleshooting.
*/
@JsonProperty(value = "correlationId")
private String correlationId;
/**
* The details of the operation.
*/
@JsonProperty(value = "httpRequest")
private String httpRequest;
/**
* Get the tenant ID of the resource.
*
* @return the tenantId value
*/
public String tenantId() {
return this.tenantId;
}
/**
* Set the tenant ID of the resource.
*
* @param tenantId the tenantId value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withTenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
/**
* Get the subscription ID of the resource.
*
* @return the subscriptionId value
*/
public String subscriptionId() {
return this.subscriptionId;
}
/**
* Set the subscription ID of the resource.
*
* @param subscriptionId the subscriptionId value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withSubscriptionId(String subscriptionId) {
this.subscriptionId = subscriptionId;
return this;
}
/**
* Get the resource group of the resource.
*
* @return the resourceGroup value
*/
public String resourceGroup() {
return this.resourceGroup;
}
/**
* Set the resource group of the resource.
*
* @param resourceGroup the resourceGroup value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withResourceGroup(String resourceGroup) {
this.resourceGroup = resourceGroup;
return this;
}
/**
* Get the resource provider performing the operation.
*
* @return the resourceProvider value
*/
public String resourceProvider() {
return this.resourceProvider;
}
/**
* Set the resource provider performing the operation.
*
* @param resourceProvider the resourceProvider value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withResourceProvider(String resourceProvider) {
this.resourceProvider = resourceProvider;
return this;
}
/**
* Get the URI of the resource in the operation.
*
* @return the resourceUri value
*/
public String resourceUri() {
return this.resourceUri;
}
/**
* Set the URI of the resource in the operation.
*
* @param resourceUri the resourceUri value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withResourceUri(String resourceUri) {
this.resourceUri = resourceUri;
return this;
}
/**
* Get the operation that was performed.
*
* @return the operationName value
*/
public String operationName() {
return this.operationName;
}
/**
* Set the operation that was performed.
*
* @param operationName the operationName value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withOperationName(String operationName) {
this.operationName = operationName;
return this;
}
/**
* Get the status of the operation.
*
* @return the status value
*/
public String status() {
return this.status;
}
/**
* Set the status of the operation.
*
* @param status the status value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withStatus(String status) {
this.status = status;
return this;
}
/**
* Get the requested authorization for the operation.
*
* @return the authorization value
*/
public String authorization() {
return this.authorization;
}
/**
* Set the requested authorization for the operation.
*
* @param authorization the authorization value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withAuthorization(String authorization) {
this.authorization = authorization;
return this;
}
/**
* Get the properties of the claims.
*
* @return the claims value
*/
public String claims() {
return this.claims;
}
/**
* Set the properties of the claims.
*
* @param claims the claims value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withClaims(String claims) {
this.claims = claims;
return this;
}
/**
* Get an operation ID used for troubleshooting.
*
* @return the correlationId value
*/
public String correlationId() {
return this.correlationId;
}
/**
* Set an operation ID used for troubleshooting.
*
* @param correlationId the correlationId value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withCorrelationId(String correlationId) {
this.correlationId = correlationId;
return this;
}
/**
* Get the details of the operation.
*
* @return the httpRequest value
*/
public String httpRequest() {
return this.httpRequest;
}
/**
* Set the details of the operation.
*
* @param httpRequest the httpRequest value to set
* @return the ResourceActionSuccessData object itself.
*/
public ResourceActionSuccessData withHttpRequest(String httpRequest) {
this.httpRequest = httpRequest;
return this;
}
}
| mit |
timheuer/Kliva-1 | src/Kliva/Services/Interfaces/IApplicationInfoService.cs | 159 | using Kliva.Models;
namespace Kliva.Services.Interfaces
{
public interface IApplicationInfoService
{
AppVersion AppVersion { get; }
}
} | mit |
freeztime/ignitedcms | application/views/admin/404/404.php | 894 | <div class="row">
<div class="mainvcontainer" style="background-image:url('<?php echo base_url('img/bg.jpg'); ?>'); min-height:900px;">
<div class="col-sm-3"></div>
<div class="animated bounceInDown col-sm-6">
<section class="panel" style="margin-top:90px;padding:50px;
box-shadow: 4px 12px 85px rgba(0,0,0,.9);
border: 1px solid #ccc;
border-radius: 10px;
">
<div class="panel-body">
<img src="<?php echo base_url("img/ig.png"); ?>" class=" img-responsive my-center" style="position:relative;">
<h1 class="text-center"> 404 error</h1>
Page not found!
</div>
</section>
</div>
<div class="col-sm-3"></div>
</div>
</div>
| mit |
PrJared/sabbath-school-lessons | src/cs/2018-03/10/05.md | 3379 | ---
title: Milét – Pavlovo rozloučení
date: 05/09/2018
---
> <p></p>
> 22Nyní jdu do Jeruzaléma, protože mě Duch nutí, a nevím, co mě tam potká. 23Vím jen tolik, že mi Duch svatý město od města ohlašuje, že na mne čekají pouta a utrpení. 24Ale já nepřikládám svému životu žádnou jinou cenu, než abych dokončil svůj běh a splnil úkol, který jsem dostal od Pána Ježíše: hlásat evangelium o Boží milosti. (Sk 20,22–24)
**Osobní studium**
Během své cesty do Jeruzaléma se Pavel zastavil i ve městě Milét, kam pozval zástupce efezského sboru, aby jim přednesl své závěrečné poselství.
`Přečti si text Sk 20,15–37. Uveď hlavní témata, o kterých Pavel při rozloučení s věřícími v Efezu mluvil.`
`Která z těchto témat tě zaujala nejvíce? Proč? Co se z Pavlova vyprávění můžeš naučit?`
Pavel si naplánoval novou cestu, jejímž cílem měla být Hispanie (nynější Španělsko; Ř 15,22–29). Předtím chtěl ještě zajít do Jeruzaléma a cestou do Hispanie byl rozhodnut navštívit Řím. Pavel předpokládal, že se už nikdy nebude moci vrátit do Malé Asie. Proto se ve své řeči soustředil nejprve na jakési zhodnocení let strávených v Efezu. Nemluvil však jen o minulosti a o svém působení u Efezanů. Zaměřil se i na budoucnost a mluvil o nejistotě, která ho čeká v souvislosti s návštěvou Jeruzaléma (Sk 20,22.23).
Pavlovy obavy byly opodstatněné. Někteří věřící v Jeruzalémě se na něj stále dívali s určitou dávkou nedůvěry, či dokonce nepřátelství. Důvodem byla nejen Pavlova minulost pronásledovatele církve, ale také skutečnost, že při hlásání evangelia nevyžadoval od pohanů obřízku (Sk 21,20–26). Pro židovské vůdce nebyl Pavel ničím jiným než zrádcem a odpadlíkem (Sk 23,1.2). Vzhledem k tomu, že římští místodržící v Judeji v té době nebyli příliš schopní, ovládly ji v polovině prvního století různé revoluční a národní ideály. Tato atmosféra měla vliv na všechny oblasti židovské společnosti – včetně církve. V tomto kontextu se z bývalého farizea působícího mezi pohany automaticky stávala persona non grata (Sk 21,27–36).
Pavel se však ve svém projevu Efezským zaměřil i na další souvislosti. Ve Skutcích 20,28–31 jim říká, jak by se měli vypořádat s problémem falešných učitelů. Přirovnal je k „dravým vlkům“, kteří se budou snažit zničit stádo a odvést ho od pravdy. Nebezpečí falešných učitelů není tedy novým fenoménem – v církvi bylo přítomno již od jejího začátku. Jak řekl Šalomoun v jiném čase a kontextu: „Pod sluncem není nic nového“ (Kaz 1,9). Dějiny křesťanské církve odhalují ohromující škody, které falešní učitelé způsobili v církvi – a prostřednictvím církve i nevěřícím lidem. Tento problém bude v církvi přítomen až do konce (2Tm 4,3).
Pavel toho měl na srdci velmi mnoho. Uvažoval o mnoha nebezpečích, které hrozila církvi a také jemu samotnému. Přesto zůstával věrný Kristu a hlásání evangelia.
**Aplikace**
`Přečti si text 2K 4,8–14. Kdy ses naposledy cítil bezradný, pronásledovaný nebo opuštěný? Které z Pavlových myšlenek ti přinášejí povzbuzení? V čem? Na co se Pavel spoléhá nejvíce?` | mit |
nadavc/bash_koans | src/00_about_redirection.sh | 953 | lesson_title "Redirection"
test_redirecting_stdout_to_file() {
output_stdout > tmp/redirect_test.txt
local contents=$(cat tmp/redirect_test.txt)
assertEqual "$contents" __
}
test_redirecting_stderr_to_file() {
output_stderr 2> tmp/redirect_test2.txt
local contents=$(cat tmp/redirect_test2.txt)
assertEqual "$contents" __
}
test_redirecting_stdout_to_stderr() {
output_stdout 2> tmp/redirect_test3.txt 1>&2
local contents=$(cat tmp/redirect_test3.txt)
assertEqual "$contents" __
}
test_redirecting_stderr_to_stdout() {
output_stderr 1> tmp/redirect_test4.txt 2>&1
local contents=$(cat tmp/redirect_test4.txt)
assertEqual "$contents" __
}
test_redirecting_stdout_and_stderr_to_file() {
output_both 1> tmp/redirect_test5.txt 2> tmp/redirect_test6.txt
local contents5=$(cat tmp/redirect_test5.txt)
local contents6=$(cat tmp/redirect_test6.txt)
assertEqual "$contents5" __
assertEqual "$contents6" __
}
| mit |
kelly-keating/kelly-keating.github.io | webpack.config.js | 324 | module.exports = {
entry: './client/index.js',
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
},
resolve: {
extensions: ['.js', '.jsx']
},
devtool: 'source-map'
}
| mit |
ShinjiTanimoto/shirasagi | spec/factories/category/nodes.rb | 384 | FactoryBot.define do
factory :category_node_base, class: Category::Node::Base, traits: [:cms_node] do
route { "category/base" }
end
factory :category_node_node, class: Category::Node::Node, traits: [:cms_node] do
route { "category/node" }
end
factory :category_node_page, class: Category::Node::Page, traits: [:cms_node] do
route { "category/page" }
end
end
| mit |
miherlosev/testcafe-hammerhead | src/typings/upload.d.ts | 447 | import { ServiceMessage } from './proxy';
export interface FileInfo {
name: string;
type: string;
data: string;
}
export interface FileInputInfo {
name: string;
files: FileInfo[];
value: string;
}
export interface GetUploadedFilesServiceMessage extends ServiceMessage {
filePaths: string[];
}
export interface StoreUploadedFilesServiceMessage extends ServiceMessage {
data: string[];
fileNames: string[];
}
| mit |
jose/defects4j | framework/test/resources/output/foo/bar/FailingTests.java | 512 | package foo.bar;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FailingTests {
@Test
public void test0() {}
// Defects4J: flaky method
// @Test
// public void test0() {
// assertTrue(false);
// }
@Test
public void test1() {}
// Defects4J: flaky method
// @Test
// public void test1() {
// assertTrue(false);
// }
@Test
public void test2() {}
// Defects4J: flaky method
// @Test
// public void test2() {
// assertTrue(false);
// }
}
| mit |
eleanors/EaseJS | core/test/assets/test2.js | 122 | define( 'test2', ['test3', 'test4'], function( obj, str ){
return 'test2 is done, deps : [ ' + obj.name + str + ' ]';
}); | mit |
hiuwo/acq4 | acq4/analysis/scripts/eventExplorer.py | 15462 | from PyQt4 import QtCore, QtGui
import acq4.Manager
import acq4.pyqtgraph as pg
import acq4.pyqtgraph.opengl as gl
import numpy as np
import acq4.util.functions as fn
import re
man = acq4.Manager.getManager()
## update DB field to reflect dir meta info
#for i in db.select('Cell', ['rowid']):
#d = db.getDir('Cell', i[0])
#typ = d.info().get('type', '')
#db.update('Cell', {'type': typ}, rowid=i[0])
#print d, typ
global eventView, siteView, cells
eventView = 'events_view'
siteView = 'sites_view'
firstRun = False
if 'events' not in locals():
global events
events = {}
firstRun = True
win = QtGui.QMainWindow()
#cw = QtGui.QWidget()
layout = pg.LayoutWidget()
#layout = QtGui.QGridLayout()
#layout.setContentsMargins(0,0,0,0)
#layout.setSpacing(0)
#cw.setLayout(layout)
win.setCentralWidget(layout)
cellCombo = QtGui.QComboBox()
cellCombo.setSizeAdjustPolicy(cellCombo.AdjustToContents)
layout.addWidget(cellCombo)
reloadBtn = QtGui.QPushButton('reload')
layout.addWidget(reloadBtn)
separateCheck = QtGui.QCheckBox("color pre/post")
layout.addWidget(separateCheck)
colorCheck = QtGui.QCheckBox("color y position")
layout.addWidget(colorCheck)
errLimitSpin = pg.SpinBox(value=0.7, step=0.1)
layout.addWidget(errLimitSpin)
lengthRatioLimitSpin = pg.SpinBox(value=1.5, step=0.1)
layout.addWidget(lengthRatioLimitSpin)
postRgnStartSpin = pg.SpinBox(value=0.500, step=0.01, siPrefix=True, suffix='s')
layout.addWidget(postRgnStartSpin)
postRgnStopSpin = pg.SpinBox(value=0.700, step=0.01, siPrefix=True, suffix='s')
layout.addWidget(postRgnStopSpin)
spl1 = QtGui.QSplitter()
spl1.setOrientation(QtCore.Qt.Vertical)
layout.addWidget(spl1, row=1, col=0, rowspan=1, colspan=8)
pw1 = pg.PlotWidget()
spl1.addWidget(pw1)
pw1.setLabel('left', 'Amplitude', 'A')
pw1.setLabel('bottom', 'Decay Tau', 's')
spl2 = QtGui.QSplitter()
spl2.setOrientation(QtCore.Qt.Horizontal)
spl1.addWidget(spl2)
pw2 = pg.PlotWidget(labels={'bottom': ('time', 's')})
spl2.addWidget(pw2)
tab = QtGui.QTabWidget()
spl2.addWidget(tab)
## For viewing cell morphology
gv = pg.GraphicsView()
gv.setBackgroundBrush(pg.mkBrush('w'))
image = pg.ImageItem()
gv.addItem(image)
gv.enableMouse()
gv.setAspectLocked(True)
tab.addTab(gv, 'Morphology')
## 3D atlas
import acq4.analysis.atlas.CochlearNucleus as CN
atlas = CN.CNAtlasDisplayWidget()
atlas.showLabel('DCN')
atlas.showLabel('AVCN')
atlas.showLabel('PVCN')
tab.addTab(atlas, 'Atlas')
atlasPoints = gl.GLScatterPlotItem()
atlas.addItem(atlasPoints)
win.show()
win.resize(1000,800)
sp1 = pw1.scatterPlot([], pen=pg.mkPen(None), brush=(200,200,255,70), identical=True, size=8)
sp2 = pw1.scatterPlot([], pen=pg.mkPen(None), brush=(255,200,200,70), identical=True, size=8)
sp3 = pw1.scatterPlot([], pen=pg.mkPen(None), brush=(100,255,100,70), identical=True, size=8)
sp4 = pw1.scatterPlot([], pen=pg.mkPen(None), size=8)
print "Reading cell list..."
#import os, pickle
#md = os.path.abspath(os.path.split(__file__)[0])
#cacheFile = os.path.join(md, 'eventCache.p')
#if os.path.isfile(cacheFile):
#print "Read from cache..."
#ev = pickle.load(open(cacheFile, 'r'))
#else:
#pickle.dump(ev, open(cacheFile, 'w'))
## create views that link cell information to events/sites
db = man.getModule('Data Manager').currentDatabase()
if not db.hasTable(siteView):
print "Creating DB views."
db.createView(siteView, ['photostim_sites', 'DirTable_Protocol', 'DirTable_Cell']) ## seems to be unused.
if not db.hasTable(eventView):
db.createView(eventView, ['photostim_events', 'DirTable_Protocol', 'DirTable_Cell'])
cells = db.select(siteView, ['CellDir'], distinct=True)
cells = [c['CellDir'] for c in cells]
cells.sort(lambda a,b: cmp(a.name(), b.name()))
cellCombo.addItem('')
for c in cells:
cellCombo.addItem(c.name(relativeTo=man.baseDir))
#cellSpin.setMaximum(len(cells)-1)
print "Done."
def loadCell(cell, reloadData=False):
global events
if reloadData:
events.pop(cell, None)
if cell in events:
return
db = man.getModule('Data Manager').currentDatabase()
mod = man.dataModel
allEvents = []
hvals = {}
nEv = 0
positionCache = {}
tcache = {}
print "Loading all events for cell", cell
tot = db.select(eventView, 'count()', where={'CellDir': cell})[0]['count()']
print tot, "total events.."
with pg.ProgressDialog('Loading event data...', maximum=tot, wait=0) as dlg:
for ev in db.iterSelect(eventView, ['ProtocolSequenceDir', 'SourceFile', 'fitAmplitude', 'fitTime', 'fitDecayTau', 'fitRiseTau', 'fitTimeToPeak', 'fitLengthOverDecay', 'fitFractionalError', 'userTransform', 'CellType', 'CellDir', 'ProtocolDir'], where={'CellDir': cell}, toArray=True, chunkSize=200):
extra = np.empty(ev.shape, dtype=[('right', float), ('anterior', float), ('dorsal', float), ('holding', float)])
## insert holding levels
for i in range(len(ev)):
sd = ev[i]['ProtocolSequenceDir']
if sd not in hvals:
cf = ev[i]['SourceFile']
hvals[sd] = mod.getClampHoldingLevel(cf)
#print hvals[sd], cf
extra[i]['holding'] = hvals[sd]
## insert positions
for i in range(len(ev)):
protoDir = ev[i]['SourceFile'].parent()
key = protoDir
#key = (ev[i]['ProtocolSequenceDir'], ev[i]['SourceFile'])
if key not in positionCache:
#try:
#dh = ev[i]['ProtocolDir']
#p1 = pg.Point(dh.info()['Scanner']['position'])
#if key[0] not in tcache:
#tr = pg.SRTTransform()
#tr.restoreState(dh.parent().info()['userTransform'])
#tcache[key[0]] = tr
#trans = tcache[key[0]]
#p2 = trans.map(p1)
#pcache[key] = (p2.x(),p2.y())
#except:
#print key
#raise
rec = db.select('CochlearNucleus_Protocol', where={'ProtocolDir': protoDir})
if len(rec) == 0:
pos = (None, None, None)
elif len(rec) == 1:
pos = (rec[0]['right'], rec[0]['anterior'], rec[0]['dorsal'])
elif len(rec) == 2:
raise Exception("Multiple position records for %s!" % str(protoDir))
positionCache[key] = pos
extra[i]['right'] = positionCache[key][0]
extra[i]['anterior'] = positionCache[key][1]
extra[i]['dorsal'] = positionCache[key][2]
ev = fn.concatenateColumns([ev, extra])
allEvents.append(ev)
nEv += len(ev)
dlg.setValue(nEv)
if dlg.wasCanceled():
raise Exception('Canceled by user.')
ev = np.concatenate(allEvents)
numExSites = 0
numInSites = 0
for site in db.select(siteView, 'ProtocolSequenceDir', where={'CellDir': cell}):
h = hvals.get(site['ProtocolSequenceDir'],None)
if h is None:
continue
if h > -0.02:
numInSites += 1
elif h < -0.04:
numExSites += 1
events[cell] = (ev, numExSites, numInSites)
def init():
if not firstRun:
return
cellCombo.currentIndexChanged.connect(showCell)
separateCheck.toggled.connect(showCell)
colorCheck.toggled.connect(showCell)
errLimitSpin.valueChanged.connect(showCell)
lengthRatioLimitSpin.valueChanged.connect(showCell)
reloadBtn.clicked.connect(reloadCell)
for s in [sp1, sp2, sp3, sp4]:
s.sigPointsClicked.connect(plotClicked)
def plotClicked(plt, pts):
pt = pts[0]
#(id, fn, time) = pt.data
#[['SourceFile', 'ProtocolSequenceDir', 'fitTime']]
#fh = db.getDir('ProtocolSequence', id)[fn]
fh = pt.data()['SourceFile']
id = pt.data()['ProtocolSequenceDir']
time = pt.data()['fitTime']
data = fh.read()['Channel':'primary']
data = fn.besselFilter(data, 8e3)
p = pw2.plot(data, clear=True)
pos = time / data.xvals('Time')[-1]
arrow = pg.CurveArrow(p, pos=pos)
xr = pw2.viewRect().left(), pw2.viewRect().right()
if time < xr[0] or time > xr[1]:
w = xr[1]-xr[0]
pw2.setXRange(time-w/5., time+4*w/5., padding=0)
fitLen = pt.data()['fitDecayTau']*pt.data()['fitLengthOverDecay']
x = np.linspace(time, time+fitLen, fitLen * 50e3)
v = [pt.data()['fitAmplitude'], pt.data()['fitTime'], pt.data()['fitRiseTau'], pt.data()['fitDecayTau']]
y = fn.pspFunc(v, x, risePower=2.0) + data[np.argwhere(data.xvals('Time')>time)[0]-1]
pw2.plot(x, y, pen='b')
#plot.addItem(arrow)
def select(ev, ex=True):
#if source is not None:
#ev = ev[ev['CellDir']==source]
if ex:
ev = ev[ev['holding'] < -0.04] # excitatory events
ev = ev[(ev['fitAmplitude'] < 0) * (ev['fitAmplitude'] > -2e-10)]
else:
ev = ev[(ev['holding'] >= -0.02) * (ev['holding'] <= 0.01)] ## inhibitory events
ev = ev[(ev['fitAmplitude'] > 0) * (ev['fitAmplitude'] < 2e-10)]
ev = ev[(0 < ev['fitDecayTau']) * (ev['fitDecayTau'] < 0.2)] # select decay region
ev = ev[ev['fitFractionalError'] < errLimitSpin.value()]
ev = ev[ev['fitLengthOverDecay'] > lengthRatioLimitSpin.value()]
return ev
def reloadCell():
showCell(reloadData=True)
def showCell(**kwds):
pw2.clear()
reloadData = kwds.get('reloadData', False)
#global lock
#if lock:
#return
#lock = True
QtGui.QApplication.processEvents() ## prevents double-spin
#lock = False
cell = cells[cellCombo.currentIndex()-1]
dh = cell #db.getDir('Cell', cell)
loadCell(dh, reloadData=reloadData)
try:
image.setImage(dh['morphology.png'].read())
gv.setRange(image.sceneBoundingRect())
except:
image.setImage(np.zeros((2,2)))
pass
ev, numExSites, numInSites = events[cell]
ev2 = select(ev, ex=True)
ev3 = select(ev, ex=False)
if colorCheck.isChecked():
sp1.hide()
sp2.hide()
sp3.hide()
sp4.show()
start = postRgnStart()
stop = postRgnStop()
ev2post = ev2[(ev2['fitTime']>start) * (ev2['fitTime']<stop)]
ev3post = ev3[(ev3['fitTime']>start) * (ev3['fitTime']<stop)]
ev4 = np.concatenate([ev2post, ev3post])
yMax = ev4['dorsal'].max()
yMin = ev4['dorsal'].min()
brushes = []
for i in range(len(ev4)):
hue = 0.6*((ev4[i]['dorsal']-yMin) / (yMax-yMin))
brushes.append(pg.hsvColor(hue, 1.0, 1.0, 0.3))
#pts.append({
#'pos': (ev4[i]['fitDecayTau'], ev4[i]['fitAmplitude']),
#'brush': pg.hsvColor(hue, 1, 1, 0.3),
#'data': ev4[i]
#})
sp4.setData(x=ev4['fitDecayTau'], y=ev4['fitAmplitude'], symbolBrush=brushes, data=ev4)
else:
sp1.show()
sp2.show()
#sp3.show()
sp4.hide()
## excitatory
if separateCheck.isChecked():
pre = ev2[ev2['fitTime']< preRgnStop()]
post = ev2[(ev2['fitTime'] > postRgnStart()) * (ev2['fitTime'] < postRgnStop())]
else:
pre = ev2
sp1.setData(x=pre['fitDecayTau'], y=pre['fitAmplitude'], data=pre);
#print "Cell ", cell
#print " excitatory:", np.median(ev2['fitDecayTau']), np.median(ev2['fitAmplitude'])
## inhibitory
if separateCheck.isChecked():
pre = ev3[ev3['fitTime']< preRgnStop()]
post2 = ev3[(ev3['fitTime'] > postRgnStart()) * (ev3['fitTime'] < postRgnStop())]
post = np.concatenate([post, post2])
else:
pre = ev3
sp2.setData(x=pre['fitDecayTau'], y=pre['fitAmplitude'], data=pre);
#print " inhibitory:", np.median(ev2['fitDecayTau']), np.median(ev2['fitAmplitude'])
if separateCheck.isChecked():
sp3.setData(x=post['fitDecayTau'], y=post['fitAmplitude'], data=post)
sp3.show()
else:
sp3.hide()
try:
typ = ev2[0]['CellType']
except:
typ = ev3[0]['CellType']
sr = spontRate(ev2, numExSites)
sri = spontRate(ev3, numInSites)
title = "%s -- %s --- <span style='color: #99F;'>ex:</span> %s %s %s %0.1fHz --- <span style='color: #F99;'>in:</span> %s %s %s %0.1fHz" % (
dh.name(relativeTo=dh.parent().parent().parent()),
typ,
pg.siFormat(np.median(ev2['fitTimeToPeak']), error=np.std(ev2['fitTimeToPeak']), space=False, suffix='s'),
pg.siFormat(np.median(ev2['fitDecayTau']), error=np.std(ev2['fitDecayTau']), space=False, suffix='s'),
pg.siFormat(np.median(ev2['fitAmplitude']), error=np.std(ev2['fitAmplitude']), space=False, suffix='A'),
sr,
pg.siFormat(np.median(ev3['fitTimeToPeak']), error=np.std(ev3['fitTimeToPeak']), space=False, suffix='s'),
pg.siFormat(np.median(ev3['fitDecayTau']), error=np.std(ev3['fitDecayTau']), space=False, suffix='s'),
pg.siFormat(np.median(ev3['fitAmplitude']), error=np.std(ev3['fitAmplitude']), space=False, suffix='A'),
sri)
print re.sub(r'<[^>]+>', '', title)
pw1.setTitle(title)
### show cell in atlas
#rec = db.select('CochlearNucleus_Cell', where={'CellDir': cell})
#pts = []
#if len(rec) > 0:
#pos = (rec[0]['right'], rec[0]['anterior'], rec[0]['dorsal'])
#pts = [{'pos': pos, 'size': 100e-6, 'color': (0.7, 0.7, 1.0, 1.0)}]
### show event positions
evSpots = {}
for rec in ev:
p = (rec['right'], rec['anterior'], rec['dorsal'])
evSpots[p] = None
pos = np.array(evSpots.keys())
atlasPoints.setData(pos=pos, )
def spontRate(ev, n):
## This is broken. It does not take into account recordings that had no events.
ev = ev[ev['fitTime'] < preRgnStop()]
#count = {}
#dirs = set()
#for i in range(len(ev)):
#key = (ev[i]['ProtocolSequenceDir'], ev[i]['SourceFile'])
#dirs.add(set)
#if key not in count:
#count[key] = 0
#count[key] += 1
#sr = np.mean([v/(preRgnStop()) for v in count.itervalues()])
if n == 0:
return 0
return len(ev) / (preRgnStop() * n)
def preRgnStop():
return postRgnStartSpin.value() - 0.002
def postRgnStart():
return postRgnStartSpin.value() + 0.002
def postRgnStop():
return postRgnStopSpin.value()
init() | mit |
Apozhidaev/terminal.mobi | src/components/ProgressBar/index.js | 517 | import React, { PureComponent } from 'react';
class ProgressBar extends PureComponent {
render() {
const { progress, className, percent = 100 } = this.props;
return (
<div className={className}>
{progress && <div className="progress">
<div
className="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar"
style={{ width: `${percent}%` }}
/>
</div>}
</div>
);
}
}
export default ProgressBar;
| mit |
RSpace/aframe | src/utils/tracked-controls.js | 6862 | var DEFAULT_HANDEDNESS = require('../constants').DEFAULT_HANDEDNESS;
var AXIS_LABELS = ['x', 'y', 'z', 'w'];
var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
/**
* Called on controller component `.play` handlers.
* Check if controller matches parameters and inject tracked-controls component.
* Handle event listeners.
* Generate controllerconnected or controllerdisconnected events.
*
* @param {object} component - Tracked controls component.
* @param {object} idPrefix - Prefix to match in gamepad id if any.
* @param {object} queryObject - Map of values to match.
*/
module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
var el = component.el;
var isPresent = isControllerPresent(component, idPrefix, queryObject);
// If component was previously paused and now playing, re-add event listeners.
// Handle the event listeners here since this helper method is control of calling
// `.addEventListeners` and `.removeEventListeners`.
if (component.controllerPresent && !component.controllerEventsActive) {
component.addEventListeners();
}
// Nothing changed, no need to do anything.
if (isPresent === component.controllerPresent) { return isPresent; }
component.controllerPresent = isPresent;
// Update controller presence.
if (isPresent) {
component.injectTrackedControls();
component.addEventListeners();
el.emit('controllerconnected', {name: component.name, component: component});
} else {
component.removeEventListeners();
el.emit('controllerdisconnected', {name: component.name, component: component});
}
};
/**
* Enumerate controller (that have pose) and check if they match parameters.
*
* @param {object} component - Tracked controls component.
* @param {object} idPrefix - Prefix to match in gamepad id if any.
* @param {object} queryObject - Map of values to match.
*/
function isControllerPresent (component, idPrefix, queryObject) {
var gamepads;
var sceneEl = component.el.sceneEl;
var trackedControlsSystem;
var filterControllerIndex = queryObject.index || 0;
if (!idPrefix) { return false; }
trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
if (!trackedControlsSystem) { return false; }
gamepads = trackedControlsSystem.controllers;
if (!gamepads.length) { return false; }
return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand,
filterControllerIndex);
}
module.exports.isControllerPresent = isControllerPresent;
/**
* Walk through the given controllers to find any where the device ID equals
* filterIdExact, or startsWith filterIdPrefix.
* A controller where this considered true is considered a 'match'.
*
* For each matching controller:
* If filterHand is set, and the controller:
* is handed, we further verify that controller.hand equals filterHand.
* is unhanded (controller.hand is ''), we skip until we have found a
* number of matching controllers that equals filterControllerIndex
* If filterHand is not set, we skip until we have found the nth matching
* controller, where n equals filterControllerIndex
*
* The method should be called with one of: [filterIdExact, filterIdPrefix] AND
* one or both of: [filterHand, filterControllerIndex]
*
* @param {object} controllers - Array of gamepads to search
* @param {string} filterIdExact - If set, used to find controllers with id === this value
* @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
* @param {object} filterHand - If set, further filters controllers with matching 'hand' property
* @param {object} filterControllerIndex - Find the nth matching controller,
* where n equals filterControllerIndex. defaults to 0.
*/
function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand,
filterControllerIndex) {
var controller;
var i;
var matchingControllerOccurence = 0;
var targetControllerMatch = filterControllerIndex || 0;
for (i = 0; i < controllers.length; i++) {
controller = controllers[i];
// Determine if the controller ID matches our criteria.
if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
continue;
}
if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
// If the hand filter and controller handedness are defined we compare them.
if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
// If we have detected an unhanded controller and the component was asking
// for a particular hand, we need to treat the controllers in the array as
// pairs of controllers. This effectively means that we need to skip
// NUM_HANDS matches for each controller number, instead of 1.
if (filterHand && !controller.hand) {
targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
}
// We are looking for the nth occurence of a matching controller
// (n equals targetControllerMatch).
if (matchingControllerOccurence === targetControllerMatch) { return controller; }
++matchingControllerOccurence;
}
return undefined;
}
module.exports.findMatchingController = findMatchingController;
/**
* Emit specific `moved` event(s) if axes changed based on original axismoved event.
*
* @param {object} component - Controller component in use.
* @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
* @param {object} evt - Event to process.
*/
module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
var axes;
var buttonType;
var changed;
var detail;
var j;
for (buttonType in axesMapping) {
axes = axesMapping[buttonType];
changed = false;
for (j = 0; j < axes.length; j++) {
if (evt.detail.changed[axes[j]]) { changed = true; }
}
if (!changed) { continue; }
// Axis has changed. Emit the specific moved event with axis values in detail.
detail = {};
for (j = 0; j < axes.length; j++) {
detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
}
component.el.emit(buttonType + 'moved', detail);
}
};
/**
* Handle a button event and reemits the events.
*
* @param {string} id - id of the button.
* @param {string} evtName - name of the reemitted event
* @param {object} component - reference to the component
* @param {string} hand - handedness of the controller: left or right.
*/
module.exports.onButtonEvent = function (id, evtName, component, hand) {
var mapping = hand ? component.mapping[hand] : component.mapping;
var buttonName = mapping.buttons[id];
component.el.emit(buttonName + evtName);
if (component.updateModel) {
component.updateModel(buttonName, evtName);
}
};
| mit |
quentinbernet/quentinbernet.github.io | node_modules/caniuse-lite/data/features/path2d.js | 984 | module.exports={A:{A:{"2":"K D G E A B iB"},B:{"1":"AB","2":"2 C","132":"d J M H I"},C:{"1":"0 1 3 4 7 8 9 r s t u v w x y z IB BB CB DB GB","2":"2 fB FB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z ZB YB","132":"6 a b c e f g h i j k l m n o L q"},D:{"1":"GB SB OB MB lB NB KB AB PB QB","2":"2 6 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e","132":"0 1 3 4 7 8 9 f g h i j k l m n o L q r s t u v w x y z IB BB CB DB"},E:{"1":"5 A B C WB XB p aB","2":"F N K D RB JB TB UB","132":"G E VB"},F:{"1":"0 1 y z","2":"5 E B C J M H I O P Q R bB cB dB eB p EB gB","132":"6 S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x"},G:{"1":"nB oB pB qB rB sB tB uB","2":"JB hB HB jB kB LB","16":"G","132":"mB"},H:{"2":"vB"},I:{"1":"4","2":"FB F wB xB yB zB HB 0B 1B"},J:{"1":"A","2":"D"},K:{"2":"5 A B C p EB","132":"L"},L:{"1":"KB"},M:{"1":"3"},N:{"2":"A B"},O:{"132":"2B"},P:{"132":"F 3B 4B 5B 6B 7B"},Q:{"132":"8B"},R:{"132":"9B"},S:{"1":"AC"}},B:1,C:"Path2D"};
| mit |
mwalkerwells/flow-typed | definitions/npm/pretty-bytes_v4.x.x/test_pretty-bytes_v4.x.x.js | 147 | const prettyBytes = require("pretty-bytes");
(prettyBytes(123): string);
// $ExpectError
prettyBytes("123");
// $ExpectError
prettyBytes(true);
| mit |
bhlzlx/ogre | Samples/Browser/src/SampleBrowser.cpp | 3418 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgrePlatform.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
#include <coecntrl.h>
#endif
#include "SampleBrowser.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "OgreString.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "SampleBrowser_OSX.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
#include "SampleBrowser_iOS.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_NACL
#include "SampleBrowser_NaCl.h"
#endif
#if OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN && OGRE_PLATFORM != OGRE_PLATFORM_NACL
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT)
#else
int main(int argc, char *argv[])
#endif
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
[pool release];
return retVal;
#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
mAppDelegate = [[AppDelegate alloc] init];
[[NSApplication sharedApplication] setDelegate:mAppDelegate];
int retVal = NSApplicationMain(argc, (const char **) argv);
[pool release];
return retVal;
#else
try
{
bool nograb = false;
#if OGRE_PLATFORM != OGRE_PLATFORM_WIN32
if (argc >= 2 && Ogre::String(argv[1]) == "nograb")
nograb = true;
#else
// somewhat hacky, but much simpler than other solutions
if (Ogre::String(cmdLine).find("nograb") != Ogre::String::npos)
nograb = true;
#endif
OgreBites::SampleBrowser sb (nograb);
sb.go();
}
catch (Ogre::Exception& e)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
}
#endif
return 0;
}
#endif // OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN
| mit |
ALTELMA/OfficeEquipmentManager | application/libraries/PHPExcel/branches/v1.6.3/Classes/PHPExcel/Shared/Date.php | 8411 | <?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2008 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Shared
* @copyright Copyright (c) 2006 - 2008 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/** PHPExcel_Cell */
require_once 'PHPExcel/Cell.php';
/** PHPExcel_Style_NumberFormat */
require_once 'PHPExcel/Style/NumberFormat.php';
/**
* PHPExcel_Shared_Date
*
* @category PHPExcel
* @package PHPExcel_Shared
* @copyright Copyright (c) 2006 - 2008 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Shared_Date
{
/** constants */
const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0
const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0
private static $ExcelBaseDate = self::CALENDAR_WINDOWS_1900;
public static $dateTimeObjectType = 'DateTime';
/**
* Set the Excel calendar (Windows 1900 or Mac 1904)
*
* @param integer $baseDate Excel base date
* @return boolean Success or failure
*/
public static function setExcelCalendar($baseDate) {
if (($baseDate == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904)) {
self::$ExcelBaseDate = $baseDate;
return True;
}
return False;
} // function setExcelCalendar()
/**
* Return the Excel calendar (Windows 1900 or Mac 1904)
*
* @return integer $baseDate Excel base date
*/
public static function getExcelCalendar() {
return self::$ExcelBaseDate;
} // function getExcelCalendar()
/**
* Convert a date from Excel to PHP
*
* @param long $dateValue Excel date/time value
* @return long PHP serialized date/time
*/
public static function ExcelToPHP($dateValue = 0) {
if (self::$ExcelBaseDate == self::CALENDAR_WINDOWS_1900) {
$myExcelBaseDate = 25569;
// Adjust for the spurious 29-Feb-1900 (Day 60)
if ($dateValue < 60) {
--$myExcelBaseDate;
}
} else {
$myExcelBaseDate = 24107;
}
// Perform conversion
if ($dateValue >= 1) {
$utcDays = $dateValue - $myExcelBaseDate;
$returnValue = round($utcDays * 24 * 60 * 60);
} else {
$hours = round($dateValue * 24);
$mins = round($dateValue * 24 * 60) - round($hours * 60);
$secs = round($dateValue * 24 * 60 * 60) - round($hours * 60 * 60) - round($mins * 60);
$returnValue = mktime($hours, $mins, $secs);
}
// Return
return $returnValue;
} // function ExcelToPHP()
/**
* Convert a date from Excel to a PHP Date/Time object
*
* @param long $dateValue Excel date/time value
* @return long PHP date/time object
*/
public static function ExcelToPHPObject($dateValue = 0) {
$dateTime = self::ExcelToPHP($dateValue);
$days = floor($dateTime / 86400);
$time = round((($dateTime / 86400) - $days) * 86400);
$hours = round($time / 3600);
$minutes = round($time / 60) - ($hours * 60);
$seconds = round($time) - ($hours * 3600) - ($minutes * 60);
$dateObj = date_create('1-Jan-1970+'.$days.' days');
$dateObj->setTime($hours,$minutes,$seconds);
return $dateObj;
} // function ExcelToPHPObject()
/**
* Convert a date from PHP to Excel
*
* @param mixed $dateValue PHP serialized date/time or date object
* @return mixed Excel date/time value
* or boolean False on failure
*/
public static function PHPToExcel($dateValue = 0) {
$saveTimeZone = date_default_timezone_get();
date_default_timezone_set('UTC');
$retValue = False;
if ((is_object($dateValue)) && ($dateValue instanceof self::$dateTimeObjectType)) {
$retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'),
$dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s')
);
} elseif (is_numeric($dateValue)) {
$retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue),
date('H',$dateValue), date('i',$dateValue), date('s',$dateValue)
);
}
date_default_timezone_set($saveTimeZone);
return $retValue;
} // function PHPToExcel()
/**
* FormattedPHPToExcel
*
* @param long $year
* @param long $month
* @param long $day
* @param long $hours
* @param long $minutes
* @param long $seconds
* @return long Excel date/time value
*/
public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) {
if (self::$ExcelBaseDate == self::CALENDAR_WINDOWS_1900) {
//
// Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
// This affects every date following 28th February 1900
//
$excel1900isLeapYear = True;
if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = False; }
$myExcelBaseDate = 2415020;
} else {
$myExcelBaseDate = 2416481;
$excel1900isLeapYear = False;
}
// Julian base date Adjustment
if ($month > 2) {
$month = $month - 3;
} else {
$month = $month + 9;
--$year;
}
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$century = substr($year,0,2);
$decade = substr($year,2,2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
return $excelDate + $excelTime;
} // function FormattedPHPToExcel()
/**
* Is a given cell a date/time?
*
* @param PHPExcel_Cell $pCell
* @return boolean
*/
public static function isDateTime(PHPExcel_Cell $pCell) {
return self::isDateTimeFormat($pCell->getParent()->getStyle($pCell->getCoordinate())->getNumberFormat());
} // function isDateTime()
/**
* Is a given number format a date/time?
*
* @param PHPExcel_Style_NumberFormat $pFormat
* @return boolean
*/
public static function isDateTimeFormat(PHPExcel_Style_NumberFormat $pFormat) {
return self::isDateTimeFormatCode($pFormat->getFormatCode());
} // function isDateTimeFormat()
private static $possibleCharacters = array('y', 'm', 'd', 'H', 'i', 's');
/**
* Is a given number format code a date/time?
*
* @param string $pFormatCode
* @return boolean
*/
public static function isDateTimeFormatCode($pFormatCode = '') {
// Switch on formatcode
switch ($pFormatCode) {
case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8:
case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH:
return true;
}
// Try checking all possible characters
foreach (self::$possibleCharacters as $possibleCharacter) {
if (eregi($possibleCharacter, $pFormatCode)) {
return true;
}
}
// No date...
return false;
} // function isDateTimeFormatCode()
}
| mit |
mhfowler/mhfowler | settings/local.py | 239 | from settings.common import *
DATABASES = {
'default': {
"ENGINE": "django.db.backends.mysql",
"NAME": "mhfowler",
"USER": "root",
"PASSWORD": "",
"HOST": "localhost",
"PORT": ""
}
} | mit |
backpackcoder/world-in-flames | src/app/routes/forms/components/layouts/ReviewForm.js | 5184 | import React from 'react'
import UiValidate from '../../../../components/forms/validation/UiValidate'
import MaskedInput from '../../../../components/forms/inputs/MaskedInput'
import UiDatepicker from '../../../../components/forms/inputs/UiDatepicker'
const validationOptions = {
// Rules for form validation
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
review: {
required: true,
minlength: 20
},
quality: {
required: true
},
reliability: {
required: true
},
overall: {
required: true
}
},
// Messages for form validation
messages: {
name: {
required: 'Please enter your name'
},
email: {
required: 'Please enter your email address',
email: '<i class="fa fa-warning"></i><strong>Please enter a VALID email addres</strong>'
},
review: {
required: 'Please enter your review'
},
quality: {
required: 'Please rate quality of the product'
},
reliability: {
required: 'Please rate reliability of the product'
},
overall: {
required: 'Please rate the product'
}
}
};
export default class ReviewForm extends React.Component {
onSubmit(e) {
e.preventDefault();
console.log('submit stuff')
}
render() {
return (
<UiValidate options={validationOptions}>
<form id="review-form" className="smart-form" noValidate="novalidate" onSubmit={this.onSubmit}>
<header>
Review form
</header>
<fieldset>
<section>
<label className="input"> <i className="icon-append fa fa-user"/>
<input type="text" name="name" id="name" placeholder="Your name"/>
</label>
</section>
<section>
<label className="input"> <i className="icon-append fa fa-envelope-o"/>
<input type="email" name="email" id="email" placeholder="Your e-mail"/>
</label>
</section>
<section>
<label className="label"/>
<label className="textarea"> <i className="icon-append fa fa-comment"/>
<textarea rows="3" name="review" id="review" placeholder="Text of the review"/>
</label>
</section>
<section>
<div className="rating">
<input type="radio" name="quality" id="quality-5"/>
<label htmlFor="quality-5"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-4"/>
<label htmlFor="quality-4"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-3"/>
<label htmlFor="quality-3"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-2"/>
<label htmlFor="quality-2"><i className="fa fa-star"/></label>
<input type="radio" name="quality" id="quality-1"/>
<label htmlFor="quality-1"><i className="fa fa-star"/></label>
Quality of the product
</div>
<div className="rating">
<input type="radio" name="reliability" id="reliability-5"/>
<label htmlFor="reliability-5"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-4"/>
<label htmlFor="reliability-4"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-3"/>
<label htmlFor="reliability-3"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-2"/>
<label htmlFor="reliability-2"><i className="fa fa-star"/></label>
<input type="radio" name="reliability" id="reliability-1"/>
<label htmlFor="reliability-1"><i className="fa fa-star"/></label>
Reliability of the product
</div>
<div className="rating">
<input type="radio" name="overall" id="overall-5"/>
<label htmlFor="overall-5"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-4"/>
<label htmlFor="overall-4"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-3"/>
<label htmlFor="overall-3"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-2"/>
<label htmlFor="overall-2"><i className="fa fa-star"/></label>
<input type="radio" name="overall" id="overall-1"/>
<label htmlFor="overall-1"><i className="fa fa-star"/></label>
Overall rating
</div>
</section>
</fieldset>
<footer>
<button type="submit" className="btn btn-primary">
Validate Form
</button>
</footer>
</form>
</UiValidate>
)
}
} | mit |
SyliusBot/Sylius | src/Sylius/Bundle/AdminBundle/EmailManager/OrderEmailManager.php | 992 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\EmailManager;
use Sylius\Bundle\CoreBundle\Mailer\Emails;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
final class OrderEmailManager implements OrderEmailManagerInterface
{
public function __construct(private SenderInterface $emailSender)
{
}
public function sendConfirmationEmail(OrderInterface $order): void
{
$this->emailSender->send(
Emails::ORDER_CONFIRMATION_RESENT,
[$order->getCustomer()->getEmail()],
[
'order' => $order,
'channel' => $order->getChannel(),
'localeCode' => $order->getLocaleCode(),
]
);
}
}
| mit |
PrJared/sabbath-school-lessons | src/pl/2020-01/01/07.md | 2576 | ---
title: Do dalszego studium
date: 03/01/2020
---
„Biblia została zaplanowana jako przewodnik dla wszystkich, którzy chcą poznać wolę swego Stwórcy. Bóg dał ludziom pewne niezawodne proroctwa; aniołowie, a nawet sam Chrystus przyszli, aby Daniel i Jan dowiedzieli się o tym, co ma wkrótce nadejść. Te istotne kwestie dotyczące naszego zbawienia nie pozostały tajemnicą. Nie zostały przedstawione w taki sposób, aby wprawić w zakłopotanie i wprowadzić w błąd uczciwego poszukiwacza prawdy. Pan powiedział przez proroka Habakuka: »Zapisz to, co widziałeś, (…) aby to można szybko przeczytać« (Ha 2,2). Słowo Boże jest jasne dla wszystkich, którzy studiują je z otwartym w modlitwie sercem. Każda prawdziwie szczera dusza uzyska światło prawdy. »Światłości nasiano sprawiedliwemu« (Ps 97,11 BG). Żaden Kościół nie jest w stanie rozwijać się w świętości, jeśli jego członkowie nie będą szczerze poszukiwali prawdy niczym ukrytego skarbu”1.
„Studiujcie historię Daniela i jego towarzyszy. Choć żyli tam, gdzie żyli, i ze wszystkich stron otoczeni byli pokusą pobłażania swoim zachciankom, to jednak oddawali cześć Bogu i chwalili Go w swoim codziennym życiu. Postanowili unikać zła. Wystrzegali się wkraczania na ścieżkę nieprzyjaciela. Bóg nagrodził ich wytrwałą lojalność obfitymi błogosławieństwami”2.
**Pytania do dyskusji**
`1. Gdy studiujemy Księgę Daniela, musimy zwrócić uwagę na pewne bardzo ważne zagadnienie. Bóg nie tylko panuje nad narodami, ale także zna dobrze każdego z nas, i to w najpełniejszy możliwy sposób. Na przykład — jak czytamy o tym w 2. rozdziale Księgi Daniela — Bóg dał proroczy sen pogańskiemu królowi. Aby wejść w czyjś umysł we śnie i wszczepić tam logiczny przekaz, trzeba bliskości, o jakiej nie mamy nawet najmniejszego pojęcia. Jednocześnie, jak czytamy o tym, charakter tego snu świadczy, że Bóg panuje nawet nad największymi światowymi imperiami i wie wszystko, co się wydarzy aż do końca. Jakie pocieszenie i nadzieję możemy czerpać z takiego obrazu rzeczywistości? Co czujesz, wiedząc, że Bóg jest tak blisko ciebie, iż zna nawet twoje myśli? Dlaczego w tym kontekście obietnica zawarta w ofierze Jezusa na krzyżu nabiera szczególnego znaczenia?`
`2. Omówcie podczas pierwszej części nabożeństwa różnice między klasycznymi i apokaliptycznymi proroctwami. Jakie przykłady jednych i drugich, poza wymienionymi w lekcji, możecie podać?` | mit |
marufbd/marufbd.github.io | chromecast/CastVideos-chrome/README.md | 1314 | # CastVideos-chrome
===============================
This Google Cast demo app shows how to cast videos from a Chrome browser using Cast Chrome Sender SDK. It serves to demonstrate how to write a HTML5/Javascript Cast sender app that is fully compliant with the Design Checklist.
## Setup Instructions
# Pre-requisites
1. Get a Chromecast device
2. Install appropriate Chrome browser
3. Install appropriate Chrome Cast extension
See the developer guide and release notes at https://developers.google.com/cast/ for more details.
# Steps:
1. Put all files on your own server
2. Use the default media receiver app: no change or change YOUR_APP_ID to your own in CastVideos.js
4. Open a browser and point to your page at http://[YOUR_SERVER_LOCATION]/CastVideos-chrome/
##Documentation
* Cast APIs: http://developers.google.com/cast/docs/chrome_sender
## References and How to report bugs
* Cast APIs: http://developers.google.com/cast/docs/reference/chrome
* Design Checklist (http://developers.google.com/cast/docs/design_checklist)
* If you find any issues, please open a bug here on GitHub
How to make contributions?
Please read and follow the steps in the CONTRIBUTING.md
License
See LICENSE.md
## Google+
Google Cast Developers Community on Google+ [http://goo.gl/TPLDxj](http://goo.gl/TPLDxj)
| mit |
dashpay/dash | test/lint/lint-format-strings.py | 10365 | #!/usr/bin/env python3
#
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Lint format strings: This program checks that the number of arguments passed
# to a variadic format string function matches the number of format specifiers
# in the format string.
import argparse
import re
import sys
FALSE_POSITIVES = [
("src/batchedlogger.h", "strprintf(fmt, args...)"),
("src/dbwrapper.cpp", "vsnprintf(p, limit - p, format, backup_ap)"),
("src/index/base.cpp", "FatalError(const char* fmt, const Args&... args)"),
("src/netbase.cpp", "LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args)"),
("src/qt/networkstyle.cpp", "strprintf(appName, gArgs.GetDevNetName())"),
("src/qt/networkstyle.cpp", "strprintf(titleAddText, gArgs.GetDevNetName())"),
("src/rpc/rpcevo.cpp", "strprintf(it->second, nParamNum)"),
("src/stacktraces.cpp", "strprintf(fmtStr, i, si.pc, lstr, fstr)"),
("src/statsd_client.cpp", "snprintf(d->errmsg, sizeof(d->errmsg), \"could not create socket, err=%m\")"),
("src/statsd_client.cpp", "snprintf(d->errmsg, sizeof(d->errmsg), \"sendto server fail, host=%s:%d, err=%m\", d->host.c_str(), d->port)"),
("src/util.cpp", "strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION))"),
("src/util.cpp", "strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION)"),
("src/wallet/wallet.h", "WalletLogPrintf(std::string fmt, Params... parameters)"),
("src/wallet/wallet.h", "LogPrintf((\"%s \" + fmt).c_str(), GetDisplayName(), parameters...)"),
]
def parse_function_calls(function_name, source_code):
"""Return an array with all calls to function function_name in string source_code.
Preprocessor directives and C++ style comments ("//") in source_code are removed.
>>> len(parse_function_calls("foo", "foo();bar();foo();bar();"))
2
>>> parse_function_calls("foo", "foo(1);bar(1);foo(2);bar(2);")[0].startswith("foo(1);")
True
>>> parse_function_calls("foo", "foo(1);bar(1);foo(2);bar(2);")[1].startswith("foo(2);")
True
>>> len(parse_function_calls("foo", "foo();bar();// foo();bar();"))
1
>>> len(parse_function_calls("foo", "#define FOO foo();"))
0
"""
assert(type(function_name) is str and type(source_code) is str and function_name)
lines = [re.sub("// .*", " ", line).strip()
for line in source_code.split("\n")
if not line.strip().startswith("#")]
return re.findall(r"[^a-zA-Z_](?=({}\(.*).*)".format(function_name), " " + " ".join(lines))
def normalize(s):
"""Return a normalized version of string s with newlines, tabs and C style comments ("/* ... */")
replaced with spaces. Multiple spaces are replaced with a single space.
>>> normalize(" /* nothing */ foo\tfoo /* bar */ foo ")
'foo foo foo'
"""
assert(type(s) is str)
s = s.replace("\n", " ")
s = s.replace("\t", " ")
s = re.sub("/\*.*?\*/", " ", s)
s = re.sub(" {2,}", " ", s)
return s.strip()
ESCAPE_MAP = {
r"\n": "[escaped-newline]",
r"\t": "[escaped-tab]",
r'\"': "[escaped-quote]",
}
def escape(s):
"""Return the escaped version of string s with "\\\"", "\\n" and "\\t" escaped as
"[escaped-backslash]", "[escaped-newline]" and "[escaped-tab]".
>>> unescape(escape("foo")) == "foo"
True
>>> escape(r'foo \\t foo \\n foo \\\\ foo \\ foo \\"bar\\"')
'foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]'
"""
assert(type(s) is str)
for raw_value, escaped_value in ESCAPE_MAP.items():
s = s.replace(raw_value, escaped_value)
return s
def unescape(s):
"""Return the unescaped version of escaped string s.
Reverses the replacements made in function escape(s).
>>> unescape(escape("bar"))
'bar'
>>> unescape("foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]")
'foo \\\\t foo \\\\n foo \\\\\\\\ foo \\\\ foo \\\\"bar\\\\"'
"""
assert(type(s) is str)
for raw_value, escaped_value in ESCAPE_MAP.items():
s = s.replace(escaped_value, raw_value)
return s
def parse_function_call_and_arguments(function_name, function_call):
"""Split string function_call into an array of strings consisting of:
* the string function_call followed by "("
* the function call argument #1
* ...
* the function call argument #n
* a trailing ");"
The strings returned are in escaped form. See escape(...).
>>> parse_function_call_and_arguments("foo", 'foo("%s", "foo");')
['foo(', '"%s",', ' "foo"', ')']
>>> parse_function_call_and_arguments("foo", 'foo("%s", "foo");')
['foo(', '"%s",', ' "foo"', ')']
>>> parse_function_call_and_arguments("foo", 'foo("%s %s", "foo", "bar");')
['foo(', '"%s %s",', ' "foo",', ' "bar"', ')']
>>> parse_function_call_and_arguments("fooprintf", 'fooprintf("%050d", i);')
['fooprintf(', '"%050d",', ' i', ')']
>>> parse_function_call_and_arguments("foo", 'foo(bar(foobar(barfoo("foo"))), foobar); barfoo')
['foo(', 'bar(foobar(barfoo("foo"))),', ' foobar', ')']
>>> parse_function_call_and_arguments("foo", "foo()")
['foo(', '', ')']
>>> parse_function_call_and_arguments("foo", "foo(123)")
['foo(', '123', ')']
>>> parse_function_call_and_arguments("foo", 'foo("foo")')
['foo(', '"foo"', ')']
"""
assert(type(function_name) is str and type(function_call) is str and function_name)
remaining = normalize(escape(function_call))
expected_function_call = "{}(".format(function_name)
assert(remaining.startswith(expected_function_call))
parts = [expected_function_call]
remaining = remaining[len(expected_function_call):]
open_parentheses = 1
in_string = False
parts.append("")
for char in remaining:
parts.append(parts.pop() + char)
if char == "\"":
in_string = not in_string
continue
if in_string:
continue
if char == "(":
open_parentheses += 1
continue
if char == ")":
open_parentheses -= 1
if open_parentheses > 1:
continue
if open_parentheses == 0:
parts.append(parts.pop()[:-1])
parts.append(char)
break
if char == ",":
parts.append("")
return parts
def parse_string_content(argument):
"""Return the text within quotes in string argument.
>>> parse_string_content('1 "foo %d bar" 2')
'foo %d bar'
>>> parse_string_content('1 foobar 2')
''
>>> parse_string_content('1 "bar" 2')
'bar'
>>> parse_string_content('1 "foo" 2 "bar" 3')
'foobar'
>>> parse_string_content('1 "foo" 2 " " "bar" 3')
'foo bar'
>>> parse_string_content('""')
''
>>> parse_string_content('')
''
>>> parse_string_content('1 2 3')
''
"""
assert(type(argument) is str)
string_content = ""
in_string = False
for char in normalize(escape(argument)):
if char == "\"":
in_string = not in_string
elif in_string:
string_content += char
return string_content
def count_format_specifiers(format_string):
"""Return the number of format specifiers in string format_string.
>>> count_format_specifiers("foo bar foo")
0
>>> count_format_specifiers("foo %d bar foo")
1
>>> count_format_specifiers("foo %d bar %i foo")
2
>>> count_format_specifiers("foo %d bar %i foo %% foo")
2
>>> count_format_specifiers("foo %d bar %i foo %% foo %d foo")
3
>>> count_format_specifiers("foo %d bar %i foo %% foo %*d foo")
4
"""
assert(type(format_string) is str)
n = 0
in_specifier = False
for i, char in enumerate(format_string):
if format_string[i - 1:i + 1] == "%%" or format_string[i:i + 2] == "%%":
pass
elif char == "%":
in_specifier = True
n += 1
elif char in "aAcdeEfFgGinopsuxX":
in_specifier = False
elif in_specifier and char == "*":
n += 1
return n
def main():
parser = argparse.ArgumentParser(description="This program checks that the number of arguments passed "
"to a variadic format string function matches the number of format "
"specifiers in the format string.")
parser.add_argument("--skip-arguments", type=int, help="number of arguments before the format string "
"argument (e.g. 1 in the case of fprintf)", default=0)
parser.add_argument("function_name", help="function name (e.g. fprintf)", default=None)
parser.add_argument("file", nargs="*", help="C++ source code file (e.g. foo.cpp)")
args = parser.parse_args()
exit_code = 0
for filename in args.file:
with open(filename, "r", encoding="utf-8") as f:
for function_call_str in parse_function_calls(args.function_name, f.read()):
parts = parse_function_call_and_arguments(args.function_name, function_call_str)
relevant_function_call_str = unescape("".join(parts))[:512]
if (f.name, relevant_function_call_str) in FALSE_POSITIVES:
continue
if len(parts) < 3 + args.skip_arguments:
exit_code = 1
print("{}: Could not parse function call string \"{}(...)\": {}".format(f.name, args.function_name, relevant_function_call_str))
continue
argument_count = len(parts) - 3 - args.skip_arguments
format_str = parse_string_content(parts[1 + args.skip_arguments])
format_specifier_count = count_format_specifiers(format_str)
if format_specifier_count != argument_count:
exit_code = 1
print("{}: Expected {} argument(s) after format string but found {} argument(s): {}".format(f.name, format_specifier_count, argument_count, relevant_function_call_str))
continue
sys.exit(exit_code)
if __name__ == "__main__":
main()
| mit |
AcklenAvenue/Starscream | src/Starscream.Web/Api/Responses/SuccessfulLoginResponse.cs | 574 | using System;
namespace Starscream.Web.Api.Responses
{
public class SuccessfulLoginResponse<T>
{
public SuccessfulLoginResponse()
{
}
public SuccessfulLoginResponse(T token, string name, DateTime expires, string[] claims)
{
Token = token;
Name = name;
Expires = expires;
Claims = claims;
}
public T Token { get; set; }
public string Name { get; set; }
public DateTime Expires { get; set; }
public string[] Claims { get; set; }
}
} | mit |
steliann/objectj | src/ij/plugin/GroupedZProjector.java | 2033 | package ij.plugin;
import ij.*;
import ij.gui.GenericDialog;
import ij.process.*;
import ij.measure.Calibration;
/** This plugin implements the Image/Stacks/Tools/Grouped Z Project command. */
public class GroupedZProjector implements PlugIn {
private static int method = ZProjector.AVG_METHOD;
private int groupSize;
public void run(String arg) {
ImagePlus imp = IJ.getImage();
int size = imp.getStackSize();
if (size==1) {
IJ.error("Z Project", "This command requires a stack");
return;
}
if (imp.isHyperStack()) {
new ZProjector().run("");
return;
}
if (!showDialog(imp))
return;
ImagePlus imp2 = groupZProject(imp, method, groupSize);
imp2.setCalibration(imp.getCalibration());
Calibration cal = imp2.getCalibration();
cal.pixelDepth *= groupSize;
if (imp!=null)
imp2.show();
}
public ImagePlus groupZProject(ImagePlus imp, int method, int groupSize) {
if (method<0 || method>=ZProjector.METHODS.length)
return null;
imp.setDimensions(1, groupSize, imp.getStackSize()/groupSize);
ZProjector zp = new ZProjector(imp);
zp.setMethod(method);
zp.setStartSlice(1);
zp.setStopSlice(groupSize);
zp.doHyperStackProjection(true);
return zp.getProjection();
}
boolean showDialog(ImagePlus imp) {
int size = imp.getStackSize();
GenericDialog gd = new GenericDialog("Z Project");
gd.addChoice("Projection method:", ZProjector.METHODS, ZProjector.METHODS[method]);
gd.addNumericField("Group size:", size, 0);
String factors = "Valid factors: ";
int i = 1, count = 0;
while (i <= size && count<10) {
if (size % i == 0) {
count++; factors += " "+ i +",";
}
i++;
}
gd.setInsets(10,0,0);
gd.addMessage(factors+"...");
gd.showDialog();
if (gd.wasCanceled())
return false;
method = gd.getNextChoiceIndex();
groupSize = (int)gd.getNextNumber();
if (groupSize<1 || groupSize>size || (size%groupSize)!=0) {
IJ.error("ZProject", "Group size must divide evenly into the stack size.");
return false;
}
return true;
}
} | mit |
zeit/next.js | examples/with-temporal/pages/about.tsx | 368 | import type { NextPage } from 'next'
import Link from 'next/link'
import Layout from '../components/Layout'
const AboutPage: NextPage = () => (
<Layout title="About | Next.js + Temporal Example">
<h1>About</h1>
<p>This is the about page</p>
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
export default AboutPage
| mit |
kirbrown/od-ot | app/controllers/todo_lists_controller.rb | 1619 | class TodoListsController < ApplicationController
before_action :require_user
before_action :set_todo_list, only: %i[edit update destroy email]
before_action :set_back_link, except: %i[index show]
def index
@todo_lists = current_user.todo_lists
end
def show; end
def new
@todo_list = current_user.todo_lists.new
end
def edit; end
def create
@todo_list = current_user.todo_lists.new(todo_list_params)
if @todo_list.save
redirect_to todo_list_todo_items_path(@todo_list), success: 'Todo list was successfully created.'
else
render :new, error: 'Todo list could not be created.'
end
end
def update
if @todo_list.update(todo_list_params)
redirect_to todo_list_todo_items_path(@todo_list), success: 'Todo list was successfully updated.'
else
render :edit, error: 'Todo list could not be updated.'
end
end
def destroy
@todo_list.destroy
redirect_to todo_lists_url, success: 'Todo list was successfully deleted.'
end
def email
destination = params[:destination]
notifier = Notifier.todo_list(@todo_list, destination)
if destination =~ /@/ && notifier.deliver_now
redirect_to todo_list_todo_items_path(@todo_list), success: 'Todo list send.'
else
redirect_to todo_list_todo_items_path(@todo_list), error: 'Todo list could not be sent.'
end
end
private
def set_back_link
go_back_link_to todo_lists_path
end
def set_todo_list
@todo_list = current_user.todo_lists.find(params[:id])
end
def todo_list_params
params.require(:todo_list).permit(:title)
end
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.