module Test::Unit
# Test::Unit
- Ruby Unit
Testing Framework
## Introduction
Unit
testing is making waves all over the place, largely due to the fact that it is a core practice of XP. While XP is great, unit testing has been around for a long time and has always been a good idea. One of the keys to good unit testing, though, is not just writing tests, but having tests. What's the difference? Well, if you just write a test and throw it away, you have no guarantee that something won't change later which breaks your code. If, on the other hand, you have tests (obviously you have to write them first), and run them as often as possible, you slowly build up a wall of things that cannot break without you immediately knowing about it. This is when unit testing hits its peak usefulness.
Enter Test::Unit
, a framework for unit testing in Ruby, helping you to design, debug and evaluate your code by making it easy to write and have tests for it.
## Notes
Test::Unit
has grown out of and superceded Lapidary.
## Feedback
I like (and do my best to practice) XP, so I value early releases, user feedback, and clean, simple, expressive code. There is always room for improvement in everything I do, and Test::Unit
is no exception. Please, let me know what you think of Test::Unit
as it stands, and what you'd like to see expanded/changed/improved/etc. If you find a bug, let me know ASAP; one good way to let me know what the bug is is to submit a new test that catches it :-) Also, I'd love to hear about any successes you have with Test::Unit
, and any documentation you might add will be greatly appreciated. My contact info is below.
## Contact Information
A lot of discussion happens about Ruby in general on the ruby-talk mailing list (www.ruby-lang.org/en/ml.html), and you can ask any questions you might have there. I monitor the list, as do many other helpful Rubyists, and you're sure to get a quick answer. Of course, you're also welcome to email me (Nathaniel Talbott) directly at<EMAIL_ADDRESS>and I'll do my best to help you out.
## Credits
I'd like to thank…
Matz, for a great language!
Masaki Suketa, for his work on RubyUnit, which filled a vital need in the Ruby world for a very long time. I'm also grateful for his help in polishing Test::Unit
and getting the RubyUnit compatibility layer right. His graciousness in allowing Test::Unit
to supercede RubyUnit continues to be a challenge to me to be more willing to defer my own rights.
Ken McKinlay, for his interest and work on unit testing, and for his willingness to dialog about it. He was also a great help in pointing out some of the holes in the RubyUnit compatibility layer.
Dave Thomas, for the original idea that led to the extremely simple “require 'test/unit'”, plus his code to improve it even more by allowing the selection of tests from the command-line. Also, without RDoc, the documentation for Test::Unit
would stink a lot more than it does now.
Everyone who's helped out with bug reports, feature ideas, encouragement to continue, etc. It's a real privilege to be a part of the Ruby community.
The guys at RoleModel Software, for putting up with me repeating, “But this would be so much easier in Ruby!” whenever we're coding in Java.
My Creator, for giving me life, and giving it more abundantly.
## License
Test::Unit
is copyright © 2000-2003 Nathaniel Talbott. It is free software, and is distributed under the Ruby license. See the COPYING file.
Exception: lib/test/unit/diff.rb is copyright © 2008-2010 Kouhei Sutou and 2001-2008 Python Software Foundation. It is free software, and is distributed under the Ruby license and/or the PSF license. See the COPYING file and PSFL file.
## Warranty
This software is provided “as is” and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose.
## Author
Nathaniel Talbott. Copyright © 2000-2003, Nathaniel Talbott
# Usage
The general idea behind unit testing is that you write a test method that makes certain assertions about your code, working against a test fixture. A bunch of these test methods are bundled up into a test suite and can be run any time the developer wants. The results of a run are gathered in a test result and displayed to the user through some UI
. So, lets break this down and see how Test::Unit
provides each of these necessary pieces.
## Assertions
These are the heart of the framework. Think of an assertion as a statement of expected outcome, i.e. “I assert that x should be equal to y”. If, when the assertion is executed, it turns out to be correct, nothing happens, and life is good. If, on the other hand, your assertion turns out to be false, an error is propagated with pertinent information so that you can go back and make your assertion succeed, and, once again, life is good. For an explanation of the current assertions, see Test::Unit::Assertions
.
Obviously, these assertions have to be called within a context that knows about them and can do something meaningful with their pass/fail value. Also, it's handy to collect a bunch of related tests, each test represented by a method, into a common test class that knows how to run them. The tests will be in a separate class from the code they're testing for a couple of reasons. First of all, it allows your code to stay uncluttered with test code, making it easier to maintain. Second, it allows the tests to be stripped out for deployment, since they're really there for you, the developer, and your users don't need them. Third, and most importantly, it allows you to set up a common test fixture for your tests to run against.
What's a test fixture? Well, tests do not live in a vacuum; rather, they're run against the code they are testing. Often, a collection of tests will run against a common set of data, also called a fixture. If they're all bundled into the same test class, they can all share the setting up and tearing down of that data, eliminating unnecessary duplication and making it much easier to add related tests.
Test::Unit::TestCase
wraps up a collection of test methods together and allows you to easily set up and tear down the same test fixture for each test. This is done by overriding setup and/or teardown, which will be called before and after each test method that is run. The TestCase
also knows how to collect the results of your assertions into a Test::Unit::TestResult
, which can then be reported back to you… but I'm getting ahead of myself. To write a test, follow these steps:
-
Make sure
Test::Unit
is in your library path. -
require 'test/unit' in your test script.
-
Create a class that subclasses
Test::Unit::TestCase
. -
Add a method that begins with “test” to your class.
-
Make assertions in your test method.
-
Optionally define setup and/or teardown to set up and/or tear down your common test fixture.
-
You can now run your test as you would any other Ruby script… try it and see!
A really simple test might look like this (#setup and teardown are commented out to indicate that they are completely optional):
require 'test/unit' class MyTest < Test::Unit::TestCase # def setup # end # def teardown # end def test_fail assert(false, 'Assertion was false.') end end
## Test
Runners
So, now you have this great test class, but you still need a way to run it and view any failures that occur during the run. There are some test runner; console test runner, GTK+ test runner and so on. The console test runner is automatically invoked for you if you require 'test/unit' and simply run the file. To use another runner simply set default test runner ID to Test::Unit::AutoRunner:
require 'test/unit' Test::Unit::AutoRunner.default_runner = "gtk2"
## Test
Suite
As more and more unit tests accumulate for a given project, it becomes a real drag running them one at a time, and it also introduces the potential to overlook a failing test because you forget to run it. Suddenly it becomes very handy that the TestRunners can take any object that returns a Test::Unit::TestSuite
in response to a suite method. The TestSuite
can, in turn, contain other TestSuites or individual tests (typically created by a TestCase
). In other words, you can easily wrap up a group of TestCases and TestSuites.
Test::Unit
does a little bit more for you, by wrapping these up automatically when you require 'test/unit'. What does this mean? It means you could write the above test case like this instead:
require 'test/unit' require 'test_myfirsttests' require 'test_moretestsbyme' require 'test_anothersetoftests'
Test::Unit
is smart enough to find all the test cases existing in the ObjectSpace and wrap them up into a suite for you. It then runs the dynamic suite using the console TestRunner.
## Configuration file
Test::Unit
reads 'test-unit.yml' in the current working directory as Test::Unit's configuration file. It can contain the following configurations:
-
color scheme definitions
-
test runner to be used
-
test runner options
-
test collector to be used
Except color scheme definitions, all of them are specified by command line option.
Here are sample color scheme definitions:
color_schemes: inverted: success: name: red bold: true failure: name: green bold: true other_scheme: ...
Here are the syntax of color scheme definitions:
color_schemes: SCHEME_NAME: EVENT_NAME: name: COLOR_NAME intensity: BOOLEAN bold: BOOLEAN italic: BOOLEAN underline: BOOLEAN ... ...
SCHEME_NAME : the name of the color scheme
EVENT_NAME : one of [success, failure, pending, omission, notification, error]
COLOR_NAME : one of [black, red, green, yellow, blue, magenta, cyan, white]
BOOLEAN : true or false
You can use the above 'inverted' color scheme with the following configuration:
runner: console console_options: color_scheme: inverted color_schemes: inverted: success: name: red bold: true failure: name: green bold: true
## Questions?
I'd really like to get feedback from all levels of Ruby practitioners about typos, grammatical errors, unclear statements, missing points, etc., in this document (or any other).
Constants
- VERSION
Public Class Methods
Regsiter a hook that is run after running tests. To register multiple hooks, call this method multiple times.
Here is an example test case:
Test::Unit.at_exit do # ... end class TestMyClass1 < Test::Unit::TestCase class << self def shutdown # ... end end def teardown # ... end def test_my_class1 # ... end def test_my_class2 # ... end end class TestMyClass2 < Test::Unit::TestCase class << self def shutdown # ... end end def teardown # ... end def test_my_class1 # ... end def test_my_class2 # ... end end
Here is a call order:
-
TestMyClass1#test_my_class1
-
TestMyClass1#teardown
-
TestMyClass1#test_my_class2
-
TestMyClass1#teardown
-
TestMyClass1.shutdown
-
TestMyClass2#test_my_class1
-
TestMyClass2#teardown
-
TestMyClass2#test_my_class2
-
TestMyClass2#teardown
-
TestMyClass2.shutdown
@example
Test::Unit.at_exit do puts "Exit!"  To register multiple hooks, call this method multiple times.
Here is an example test case:
Test::Unit.at_start do # ... end class TestMyClass1 < Test::Unit::TestCase class << self def startup # ... end end def setup # ... end def test_my_class1 # ... end def test_my_class2 # ... end end class TestMyClass2 < Test::Unit::TestCase class << self def startup # ... end end def setup # ... end def test_my_class1 # ... end def test_my_class2 # ... end end
Here is a call order:
-
TestMyClass1.startup
-
TestMyClass1#setup
-
TestMyClass1#test_my_class1
-
TestMyClass1#setup
-
TestMyClass1#test_my_class2
-
TestMyClass2#setup
-
TestMyClass2#test_my_class1
-
TestMyClass2#setup
-
TestMyClass2#test_my_class2
@example
Test::Unit.at_start do puts "Start!" end
@yield A block that is run before running tests. @yieldreturn [void] @return [void]
@since 2.5.2
# File lib/test/unit.rb, line 407 def at_start(&hook) @@at_start_hooks << hook end
Set true when Test::Unit
has run. If set to true Test::Unit
will not automatically run at exit.
@deprecated Use Test::Unit::AutoRunner.need_auto_run=
instead.
# File lib/test/unit.rb, line 321 def run=(have_run) AutoRunner.need_auto_run = (not have_run) end
Already tests have run?
@deprecated Use Test::Unit::AutoRunner.need_auto_run?
instead.
# File lib/test/unit.rb, line 328 def run? not AutoRunner.need_auto_run? end
@api private
# File lib/test/unit.rb, line 499 def run_at_exit_hooks @@at_exit_hooks.each do |hook| hook.call end end
@api private
# File lib/test/unit.rb, line 412 def run_at_start_hooks @@at_start_hooks.each do |hook| hook.call end end


Introductions
Build the future of DeFi Gaming
Installation
bepro-js is available as npm package.
// with npm
$ npm i bepro-js
Before try to install, make sure your working directory has Python 2
and the recommended NVM
version setted on. To do, so:
- Setting of Python 2:
// Install it via bash terminal globally
$ sudo apt install python2
// Check the installed version.
// Must shown Python 2.7.18rc1 on terminal to the install be OK
$ python2 --version
// Verify Python 2.7 path
$ ls /usr/bin/python*
// Set Python 2 as alternative 1
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
// Confirm Python 2 as alternative priority 1
$ sudo update-alternatives --config python
// Confirm the procedure.
// Must shown Python 2.7.18rc1 on terminal to the install be OK
$ python --version
// On the working directory, run the cmd below to set Python locally
$ npm config set python python
- Setting of Node:
// Install NVM recommended version for bepro-js
$ nvm install 8.12.0
// Set it on the working directory
$ nvm alias default v8.12.0
// Use the settled as default
$ nvm use default
Now, your work directory is able to install and run bepro-js.
Usage
https://bepronetwork.github.io/bepro-js/
/* Note : WEB3_LINK should be get from Infura/Quicknode or any other Web3 Provider - ETH, BSC, Moonbeam and others are supported */
import moment from 'moment';
import { Application } from 'bepro-js';
/* 1 - Instantiate the App with the Infura/Web3 Connection */
let app = new Application({opt : {web3Connection : 'WEB3_LINK'}});
/* 2 - Connect the App to the Metamask Web3 Injected wallet*/
await app.login();
/* or instantiate with the provided web3Connection */
await app.start()
/* 3 - Generate a Object (Staking, ERC20 etc..) */
let staking = app.getStakingContract({contractAddress : /* Contract Address (optional) */});
/* 4 - Assert all object data */
await staking.__assert();
/* or deploy the contract*/
await staking.deploy();
/* 5 - Access other Methods */
await staking.availableTokens();
Contribution
Contributions are welcomed but we ask to red existing code guidelines, specially the code format. Please review Contributor guidelines
License
Notes
The usage of ETH in all methods or params means using the native currency of that blockchain, example BSC in Binance Chain would still be nominated as ETH


For everyone person who stumbles across your message and "hearts" it, you will see more messages with more hearts. Giving out higher quality messages is rewarded. Also, we heart every message we allow into our database!
This app is about unconditional love/good-will. There is system in place to reward good effort but you wont see any sort of rank or how many hearts your messages receive.
We are working to make this as safe a space as possible.  We have message moderation, a filtering system and a banning procedure. However, it is still possible that you will receive a message that makes you feel uncomfortable.
We do not recommend this app to people who are having suicidal thoughts or are severely / moderately depressed. This app is not a replacement for professional support.


A detailed overview of ECMAScript 6 features.
es6features
This document is taken from Luke Hoban's excellent es6features repo. Go give it a star on GitHub!
REPL
Be sure to try these features out in the online REPL.
ECMAScript 6 is the upcoming version of the ECMAScript standard. This standard is targeting ratification in June 2015. ES2015 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now.
See the draft ES2015 standard for full specification of the ECMAScript 6 language.
Arrows are a function shorthand using the =>
syntax. They are syntactically
similar to the related feature in C#, Java 8 and CoffeeScript. They support
both expression and statement bodies. Unlike functions, arrows share the same
lexical this
as their surrounding code.
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
}
ES2015 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
class SkinnedMesh extends THREE.Mesh {
constructor(geometry, materials) {
super(geometry, materials);
this.idMatrix = SkinnedMesh.defaultMatrix();
this.bones = [];
this.boneMatrices = [];
//...
}
update(camera) {
//...
super.update();
}
static defaultMatrix() {
return new THREE.Matrix4();
}
}
Object literals are extended to support setting the prototype at construction,
shorthand for foo: foo
assignments, defining methods and making super calls.
Together, these also bring object literals and class declarations closer
together, and let object-based design benefit from some of the same
conveniences.
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ "prop_" + (() => 42)() ]: 42
};
__proto__
support comes from the JavaScript engine running your program. Although most support the now standard property, some do not.
Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.
// Basic literal string creation
`In ES5 "\n" is a line-feed.`
// Multiline strings
`In ES5 this is
not legal.`
// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// Construct an HTTP request prefix is used to interpret the replacements and construction
GET`http://foo.org/bar?a=${a}&b=${b}
Content-Type: application/json
X-Credentials: ${credentials}
{ "foo": ${foo},
"bar": ${bar}}`(myOnReadyStateChangeHandler);
Destructuring allows binding using pattern matching, with support for matching
arrays and objects. Destructuring is fail-soft, similar to standard object
lookup foo["bar"]
, producing undefined
values when not found.
// list matching
var [a, , b] = [1,2,3];
// object matching
var { op: a, lhs: { op: b }, rhs: c }
= getASTNode()
// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode()
// Can be used in parameter position
function g({name: x}) {
console.log(x);
}
g({name: 5})
// Fail-soft destructuring
var [a] = [];
a === undefined;
// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;
Callee-evaluated default parameter values. Turn an array into consecutive
arguments in a function call. Bind trailing parameters to an array. Rest
replaces the need for arguments
and addresses common cases more directly.
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
Block-scoped binding constructs. let
is the new var
. const
is
single-assignment. Static restrictions prevent use before assignment.
function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// error, already declared in block
let x = "inner";
}
}
Iterator objects enable custom iteration like CLR IEnumerable or Java
Iterable. Generalize for..in
to custom iterator-based iteration with
for..of
. Don’t require realizing an array, enabling lazy design patterns like
LINQ.
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
Iteration is based on these duck-typed interfaces (using TypeScript type syntax for exposition only):
interface IteratorResult {
done: boolean;
value: any;
}
interface Iterator {
next(): IteratorResult;
}
interface Iterable {
[Symbol.iterator](): Iterator
}
Support via polyfill
In order to use Iterators you must include the Babel polyfill.
Generators simplify iterator-authoring using function*
and yield
. A function
declared as function* returns a Generator instance. Generators are subtypes of
iterators which include additional next
and throw
. These enable values to
flow back into the generator, so yield
is an expression form which returns a
value (or throws).
Note: Can also be used to enable ‘await’-like async programming, see also ES7 await
proposal.
var fibonacci = {
[Symbol.iterator]: function*() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
The generator interface is (using TypeScript type syntax for exposition only):
interface Generator extends Iterator {
next(value?: any): IteratorResult;
throw(exception: any);
}
Support via polyfill
In order to use Generators you must include the Babel polyfill.
Array and generator comprehensions provide simple declarative list processing similar as used in many functional programming patterns.
// Array comprehensions
var results = [
for(c of customers)
if (c.city == "Seattle")
{ name: c.name, age: c.age }
]
// Generator comprehensions
var results = (
for(c of customers)
if (c.city == "Seattle")
{ name: c.name, age: c.age }
)
Disabled by default
These are only available if you enable experimental support. See experimental usage for more information.
Non-breaking additions to support full Unicode, including new unicode literal
form in strings and new RegExp u
mode to handle code points, as well as new
APIs to process strings at the 21bit code points level. These additions support
building global apps in JavaScript.
// same as ES5.1
"𠮷".length == 2
// new RegExp behaviour, opt-in ‘u’
"𠮷".match(/./u)[0].length == 2
// new form
"\u{20BB7}" == "𠮷" == "\uD842\uDFB7"
// new String ops
"𠮷".codePointAt(0) == 0x20BB7
// for-of iterates code points
for(var c of "𠮷") {
console.log(c);
}
Language-level support for modules for component definition. Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));
Some additional features include export default
and export *
:
// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
return Math.exp(x);
}
// app.js
import exp, {pi, e} from "lib/mathplusplus";
alert("2π = " + exp(pi, e));
Module Formatters
Babel can transpile ES2015 Modules to several different formats including Common.js, AMD, System, and UMD. You can even create your own. For more details see the modules docs.
Module loaders support:
The default module loader can be configured, and new loaders can be constructed to evaluated and load code in isolated or constrained contexts.
// Dynamic loading – ‘System’ is default loader
System.import("lib/math").then(function(m) {
alert("2π = " + m.sum(m.pi, m.pi));
});
// Create execution sandboxes – new Loaders
var loader = new Loader({
global: fixup(window) // replace ‘console.log’
});
loader.eval("console.log(\"hello world!\");");
// Directly manipulate module cache
System.get("jquery");
System.set("jquery", Module({$: $})); // WARNING: not yet finalized
Additional polyfill needed
Since Babel defaults to using common.js modules, it does not include the polyfill for the module loader API. Get it here.
Using Module Loader
In order to use this, you'll need to tell Babel to use the
system
module formatter. Also be sure to check out System.js
Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set
Support via polyfill
In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill.
Proxies enable creation of objects with the full range of behaviors available to host objects. Can be used for interception, object virtualization, logging/profiling, etc.
// Proxying a normal object
var target = {};
var handler = {
get: function (receiver, name) {
return `Hello, ${name}!`;
}
};
var p = new Proxy(target, handler);
p.world === "Hello, world!";
// Proxying a function object
var target = function () { return "I am the target"; };
var handler = {
apply: function (receiver, ...args) {
return "I am the proxy";
}
};
var p = new Proxy(target, handler);
p() === "I am the proxy";
There are traps available for all of the runtime-level meta-operations:
var handler =
{
get:...,
set:...,
has:...,
deleteProperty:...,
apply:...,
construct:...,
getOwnPropertyDescriptor:...,
defineProperty:...,
getPrototypeOf:...,
setPrototypeOf:...,
enumerate:...,
ownKeys:...,
preventExtensions:...,
isExtensible:...
}
Unsupported feature
Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support from various JavaScript engines.
Symbols enable access control for object state. Symbols allow properties to be
keyed by either string
(as in ES5) or symbol
. Symbols are a new primitive
type. Optional name
parameter used in debugging - but is not part of identity.
Symbols are unique (like gensym), but not private since they are exposed via
reflection features like Object.getOwnPropertySymbols
.
(function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {
... this[key] ...
}
};
})();
var c = new MyClass("hello")
c["key"] === undefined
Support via polyfill
In order to support Symbols you must include the Babel polyfill.
In ES2015, built-ins like Array
, Date
and DOM Element
s can be subclassed.
// User code of Array subclass
class MyArray extends Array {
constructor(...args) { super(...args); }
}
var arr = new MyArray();
arr[1] = 12;
arr.length == 2
Partial support
Built-in subclassability should be evaluated on a case-by-case basis as classes such as
HTMLElement
can be subclassed while many such asDate
,Array
andError
cannot be due to ES5 engine limitations.
Many new library additions, including core Math libraries, Array conversion helpers, and Object.assign for copying.
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll("*")) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1,2,3].findIndex(x => x == 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
Object.assign(Point, { origin: new Point(0,0) })
Limited support from polyfill
Most of these APIs are supported by the Babel polyfill. However, certain features are omitted for various reasons (e.g.
String.prototype.normalize
needs a lot of additional code to support). You can find more polyfills here.
Two new numeric literal forms are added for binary (b
) and octal (o
).
0b111110111 === 503 // true
0o767 === 503 // true
Only supports literal form
Babel is only able to transform
0o767
and notNumber("0o767")
.
Promises are a library for asynchronous programming. Promises are a first class representation of a value that may be made available in the future. Promises are used in many existing JavaScript libraries.
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})
Support via polyfill
In order to support Promises you must include the Babel polyfill.
Full reflection API exposing the runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. Especially useful for implementing proxies.
var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Reflect.ownKeys(O); // ['a', 'b', Symbol(c)]
function C(a, b){
this.c = a + b;
}
var instance = Reflect.construct(C, [20, 22]);
instance.c; // 42
Support via polyfill
In order to use the Reflect API you must include the Babel polyfill.
Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes recursive algorithms safe in the face of unbounded inputs.
function factorial(n, acc = 1) {
"use strict";
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES2015
factorial(100000)
Partial support
Only explicit self referencing tail recursion is supported due to the complexity and performance impact of supporting tail calls globally.


Examples to test the "relative" and "assets" variables, and to show how they work
Assets folder is in the same dir as dest files.
assets_two: { options: {assets: 'test/actual'}, files: {'test/actual/assets-same-folder.html': ['test/files/assets.hbs']} },


The Shawshank Redemption (1994) A movie review by Serdar Yegulalp Copyright 1997 by Serdar Yegulalp
CAPSULE: A rare one. A grand and wise movie about cosmic patience, hope found, and hope kept.
The beauty of THE SHAWSHANK REDEMPTION is in the slow and careful way it works towards its conclusion. Which is, I have to say, a deceptive one: the movie starts by making you believe it's going to find its subject in one man, but in reality is about another.
The two men in question are Andy Dufresne (Tim Robbins) and Red (Morgan Freeman), inmates in Shawshank Prison. Dufresne, as we learn in the opening credits, has been sentenced to two life sentences for murdering his wife and her lover. We are shown quite plainly that he didn't do it, but in prison everyon's innocent: his factual innocence means nothing there.
Dufresne is assaulted brutally over a period of years. The way the movie deploys this is heartbreaking: this is not one of those cheapjack movies where the hero sits up all night working to conceal a rock in his fist and then creams his tormentors with one blow each. He will only be able to survive by outlasting others, by outthinking them, and by putting himself out of their reach.
Red is a procurer: for the right price, he can get you anything short of escape. But in Shawshank, any escape is worth it -- even a poster of Rita Hayworth -- and so Red is constantly in business. Dufresne and Red slowly grow to like each other, Red warming to Dufresne's quiet, persistent manner.
Slowly, over the course of time, Dufresne begins to make changes in the way the prison operates. He has all the time in the world; why not make the most of it? And while this is happening, another, more subtle series of changes is taking place inside Red -- one which we see dramatized in each of his consecutive parole board meetings, ten years or so apart.
The movie is patient. There is no hurried scurrying from one forced plot point to another, but instead the wonderful feeling of a story developing on its own, flowing naturally from its material and its characters. And what characters: as Dufresne, Tim Robbins is almost invisible, but all the better for it. When he finally smiles and raises his face to the rain near the end of the movie (in a shot which was better off being kept out of the trailers), he's earned it. Freeman, as Red, does gradual things with his role that are worth watching the movie a second time for. Maybe a third, since he's a lot more important to the significance of the title than we think at first.
There are some deviations from the original Stephen King novella, and some people will no doubt find this irksome, although it's probably inevitable. But they don't damage the movie as a whole -- in fact, it would probably take nothing short of a missing reel of film to do that.
Four out of four rock hammers.
<EMAIL_ADDRESS>EFNet IRC: GinRei http://www.io.com/~syegul another worldly device... you can crush me as I speak/write on rocks what you feel/now feel this truth =smilin' in your face, all the time wanna take your place, the BACKSTABBERS=
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Demonstration of waveform-compare — an xcorrSound tool
Waveform-compare compares two audio files and outputs the similarity.
The tool can be used in quality assurance.
This tests xcorrsound functionality, but not performance which is affected by network bandwidth and
server load.
The tool outputs "success" or "failure", depending on similarity for the best match (default threshold is 0.98),
as well as offset and similarity (between 0 and 1) for best match, and in case of failure the block
where the failure occurred.
The samples are derived from "Test Drive by Zapac [Attribution Noncommercial (3.0)]" from ccMixter.org.
ccMixter is a community music site featuring remixes licensed under Creative Commons.
ccmixter.org/files/Zapac/26047


Here I am using only two colors: white and a light blue (with a tint of violet).
This was actually the first design I did. For me it was easier to do this one with only two colors, three colors was more complicated for me.
The approach I had was to divide elements with one or the other color. Text would preferably be white and background would be blue, but on buttons it will be reversed to highlight them and show that they are different.
Main content area is bordered with white line to show that it is separated from the navigation bar and the side bar.
...
asdfjkl;


Need to find a place to meet? Get in a virtual room with all the people you want to meet, send your location, and our algorithm will determine the best place to meet. If you would like to create a room, press the button below.


public interface Session
Sessions are created on demand via: Request.session()
.
Sessions have a lot of uses cases but most commons are: auth, store information about current user, etc.
A session attribute must be String
or a primitive. Session doesn't allow to store arbitrary objects. It is a simple mechanism to store basic data.
There is no timeout for sessions from server perspective. By default, a session will expire when the user close the browser (a.k.a session cookie).
A Session.Store
is responsible for saving session data. Sessions are kept in memory, by default using the Session.Mem
store, which is useful for development, but wont scale well on production environments. An redis, memcached, ehcache store will be a better option.
Sessions are persisted every time a request exit, if they are dirty. A session get dirty if an attribute is added or removed from it.
The session.saveInterval
property indicates how frequently a session will be persisted (in millis).
In short, a session is persisted when: 1) it is dirty; or 2) save interval has expired it.
Next session describe the most important options:
The session.cookie.maxAge
sets the maximum age in seconds. A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. Default maxAge is: -1
.
If the application.secret
property has been set, then the session cookie will be signed it with it.
The session.cookie.name
indicates the name of the cookie that hold the session ID, by defaults: jooby.sid
. Cookie's name can be explicitly set with Cookie.Definition.name(String)
on Session.Definition.cookie()
.
| Modifier and Type | Interface and Description |
|---|---|
static interface |
Session.Builder
Build or restore a session from a persistent storage.
|
static class |
Session.Definition
Hold session related configuration parameters.
|
static class |
Session.Destroyed
Throw when session access is required but the session has been destroyed.\ See destroy() .
|
static class |
Session.Mem
A keep in memory session store.
|
static interface |
Session.Store
Read, save and delete sessions from a persistent storage.
|
| Modifier and Type | Field and Description |
|---|---|
static String |
COOKIE_SESSION
Global/Shared id of cookie sessions.
|
| Modifier and Type | Method and Description |
|---|---|
long |
accessedAt()
The last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.
|
Map<String,String> |
attributes() |
long |
createdAt()
The time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT for server side sessions.
|
void |
destroy()
Invalidates this session then unset any objects bound to it.
|
long |
expiryAt()
The time when this session is going to expire, measured in milliseconds since midnight January 1, 1970 GMT.
|
Mutant |
get(String name)
Get a object from this session.
|
String |
id()
A session ID for server side sessions.
|
boolean |
isDestroyed()
True if the session was destroy() .
|
boolean |
isSet(String name)
Test if the var name exists inside the session local attributes.
|
Session |
renewId()
Assign a new ID to the existing session.
|
long |
savedAt()
Last time the session was save it as epoch millis or -1 for client side sessions.
|
default Session |
set(String name, boolean value)
Set a session local using a the given name.
|
default Session |
set(String name, byte value)
Set a session local using a the given name.
|
default Session |
set(String name, char value)
Set a session local using a the given name.
|
default Session |
set(String name, CharSequence value)
Set a session local using a the given name.
|
default Session |
set(String name, double value)
Set a session local using a the given name.
|
default Session |
set(String name, float value)
Set a session local using a the given name.
|
default Session |
set(String name, int value)
Set a session local using a the given name.
|
default Session |
set(String name, long value)
Set a session local using a the given name.
|
default Session |
set(String name, short value)
Set a session local using a the given name.
|
Session |
set(String name, String value)
Set a session local using a the given name.
|
Session |
unset()
Unset/remove all the session data.
|
Mutant |
unset(String name)
Remove a local value (if any) from session locals.
|
static final String COOKIE_SESSION
@Nonnull String id()
COOKIE_SESSION
for client side sessions. Session ID on client sessions doesn't make sense because resolution of session is done via cookie name. Another reason of not saving the session ID inside the cookie, is the cookie size (up to 4kb). If the session ID is persisted then users lost space to save business data.
long createdAt()
-1
for client side sessions.
-1
for client side sessions.
long savedAt()
-1
for client side sessions.
-1
for client side sessions.
long accessedAt()
-1
for client side sessions.
Actions that your application takes, such as getting or setting a value associated with the session, do not affect the access time.
-1
for client side sessions.
long expiryAt()
-1
for client side sessions.
-1
for client side sessions.
@Nonnull Mutant get(String name)
name
- Attribute's name.
boolean isSet(String name)
name
- A local var's name.
@Nonnull default Session set(String name, byte value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, char value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, boolean value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, short value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, int value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, long value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, float value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, double value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull default Session set(String name, CharSequence value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull Session set(String name, String value)
name
- Attribute's name.
value
- Attribute's value.
@Nonnull Mutant unset(String name)
name
- Attribute's name.
void destroy()
boolean isDestroyed()
destroy()
.
destroy()
.
Session renewId()
Copyright © 2019. All rights reserved.


Ex command ranges
Many ex commands accept a range of lines to operate upon. The range precede the command name and consists of zero, one or two line addresses separated with comma.
A line address can be written as:
- an absolute line number, ie 3
- $ denotes the last line
- . (a dot) referes to the current line
- a mark (eg 'x)
- % denotes all lines, same as 1,$
- a forward search pattern, delimited by slashes, eg /foo/
- a backward search pattern, delimited by question marks, eg ?foo?
Additionally, a line offset may be appended to a line address with + or -. For example, .+2 means two lines after the current line.


I live in a small hut in the mountains of Kumano Kodō on Kii Hantō and would not like to be contacted.


--- layout: post title: Horse study date: '2016-12-09T00:35:41+01:00' categories: - Horses - Sketches picture_url: https://film-Storyboards.tumblr.com/post/154237649571/horse-study ---


#include <tinyxml.h>
Inheritance diagram for TiXmlDocument::
Public Methods | |
| TiXmlDocument () | |
| Create an empty document, that has no name. | |
| TiXmlDocument (const char *documentName) | |
| Create a document with a name. The name of the document is also the filename of the xml. | |
| TiXmlDocument (const std::string &documentName) | |
| Constructor. | |
| bool | LoadFile () |
| Load a file using the current document value. More... | |
| bool | SaveFile () const |
| Save a file using the current document value. Returns true if successful. | |
| bool | LoadFile (const char *filename) |
| Load a file using the given filename. Returns true if successful. | |
| bool | SaveFile (const char *filename) const |
| Save a file using the given filename. Returns true if successful. | |
| bool | LoadFile (const std::string &filename) |
| bool | SaveFile (const std::string &filename) const |
| < STL std::string version. | |
| virtual const char * | Parse (const char *p, TiXmlParsingData *data=0) |
| Parse the given null terminated block of xml data. | |
| TiXmlElement * | RootElement () const |
| Get the root element -- the only top level element -- of the document. More... | |
| bool | Error () const |
| If an error occurs, Error will be set to true. More... | |
| const char * | ErrorDesc () const |
| Contains a textual (english) description of the error if one occurs. | |
| const int | ErrorId () const |
| Generally, you probably want the error string ( ErrorDesc() ). More... | |
| int | ErrorRow () |
| Returns the location (if known) of the error. More... | |
| int | ErrorCol () |
| The column where the error occured. See ErrorRow(). | |
| void | SetTabSize (int _tabsize) |
| By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. More... | |
| void | ClearError () |
| If you have handled the error, it can be reset with this call. More... | |
| void | Print () const |
| Dump the document to standard out. | |
| virtual void | Print (FILE *cfile, int depth=0) const |
| All TinyXml classes can print themselves to a filestream. More... |
A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name.
|
|
If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. |
|
|
If an error occurs, Error will be set to true. Also, |
|
|
Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. |
|
|
Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.)
|
|
|
|
|
|
Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. |
|
|
All TinyXml classes can print themselves to a filestream. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) Reimplemented from TiXmlBase. |
|
|
Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. |
|
|
By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Load( "myfile.xml" );
|


Pakistan to host first test match since 2009 Sri Lanka bus attack
Test cricket makes a return to Pakistan after more than 10 years as Sri Lankan cricket team agrees to tour in December.
Pakistan is set to play its first international test match on home soil in more than a decade when it hosts the Sri Lankan cricket team for a two-match series next month.
Pakistan has not hosted the longer format of the sport - played more than five days - since the 2009 attack on the Sri Lankan cricket team bus in Lahore that left six security personnel and two civilians dead and six players injured.
"After more than 10 years, test cricket will return to Pakistan in December when Sri Lanka will play their World Test Championship matches in Rawalpindi and Karachi," Pakistan Cricket Board (PCB) said in a statement on Thursday.
More:
-
India-Pakistan cricket dispute over army caps and politics in sport
-
Bangladesh's cricket star Shakib banned over corruption
-
Exclusive: Cricket match-fixers caught in the act in Sri Lanka
The first match in Rawalpindi will be played from December 11-15, while the southern city of Karachi will host the second match from December 19-23.
PCB said Sri Lanka agreed to go ahead with the test series after the successful staging of one-day and Twenty20 internationals in September and October.
"This is fabulous news for Pakistan and its reputation of being as safe and secure as any other country in the world," said Zakir Khan, PCB's director of international cricket, in a statement.
After a lapse of six years, international cricket returned to Pakistan in 2015 when Zimbabwe toured the country for one-day and Twenty20 matches.
That tour was completed despite a suicide blast near the venue, Gaddafi Stadium, in Lahore.
Pakistan has hosted a number of limited-overs internationals in recent years, with Sri Lanka playing three ODIs and three T20 matches in September and October, though 10 key players opted out of that trip citing security concerns.
Sri Lanka Cricket's Chief Executive Ashley de Silva said it was time for test cricket to return to Pakistan.
"We are pleased to confirm our return visit to Pakistan as, based on our earlier visit, we are comfortable and convinced conditions are suitable and conducive for Test cricket," he said.
"We also believe all cricket-playing countries should host international cricket at home and in this relation we are happy to play our part in complete resumption of international cricket in Pakistan."


--- permalink: /404.html title: "Oops, we are not camping here.You seem to have lost your way..." layout: single author_profile: false excerpt: "Oops, we are not camping here." ads: false share: false sitemap: false ---


- waftSensations(int, int)
- Method in class au.id.richardburgmann.TheWorld
-
- wait(int) - Method in class
au.id.richardburgmann.WWSimulator
-
- WALLS -
Static variable in class au.id.richardburgmann.TheWorld
-
Constant, Usage worldState[WALLLS][4][4]
Try not to walk into them, they hurt.
- WALLS_PLACEMENT
- Variable in class au.id.richardburgmann.TheWorld
-
Decides if the Walls will start in the fixed location or in
a random location on the grid.
- WALLS_X -
Variable in class au.id.richardburgmann.TheWorld
-
Initial starting location loaded from properties file.
- WALLS_Y -
Variable in class au.id.richardburgmann.TheWorld
-
Initial starting location loaded from properties file.
- wallsSprite
- Variable in class au.id.richardburgmann.WWSimulator
-
- weights
- Variable in class au.id.richardburgmann.brains.QTableBrain.BrainCell
-
- whereAmI(TheWorld)
- Method in interface au.id.richardburgmann.brains.Brain
-
- windowActivated(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowClosed(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowClosing(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowDeactivated(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowDeiconified(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowIconified(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowOpened(WindowEvent)
- Method in class au.id.richardburgmann.WWSimulator
-
- windowStateChanged(WindowEvent)
- Method in class au.id.richardburgmann.gui.GuiEventListener
-
- worldState - Variable in class
au.id.richardburgmann.TheWorld
-
worldState does what it says on the box, it holds the entire state of the world.
- worldStateValue
- Variable in class au.id.richardburgmann.TheWorld
-
- WUMPUS -
Static variable in class au.id.richardburgmann.TheWorld
-
Constant, usage is worldState[WUMPUS][4][4]
There can only be one Wumpus in the world at a time.
- WUMPUS_PLACEMENT
- Variable in class au.id.richardburgmann.TheWorld
-
Decides if the Wumpus will start in the fixed location 2,2 or in
a random location on the grid.
- WUMPUS_X -
Variable in class au.id.richardburgmann.TheWorld
-
Initial starting location loaded from properties file.
- WUMPUS_Y -
Variable in class au.id.richardburgmann.TheWorld
-
Initial starting location loaded from properties file.
- wumpusSprite - Variable in
class au.id.richardburgmann.WWSimulator
-
- WWSimulator - Class in au.id.richardburgmann
-
The Wumpus World Simulator enables you to explore the world of the Wumpus and Adventurer
with a GUI
representation of the world.
- WWSimulator() - Constructor
for class au.id.richardburgmann.WWSimulator
-
- wwSimulator
- Static variable in class au.id.richardburgmann.WWSimulator
-


Cinema Uprising by Steve Evans
American Beauty Dir: Sam Mendes. Starring Kevin Spacey, Annette Bening, Thora Birch, Mena Suvari, Wes Bentley, Peter Gallagher and Chris Cooper.
The pitch: A man hobbled by a mid-life crisis and a nightmarish family channels his depression into lust for a teen-age girl.
Yes, and there's so much more. A jet-black satire of suburbia, this cautionary fable with a grim, inevitable climax features a stunning performance from Spacey, as the 42-year-old advertising man who hates his job and shrewish wife (Bening). Seldom does a film spew such venom, or offer such a myopic and pessimistic worldview, only to shatter our expectations with a glimmer of hope at the end. In terms of metaphor, as social commentary and, yes, as art, American Beauty is the most challenging film of 1999, sure to prompt controversy and conversation. The constant, symbolic use of the color red is enough to fuel many a late-night discussion, long after the credits roll. Expect Oscar® nominations for both actors, first-time film director Mendes, for the incredible script by television writer Alan Ball (Cybill) and certainly for the picture itself. Let us be clear, so that no one goes into the theater unaware: American Beauty is a difficult, provocative experience, a film concerned with ideas that outwardly decent people don't discuss, though some no doubt ponder in their hearts.
Watching his daughter's best friend Angela (Suvari) perform her cheerleading routines, Spacey discovers a fire in his loins and a passion for life that has been missing for two decades. When he sees Suvari strut, her arms snaking over her lithe body, it's lust at first sight.  Don't dismiss this as just another Lolita tale, although it bears more than passing resemblance to Nabokov's most famous novel. American Beauty is that rare flower in American film – a major-studio (Dreamworks) production with A-list stars tackling material that many daredevil independents might hesitate to touch. The picture works the same territory as Todd Solondz's repugnant film Happiness, except here the characters are treated with compassion and a degree of humanity in spite of their weaknesses.
As the film opens, we learn Spacey's character is already dead. He narrates in flashback, a technique reminiscent of Sunset Boulevard. And it works.  Spacey explains his fall and ultimate redemption in the cynical-comical narration that frames the film. In fact, he says it all:
`In a year, I would be dead,' he says. `In a way, I already was.'
His character is a loser whose career is trapped in an office cubicle. His wife, a real-estate saleswoman, and their teen-age daughter (Birch) despise him for no reason other than he is socially awkward. Spacey doesn't even seem to like himself, though he masturbates in the shower before work and declares it will be `the highlight of my day.'
His wife would rather tend to her blood-red roses, framing the white-picket fence around their well-appointed home.  She worries that Spacey might spill a beer on her $4,000 silk upholstered sofa. Bening is mesmerizing in the role.
Spacey's daughter is embarrassed for him as he stumbles out the door, spilling the papers in his briefcase on the sidewalk.
The man knows something is missing from his life. When he meets the teen-age sexpot Angela, his brain begins to boil. He fantasizes encounters with the girl, reclining on a bed of rose petals. He quits his job, extorts $60,000 from his hateful boss and buys a 1971 fireapple-red muscle car. American Woman by the Guess Who blares on the stereo as he drives home. He wails along with the anthem, closing his eyes and nodding in recognition when that serpentine guitar solo kicks in (this movie deals brilliantly in subtext). He starts working out with free weights in the garage, after he eavesdrops on Angela telling his daughter that her dad would be hot if he had a little more muscle tone.
At a business party, while his wife flirts with the local king of home sales (a slick, silver-haired Gallagher), Spacey sneaks out of the noxious gathering to smoke a joint in the alley with the waiter (Bentley), a strange kid who's just moved in to Spacey's neighborhood. He's the creepy teen-ager next door.
Bentley has his own obsessions. He videotapes Spacey's daughter from his bedroom and slowly, shyly, begins an awkward romance with the troubled girl. He also sells high-quality pot and hides this enterprise from his abusive, homophobic ex-Marine father (Cooper). Bentley has to provide urine samples to his brutal dad every six months, ever since he was busted for dealing. His mother has been so brow-beaten by Cooper that she can only stare at the wall and make apologies for a house that is already spotless. Bentley is a brooding teen, biding his time for a chance to leave home. And although he professes to love the beauty in the world, in his piercing stare we sometimes catch a glimpse of Columbine madness.
 Theirs is the only enduring relationship in the film.
Their chance encounter with Spacey and later, with the baleful Cooper, triggers a series of comic misunderstandings between the core characters. The confusion escalates with frightening speed into violence and mind-numbing tragedy on a thunderous, rain-splattered night.
Spacey and his teen-age obsession exchange unforgettable words that will leave even the most jaded viewer reeling. Spacey's closing monologue, indeed, his final words, will haunt us long after the lights come up and we are left to ponder -- as if his words were not enough -- that richly symbolic use of red: the color of jealousy and hate. And of love.
Rated R for sexuality, nudity, familial violence, pervasive language and drug use.
Cinema Uprising copyright C 1999 by Stephen B. Evans. All rights reserved. This work may not be reproduced or transmitted in any form, by any means, without the prior, written permission of the author.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Born 436 BCE, died 338 BCE (source for date: OCD 3 ). Isocrates was the child of a wealthy flute-manufacturer who gave him an excellent education. He is said to have studied under Prodicus, Gorgias, Tisias, Theramenes, and Socrates. Isocrates spent the decade of the 390s writing speeches. However, much of the rest of Isocrates’ life was dedicated to teaching; he established a school at Athens sometime before 386 BCE (source for date: OCD 3 ). Among his students were the orators Hyperides and Isaeus, the historians Ephorus and Theopompus, and the atthidographer Androtion. Isocrates’ works are characterised by expressions of great love of Athens and by the promotion of ideas of Panhellenism, whereby, in his view, all of the Greek peoples could unite and declare war on the barbarous Persians. Of his works, twenty-one discourses on a wide range of topics and nine letters survive, most of which are considered to be genuine. (See also the genre of Oratory.)


Enum CipItemFlag
Enumerates all known CIP item flags.
Namespace: Fibula.Parsing.CipFiles.Enumerations
Assembly: Fibula.Parsing.CipFiles.dll
Syntax
public enum CipItemFlag : byte
Fields
| Name | Description |
|---|---|
| Ammo | The item is ammunition. |
| Armor | The item has armor traits. |
| Avoid | The item hints at avoiding pathfind. |
| Bank | The item has pathfinding. |
| Bed | The item is a bed. |
| Bottom | The item stays on bottom. |
| Bow | The item shoots ammunition. |
| ChangeUse | The item can be changed on use. |
| Chest | The item is a chest. |
| Clip | The item is clipped. |
| Clothes | The item can be dressed. |
| CollisionEvent | The item can trigger collision event rules. |
| Container | The item is a container. |
| Corpse | The item is a corpse. |
| Cumulative | The item is cummulative. |
| Destroy | The item can be destroyed. |
| Disguise | The item looks like another item. |
| DistUse | The item can be used at a distance. |
| Expire | The item has time based expiration. |
| ExpireStop | The item's expiration stops on use or undressing. |
| Food | The item has nutrition. |
| ForceUse | The item can be used even if there are other items blocking it. |
| Hang | The item can be hanged on a wall with a hook. |
| Height | The item has height. |
| HookEast | The item can hang/unhang as long as it is interacted with from the east. |
| HookSouth | The item can hang/unhang as long as it is interacted with from the south. |
| Information | The item provides extra information. |
| Key | The item is a key. |
| KeyDoor | The item is a door that can be locked. |
| LevelDoor | The item is a door that has level requirements. |
| Light | The item irradiates light. |
| LiquidContainer | The item is a liquid container. |
| LiquidPool | The item is a liquid pool. |
| LiquidSource | The item is a liquid source. |
| MagicField | The item is a magic field. |
| MovementEvent | The item can trigger movement events. |
| MultiUse | The item can be used on other things. |
| NameDoor | The item is a door which has a list of allowed users. |
| Protection | The item provides protection against some type of damage. |
| QuestDoor | The item is a door that is part of a quest. |
| RestrictLevel | The item has a level restriction. |
| RestrictProfession | The item has a profession restriction. |
| RopeSpot | The item is a spot where a rope can be used. |
| Rotate | The item can be rotated. |
| Rune | The item is a rune. |
| SeparationEvent | The item can trigger separation events. |
| Shield | The item has shield traits. |
| ShowDetail | The item has extra detail, like expire time. |
| SkillBoost | The item boosts skills. |
| Special | The item has special traits. |
| Take | The item can be taken. |
| TeleportAbsolute | The item is a teleportation device to an absolute location. |
| TeleportRelative | The item is a teleportation device to a relative location. |
| Text | The item holds text information. |
| Throw | The item can be thrown (as a weapon). |
| Top | The item stays on top of others. |
| Unlay | The item blocks laying other items on top. |
| Unmove | The item cannot be moved. |
| Unpass | The item blocks movement on top of it. |
| Unthrow | The item blocks throws through it. |
| UseEvent | The item can trigger use events. |
| Wand | The item is a wand. |
| Weapon | The item is a weapon. |
| WearOut | The item has a limited number of uses. |
| Write | The item can be writen on, multiple times. |
| WriteOnce | The item can be writen on only once. |


{% extends "layout.html" %} {% block bar_heading %} MOT testing service {% endblock %} {% block content %} {% include "includes/phase_banner_beta.html" %} Temporary sign in Sign in without your security card What was your favourite place to visit as a child? What did you want to be when you grew up? Forgotten your security questions? Call the DVSA helpdesk on 0330 123 5654 to reset your questions. Opening hours are: Monday to friday, 8am to 8pm Saturday, 8am to 2pm Sunday, closed Continue Back {% endblock %}
Call the DVSA helpdesk on 0330 123 5654 to reset your questions.
Opening hours are:
Continue


htmlentities
(PHP 4, PHP 5, PHP 7)
htmlentities — Convert all applicable characters to HTML entities
说明
string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401
[, string $encoding = ini_get("default_charset") [, bool $double_encode = true
]]] )
This function is identical to htmlspecialchars() in all ways, except with
htmlentities(), all characters which have HTML character entity equivalents are
translated into these entities.
If you want to decode instead (the reverse) you can use html_entity_decode().
参数
string
The input string.
flags
A bitmask of one or more of the following flags, which specify how to
handle quotes, invalid code unit sequences and the used document type. The
default is ENT_COMPAT | ENT_HTML401.
Available flags constants
Constant Name Description
ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES Will convert both double and single quotes.
ENT_NOQUOTES Will leave both double and single quotes unconverted.
Silently discard invalid code unit sequences instead of
ENT_IGNORE returning an empty string. Using this flag is discouraged as
it » may have security implications.
Replace invalid code unit sequences with a Unicode
ENT_SUBSTITUTE Replacement Character U+FFFD (UTF-8) or FFFD; (otherwise)
instead of returning an empty string.
Replace invalid code points for the given document type with
a Unicode Replacement Character U+FFFD (UTF-8) or FFFD;
ENT_DISALLOWED (otherwise) instead of leaving them as is. This may be
useful, for instance, to ensure the well-formedness of XML
documents with embedded external content.
ENT_HTML401 Handle code as HTML 4.01.
ENT_XML1 Handle code as XML 1.
ENT_XHTML Handle code as XHTML.
ENT_HTML5 Handle code as HTML 5.
encoding
An optional argument defining the encoding used when converting characters.
If omitted, the default value of the encoding varies depending on the PHP
version in use. In PHP 5.6 and later, the default_charset configuration
option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the
default. Earlier versions of PHP use ISO-8859-1.
Although this argument is technically optional, you are highly encouraged
to specify the correct value for your code if you are using PHP 5.5 or
earlier, or if your default_charset configuration option may be set
incorrectly for the given input.
支持以下字符集：
支持的字符集列表
字符集 别名 描述
ISO-8859-1 ISO8859-1 西欧，Latin-1
ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 ISO8859-15 西欧，Latin-9。增加欧元符号，法语和芬兰语字母在
Latin-1(ISO-8859-1) 中缺失。
UTF-8 ASCII 兼容的多字节 8 位 Unicode。
cp866 ibm866, 866 DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到
支持。
Windows-1251, Windows 特有的西里尔编码。本字符集在 4.3.2 版本中
cp1251 win-1251, 得到支持。
1251
cp1252 Windows-1252, Windows 特有的西欧编码。
1252
KOI8-R koi8-ru, 俄语。本字符集在 4.3.2 版本中得到支持。
koi8r
BIG5 950 繁体中文，主要用于中国台湾省。
GB2312 936 简体中文，中国国家标准字符集。
BIG5-HKSCS 繁体中文，附带香港扩展的 Big5 字符集。
Shift_JIS SJIS, 932 日语
EUC-JP EUCJP 日语
MacRoman Mac OS 使用的字符串。
An empty string activates detection from script
'' encoding (Zend multibyte), default_charset and
current locale (see nl_langinfo() and setlocale()
), in this order. Not recommended.
Note: 其他字符集没有认可。将会使用默认编码并抛出异常。
double_encode
When double_encode is turned off PHP will not encode existing html
entities. The default is to convert everything.
返回值
Returns the encoded string.
If the input string contains an invalid code unit sequence within the given
encoding an empty string will be returned, unless either the ENT_IGNORE or
ENT_SUBSTITUTE flags are set.
更新日志
版本 说明
5.6.0 The default value for the encoding parameter was changed to be the value
of the default_charset configuration option.
5.4.0 The default value for the encoding parameter was changed to UTF-8.
5.4.0 The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1,
ENT_XHTML and ENT_HTML5 were added.
5.3.0 The constant ENT_IGNORE was added.
5.2.3 The double_encode parameter was added.
范例
Example #1 A htmlentities() example
bold";
// Outputs: A 'quote' is bold
echo htmlentities($str);
// Outputs: A 'quote' is bold
echo htmlentities($str, ENT_QUOTES);
?>
Example #2 Usage of ENT_IGNORE
参见
• html_entity_decode() - Convert all HTML entities to their applicable
characters
• get_html_translation_table() - 返回使用 htmlspecialchars 和 htmlentities 后
的转换表
• htmlspecialchars() - Convert special characters to HTML entities
• nl2br() - 在字符串所有新行之前插入 HTML 换行标记
• urlencode() - 编码 URL 字符串
User Contributed Notes 39 notes
===============================================================================
An important note below about using this function to secure your application
against Cross Site Scripting (XSS) vulnerabilities.
When printing user input in an attribute of an HTML tag, the default
configuration of htmlEntities() doesn't protect you against XSS, when using
single quotes to define the border of the tag's attribute-value. XSS is then
possible by injecting a single quote:
XSS possible (insecure):
"; # results in:
?>
Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your
application is secure:
"; # results in:
?>
The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in
certain tag's attributes, like the 'href' attribute of the 'a' tag. When
clicked on the link below, the given JavaScript will get executed:
link"; # results in: link
?>
===============================================================================
I've seen lots of functions to convert all the entities, but I needed to do a
fulltext search in a db field that had named entities instead of numeric
entities (edited by tinymce), so I searched the tinymce source and found a
string with the value->entity mapping. So, i wrote the following function to
encode the user's query with named entities.
The string I used is different of the original, because i didn't want to
convert ' or ". The string is too long, so I had to cut it. To get the original
check TinyMCE source and search for nbsp or other entity ;)
===============================================================================
html entities does not encode all unicode characters. It encodes what it can
[all of latin1], and the others slip through. Љ is the nasty I use. I
have searched for a function which encodes everything, but in the end I wrote
this. This is as simple as I can get it. Consult an ansii table to custom
include/omit chars you want/don't. I'm sure it's not that fast.
// Unicode-proof htmlentities.
// Returns 'normal' chars as chars and weirdos as numeric html entites.
function superentities( $str ){
// get rid of existing entities else double-escape
$str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
$ar = preg_split('/(? 1) || /* multi-byte [unicode] */
($o <32 || $o > 126) || /* <- control / latin weirdos -> */
($o >33 && $o < 40) ||/* quotes + ambersand */
($o >59 && $o < 63) /* html */
) {
// convert to numeric entity
$c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff),
'UTF-8');
}
$str2 .= $c;
}
return $str2;
}
===============================================================================
The following will make a string completely safe for XML:
0 && $ord < 32) || ($ord >= 127)) {
$strout .= "&#{$ord};";
}
else {
switch ($strin[$i]) {
case '<':
$strout .= '<';
break;
case '>':
$strout .= '>';
break;
case '&':
$strout .= '&';
break;
case '"':
$strout .= '"';
break;
default:
$strout .= $strin[$i];
}
}
}
return $strout;
}
?>
===============================================================================
If you are building a loadvars page for Flash and have problems with special
chars such as " & ", " ' " etc, you should escape them for flash:
Try trace(escape("&")); in flash' actionscript to see the escape code for &;
% = %25
& = %26
' = %27
Those are the two that concerned me. YMMV.
===============================================================================
When putting values inside comment tags you should replace -- with
45;- too, as this would end your tag and show the rest of the comment.
===============================================================================
htmlentities seems to have changed at some point between version 5.1.6 and
5.3.3, such that it now returns an empty string for anything containing a pound
sign:
$ php -v
PHP 5.1.6 (cli) (built: May 22 2008 09:08:44)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
£hello
$
$ php -v
PHP 5.3.3 (cli) (built: Aug 19 2010 12:07:49)
$ php -r "echo htmlentities('£hello', null, 'utf-8');"
$
(Returns an empty string the second time)
Just a heads up.
===============================================================================
A useful little function to convert the symbols in the different inputs.
0) {
$var = htmlentities($var, ENT_NOQUOTES, 'UTF-8');
$var = str_replace('\"', '', $var);
$var = str_replace("\'", '', $var);
} else {
$var = htmlentities($var, ENT_QUOTES, 'UTF-8');
}
return $var;
}
?>
Usage with quotes for example message:
$message = ConvertSimbols($message);
Usage without quotes for example link:
$link = ConvertSimbols($link, 1);
===============================================================================
The flag ENT_HTML5 also strips newline chars like \n with htmlentities while
htmlspecialchars is not affected by that.
If you want to use nl2br on that string afterwards you might end up searching
the problem like i did. This does not apply to other flags like e.g. ENT_XHTML
which confused me.
Tested this with PHP 5.4 / 5.5 / 5.6-dev with same results, so it seems that
this is an intended "feature".
===============================================================================
For use of html tags, ampersands, etc. in xml document
(f.e.
data 1 & data2
)
one can use the CDATA brackets:
data 1 & data2]]>
-rq
===============================================================================
I'm glad 5.4 has xml support, but many of us are working with older
installations, some of us still have to use PHP4. If you're like me you've been
frustrated with trying to use htmlentites/htmlspecial chars with xml output. I
was hoping to find an option to force numeric encoding, lacking that, I have
written my own xmlencode function, which I now offer:
usage:
$string xmlencode( $string )
it will use htmlspecialchars for the valid xml entities amp, quote, lt, gt,
(apos) and return the numeric entity for all other non alpha-numeric
characters.
-------------------------------------------
1 ) ) {
die( "function: 'get_xml_entity_at_index_0' requires data type:
'char' (single character). '{$CHAR[0]}' does not match this type." );
}
switch( $CHAR[0] ) {
case "'": case '"': case '&': case '<': case '>':
return htmlspecialchars( $CHAR[0], ENT_QUOTES ); break;
default:
return numeric_entity_4_char($CHAR[0]); break;
}
}
function numeric_entity_4_char( $char ) {
return "".str_pad(ord($char), 3, '0', STR_PAD_LEFT).";";
}
}
?>
===============================================================================
For those Spanish (and not only) folks, that want their national letters back
after htmlentities :)
ENT_NOQUOTES,
'encoding' => 'UTF-8',
);
return preg_replace_callback(
'/&\w(acute|uml|tilde);/',
create_function(
'$m',
'return html_entity_decode($m[0], ' . $options['quote'] . ', "' .
$options['encoding'] . '");'
),
$encodedValue
);
}
?>
===============================================================================
Had a heck of a time to get my rss entities right. using htmlentities didn't
work and using html_entity_decode didn't work either. Ended up writing a custom
function to encode and decode. It might still need some work but I thought to
share it because I couldn't find anything on the net. Always open for
suggestions to improve it! Here it is:
$value) {
//print("
key: $key, value: $value
\n");
switch ($value) {
// These ones we can skip
case ' ':
break;
case '>':
case '<':
case '"':
case ''':
case '&':
$entity_custom_from[$array_position] = $key;
$entity_custom_to[$array_position] = $value;
$array_position++;
break;
default:
$entity_custom_from[$array_position] = $value;
$entity_custom_to[$array_position] = $key;
$array_position++;
}
}
}
return str_replace($entity_custom_from, $entity_custom_to, $data);
}
?>
===============================================================================
Trouble when using files with different charset?
htmlentities and html_entity_decode can be used to translate between charset!
Sample function:
===============================================================================
Hi there,
after several and several tests, I figured out that dot:
- htmlentities() function remove characters like "à","è",etc when you specify a
flag and a charset
- htmlentities() function DOES NOT remove characters like those above when you
DO NOT specify anything
So, let's assume that..
I used this for a textarea content for comments. Anyway, note that using the
"$res_2" form the function will leave unconverted single/double quotes. At this
point you should use str_replace() function to perform the characters but be
careful because..
Nice
?>
Hope it will helps you.
Regards,
W.D.
===============================================================================
I use this function to encode all the xml entities and also all the &something;
that are not defined in xml like ™
You can also decode what you encode with my decode function.
My function works a little like the htmlentities.
You can also add other string to the array if you want to exclude them from the
encoding.
$value){
$arr_xml_special_char_regex .= "(?!$value)";
}
$arr_xml_special_char_regex .= ")";
// Scan the array for &something_not_xml; syntax
$pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";
// Replace the &something_not_xml; with &something_not_xml;
$replacement = '&${1}';
return preg_replace($pattern, $replacement, $text);
}
?>
===============================================================================
A version of the xml entities function below. This one replaces the "prime"
character (′) with which I had difficulties.
', '�' ), array ( '&'
, '"', ''' , '<' , '>', ''' ), $string );
}
?>
===============================================================================
This fuction is particularly useful against XSS (cross-site-scripting-). XSS
makes use of holes in code, whether it be in Javascript or PHP. XSS often, if
not always, uses HTML entities to do its evil deeds, so this function in
co-operation with your scripts (particularly search or submitting scripts) is a
very useful tool in combatting "H4X0rz".
===============================================================================
Correction to my previous post: the set of ENTITY declarations must be inside a
\n"
;
}
}
$output .= "]>\n";
return($output);
}
// ref: http://php.net/manual/en/function.get-html-translation-table.php#76564
function get_html_translation_table_CP1252($type) {
$trans = get_html_translation_table($type);
$trans[chr(130)] = '‚'; // Single Low-9 Quotation Mark
$trans[chr(131)] = 'ƒ'; // Latin Small Letter F With Hook
$trans[chr(132)] = '„'; // Double Low-9 Quotation Mark
$trans[chr(133)] = '…'; // Horizontal Ellipsis
$trans[chr(134)] = '†'; // Dagger
$trans[chr(135)] = '‡'; // Double Dagger
$trans[chr(136)] = 'ˆ'; // Modifier Letter Circumflex Accent
$trans[chr(137)] = '‰'; // Per Mille Sign
$trans[chr(138)] = 'Š'; // Latin Capital Letter S With Caron
$trans[chr(139)] = '‹'; // Single Left-Pointing Angle
Quotation Mark
$trans[chr(140)] = 'Œ'; // Latin Capital Ligature OE
$trans[chr(145)] = '‘'; // Left Single Quotation Mark
$trans[chr(146)] = '’'; // Right Single Quotation Mark
$trans[chr(147)] = '“'; // Left Double Quotation Mark
$trans[chr(148)] = '”'; // Right Double Quotation Mark
$trans[chr(149)] = '•'; // Bullet
$trans[chr(150)] = '–'; // En Dash
$trans[chr(151)] = '—'; // Em Dash
$trans[chr(152)] = '˜'; // Small Tilde
$trans[chr(153)] = '™'; // Trade Mark Sign
$trans[chr(154)] = 'š'; // Latin Small Letter S With Caron
$trans[chr(155)] = '›'; // Single Right-Pointing Angle
Quotation Mark
$trans[chr(156)] = 'œ'; // Latin Small Ligature OE
$trans[chr(159)] = 'Ÿ'; // Latin Capital Letter Y With
Diaeresis
$trans['euro'] = '€'; // euro currency symbol
ksort($trans);
return $trans;
}
?>
[EDIT BY danbrown AT php DOT net: The user's original note contained the
following text:
"So here's something fun: if you create an XML document in PHP and use
htmlentities() to encode text data, then later want to read and parse the same
document with PHP's xml_parse(), unless you include entity declarations into
the generated document, the parser will stop on the unknown entities.
To account for this, I created a small function to take the translation table
and turn it into XML definitions. I insert this output into the XML
document immediately after the line and the parse errors magically
vanish"
]
===============================================================================
I needed a simple little function to take a string and convert extended ascii
characters into html entities. I couldn't find a function for this so I whipped
one up.
===============================================================================
correction to my previous post and improvement of the function: (the post was
changed by the html parser and the characters displays as they should not)
'€',
130 => '‚',
131 => 'ƒ',
132 => '„',
133 => '…',
134 => '†',
135 => '‡',
136 => 'ˆ',
137 => '‰',
138 => 'Š',
139 => '‹',
140 => 'Œ',
142 => 'Ž',
145 => '‘',
146 => '’',
147 => '“',
148 => '”',
149 => '•',
150 => '–',
151 => '—',
152 => '˜',
153 => '™',
154 => 'š',
155 => '›',
156 => 'œ',
158 => 'ž',
159 => 'Ÿ');
$num = ord($num);
return (($num > 127 && $num < 160) ? $chars[$num] : "".$num.";" );
}
?>
in the previous post, to correct the HEX values that are not rendered, the
program use a for each cicle, but that introduces a mayor complexity in
execution time, so, we use the ability to call functions in the preg_replace
second parameter, and ceate another funcion that evaluates the ord of the
character given, and if it is between 127 and 160 it returns the modified HEX
value to be understood by the browser and not brake the XML
(this work with dynamic XML generated form php with dynamic data from any
source)
p.d: the '&'(&) should appear in this post as a single ampersand character and
not as the html entity
===============================================================================
Note that you'll have use htmlentities() before any other function who'll edit
text like nl2br().
If you use nl2br() first, the htmlentities() function will change
 to &
lt;br>.
===============================================================================
Note that as of 5.2.5 it appears that if the input string contains a character
that is not valid for the output encoding you've specified, then this function
returns null.
You might expect it to just strip the invalid char, but it doesn't.
You can strip the chars yourself like so:
iconv('utf-8','utf-8',$str);
You can combine that with htmlentities also:
$str = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str, ENT_QUOTES, 'UTF-8');
Should give you a string with htmlentities encoded to utf-8, and any
unsupported chars stripped.
===============================================================================
CZECH entities:
'ě',
'Ě' => 'Ě',
'š' => 'š',
'Š' => 'Š',
'č' => 'č',
'Č' => 'Č',
'ř' => 'ř',
'Ř' => 'Ř',
'ž' => 'ž',
'Ž' => 'Ž',
'ý' => 'ý',
'Ý' => 'Ý',
'á' => 'á',
'Á' => 'Á',
'í' => 'í',
'Í' => 'Í',
'é' => 'é',
'É' => 'É',
'ú' => 'ú',
'ů' => 'ů',
'Ů' => 'Ů',
'ď' => 'ď',
'Ď' => 'Ď',
'ť' => 'ť',
'Ť' => 'Ť',
'ň' => 'ň',
'Ň' => 'Ň'
);
echo strtr('ěščřžýáíéúůďťňĚŠČŘŽÝÁÍÉÚŮĎŤŇ', $ent);
?>
===============================================================================
When using UTF-8 as charset, you'll have to set UTF-8 in braces, otherwise the
varaible is not recognized.
===============================================================================
'€',
130 => '‚',
131 => 'ƒ',
132 => '„',
133 => '…',
134 => '†',
135 => '‡',
136 => 'ˆ',
137 => '‰',
138 => 'Š',
139 => '‹',
140 => 'Œ',
142 => 'Ž',
145 => '‘',
146 => '’',
147 => '“',
148 => '”',
149 => '•',
150 => '–',
151 => '—',
152 => '˜',
153 => '™',
154 => 'š',
155 => '›',
156 => 'œ',
158 => 'ž',
159 => 'Ÿ');
?>
===============================================================================
I just thought I would add that if you're using the default charset,
htmlentities will not correctly return the trademark ( ™ ) sign.
Instead it will return something like this: â�¢
If you need the trademark symbol, use:
===============================================================================
under what circumstances would someone want a ntilde [ñ] to be converted into
"Ã±" as htmlentities does?
the correct method of translation should return the accurate NCR for the
multibyte unicode sequence
which in this case is ñ
unicode_string_to_array($content);
$swap = "";
$iCount = count($contents);
for ($o=0;$o<$iCount;$o++) {
$contents[$o] = $this->unicode_entity_replace($contents[$o]);
$swap .= $contents[$o];
}
return mb_convert_encoding($swap,"UTF-8"); //not really necessary,
but why not.
}
public function unicode_string_to_array( $string ) { //adjwilli
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr( $string, 0, 1, "UTF-8" );
$string = mb_substr( $string, 1, $strlen, "UTF-8" );
$strlen = mb_strlen( $string );
}
return $array;
}
public function unicode_entity_replace($c) { //m. perez
$h = ord($c{0});
if ($h <= 0x7F) {
return $c;
} else if ($h < 0xC2) {
return $c;
}
if ($h <= 0xDF) {
$h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
$h = "" . $h . ";";
return $h;
} else if ($h <= 0xEF) {
$h = ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2})
& 0x3F);
$h = "" . $h . ";";
return $h;
} else if ($h <= 0xF4) {
$h = ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2
}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
$h = "" . $h . ";";
return $h;
}
}
}//
//utf-8 environment
$content = "baño baño baño日本語 = nihongo da ze.
";
$oUnicodeReplace = new unicode_replace_entities();
$content = $oUnicodeReplace->UTF8entities($content);
echo "
Result:
";
echo $content;
$source = htmlentities($content);
echo "
htmlentities of resulting data:
";
echo $source;
echo "
Note: Entities get replaced with 'literals' in textarea
FF3
";
echo "";
echo "
For editing NCR's rather than 'literals' in a textarea
";
echo "";
?>
===============================================================================
Croatian entites
'Ć',
'ć'=>'ć',
'Č'=>'Č',
'č'=>'č',
'Đ'=>'Đ',
'đ'=>'đ',
'Š'=>'Š',
'š'=>'š',
'Ž'=>'Ž',
'ž'=>'ž'
);
echo strtr('ĆćČčĐđŠšŽž', $ent);
?>
===============================================================================
When happens that you want to encode special characters but not the HTML tags
using this function you've two options:
a) Build your own function and go replace by character; eg.
b) use this function and simple restore the html tags afterwards. Which gives
you a 6 line function as follow:
",$res);
$res = str_replace(""",'"',$res);
$res = str_replace("&",'&',$res);
return $res;
}
?>
===============================================================================
If you want something simple that actually works, try this. Strips MS word and
other entities and returns a clear data string:
===============================================================================
unhtmlentities for all entities:
$htmlentitie ) {
$trans_tbl2[$ascii] = ''.ord($ascii).';';
}
$trans_tbl1 = array_flip ($trans_tbl1);
$trans_tbl2 = array_flip ($trans_tbl2);
return strtr (strtr ($string, $trans_tbl1), $trans_tbl2);
}
?>
===============================================================================
A pointer to http://www.php.net/manual/en/function.mb-convert-encoding.php if
your intention is to translate *all* characters in a charset to their
corresponding HTML entities, not just named characters. Non-named characters
will be replaced with HTML numeric encoding. eg:
$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
===============================================================================
use htmlspecialchars() if you are passing in a usual ASCII string. It is
faster than htmlentities().
For example, if you are just doing
htmlentities('');
then you can just use htmlspecialchars(). htmlentities() will look for all
possible ways to convert string into html entities, such as © or é
(which is e with an acute accent on top).
Note that ASCII is just 7 bit, which is 0x00 to 0x7F. htmlspecialchars() will
handle characters inside this range already. htmlentities() is for the 8-bit
Latin-1 (ISO-8859-1) to handle European characters, or for UTF-8 when the 3rd
argument is "UTF-8" to handle UTF-8 characters, or other types of encodings
using different values for the 3rd argument passed into htmlentities().
===============================================================================
The data returned by a text input field is ready to be used in a data base
query when enclosed in single quotes, e.g.
But you will get problems when writing back this data into the input field's
value,
";
?>
because hmtl codes would be interpreted and escape sequences would cause
strange output.
The following function may help:
Try some input like: a'b"c\d\'e\"f\\g&x#27;h to test ...
===============================================================================
htmlentites is a very handy function, but it fails to fix one thing which I
deal with alot: word 'smart' quotes and emdashes.
The below function replaces the funky double quotes with ", funky single
quotes with standard single quotes and fixes emdashes.
===============================================================================
All Codes list
array('À'=>'À', 'à'=>'à', 'Á'=>'Á', 'á'=>'á', 'Â'=>
'Â', 'â'=>'â', 'Ã'=>'Ã', 'ã'=>'ã', 'Ä'=>'Ä', 'ä'
=>'ä', 'Å'=>'Å', 'å'=>'å', 'Æ'=>'Æ', 'æ'=>'æ', 'Ç'
=>'Ç', 'ç'=>'ç', 'Ð'=>'Ð', 'ð'=>'ð', 'È'=>'È', 'è'
=>'è', 'É'=>'É', 'é'=>'é', 'Ê'=>'Ê', 'ê'=>'ê',
'Ë'=>'Ë', 'ë'=>'ë', 'Ì'=>'Ì', 'ì'=>'ì', 'Í'=>'Í
', 'í'=>'í', 'Î'=>'Î', 'î'=>'î', 'Ï'=>'Ï', 'ï'=>'ï
', 'Ñ'=>'Ñ', 'ñ'=>'ñ', 'Ò'=>'Ò', 'ò'=>'ò', 'Ó'=>'&
Oacute;', 'ó'=>'ó', 'Ô'=>'Ô', 'ô'=>'ô', 'Õ'=>'Õ', 'õ'
=>'õ', 'Ö'=>'Ö', 'ö'=>'ö', 'Ø'=>'Ø', 'ø'=>'ø',
'Œ'=>'Œ', 'œ'=>'œ', 'ß'=>'ß', 'Þ'=>'Þ', 'þ'=>'þ',
'Ù'=>'Ù', 'ù'=>'ù', 'Ú'=>'Ú', 'ú'=>'ú', 'Û'=>'&
Ucirc;', 'û'=>'û', 'Ü'=>'Ü', 'ü'=>'ü', 'Ý'=>'Ý', 'ý'=>'&
yacute;', 'Ÿ'=>'Ÿ', 'ÿ'=>'ÿ');
===============================================================================
here the centralized version of htmlentities() for multibyte.
===============================================================================
This function will encode anything that is non Standard ASCII (that is, that is
above #127 in the ascii table)
[http://www.php.net/htmlentities]
function allhtmlentities($string) {
if ( strlen($string) == 0 )
return $string;
$result = '';
$string = htmlentities($string, HTML_ENTITIES);
$string = preg_split("//", $string, -1, PREG_SPLIT_NO_EMPTY);
$ord = 0;
for ( $i = 0; $i < count($string); $i++ ) {
$ord = ord($string[$i]);
if ( $ord > 127 ) {
$string[$i] = '' . $ord . ';';
}
}
return implode('',$string);
}
?>