text
stringlengths 1
22.8M
|
|---|
SIP trunking is a voice over Internet Protocol (VoIP) technology and streaming media service based on the Session Initiation Protocol (SIP) by which Internet telephony service providers (ITSPs) deliver telephone services and unified communications to customers equipped with SIP-based private branch exchange (IP-PBX) and unified communications facilities. Most unified communications applications provide voice, video, and other streaming media applications such as desktop sharing, web conferencing, and shared whiteboard.
Domains
The architecture of SIP trunking provides a partitioning of the unified communications network into two different domains of expertise:
Private domain: refers to a part of the network connected to a PBX or unified communications server.
Public domain: refers to the part of the network which allows access into the public switched telephone network (PSTN) or public land mobile network (PLMN).
The interconnection between the two domains must occur through a SIP trunk. The interconnection between the two domains, created by transport via the Internet Protocol (IP), involves setting specific rules and regulations as well as the ability to handle some services and protocols that fall under the name of SIP trunking.
The ITSP is responsible to the applicable regulatory authority regarding all the following law obligations of the public domain:
Tracking traffic;
Identification of users;
Implementation of the lawful interception mechanisms.
The private domain instead, by nature, is not subject to particular constraints of law, and may be either the responsibility of the ITSP, the end user (enterprise), or of a third party who provides the voice services to the company
Architecture
Each domain has elements that perform the characteristic features requested of that domain, in particular the result (as part of any front-end network to the customer) is logically divided into two levels:
The control of access (Class 5 softswitch);
Network-border elements that separate the Public Domain from the Private Domain, implementing all the appropriate ITSP phone security policies.
The private domain consists of three levels:
corporate-border elements that separate the public domain from the private domain, implementing the appropriate company security policies
central corporate switching node
IP PBXs
See also
Trunking
Session border controller (SBC)
References
Telecommunication services
VoIP protocols
|
The 1975 Jackson State Tigers football team represented the Jackson State University as a member of the Southwestern Athletic Conference (SWAC) during the 1975 NCAA Division II football season. Led by fifth-year head coach Robert Hill, The Tigers compiled an overall record of 7–3 with a conference mark of 4–2, sharing the SWAC title with Grambling State and Southern.
Schedule
References
Jackson State
Jackson State Tigers football seasons
Southwestern Athletic Conference football champion seasons
Jackson State Tigers football
|
```php
<?php
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
*/
namespace Google\Service\BinaryAuthorization;
class SigstorePublicKey extends \Google\Model
{
/**
* @var string
*/
public $publicKeyPem;
/**
* @param string
*/
public function setPublicKeyPem($publicKeyPem)
{
$this->publicKeyPem = $publicKeyPem;
}
/**
* @return string
*/
public function getPublicKeyPem()
{
return $this->publicKeyPem;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SigstorePublicKey::class, 'Google_Service_BinaryAuthorization_SigstorePublicKey');
```
|
```kotlin
package com.cyl.musiclake.ui.music.artist.presenter
import com.cyl.musiclake.ui.base.BasePresenter
import com.cyl.musiclake.ui.music.artist.contract.ArtistSongContract
import javax.inject.Inject
/**
* Created by yonglong on 2018/1/7.
*/
class ArtistSongsPresenter @Inject
constructor() : BasePresenter<ArtistSongContract.View>(), ArtistSongContract.Presenter {
override fun loadSongs(artistName: String) {
}
}
```
|
Charles Gustavus Ulrich Dahlgren (August 13, 1811 – December 18, 1888) was a brigadier general of Mississippi State Troops (or Mississippi Militia) with allegiance to the Confederate States of America during the American Civil War. He commanded the 3rd Brigade of the Mississippi Militia, before a dispute with the President of the Confederate States of America, Jefferson Davis, over transfer of the state troops to the Confederate States Army cost him his career.
Early life and career
Dahlgren was born in Philadelphia, Pennsylvania, the son of Bernhard Ulrik Dahlgren (1784-1824) and Martha (Rowan) Dahlgren (1789-1838). His father was a merchant and Swedish Consul stationed in Philadelphia. He briefly served in the United States Navy. His older brother was John A. Dahlgren, an admiral in the Union Navy. He moved to Louisiana, then to Mississippi, as a young man. He was an official of the Bank of the United States at Natchez, Mississippi, and engaged in several other business ventures.
Civil War service
Following Mississippi's passage of the ordinance of secession and the subsequent outbreak of the Civil War, Dahlgren raised two regiments of state-sponsored volunteer infantry (the 3rd and 7th Mississippi Infantry Regiments) by his own means. When his brigade (Brigade 3) was transferred from state service to the Provisional Army of the Confederate States, he lost his command. Dahlgren was known for a short temper and strong opinions, and strongly opposed this transfer. His outspoken opposition to the nationalization of his men cost him his command and sparked a feud with the family of Jefferson Davis that spanned from 1862 to 1906.
Later life
After the Civil War, Dahlgren had lost his plantation and fortune and moved to New Orleans to practice law. Thereafter, he moved with his family to Nashville, Tennessee, for several months in 1870, then to Winchester, Virginia, and finally to New York City in 1876, where he worked as a lawyer and public accountant. He died at Brooklyn, New York, on December 18, 1888, and was buried in the City Cemetery, Natchez, Mississippi.
See also
List of American Civil War generals (Acting Confederate)
Notes
References
Allardice, Bruce S. More Generals in Gray. Baton Rouge: Louisiana State University Press, 1995. .
Eicher, John H., and David J. Eicher, Civil War High Commands. Stanford: Stanford University Press, 2001. .
Gower, Herschel, Charles Dahlgren of Natchez: The Civil War and Dynastic Decline, Brassey's, Inc., 2002, .
Marell, Oscar G. Sweden-America (Swedish Chamber of Commerce of the United States of America, 1918.
1811 births
1888 deaths
Military personnel from Philadelphia
American people of Swedish descent
Confederate militia generals
People of Mississippi in the American Civil War
Northern-born Confederates
|
```java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.api.dsl.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.Bind;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Introspectable;
import com.oracle.truffle.api.dsl.Introspection;
import com.oracle.truffle.api.dsl.Introspection.SpecializationInfo;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.dsl.UnsupportedSpecializationException;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindBindsCacheNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindCachedNodeTestNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindFieldNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindInLimitNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindMethodNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindMethodTwiceNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindNodeFieldNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindThisMultipleInstancesTestNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindThisTestNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedInAssumptionNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedInLimitNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedWithLibraryNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicAndCachedNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicWithLibraryNodeGen;
import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.IntrospectableNodeGen;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.profiles.InlinedBranchProfile;
import com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest;
@SuppressWarnings({"truffle-inlining", "truffle-neverdefault", "truffle-sharing", "unused"})
public class BindExpressionTest extends AbstractPolyglotTest {
static class TestObject {
Object storage = new Object();
Assumption assumption = Truffle.getRuntime().createAssumption();
int counter = 0;
int bind() {
return counter++;
}
}
/*
* Test that storage field extraction works. Unfortunately here we cannot check how many times a
* field is read.
*/
@Test
public void testBindField() {
BindFieldNode node = BindFieldNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
assertFails(() -> node.execute(new TestObject()), UnsupportedSpecializationException.class);
}
abstract static class BindFieldNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "storage == cachedStorage", limit = "1")
Object s0(TestObject a0,
@Bind("a0.storage") Object storage,
@Cached("storage") Object cachedStorage) {
assertSame(storage, cachedStorage);
assertSame(a0.storage, storage);
return a0;
}
}
/*
* This test verifies that the extract expression is invoked exactly once. Even though it is
* used multiple times.
*/
@Test
public void testBindMethod() {
BindMethodNode node = BindMethodNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindMethodNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "counter == 0")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter,
@Cached("counter") int cachedCounter) {
assertEquals(0, counter);
assertEquals(0, cachedCounter);
return a0;
}
}
/*
* This test verifies that the expression is invoked once even if used multiple times in the
* guard.
*/
@Test
public void testBindMethodTwice() {
BindMethodTwiceNode node = BindMethodTwiceNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindMethodTwiceNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "counter == 0 || counter == 1")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter,
@Cached("counter") int cachedCounter) {
assertEquals(0, cachedCounter);
return a0;
}
}
/*
* Tests that if a guard binds a cached expression indirectly through extract it is not actually
* executed multiple times.
*/
@Test
public void testBindBindsCache() {
BindBindsCacheNode node = BindBindsCacheNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
node.execute(o);
}
abstract static class BindBindsCacheNode extends Node {
abstract Object execute(Object arg0);
@ExpectError("The limit expression has no effect.%")
// this guard is trivially true but the DSL cannot detect that yet.
@Specialization(guards = "counter == cachedCounter", limit = "3")
Object s0(TestObject a0,
@Cached("0") int cachedCounter,
@Bind("cachedCounter") int counter) {
assertEquals(0, counter);
assertEquals(0, cachedCounter);
return a0;
}
}
/*
* We need to make sure introspectable does not include bind parameters.
*/
@Test
public void testIntrospectable() {
IntrospectableNode node = IntrospectableNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
List<SpecializationInfo> infos = Introspection.getSpecializations(node);
assertEquals(1, infos.size());
for (SpecializationInfo info : infos) {
assertEquals(1, info.getInstances());
List<Object> cachedData = info.getCachedData(0);
assertEquals(1, cachedData.size());
assertSame(o.storage, cachedData.iterator().next());
}
}
@Introspectable
abstract static class IntrospectableNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "storage == cachedStorage", limit = "2")
Object s0(TestObject a0,
@Bind("a0.storage") Object storage,
@Cached("storage") Object cachedStorage) {
assertSame(storage, cachedStorage);
assertSame(a0.storage, storage);
return a0;
}
}
/*
* This test verifies that an extract expression can be used in a limit expression if it only
* binds cached values.
*/
@Test
public void testBindInLimit() {
BindInLimitNode node = BindInLimitNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindInLimitNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "counter == cachedCounter", limit = "limit")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter,
@Bind("2") int limit,
@Cached("counter") int cachedCounter) {
assertEquals(cachedCounter, counter);
assertEquals(cachedCounter, cachedCounter);
return a0;
}
}
/*
* This test verifies that an extract expression can be chained transitively and its dynamic
* nature is preserved.
*/
@Test
public void testBindTransitiveDynamic() {
BindTransitiveDynamicNode node = BindTransitiveDynamicNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindTransitiveDynamicNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "counter4 == cachedCounter", limit = "2")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter1,
@Bind("counter1") int counter2,
@Bind("counter2") int counter3,
@Bind("counter3") int counter4,
@Cached("counter3") int cachedCounter) {
return a0;
}
}
/*
* This test verifies that an extract expression can be chained transitively and its dynamic
* nature is preserved.
*/
@Test
public void testBindTransitiveDynamicAndCachedNode() {
BindTransitiveDynamicAndCachedNode node = BindTransitiveDynamicAndCachedNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindTransitiveDynamicAndCachedNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "counter1 == counter2", limit = "2")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter1,
@Cached("counter1") int cachedCounter,
@Bind("cachedCounter") int counter2) {
return a0;
}
}
/*
* This test verifies that an extract expression can be chained transitively and its dynamic
* nature is preserved when used with a library.
*/
@Test
public void testBindTransitiveDynamicWithLibrary() {
BindTransitiveDynamicWithLibraryNode node = adoptNode(BindTransitiveDynamicWithLibraryNodeGen.create()).get();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindTransitiveDynamicWithLibraryNode extends Node {
abstract Object execute(Object arg0);
// this should not trigger a warning
@Specialization(guards = "counter2 < 2", limit = "3")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter1,
@Bind("counter1") int counter2,
@CachedLibrary("counter2") InteropLibrary lib) {
assertTrue(lib.isNumber(counter2));
return a0;
}
}
/*
* This test verifies that an extract expression can be chained transitively and its cached
* nature is preserved when used with a library.
*/
@Test
public void testBindTransitiveCachedWithLibrary() {
BindTransitiveCachedWithLibraryNode node = BindTransitiveCachedWithLibraryNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
}
abstract static class BindTransitiveCachedWithLibraryNode extends Node {
abstract Object execute(Object arg0);
@ExpectError("The limit expression has no effect.%")
@Specialization(limit = "3")
Object s0(TestObject a0,
@Cached("a0.bind()") int cachedCounter,
@Bind("cachedCounter") int counter1,
@Bind("counter1") int counter2,
@CachedLibrary("counter2") InteropLibrary lib) {
assertTrue(lib.isNumber(counter2));
return a0;
}
}
@Test
public void testBindTransitiveCachedInLimit() {
BindTransitiveCachedInLimitNode node = BindTransitiveCachedInLimitNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
abstract static class BindTransitiveCachedInLimitNode extends Node {
abstract Object execute(Object arg0);
@Specialization(guards = "cachedBind == counter", limit = "extractCachedLimit2")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter,
@Cached("counter") int cachedBind,
@Cached("2") int cachedLimit,
@Bind("cachedLimit") int extractCachedLimit1,
@Bind("extractCachedLimit1") int extractCachedLimit2) {
assertEquals(2, cachedLimit);
return a0;
}
}
@Test
public void testBindTransitiveCachedInAssumption() {
BindTransitiveCachedInAssumptionNode node = BindTransitiveCachedInAssumptionNodeGen.create();
TestObject o = new TestObject();
node.execute(o);
node.execute(o);
o.assumption.invalidate();
assertFails(() -> node.execute(o), UnsupportedSpecializationException.class);
}
/*
* Test use of assumption is allowed for transitive extracted cached values.
*/
@SuppressWarnings("truffle-assumption")
abstract static class BindTransitiveCachedInAssumptionNode extends Node {
abstract Object execute(Object arg0);
@Specialization(assumptions = "extractAssumption2")
Object s0(TestObject a0,
@Cached(value = "a0.assumption", neverDefault = true) Assumption assumption,
@Bind("assumption") Assumption extractAssumption1,
@Bind("extractAssumption1") Assumption extractAssumption2) {
return a0;
}
}
@Test
public void testBindNodeField() {
BindNodeFieldNode node = BindNodeFieldNodeGen.create(2);
TestObject o = new TestObject();
assertEquals(2, node.execute(o));
assertEquals(2, node.execute(o));
}
@NodeField(name = "field0", type = int.class)
abstract static class BindNodeFieldNode extends Node {
abstract Object execute(Object arg0);
@Specialization
int s0(TestObject a0,
@Bind("field0") int field) {
return field;
}
}
@Test
public void testBindThis() {
BindThisTest node = BindThisTestNodeGen.create();
node.execute();
}
abstract static class BindThisTest extends Node {
abstract void execute();
@Specialization
void s0(@Bind("this") Node thisNode) {
assertSame(this, thisNode);
}
}
abstract static class BindThisParentTest extends Node {
abstract void execute();
@Specialization
void s0(@Bind("this.getParent()") Node thisNode) {
assertSame(this.getParent(), thisNode);
}
}
@Test
public void testBindThisMultipleInstances() {
BindThisMultipleInstancesTest node = BindThisMultipleInstancesTestNodeGen.create();
node.execute(42);
node.execute(43);
node.execute(44);
node.execute(45);
}
abstract static class BindThisMultipleInstancesTest extends Node {
abstract void execute(int arg);
@Specialization(guards = "arg == cachedArg", limit = "2")
void s0(int arg,
@Cached("arg") int cachedArg,
@Bind("this") Node thisNode) {
/*
* The specialization does not bind nodes therefore it returns the current node instead
* of the specialization class.
*/
assertSame(this, this);
}
@SuppressWarnings("truffle-static-method")
@Specialization(guards = "arg == cachedArg", limit = "2")
void s1(int arg,
@Cached("arg") int cachedArg,
@Cached InlinedBranchProfile branchProfile,
@Bind("this") Node thisNode) {
/*
* The specialization does not bind nodes therefore it returns the current node instead
* of the specialization class.
*/
branchProfile.enter(thisNode);
assertNotSame(this, thisNode);
assertSame(thisNode.getParent(), this);
}
}
@Test
public void testBindCachedNodeTest() {
BindCachedNodeTest node = adoptNode(BindCachedNodeTestNodeGen.create()).get();
TestObject o = new TestObject();
assertEquals("42", node.execute("42"));
}
abstract static class BoundTestNode extends Node {
abstract Object execute(Object arg);
@Specialization
Object s0(Object arg) {
return arg;
}
}
abstract static class BindCachedNodeTest extends Node {
static int LIMIT = 0;
abstract Object execute(Object arg0);
@Specialization(limit = "LIMIT")
Object s0(Object arg0,
@Cached BoundTestNode testNode,
@Bind("testNode.execute(arg0)") Object result,
@CachedLibrary("result") InteropLibrary lib) {
try {
return lib.asString(result);
} catch (UnsupportedMessageException e) {
throw CompilerDirectives.shouldNotReachHere();
}
}
}
@SuppressWarnings("truffle-assumption")
abstract static class ErrorUseInAssumptionsNode extends Node {
abstract Object execute(Object arg0);
@ExpectError("Assumption expressions must not bind dynamic parameter values.")
@Specialization(assumptions = "assumption")
Object s0(TestObject a0,
@Bind("a0.assumption") Assumption assumption) {
return a0;
}
}
abstract static class ErrorUseInLimitNode extends Node {
abstract Object execute(Object arg0);
@ExpectError("Limit expressions must not bind dynamic parameter values.")
@Specialization(guards = "counter == cachedCounter", limit = "counter")
Object s0(TestObject a0,
@Bind("a0.bind()") int counter,
@Cached("counter") int cachedCounter) {
assertEquals(1, counter);
assertEquals(1, cachedCounter);
return a0;
}
}
abstract static class ErrorCyclicUseNode extends Node {
abstract Object execute(Object arg0);
@Specialization
Object s0(TestObject a0,
@Bind("a0.bind()") int extract,
@ExpectError("The initializer expression of parameter 'counter1' binds uninitialized parameter 'counter2. Reorder the parameters to resolve the problem.")//
@Bind("counter2") int counter1,
@Bind("counter1") int counter2) {
return a0;
}
}
abstract static class ErrorSyntaxNode extends Node {
abstract Object execute(Object arg0);
@Specialization
Object s0(TestObject a0,
@ExpectError("Error parsing expression 'asdf32': asdf32 cannot be resolved.")//
@Bind("asdf32") int extract) {
return a0;
}
}
abstract static class ErrorEmptyNode extends Node {
abstract Object execute(Object arg0);
@Specialization
Object s0(TestObject a0,
@ExpectError("Error parsing expression '': line 1:0 mismatched input '<EOF>'%")//
@Bind("") int extract) {
return a0;
}
}
/*
* We don't want that static node constructors are looked up for extract annotations. This
* should only work for Cached.
*/
abstract static class ErrorUseNodeNode extends Node {
abstract Object execute(Object arg0);
@Specialization
Object s0(TestObject a0,
@ExpectError("Error parsing expression 'create()': The method create is undefined for the enclosing scope.")//
@Bind("create()") BindFieldNode node) {
return a0;
}
}
abstract static class ErrorBindThisWithCachedTest extends Node {
abstract void execute();
@Specialization
void s0(@ExpectError("Cannot use 'this' with @Cached use @Bind instead.") //
@Cached("this") Node thisNode) {
}
}
}
```
|
Giv'ot Zaid (, lit. Hills of Zaid) was a kibbutz in northern Israel.
History
The kibbutz was established in 1943, to the north of the former home of Alexander Zaïd (from whom it took its name), who was murdered in 1938. The founders were made up of members of the Yerushalayimi gar'in organised by Yohanan Zaïd, graduates of Mikveh Israel organised by Yiftah Zaïd, and immigrants from Poland and Romania. By 1947 it had 135 members, with 2,300 dunams being cultivated.
In 1950 the kibbutz was dissolved due to disagreements between the residents. In 1951, some of them established the village of Beit Zaid on the site of Zaïd's residence. In 1960 a centre for adults with special needs, Kfar Tikvah was founded on the site of Givat Zaid.
References
Former kibbutzim
Populated places established in 1943
1943 establishments in Mandatory Palestine
Jezreel Valley Regional Council
1950 disestablishments in Israel
|
Dudley v Dudley (1705) Prec Ch 241; 24 ER 118 is a 1705 case of the Court of Chancery commonly cited in textbooks on law for its statement on the nature of equity.
Lord Cowper, who gave the report, is sometimes misspelled as Lord Copper.
Facts
Edward Ward 7th Baron Dudley and 2nd Baron Ward leased for 99 years real property in trust for himself for his life, then in trust to pay out of the rents, issues, and profits as annuities for his grandchildren (Edward Ward (the plaintive's father), son and heir of William Ward, eldest son of the 7th Baron Dudley; and William Ward, son of Ferdinando Dudley Ward second son of the seventh Baron Dudley); and to the grandchildren to 7th Baron Dudley's brother, William Ward, (Frances Porter and Catherine Porter). The remainder of the lease was in trust to the 7th Baron Dudley and heirs of his body male. The annuities arose on the death of the 7th Baron Dudley.
The seventh Baron Dudley died on 28 June 1701. Edward Ward a minor, (the plaintive's father) succeeded as the 8th Baron Dudley and 3rd Baron Ward, since his father predeceased the 7th Baron Dudley and received his annuity and the remainder of the lease in trust. The 8th Baron Dudley married Diana Howard, the defendant. The 8th Baron Dudley died on 20 March 1704 while his wife, Lady Diana was pregnant. On 16 June 1704 Lady Diana gave birth to Edward Ward, 9th Baron Dudley and fourth Baron Ward, the plaintive. Lady Diana brought a Writ of Dower at law that was granted but stayed enforcement because of the lease. This bill was filed by the Honorable Thomas Newport on behalf of the 9th Baron Dudley for administration the will of his father and great-grandfather. Lady Diana filed a cross bill demanding one third of the surplus of the lease after the payment of the annuities as her dower.
Holding
"[T]he right of a dowress to her dower is not only a legal right, so adjudged at law, but is also a moral right, to be provided for, and to have a maintenance and sustenance out of her husband's estate to live upon; she is therefore in the care of the law, and a favourite of the law; and upon this moral law is the law of England founded, as to the right of dower."
"[A] marriage is as much a contract (and I am sure more sacred) and ought to be as much regarded and relieved, as a defective jointure."
The lady dowager has as her dower the benefit of this trust term, and that the trustees do account to her for the third part of the clear profits above the charge of any yearly annuities, from the death of her husband and from time to time for the future during the term, and the term to stand charged therewith during her life.
"[F]or what are the profits, but the lands, or what is the land, but the profits?"
Nature of Equity
"Equity is no part of the law, but a moral virtue, which qualifies, moderates, and reforms the rigour, hardness and edge of the law, and is a universal truth. It does also assist the law, where it is defective and weak in the constitution (which is the life of the law), and defends the law from crafty evasions, delusions and mere subtleties, invented and contrived to evade and elude the common law, whereby such as have undoubted right are made remediless. And thus is the office of equity to protect and support the common law from shifts and contrivances against the justice of the law. Equity, therefore, does not destroy the law, nor create it, but assists it. "
References
External links
Court of Chancery cases
English property case law
English trusts case law
1705 in law
1700s in case law
1700s in British law
1705 in England
Equity (law)
|
Wuttagoonaspis is a extinct genus of primitive arthrodire placoderm fish from the Middle Devonian of Australia. The box-like skull is up to 18 centimeters in length, and the median dorsal plate averages in length about 10 centimeters. It contains two species: the type species Wuttagoonaspis fletcheri, described by Ritchie in 1973, and Wuttagoonaspis milligani, described by Young and Goujet in 2003.
Classification
Wuttagoonaspis belongs to the family Wuttagoonaspidae, and is closely related to Yiminaspis. It is one of the more basal members of the order Arthrodira, as shown in the cladogram below:
References
Placoderms of Australia
Wuttagoonaspidae
|
```xml
import Disclosure from './Disclosure';
export type { DisclosureProps } from './Disclosure';
export default Disclosure;
```
|
Granges-le-Bourg () is a commune in the Haute-Saône department in the region of Bourgogne-Franche-Comté in eastern France.
Population
See also
Communes of the Haute-Saône department
References
Communes of Haute-Saône
|
```groff
.\" Generated by Mmark Markdown Processer - mmark.miek.nl
.TH "COREDNS-CANCEL" 7 "March 2021" "CoreDNS" "CoreDNS Plugins"
.SH "NAME"
.PP
\fIcancel\fP - cancels a request's context after 5001 milliseconds.
.SH "DESCRIPTION"
.PP
The \fIcancel\fP plugin creates a canceling context for each request. It adds a timeout that gets
triggered after 5001 milliseconds.
.PP
The 5001 number was chosen because the default timeout for DNS clients is 5 seconds, after that they
give up.
.PP
A plugin interested in the cancellation status should call \fB\fCplugin.Done()\fR on the context. If the
context was canceled due to a timeout the plugin should not write anything back to the client and
return a value indicating CoreDNS should not either; a zero return value should suffice for that.
.SH "SYNTAX"
.PP
.RS
.nf
cancel [TIMEOUT]
.fi
.RE
.IP \(bu 4
\fBTIMEOUT\fP allows setting a custom timeout. The default timeout is 5001 milliseconds (\fB\fC5001 ms\fR)
.SH "EXAMPLES"
.PP
.RS
.nf
example.org {
cancel
whoami
}
.fi
.RE
.PP
Or with a custom timeout:
.PP
.RS
.nf
example.org {
cancel 1s
whoami
}
.fi
.RE
.SH "SEE ALSO"
.PP
The Go documentation for the context package.
```
|
Arpeggi may refer to:
the original name of the song "Weird Fishes/Arpeggi", by Radiohead
Arpeggi, Inc., a bioinformatics startup company acquired by Gene by Gene in 2013
the plural of arpeggio
|
```sqlpl
update ACT_GE_PROPERTY set VALUE_ = '6.1.1.0' where NAME_ = 'schema.version';
alter table ACT_RU_JOB add column CREATE_TIME_ timestamp;
alter table ACT_RU_TIMER_JOB add column CREATE_TIME_ timestamp;
alter table ACT_RU_SUSPENDED_JOB add column CREATE_TIME_ timestamp;
alter table ACT_RU_DEADLETTER_JOB add column CREATE_TIME_ timestamp;
update ACT_RU_JOB set CREATE_TIME_=CURRENT_TIMESTAMP;
update ACT_RU_TIMER_JOB set CREATE_TIME_=CURRENT_TIMESTAMP;
update ACT_RU_SUSPENDED_JOB set CREATE_TIME_=CURRENT_TIMESTAMP;
update ACT_RU_DEADLETTER_JOB set CREATE_TIME_=CURRENT_TIMESTAMP;
```
|
```javascript
/**
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var floor = require( '@stdlib/math/base/special/floor' );
var Float64Array = require( '@stdlib/array/float64' );
var dcopy = require( '@stdlib/blas/base/dcopy' );
var pkg = require( './../package.json' ).name;
var dsort2sh = require( './../lib/dsort2sh.js' );
// FUNCTIONS //
/**
* Create a benchmark function.
*
* @private
* @param {PositiveInteger} iter - number of iterations
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( iter, len ) {
var tmp;
var out;
var x;
var i;
var j;
x = [];
for ( i = 0; i < iter; i++ ) {
tmp = new Float64Array( len );
for ( j = 0; j < len; j++ ) {
tmp[ j ] = iter - j - randu();
}
x.push( tmp );
}
out = new Float64Array( len );
return benchmark;
function benchmark( b ) {
var xc;
var y;
var i;
xc = x.slice();
for ( i = 0; i < iter; i++ ) {
xc[ i ] = dcopy( len, x[ i ], 1, new Float64Array( len ), 1 );
}
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = dsort2sh( len, 1, xc[ i ], 1, out, 1 );
if ( isnan( y[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y[ i%len ] ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
function main() {
var opts;
var iter;
var len;
var min;
var max;
var f;
var i;
iter = 1e6;
min = 1; // 10^min
max = 4; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( iter, len );
opts = {
'iterations': iter
};
bench( pkg+'::reverse_sorted,random:len='+len, opts, f );
iter = floor( pow( iter, 3.0/4.0 ) );
}
}
main();
```
|
```go
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
// Package windows contains an interface to the low-level operating system
// primitives. OS details vary depending on the underlying system, and
// by default, godoc will display the OS-specific documentation for the current
// system. If you want godoc to display syscall documentation for another
// system, set $GOOS and $GOARCH to the desired system. For example, if
// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
// to freebsd and $GOARCH to arm.
//
// The primary use of this package is inside other packages that provide a more
// portable interface to the system, such as "os", "time" and "net". Use
// those packages rather than this one if you can.
//
// For details of the functions and data types in this package consult
// the manuals for the appropriate operating system.
//
// These calls return err == nil to indicate success; otherwise
// err represents an operating system error describing the failure and
// holds a value of type syscall.Errno.
package windows // import "golang.org/x/sys/windows"
import (
"syscall"
)
// ByteSliceFromString returns a NUL-terminated slice of bytes
// containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, syscall.EINVAL).
func ByteSliceFromString(s string) ([]byte, error) {
for i := 0; i < len(s); i++ {
if s[i] == 0 {
return nil, syscall.EINVAL
}
}
a := make([]byte, len(s)+1)
copy(a, s)
return a, nil
}
// BytePtrFromString returns a pointer to a NUL-terminated array of
// bytes containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, syscall.EINVAL).
func BytePtrFromString(s string) (*byte, error) {
a, err := ByteSliceFromString(s)
if err != nil {
return nil, err
}
return &a[0], nil
}
// Single-word zero for use when we need a valid pointer to 0 bytes.
// See mksyscall.pl.
var _zero uintptr
func (ts *Timespec) Unix() (sec int64, nsec int64) {
return int64(ts.Sec), int64(ts.Nsec)
}
func (tv *Timeval) Unix() (sec int64, nsec int64) {
return int64(tv.Sec), int64(tv.Usec) * 1000
}
func (ts *Timespec) Nano() int64 {
return int64(ts.Sec)*1e9 + int64(ts.Nsec)
}
func (tv *Timeval) Nano() int64 {
return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
}
```
|
The 2007 NCAA Division II football rankings are from the American Football Coaches Association (AFCA). This is for the 2007 season.
Legend
American Football Coaches Association poll
Notes
References
Rankings
NCAA Division II football rankings
|
Armillaria pallidula is a species of mushroom in the family Physalacriaceae. This species is found in Australia.
See also
List of Armillaria species
References
pallidula
Fungal tree pathogens and diseases
Fungi of Australia
Fungi described in 1988
Taxa named by Roy Watling
|
```scala
package chipyard.harness
import chisel3._
import scala.collection.mutable.{ArrayBuffer, LinkedHashMap}
import freechips.rocketchip.diplomacy.{LazyModule}
import org.chipsalliance.cde.config.{Field, Parameters}
import freechips.rocketchip.util.{ResetCatchAndSync}
import freechips.rocketchip.prci.{ClockBundle, ClockBundleParameters, ClockSinkParameters, ClockParameters}
import chipyard.harness.{ApplyHarnessBinders, HarnessBinders}
import chipyard.clocking.{SimplePllConfiguration, ClockDividerN}
import chipyard.{ChipTop}
// -------------------------------
// Chipyard Test Harness
// -------------------------------
class TestHarness(implicit val p: Parameters) extends Module with HasHarnessInstantiators {
val io = IO(new Bundle {
val success = Output(Bool())
})
val success = WireInit(false.B)
io.success := success
override val supportsMultiChip = true
// By default, the chipyard makefile sets the TestHarness implicit clock to be 1GHz
// This clock shouldn't be used by this TestHarness however, as most users
// will use the AbsoluteFreqHarnessClockInstantiator, which generates clocks
// in verilog blackboxes
def referenceClockFreqMHz = 1000.0
def referenceClock = clock
def referenceReset = reset
val lazyDuts = instantiateChipTops()
}
```
|
Drillia angolensis is a species of sea snail, a marine gastropod mollusk in the family Drilliidae.
Description
The size of an adult shell varies between 15 mm and 26 mm.
Distribution
This species occurs in the demersal zone of the Atlantic Ocean off Angola, found at a depth of 72 m.
References
Gofas, S.; Afonso, J.P.; Brandào, M. (Ed.). (S.a.). Conchas e Moluscos de Angola = Coquillages et Mollusques d'Angola. [Shells and molluscs of Angola]. Universidade Agostinho / Elf Aquitaine Angola: Angola. 140 pp
Tucker, J.K. 2004 Catalog of recent and fossil turrids (Mollusca: Gastropoda). Zootaxa 682:1–1295
External links
Endemic fauna of Angola
angolensis
Gastropods described in 1923
|
A virtual telecine is a piece of video equipment that can play back data files in real time. The colorist-video operator controls the virtual telecine like a normal telecine, although without controls like focus and framing. The data files can be from a Spirit DataCine, motion picture film scanner (like a Cineon), CGI animation computer, or an Acquisition professional video camera. The normal input data file standard is DPX. The output of data files are often used in digital intermediate post-production using a film recorder for film-out. The control room for the virtual telecine is called the color suite.
The 2000 movie O Brother, Where Art Thou? was scanned with Spirit DataCine, color corrected with a VDC-2000 and a Pandora Int. Pogle Color Corrector with MegaDEF. A Kodak Lightning II film recorder was used to output the data back on to film.
Virtual telecines are also used in film restoration.
Another advantage of a virtual telecine is once the film is on the storage array the frames may be played over and over again without damage or dirt to the film. This would be the case for outputting to different TV standards (NTSC or PAL) or formats: (pan and scan, letterboxed, or other aspect ratio. Restoration, special effect, color grading, and other changes can be applied to the data file frames before playout.
Virtual telecine is like a "tape to tape" color correction process, but with the difference of: higher resolution (2k or 4k) and the use of film restoration tools with standards-aspect ratio tools.
2k virtual DataCine products
First virtual telecine by Philips, now Grass Valley a Thomson SA Brand:
VDC-2000 Virtual DataCine
Specter FS Virtual DataCine
These are able to play out 2k data files in non-linear real time. Size, rotation and color correction-color grading are all able to be done in real time controlled by a telecine color corrector. A Silicon Graphics-SGI computer, an Origin 2000, is used to play the data files to "Spirit DataCine hardware". The Virtual DataCine can output SDTV (NTSC or PAL) and HDTV-high definition or Data files DPX (or TIF), the same as the Datacine. First generation input/output interface for data files as the optical fiber HIPPI cables (up to 6 frame/s at 2k), the next generation interface is GSN-Gigabit Ethernet fibre Optic (up to 30 frame/s at 2k). GSN is also called HIPPI-6400 and was later renamed GSN (for Gigabyte System Network). The SAN hard disk are interfaces to the Virtual DataCine by dual FC-Fibre Channel, cables.
Real time 2k Color Correction is done by a Pandora International's Pogle with a MegaDEF. Input and output 3D LUT-Look up tables are also used to control the look and standard of the clips.
On a Spirit Datacine Phantom TransferEngine software running on an SGI computer or Bones Linux-based software is used to record the DPX files from the Spirit DataCine. These files are stored in the virtual telecine or on a SAN hard disk storage array.
The end product was accomplished by playing the DPX files back through the Spirit Datacine's process electronics and a Pandora International's MegaDef Colour Correction system.
VDC-2000 Specter and Specter FS are made in Weiterstadt-Darmstadt Germany by Grass Valley - a Thomson SA brand, former names see Philips Broadcast and Robert Bosch GmbH, Fernseh Division.
Real-time virtual telecines
HDTV 4:2:2 and better 4:4:4 RGB can be used as a Virtual Telecine. In this case, standard HDTV video products can be used in a post-production work flow.
As faster computers and SAN-Storage area network came on the market, more Real time 2k Virtual Telecine came on to the market. SDTV is easier to output in real time than HDTV or 2k or 4k display resolution files.
Limitation to speed are: color correction, resizing aspect ratio, dirt removal, special effects, motion picture credits, and other restoration. Also bandwidth speed of the hardware limits real time playout: CPU, interface, SAN, memory, software and hardware.
Some Current virtual telecines are:
Da Vinci Systems Splice
Bones by DFT Digital Film Technology in Weiterstadt, Germany.
Filmlight Baselight
Marquise Technologies MIST prime and MIST i/o
SpectSoft RaveHD and Rave2K
DFT Flexxity
Non-real-time virtual telecines
A number of products are on the market that can output frames in less than real time. These can be used to output DPX data file, but are too slow for HDTV. For some digital intermediate work 4k data is needed. These large 4k display resolution files cannot be transferred in real time.
See also
Digital cinematography
Telecine
Direct to Disk Recording
Hard disk recorder
Lustre (file system)
Fernseh
External links
A Brief History for Colorists, History of Telecines
Photo of a VDC Specter in three 19 inch rackes
theasc.com, © 2003 American Cinematographer, DI by Debra Kaufman
American Cinematographer A flex Finish
Thomson Grassvalley Home Page
Ascent Media's Virtual Telecine
- Pogle
Pandora International Home Page
Marquise Technologies Home Page
Grande Vitesse Systems Home Page
theasc.com, © 2003 American Cinematographer, DI by Debra Kaufman
American Cinematographer A flex Finish
kodak.com "Restoration of an impeccably preserved old negative"
Digital Content Producer, NAB 20000: Choose Your Weapons, March 1, 2000, By Dan Ochiva, Michael Goldman, Barry Braverman, Audrey Doyle, Philip De Lancie, Matt Cheplic, and Pete
Film production
Television technology
Video hardware
|
```javascript
/**
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
'use strict';
// MODULES //
var addon = require( './../src/addon.node' );
// MAIN //
/**
* Evaluates the beta function.
*
* @private
* @param {NonNegativeNumber} a - input value
* @param {NonNegativeNumber} b - input value
* @returns {number} evaluated beta function
*
* @example
* var v = beta( 0.0, 0.5 );
* // returns Infinity
*
* @example
* var v = beta( 1.0, 1.0 );
* // returns 1.0
*
* @example
* var v = beta( -1.0, 2.0 );
* // returns NaN
*
* @example
* var v = beta( 5.0, 0.2 );
* // returns ~3.382
*
* @example
* var v = beta( 4.0, 1.0 );
* // returns 0.25
*
* @example
* var v = beta( NaN, 2.0 );
* // returns NaN
*/
function beta( a, b ) {
return addon( a, b );
}
// EXPORTS //
module.exports = beta;
```
|
```c++
/*
* PROGRAM: Client/Server Common Code
* MODULE: fbsyslog.h
* DESCRIPTION: System log facility (win32)
*
* The contents of this file are subject to the Interbase Public
*
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
*
* Created by: Alex Peshkov <peshkoff@mail.ru>
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#include "firebird.h"
#include "../common/os/fbsyslog.h"
#include "../common/classes/init.h"
#include <Windows.h>
namespace {
typedef HANDLE WINAPI tRegisterEventSource(LPCTSTR lpUNCServerName, LPCTSTR lpSourceName);
typedef BOOL WINAPI tReportEvent(
HANDLE hEventLog,
WORD wType,
WORD wCategory,
DWORD dwEventID,
PSID lpUserSid,
WORD wNumStrings,
DWORD dwDataSize,
LPCTSTR *lpStrings,
LPVOID lpRawData);
class SyslogAccess
{
private:
CRITICAL_SECTION cs;
HANDLE LogHandle;
tReportEvent *fReportEvent;
bool InitFlag;
public:
explicit SyslogAccess(Firebird::MemoryPool&)
{
InitializeCriticalSection(&cs);
InitFlag = false;
LogHandle = 0;
}
~SyslogAccess()
{
DeleteCriticalSection(&cs);
}
void Record(WORD wType, const char* msg);
};
void SyslogAccess::Record(WORD wType, const char* msg)
{
EnterCriticalSection(&cs);
if (! InitFlag) {
InitFlag = true;
HINSTANCE hLib = LoadLibrary("Advapi32");
tRegisterEventSource *fRegisterEventSource = hLib ?
(tRegisterEventSource *) GetProcAddress(hLib, "RegisterEventSourceA") : 0;
fReportEvent = hLib ?
(tReportEvent *) GetProcAddress(hLib, "ReportEventA") : 0;
LogHandle = fRegisterEventSource && fReportEvent ?
fRegisterEventSource(0, "Firebird SQL Server") : 0;
}
bool use9x = true;
if (LogHandle) {
LPCTSTR sb[1];
sb[0] = msg;
if (fReportEvent(LogHandle, wType, 0, 0, 0, 1, 0, sb, 0)) {
use9x = false;
}
}
if (use9x) {
::MessageBox(0, msg, "Firebird Error", MB_ICONSTOP);
}
LeaveCriticalSection(&cs);
}
Firebird::InitInstance<SyslogAccess> iSyslogAccess;
} // namespace
namespace Firebird {
void Syslog::Record(Severity level, const char* msg)
{
WORD wType = EVENTLOG_ERROR_TYPE;
switch (level)
{
case Warning:
wType = EVENTLOG_INFORMATION_TYPE;
break;
case Error:
default:
wType = EVENTLOG_ERROR_TYPE;
break;
}
iSyslogAccess().Record(wType, msg);
}
} // namespace Firebird
```
|
Bone Cruncher is a puzzle video game for the Acorn Electron, BBC Micro, and Commodore 64 first published by Superior Software in 1987. It uses the "rocks and diamonds" mechanics of Boulder Dash. An Amiga version was released in 1988.
Gameplay
The player controls a dragon called Bono, who operates a soap business. He collects bones from around the chambers of his castle and uses them to make soap in a cauldron. He then delivers the soap to sea-monsters, situated at various exits from the castle.
The game uses the gameplay mechanics popularised in Boulder Dash and Superior's own Repton series. The player can dig through earth and push boulders but where boulders will fall from above if area below them is cleared. The main difference in this game is that, although the characters are depicted in side profile, the camera is meant to be overhead so objects are not subject to gravity in the same way. The 'boulders' are living creatures known as Glooks and rather than just heading down the screen, they will head in the direction of a bathing sea-monster. As such, they change direction during play which changes the layout of the maze. This means the player must decide the order that the soap is delivered. Glooks are generally harmless but can crush the player when they move.
There are two other deadly creatures in the castle: monsters and spiders. Monsters can be trapped by pushing Glooks onto them. If they can't move, they turn to skeletons which Bono can collect to make soap. They can also be lured into trapdoors but then their bones are lost. Spiders, as well as being deadly to Bono, eat skeletons.
Another character in the game is Bono's assistant Fozzy who can be used to hold back monsters or spiders but can become trapped. There are also keys and doors and on each level a hidden 'volcano' that will spew out Glooks if walked over.
It takes five skeletons to make a bar of soap and five bars of soap must be created, and delivered to the sea-monsters, in each chamber. There are 22 chambers in the castle.
Development and release
The game was designed by German programmer Andreas Kemnitz, originally for the Commodore 64. He submitted the game to Superior Software, who had recently published the similar Repton 3 on the C64. Superior commissioned conversions to the BBC Micro and Acorn Electron, machines on which they were market leaders, and also Amiga. All versions of the game are almost identical, with no real changes for the 16-bit Amiga version. The game was launched before Christmas 1987 with all four versions being advertised but the Amiga version was delayed, finally getting released in Spring 1988.
Reception
The game received mostly positive reviews but there was a mixed response. ACE gave the C64 version a score of 943 (out of 1000) and the Amiga version 948. Electron User gave an overall score of 9/10, particularly praising the humour of the game and the "beautifully animated" sprites.
The Games Machine also picked out the character animation for praise in their review of the BBC Micro and C64 versions and while generally positive, awarding a score of 70%, the review questions the relevance of this type of game; "Bone Cruncher is an old-style game and its general aim is a little tired by today's standards. However, it is cleverly designed, presents sufficient challenge for worthy gameplay and the creatures' representation adds considerable charm". When reviewing the Amiga version, they gave a lower score of 61% as while conceding it "plays just as well as the 8-bit game", the fact that "it lacks any attempt at improvement" on a much more capable machine was considered a mistake.
Zzap!64 were less impressed, giving a score of 56% and concluding that the game is a "polished, but merely average addition to an already jaded format". Computer and Video Games, reviewing the C64 version, went further, saying the game is "antiquated" and "a load of dross", awarding only 5/10 for playability and 4/10 for sound, graphics and value.
Legacy
The BBC and Electron versions were included on the Play It Again Sam 7 compilation in 1989 and reissued as part of the Superior/Blue Ribbon budget series in 1990.
References
External links
Bone Cruncher at the Amiga Hall of Light
1987 video games
Amiga games
BBC Micro and Acorn Electron games
Commodore 64 games
Europe-exclusive video games
Rocks-and-diamonds games
Superior Software games
Video games developed in Germany
Single-player video games
|
```python
import logging
from datetime import datetime
from typing import List
from uuid import UUID
import pymongo
from passlib.hash import pbkdf2_sha512
from pydantic import BaseModel, validator
from api.server.db import IDBaseModel
from api.server.db.mongo import mongo
logger = logging.getLogger("API")
class EditUser(BaseModel):
username: str = ""
new_username: str = ""
old_password: str = ""
new_password: str = ""
active: bool = True
roles: List[UUID] = []
class EditPersonalUser(BaseModel):
new_username: str = ""
old_password: str = ""
new_password: str = ""
class UserModel(IDBaseModel):
id_: UUID = None
hashed: bool = False
username: str
password: str = None
roles: List[UUID]
active: bool = True
last_login_at: datetime = None
current_login_at: datetime = None
last_login_ip: str = None
current_login_ip: str = None
login_count: int = 0
_name_field = "username"
@validator('password')
def hash_pass(cls, password, values):
if not values:
return password
if values.get("hashed") and not password:
return password
if values.get("hashed") and not password.startswith("$pbkdf2-sha512$25000$"):
raise ValueError("Hashed password not in expected format.")
elif not values.get("hashed") and password.startswith("$pbkdf2-sha512$25000$"):
raise ValueError("Got a hashed password but hashed flag was unset.")
elif not values.get("hashed"):
values["hashed"] = True
r = pbkdf2_sha512.hash(password)
return r
else:
return password
@validator('roles', whole=True)
def verify_roles_exist(cls, roles):
roles_col: pymongo.collection.Collection = mongo.reg_client.walkoff_db.roles
for role in roles:
if not roles_col.find_one({"id_": role}):
raise ValueError(f"Role {role} does not exist.")
return roles
async def verify_password(self, password_attempt: str):
"""Verifies that the input password matches with the stored password.
Args:
password_attempt(str): The input password.
Returns:
(bool): True if the passwords match, False if not.
"""
return pbkdf2_sha512.verify(password_attempt, self.password)
async def hash_and_set_password(self, password: str):
"""Verifies that the input password matches with the stored password.
Args:
password_attempt(str): The input password.
Returns:
(bool): True if the passwords match, False if not.
"""
self.password = pbkdf2_sha512.hash(password)
# async def set_roles(self, new_roles, role_col):
# """Sets the roles for a User.
#
# Args:
# new_roles (list[int]|set(int)): A list of Role IDs for the User.
# """
#
# new_role_ids = set(new_roles)
#
# ret = []
# for id_ in new_role_ids:
# new_roles.append(await role_col.find_one({"id_": id_}, projection={'_id': False}))
#
# self.roles[:] = ret
#
# roles_not_added = new_role_ids - {role.id_ for role in new_roles}
# if roles_not_added:
# logger.warning(f"Cannot add roles {roles_not_added} to user {self.id_}. Roles do not exist")
async def login(self, ip_address):
"""Tracks login information for the User upon logging in.
Args:
ip_address (str): The IP address from which the User logged in.
"""
self.last_login_at = self.current_login_at
self.current_login_at = datetime.utcnow()
self.last_login_ip = self.current_login_ip
self.current_login_ip = ip_address
self.login_count += 1
async def logout(self):
"""Tracks login/logout information for the User upon logging out"""
if self.login_count > 0:
self.login_count -= 1
else:
logger.warning(f"User {self.id_} logged out, but login count was already at 0")
# async def has_role(self, role):
# """Checks if a User has a Role associated with it.
#
# Args:
# role (int): The ID of the Role.
#
# Returns:
# (bool): True if the User has the Role, False otherwise.
# """
# return role in [role.id_ for role in self.roles]
#
```
|
```javascript
import Icon from '../components/Icon.vue'
Icon.register({
horse: {
width: 576,
height: 512,
paths: [
{
d: 'M575.9 76.6l0.1 77.7c0 0 0 0 0 0 0 13.5-8.3 25-20.1 29.7l-32.6 13c-15.4 6.2-33-0.5-40.5-15.4l-18.9-37.7-16-7.1v102.5c0 0.2 0.1 0.4 0.1 0.6 0 30.5-12.3 58-32 78.2v177.8c0 8.8-7.2 16-16 16h-64c-8.8 0-16-7.2-16-16v-150.4l-134-22.3-23.8 63.6 26.3 105.3c2.5 10.1-5.1 19.9-15.5 19.9h-66c-7.5 0-13.8-5.2-15.5-12.1l-24.8-99.4c-1.2-5-1.9-10.2-1.9-15.6 0-7.9 1.4-15.5 4.1-22.4l25.7-68.6c-18.7-17.5-30.5-42.2-30.5-69.9 0-2.6 0.6-5.1 0.8-7.7-9.9 7.3-16.8 18.5-16.8 31.7v56c0 8.8-7.2 16-16 16h-16c-8.8 0-16-7.2-16-16v-56c0-48.5 39.5-88 88-88v1.1c17.6-20.1 43.2-33.1 72-33.1h159.9c0-70.7 57.3-128 128-128h120c5.1 0 8.9 4.7 7.9 9.6-2.7 13.2-11.1 23.8-22.2 30.7 5.1 5.4 9.9 10.5 13.7 14.5 5.6 5.9 8.6 13.7 8.6 21.8zM511.9 96c8.8 0 16-7.2 16-16s-7.2-16-16-16-16 7.2-16 16 7.2 16 16 16z'
}
]
}
})
```
|
```yaml
# Each section from every release note are combined when the
# CHANGELOG.rst is rendered. So the text needs to be worded so that
# it does not depend on any information only available in another
# section. This may mean repeating some details, but each section
# must be readable independently of the other.
#
# Each section note must be formatted as reStructuredText.
---
features:
- |
The bpf syscall is now monitored by CWS; rules can be written on BPF commands.
```
|
That Malicious Age (Italian: Quella età maliziosa) is a 1975 Italian erotic drama film co-written and directed by Silvio Amadio. It features Nino Castelnuovo and Gloria Guida.
Plot
Napoleone (Castelnuovo) is an artist bored of his married life and applies to work as a gardener at a summer mansion. On his way to Elba, he meets an attractive teenage girl (Guida) who attempts to seduce him and when he gets to the mansion, he learns that she is Paola, his employers' daughter living with her mother (Anita Sanders) and stepfather (Silvio Amadio). The mother is soon attracted to Napoleone but he has a growing affection for Paola, fuelled by her flirtatious behavior and his passion eventually turns into violence against a mentally disturbed fisherman (Mimmo Palmara) courting Paola.
Cast
Gloria Guida as Paola
Nino Castelnuovo as Napoleone
Anita Sanders as Paola's mother
Mimmo Palmara as Fisher
Andrea Aureli as Adolfo, the writer
Fabio Garriba
Critical reception
The film was generally badly received by critics. Italian critic Paolo Mereghetti described the film as "unresolved", noting the ambitious efforts to combine melodramatic tension, psychological introspection and class morality but concluding that these aspirations ended up getting lost in long sequences of silences and panoramic views. The review of the website LogTake pointed out the unconvincing "awkward juxtaposition (rather than contamination) of genres" of the film, which starts as a commedia erotica abruptly turning to drama, and refers to the film as "uncertain, confused, approximate, annoyingly misogynistic".
References
External links
That Malicious Age at OFDb.de
1975 romantic drama films
1975 films
Films directed by Silvio Amadio
Films set in the Mediterranean Sea
Films set in Tuscany
Films set on islands
Italian coming-of-age drama films
Italian romantic drama films
1970s Italian-language films
1970s coming-of-age drama films
Films scored by Roberto Pregadio
1970s Italian films
|
The Eyes of Mystery is a lost 1918 American silent mystery film directed by Tod Browning starring Edith Storey.
Plot
As described in a film magazine, Carma Carmichael (Storey), who lives with her uncle Quincy Carmichael (Andrews), is kidnapped by her father and held for ransom. In order to trap the criminals and secure Jack Carrington (Barker) as Carma's husband, Quincy fakes his death and makes Jack his heir. Carma is angered by her uncle's action is determined to take her rightful place. By going through some of her uncle's papers, she discovers that the man she believes to be her father is an impostor and that her father is dead. Carma's supposed father and a group of moonshiners attack the Carmichael home and are fought off by Carma, Jack, and a friend. Quincy, believing it is time to return to life, does so in time to get the sheriff's posse on the house grounds, drive off the moonshiners, and capture the crooks.
Cast
Edith Storey as Carma Carmichael
Bradley Barker as Jack Carrington
Harry Northrup as Roger Carmichael (credited as Harry S. Northrup)
Frank Andrews as Quincy Carmichael
Kempton Greene as Steve Graham
Frank Bennett as Seth Megget (credited as Frank Fisher Bennett)
Louis Wolheim as Brad Tilton (credited as Louis R. Wolheim)
Anthony Byrd as Uncle George
Pauline Dempsey as Aunt Liza
Monte Blue *uncredited role
Reception
Like many American films of the time, The Eyes of Mystery was subject to cuts by city and state film censorship boards. For example, the Chicago Board of Censors required a cut, in Reel 1, of slugging a man, Reel 4, the vision of shooting Carma's father, Reel 5, five views of moonshiners shooting at house, Carma shooting man in white and shooting man out of tree, throwing man over porch, two scenes of breaking door with ax, closeup of shooting where Carma is used as a shield, overseer shooting Carma's father and he shooting overseer.
References
External links
1918 films
American silent feature films
American black-and-white films
Films directed by Tod Browning
Lost American mystery films
1918 mystery films
1918 lost films
1910s American films
Silent American mystery films
|
Baby Life is a simulation for the Nintendo DS by French studio Pasta Games. The gameplay of the game is somewhat similar with the Tamagotchi games but more complex.
Development
The game was published by Deep Silver, the games label of digital entertainment company Koch Media, and French publisher Game Life. Game Life had previously released the title Horse Life which had demonstrated the concept. The game was a Nintendo DS exclusive that was released at the end of 2008. Koch Media owned the publishing rights for all PAL regions. The game was previewed at the Games Convention 2008 alongside Horse Life 2.
Gameplay
In the game, players take control of their personal babies. from age 9 to 15 months. They teach the baby speech, movement, and behaviour. Over 100 clothing items can be accessed, either to use or to trade over Wi-Fi. The game utilises NDS features such as the speech system and the stylus. Emmanuel Drouin, managing director of Game Life, said that the game allows players to interact with the "most lovely hero you can have in a videogame: a baby".
Critical reception
Softpedia described the gameplay as "clearly more complex and probably even more fun" than a Tamagotchi. Pocket Gamer jokingly argued that the game is an alternative to those who want a baby but who are unwilling or unable to attract a member of the opposite sex.
References
External links
GameSpot Summary
2008 video games
Europe-exclusive video games
Life simulation games
Nintendo DS games
Nintendo DS-only games
Video games developed in France
Virtual baby video games
Deep Silver games
Single-player video games
|
```c
/**
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "stdlib/blas/ext/base/dcusumors.h"
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
int main( void ) {
// Create strided arrays:
const double x[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 };
double y[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
// Specify the number of elements:
const int64_t N = 4;
// Specify stride lengths:
const int64_t strideX = 2;
const int64_t strideY = -2;
// Compute the cumulative sum:
stdlib_strided_dcusumors( N, 0.0, x, strideX, y, strideY );
// Print the result:
for ( int64_t i = 0; i < 8; i++ ) {
printf( "y[ %"PRId64" ] = %lf\n", i, y[ i ] );
}
}
```
|
The South Pars/North Dome field is a natural-gas condensate field located in the Persian Gulf. It is by far the world's largest natural gas field, with ownership of the field shared between Iran and Qatar. According to the International Energy Agency (IEA), the field holds an estimated of in-situ natural gas and some of natural gas condensates. On the list of natural gas fields it has almost as much recoverable reserves as all the other fields combined. It has significant geostrategic influence.
This gas field covers an area of , of which (South Pars) is in Iranian territorial waters and (North Dome) is in Qatari territorial waters.
Field geology
The field is below the seabed at a water depth of , and consists of two independent gas-bearing formations: Kangan (Triassic) and Upper Dalan (Permian). Each formation is divided into two different reservoir layers, separated by impermeable barriers. The field consists of four independent reservoir layers K1, K2, K3, and K4.
The K1 and K3 units are mainly composed of dolomites and anhydrites, while K2 and K4, which constitute major gas reservoirs, comprise limestone and dolomite. A massive anhydrite (the Nar member) separates the K4 from the underlying K5 unit which has poor reservoir qualities. The gross pay zone in the South Pars field is approximately 450 m thick, extending from depths of approximately 2750 to 3200 m. Reservoir strata dip gently to the NE. The average thickness of the reservoir units declines from South Pars (some ) to North field (). As in other reservoir structures in neighboring areas, the reservoir in the Qatar Arch is cut by a set of NNW-SSE trending faults. Diagenesis has a major effect on reservoir quality of the field.
The field is a part of the N-trending Qatar Arch structural feature that is bounded by the Zagros fold and thrust belt to the north and northeast.
In the field, gas accumulation is mostly limited to the Permian–Triassic stratigraphic units. These units known as the Kangan–Dalan Formations constitute very extensive natural gas reservoirs in the field and Persian Gulf area, which composed of carbonate–evaporite series also known as the Khuff Formation.
Permian–Early Triassic has been divided into Faraghan (Early Permian), Dalan (Late Permian) and Kangan (Early Triassic) Formations.
Reserves
According to International Energy Agency (IEA), the combined structure is the world's largest gas field.
In-place volumes are estimated to be around gas in place and some of natural gas condensate in place. With in place volumes equivalent to of oil (310 billion boe of gas and 50 billion boe of natural gas condensate) the field is the world's biggest conventional hydrocarbon accumulation.
The field recoverable gas reserve is equivalent to some of oil and it also holds about of recoverable condensate corresponding of about of oil equivalent recoverable hydrocarbons.
The gas recovery factor of the field is about 70%, corresponding of about of total recoverable gas reserves which stands for about 19% of world recoverable gas reserves.
The estimates for the Iranian section are of natural gas in place and around of recoverable gas which stands for 36% of Iran's total proven gas reserves and 5.6% of the world's proven gas reserves.
The estimates for the Qatari section are of recoverable gas which stands for almost 99% of Qatar's total proven gas reserves and 14% of the world's proven gas reserves.
Table 1 - South Pars/North Field gas reserves
Note: 1 km³ = 1,000,000,000 m³ = 1 Billion m³ = 1 Trillion Liters
However, since the field is a common field and the reservoir is highly homogenous, the ultimate recoverable reserves of each country may vary from this technical assessment which only considers the static data and does not include rate of gas migration. So, it is better to say that the ultimate recoverable reserves of each country would be a factor of cumulative gas production by each of them.
The Iranian section also holds of condensate in place of which some are believed to be recoverable, while Qatari section believed to contains some of condensate in place and at least some of recoverable condensate.
The field is rich in liquids and yields approximately of condensate per of gas. It has also very high level of well productivity which in average stands for per day per well, while the average natural gas well productivity in Iran is 1.5 million cubic meters per day per well.
Reserve uncertainties
In 2005, QatarEnergy became worried the North Dome's reserves were being developed too quickly, which could reduce reservoir pressure and possibly damage its long-term production potential. In early 2005, the government placed a moratorium on additional development projects at the North Dome pending a study of the field's reservoirs. This assessment is not expected to end until after 2009, meaning new projects are unlikely to be signed before 2010. However, this did not affect projects approved or underway before the moratorium.
The 2005 moratorium by Qatar and the subsequent extension of that raised some questions about the actual proven reserves in Qatari side of the field. There was some news in 2006 that ConocoPhillips drilled unexpectedly dry holes in the North Field and this event was at least a partial catalyst for a revamped perspective on the North field structure and potential. Further supporting evidence for skepticism about the real scale of Qatari's reserves came from the 2008 exploration round in Qatar to target exploration of gas in the pre-Khuff formation. Even one of the blocks is exactly located beneath the North Dome Field.
On 29 October 2007, Qatargas CEO Faisal Al Suwaidi stated that the 5-year moratorium on new North Field gas development projects, imposed in 2005, could be extended to 2011 or 2012. The exploration moratorium was lifted by Qatar in April 2017 with the announcement of a new gas project in the southern part of the field.
South Pars development
The South Pars Field was discovered in 1990 by National Iranian Oil Company (NIOC). The Pars Oil and Gas Company, a subsidiary of NIOC, has jurisdiction over all South Pars-related projects. Field development has been delayed by various problems - technical (i.e., high levels of mercaptans and foul-smelling sulfur compounds), contractual issues and, recently, politics.
Gas production started from the field by commissioning phase 2 in December 2002 to produce of wet gas. Gas is sent to shore via pipeline, and processed at Assaluyeh.
Condensate production from South Pars is currently , and by 2010, could increase to over . As of December 2010, South pars gas field's production capacity stands at of natural gas per day. Gas production at South Pars rose by nearly 30% between March 2009 and March 2010. The field's reserves are estimated at of natural gas and of natural gas condensates. Production at South Pars gas field will rise to per day in 2012.
NIOC is planning to develop the field in 24 to 30 phases, capable of producing about to of natural gas per day. Each standard phase is defined for daily production of of natural gas, of condensate, 1500 tonnes of liquefied petroleum gas (LPG) and 200 tonnes of sulfur, however some phases have some different production plans. Each of the phases is estimated to have an average capital spend of around US$1.5 billion, and most will be led by foreign oil firms working in partnership with local companies.
Development of a South Pars phase by the Norwegian Statoil company has become infamous after extensive report of misconduct and bribery to the Horton Investments, an Iranian consultancy firm owned by Mehdi Hashemi Rafsanjani, son of former Iranian President Hashemi Rafsanjani. Statoil committed to spending US$300 million to construct three production platforms and a pipeline. The government of Mr Ahmadinejad, who came to power in 2005, has favoured local firms over foreign companies in the energy and other sectors.
By the beginning of 2008, phases 1, 2, 3, 4 and 5 have been brought to production and by the end of 2008, phases 6, 7, 8, 9 and 10 will be on stream. Phases 12, 15, 16, 17, 18, 19, 27 and 28 are under different development stages.
Project finance
As of December 2010, about $30 billion have been invested in South Pars gas fields' development plan. It is estimated that the amount will reach over $40 billion by 2015. The Ministry of Petroleum in Iran said in a revised statement in 2011 that Iran will invest some $90 billion between 2011 and 2015 ($60 billion will be allocated to the upstream sector and the rest to the downstream sector).
Economic studies show with the operation of each South Pars phase, one percent is added to the country's gross domestic product (GDP), while phase 12 will add more than three percent of GDP.
South Pars phases
As at 2012, some 400 Iranian companies were taking part in the development of the South Pars gas field through supplying equipment to related projects.
Phase 1 was developed by Petropars to produce per day of natural gas, of condensate, 1500 tons of LPG per day plus 200 tons of sulfur per day.
Phases 2 and 3 were developed by a consortium of Total S.A., Petronas and Gazprom to produce per day of natural gas, of condensate, 3000 tons of LPG per day plus 400 tons of sulfur per day. It came online in March 2003.
Phases 4 and 5 were developed by Eni and Petropars, to produce per day of rich natural gas, per day of ethane, of condensate, 3000 tons of LPG per day plus 400 tons of sulfur per day.
Phases 6, 7 and 8 being developed by Petropars and Statoil to produce lean gas for re-injection into the Aghajari oilfield, and heavy gas and condensate for export. It involves construction of three offshore platforms in addition to the land based facilities. Statoil is developing the offshore platforms while Petropars is developing the land based facilities. A pipe will be laid from each platform to the coast. These phases will produce per day of natural gas, of ethane, of condensate, 4500 tons of LPG per day plus 600 tons of sulfur per day.
Phases 9 and 10 being developed by a joint venture of GS of South Korea, Oil Industries Engineering and Construction Company (OIEC Group) and Iranian Offshore Engineering and Construction Company (IOEC), in September 2002. The share of Iranian players in this contract exceeds 60%. These phases produce per day of natural gas, per day of ethane, of condensate, 3000 tons of LPG per day plus 400 tons of sulfur per day. Phases 9 & 10 were inaugurated by President Ahmadinejad in March 2009.
Phases 11 will produce LNG through the Pars LNG project. The project was awarded to China National Petroleum Corporation in 2010 after that France's Total S.A. was excluded from the project by Iran. Finally in December 2016, the memorandum of understanding for development of this phase has been awarded to a consortium of Total from France, CNPC from China and Petropars from Iran. After September 2021, the development plans of this gas field continued by entrusting the continuation of the work to Iranian companies, including National Oil Company, Petropars, Pars Oil and Gas and Marine Facilities. In June 2023, the 3,200-ton platform, the heaviest in the South Pars field, was moved and installed in an unprecedented operation by Iranian experts, and gas production from this phase started.
Phases 12 development begin carried out by Petropars as a LNG project. This phase will produce per day of rich natural gas, of ethane, of natural gas condensate, 3000 tons of LPG per day plus 400 tons of sulfur per day. Venezuela’s state-owned oil company Petroleos de Venezuela S.A. (PDVSA) will finance 10% of the $7.8 billion project. Angola’s Sonangol Group has also been awarded a 20% stake in phase 12 project.
Phase 13 and 14 development will be for Persian LNG production. Development was awarded to an Iranian company (Khatam-ol-Osea) for $5 billion. The Iranian Khatam-ol-Osea Consortium is made up of several large Iranian companies, namely Khatam al-Anbia Construction Headquarters, Oil Industries Engineering & Construction (OIEC), SADRA, ISOICO, IDRO, and NIDC. The contract to develop phase 13 was signed with a consortium comprising Mapna, SADRA and Petro Pidar Iranian companies and the phase 14 with another consortia consisting of Industrial Development and Renovation Organization (IDRO), National Iranian Drilling Company (NIDC), Machine Sazi Arak (MSA) and Iranian Offshore Engineering and Construction Company (IOEC).
Phases 15 and 16 development was awarded to Khatam al-Anbia. These phases will produce per day of natural gas, of ethane, of natural gas condensate, 3,000 tons of LPG per day plus 400 tons of sulfur per day. In July 2010, the project was transferred to Iran Shipbuilding & Offshore Industries Complex. At that time, the $2 billion project was already 50% complete. Phase 15 & 16 will be completed by March 2012.
Phases 17 and 18 development was assigned to a consortium of Oil Industries Engineering and Construction Company (OIEC Group), Iran Offshore Engineering and Construction (IOEC) and Industrial Development and Renovation Organization of Iran (IDRO). These phases produce per day of natural gas, of ethane, of natural gas condensate, 3,000 tons of LPG per day plus 400 tons of sulfur per day. Phases 17 & 18 were inaugurated by President Hassan Rouhani in April 2017.
Phase 19 development was awarded to Petropars. These phases will produce per day of natural gas, of ethane, of natural gas condensate, 3,000 tons of LPG per day plus 400 tons of sulfur per day. As it is understood this phase is defined within phase 1 so it can be regarded as some kind of expansion for phase 1.
Phases 20 and 21 development was awarded to OIEC Group. per day of natural gas, of ethane, of natural gas condensate, 3,000 tons of LPG per day plus 400 tons of sulfur per day. Phases 20 & 21 were inaugurated by President Hassan Rouhani in April 2017.
Phases 22, 23 and 24 were awarded to Khatam al-Anbia, Petro Sina Arian and SADRA and are located in the north-eastern frontier of the field. The aim of phases 22, 23 and 24 development is to produce per day of natural gas, of natural gas condensate, and 300 tons of sulfur per day. The three phases also are designed to produce 800,000 tons of LNG and 750,000 tons of ethane per year.
Phases 25 and 26 are in tender.
Phases 27 and 28 development was assigned to Petropars on an EPC scheme. These phases will produce per day of natural gas, of ethane, of natural gas condensate, 3,000 tons of LPG per day plus 400 tons of sulfur per day.
South Pars gas and condensate production plan
Table Sources: NIOC, Pars Oil & Gas Company, Shana and Media
Development delays and criticisms
While several phases of South Pars gas field are still waiting for development and the ongoing development phases are facing delays, NIOC authorities are conducting negotiations for development of other Iranian offshore gas fields like North Pars, Kish, Golshan, Ferdows and Lavan.
Many Iranian energy analysts believe that NIOC authorities should focus on full development of South Pars field prior to conduction of any new project for development of other undeveloped Iranian offshore gas fields.
The priority of South Pars full development is not only due to its shared nature with Qatar, but also with huge capability of the field to add significant liquid production to Iranian liquid export capacity.
On 27 February 2009, one of the members of Iranian Parliaments criticized lack of attention on the importance of acceleration of South Pars field development and the field development delays.
Scale and impacts of delays
By the end of 2008, Qatar's cumulative production from the field was two times higher than Iran's cumulative production from the field. Qatar produced about of natural gas in the period of 1997 to 2008, while Iran produced about of natural gas in the period of 2003 to 2008. The 2:1 ratio of Qatar's cumulative gas production from the field to Iran's is forecasted to continue at least for the short term: by the end of 2011, Qatar's total cumulative production from the field will reach of natural gas, while Iran's will stand at of natural gas in the same year. The ratio is maintained mainly because Qatar's annual production is almost twice the Iranian production level.
In 2011, Qatar will reach an annual production capacity of natural gas per year, while in that year Iran's production capacity will reach per year. If Iran could implement all of its South Pars planned development projects on time, then it would reach the production capacity of of natural gas per year, not earlier than 2015.
The most important impact of delays and lower production in Iranian side would be migration of gas to the Qatari part and a loss of condensate yield due to decreased field pressure.
North Dome development
The North Dome, also known as North Field, was discovered in 1971, with the completion of Shell's North West Dome-1 well.
With falling oil and associated gas production, and depletion of the Khuff reserves, developing the North field became imperative. In 1984 it was decided that development would occur in phases. Phase 1 involved installing production, processing, and transport facilities for of natural gas per day to serve local utilities and produce 5,000 tons per day of propane, butane, gasoline, and naphtha. In 1989 a gas sweetening plant and sulfur processing unit were added. Phase one was online by early 1991. Gas from North Field phase one has been primarily used for local demand, and injection into the Dukhan field. Phase two was expected to involve selling North Field gas to its neighbors, possibly through a Gulf Cooperation Council (GCC) gas grid. Phase three involved exporting to Europe and Asia. Even before the Persian Gulf War, this phase ran into trouble. To justify the investment, QatarEnergy needed two large-scale long-term supply contracts. Despite efforts from QP managing director Jaber al-Marri, contracts were not forthcoming. This switched emphasis to domestic outlets. In 1988, a firm of international consultants presented a plan to QP for developing domestic projects to utilize Qatari gas. Suggestions included an aluminum smelter, a ferro-alloy production plant, methanol production facilities, and expansion of petrochemical and fertilizer operations.
Qatar rapidly expanded its production and exports from North Dome Field. Here are a number of milestones:
1989: Qatar begins production from North Field phase one (Alpha) at rate of of natural gas per day.
1997: Qatar begins exporting by sending (0.16 million tons) of LNG to Spain.
2005: Qatar exports a total of (27.9 million tons) of LNG. Of this, went to Japan, to South Korea, to India, to Spain, and to the United States.
2006: Qatar surpasses Indonesia as the world's largest LNG exporter.
2007: In March QatarEnergy solidifies its leading role when Qatargas completed its fifth LNG production train, giving the country of annual liquefaction capacity, the most in the world.
Subsequent phases of the North field development provided feedstock to LNG plants at Ras Laffan Industrial City.
Based on the current Qatar planned projects, production of LNG from North Dome Field may reach to to per day by 2012, any further increase in the production level of the Qatari side of the field is subject to the result of the ongoing study by QatarEnergy which is supposed to be released in 2012.
The prospects for further growth in Qatari gas production beyond 2012 are clouded by the uncertainty created by a moratorium on new export projects, which was imposed in 2005 while the effect of existing projects on North Field reservoirs was studied.
In order to monetize North Dome's vast resources of gas and liquids, Qatar has undertaken ambitious plans for establishment of the world's biggest LNG and GTL industry.
Qatar's LNG industry
Qatar's LNG company called Qatargas is located in the Ras Laffan Industrial Port on the coast of Persian Gulf.
Since 1997, Qatar has been exporting LNG from the North Field. In 2006, Qatar surpassed Indonesia as the world's largest LNG exporter. Based on the massive gas resources of the field, Qatar is developing the world biggest LNG export facilities in order to reach the capacity of 77 million metric ton per year by 2012 (see table below).
Qatargas is the main company responsible for Qatar's LNG projects.
Qatar's GTL industry
Oryx GTL (Sasol)
The ORYX GTL plant was commissioned in early 2007, as the first operational GTL plant in Qatar. The plant nameplate capacity is , however, the plant has faced technical challenges and did not reach full capacity during the first year of operation. Modifications recommended by Sasol assist with overcoming this shortfall and production capacity was reached/ maintained from 2009 onwards. The plant uses of natural gas from the Al Khaleej Gas project. The ORYX GTL project uses Sasol's Slurry Phase Distillate (SPD) process.
Pearl GTL (Shell)
The project is under construction and will be the world's largest GTL plant which will have the capacity of of middle distillates and significant quantities of LPG and condensate. The first of two GTL trains is planned to start production in 2011. Around of natural gas will be supplied from the North field to the project. Shell has 100% of the equity in the integrated upstream and plant project.
Table 3. North Field production plan (million cubic feet per day).
Table sources: QatarGas, QatarEnergy and internet
See also
Aghajari Gas Injection Project
Dolphin Gas Project
Ferdowsi Gas Field
Golshan Gas Field
Kish Gas Field
NIOC Recent Discoveries
Pearl GTL
World Largest Gas Fields
Iran-Iraq-Syria pipeline
Qatar-Turkey pipeline
Helium (a quarter of the Earth's helium reserves is estimated to be in South Pars)
Notes
References
Qatar: Country Analysis 2007 - Energy Information Administration - (Adobe Acrobat *.PDF document)
Iran: Country Analysis 2006 - Energy Information Administration - (Adobe Acrobat *.PDF document)
Northern Qatar Arch Extension - Zagros Fold Belt Province - USGS - (Adobe Acrobat *.PDF document)
World Energy Outlook 2005 - International Energy Agency - (Adobe Acrobat *.PDF document)
Annual Report 2005 - QatarEnergy - (Adobe Acrobat *.PDF document)
External links
Iran–Qatar border
Natural gas fields in Iran
Natural gas fields in Qatar
Oil fields of Iran
Persian Gulf
|
Kaliszanie (, those from Kalisz) or Kalisz Opposition was a semi-formal political group opposed to the conservative authorities of the Kingdom of Poland in the period preceding the outbreak of the November Uprising. The circle was formed around 1820 by brothers Bonawentura and Wincenty Niemojowski, two liberal politicians from the western provinces of Poland. The group was opposed to the government, yet supported only legal means of political struggle. Its main aims were the defence of the autonomy of Congress Poland within the Russian Empire and the Polish Constitution of 1815. They also played a pivotal role in founding of the National Patriotic Society.
Although opposing to any means of revolutionary changes, the Kaliszanie eventually supported the November Uprising and joined the ranks of the National Government in 1830. During the period of struggle against Russia the Kaliszanie practically dominated the government, controlling the ministries of internal affairs, treasury and war. Following the fall of the uprising in 1831, most of its members had to flee Poland and continued their political activities abroad, notably in London and Paris.
Among the noted politicians commonly associated with the movement were Alojzy and Józef Biernacki, Teodor and Teofil Morawski, Bonawentura, Jan Nepomucen and Wincenty Niemojowski, Antoni Jan and Władysław Tomasz Ostrowski, Ignacy Prądzyński, Stanisław Kaczkowski, Józef Komorowski, Jan Nepomucen Umiński and Walenty Zwierkowski.
Notes and references
In-line:
General:
Establishments in Congress Poland
Political history of Poland
People from Kalisz
|
Ian Kehoe is an Irish journalist, writer, broadcaster and former editor of The Sunday Business Post.
Kehoe, who is from Enniscorthy in County Wexford in the south-east of Ireland, holds a degree in journalism and a masters in international relations from Dublin City University (DCU).
He worked as Business editor, and deputy editor before becoming editor of the post in 2014, he resigned in 2018. He was appointed to the board of RTÉ in 2018.
Kehoe has worked as a reporter on RTÉ's Prime Time Current Affairs show.
In 2013 along with Gavin Daly he published Citizen Quinn about the rise and fall of Sean Quinn.
In 2019, along with Tom Lyons, he launched The Currency, a business and news website.
Books
Citizen Quinn by Gavin Daly and Ian Kehoe, Penguin Ireland, 2013.
References
Living people
Irish journalists
Irish newspaper editors
Business Post people
Alumni of Dublin City University
1980 births
|
```objective-c
/**
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef zzdeps_posix_memory_utils_posix_h
#define zzdeps_posix_memory_utils_posix_h
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "../common/memory-utils-common.h"
#include "../zz.h"
zsize zz_posix_vm_get_page_size();
zbool zz_posix_vm_check_address_valid_via_msync(const zpointer p);
zbool zz_posix_vm_check_address_valid_via_signal(zpointer p);
zbool zz_posix_vm_protect(const zaddr address, zsize size, int page_prot);
zbool zz_posix_vm_protect_as_executable(const zaddr address, zsize size);
zbool zz_posxi_vm_protect_as_writable(const zaddr address, zsize size);
zpointer zz_posix_vm_allocate_pages(zsize n_pages);
zpointer zz_posix_vm_allocate(zsize size);
zpointer zz_posix_vm_allocate_near_pages(zaddr address, zsize range_size, zsize n_pages);
zpointer zz_posix_vm_search_text_code_cave(zaddr address, zsize range_size, zsize size);
zbool zz_posix_vm_patch_code(const zaddr address, const zpointer codedata, zuint codedata_size);
#endif
```
|
```java
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
package io.camunda.zeebe.protocol.impl.record.value.deployment;
import static io.camunda.zeebe.util.buffer.BufferUtil.bufferAsString;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.camunda.zeebe.msgpack.property.BinaryProperty;
import io.camunda.zeebe.msgpack.property.IntegerProperty;
import io.camunda.zeebe.msgpack.property.LongProperty;
import io.camunda.zeebe.msgpack.property.StringProperty;
import io.camunda.zeebe.protocol.impl.record.UnifiedRecordValue;
import io.camunda.zeebe.protocol.record.value.TenantOwned;
import io.camunda.zeebe.protocol.record.value.deployment.Form;
import io.camunda.zeebe.util.buffer.BufferUtil;
import org.agrona.DirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
public final class FormRecord extends UnifiedRecordValue implements Form {
private final StringProperty formIdProp = new StringProperty("formId");
private final IntegerProperty versionProp = new IntegerProperty("version");
private final LongProperty formKeyProp = new LongProperty("formKey");
private final StringProperty resourceNameProp = new StringProperty("resourceName");
private final BinaryProperty checksumProp = new BinaryProperty("checksum", new UnsafeBuffer());
private final BinaryProperty resourceProp = new BinaryProperty("resource", new UnsafeBuffer());
private final StringProperty tenantIdProp =
new StringProperty("tenantId", TenantOwned.DEFAULT_TENANT_IDENTIFIER);
private final LongProperty deploymentKeyProp = new LongProperty("deploymentKey", -1);
public FormRecord() {
super(8);
declareProperty(formIdProp)
.declareProperty(versionProp)
.declareProperty(formKeyProp)
.declareProperty(resourceNameProp)
.declareProperty(checksumProp)
.declareProperty(resourceProp)
.declareProperty(tenantIdProp)
.declareProperty(deploymentKeyProp);
}
public FormRecord wrap(final FormMetadataRecord metadata, final byte[] resource) {
formIdProp.setValue(metadata.getFormId());
versionProp.setValue(metadata.getVersion());
checksumProp.setValue(metadata.getChecksumBuffer());
formKeyProp.setValue(metadata.getFormKey());
resourceNameProp.setValue(metadata.getResourceNameBuffer());
resourceProp.setValue(BufferUtil.wrapArray(resource));
tenantIdProp.setValue(metadata.getTenantId());
deploymentKeyProp.setValue(metadata.getDeploymentKey());
return this;
}
@Override
public String getFormId() {
return BufferUtil.bufferAsString(formIdProp.getValue());
}
public FormRecord setFormId(final String formId) {
formIdProp.setValue(formId);
return this;
}
public FormRecord setFormId(final DirectBuffer formId) {
formIdProp.setValue(formId);
return this;
}
@Override
public int getVersion() {
return versionProp.getValue();
}
public FormRecord setVersion(final int version) {
versionProp.setValue(version);
return this;
}
@Override
public long getFormKey() {
return formKeyProp.getValue();
}
public FormRecord setFormKey(final long key) {
formKeyProp.setValue(key);
return this;
}
@Override
public String getResourceName() {
return BufferUtil.bufferAsString(resourceNameProp.getValue());
}
public FormRecord setResourceName(final String resourceName) {
resourceNameProp.setValue(resourceName);
return this;
}
public FormRecord setResourceName(final DirectBuffer resourceName) {
resourceNameProp.setValue(resourceName);
return this;
}
@Override
public byte[] getChecksum() {
return BufferUtil.bufferAsArray(checksumProp.getValue());
}
public FormRecord setChecksum(final DirectBuffer checksumBuffer) {
checksumProp.setValue(checksumBuffer);
return this;
}
@Override
public boolean isDuplicate() {
return false;
}
@Override
public long getDeploymentKey() {
return deploymentKeyProp.getValue();
}
public FormRecord setDeploymentKey(final long deploymentKey) {
deploymentKeyProp.setValue(deploymentKey);
return this;
}
@JsonIgnore
public DirectBuffer getChecksumBuffer() {
return checksumProp.getValue();
}
@Override
public byte[] getResource() {
return BufferUtil.bufferAsArray(resourceProp.getValue());
}
public FormRecord setResource(final DirectBuffer resource) {
return setResource(resource, 0, resource.capacity());
}
@JsonIgnore
public DirectBuffer getFormIdBuffer() {
return formIdProp.getValue();
}
@Override
@JsonIgnore
public int getLength() {
return super.getLength();
}
@Override
@JsonIgnore
public int getEncodedLength() {
return super.getEncodedLength();
}
@JsonIgnore
public DirectBuffer getResourceNameBuffer() {
return resourceNameProp.getValue();
}
public FormRecord setFormId(final DirectBuffer formId, final int offset, final int length) {
formIdProp.setValue(formId, offset, length);
return this;
}
public FormRecord setResource(final DirectBuffer resource, final int offset, final int length) {
resourceProp.setValue(resource, offset, length);
return this;
}
@JsonIgnore
public DirectBuffer getResourceBuffer() {
return resourceProp.getValue();
}
@Override
public String getTenantId() {
return bufferAsString(tenantIdProp.getValue());
}
public FormRecord setTenantId(final String tenantId) {
tenantIdProp.setValue(tenantId);
return this;
}
}
```
|
```shell
Rapidly invoke an editor to write a long, complex, or tricky command
Terminal based browser
Useful aliasing in bash
Adding directories to your `$PATH`
Sequential execution using the `;` statement separator
```
|
```python
import demistomock as demisto
from CommonServerPython import *
import json
import traceback
from typing import Any, Dict
def get_entry_context(domains, is_single) -> Dict[str, Any]:
urls_to_return = []
if is_single:
if domains.startswith('path_to_url or domains.startswith('path_to_url # NOSONAR
urls_to_return.append(domains)
else:
urls_to_return.append("http://{}".format(domains)) # NOSONAR
urls_to_return.append("https://{}".format(domains))
else:
for domain in domains:
if domain.startswith('path_to_url or domain.startswith('path_to_url # NOSONAR
urls_to_return.append(domain)
else:
urls_to_return.append("http://{}".format(domain)) # NOSONAR
urls_to_return.append("https://{}".format(domain))
ec = {"DomainToURL": urls_to_return}
return ec
def main() -> None:
try:
domains = demisto.args().get('domains', [])
if domains[0] == '[' and domains[-1] == ']':
domains = json.loads(domains)
ec = get_entry_context(domains, False)
else:
ec = get_entry_context(domains, True)
demisto.results(
{"Type": entryTypes['note'], "EntryContext": ec, "Contents": {}, "ContentsFormat": formats["json"]})
except Exception as e:
demisto.error(traceback.format_exc())
return_error(f'Error occurred while extracting Domain(s):\n{e}')
# python2 uses __builtin__ python3 uses builtins
if __name__ == '__builtin__' or __name__ == 'builtins':
main()
```
|
```php
</{{ $widget['wrapper']['element'] ?? 'div' }}>
```
|
```c
/* $OpenBSD: progressmeter.c,v 1.53 2023/04/12 14:22:04 jsg Exp $ */
/*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/uio.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "progressmeter.h"
#include "atomicio.h"
#include "misc.h"
#include "utf8.h"
#define DEFAULT_WINSIZE 80
#define MAX_WINSIZE 512
#define PADDING 1 /* padding between the progress indicators */
#define UPDATE_INTERVAL 1 /* update the progress meter every second */
#define STALL_TIME 5 /* we're stalled after this many seconds */
/* determines whether we can output to the terminal */
static int can_output(void);
/* window resizing */
static void sig_winch(int);
static void setscreensize(void);
/* signal handler for updating the progress meter */
static void sig_alarm(int);
static double start; /* start progress */
static double last_update; /* last progress update */
static const char *file; /* name of the file being transferred */
static off_t start_pos; /* initial position of transfer */
static off_t end_pos; /* ending position of transfer */
static off_t cur_pos; /* transfer position as of last refresh */
static volatile off_t *counter; /* progress counter */
static long stalled; /* how long we have been stalled */
static int bytes_per_second; /* current speed in bytes per second */
static int win_size; /* terminal window size */
static volatile sig_atomic_t win_resized; /* for window resizing */
static volatile sig_atomic_t alarm_fired;
/* units for format_size */
static const char unit[] = " KMGT";
static int
can_output(void)
{
return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}
/* size needed to format integer type v, using (nbits(v) * log2(10) / 10) */
#define STRING_SIZE(v) (((sizeof(v) * 8 * 4) / 10) + 1)
static const char *
format_rate(off_t bytes)
{
int i;
static char buf[STRING_SIZE(bytes) * 2 + 16];
bytes *= 100;
for (i = 0; bytes >= 100*1000 && unit[i] != 'T'; i++)
bytes = (bytes + 512) / 1024;
if (i == 0) {
i++;
bytes = (bytes + 512) / 1024;
}
snprintf(buf, sizeof(buf), "%3lld.%1lld%c%s",
(long long) (bytes + 5) / 100,
(long long) (bytes + 5) / 10 % 10,
unit[i],
i ? "B" : " ");
return buf;
}
static const char *
format_size(off_t bytes)
{
int i;
static char buf[STRING_SIZE(bytes) + 16];
for (i = 0; bytes >= 10000 && unit[i] != 'T'; i++)
bytes = (bytes + 512) / 1024;
snprintf(buf, sizeof(buf), "%4lld%c%s",
(long long) bytes,
unit[i],
i ? "B" : " ");
return buf;
}
void
refresh_progress_meter(int force_update)
{
char *buf = NULL, *obuf = NULL;
off_t transferred;
double elapsed, now;
int percent;
off_t bytes_left;
int cur_speed;
int hours, minutes, seconds;
int file_len, cols;
if ((!force_update && !alarm_fired && !win_resized) || !can_output())
return;
alarm_fired = 0;
if (win_resized) {
setscreensize();
win_resized = 0;
}
transferred = *counter - (cur_pos ? cur_pos : start_pos);
cur_pos = *counter;
now = monotime_double();
bytes_left = end_pos - cur_pos;
if (bytes_left > 0)
elapsed = now - last_update;
else {
elapsed = now - start;
/* Calculate true total speed when done */
transferred = end_pos - start_pos;
bytes_per_second = 0;
}
/* calculate speed */
if (elapsed != 0)
cur_speed = (transferred / elapsed);
else
cur_speed = transferred;
#define AGE_FACTOR 0.9
if (bytes_per_second != 0) {
bytes_per_second = (bytes_per_second * AGE_FACTOR) +
(cur_speed * (1.0 - AGE_FACTOR));
} else
bytes_per_second = cur_speed;
last_update = now;
/* Don't bother if we can't even display the completion percentage */
if (win_size < 4)
return;
/* filename */
file_len = cols = win_size - 36;
if (file_len > 0) {
asmprintf(&buf, INT_MAX, &cols, "%-*s", file_len, file);
/* If we used fewer columns than expected then pad */
if (cols < file_len)
xextendf(&buf, NULL, "%*s", file_len - cols, "");
}
/* percent of transfer done */
if (end_pos == 0 || cur_pos == end_pos)
percent = 100;
else
percent = ((float)cur_pos / end_pos) * 100;
/* percent / amount transferred / bandwidth usage */
xextendf(&buf, NULL, " %3d%% %s %s/s ", percent, format_size(cur_pos),
format_rate((off_t)bytes_per_second));
/* ETA */
if (!transferred)
stalled += elapsed;
else
stalled = 0;
if (stalled >= STALL_TIME)
xextendf(&buf, NULL, "- stalled -");
else if (bytes_per_second == 0 && bytes_left)
xextendf(&buf, NULL, " --:-- ETA");
else {
if (bytes_left > 0)
seconds = bytes_left / bytes_per_second;
else
seconds = elapsed;
hours = seconds / 3600;
seconds -= hours * 3600;
minutes = seconds / 60;
seconds -= minutes * 60;
if (hours != 0) {
xextendf(&buf, NULL, "%d:%02d:%02d",
hours, minutes, seconds);
} else
xextendf(&buf, NULL, " %02d:%02d", minutes, seconds);
if (bytes_left > 0)
xextendf(&buf, NULL, " ETA");
else
xextendf(&buf, NULL, " ");
}
/* Finally, truncate string at window width */
cols = win_size - 1;
asmprintf(&obuf, INT_MAX, &cols, " %s", buf);
if (obuf != NULL) {
*obuf = '\r'; /* must insert as asmprintf() would escape it */
atomicio(vwrite, STDOUT_FILENO, obuf, strlen(obuf));
}
free(buf);
free(obuf);
}
static void
sig_alarm(int ignore)
{
alarm_fired = 1;
alarm(UPDATE_INTERVAL);
}
void
start_progress_meter(const char *f, off_t filesize, off_t *ctr)
{
start = last_update = monotime_double();
file = f;
start_pos = *ctr;
end_pos = filesize;
cur_pos = 0;
counter = ctr;
stalled = 0;
bytes_per_second = 0;
setscreensize();
refresh_progress_meter(1);
ssh_signal(SIGALRM, sig_alarm);
ssh_signal(SIGWINCH, sig_winch);
alarm(UPDATE_INTERVAL);
}
void
stop_progress_meter(void)
{
alarm(0);
if (!can_output())
return;
/* Ensure we complete the progress */
if (cur_pos != end_pos)
refresh_progress_meter(1);
atomicio(vwrite, STDOUT_FILENO, "\n", 1);
}
static void
sig_winch(int sig)
{
win_resized = 1;
}
static void
setscreensize(void)
{
struct winsize winsize;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
winsize.ws_col != 0) {
if (winsize.ws_col > MAX_WINSIZE)
win_size = MAX_WINSIZE;
else
win_size = winsize.ws_col;
} else
win_size = DEFAULT_WINSIZE;
win_size += 1; /* trailing \0 */
}
```
|
```php
<?php
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
*/
namespace Google\Service\Aiplatform;
class GoogleCloudAiplatformV1ListSavedQueriesResponse extends \Google\Collection
{
protected $collection_key = 'savedQueries';
/**
* @var string
*/
public $nextPageToken;
protected $savedQueriesType = GoogleCloudAiplatformV1SavedQuery::class;
protected $savedQueriesDataType = 'array';
/**
* @param string
*/
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
/**
* @return string
*/
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param GoogleCloudAiplatformV1SavedQuery[]
*/
public function setSavedQueries($savedQueries)
{
$this->savedQueries = $savedQueries;
}
/**
* @return GoogleCloudAiplatformV1SavedQuery[]
*/
public function getSavedQueries()
{
return $this->savedQueries;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudAiplatformV1ListSavedQueriesResponse::class, your_sha256_hashsResponse');
```
|
```c
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, path_to_url
*/
#include "tomcrypt.h"
/**
@file der_length_integer.c
ASN.1 DER, get length of encoding, Tom St Denis
*/
#ifdef LTC_DER
/**
Gets length of DER encoding of num
@param num The int to get the size of
@param outlen [out] The length of the DER encoding for the given integer
@return CRYPT_OK if successful
*/
int der_length_integer(void *num, unsigned long *outlen)
{
unsigned long z, len;
int leading_zero;
LTC_ARGCHK(num != NULL);
LTC_ARGCHK(outlen != NULL);
if (mp_cmp_d(num, 0) != LTC_MP_LT) {
/* positive */
/* we only need a leading zero if the msb of the first byte is one */
if ((mp_count_bits(num) & 7) == 0 || mp_iszero(num) == LTC_MP_YES) {
leading_zero = 1;
} else {
leading_zero = 0;
}
/* size for bignum */
z = len = leading_zero + mp_unsigned_bin_size(num);
} else {
/* it's negative */
/* find power of 2 that is a multiple of eight and greater than count bits */
leading_zero = 0;
z = mp_count_bits(num);
z = z + (8 - (z & 7));
if (((mp_cnt_lsb(num)+1)==mp_count_bits(num)) && ((mp_count_bits(num)&7)==0)) --z;
len = z = z >> 3;
}
/* now we need a length */
if (z < 128) {
/* short form */
++len;
} else {
/* long form (relies on z != 0), assumes length bytes < 128 */
++len;
while (z) {
++len;
z >>= 8;
}
}
/* we need a 0x02 to indicate it's INTEGER */
++len;
/* return length */
*outlen = len;
return CRYPT_OK;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/integer/der_length_integer.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2006/04/22 01:22:55 $ */
```
|
```smalltalk
using System;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using DotnetSpider.Extensions;
using DotnetSpider.MessageQueue;
using DotnetSpider.Statistic.Store;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using IMessageQueue = DotnetSpider.MessageQueue.IMessageQueue;
namespace DotnetSpider.Statistic;
public class StatisticHostService(
ILogger<StatisticHostService> logger,
IMessageQueue messageQueue,
IStatisticStore statisticStore)
: BackgroundService
{
private AsyncMessageConsumer<byte[]> _consumer;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogDebug("Statistic service is starting");
await statisticStore.EnsureDatabaseAndTableCreatedAsync();
_consumer = new AsyncMessageConsumer<byte[]>(Topics.Statistics);
_consumer.Received += async bytes =>
{
var message = await bytes.DeserializeAsync(stoppingToken);
switch (message)
{
case null:
logger.LogWarning("Received empty message");
return;
case Messages.Statistic.Success success:
await statisticStore.IncreaseSuccessAsync(success.SpiderId);
break;
case Messages.Statistic.Start start:
await statisticStore.StartAsync(start.SpiderId, start.SpiderName);
break;
case Messages.Statistic.Failure failure:
await statisticStore.IncreaseFailureAsync(failure.SpiderId);
break;
case Messages.Statistic.Total total:
await statisticStore.IncreaseTotalAsync(total.SpiderId, total.Count);
break;
case Messages.Statistic.Exit exit:
await statisticStore.ExitAsync(exit.SpiderId);
break;
case Messages.Statistic.RegisterAgent registerAgent:
await statisticStore.RegisterAgentAsync(registerAgent.AgentId, registerAgent.AgentName);
break;
case Messages.Statistic.AgentSuccess agentSuccess:
await statisticStore.IncreaseAgentSuccessAsync(agentSuccess.AgentId,
agentSuccess.ElapsedMilliseconds);
break;
case Messages.Statistic.AgentFailure agentFailure:
await statisticStore.IncreaseAgentFailureAsync(agentFailure.AgentId,
agentFailure.ElapsedMilliseconds);
break;
case Messages.Statistic.Print print:
{
var statistics = await statisticStore.GetSpiderStatisticAsync(print.SpiderId);
if (statistics != null)
{
var left = statistics.Total >= statistics.Success
? (statistics.Total - statistics.Success - statistics.Failure).ToString()
: "-";
var now = DateTimeOffset.Now;
var speed = (decimal)(statistics.Success /
(now - (statistics.Start ?? now.AddMinutes(-1))).TotalSeconds);
logger.LogInformation(
"Spider {SpiderId} total {Total}, speed: {Speed}, success {Success}, failure {Failure}, left {Left}",
print.SpiderId, statistics.Total, decimal.Round(speed, 2), statistics.Success,
statistics.Failure, left);
}
break;
}
default:
{
var text = Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(message));
logger.LogWarning("Not supported message: {NotSupportedMessage}", text);
break;
}
}
};
await messageQueue.ConsumeAsync(_consumer);
logger.LogDebug("Statistic service started");
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogDebug("Statistic service is stopping");
_consumer?.Close();
await base.StopAsync(cancellationToken);
logger.LogDebug("Statistic service stopped");
}
}
```
|
```java
package com.yahoo.security.tls;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509SslContext;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A static {@link TlsContext}
*
* @author bjorncs
*/
public class DefaultTlsContext implements TlsContext {
private static final Logger log = Logger.getLogger(DefaultTlsContext.class.getName());
private final X509SslContext sslContext;
private final String[] validCiphers;
private final String[] validProtocols;
private final PeerAuthentication peerAuthentication;
public static DefaultTlsContext of(X509SslContext sslContext, PeerAuthentication peerAuthentication) {
return new DefaultTlsContext(sslContext, TlsContext.ALLOWED_CIPHER_SUITES, TlsContext.ALLOWED_PROTOCOLS, peerAuthentication);
}
public static DefaultTlsContext of(
List<X509Certificate> certificates, PrivateKey privateKey, List<X509Certificate> caCertificates,
AuthorizedPeers authorizedPeers, AuthorizationMode mode, PeerAuthentication peerAuthentication,
HostnameVerification hostnameVerification) {
var ctx = createSslContext(certificates, privateKey, caCertificates, authorizedPeers, mode, hostnameVerification);
return of(ctx, peerAuthentication);
}
public static DefaultTlsContext of(
X509SslContext sslContext, Set<String> acceptedCiphers, Set<String> acceptedProtocols,
PeerAuthentication peerAuthentication) {
return new DefaultTlsContext(sslContext, acceptedCiphers, acceptedProtocols, peerAuthentication);
}
private DefaultTlsContext(X509SslContext sslContext, Set<String> acceptedCiphers, Set<String> acceptedProtocols,
PeerAuthentication peerAuthentication) {
this.sslContext = sslContext;
this.peerAuthentication = peerAuthentication;
this.validCiphers = getAllowedCiphers(sslContext.context(), acceptedCiphers);
this.validProtocols = getAllowedProtocols(sslContext.context(), acceptedProtocols);
}
private static String[] getAllowedCiphers(SSLContext sslContext, Set<String> acceptedCiphers) {
Set<String> supportedCiphers = TlsContext.getAllowedCipherSuites(sslContext);
String[] allowedCiphers = supportedCiphers.stream()
.filter(acceptedCiphers::contains)
.toArray(String[]::new);
if (allowedCiphers.length == 0) {
throw new IllegalStateException(
String.format("None of the accepted ciphers are supported (supported=%s, accepted=%s)",
supportedCiphers, acceptedCiphers));
}
log.log(Level.FINE, () -> String.format("Allowed cipher suites that are supported: %s", List.of(allowedCiphers)));
return allowedCiphers;
}
private static String[] getAllowedProtocols(SSLContext sslContext, Set<String> acceptedProtocols) {
Set<String> supportedProtocols = TlsContext.getAllowedProtocols(sslContext);
String[] allowedProtocols = supportedProtocols.stream()
.filter(acceptedProtocols::contains)
.toArray(String[]::new);
if (allowedProtocols.length == 0) {
throw new IllegalStateException(
String.format("None of the accepted protocols are supported (supported=%s, accepted=%s)",
supportedProtocols, acceptedProtocols));
}
log.log(Level.FINE, () -> String.format("Allowed protocols that are supported: %s", Arrays.toString(allowedProtocols)));
return allowedProtocols;
}
@Override
public X509SslContext sslContext() {
return sslContext;
}
@Override
public SSLParameters parameters() {
return createSslParameters();
}
private SSLParameters createSslParameters() {
SSLParameters newParameters = sslContext.context().getDefaultSSLParameters();
newParameters.setCipherSuites(validCiphers);
newParameters.setProtocols(validProtocols);
switch (peerAuthentication) {
case WANT:
newParameters.setWantClientAuth(true);
break;
case NEED:
newParameters.setNeedClientAuth(true);
break;
case DISABLED:
break;
default:
throw new UnsupportedOperationException("Unknown peer authentication: " + peerAuthentication);
}
return newParameters;
}
private static X509SslContext createSslContext(
List<X509Certificate> certificates, PrivateKey privateKey, List<X509Certificate> caCertificates,
AuthorizedPeers authorizedPeers, AuthorizationMode mode, HostnameVerification hostnameVerification) {
SslContextBuilder builder = new SslContextBuilder();
if (!certificates.isEmpty()) {
builder.withKeyStore(privateKey, certificates);
}
if (!caCertificates.isEmpty()) {
builder.withTrustStore(caCertificates);
}
return builder.withTrustManagerFactory(truststore ->
new PeerAuthorizerTrustManager(authorizedPeers, mode, hostnameVerification, truststore))
.buildContext();
}
}
```
|
Chief of the Suquamish – Chief Seattle, also known as Bust of Chief Seattle and Chief Seattle Fountain, is a bust depicting Chief Seattle by artist James A. Wehn. It was commissioned by the Seattle Park Board to accommodate the Alaska-Yukon-Pacific Exposition, and initially sat on a fountain for men, dogs and horses.
Versions
The bronze installed at the intersection of First Avenue and Yesler Way in Pioneer Square, Seattle, was created in 1909. It was surveyed and deemed "treatment needed" by the Smithsonian Institution's "Save Outdoor Sculpture!" program in March 1994.
Another version of the bust is installed at Seattle University.
See also
1909 in art
Native Americans in popular culture
References
External links
1909 establishments in Washington (state)
1909 sculptures
Bronze sculptures in Washington (state)
Busts in Washington (state)
Monuments and memorials in Seattle
Sculptures of Native Americans in Washington (state)
Outdoor sculptures in Seattle
Sculptures of men in Washington (state)
Seattle University campus
World's fair sculptures
Alaska–Yukon–Pacific Exposition
|
```java
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.flowable.eventregistry.rest.service.api;
import org.flowable.eventregistry.api.ChannelDefinition;
import org.flowable.eventregistry.api.ChannelDefinitionQuery;
import org.flowable.eventregistry.api.EventDefinition;
import org.flowable.eventregistry.api.EventDefinitionQuery;
import org.flowable.eventregistry.api.EventDeployment;
import org.flowable.eventregistry.api.EventDeploymentBuilder;
import org.flowable.eventregistry.api.EventDeploymentQuery;
import org.flowable.eventregistry.rest.service.api.runtime.EventInstanceCreateRequest;
public interface EventRegistryRestApiInterceptor {
void accessEventDefinitionById(EventDefinition eventDefinition);
void accessEventDefinitionsWithQuery(EventDefinitionQuery eventDefinitionQuery);
void accessChannelDefinitionById(ChannelDefinition channelDefinition);
void accessChannelDefinitionsWithQuery(ChannelDefinitionQuery channelDefinitionQuery);
void accessDeploymentById(EventDeployment deployment);
void accessDeploymentsWithQuery(EventDeploymentQuery deploymentQuery);
void executeNewDeploymentForTenantId(String tenantId);
void enhanceDeployment(EventDeploymentBuilder eventDeploymentBuilder);
void deleteDeployment(EventDeployment deployment);
void createEventInstance(EventInstanceCreateRequest request);
void accessManagementInfo();
void accessTableInfo();
}
```
|
```smalltalk
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Refactorings;
internal static class RemoveContainingStatementRefactoring
{
public static void ComputeRefactoring(RefactoringContext context, StatementSyntax statement)
{
if (!context.Span.IsEmpty)
return;
if (statement.Kind() == SyntaxKind.Block
&& !((BlockSyntax)statement).Statements.Any())
{
return;
}
SyntaxNode parent = statement.Parent;
if (parent.IsKind(SyntaxKind.Block))
{
statement = (BlockSyntax)parent;
parent = statement.Parent;
}
if (parent is null)
return;
if (!CheckContainingNode(parent))
return;
if (!GetContainingBlock(parent).IsKind(SyntaxKind.Block))
return;
context.RegisterRefactoring(
(parent.IsKind(SyntaxKind.ElseClause))
? "Remove containing else clause"
: "Remove containing statement",
ct => RefactorAsync(context.Document, statement, ct),
RefactoringDescriptors.RemoveContainingStatement);
}
private static SyntaxNode GetContainingBlock(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.ElseClause))
{
return ((ElseClauseSyntax)node).GetTopmostIf()?.Parent;
}
else
{
return node.Parent;
}
}
private static bool CheckContainingNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.LockStatement:
case SyntaxKind.FixedStatement:
case SyntaxKind.UnsafeStatement:
case SyntaxKind.TryStatement:
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return true;
case SyntaxKind.IfStatement:
return ((IfStatementSyntax)node).IsTopmostIf();
case SyntaxKind.ElseClause:
return ((ElseClauseSyntax)node).Statement?.Kind() != SyntaxKind.IfStatement;
}
return false;
}
public static Task<Document> RefactorAsync(
Document document,
StatementSyntax statement,
CancellationToken cancellationToken = default)
{
IEnumerable<StatementSyntax> newNodes = GetNewNodes(statement).Select(f => f.WithFormatterAnnotation());
if (statement.IsParentKind(SyntaxKind.ElseClause))
{
IfStatementSyntax ifStatement = ((ElseClauseSyntax)statement.Parent).GetTopmostIf();
var block = (BlockSyntax)ifStatement.Parent;
int index = block.Statements.IndexOf(ifStatement);
BlockSyntax newBlock = block.RemoveNode(statement.Parent, SyntaxRemoveOptions.KeepNoTrivia);
newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index + 1, newNodes));
return document.ReplaceNodeAsync(block, newBlock, cancellationToken);
}
else
{
return document.ReplaceNodeAsync(statement.Parent, newNodes, cancellationToken);
}
}
private static IEnumerable<StatementSyntax> GetNewNodes(StatementSyntax statement)
{
List<SyntaxTrivia> list;
if (statement.IsParentKind(SyntaxKind.ElseClause))
{
list = new List<SyntaxTrivia>() { CSharpFactory.NewLine() };
}
else
{
list = statement.Parent.GetLeadingTrivia()
.Reverse()
.SkipWhile(f => f.IsWhitespaceTrivia())
.Reverse()
.ToList();
}
if (statement.IsKind(SyntaxKind.Block))
{
SyntaxList<StatementSyntax>.Enumerator en = ((BlockSyntax)statement).Statements.GetEnumerator();
if (en.MoveNext())
{
list.AddRange(en.Current.GetLeadingTrivia());
yield return en.Current.WithLeadingTrivia(list);
while (en.MoveNext())
yield return en.Current;
}
}
else
{
list.AddRange(statement.GetLeadingTrivia());
yield return statement.WithLeadingTrivia(list);
}
}
}
```
|
```go
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package sesv2 provides the client and types for making API
// requests to Amazon Simple Email Service.
//
// Amazon SES (path_to_url is an Amazon Web Services service
// that you can use to send email messages to your customers.
//
// If you're new to Amazon SES API v2, you might find it helpful to review the
// Amazon Simple Email Service Developer Guide (path_to_url
// The Amazon SES Developer Guide provides information and code samples that
// demonstrate how to use Amazon SES API v2 features programmatically.
//
// See path_to_url for more information on this service.
//
// See sesv2 package documentation for more information.
// path_to_url
//
// # Using the Client
//
// To contact Amazon Simple Email Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// path_to_url
//
// See aws.Config documentation for more information on configuring SDK clients.
// path_to_url#Config
//
// See the Amazon Simple Email Service client SESV2 for more
// information on creating client for this service.
// path_to_url#New
package sesv2
```
|
```c++
///|/
///|/ PrusaSlicer is released under the terms of the AGPLv3 or higher
///|/
#ifndef slic3r_SupportLayer_hpp_
#define slic3r_SupportLayer_hpp_
#include <oneapi/tbb/scalable_allocator.h>
#include <oneapi/tbb/spin_mutex.h>
// for Slic3r::deque
#include "../libslic3r.h"
#include "../ClipperUtils.hpp"
#include "../Polygon.hpp"
namespace Slic3r::FFFSupport {
// Support layer type to be used by SupportGeneratorLayer. This type carries a much more detailed information
// about the support layer type than the final support layers stored in a PrintObject.
enum class SupporLayerType {
Unknown = 0,
// Ratft base layer, to be printed with the support material.
RaftBase,
// Raft interface layer, to be printed with the support interface material.
RaftInterface,
// Bottom contact layer placed over a top surface of an object. To be printed with a support interface material.
BottomContact,
// Dense interface layer, to be printed with the support interface material.
// This layer is separated from an object by an BottomContact layer.
BottomInterface,
// Sparse base support layer, to be printed with a support material.
Base,
// Dense interface layer, to be printed with the support interface material.
// This layer is separated from an object with TopContact layer.
TopInterface,
// Top contact layer directly supporting an overhang. To be printed with a support interface material.
TopContact,
// Some undecided type yet. It will turn into Base first, then it may turn into BottomInterface or TopInterface.
Intermediate,
};
// A support layer type used internally by the SupportMaterial class. This class carries a much more detailed
// information about the support layer than the layers stored in the PrintObject, mainly
// the SupportGeneratorLayer is aware of the bridging flow and the interface gaps between the object and the support.
class SupportGeneratorLayer
{
public:
void reset() {
*this = SupportGeneratorLayer();
}
bool operator==(const SupportGeneratorLayer &layer2) const {
return print_z == layer2.print_z && height == layer2.height && bridging == layer2.bridging;
}
// Order the layers by lexicographically by an increasing print_z and a decreasing layer height.
bool operator<(const SupportGeneratorLayer &layer2) const {
if (print_z < layer2.print_z) {
return true;
} else if (print_z == layer2.print_z) {
if (height > layer2.height)
return true;
else if (height == layer2.height) {
// Bridging layers first.
return bridging && ! layer2.bridging;
} else
return false;
} else
return false;
}
void merge(SupportGeneratorLayer &&rhs) {
// The union_() does not support move semantic yet, but maybe one day it will.
this->polygons = union_(this->polygons, std::move(rhs.polygons));
auto merge = [](std::unique_ptr<Polygons> &dst, std::unique_ptr<Polygons> &src) {
if (! dst || dst->empty())
dst = std::move(src);
else if (src && ! src->empty())
*dst = union_(*dst, std::move(*src));
};
merge(this->contact_polygons, rhs.contact_polygons);
merge(this->overhang_polygons, rhs.overhang_polygons);
merge(this->enforcer_polygons, rhs.enforcer_polygons);
rhs.reset();
}
// For the bridging flow, bottom_print_z will be above bottom_z to account for the vertical separation.
// For the non-bridging flow, bottom_print_z will be equal to bottom_z.
coordf_t bottom_print_z() const { return print_z - height; }
// To sort the extremes of top / bottom interface layers.
coordf_t extreme_z() const { return (this->layer_type == SupporLayerType::TopContact) ? this->bottom_z : this->print_z; }
SupporLayerType layer_type { SupporLayerType::Unknown };
// Z used for printing, in unscaled coordinates.
coordf_t print_z { 0 };
// Bottom Z of this layer. For soluble layers, bottom_z + height = print_z,
// otherwise bottom_z + gap + height = print_z.
coordf_t bottom_z { 0 };
// Layer height in unscaled coordinates.
coordf_t height { 0 };
// Index of a PrintObject layer_id supported by this layer. This will be set for top contact layers.
// If this is not a contact layer, it will be set to size_t(-1).
size_t idx_object_layer_above { size_t(-1) };
// Index of a PrintObject layer_id, which supports this layer. This will be set for bottom contact layers.
// If this is not a contact layer, it will be set to size_t(-1).
size_t idx_object_layer_below { size_t(-1) };
// Use a bridging flow when printing this support layer.
bool bridging { false };
// Polygons to be filled by the support pattern.
Polygons polygons;
// Currently for the contact layers only.
std::unique_ptr<Polygons> contact_polygons;
std::unique_ptr<Polygons> overhang_polygons;
// Enforcers need to be propagated independently in case the "support on build plate only" option is enabled.
std::unique_ptr<Polygons> enforcer_polygons;
};
// Layers are allocated and owned by a deque. Once a layer is allocated, it is maintained
// up to the end of a generate() method. The layer storage may be replaced by an allocator class in the future,
// which would allocate layers by multiple chunks.
class SupportGeneratorLayerStorage {
public:
SupportGeneratorLayer& allocate_unguarded(SupporLayerType layer_type) {
m_storage.emplace_back();
m_storage.back().layer_type = layer_type;
return m_storage.back();
}
SupportGeneratorLayer& allocate(SupporLayerType layer_type)
{
m_mutex.lock();
m_storage.emplace_back();
SupportGeneratorLayer *layer_new = &m_storage.back();
m_mutex.unlock();
layer_new->layer_type = layer_type;
return *layer_new;
}
private:
template<typename BaseType>
using Allocator = tbb::scalable_allocator<BaseType>;
Slic3r::deque<SupportGeneratorLayer, Allocator<SupportGeneratorLayer>> m_storage;
tbb::spin_mutex m_mutex;
};
using SupportGeneratorLayersPtr = std::vector<SupportGeneratorLayer*>;
} // namespace Slic3r
#endif /* slic3r_SupportLayer_hpp_ */
```
|
```racket
#lang hackett
(require hackett/private/test)
(def my-empty : (forall [a] (List a)) (List))
(defn last : (forall [a] {(List a) -> a})
[[(List)] (error! "last of empty list")]
[[(List x)] x]
[[{x :: xs}] (last xs)])
(test {(List 1 2 3) ==! {1 :: 2 :: 3 :: Nil}})
(test {(head! (last (List (List 8 9) (List 10 100)))) ==! 10})
```
|
```objective-c
//
// Generated by class-dump 3.5 (64 bit).
//
//
#import <WebDriverAgentLib/CDStructures.h>
#import "XCDebugLogDelegate-Protocol.h"
#import "XCTestDriverInterface-Protocol.h"
#import "XCTestManager_TestsInterface-Protocol.h"
#import "XCTestManager_IDEInterface-Protocol.h"
#import "XCTestManager_ManagerInterface-Protocol.h"
@class DTXConnection, NSMutableArray, NSString, NSUUID, NSXPCConnection, XCTestConfiguration, XCTestSuite;
@interface XCTestDriver : NSObject <XCTestManager_TestsInterface, XCTestDriverInterface, XCDebugLogDelegate>
{
XCTestConfiguration *_testConfiguration;
NSObject<OS_dispatch_queue> *_queue;
NSMutableArray *_debugMessageBuffer;
int _debugMessageBufferOverflow;
}
@property int debugMessageBufferOverflow; // @synthesize debugMessageBufferOverflow=_debugMessageBufferOverflow;
@property(retain) NSMutableArray *debugMessageBuffer; // @synthesize debugMessageBuffer=_debugMessageBuffer;
@property(retain) NSObject<OS_dispatch_queue> *queue; // @synthesize queue=_queue;
@property(readonly) XCTestConfiguration *testConfiguration; // @synthesize testConfiguration=_testConfiguration;
// Removed since Xcode 12.0
+ (instancetype)sharedTestDriver;
- (void)runTestConfiguration:(id)arg1 completionHandler:(CDUnknownBlockType)arg2;
- (void)runTestSuite:(id)arg1 completionHandler:(CDUnknownBlockType)arg2;
- (void)reportStallOnMainThreadInTestCase:(id)arg1 method:(id)arg2 file:(id)arg3 line:(unsigned long long)arg4;
- (BOOL)runTestsAndReturnError:(id *)arg1;
- (id)_readyIDESession:(id *)arg1;
- (int)_connectedSocketForIDESession:(id *)arg1;
- (void)logDebugMessage:(id)arg1;
- (id)initWithTestConfiguration:(id)arg1;
// Removed with iOS 10.3
@property(readonly) id <XCTestManager_ManagerInterface> managerProxy;
@end
```
|
```go
package raft
import (
"bytes"
crand "crypto/rand"
"fmt"
"math"
"math/big"
"math/rand"
"time"
"github.com/hashicorp/go-msgpack/codec"
)
func init() {
// Ensure we use a high-entropy seed for the psuedo-random generator
rand.Seed(newSeed())
}
// returns an int64 from a crypto random source
// can be used to seed a source for a math/rand.
func newSeed() int64 {
r, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return r.Int64()
}
// randomTimeout returns a value that is between the minVal and 2x minVal.
func randomTimeout(minVal time.Duration) <-chan time.Time {
if minVal == 0 {
return nil
}
extra := (time.Duration(rand.Int63()) % minVal)
return time.After(minVal + extra)
}
// min returns the minimum.
func min(a, b uint64) uint64 {
if a <= b {
return a
}
return b
}
// max returns the maximum.
func max(a, b uint64) uint64 {
if a >= b {
return a
}
return b
}
// generateUUID is used to generate a random UUID.
func generateUUID() string {
buf := make([]byte, 16)
if _, err := crand.Read(buf); err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16])
}
// asyncNotifyCh is used to do an async channel send
// to a single channel without blocking.
func asyncNotifyCh(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// asyncNotifyBool is used to do an async notification
// on a bool channel.
func asyncNotifyBool(ch chan bool, v bool) {
select {
case ch <- v:
default:
}
}
// ExcludePeer is used to exclude a single peer from a list of peers.
func ExcludePeer(peers []string, peer string) []string {
otherPeers := make([]string, 0, len(peers))
for _, p := range peers {
if p != peer {
otherPeers = append(otherPeers, p)
}
}
return otherPeers
}
// PeerContained checks if a given peer is contained in a list.
func PeerContained(peers []string, peer string) bool {
for _, p := range peers {
if p == peer {
return true
}
}
return false
}
// AddUniquePeer is used to add a peer to a list of existing
// peers only if it is not already contained.
func AddUniquePeer(peers []string, peer string) []string {
if PeerContained(peers, peer) {
return peers
}
return append(peers, peer)
}
// encodePeers is used to serialize a list of peers.
func encodePeers(peers []string, trans Transport) []byte {
// Encode each peer
var encPeers [][]byte
for _, p := range peers {
encPeers = append(encPeers, trans.EncodePeer(p))
}
// Encode the entire array
buf, err := encodeMsgPack(encPeers)
if err != nil {
panic(fmt.Errorf("failed to encode peers: %v", err))
}
return buf.Bytes()
}
// decodePeers is used to deserialize a list of peers.
func decodePeers(buf []byte, trans Transport) []string {
// Decode the buffer first
var encPeers [][]byte
if err := decodeMsgPack(buf, &encPeers); err != nil {
panic(fmt.Errorf("failed to decode peers: %v", err))
}
// Deserialize each peer
var peers []string
for _, enc := range encPeers {
peers = append(peers, trans.DecodePeer(enc))
}
return peers
}
// Decode reverses the encode operation on a byte slice input.
func decodeMsgPack(buf []byte, out interface{}) error {
r := bytes.NewBuffer(buf)
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(r, &hd)
return dec.Decode(out)
}
// Encode writes an encoded object to a new bytes buffer.
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
// backoff is used to compute an exponential backoff
// duration. Base time is scaled by the current round,
// up to some maximum scale factor.
func backoff(base time.Duration, round, limit uint64) time.Duration {
power := min(round, limit)
for power > 2 {
base *= 2
power--
}
return base
}
```
|
```ruby
# -*- encoding: utf-8 -*-
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
describe "String#casecmp independent of case" do
it "returns -1 when less than other" do
"a".casecmp("b").should == -1
"A".casecmp("b").should == -1
end
it "returns 0 when equal to other" do
"a".casecmp("a").should == 0
"A".casecmp("a").should == 0
end
it "returns 1 when greater than other" do
"b".casecmp("a").should == 1
"B".casecmp("a").should == 1
end
it "tries to convert other to string using to_str" do
other = mock('x')
other.should_receive(:to_str).and_return("abc")
"abc".casecmp(other).should == 0
end
it "returns nil if other can't be converted to a string" do
"abc".casecmp(mock('abc')).should be_nil
end
it "returns nil if incompatible encodings" do
"".casecmp("".encode(Encoding::EUC_JP)).should be_nil
end
describe "in UTF-8 mode" do
describe "for non-ASCII characters" do
before :each do
@upper_a_tilde = ""
@lower_a_tilde = ""
@upper_a_umlaut = ""
@lower_a_umlaut = ""
end
it "returns -1 when numerically less than other" do
@upper_a_tilde.casecmp(@lower_a_tilde).should == -1
@upper_a_tilde.casecmp(@upper_a_umlaut).should == -1
end
it "returns 0 when numerically equal to other" do
@upper_a_tilde.casecmp(@upper_a_tilde).should == 0
end
it "returns 1 when numerically greater than other" do
@lower_a_umlaut.casecmp(@upper_a_umlaut).should == 1
@lower_a_umlaut.casecmp(@lower_a_tilde).should == 1
end
end
describe "for ASCII characters" do
it "returns -1 when less than other" do
"a".casecmp("b").should == -1
"A".casecmp("b").should == -1
end
it "returns 0 when equal to other" do
"a".casecmp("a").should == 0
"A".casecmp("a").should == 0
end
it "returns 1 when greater than other" do
"b".casecmp("a").should == 1
"B".casecmp("a").should == 1
end
end
end
describe "for non-ASCII characters" do
before :each do
@upper_a_tilde = "\xc3"
@lower_a_tilde = "\xe3"
end
it "returns -1 when numerically less than other" do
@upper_a_tilde.casecmp(@lower_a_tilde).should == -1
end
it "returns 0 when equal to other" do
@upper_a_tilde.casecmp("\xc3").should == 0
end
it "returns 1 when numerically greater than other" do
@lower_a_tilde.casecmp(@upper_a_tilde).should == 1
end
it "does not case fold" do
"".casecmp("ss").should == 1
end
end
describe "when comparing a subclass instance" do
it "returns -1 when less than other" do
b = StringSpecs::MyString.new "b"
"a".casecmp(b).should == -1
"A".casecmp(b).should == -1
end
it "returns 0 when equal to other" do
a = StringSpecs::MyString.new "a"
"a".casecmp(a).should == 0
"A".casecmp(a).should == 0
end
it "returns 1 when greater than other" do
a = StringSpecs::MyString.new "a"
"b".casecmp(a).should == 1
"B".casecmp(a).should == 1
end
end
it "returns 0 for empty strings in different encodings" do
''.b.casecmp('').should == 0
''.b.casecmp(''.encode("UTF-32LE")).should == 0
end
end
describe 'String#casecmp? independent of case' do
it 'returns true when equal to other' do
'abc'.casecmp?('abc').should == true
'abc'.casecmp?('ABC').should == true
end
it 'returns false when not equal to other' do
'abc'.casecmp?('DEF').should == false
'abc'.casecmp?('def').should == false
end
it "tries to convert other to string using to_str" do
other = mock('x')
other.should_receive(:to_str).and_return("abc")
"abc".casecmp?(other).should == true
end
it "returns nil if incompatible encodings" do
"".casecmp?("".encode(Encoding::EUC_JP)).should be_nil
end
describe 'for UNICODE characters' do
it 'returns true when downcase(:fold) on unicode' do
''.casecmp?('').should == true
end
end
describe "when comparing a subclass instance" do
it 'returns true when equal to other' do
a = StringSpecs::MyString.new "a"
'a'.casecmp?(a).should == true
'A'.casecmp?(a).should == true
end
it 'returns false when not equal to other' do
b = StringSpecs::MyString.new "a"
'b'.casecmp?(b).should == false
'B'.casecmp?(b).should == false
end
end
describe "in UTF-8 mode" do
describe "for non-ASCII characters" do
before :each do
@upper_a_tilde = ""
@lower_a_tilde = ""
@upper_a_umlaut = ""
@lower_a_umlaut = ""
end
it "returns true when they are the same with normalized case" do
@upper_a_tilde.casecmp?(@lower_a_tilde).should == true
end
it "returns false when they are unrelated" do
@upper_a_tilde.casecmp?(@upper_a_umlaut).should == false
end
it "returns true when they have the same bytes" do
@upper_a_tilde.casecmp?(@upper_a_tilde).should == true
end
end
end
it "case folds" do
"".casecmp?("ss").should be_true
end
it "returns nil if other can't be converted to a string" do
"abc".casecmp?(mock('abc')).should be_nil
end
it "returns true for empty strings in different encodings" do
''.b.should.casecmp?('')
''.b.should.casecmp?(''.encode("UTF-32LE"))
end
end
```
|
River Rat is the eighth full-length studio album by American country rap artist Ryan Upchurch. It was released on December 21, 2018 via Redneck Nation Records. It was recorded in Nashville, Tennessee and produced by Thomas "Greenway" Toner a.k.a. T-Stoner.
The album peaked at number 191 on the Billboard 200 albums chart and at number 21 on the Top Country Albums chart in the United States
Track listing
Charts
References
External links
River Rat by Upchurch on iTunes
Upchurch© River Rat album on Redneck Nation
2018 albums
Upchurch (musician) albums
|
```java
/**
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.thingsboard.server.service.queue.ruleengine;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.queue.ProcessingStrategy;
import org.thingsboard.server.common.data.queue.ProcessingStrategyType;
import org.thingsboard.server.common.data.queue.Queue;
import org.thingsboard.server.common.data.queue.SubmitStrategy;
import org.thingsboard.server.common.data.queue.SubmitStrategyType;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgDataType;
import org.thingsboard.server.common.msg.TbMsgProcessingCtx;
import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg;
import org.thingsboard.server.common.msg.queue.RuleEngineException;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg;
import org.thingsboard.server.queue.TbQueueConsumer;
import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.discovery.QueueKey;
import org.thingsboard.server.service.queue.processing.TbRuleEngineProcessingStrategyFactory;
import org.thingsboard.server.service.queue.processing.TbRuleEngineSubmitStrategyFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.RETRY_ALL;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.RETRY_FAILED;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.RETRY_FAILED_AND_TIMED_OUT;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.RETRY_TIMED_OUT;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.SKIP_ALL_FAILURES;
import static org.thingsboard.server.common.data.queue.ProcessingStrategyType.SKIP_ALL_FAILURES_AND_TIMED_OUT;
import static org.thingsboard.server.common.data.queue.SubmitStrategyType.BATCH;
import static org.thingsboard.server.common.data.queue.SubmitStrategyType.BURST;
import static org.thingsboard.server.common.data.queue.SubmitStrategyType.SEQUENTIAL_BY_ORIGINATOR;
@Slf4j
@MockitoSettings(strictness = Strictness.LENIENT)
public class TbRuleEngineStrategyTest {
@Mock
private ActorSystemContext actorContext;
@Mock
private TbQueueConsumer<TbProtoQueueMsg<ToRuleEngineMsg>> consumer;
private TbRuleEngineConsumerContext ruleEngineConsumerContext;
private static UUID tenantId = UUID.randomUUID();
private static DeviceId deviceId = new DeviceId(UUID.randomUUID());
@BeforeEach
public void beforeEach() {
ruleEngineConsumerContext = new TbRuleEngineConsumerContext(
actorContext, mock(), new TbRuleEngineSubmitStrategyFactory(),
new TbRuleEngineProcessingStrategyFactory(), mock(), mock(),
mock(), mock(), mock(), mock()
);
when(consumer.isStopped()).thenReturn(false);
}
private static Stream<Arguments> testData() {
return Stream.of(
//BURST
Arguments.of(BURST, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_ALL, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_ALL, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(2), new ProcessingData(2))),
Arguments.of(BURST, RETRY_ALL, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(2), new ProcessingData(2))),
Arguments.of(BURST, RETRY_FAILED, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_FAILED, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_FAILED, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BURST, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
//BATCH
Arguments.of(BATCH, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, RETRY_ALL, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_ALL, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(2), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_ALL, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(2), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_FAILED, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_FAILED, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, RETRY_FAILED, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(1), new ProcessingData(0))),
Arguments.of(BATCH, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(BATCH, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
//SEQUENTIAL_BY_ORIGINATOR
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, SKIP_ALL_FAILURES_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_ALL, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_ALL, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_ALL, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED, 3, List.of(new ProcessingData(false, true, 1), new ProcessingData(0), new ProcessingData(0))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(1), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(true, false, 2), new ProcessingData(1), new ProcessingData(1))),
Arguments.of(SEQUENTIAL_BY_ORIGINATOR, RETRY_FAILED_AND_TIMED_OUT, 3, List.of(new ProcessingData(false, true, 2), new ProcessingData(1), new ProcessingData(1)))
);
}
@ParameterizedTest
@MethodSource("testData")
public void processMsgsTest(SubmitStrategyType submitStrategyType, ProcessingStrategyType processingStrategyType, int retries, List<ProcessingData> processingData) throws Exception {
var queue = new Queue();
queue.setName("Test");
queue.setPackProcessingTimeout(100);
SubmitStrategy submitStrategy = new SubmitStrategy();
submitStrategy.setType(submitStrategyType);
submitStrategy.setBatchSize(2);
queue.setSubmitStrategy(submitStrategy);
ProcessingStrategy processingStrategy = new ProcessingStrategy();
processingStrategy.setType(processingStrategyType);
processingStrategy.setRetries(retries);
queue.setProcessingStrategy(processingStrategy);
QueueKey queueKey = new QueueKey(ServiceType.TB_RULE_ENGINE, queue);
var consumerManager = TbRuleEngineQueueConsumerManager.create()
.ctx(ruleEngineConsumerContext)
.queueKey(queueKey)
.build();
consumerManager.init(queue);
Map<UUID, ProcessingData> msgsMap = processingData.stream().collect(Collectors.toMap(data -> data.tbMsg.getId(), data -> data));
Map<UUID, AtomicInteger> attemptsMap = new HashMap<>();
Map<UUID, AtomicBoolean> failedMap = new HashMap<>();
Map<UUID, AtomicBoolean> timeoutMap = new HashMap<>();
doAnswer(inv -> {
QueueToRuleEngineMsg msg = inv.getArgument(0);
UUID msgId = msg.getMsg().getId();
var data = msgsMap.get(msgId);
var attempts = attemptsMap.computeIfAbsent(msgId, key -> new AtomicInteger(0));
Assertions.assertTrue(attempts.getAndIncrement() <= data.attempts);
var callback = msg.getMsg().getCallback();
if (data.shouldFailed) {
var alreadyFailed = failedMap.computeIfAbsent(msgId, key -> new AtomicBoolean(false));
if (!alreadyFailed.getAndSet(true)) {
callback.onFailure(new RuleEngineException("Failed to process test msg!"));
return null;
}
}
if (data.shouldTimeout) {
var alreadyTimedOuted = timeoutMap.computeIfAbsent(msgId, key -> new AtomicBoolean(false));
if (!alreadyTimedOuted.getAndSet(true)) {
return null;
}
}
callback.onSuccess();
return null;
}).when(actorContext).tell(any());
List<TbProtoQueueMsg<ToRuleEngineMsg>> protoMsgs = processingData.stream()
.map(data -> data.tbMsg)
.map(this::toProto)
.toList();
consumerManager.processMsgs(protoMsgs, consumer, queue);
processingData.forEach(data -> {
verify(actorContext, times(data.attempts)).tell(argThat(msg ->
((QueueToRuleEngineMsg) msg).getMsg().getId().equals(data.tbMsg.getId())
));
});
}
private static TbMsg createRandomMsg() {
return TbMsg.builder()
.id(UUID.randomUUID())
.type("test type")
.originator(deviceId)
.dataType(TbMsgDataType.TEXT)
.data("test data")
.ctx(new TbMsgProcessingCtx())
.build();
}
private TbProtoQueueMsg<ToRuleEngineMsg> toProto(TbMsg tbMsg) {
return new TbProtoQueueMsg<>(UUID.randomUUID(), ToRuleEngineMsg.newBuilder()
.setTenantIdMSB(tenantId.getMostSignificantBits())
.setTenantIdLSB(tenantId.getLeastSignificantBits())
.addRelationTypes("Success")
.setTbMsg(TbMsg.toByteString(tbMsg))
.build());
}
@RequiredArgsConstructor
@EqualsAndHashCode
@ToString(exclude = "tbMsg")
private static class ProcessingData {
private final TbMsg tbMsg = createRandomMsg();
private final boolean shouldFailed;
private final boolean shouldTimeout;
private final int attempts;
public ProcessingData(int attempts) {
shouldFailed = false;
shouldTimeout = false;
this.attempts = attempts;
}
}
}
```
|
```c++
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/tracing/tracing-category-observer.h"
#include "src/base/atomic-utils.h"
#include "src/flags.h"
#include "src/tracing/trace-event.h"
#include "src/v8.h"
namespace v8 {
namespace tracing {
TracingCategoryObserver* TracingCategoryObserver::instance_ = nullptr;
void TracingCategoryObserver::SetUp() {
TracingCategoryObserver::instance_ = new TracingCategoryObserver();
v8::internal::V8::GetCurrentPlatform()
->GetTracingController()
->AddTraceStateObserver(TracingCategoryObserver::instance_);
TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats"));
TRACE_EVENT_WARMUP_CATEGORY(
TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats_sampling"));
TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("v8.gc_stats"));
TRACE_EVENT_WARMUP_CATEGORY(TRACE_DISABLED_BY_DEFAULT("v8.ic_stats"));
}
void TracingCategoryObserver::TearDown() {
v8::internal::V8::GetCurrentPlatform()
->GetTracingController()
->RemoveTraceStateObserver(TracingCategoryObserver::instance_);
delete TracingCategoryObserver::instance_;
}
void TracingCategoryObserver::OnTraceEnabled() {
bool enabled = false;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats"), &enabled);
if (enabled) {
base::AsAtomic32::Relaxed_Store(
&v8::internal::FLAG_runtime_stats,
(v8::internal::FLAG_runtime_stats | ENABLED_BY_TRACING));
}
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats_sampling"), &enabled);
if (enabled) {
base::AsAtomic32::Relaxed_Store(
&v8::internal::FLAG_runtime_stats,
v8::internal::FLAG_runtime_stats | ENABLED_BY_SAMPLING);
}
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("v8.gc_stats"),
&enabled);
if (enabled) {
v8::internal::FLAG_gc_stats |= ENABLED_BY_TRACING;
}
TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("v8.ic_stats"),
&enabled);
if (enabled) {
v8::internal::FLAG_ic_stats |= ENABLED_BY_TRACING;
}
}
void TracingCategoryObserver::OnTraceDisabled() {
base::AsAtomic32::Relaxed_Store(
&v8::internal::FLAG_runtime_stats,
v8::internal::FLAG_runtime_stats &
~(ENABLED_BY_TRACING | ENABLED_BY_SAMPLING));
v8::internal::FLAG_gc_stats &= ~ENABLED_BY_TRACING;
v8::internal::FLAG_ic_stats &= ~ENABLED_BY_TRACING;
}
} // namespace tracing
} // namespace v8
```
|
```java
/*
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.apache.shardingsphere.proxy.backend.mysql.handler.admin.executor.variable.session;
import org.apache.shardingsphere.proxy.backend.handler.admin.executor.variable.session.ReplayedSessionVariableProvider;
/**
* Replayed session variables provider of MySQL.
*/
public final class MySQLReplayedSessionVariableProvider implements ReplayedSessionVariableProvider {
@Override
public boolean isNeedToReplay(final String variableName) {
return variableName.startsWith("@");
}
@Override
public String getDatabaseType() {
return "MySQL";
}
}
```
|
Marcum is a family name. Notable persons with that name include:
Deanna B. Marcum (1946–2022), American librarian and nonprofit leader
John Marcum (1995-present), ARCA founder, NASCAR official
Johnny Marcum (1909–1984), baseball pitcher
Justin Marcum, politician
Kent Marcum, composer
Leo Marcum (born 1942), American politician, lawyer
Shaun Marcum (born 1981), baseball pitcher
Tim Marcum (1944–2013), football coach
Other
Marcum Q-function, mathematical function
Marcum, Kentucky
Markham (disambiguation)
Morecambe (disambiguation)
|
```java
/*
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* specific language governing permissions and limitations
*/
package org.apache.guacamole.auth.ldap.conf;
import java.util.Collections;
import java.util.List;
import org.apache.directory.api.ldap.model.filter.ExprNode;
import org.apache.directory.api.ldap.model.filter.PresenceNode;
import org.apache.directory.api.ldap.model.message.AliasDerefMode;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleServerException;
/**
* LDAPConfiguration implementation that returns the default values for all
* configuration parameters. For any configuration parameters that are
* required (such as {@link #getUserBaseDN()}), an exception is thrown.
*/
public class DefaultLDAPConfiguration implements LDAPConfiguration {
@Override
public String appliesTo(String username) {
return null;
}
@Override
public String getServerHostname() {
return "localhost";
}
@Override
public int getServerPort() {
return getEncryptionMethod().DEFAULT_PORT;
}
@Override
public List<String> getUsernameAttributes() {
return Collections.singletonList("uid");
}
@Override
public Dn getUserBaseDN() throws GuacamoleException {
throw new GuacamoleServerException("All LDAP servers must have a defined user base DN.");
}
@Override
public Dn getConfigurationBaseDN() {
return null;
}
@Override
public List<String> getGroupNameAttributes() {
return Collections.singletonList("cn");
}
@Override
public Dn getGroupBaseDN() {
return null;
}
@Override
public String getSearchBindDN() {
return null;
}
@Override
public String getSearchBindPassword() {
return null;
}
@Override
public EncryptionMethod getEncryptionMethod() {
return EncryptionMethod.NONE;
}
@Override
public LDAPSSLProtocol getSslProtocol() {
return LDAPSSLProtocol.TLSv1_3;
}
@Override
public int getMaxResults() {
return 1000;
}
@Override
public AliasDerefMode getDereferenceAliases() {
return AliasDerefMode.NEVER_DEREF_ALIASES;
}
@Override
public boolean getFollowReferrals() {
return false;
}
@Override
public int getMaxReferralHops() {
return 5;
}
@Override
public ExprNode getUserSearchFilter() {
return new PresenceNode("objectClass");
}
@Override
public ExprNode getGroupSearchFilter() {
return new PresenceNode("objectClass");
}
@Override
public int getOperationTimeout() {
return 30;
}
@Override
public int getNetworkTimeout() {
return 30000;
}
@Override
public List<String> getAttributes() {
return Collections.<String>emptyList();
}
@Override
public String getMemberAttribute() {
return "member";
}
@Override
public MemberAttributeType getMemberAttributeType()
throws GuacamoleException {
return MemberAttributeType.DN;
}
}
```
|
```scala
package com.prisma.connectors.utils
import com.prisma.api.connector.ApiConnector
import com.prisma.api.connector.mongo.MongoApiConnector
import com.prisma.api.connector.mysql.MySqlApiConnector
import com.prisma.api.connector.postgres.PostgresApiConnector
import com.prisma.api.connector.sqlite.SQLiteApiConnector
import com.prisma.config.PrismaConfig
import com.prisma.deploy.connector.DeployConnector
import com.prisma.deploy.connector.mongo.MongoDeployConnector
import com.prisma.deploy.connector.mysql.MySqlDeployConnector
import com.prisma.deploy.connector.postgres.PostgresDeployConnector
import com.prisma.deploy.connector.sqlite.SQLiteDeployConnector
import scala.concurrent.ExecutionContext
object ConnectorLoader {
def loadApiConnector(config: PrismaConfig)(implicit ec: ExecutionContext, drivers: SupportedDrivers): ApiConnector = {
val databaseConfig = config.databases.head
databaseConfig.connector match {
case "mysql" => MySqlApiConnector(databaseConfig, drivers(SupportedDrivers.MYSQL))
case "postgres" => PostgresApiConnector(databaseConfig, drivers(SupportedDrivers.POSTGRES))
case "sqlite" => SQLiteApiConnector(databaseConfig, drivers(SupportedDrivers.SQLITE))
case "mongo" => MongoApiConnector(databaseConfig)
case conn => sys.error(s"Unknown connector $conn")
}
}
def loadDeployConnector(config: PrismaConfig)(implicit ec: ExecutionContext, drivers: SupportedDrivers): DeployConnector = {
val databaseConfig = config.databases.head
databaseConfig.connector match {
case "mysql" => MySqlDeployConnector(databaseConfig, drivers(SupportedDrivers.MYSQL))
case "mysql-native" => MySqlDeployConnector(databaseConfig, drivers(SupportedDrivers.MYSQL))
case "postgres" => PostgresDeployConnector(databaseConfig, drivers(SupportedDrivers.POSTGRES))
case "postgres-native" => PostgresDeployConnector(databaseConfig, drivers(SupportedDrivers.POSTGRES))
case "sqlite-native" => SQLiteDeployConnector(databaseConfig, drivers(SupportedDrivers.SQLITE))
case "native-integration-tests" => SQLiteDeployConnector(databaseConfig, drivers(SupportedDrivers.SQLITE))
case "sqlite" => SQLiteDeployConnector(databaseConfig, drivers(SupportedDrivers.SQLITE))
case "mongo" => MongoDeployConnector(databaseConfig)
case conn => sys.error(s"Unknown connector $conn")
}
}
}
```
|
"Up Down" is a song written by Michael Hardy, Brad Clawson, and CJ Solar, and recorded by American country music singer Morgan Wallen along with country music duo Florida Georgia Line. The song is Wallen's second single release overall, and it appears on his 2018 studio album If I Know Me. "Up Down" has reached number one on the Billboard Country Airplay chart and number five on the Hot Country Songs chart. It also reached number 49 on the Hot 100 chart. The song was certified Platinum by the Recording Industry Association of America (RIAA), and has sold 267,000 units as of August 2018. It achieved similar chart success in Canada, reaching number one on the Canada Country chart.
An accompanying music video for the song, directed by Justin Clough, features Wallen and both members of Florida Georgia Line partying on a beach, and in concert.
Composition
Hardy, a close friend of Wallen's, wrote the song with Brad Clawson (son of Nashville songwriter Rodney Clawson) and CJ Solar. Originally Wallen had intended to sing the song solo, but he contacted Florida Georgia Line to ask for their opinion of the song, and the duo chose to sing guest vocals on it. Wallen said that he identified with the song's theme of having a good time in a small town because of his own upbringing.
Commercial performance
The song was certified Platinum on July 31, 2018 and double Platinum on February 25, 2020 for 2 million combined sales and streams units. It has sold 333,000 copies in the United States as of September 2018.
Music video
The song's music video features Wallen and both members of Florida Georgia Line partying at Perdido Pass in Orange Beach, Alabama and in concert at The Wharf Amphitheater on Orange Beach, Alabama {A Green} . It was directed by Justin Clough.
Parodies
In July 2018, country music parodist Cledus T. Judd released a parody of the song titled "(Weight's Goin') Up Down, Up Down". The parody has its own music video, directed by Judd himself and featuring members of his family.
Charts & certifications
Weekly charts
Certifications
Year-end charts
References
2017 singles
Morgan Wallen songs
Florida Georgia Line songs
Vocal collaborations
Song recordings produced by Joey Moi
Big Loud singles
Songs written by Hardy (singer)
Songs written by C.J. Solar
|
```go
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64
// +build solaris
package socket
import "unsafe"
func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {
for i := range vs {
vs[i].set(bs[i])
}
if len(vs) > 0 {
h.Iov = &vs[0]
h.Iovlen = int32(len(vs))
}
if len(oob) > 0 {
h.Accrights = (*int8)(unsafe.Pointer(&oob[0]))
h.Accrightslen = int32(len(oob))
}
if sa != nil {
h.Name = (*byte)(unsafe.Pointer(&sa[0]))
h.Namelen = uint32(len(sa))
}
}
func (h *msghdr) controllen() int {
return int(h.Accrightslen)
}
func (h *msghdr) flags() int {
return int(NativeEndian.Uint32(h.Pad_cgo_2[:]))
}
```
|
Amaliegade 4 is a historic property located in the Frederiksstaden Quarter of central Copenhagen, Denmark. It was built for sugar manufacturer Christian Rønnenkamp in 1829 and was listed on the Danish Registry of Protected Buildings and Places in 1950. Other notable former residents include politician Christian Albrecht Bluhme and painter Viggo Johansen.
History
St. Croix Sugar House
In the site was originally part of the large corner property (Sankt Annæ Plads 18). In the new cadastre of 1756, the property was listed as No. 71 P. It was by then owned by Johan Just Bradt. On Christian Gedde's map of St. Ann's East Quarter, the property was marked as No. 323.
A sugar refinery known as St. Croix Sugar House was in approximately 1783 established at the site by Østersøisk-guineisk Handelsselskab. The sugar refinery was by 1787 managed by Niels Nielsen Hald. He lived in one of the apartments of the corner building with his five children (aged two to 14), a maid, three sugar refinery workers (svend)) and nine apprentices. Jeppe Prætorius was by 1787 among the residents.
The company was liquidated in 1787. The sugar refinery was continued by new owners but closed during the economic crisis of the war with England and the bombardment of Copenhagen in 1807.
Christian Rønnenkamp
The property was sold in public auction to Christian Rønnenkamp who already owned a sugar refinery in Dronningens Tværgade. The present building on the site (Amaliegade 4) was constructed for him in 1828-29. He both had his home in, and ran his business from, the new building. His sugar products were sold from a retail outlet on the ground floor.
In 1835, Rønnenkamp purchased the estates of Næsbygård and Bavelse from the Danish government. He then sold his property in Copenhagen and the sugar refinery closed but at least in the beginning he seems to have experimented with cultivation of sugar beets on his new estates.
1834 census
The property was home to 30 residents in six households at the 1734 census. Barbara Rosenkrantz født Prinsesse Af Wiasemskoj, a widow, resided on the ground floor with her niece
Mathilde Rosenkrantz, her lady's companion Emilie Labott, two male servants and three maids. Antoinette Wleugel (née Dorrien), widow of counter admiral Cornelius Wleugel, resided on the first floor with her daughter Caroline Wleugel, husjomfru Christiane Wolbye, a female cook, one male servant and one maid. Johannes Johansen, a commander in the Royal Danish Nacy, resided on the second floor with his wife Anna Johansen, a female cook, one male servant and one maid. Lars Petersen, a beer seller (øltaooer), resided in the basement with his wife Elisabeth Petersen and two daughters (aged 16 and 21). Christopher Korring, a workman, resided in the cross wing with his wife Enge Nielsen, their five-year-old daughter and the stableman Hans Jacob. Peter Jensen, a concierge, resided in the basement with his wife Karen Lorentzen and their five-year-old son.
18451900
The only residents of the building at the 1845 census were the concierge Georg Koefoed, his wife Sophie Koefoed, their two daughters (aged one and six) and one lodger.
Count Carl von Moltke was a resident of the building for around a year in 1855. His next home was at, Amaliegade 17. Frederik Marcus Knuth, Count of Knuthenborg,had his last cith home in the building. He died on 8 January 1856.
Former prime minister Christian Albrecht Bluhme lived at Amaliegade 4 in 1862–63.
The painter Viggo Johansen lived in the building from 1895 to 1900.
20th century
The company Valeur & Jensens was based in the building in 1901.
The building was owned by Arnold Louis Henri Gameél (1848-) in 1908. He was emplued in the firm A. C. Gamél. He was a board member of Københavns Asylselskab, He was the son of Antoine Cyrelle Gamél.
The retired politician and Cmanaging director Tyge Rothe (1877-1970) resided at Amaliegade 4B from 1941 to 1963.
N. Schiøtt & Hochbrandt, a shipping company, acquired the building in 1950 and made it their new headquarters.
Architecture
Amaliegade 4 consists of three storeys and a cellar and is five bays wide. A gateway on the right side of the building opens to a long, narrow courtyard. An 11-bay side wing (No. 4B) of the same age as the main wing extends along the north side of the courtyard. At the bottom of the courtyard is a four-bay rear wing (No. 4C) which dates from before 1828. The entire complex was listed on the Danish Registry of Protected Buildings and Places in 1950.
Today
The building is now owned by E/F Amaliegade 4 and used as office space.
References
External links
Source
Listed buildings and structures in Copenhagen
Residential buildings completed in 1755
Frederiksstaden
Sugar refineries in Copenhagen
|
```objective-c
#ifndef VIDEO_VOODOO_RENDER_H
#define VIDEO_VOODOO_RENDER_H
#if !(defined i386 || defined __i386 || defined __i386__ || defined _X86_ || defined _M_IX86 || defined __amd64__ || defined _M_X64)
# define NO_CODEGEN
#endif
#ifndef NO_CODEGEN
void voodoo_codegen_init(voodoo_t *voodoo);
void voodoo_codegen_close(voodoo_t *voodoo);
#endif
#define DEPTH_TEST(comp_depth) \
do { \
switch (depth_op) { \
case DEPTHOP_NEVER: \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
case DEPTHOP_LESSTHAN: \
if (!(comp_depth < old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_EQUAL: \
if (!(comp_depth == old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_LESSTHANEQUAL: \
if (!(comp_depth <= old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_GREATERTHAN: \
if (!(comp_depth > old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_NOTEQUAL: \
if (!(comp_depth != old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_GREATERTHANEQUAL: \
if (!(comp_depth >= old_depth)) { \
voodoo->fbiZFuncFail++; \
goto skip_pixel; \
} \
break; \
case DEPTHOP_ALWAYS: \
break; \
} \
} while (0)
#define APPLY_FOG(src_r, src_g, src_b, z, ia, w) \
do { \
if (params->fogMode & FOG_CONSTANT) { \
src_r += params->fogColor.r; \
src_g += params->fogColor.g; \
src_b += params->fogColor.b; \
} else { \
int fog_r, fog_g, fog_b, fog_a = 0; \
int fog_idx; \
\
if (!(params->fogMode & FOG_ADD)) { \
fog_r = params->fogColor.r; \
fog_g = params->fogColor.g; \
fog_b = params->fogColor.b; \
} else \
fog_r = fog_g = fog_b = 0; \
\
if (!(params->fogMode & FOG_MULT)) { \
fog_r -= src_r; \
fog_g -= src_g; \
fog_b -= src_b; \
} \
\
switch (params->fogMode & (FOG_Z | FOG_ALPHA)) { \
case 0: \
fog_idx = (w_depth >> 10) & 0x3f; \
\
fog_a = params->fogTable[fog_idx].fog; \
fog_a += (params->fogTable[fog_idx].dfog * ((w_depth >> 2) & 0xff)) >> 10; \
break; \
case FOG_Z: \
fog_a = (z >> 20) & 0xff; \
break; \
case FOG_ALPHA: \
fog_a = CLAMP(ia >> 12); \
break; \
case FOG_W: \
fog_a = CLAMP((w >> 32) & 0xff); \
break; \
} \
fog_a++; \
\
fog_r = (fog_r * fog_a) >> 8; \
fog_g = (fog_g * fog_a) >> 8; \
fog_b = (fog_b * fog_a) >> 8; \
\
if (params->fogMode & FOG_MULT) { \
src_r = fog_r; \
src_g = fog_g; \
src_b = fog_b; \
} else { \
src_r += fog_r; \
src_g += fog_g; \
src_b += fog_b; \
} \
} \
\
src_r = CLAMP(src_r); \
src_g = CLAMP(src_g); \
src_b = CLAMP(src_b); \
} while (0)
#define ALPHA_TEST(src_a) \
do { \
switch (alpha_func) { \
case AFUNC_NEVER: \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
case AFUNC_LESSTHAN: \
if (!(src_a < a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_EQUAL: \
if (!(src_a == a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_LESSTHANEQUAL: \
if (!(src_a <= a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_GREATERTHAN: \
if (!(src_a > a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_NOTEQUAL: \
if (!(src_a != a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_GREATERTHANEQUAL: \
if (!(src_a >= a_ref)) { \
voodoo->fbiAFuncFail++; \
goto skip_pixel; \
} \
break; \
case AFUNC_ALWAYS: \
break; \
} \
} while (0)
#define ALPHA_BLEND(src_r, src_g, src_b, src_a) \
do { \
int _a; \
int newdest_r = 0, newdest_g = 0, newdest_b = 0; \
\
switch (dest_afunc) { \
case AFUNC_AZERO: \
newdest_r = newdest_g = newdest_b = 0; \
break; \
case AFUNC_ASRC_ALPHA: \
newdest_r = (dest_r * src_a) / 255; \
newdest_g = (dest_g * src_a) / 255; \
newdest_b = (dest_b * src_a) / 255; \
break; \
case AFUNC_A_COLOR: \
newdest_r = (dest_r * src_r) / 255; \
newdest_g = (dest_g * src_g) / 255; \
newdest_b = (dest_b * src_b) / 255; \
break; \
case AFUNC_ADST_ALPHA: \
newdest_r = (dest_r * dest_a) / 255; \
newdest_g = (dest_g * dest_a) / 255; \
newdest_b = (dest_b * dest_a) / 255; \
break; \
case AFUNC_AONE: \
newdest_r = dest_r; \
newdest_g = dest_g; \
newdest_b = dest_b; \
break; \
case AFUNC_AOMSRC_ALPHA: \
newdest_r = (dest_r * (255 - src_a)) / 255; \
newdest_g = (dest_g * (255 - src_a)) / 255; \
newdest_b = (dest_b * (255 - src_a)) / 255; \
break; \
case AFUNC_AOM_COLOR: \
newdest_r = (dest_r * (255 - src_r)) / 255; \
newdest_g = (dest_g * (255 - src_g)) / 255; \
newdest_b = (dest_b * (255 - src_b)) / 255; \
break; \
case AFUNC_AOMDST_ALPHA: \
newdest_r = (dest_r * (255 - dest_a)) / 255; \
newdest_g = (dest_g * (255 - dest_a)) / 255; \
newdest_b = (dest_b * (255 - dest_a)) / 255; \
break; \
case AFUNC_ASATURATE: \
_a = MIN(src_a, 1 - dest_a); \
newdest_r = (dest_r * _a) / 255; \
newdest_g = (dest_g * _a) / 255; \
newdest_b = (dest_b * _a) / 255; \
break; \
} \
\
switch (src_afunc) { \
case AFUNC_AZERO: \
src_r = src_g = src_b = 0; \
break; \
case AFUNC_ASRC_ALPHA: \
src_r = (src_r * src_a) / 255; \
src_g = (src_g * src_a) / 255; \
src_b = (src_b * src_a) / 255; \
break; \
case AFUNC_A_COLOR: \
src_r = (src_r * dest_r) / 255; \
src_g = (src_g * dest_g) / 255; \
src_b = (src_b * dest_b) / 255; \
break; \
case AFUNC_ADST_ALPHA: \
src_r = (src_r * dest_a) / 255; \
src_g = (src_g * dest_a) / 255; \
src_b = (src_b * dest_a) / 255; \
break; \
case AFUNC_AONE: \
break; \
case AFUNC_AOMSRC_ALPHA: \
src_r = (src_r * (255 - src_a)) / 255; \
src_g = (src_g * (255 - src_a)) / 255; \
src_b = (src_b * (255 - src_a)) / 255; \
break; \
case AFUNC_AOM_COLOR: \
src_r = (src_r * (255 - dest_r)) / 255; \
src_g = (src_g * (255 - dest_g)) / 255; \
src_b = (src_b * (255 - dest_b)) / 255; \
break; \
case AFUNC_AOMDST_ALPHA: \
src_r = (src_r * (255 - dest_a)) / 255; \
src_g = (src_g * (255 - dest_a)) / 255; \
src_b = (src_b * (255 - dest_a)) / 255; \
break; \
case AFUNC_ACOLORBEFOREFOG: \
fatal("AFUNC_ACOLORBEFOREFOG\n"); \
break; \
} \
\
src_r += newdest_r; \
src_g += newdest_g; \
src_b += newdest_b; \
\
src_r = CLAMP(src_r); \
src_g = CLAMP(src_g); \
src_b = CLAMP(src_b); \
} while (0)
void voodoo_render_thread_1(void *param);
void voodoo_render_thread_2(void *param);
void voodoo_render_thread_3(void *param);
void voodoo_render_thread_4(void *param);
void voodoo_queue_triangle(voodoo_t *voodoo, voodoo_params_t *params);
extern int voodoo_recomp;
extern int tris;
static __inline void
voodoo_wake_render_thread(voodoo_t *voodoo)
{
thread_set_event(voodoo->wake_render_thread[0]); /*Wake up render thread if moving from idle*/
if (voodoo->render_threads >= 2)
thread_set_event(voodoo->wake_render_thread[1]); /*Wake up render thread if moving from idle*/
if (voodoo->render_threads == 4) {
thread_set_event(voodoo->wake_render_thread[2]); /*Wake up render thread if moving from idle*/
thread_set_event(voodoo->wake_render_thread[3]); /*Wake up render thread if moving from idle*/
}
}
static __inline void
voodoo_wait_for_render_thread_idle(voodoo_t *voodoo)
{
while (!PARAM_EMPTY(0) || (voodoo->render_threads >= 2 && !PARAM_EMPTY(1)) || (voodoo->render_threads == 4 && (!PARAM_EMPTY(2) || !PARAM_EMPTY(3))) || voodoo->render_voodoo_busy[0] || (voodoo->render_threads >= 2 && voodoo->render_voodoo_busy[1]) || (voodoo->render_threads == 4 && (voodoo->render_voodoo_busy[2] || voodoo->render_voodoo_busy[3]))) {
voodoo_wake_render_thread(voodoo);
if (!PARAM_EMPTY(0) || voodoo->render_voodoo_busy[0])
thread_wait_event(voodoo->render_not_full_event[0], 1);
if (voodoo->render_threads >= 2 && (!PARAM_EMPTY(1) || voodoo->render_voodoo_busy[1]))
thread_wait_event(voodoo->render_not_full_event[1], 1);
if (voodoo->render_threads == 4 && (!PARAM_EMPTY(2) || voodoo->render_voodoo_busy[2]))
thread_wait_event(voodoo->render_not_full_event[2], 1);
if (voodoo->render_threads == 4 && (!PARAM_EMPTY(3) || voodoo->render_voodoo_busy[3]))
thread_wait_event(voodoo->render_not_full_event[3], 1);
}
}
#endif /*VIDEO_VOODOO_RENDER_H*/
```
|
is a Japanese composer, arranger, and pianist best known for his work on the soundtracks for films and games.
Early life and education
Yusuke Hatano was born in New Jersey, returned to Japan, and studied high school in Singapore and Malaysia. During his university life at the University of Queensland in Brisbane, Australia, he won the Percy Brier Memorial Prize with his composition Oriental Isolation. Interested in a range of musical genres – from classical and jazz to contemporary and electronic music – Hatano spent the formative years of his career as a jazz pianist in Brisbane, before relocating to Hong Kong in 2011.
Career
Hatano's film compositions have attracted international attention, with his work for the film Full Strike debuting with a world premiere at the 2015 Osaka Asian Film Festival. Full Strike was the winner of Best Asian Film at the Neuchâtel International Fantastic Film Festival (NIFFF) 2015, and the official selection of Osaka Asian Film Festival 2015 and New York Asian Film Festival 2015. In 2017, Hatano was nominated for the Best Original Music for film "Soul Mate" at the 11th Asian Film Awards, and for the 36th Hong Kong Film Awards, he has been nominated for Best Original Film Song for film "Happiness", Best Original Music for film "Mad World" and Best Original Music for film "Soul Mate". In this year, Hatano won BEST ORIGINAL MUSIC at the Hong Kong Film Award, Los Angeles Golden Screen Award, and China Hamilton Behind the Scenes Award.
Hatano has written scores for films including "Mad World" directed by Chun Wong starring Eric Tsang and Shawn Yue, Soulmate produced by Peter Chan and Jo Jo Hui, directed by Derek Tsang starring Zhou Dongyu and Sichun Ma, Line Walker directed by Jazz Boon starring Nick Cheung, Louis Koo, Francis Ng, and Charmaine Sheh, Happiness directed by Andy Lo Yiu Fai starring Kara Hui and Carlos Chan which won the Asian CineVision 2016 Asian Media Humanitarian Award in New York as well as Best Actress and Best Supporting Actor at the 7th Macau International Movie Festival, GOOD TAKE! : Cement, GOOD TAKE! : The Banquet, GOOD TAKE! : GOOD TAKE, Full Strike, and Hardcore Comedy: Shocking Wet Dreams. He is also the composer for the Madhead app game Chronosgate. He has also composed music for pop artists including for Softhard concert promotion, Ken Hung, arranged music for Vivian Chan and AGA.
Performances
In 2012, Hatano was the featured pianist for charity jazz concert Love Affairs with Jolie. In 2015, he performed Leslie Cheung’s song 你在何地 at the Hong Kong Coliseum with director Derek Kwok at famous lyricist Calvin Poon's "P For Poon Party" Concert. In 2016, he performed with William So and 為你鍾情 composer Wong Ching Yu for Community Chest on TVB. In October 2016, charity jazz concert "Moments with Anne", with Yusuke Hatano as the director and pianist, had donated over $200,000 to the Community Chest of Hong Kong. As the music director and featured pianist, Yusuke performed for the countdown performance of 2019 to 2020 at MGM Cotai Macau.
Filmography
Games
Works for pop albums
(In Order of Starting Year of Affiliation)
Awards and nominations
References
External links
1986 births
21st-century Japanese male musicians
21st-century Japanese pianists
Japanese film score composers
Japanese male film score composers
Japanese male pianists
Japanese music arrangers
Japanese pianists
Living people
|
```ruby
# frozen_string_literal: true
class AddColorsToDecidimOrganization < ActiveRecord::Migration[5.2]
def change
add_column :decidim_organizations, :colors, :jsonb, default: {}
end
end
```
|
```go
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/scheduling/v1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type SchedulingV1Interface interface {
RESTClient() rest.Interface
PriorityClassesGetter
}
// SchedulingV1Client is used to interact with features provided by the scheduling.k8s.io group.
type SchedulingV1Client struct {
restClient rest.Interface
}
func (c *SchedulingV1Client) PriorityClasses() PriorityClassInterface {
return newPriorityClasses(c)
}
// NewForConfig creates a new SchedulingV1Client for the given config.
func NewForConfig(c *rest.Config) (*SchedulingV1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &SchedulingV1Client{client}, nil
}
// NewForConfigOrDie creates a new SchedulingV1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *SchedulingV1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new SchedulingV1Client for the given RESTClient.
func New(c rest.Interface) *SchedulingV1Client {
return &SchedulingV1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *SchedulingV1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
```
|
```java
/*
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.apache.rocketmq.tools.command.broker;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.srvutil.ServerUtil;
import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;
import org.apache.rocketmq.tools.command.CommandUtil;
import org.apache.rocketmq.tools.command.SubCommand;
import org.apache.rocketmq.tools.command.SubCommandException;
public class RemoveColdDataFlowCtrGroupConfigSubCommand implements SubCommand {
@Override
public String commandName() {
return "removeColdDataFlowCtrGroupConfig";
}
@Override
public String commandDesc() {
return "Remove consumer from cold ctr config.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "update which broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "update which cluster");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("g", "consumerGroup", true, "the consumer group will remove from the config");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String consumerGroup = commandLine.getOptionValue('g').trim();
if (commandLine.hasOption('b')) {
String brokerAddr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.removeColdDataFlowCtrGroupConfig(brokerAddr, consumerGroup);
System.out.printf("remove broker cold read threshold success, %s\n", brokerAddr);
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> masterSet = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
for (String brokerAddr : masterSet) {
try {
defaultMQAdminExt.removeColdDataFlowCtrGroupConfig(brokerAddr, consumerGroup);
System.out.printf("remove broker cold read threshold success, %s\n", brokerAddr);
} catch (Exception e) {
e.printStackTrace();
}
}
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
```
|
```go
package resinit
import "net"
// Work around a glibc bug where cached configs from /etc/resolv.conf can cause
// DNS failures after the network changes. This is a no-op on non-Linux
// platforms. See implementation details in resinit_linux.go. The Rust standard
// library contains a similar workaround:
// path_to_url#L186-L190
func ResInitIfDNSError(err error) {
// There are two error cases we need to handle, a raw *net.DNSError, and
// one wrapped in a *net.OpError. Detect that second case, and unwrap it.
if opErr, isOpErr := err.(*net.OpError); isOpErr {
err = opErr.Err
}
if _, isDNSError := err.(*net.DNSError); isDNSError {
resInit()
}
}
```
|
The Venetian Renaissance had a distinct character compared to the general Italian Renaissance elsewhere. The Republic of Venice was topographically distinct from the rest of the city-states of Renaissance Italy as a result of their geographic location, which isolated the city politically, economically and culturally, allowing the city the leisure to pursue the pleasures of art. The influence of Venetian art did not cease at the end of the Renaissance period. Its practices persisted through the works of art critics and artists proliferating its prominence around Europe to the 19th century.
Though a long decline in the political and economic power of the Republic began before 1500, Venice at that date remained "the richest, most powerful, and most populous Italian city" and controlled significant territories on the mainland, known as the terraferma, which included several small cities who contributed artists to the Venetian school, in particular Padua, Brescia and Verona. The Republic's territories also included Istria, Dalmatia and the islands now off the Croatian coast, who also contributed. Indeed, "the major Venetian painters of the sixteenth century were rarely natives of the city" itself, and some mostly worked in the Republic's other territories, or further afield. Much the same is true of the Venetian architects.
Though by no means an important centre of Renaissance humanism, Venice was the undoubted centre of book publishing in Italy, and very important in that respect; Venetian editions were distributed across Europe. Aldus Manutius was the most important printer/publisher, but by no means the only one.
Painting
Venetian painting was a major force in Italian Renaissance painting and beyond. Beginning with the work of Giovanni Bellini (c. 1430–1516) and his brother Gentile Bellini (c. 1429–1507) and their workshops, the major artists of the Venetian school included Giorgione (c. 1477–1510), Titian (c. 1489–1576), Tintoretto (1518–1594), Paolo Veronese (1528–1588) and Jacopo Bassano (1510–1592) and his sons. Considered to give primacy of colour over line, the tradition of the Venetian school contrasted with the Mannerism prevalent in the rest of Italy. The Venetian style exerted great influence upon the subsequent development of Western painting.
The harmonious concord and stability, and tight government control, of Venice was reflected in its paintings. Venice was widely known and revered for retaining the reputation of "unsullied liberty, unwavering religiosity, social harmony and unfailing peaceful intentions." The Republic of Venice was the leading city to uphold the utilisation of artistic patronage as an "arm of government" in its realisation of the potential of art as a political asset.
The rest of Italy tended to ignore or underestimate Venetian painting; Giorgio Vasari's neglect of the school in the first edition of his Lives of the Most Excellent Painters, Sculptors, and Architects in 1550 was so conspicuous that he realized he needed to visit Venice for extra material in his second edition of 1568. In contrast, foreigners, for whom Venice was often the first major Italian city visited, always had a great appreciation for it and, after Venice itself, the best collections are now in the large European museums rather than other Italian cities. At the top, princely, level, Venetian artists tended to be the most sought-after for commissions abroad, from Titian onwards, and in the 18th century most of the best painters spent significant periods abroad, generally with great success.
The traditional methods of the Byzantine style persisted even in the painting faction until around 1400 before the dominant style began to shift towards International Gothic and Italian Renaissance first brought into Venice by Paduan Guariento di Arpo, Gentile da Fabriano and Pisanello when they were commissioned to ornament the frescoes of the Doge's Palace.
The symbol of Venice is known to be the Virgin or the goddess Venus, but the Lion of Saint Mark is the oldest and most universal symbol of the Republic. The Lion is the figure which welcomes outsiders into the city, as it stands on the summit of the column on the Piazzetta, along with other public structures such as the city gates and palaces. Depictions of lions in paintings represented the significance of the saint as the patron of the city of Venice.
An example is the tempera on canvas by Vittore Carpaccio, Lion of Saint Mark, 1516. The powerful image of the lion portrayed with the divine marks of the halo and wings, points to an open book with the inscriptions "Peace unto you Mark, my evangelist" explicitly stating its protection and blessing over the city. The delineation of the lion’s front paws above land whilst the rear paws stand above the sea alludes to the dominance of Venice's reign over both territories as a fulfilment of Saint Mark's promise.
Architecture
Compared to the Renaissance architecture of other Italian cities, in Venice there was a degree of conservatism, especially in retaining the overall form of buildings, which in the city were usually replacements on a confined site, and in windows, where arched or round tops, sometimes with a classicized version of the tracery of Venetian Gothic architecture, remained far more heavily used than in other cities. The Doge's Palace was much rebuilt after fires, but mostly behind the Gothic facades.
The Venetian elite had a collective belief in the importance of architecture in bolstering confidence in the Republic, and a Senate resolution in 1535 noted that it was "the most beautiful and illustrious city which at present exists in the world". At the same time, overt competition between patrician families was discouraged, in favour of "harmonious equality", which applied to buildings as to other areas, and novelty for its own sake, or to recapture the glories of antiquity, was regarded with suspicion. Though visitors admired the rich ensembles, Venetian architecture did not have much influence beyond the republic's own possessions before Andrea Palladio (1508–1580), whose style of Palladian architecture became hugely influential some time after his death, not least in the English-speaking world.
Art and architecture were utilised as a powerful method to display the grandeur of the city of Venice. Architectures and structures such as St Mark's Basilica, Piazza San Marco and the Doge's Palace to name a few were "a visible expression of the idea of Venice." Venice was able to prolong its state of freedom for more than a thousand years and established a standing superior to that of Rome. The citizens of Venice believed themselves to be a pious nation for the lack of association with paganism in the past and claims that the city was founded on the Day of the Annunciation. Therefore, Venetians used pompous and intricate architectural designs to display the city's "pure, legitimate and undefiled" Christianity. The art during the Renaissance period of Venice continued to draw heavy influence from the styles of the Byzantine Empire.
Mauro Codussi (1440–1504) from Lombardy was one of the first architects to work in a Renaissance style in Venice, with his son Domenico assisting him and carrying on his practice after his death. His work respects and alludes to many elements of the Venetian Gothic, and harmonizes well with it. Other architects active in the early Renaissance period include Giorgio Spavento (active from 1489 or before, d. 1509), and Antonio Abbondi, often known as Scarpagnino (died 1549), who was active from at least 1505. San Sebastiano, Venice, begun 1506, is an early work. Both of these had many government commissions.
Jacopo Sansovino (1486–1570), also an important sculptor, was a Florentine with a successful career in Florence and then Rome. He fled to Venice after the catastrophic Sack of Rome in 1527 and in 1529 was appointed chief architect and superintendent of properties (Protomaestro or Proto) to the Procurators of San Marco. Before long he found a style that satisfied Venetian patrons and was "definitive for the entire subsequent history of Venetian architecture". He created the appearance of much of the area around the Piazza San Marco beyond Basilica of San Marco itself, designing the Biblioteca Marciana (1537 onwards) and mint or "Zecca" on the Piazzetta di San Marco. His palazzi include Palazzo Corner della Ca' Grande (1532 onwards) and Palazzo Dolfin Manin from 1536.
The Biblioteca Marciana is considered his "undoubted masterpiece", and a key work in Venetian Renaissance architecture. Palladio, who saw it being built, called it "probably the richest ever built from the days of ancients up to now", and it has been described by Frederick Hartt as "surely one of the most satisfying structures in Italian architectural history". It has an extremely prominent site, with the long facade facing the Doge's Palace across the Piazzetta di San Marco, and the shorter sides facing the lagoon and the Piazza San Marco.
Michele Sanmicheli (1484–1559) from Verona in the terraferma, trained further south, and on his return to Verona in 1527 was hired by the state as a military architect. Most of his work was fortifications and military or naval buildings around the Venetian territories, especially in Verona, but he also built a number of palaces that are very original, and take Venetian architecture into Mannerism. His work in Verona represents a group of buildings defining the city in a way comparable to Palladio's in Vicenza. The Palazzo Bevilacqua in Verona (begun 1529) is the most famous of these.
The principal architect of the later Venetian Renaissance, was Andrea Palladio (1508–1580), who was also the key figure in later Italian Renaissance architecture, and its most important writer on architecture. But apart from the two large churches of San Giorgio Maggiore (1566 on), and Il Redentore (1577 on), he designed relatively little in the city itself, for a number of reasons. He designed many villas in the Veneto, in Vicenza and a series of famous country houses, relatively small compared to some further south, for the Venetian elite. Palladio's style was later developed in the Palladian architecture of both Britain and the American colonies, and his Venetian window, with a central arched top, took a very Venetian element around the world. The World Heritage Site of the City of Vicenza and the Palladian Villas of the Veneto includes 23 buildings in the city, and 24 country villas.
Vincenzo Scamozzi (1548–1616) from Vicenza only moved to Venice in 1581, the year after Palladio's death. He designed the Procuratie Nuove on the Piazza San Marco, and completed many projects Palladio had left incomplete. His pupil Baldassare Longhena (1598–1682), who was for a change born in the city, in turn completed Scamozzi's projects and, while he introduced a full-blown Baroque architecture to Venice, many buildings, especially palaces, continued to develop a Baroque form of the Venetian Renaissance style.
Architectural publishing
Venice was a major European centre for all book printing publishing, and became the major centre for architectural publishing. Vitruvius is the only significant classical writer on architecture to survive, and his work De architectura was keenly studied by all Renaissance architects. Although the Latin text had been printed before, the first edition illustrated with woodcuts was produced by Fra Giovanni Giocondo in Venice in 1511; he had designed the Fondaco dei Tedeschi in 1505–08.
The "Seven Books" or Tutte l'opere d'architettura et prospetiva of Sebastiano Serlio (1475–1554) were also published in Venice, in several volumes from 1537 onwards. He had worked in the city as an architect, but left little mark. These were also heavily illustrated and became essential reading, and quickly copied and translated around Europe. The patrician humanist, clergyman and Venetian diplomat Daniele Barbaro was a patron of Palladio (Villa Barbaro), and Palladio illustrated his Italian translation of Vitruvius (1556). Palladio's own I quattro libri dell'architettura (1570), illustrated by himself, again had a huge influence across Europe.
Vincenzo Scamozzi's main book L’Idea dell’Architettura Universale was published in 1615, and essentially looks back to Palladio; it was influential in spreading Palladianism.
Music
In music history, the "Venetian School" was the body and work of composers working in Venice from about 1550 to around 1610, many working in the Venetian polychoral style. The Venetian polychoral compositions of the late sixteenth century were among the most famous musical works in Europe, and their influence on musical practice in other countries was enormous. The innovations introduced by the Venetian school, along with the contemporary development of monody and opera in Florence, together define the end of the musical Renaissance and the beginning of the musical Baroque.
As in other media, the rich patronage available in Venice drew composers from elsewhere in Italy, and beyond, to work in the city. Venice was also the European leader in publishing the new form of printed music scores.
Several major factors came together to create the Venetian School. The first was political: after the death of Pope Leo X in 1521 and the Sack of Rome in 1527, the long dominant musical establishment in Rome was eclipsed: many musicians either moved elsewhere or chose not to go to Rome, and Venice was one of several places to have an environment conducive to creativity.
Another factor, possibly the most important, was the existence of the splendid Basilica San Marco di Venezia (commonly known as St. Mark's), with its unique interior with opposing choir lofts. Because of the spacious architecture of this basilica, it was necessary to develop a musical style which exploited the sound-delay to advantage, rather than fought against it: thus the Venetian polychoral style was developed, the grand antiphonal style in which groups of singers and instruments played sometimes in opposition, and sometimes together, united by the sound of the organ. The first composer to make this effect famous was Adrian Willaert, who became maestro di cappella of St. Mark's in 1527, and remained in the position until his death in 1562. Gioseffo Zarlino, one of the most influential writers on music of the age, called Willaert "the new Pythagoras," and Willaert's influence was profound, not only as a composer but as a teacher, since most of the Venetians who followed studied with him.
In the 1560s, two distinct groups developed within the Venetian school: a progressive group, led by Baldassare Donato, and a conservative group, led by Zarlino who was then maestro di cappella. Members of the conservative branch tended to follow the style of Franco-Flemish polyphony, and included Cipriano de Rore, Zarlino, and Claudio Merulo; members of the progressive group included Donato, Giovanni Croce, and later Andrea and Giovanni Gabrieli. An additional point of contention between the two groups was whether or not Venetians—or at least Italians—should be given the top job of maestro di cappella at St. Mark's. Eventually the group favoring local talent prevailed, ending the dominance of foreign musicians in Venice; in 1603, Giovanni Croce was appointed to the job, followed by Giulio Cesare Martinengo in 1609.
The peak of development of the Venetian School was in the 1580s, when Andrea and Giovanni Gabrieli composed enormous works for multiple choirs, groups of brass and string instruments, and organ. These works are the first to include dynamics, and are among the first to include specific instructions for ensemble instrumentation. Organists working at the same time included Claudio Merulo and Girolamo Diruta; they began to define an instrumental style and technique which moved to northern Europe in the succeeding generations, culminating in the works of Sweelinck, Buxtehude, and eventually J.S. Bach.
Venetian Guilds
The Venetian community in the Renaissance was constructed on the emphasis on the relationships between neighbours, ritual brothers and kinsmen all living together in equality from the upper and lower social class. Many scholars believe that the stability, prosperity and political security was significantly due to their notion of working together and communal action. Petrarch, in the mid-fourteenth century, described Venice as "solidly built on marble but standing more solid on a foundation of civil concord." The stability of Venice was escalated through the system of guilds. Dennis Romano wrote in his book, Patricians and Popolani: "Nowhere in Venetian society was the emphasis on community and solidarity more pronounced than in the guilds." By the mid-fourteenth century, Venice had founded more than fifty guilds that helped to achieve cooperation from both members of the government and the guild. The government was shrewd to practice fair justice equally to all social levels, which prevented riots or political protests. Depending on the artisan's trade and specialty, individuals joined the corresponding guild group upon a pledge of allegiance to the doge. There were many types of guilds such as the stonemasons, woodcarvers, glassmakers, furriers and wool industries.
"Arte dei depentori" is a painter's guild which is the oldest known guild dating back to 1271. This groups are not exclusive to painters but also includes gilders, textiles designers, embroiderers, gold-tooled leather artisans, playing-card makers, mask makers, and sign painters. The stratification of the guilds was divided into master craftsmen and workers or apprentices. The masters were in charge of production processes whilst depending on their competency and skills, the workers contributed to production of goods or took on trivial chores such as sweeping the floor or grinding pigments. The functions of the guilds were both political and cultural, contributing their talents during special celebrations and ceremonies. On special events such as the Feast of Saint Mark, members of each guild participated in these events for trading of expensive items such as paintings, furniture, carpets, objects of glass, gold, and textiles.
Notes
References
Burns, Howard, "Architecture", in Jane Martineau (ed), The Genius of Venice, 1500–1600, 1983, Royal Academy of Arts, London.
Freedberg, Sydney J. Painting in Italy, 1500–1600, 3rd edn. 1993, Yale,
Gardner's: Art Through the Ages—International Edition, Brace Harcourt Jovanovich, 9th edition, 1991.
Hartt, Frederick, History of Italian Renaissance Art, (2nd edn.) 1987, Thames & Hudson (US Harry N Abrams),
Howard, Deborah (2004), The Architectural History of Venice (2nd edn), Yale UP,
The Prado Guide, Ed. Maria Dolores Jimenez-Blanco, Museo Nacional del Prado, English 2nd revised edition, 2009.
Romano, Dennis, "Patricians and Popolani: the Social Foundations of the Venetian Renaissance State," (Baltimore: Johns Hopkins University Press, 1987)
Steer, John, Venetian painting: A concise history, 1970, London: Thames and Hudson (World of Art),
Summerson, John, The Classical Language of Architecture, 1980 edition, Thames and Hudson World of Art series,
Wittkower, Rudolf, Art and Architecture in Italy, 1600–1750, Penguin/Yale History of Art, 3rd edition, 1973,
Wolters, Wolfgang and Huse, Norbert, The Art of Renaissance Venice: Architecture, Sculpture, and Painting, 1460–1590, 1993, University of Chicago Press
Renaissance by country
14th century in the Republic of Venice
15th century in the Republic of Venice
16th century in the Republic of Venice
17th century in the Republic of Venice
Culture of the Republic of Venice
|
```javascript
Object.defineProperty(exports,"__esModule",{value:true});var _jsxFileName='src/components/Backdrop.js';var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _react=require('react');var _react2=_interopRequireDefault(_react);var _reactNative=require('react-native');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var babelPluginFlowReactPropTypes_proptype_BackdropProps=require('../type').babelPluginFlowReactPropTypes_proptype_BackdropProps||require('prop-types').any;var Backdrop=function(_Component){_inherits(Backdrop,_Component);function Backdrop(){var _ref;var _temp,_this,_ret;_classCallCheck(this,Backdrop);for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return _ret=(_temp=(_this=_possibleConstructorReturn(this,(_ref=Backdrop.__proto__||Object.getPrototypeOf(Backdrop)).call.apply(_ref,[this].concat(args))),_this),_this.setOpacity=function(value){_this.opacity.setValue(value);},_this.opacity=new _reactNative.Animated.Value(0),_temp),_possibleConstructorReturn(_this,_ret);}_createClass(Backdrop,[{key:'componentDidUpdate',value:function componentDidUpdate(prevProps){var _props=this.props,visible=_props.visible,useNativeDriver=_props.useNativeDriver,opacity=_props.opacity,duration=_props.animationDuration;if(prevProps.visible!==visible){var toValue=visible?opacity:0;_reactNative.Animated.timing(this.opacity,{toValue:toValue,duration:duration,useNativeDriver:useNativeDriver}).start();}}},{key:'render',value:function render(){var _props2=this.props,onPress=_props2.onPress,pointerEvents=_props2.pointerEvents,backgroundColor=_props2.backgroundColor;var opacity=this.opacity;return _react2.default.createElement(_reactNative.Animated.View,{pointerEvents:pointerEvents,style:_reactNative.StyleSheet.flatten([_reactNative.StyleSheet.absoluteFill,{backgroundColor:backgroundColor,opacity:opacity}]),__source:{fileName:_jsxFileName,lineNumber:44}},_react2.default.createElement(_reactNative.TouchableOpacity,{onPress:onPress,style:_reactNative.StyleSheet.absoluteFill,__source:{fileName:_jsxFileName,lineNumber:51}}));}}]);return Backdrop;}(_react.Component);Backdrop.defaultProps={backgroundColor:'#000',opacity:0.5,animationDuration:2000,visible:false,useNativeDriver:true,onPress:function onPress(){}};Backdrop.propTypes=babelPluginFlowReactPropTypes_proptype_BackdropProps;exports.default=Backdrop;
```
|
Jawei Chiefdom is a chiefdom in Kailahun District of Sierra Leone with a population of 42,635. Its largest town and headquarters is Daru.
Geography
Jawei Chiefdom is located on the southwestern edge of Kailahun District, bordering Dama Chiefdom and Gaura Chiefdom of Kenema District to the southwest. Jawei borders Jaluahun Chiefdom to the northwest, Mandu Chiefdom to the northeast, and Malema Chiefdom to the southeast. The Moa River transects the chiefdom.
Settlements
The other important town in Jawei Chiefdom is Benduma. Villages in Jawei dChiefdom include Bombohun, Nyedehun, Gbajorma, Tomboma, Folu, Giehun, Guma,Karlu, Karlu Kambama, Kutoma, Manowah, Mamabu, Bembeyeima, Pellie and Potoru, nyeama
Economy
The economy is primarily agricultural; however there is some mining. The primary export is palm oil.
Civil war
During the 1991-2002 civil war various villages in northern Jawei Chiefdom were occupied by the Revolutionary United Front (RUF) and National Patriotic Front of Liberia ((NPFL)) during their initial on-thrust in Spring 1991. The RUF got as far as Benduma, but did not attack Daru or the Moa Barracks across the river, where the Sierra Leone Army (SLA) was based. Guinean troops soon arrived in Daru to support the SLA. The Guineans attacked and drove the RUF out of Benduma, after which battle neither side stationed troops there. In June 1991, RUF and NPFL attacked the Moa Barracks at Daru, but despite the gallantry of the NPFL commander, who was killed on the bridge over the Moa, the Guinean troops and the SLA turned back the assault. Fighting continued in Jawei Chiefdom over the next two years with little change in territory. In December 1992, after an almost successful RUF attack on nearby Segbwema in Jaluahun Chiefdom, some of the Guinean troops were sent from the Moa Barracks to Segbwema. At that same time local hunters, often members of secret hunting societies, began to form into auxiliary units to assist the SLA in Jawei Chiefdom. Finally in May 1993, the SLA with the assistance of these "civilian" units were able to dislodge the RUF from their bases in northern Jawei.
Nonetheless, RUF guerrilla warfare continued in the chiefdom and it was still considered unsafe during the February 1996 elections. Shortly after the election, local chiefs were encouraged to send their young men to Kamajor society initiations after which they were formed into Civil Defence Forces (CDF) units. Prior to this the local hunters were under the command of their own chiefs, but this changed them into a state force. With this new status the Jawei CDF units began attacking RUF positions without SLA support. By January 1997, some Jawei forces were fighting as far away as Upper Bambara Chiefdom. By September 1997 the Jawei Kamajors had all of Jawei Chiefdom under their control and the guerrilla war there ceased.
In March 1998, Nigerian ECOMOG forces arrived in Daru to support the Kamajors. But this had the effect of drawing combined RUF and Armed Forces Revolutionary Council (AFRC) forces to attack Daru which they did several times during 1998 and early 1999. The last such attack was on 7 July 1999, just two days before the ceasefire mandated in the Lomé Peace Accord. But the fighting continued anyway with the Kamajors attacking RUF/AFRC positions at Daru Junction on 17 July, driving them out. But the RUF/AFRC recaptured Daru Junction a month later.
In Spring 2000 with the arrival of UNAMSIL personnel disarmament started in Jawei Chiefdom, where a Disarmament, Demobilisation and Reintegration Camp had been set up in November the previous year. But it was interrupted in May by resistance to the northeast. The process was only restarted in late July.
Recent history
A boundary dispute between Jawei and Malema Chiefdom, arising in 2004 out of the dislocations suffered during the civil war, was settled in 2007 at the direction of the president Bai Koroma.
In September 2009 the chiefdom suffered serve and unusual flooding as the Moa River over flowed. Chief Fadah Kallon said that it was the first such flood ever to hit the chiefdom. The flood has been partially attributed to the chronic deforestation that occurs in Sierra Leone.
Notes
Chiefdoms of Sierra Leone
Eastern Province, Sierra Leone
|
```html
<p>{{ message | async }}</p>
```
|
```julia
#!/usr/bin/env julia
#
# @license Apache-2.0
#
#
#
# path_to_url
#
# Unless required by applicable law or agreed to in writing, software
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import Distributions: cdf, Cauchy
import JSON
"""
gen( x, x0, gamma, name )
Generate fixture data and write to file.
# Arguments
* `x`: input value
* `x0`: location parameter
* `gamma`: scale parameter
* `name::AbstractString`: output filename
# Examples
``` julia
julia> x = rand( 1000 ) .* 100.0;
julia> x0 = rand( 1000 ) .* 25.0;
julia> gamma = rand( 1000 ) .* 20.0;
julia> gen( x, x0, gamma, \"data.json\" );
```
"""
function gen( x, x0, gamma, name )
z = Array{Float64}( undef, length(x) );
for i in eachindex(x)
z[ i ] = cdf( Cauchy( x0[i], gamma[i] ), x[i] );
end
# Store data to be written to file as a collection:
data = Dict([
("x", x),
("x0", x0),
("gamma", gamma),
("expected", z)
]);
# Based on the script directory, create an output filepath:
filepath = joinpath( dir, name );
# Write the data to the output filepath as JSON:
outfile = open( filepath, "w" );
write( outfile, JSON.json(data) );
write( outfile, "\n" );
close( outfile );
end
# Get the filename:
file = @__FILE__;
# Extract the directory in which this file resides:
dir = dirname( file );
# Random (negative median):
x = rand( 1000 ) .* 100.0 .- 200.0;
x0 = rand( 1000 ) .* -50.0;
gamma = rand( 1000 ) .* 20.0;
gen( x, x0, gamma, "negative_median.json" );
# Random (positive median):
x = rand( 1000 ) .* 100.0 .- 200.0;
x0 = rand( 1000 ) .* 50.0;
gamma = rand( 1000 ) .* 20.0;
gen( x, x0, gamma, "positive_median.json" );
# Random (large gamma):
x = rand( 1000 ) .* 2.0;
x0 = rand( 1000 ) .* 1.0;
gamma = rand( 1000 ) .* 50.0;
gen( x, x0, gamma, "large_gamma.json" );
```
|
RL, Rl or rl may refer to:
In arts and entertainment
Radio Liberty, US broadcaster
Rocket League, a video game
Businesses and organizations
Ralph Lauren Corporation (NYSE ticker)
Réseau Luxembourgeois des Amateurs d'Ondes Courtes, an amateur radio organization in Luxembourg
Royal Phnom Penh Airways (IATA code)
People known by the given initials
R. L. Huggar, an R&B singer
RL Grime, American musician, producer
R. L. Stine, American author
In science and technology
RL (complexity), a complexity class of mathematical problems
RL circuit, a circuit with a resistor and an inductor
Reinforcement learning, an area of machine learning
Reduced level, elevations of survey points with reference to a common assumed datum.
Rhyncholaelia (Rl.), a genus of orchids
Other uses
Rl (digraph) in Australian Aboriginal languages
Acura RL, an automobile
Real life, Internet term
Registered Locksmith, US certification
Report Long, a type of US Congressional Research Service Report
Rugby league, a sport
|
```c++
#include "LoginDialog.hpp"
#include "GUI_App.hpp"
#include "wxExtensions.hpp"
#include "GUI.hpp"
#include "I18N.hpp"
#include "format.hpp"
namespace Slic3r {
namespace GUI {
LoginDialog::LoginDialog(wxWindow* parent, UserAccount* user_account)
// TRN: This is the dialog title.
: DPIDialog(parent, wxID_ANY, ("Prusa Account"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
, p_user_account(user_account)
{
const int em = wxGetApp().em_unit();
bool logged = p_user_account->is_logged();
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
// sizer with black border
wxStaticBoxSizer* static_box_sizer = new wxStaticBoxSizer(wxVERTICAL, this, ("Log into your Prusa Account"));
static_box_sizer->SetMinSize(wxSize(em * 30, em * 15));
// avatar
boost::filesystem::path path = p_user_account->get_avatar_path(logged);
ScalableBitmap logo(this, path, wxSize(em * 10, em * 10));
m_avatar_bitmap = new wxStaticBitmap(this, wxID_ANY, logo.bmp(), wxDefaultPosition, wxDefaultSize);
static_box_sizer->Add(m_avatar_bitmap, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 10);
// username
const wxString username = GUI::format_wxstr("%1%", logged ? from_u8(p_user_account->get_username()) : ("Anonymous"));
m_username_label = new wxStaticText(this, wxID_ANY, username, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);
m_username_label->SetFont(m_username_label->GetFont().Bold());
static_box_sizer->Add(m_username_label, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5);
// login button
m_login_button_id = NewControlId();
m_login_button = new wxButton(this, m_login_button_id, logged ? ("Log out") : ("Log in"));
static_box_sizer->Add(m_login_button, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 10);
// TODO: why is m_login_button always hovered?
main_sizer->Add(static_box_sizer, 1, wxEXPAND | wxALL, 10);
// continue button
m_continue_button = new wxButton(this, wxID_OK, logged ? ("Continue") : ("Continue without Prusa Account"));
main_sizer->Add(m_continue_button, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 10);
SetSizerAndFit(main_sizer);
m_login_button->Bind(wxEVT_BUTTON, [user_account = p_user_account](wxCommandEvent& event) {
if (!user_account->is_logged())
user_account->do_login();
else
user_account->do_logout();
});
wxGetApp().UpdateDlgDarkUI(this);
SetFocus();
}
LoginDialog::~LoginDialog()
{
}
void LoginDialog::update_account()
{
bool logged = p_user_account->is_logged();
const wxString username = GUI::format_wxstr("%1%", logged ? from_u8(p_user_account->get_username()) : ("Anonymous"));
m_username_label->SetLabel(username);
boost::filesystem::path path = p_user_account->get_avatar_path(logged);
if (boost::filesystem::exists(path)) {
const int em = wxGetApp().em_unit();
ScalableBitmap logo(this, path, wxSize(em * 10, em * 10));
m_avatar_bitmap->SetBitmap(logo.bmp());
}
m_login_button->SetLabel(logged ? ("Log out") : ("Log in"));
m_continue_button->SetLabel(logged ? ("Continue") : ("Continue without Prusa Account"));
// TODO: resize correctly m_continue_button
//m_continue_button->Fit();
Fit();
Refresh();
}
void LoginDialog::on_dpi_changed(const wxRect& suggested_rect)
{
SetFont(wxGetApp().normal_font());
const int em = em_unit();
msw_buttons_rescale(this, em, { wxID_OK, m_login_button_id});
Fit();
Refresh();
}
}}// Slicer::GUI
```
|
```javascript
const _ = require('lodash')
const keygen = require('browser/lib/keygen')
const resolveStorageData = require('./resolveStorageData')
const resolveStorageNotes = require('./resolveStorageNotes')
const consts = require('browser/lib/consts')
const path = require('path')
const CSON = require('@rokt33r/season')
/**
* @param {Object}
* name, path, type
*
* 1. check if BoostnoteJSON can be created
* if the file doesn't exist or isn't valid, try to rewrite it.
* if the rewriting failed, throw Error
* 2. save metadata to localStorage
* 3. fetch notes & folders
* 4. return `{storage: {...} folders: [folder]}`
*/
function addStorage(input) {
if (!_.isString(input.path)) {
return Promise.reject(new Error('Path must be a string.'))
}
let rawStorages
try {
rawStorages = JSON.parse(localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('invalid storages')
} catch (e) {
console.warn(e)
rawStorages = []
}
let key = keygen()
while (rawStorages.some(storage => storage.key === key)) {
key = keygen()
}
let newStorage = {
key,
name: input.name,
type: input.type,
path: input.path,
isOpen: false
}
return Promise.resolve(newStorage)
.then(resolveStorageData)
.then(function saveMetadataToLocalStorage(resolvedStorage) {
newStorage = resolvedStorage
rawStorages.push({
key: newStorage.key,
type: newStorage.type,
name: newStorage.name,
path: newStorage.path,
isOpen: false
})
localStorage.setItem('storages', JSON.stringify(rawStorages))
return newStorage
})
.then(function(storage) {
return resolveStorageNotes(storage).then(notes => {
let unknownCount = 0
notes.forEach(note => {
if (!storage.folders.some(folder => note.folder === folder.key)) {
unknownCount++
storage.folders.push({
key: note.folder,
color: consts.FOLDER_COLORS[(unknownCount - 1) % 7],
name: 'Unknown ' + unknownCount
})
}
})
if (unknownCount > 0) {
CSON.writeFileSync(
path.join(storage.path, 'boostnote.json'),
_.pick(storage, ['folders', 'version'])
)
}
return notes
})
})
.then(function returnValue(notes) {
return {
storage: newStorage,
notes
}
})
}
module.exports = addStorage
```
|
Krutoyak () is a rural locality (a village) in Bereznikovskoye Rural Settlement, Sobinsky District, Vladimir Oblast, Russia. The population was 77 as of 2010.
Geography
Krutoyak is located on the Klyazma River, 8 km southwest of Sobinka (the district's administrative centre) by road. Perebor is the nearest rural locality.
References
Rural localities in Sobinsky District
|
Methylnaphthalene may refer to:
1-Methylnaphthalene
2-Methylnaphthalene
|
```sqlpl
DROP TABLE IF EXISTS t;
DROP TABLE IF EXISTS nt;
DROP TABLE IF EXISTS ntxy;
CREATE TABLE t (x String) ENGINE = Log();
CREATE TABLE nt (x Nullable(String)) ENGINE = Log();
CREATE TABLE ntxy (x Nullable(String), y Nullable(String)) ENGINE = Log();
INSERT INTO t (x) VALUES ('id'), ('1');
INSERT INTO nt (x) VALUES ('id'), (NULL), ('1');
INSERT INTO ntxy (x, y) VALUES ('id', 'id'), (NULL, NULL), ('1', '1');
SET join_use_nulls = 1;
SELECT 'on with or';
SELECT 'n rj n', t1.x, t2.x FROM nt AS t1 RIGHT JOIN ntxy AS t2 ON t1.x = t2.x OR t1.x = t2.y ORDER BY t1.x;
SELECT 'n a rj n', t1.x, t2.x FROM nt AS t1 ANY RIGHT JOIN ntxy AS t2 ON t1.x = t2.x OR t1.x = t2.y ORDER BY t1.x;
SELECT 'n fj n', t1.x, t2.x FROM nt AS t1 FULL JOIN ntxy AS t2 ON t1.x = t2.x OR t1.x = t2.y ORDER BY t1.x;
SELECT 't rj n', t1.x, t2.x FROM t AS t1 RIGHT JOIN ntxy AS t2 ON t1.x = t2.x OR t1.x = t2.y ORDER BY t1.x;
SELECT 't fj n', t1.x, t2.x FROM t AS t1 FULL JOIN ntxy AS t2 ON t1.x = t2.x OR t1.x = t2.y ORDER BY t1.x;
SELECT 'n rj t', t1.x, t2.x FROM ntxy AS t1 RIGHT JOIN t AS t2 ON t1.x = t2.x OR t1.y = t2.x ORDER BY t1.x;
SELECT 'n a rj t', t1.x, t2.x FROM ntxy AS t1 ANY RIGHT JOIN t AS t2 ON t1.x = t2.x OR t1.y = t2.x ORDER BY t1.x;
SELECT 'n fj t', t1.x, t2.x FROM ntxy AS t1 FULL JOIN t AS t2 ON t1.x = t2.x OR t2.x = t1.y ORDER BY t1.x;
SELECT 'n fj t', t1.x, t2.x FROM ntxy AS t1 FULL JOIN t AS t2 ON t2.x = t1.y OR t1.x = t2.x ORDER BY t1.x;
DROP TABLE t;
DROP TABLE nt;
DROP TABLE ntxy;
```
|
```php
<?php
/**
*/
?>
<!DOCTYPE html>
<html class="ng-csp" data-placeholder-focus="false" lang="<?php p($_['language']); ?>" data-locale="<?php p($_['locale']); ?>" translate="no" >
<head data-requesttoken="<?php p($_['requesttoken']); ?>">
<meta charset="utf-8">
<title>
<?php p($theme->getTitle()); ?>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0<?php if (isset($_['viewport_maximum_scale'])) {
p(', maximum-scale=' . $_['viewport_maximum_scale']);
} ?>">
<meta name="theme-color" content="<?php p($theme->getColorPrimary()); ?>">
<meta name="csp-nonce" nonce="<?php p($_['cspNonce']); /* Do not pass into "content" to prevent exfiltration */ ?>">
<link rel="icon" href="<?php print_unescaped(image_path('core', 'favicon.ico')); /* IE11+ supports png */ ?>">
<link rel="apple-touch-icon" href="<?php print_unescaped(image_path('core', 'favicon-touch.png')); ?>">
<link rel="mask-icon" sizes="any" href="<?php print_unescaped(image_path('core', 'favicon-mask.svg')); ?>" color="<?php p($theme->getColorPrimary()); ?>">
<?php emit_css_loading_tags($_); ?>
<?php emit_script_loading_tags($_); ?>
<?php print_unescaped($_['headers']); ?>
</head>
<body id="body-public" class="layout-base">
<?php include 'layout.noscript.warning.php'; ?>
<?php include 'layout.initial-state.php'; ?>
<div id="content" class="app-public" role="main">
<?php print_unescaped($_['content']); ?>
</div>
</body>
</html>
```
|
This is a list of ministers of internal affairs of the Republic of Cyprus since the independence in 1960:
Notes
See also
Ministry of Interior (Cyprus)
External links
Official list on the Web site of the Ministry
Internal affairs
el:Υπουργείο Εσωτερικών (Κύπρος)
|
Guillermo Mackenna (born 1974) is a Chilean lawyer who served as the president of Blanco y Negro from March 2010 to March 2011.
In 2018, he was proposed as candidate for being member of the Patrimonial Court of the Asociación Nacional de Fútbol Profesional (ANFP), which was dismissed.
References
External links
Profile at VialAbogados
1974 births
Living people
Chilean businesspeople
Chilean people of Irish descent
Gabriela Mistral University alumni
Northwestern University alumni
Presidents of Blanco y Negro S.A.
Guillermo
Chilean lawyers
|
CBWFT-DT (channel 3) is an Ici Radio-Canada Télé station in Winnipeg, Manitoba, Canada, serving the province's Franco-Manitoban population. It has common ownership with CBC Television station CBWT-DT (channel 6). Both stations share studios on Portage Avenue and Young Street in Downtown Winnipeg, while CBWFT-DT's transmitter is located atop the Richardson Building.
History
The CBC announced on February 17, 1959, that they would appear before the BBG (predecessor to the CRTC) in Ottawa on March 18 to apply for a license to extend Radio-Canada's television signal into the Winnipeg area.
CBWFT first signed on at 3 p.m. on April 24, 1960, using channel 6 with an EIRP of 2,800 watts. At the same time two VTRs, worth $75,000 each were installed at the station. It was the first francophone television station west of Ontario. Its opening broadcast was a ceremony held at the Notre Dame Auditorium in St. Boniface. Dignitaries included in attendance were Lieutenant-Governor Errick Willis; Premier Duff Roblin; CBC President Alphonse Ouimet; Marcel Ouimet, general manager of Radio-Canada; J. R. Finlay, CBC Prairie Region Director; and Leo Remillard, CBWFT's program director.
At first, CBWFT's broadcast day ran between 6 and 12 hours, with a longer programming day on weekends. Over the years, this was extended to encompass most of the day. Initially, Radio-Canada's microwave link did not reach as far as Winnipeg. Instead, videotapes and films were "bicycled" from Montreal and delayed by one week, except for news and live events like La Soirée du hockey.
On November 15, 1964, it swapped frequencies with CBWT and a higher-powered transmitter was installed at the new site near Starbuck. From 1964 till the early 1980s, it referred to itself simply as "CBWFT canal 3 Winnipeg". During the early 1980s, CBWFT was known as "CBWFT 3/10", signifying its position on Channel 3, Cable 10 in Winnipeg. On January 1, 1986, it became known as "Radio-Canada Manitoba".
By October 31, 1966, CBWFT was connected to the Radio-Canada microwave signal, allowing the live feed of Le Téléjournal at 6 p.m. Prior to this the newscast consisted of Radio-Canada's radio news with locally inserted images. Several months after the first Anik A satellite was launched in 1972, CBWFT switched to the satellite feed of Radio-Canada and dropped the microwave feed, except to distribute its signal within its coverage area, Manitoba and Northwestern Ontario, and part of Saskatchewan. In 1976, a rebroadcaster of CBWFT programming in Regina became CBKFT. In 1985, CBKFT was issued a separate license to broadcast its own Ce Soir regional news program.
News operation
In 2005, the long-running Ce Soir news program was renamed to Le Téléjournal, which is the same name of the French national news program on Radio-Canada. The Téléjournal local edition is normally 30 minutes in length, however the Wednesday edition is 60 minutes. The program is also rebroadcast at 11 p.m.
As of 2023, the Monday to Thursday bulletins are presented by Godlove Kamwa and Friday to Sunday by Cédrick Noufele.
Technical information
Subchannel
Analogue-to-digital conversion
CBWFT switched from analogue to digital television broadcasting on December 9, 2011, from its Winnipeg transmitter atop the Richardson Building, after several delays, due to an "unforeseen delay that is outside of the Corporation's control," involving antenna erection. CBWFT's digital signal operates on UHF channel 51. Through the use of PSIP, digital television receivers will display CBWFT's virtual channel as 3.1.
Transmitters
CBWFT operated 11 analogue television retransmitters in Manitoba (e.g. Brandon) and Northwestern Ontario (in the parts of that region which fall in the Central Time Zone, e.g. Kenora). Due to federal funding reductions to the CBC, in April 2012, the CBC responded with substantial budget cuts, which included shutting down CBC's and Radio-Canada's remaining analog transmitters on July 31, 2012. None of CBC or Radio-Canada's television rebroadcasters were converted to digital.
Manitoba
Northwest Ontario
References
External links
ICI Manitoba
BWFT-DT
BWFT-DT
Television channels and stations established in 1960
Franco-Manitoban culture
1960 establishments in Manitoba
|
```swift
//
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
import UIKit
import FirebaseFirestore
import SDWebImage
class RestaurantDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
NewReviewViewControllerDelegate {
var titleImageURL: URL?
var restaurant: Restaurant?
var restaurantReference: DocumentReference?
var localCollection: LocalCollection<Review>!
static func fromStoryboard(_ storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil))
-> RestaurantDetailViewController {
let controller = storyboard
.instantiateViewController(
withIdentifier: "RestaurantDetailViewController"
) as! RestaurantDetailViewController
return controller
}
@IBOutlet var tableView: UITableView!
@IBOutlet var titleView: RestaurantTitleView!
let backgroundView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
title = restaurant?.name
navigationController?.navigationBar.tintColor = UIColor.white
backgroundView.image = UIImage(named: "pizza-monster")!
backgroundView.contentScaleFactor = 2
backgroundView.contentMode = .bottom
tableView.backgroundView = backgroundView
tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 140
let query = restaurantReference!.collection("ratings")
localCollection = LocalCollection(query: query) { [unowned self] changes in
if self.localCollection.count == 0 {
self.tableView.backgroundView = self.backgroundView
return
} else {
self.tableView.backgroundView = nil
}
var indexPaths: [IndexPath] = []
// Only care about additions in this block, updating existing reviews probably not important
// as there's no way to edit reviews.
for addition in changes.filter({ $0.type == .added }) {
let index = self.localCollection.index(of: addition.document)!
let indexPath = IndexPath(row: index, section: 0)
indexPaths.append(indexPath)
}
self.tableView.insertRows(at: indexPaths, with: .automatic)
}
}
deinit {
localCollection.stopListening()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
localCollection.listen()
titleView.populate(restaurant: restaurant!)
if let url = titleImageURL {
titleView.populateImage(url: url)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
set {}
get {
return .lightContent
}
}
@IBAction func didTapAddButton(_ sender: Any) {
let controller = NewReviewViewController.fromStoryboard()
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return localCollection.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewTableViewCell",
for: indexPath) as! ReviewTableViewCell
let review = localCollection[indexPath.row]
cell.populate(review: review)
return cell
}
// MARK: - NewReviewViewControllerDelegate
func reviewController(_ controller: NewReviewViewController,
didSubmitFormWithReview review: Review) {
guard let reference = restaurantReference else { return }
let reviewsCollection = reference.collection("ratings")
let newReviewReference = reviewsCollection.document()
// Writing data in a transaction
let firestore = Firestore.firestore()
firestore.runTransaction({ (transaction, errorPointer) -> Any? in
// Read data from Firestore inside the transaction, so we don't accidentally
// update using stale client data. Error if we're unable to read here.
let restaurantSnapshot: DocumentSnapshot
do {
restaurantSnapshot = try transaction.getDocument(reference)
} catch let error as NSError {
errorPointer?.pointee = error
return nil
}
// Error if the restaurant data in Firestore has somehow changed or is malformed.
let maybeRestaurant: Restaurant?
do {
maybeRestaurant = try restaurantSnapshot.data(as: Restaurant.self)
} catch {
errorPointer?.pointee = NSError(domain: "FriendlyEatsErrorDomain", code: 0, userInfo: [
NSLocalizedDescriptionKey: "Unable to read restaurant at Firestore path: \(reference.path): \(error)",
])
return nil
}
guard let restaurant = maybeRestaurant else {
errorPointer?.pointee = NSError(domain: "FriendlyEatsErrorDomain", code: 0, userInfo: [
NSLocalizedDescriptionKey: "Missing restaurant at Firestore path: \(reference.path)",
])
return nil
}
// Update the restaurant's rating and rating count and post the new review at the
// same time.
let newAverage = (Float(restaurant.ratingCount) * restaurant
.averageRating + Float(review.rating))
/ Float(restaurant.ratingCount + 1)
do {
try transaction.setData(from: review, forDocument: newReviewReference)
} catch let error as NSError {
errorPointer?.pointee = error
return nil
}
transaction.updateData([
"numRatings": restaurant.ratingCount + 1,
"avgRating": newAverage,
], forDocument: reference)
return nil
}) { object, error in
if let error = error {
print(error)
} else {
// Pop the review controller on success
if self.navigationController?.topViewController?
.isKind(of: NewReviewViewController.self) ?? false {
self.navigationController?.popViewController(animated: true)
}
}
}
}
}
class RestaurantTitleView: UIView {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var categoryLabel: UILabel!
@IBOutlet var cityLabel: UILabel!
@IBOutlet var priceLabel: UILabel!
@IBOutlet var starsView: ImmutableStarsView! {
didSet {
starsView.highlightedColor = UIColor.white.cgColor
}
}
@IBOutlet var titleImageView: UIImageView! {
didSet {
let gradient = CAGradientLayer()
gradient.colors = [
UIColor(red: 0, green: 0, blue: 0, alpha: 0.6).cgColor,
UIColor.clear.cgColor,
]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x: 0, y: 1)
gradient.endPoint = CGPoint(x: 0, y: 0)
gradient.frame = CGRect(x: 0,
y: 0,
width: UIScreen.main.bounds.width,
height: titleImageView.bounds.height)
titleImageView.layer.insertSublayer(gradient, at: 0)
titleImageView.contentMode = .scaleAspectFill
titleImageView.clipsToBounds = true
}
}
func populateImage(url: URL) {
titleImageView.sd_setImage(with: url)
}
func populate(restaurant: Restaurant) {
nameLabel.text = restaurant.name
starsView.rating = Int(restaurant.averageRating.rounded())
categoryLabel.text = restaurant.category
cityLabel.text = restaurant.city
priceLabel.text = priceString(from: restaurant.price)
}
}
class ReviewTableViewCell: UITableViewCell {
@IBOutlet var usernameLabel: UILabel!
@IBOutlet var reviewContentsLabel: UILabel!
@IBOutlet var starsView: ImmutableStarsView!
func populate(review: Review) {
usernameLabel.text = review.username
reviewContentsLabel.text = review.text
starsView.rating = review.rating
}
}
```
|
```objective-c
#pragma once
#include <memory>
#include <string>
#include <vector>
class FRT_Target;
class FRT_RPCRequest;
class FRT_Values;
namespace fnet::frt { class StandaloneFRT; }
struct Flags {
std::string method;
std::vector<std::string> args;
std::string targethost;
int portnumber;
Flags(const Flags &);
Flags & operator=(const Flags &);
Flags();
~Flags();
};
class ProxyCmd
{
private:
std::unique_ptr<fnet::frt::StandaloneFRT> _server;
FRT_Target *_target;
FRT_RPCRequest *_req;
Flags _flags;
void initRPC();
void invokeRPC();
void finiRPC();
void printArray(FRT_Values *rvals);
std::string makeSpec();
void autoPrint();
public:
ProxyCmd(const Flags& flags);
virtual ~ProxyCmd();
int action();
};
```
|
```objective-c
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_
#define BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_
#include "base/base_export.h"
#include "base/memory/scoped_ptr.h"
namespace base {
class DiscardableMemory;
class BASE_EXPORT DiscardableMemoryAllocator {
public:
// Returns the allocator instance.
static DiscardableMemoryAllocator* GetInstance();
// Sets the allocator instance. Can only be called once, e.g. on startup.
// Ownership of |instance| remains with the caller.
static void SetInstance(DiscardableMemoryAllocator* allocator);
virtual scoped_ptr<DiscardableMemory> AllocateLockedDiscardableMemory(
size_t size)
= 0;
protected:
virtual ~DiscardableMemoryAllocator() { }
};
} // namespace base
#endif // BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_
```
|
```scala
/*
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.apache.spark.carbondata.restructure
import org.apache.spark.sql.CarbonEnv
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.test.util.QueryTest
import org.scalatest.BeforeAndAfterAll
import org.apache.carbondata.core.metadata.schema.table.CarbonTable
import org.apache.carbondata.core.statusmanager.SegmentStatusManager
import org.apache.carbondata.core.util.path.CarbonTablePath
class AlterTableUpgradeSegmentTest extends QueryTest with BeforeAndAfterAll {
override protected def beforeAll(): Unit = {
sql("drop table if exists altertest")
sql("create table altertest(a string) STORED AS carbondata")
sql("insert into altertest select 'k'")
sql("insert into altertest select 'tttttt'")
}
private def removeDataAndIndexSizeFromTableStatus(table: CarbonTable): Unit = {
val loadMetaDataDetails = SegmentStatusManager.readTableStatusFile(CarbonTablePath
.getTableStatusFilePath(table.getTablePath, table.getTableStatusVersion))
loadMetaDataDetails.foreach { loadMetaDataDetail =>
loadMetaDataDetail.setIndexSize("0")
loadMetaDataDetail.setDataSize("0")
}
SegmentStatusManager.writeLoadDetailsIntoFile(CarbonTablePath
.getTableStatusFilePath(table.getTablePath, table.getTableStatusVersion), loadMetaDataDetails)
}
test("test alter table upgrade segment test") {
val carbonTable =
CarbonEnv.getCarbonTable(TableIdentifier("altertest"))(sqlContext.sparkSession)
removeDataAndIndexSizeFromTableStatus(carbonTable)
val loadMetaDataDetails = SegmentStatusManager.readTableStatusFile(CarbonTablePath
.getTableStatusFilePath(carbonTable.getTablePath, carbonTable.getTableStatusVersion))
loadMetaDataDetails.foreach(detail => assert(detail.getIndexSize.toInt + detail.getDataSize
.toInt == 0))
sql("alter table altertest compact 'upgrade_segment'")
val loadMetaDataDetailsNew = SegmentStatusManager.readTableStatusFile(CarbonTablePath
.getTableStatusFilePath(carbonTable.getTablePath, carbonTable.getTableStatusVersion))
loadMetaDataDetailsNew.foreach{detail =>
assert(detail.getIndexSize.toInt != 0)
assert(detail.getDataSize.toInt != 0)}
}
override protected def afterAll(): Unit = {
sql("drop table if exists altertest")
}
}
```
|
```xml
<vector xmlns:android="path_to_url" android:height="27.2dp" android:tint="?attr/colorControlNormal" android:viewportHeight="512" android:viewportWidth="640" android:width="34.0dp">
<path android:fillColor="@android:color/white" android:pathData="M256 336h-0.02c0-16.18 1.34-8.73-85.05-181.51-17.65-35.29-68.19-35.36-85.87 0C-2.06 328.75 0.02 320.33 0.02 336H0c0 44.18 57.31 80 128 80s128-35.82 128-80zM128 176l72 144H56l72-144zm511.98 160c0-16.18 1.34-8.73-85.05-181.51-17.65-35.29-68.19-35.36-85.87 0-87.12 174.26-85.04 165.84-85.04 181.51H384c0 44.18 57.31 80 128 80s128-35.82 128-80h-0.02zM440 320l72-144 72 144H440zm88 128H352V153.25c23.51-10.29 41.16-31.48 46.39-57.25H528c8.84 0 16-7.16 16-16V48c0-8.84-7.16-16-16-16H383.64C369.04 12.68 346.09 0 320 0s-49.04 12.68-63.64 32H112c-8.84 0-16 7.16-16 16v32c0 8.84 7.16 16 16 16h129.61c5.23 25.76 22.87 46.96 46.39 57.25V448H112c-8.84 0-16 7.16-16 16v32c0 8.84 7.16 16 16 16h416c8.84 0 16-7.16 16-16v-32c0-8.84-7.16-16-16-16z"/>
</vector>
```
|
```makefile
################################################################################
#
# xdriver_xf86-video-vesa
#
################################################################################
XDRIVER_XF86_VIDEO_VESA_VERSION = 2.3.3
XDRIVER_XF86_VIDEO_VESA_SOURCE = xf86-video-vesa-$(XDRIVER_XF86_VIDEO_VESA_VERSION).tar.bz2
XDRIVER_XF86_VIDEO_VESA_SITE = path_to_url
XDRIVER_XF86_VIDEO_VESA_LICENSE = MIT
XDRIVER_XF86_VIDEO_VESA_LICENSE_FILES = COPYING
XDRIVER_XF86_VIDEO_VESA_DEPENDENCIES = xserver_xorg-server xproto_fontsproto xproto_randrproto xproto_renderproto xproto_xextproto xproto_xproto
$(eval $(autotools-package))
```
|
The Revolutionary Communist Movement of Greece or EKKE (Greek: Επαναστατικό Κομμουνιστικό Κίνημα Ελλάδας, ΕΚΚΕ) is a communist political party in Greece.
Alliances
In 1999, EKKE joined the Radical Left Front (MERA) political coalition and in 2009 Anticapitalist Left Cooperation for the Overthrow.
See also
Anticapitalist Left Cooperation for the Overthrow
Radical Left Front
External links
EKKE web site
Communist parties in Greece
Far-left politics in Greece
|
The Buhl A-1 Autogiro was an autogyro optimised for air camera work designed and built from 1930. To this end, Etienne Dormoy designed the Buhl A-1, an autogyro with a pusher engine located behind the pilot and camera operator. The Buhl A-1 was the first pusher style autogyro.
Specifications
See also
References
External links
The Buhl A-1 Autogiro
Bull A-1
Single-engined pusher autogyros
1930s United States experimental aircraft
Low-wing aircraft
Aircraft first flown in 1931
|
Bono is an unincorporated community in Lucas County, Ohio, United States.
History
A post office called Bono was established in 1898, and remained in operation until it was discontinued in 1974. The community bears the name of Francis Bunno, chief of the Cherokee.
Notes
Unincorporated communities in Lucas County, Ohio
Unincorporated communities in Ohio
|
The 1996 Russian Second League was the fifth edition of Russian Second Division. There were 3 zones with 60 teams starting the competition (2 were excluded before the end of the season).
Zone West
Overview
Standings
Top goalscorers
33 goals
Ibragim Gasanbekov (FC Anzhi Makhachkala)
31 goals
Vitali Yermilov (FC Torpedo Taganrog)
29 goals
Sergei Lavrentyev (FC MChS-Selyatino Selyatino)
25 goals
Igor Lyakhov (FC Metallurg Lipetsk)
23 goals
Sergei Polstyanov (FC Metallurg Lipetsk)
17 goals
Vladimir Kharin (FC Lokomotiv Liski)
16 goals
Aleksandr Zhidkov (FC Metallurg Lipetsk)
15 goals
Andrei Bakalets (FC MChS-Selyatino Selyatino)
14 goals
Vladimir Ivanov (FC Gatchina)
13 goals
Isa Markhiyev (FC Angusht Nazran)
Zone Centre
Overview
Standings
Top goalscorers
34 goals
Konstantin Paramonov (FC Amkar Perm)
30 goals
Valeri Solyanik (FC CSK VVS-Kristall Smolensk)
27 goals
Aleksandr Kuzmichyov (FC Arsenal Tula)
25 goals
Aleksei Chernov (FC Lada Dimitrovgrad)
24 goals
Andrei Knyazev (FC Metallurg Magnitogorsk)
21 goals
Oleg Nechayev (FC Lada Dimitrovgrad)
20 goals
Vladimir Pantyushenko (FC Rubin Kazan)
19 goals
Oleg Sinelobov (FC Nosta Novotroitsk)
17 goals
Armen Adamyan (FC CSK VVS-Kristall Smolensk)
16 goals
Igor Palachyov (FC Nosta Novotroitsk)
Aleksandr Zaikin (FC Lada Dimitrovgrad)
Zone East
Overview
Standings
Top goalscorers
22 goals
Marat Mulashev (FC Irtysh Omsk)
18 goals
Sergei Ageyev (FC Viktoriya Nazarovo)
16 goals
Anatoli Kisurin (FC Dynamo Omsk)
14 goals
Sergei Rogalevskiy (FC Kuzbass Kemerovo)
13 goals
Sergei Shaporenko (FC Irtysh Omsk)
11 goals
Aleksandr Bogatyryov (FC Viktoriya Nazarovo)
Yevgeni Savin (FC Dynamo Barnaul)
10 goals
Maksim Shvetsov (FC SKA Khabarovsk)
9 goals
Stanislav Achkasov (FC Kuzbass Kemerovo)
Ruslan Akhidzhak (FC Tom Tomsk)
Stanislav Chaplygin (FC Metallurg-ZapSib Novokuznetsk)
Yury Khadaronak (FC Samotlor-XXI Nizhnevartovsk)
Sergei Kondratskiy (FC Irtysh Omsk)
Konstantin Orlov (FC Metallurg-ZapSib Novokuznetsk)
Vitali Razdrogin (FC Irtysh Omsk)
Viktor Sebelev (FC Tom Tomsk)
Taras Shulga (FC SKA Khabarovsk)
See also
1996 Russian Top League
1996 Russian First League
1996 Russian Third League
3
1996
Russia
Russia
|
```kotlin
package de.westnordost.streetcomplete.screens.main.teammode
import android.content.Context
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.GridLayoutManager
import de.westnordost.streetcomplete.databinding.DialogTeamModeBinding
import de.westnordost.streetcomplete.screens.main.teammode.TeamModeColorCircleView.Companion.MAX_TEAM_SIZE
/** Shows a dialog containing the team mode settings */
class TeamModeDialog(
context: Context,
onEnableTeamMode: (Int, Int) -> Unit
) : AlertDialog(context) {
private var selectedTeamSize: Int? = null
private var selectedIndexInTeam: Int? = null
private val binding = DialogTeamModeBinding.inflate(LayoutInflater.from(context))
init {
val adapter = TeamModeIndexSelectAdapter()
adapter.listeners.add(object : TeamModeIndexSelectAdapter.OnSelectedIndexChangedListener {
override fun onSelectedIndexChanged(index: Int?) {
selectedIndexInTeam = index
updateOkButtonEnablement()
}
})
binding.colorCircles.adapter = adapter
binding.colorCircles.layoutManager = GridLayoutManager(context, 3)
binding.teamSizeInput.doAfterTextChanged { editable ->
selectedTeamSize = parseTeamSize(editable.toString())
updateOkButtonEnablement()
if (selectedTeamSize == null) {
binding.introText.isGone = false
binding.teamSizeHint.isGone = false
binding.colorHint.isGone = true
binding.colorCircles.isGone = true
} else {
binding.introText.isGone = true
binding.teamSizeHint.isGone = true
binding.colorHint.isGone = false
binding.colorCircles.isGone = false
adapter.count = selectedTeamSize!!
}
}
setButton(BUTTON_POSITIVE, context.resources.getText(android.R.string.ok)) { _, _ ->
onEnableTeamMode(selectedTeamSize!!, selectedIndexInTeam!!)
dismiss()
}
setOnShowListener { updateOkButtonEnablement() }
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
setView(binding.root)
}
private fun updateOkButtonEnablement() {
getButton(BUTTON_POSITIVE)?.isEnabled = selectedTeamSize != null && selectedIndexInTeam != null
}
private fun parseTeamSize(string: String): Int? =
try {
val number = Integer.parseInt(string)
if (number in 2..MAX_TEAM_SIZE) number else null
} catch (e: NumberFormatException) {
null
}
}
```
|
Razhden Rolandiyevich Melkadze (; born 4 December 1983) is a former Russian professional football player of Georgian descent.
He played 2 seasons in the Russian Football National League for FC Arsenal Tula, FC Dynamo Bryansk and FC Oryol.
External links
1983 births
Russian sportspeople of Georgian descent
Living people
Russian men's footballers
FC Oryol players
FC Arsenal Tula players
Men's association football defenders
FC Dynamo Bryansk players
FC Sever Murmansk players
|
```c++
// TnzLib includes
#include "toonz/tstageobjectcmd.h"
#include "toonz/txsheethandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/tfxhandle.h"
#include "toonz/txsheet.h"
#include "toonz/toonzscene.h"
#include "toonz/tstageobjectspline.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/tcamera.h"
#include "toonz/tcolumnfxset.h"
#include "toonz/fxdag.h"
// TnzBase includes
#include "tdoublekeyframe.h"
#include "tfx.h"
// TnzCore includes
#include "tundo.h"
#include "tconvert.h"
#include "historytypes.h"
// Qt includes
#include <QMap>
#include <QString>
namespace {
bool canRemoveFx(const std::set<TFx *> &leaves, TFx *fx) {
for (int i = 0; i < fx->getInputPortCount(); i++) {
TFx *inputFx = fx->getInputPort(i)->getFx();
if (!inputFx) continue;
if (leaves.count(inputFx) > 0) continue;
if (!canRemoveFx(leaves, inputFx)) return false;
}
return fx->getInputPortCount() > 0;
}
//=========================================================
//
// NewCameraUndo
//
//---------------------------------------------------------
class NewCameraUndo final : public TUndo {
TStageObjectId m_cameraId, m_oldCurrentId;
TStageObject *m_stageObject;
TXsheetHandle *m_xshHandle;
TObjectHandle *m_objHandle;
public:
NewCameraUndo(const TStageObjectId &cameraId, TXsheetHandle *xshHandle,
TObjectHandle *objHandle)
: m_cameraId(cameraId)
, m_stageObject(0)
, m_xshHandle(xshHandle)
, m_objHandle(objHandle) {
assert(cameraId.isCamera());
TXsheet *xsh = m_xshHandle->getXsheet();
m_stageObject = xsh->getStageObject(m_cameraId);
m_stageObject->addRef();
m_oldCurrentId = m_objHandle->getObjectId();
}
~NewCameraUndo() { m_stageObject->release(); }
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
if (m_cameraId == m_objHandle->getObjectId())
m_objHandle->setObjectId(m_oldCurrentId);
xsh->getStageObjectTree()->removeStageObject(m_cameraId);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->insertStageObject(m_stageObject);
m_objHandle->setObjectId(m_cameraId);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("New Camera %1")
.arg(QString::fromStdString(m_cameraId.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
private:
// not implemented
NewCameraUndo(const NewCameraUndo &);
NewCameraUndo &operator=(const NewCameraUndo &);
};
//=========================================================
//
// NewPegbarUndo
//
//---------------------------------------------------------
class NewPegbarUndo final : public TUndo {
TStageObjectId m_id, m_oldCurrentId;
TStageObject *m_stageObject;
TXsheetHandle *m_xshHandle;
TObjectHandle *m_objHandle;
public:
NewPegbarUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
TObjectHandle *objHandle)
: m_id(id)
, m_stageObject(0)
, m_xshHandle(xshHandle)
, m_objHandle(objHandle) {
assert(!id.isTable());
TXsheet *xsh = m_xshHandle->getXsheet();
m_stageObject = xsh->getStageObject(m_id);
m_stageObject->addRef();
m_oldCurrentId = m_objHandle->getObjectId();
}
~NewPegbarUndo() { m_stageObject->release(); }
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
if (m_id == m_objHandle->getObjectId())
m_objHandle->setObjectId(m_oldCurrentId);
xsh->getStageObjectTree()->removeStageObject(m_id);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->insertStageObject(m_stageObject);
m_objHandle->setObjectId(m_id);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("New Pegbar %1")
.arg(QString::fromStdString(m_id.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
private:
// not implemented
NewPegbarUndo(const NewPegbarUndo &);
NewPegbarUndo &operator=(const NewPegbarUndo &);
};
//===================================================================
//
// SetActiveCameraUndo
//
//your_sha256_hash---
class SetActiveCameraUndo final : public TUndo {
TStageObjectId m_oldCameraId, m_newCameraId;
TXsheetHandle *m_xshHandle;
public:
SetActiveCameraUndo(const TStageObjectId &oldCameraId,
const TStageObjectId &newCameraId,
TXsheetHandle *xshHandle)
: m_oldCameraId(oldCameraId)
, m_newCameraId(newCameraId)
, m_xshHandle(xshHandle) {}
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->setCurrentCameraId(m_oldCameraId);
// make the preview camera same as the final camera
xsh->getStageObjectTree()->setCurrentPreviewCameraId(m_oldCameraId);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->setCurrentCameraId(m_newCameraId);
// make the preview camera same as the final camera
xsh->getStageObjectTree()->setCurrentPreviewCameraId(m_newCameraId);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("Set Active Camera %1 > %2")
.arg(QString::fromStdString(m_oldCameraId.toString()))
.arg(QString::fromStdString(m_newCameraId.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// RemoveSplineUndo
//
//your_sha256_hash---
class RemoveSplineUndo final : public TUndo {
TStageObjectId m_id;
TStageObjectSpline *m_spline;
std::vector<TStageObjectId> m_ids;
TXsheetHandle *m_xshHandle;
public:
RemoveSplineUndo(TStageObjectSpline *spline, TXsheetHandle *xshHandle)
: m_spline(spline), m_xshHandle(xshHandle) {
m_spline->addRef();
TStageObjectTree *pegbarTree =
m_xshHandle->getXsheet()->getStageObjectTree();
for (int i = 0; i < pegbarTree->getStageObjectCount(); i++) {
TStageObject *pegbar = pegbarTree->getStageObject(i);
if (pegbar->getSpline() == m_spline) m_ids.push_back(pegbar->getId());
}
}
~RemoveSplineUndo() { m_spline->release(); }
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->insertSpline(m_spline);
for (int i = 0; i < (int)m_ids.size(); i++) {
TStageObject *pegbar = xsh->getStageObject(m_ids[i]);
assert(pegbar);
pegbar->setSpline(m_spline);
}
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
for (int i = 0; i < (int)m_ids.size(); i++) {
TStageObject *pegbar = xsh->getStageObject(m_ids[i]);
assert(pegbar);
pegbar->setSpline(0);
}
xsh->getStageObjectTree()->removeSpline(m_spline);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + sizeof(TStageObjectSpline) +
sizeof(TStageObjectId) * m_ids.size();
}
QString getHistoryString() override {
return QObject::tr("Remove Spline %1")
.arg(QString::fromStdString(m_id.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// NewSplineUndo
//
//your_sha256_hash---
class NewSplineUndo final : public TUndo {
TStageObjectId m_id;
TStageObjectSpline *m_spline;
TXsheetHandle *m_xshHandle;
public:
NewSplineUndo(const TStageObjectId &id, TStageObjectSpline *spline,
TXsheetHandle *xshHandle)
: m_id(id), m_spline(spline), m_xshHandle(xshHandle) {
m_spline->addRef();
}
~NewSplineUndo() { m_spline->release(); }
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
TStageObject *pegbar = xsh->getStageObject(m_id);
assert(pegbar);
pegbar->setSpline(0);
xsh->getStageObjectTree()->removeSpline(m_spline);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
xsh->getStageObjectTree()->insertSpline(m_spline);
TStageObject *pegbar = xsh->getStageObject(m_id);
assert(pegbar);
pegbar->setSpline(m_spline);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + sizeof(TStageObjectSpline);
}
QString getHistoryString() override {
return QObject::tr("New Motion Path %1")
.arg(QString::fromStdString(m_spline->getName()));
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// SplineLinkUndo
//
//your_sha256_hash---
class SplineLinkUndo final : public TUndo {
TStageObjectId m_id;
TStageObjectSpline *m_spline;
TXsheetHandle *m_xshHandle;
public:
SplineLinkUndo(const TStageObjectId &id, TStageObjectSpline *spline,
TXsheetHandle *xshHandle)
: m_id(id), m_spline(spline), m_xshHandle(xshHandle) {
m_spline->addRef();
}
~SplineLinkUndo() { m_spline->release(); }
void undo() const override {
TStageObject *object = m_xshHandle->getXsheet()->getStageObject(m_id);
object->setSpline(0);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TStageObject *object = m_xshHandle->getXsheet()->getStageObject(m_id);
object->setSpline(m_spline);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + sizeof(TStageObjectSpline);
}
QString getHistoryString() override {
return QObject::tr("Link Motion Path %1 > %2")
.arg(QString::fromStdString(m_spline->getName()))
.arg(QString::fromStdString(m_id.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// DeleteSplineLinkUndo
//
//your_sha256_hash---
class RemoveSplineLinkUndo final : public TUndo {
TStageObjectId m_id;
TStageObjectSpline *m_spline;
TXsheetHandle *m_xshHandle;
TObjectHandle *m_objHandle;
public:
RemoveSplineLinkUndo(const TStageObjectId &id, TStageObjectSpline *spline,
TXsheetHandle *xshHandle, TObjectHandle *objHandle)
: m_id(id)
, m_spline(spline)
, m_xshHandle(xshHandle)
, m_objHandle(objHandle) {
m_spline->addRef();
}
~RemoveSplineLinkUndo() { m_spline->release(); }
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
TStageObjectTree *objTree = xsh->getStageObjectTree();
TStageObject *object = objTree->getStageObject(m_id, false);
if (!object) return;
object->setSpline(m_spline);
if (m_objHandle->getObjectId() == m_id) m_objHandle->setIsSpline(true);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
TStageObjectTree *objTree = xsh->getStageObjectTree();
TStageObject *object = objTree->getStageObject(m_id, false);
if (!object) return;
object->setSpline(0);
if (m_objHandle->getObjectId() == m_id) m_objHandle->setIsSpline(false);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + sizeof(TStageObjectSpline);
}
};
//===================================================================
//
// RemovePegbarNodeUndo
//
//your_sha256_hash---
class RemovePegbarNodeUndo final : public TUndo {
TStageObjectId m_objId;
TXshColumnP m_column;
TStageObjectParams *m_params;
QList<TStageObjectId> m_linkedObj;
TXsheetHandle *m_xshHandle;
public:
RemovePegbarNodeUndo(TStageObjectId id, TXsheetHandle *xshHandle)
: TUndo(), m_objId(id), m_xshHandle(xshHandle), m_column(0) {
TXsheet *xsh = xshHandle->getXsheet();
TStageObject *obj = xsh->getStageObject(id);
assert(obj);
m_params = obj->getParams();
if (id.isColumn()) m_column = xsh->getColumn(id.getIndex());
}
~RemovePegbarNodeUndo() { delete m_params; }
void setLinkedObjects(const QList<TStageObjectId> &linkedObj) {
m_linkedObj = linkedObj;
}
void undo() const override {
// reinsert Object
TXsheet *xsh = m_xshHandle->getXsheet();
if (m_objId.isColumn() && m_column)
xsh->insertColumn(m_objId.getIndex(), m_column.getPointer());
TStageObject *obj = xsh->getStageObject(m_objId);
obj->assignParams(m_params);
obj->setParent(m_params->m_parentId);
int i, linkCount = m_linkedObj.size();
for (i = 0; i < linkCount; i++) {
TStageObject *linkedObj = xsh->getStageObject(m_linkedObj[i]);
assert(linkedObj);
linkedObj->setParent(m_objId);
}
m_xshHandle->notifyXsheetChanged();
xsh->notifyStageObjectAdded(m_objId);
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
int pegbarsCount = xsh->getStageObjectTree()->getStageObjectCount();
int i;
for (i = 0; i < pegbarsCount; ++i) {
TStageObject *other = xsh->getStageObjectTree()->getStageObject(i);
if (other->getId() == m_objId) continue;
if (other->getParent() == m_objId)
other->setParent(xsh->getStageObjectParent(m_objId));
}
if (m_objId.isColumn())
xsh->removeColumn(m_objId.getIndex());
else
xsh->getStageObjectTree()->removeStageObject(m_objId);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + sizeof(TStageObjectParams) + sizeof(m_xshHandle);
}
QString getHistoryString() override {
return QObject::tr("Remove Object %1")
.arg(QString::fromStdString(m_objId.toString()));
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// RemoveColumnsUndo
//
//your_sha256_hash---
class RemoveColumnsUndo final : public TUndo {
std::vector<TFx *> m_deletedFx;
std::vector<TFx *> m_terminalFx;
QMap<TStageObjectId, QList<TFxPort *>> m_columnFxConnections;
QList<TFx *> m_notTerminalColumns;
TXsheetHandle *m_xshHandle;
public:
RemoveColumnsUndo(
const std::vector<TFx *> &deletedFx, const std::vector<TFx *> &terminalFx,
const QMap<TStageObjectId, QList<TFxPort *>> columnFxConnections,
const QList<TFx *> ¬TerminalColumns, TXsheetHandle *xshHandle)
: TUndo()
, m_deletedFx(deletedFx)
, m_terminalFx(terminalFx)
, m_columnFxConnections(columnFxConnections)
, m_notTerminalColumns(notTerminalColumns)
, m_xshHandle(xshHandle) {
int i;
for (i = 0; i < (int)m_deletedFx.size(); i++) m_deletedFx[i]->addRef();
}
~RemoveColumnsUndo() {
int i;
for (i = 0; i < (int)m_deletedFx.size(); i++) m_deletedFx[i]->release();
}
void undo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
TFxSet *terminalFxs = xsh->getFxDag()->getTerminalFxs();
TFxSet *internalFxs = xsh->getFxDag()->getInternalFxs();
int i;
for (i = 0; i < (int)m_deletedFx.size(); i++)
internalFxs->addFx(m_deletedFx[i]);
for (i = 0; i < (int)m_terminalFx.size(); i++)
terminalFxs->addFx(m_terminalFx[i]);
QMap<TStageObjectId, QList<TFxPort *>>::const_iterator it;
for (it = m_columnFxConnections.begin(); it != m_columnFxConnections.end();
it++) {
TStageObjectId id = it.key();
QList<TFxPort *> ports = it.value();
TXshColumnP column = xsh->getColumn(id.getIndex());
assert(column);
int j;
for (j = 0; j < ports.size(); j++) ports[j]->setFx(column->getFx());
}
for (i = 0; i < m_notTerminalColumns.size(); i++)
terminalFxs->removeFx(m_notTerminalColumns[i]);
m_xshHandle->notifyXsheetChanged();
xsh->notifyFxAdded(m_deletedFx);
}
void redo() const override {
TXsheet *xsh = m_xshHandle->getXsheet();
TFxSet *terminalFxs = xsh->getFxDag()->getTerminalFxs();
TFxSet *internalFxs = xsh->getFxDag()->getInternalFxs();
int i;
for (i = 0; i < (int)m_deletedFx.size(); i++)
internalFxs->removeFx(m_deletedFx[i]);
for (i = 0; i < (int)m_terminalFx.size(); i++)
terminalFxs->removeFx(m_terminalFx[i]);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof *this + m_deletedFx.size() * sizeof(TFx) +
m_terminalFx.size() * sizeof(TFx) +
m_columnFxConnections.size() *
(sizeof(TStageObjectId) + 10 * sizeof(TFxPort)) +
m_notTerminalColumns.size() * sizeof(TFx) + sizeof(TXsheetHandle);
}
QString getHistoryString() override {
QString str = QObject::tr("Remove Column ");
QMap<TStageObjectId, QList<TFxPort *>>::const_iterator it;
for (it = m_columnFxConnections.begin(); it != m_columnFxConnections.end();
it++) {
TStageObjectId id = it.key();
if (it != m_columnFxConnections.begin())
str += QString::fromStdString(", ");
str += QString::fromStdString(id.toString());
}
return str;
}
int getHistoryType() override { return HistoryType::Schematic; }
};
//===================================================================
//
// UndoGroup
//
//your_sha256_hash---
class UndoGroup final : public TUndo {
QList<TStageObjectId> m_ids;
int m_groupId;
QList<int> m_positions;
TXsheetHandle *m_xshHandle;
public:
UndoGroup(const QList<TStageObjectId> &ids, int groupId,
const QList<int> &positions, TXsheetHandle *xshHandle)
: m_ids(ids)
, m_groupId(groupId)
, m_positions(positions)
, m_xshHandle(xshHandle) {}
~UndoGroup() {}
void undo() const override {
assert(m_ids.size() == m_positions.size());
TStageObjectTree *pegTree = m_xshHandle->getXsheet()->getStageObjectTree();
int i;
for (i = 0; i < m_ids.size(); i++) {
TStageObject *obj = pegTree->getStageObject(m_ids[i], false);
if (obj) {
obj->removeGroupName(m_positions[i]);
obj->removeGroupId(m_positions[i]);
}
}
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
assert(m_ids.size() == m_positions.size());
TStageObjectTree *pegTree = m_xshHandle->getXsheet()->getStageObjectTree();
int i;
for (i = 0; i < m_ids.size(); i++) {
TStageObject *obj = pegTree->getStageObject(m_ids[i], false);
if (obj) {
obj->setGroupId(m_groupId, m_positions[i]);
obj->setGroupName(L"Group " + std::to_wstring(m_groupId),
m_positions[i]);
}
}
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof *this; }
};
//===================================================================
//
// UndoUngroup
//
//your_sha256_hash---
class UndoUngroup final : public TUndo {
QList<TStageObjectId> m_objsId;
QList<int> m_positions;
int m_groupId;
std::wstring m_groupName;
TXsheetHandle *m_xshHandle;
public:
UndoUngroup(const QList<TStageObject *> &objs, TXsheetHandle *xshHandle)
: m_xshHandle(xshHandle) {
assert(objs.size() > 0);
int i;
for (i = 0; i < objs.size(); i++) {
m_objsId.append(objs[i]->getId());
if (i == 0) {
m_groupId = objs[i]->getGroupId();
m_groupName = objs[i]->getGroupName(false);
}
}
}
~UndoUngroup() {}
void setStackPositions(const QList<int> &positions) {
m_positions = positions;
}
void undo() const override {
assert(m_objsId.size() == m_positions.size());
TStageObjectTree *objTree = m_xshHandle->getXsheet()->getStageObjectTree();
if (!objTree) return;
int i;
for (i = 0; i < m_objsId.size(); i++) {
TStageObject *obj = objTree->getStageObject(m_objsId[i], false);
if (!obj) continue;
obj->setGroupId(m_groupId, m_positions[i]);
obj->setGroupName(m_groupName, m_positions[i]);
}
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
assert(m_objsId.size() == m_positions.size());
TStageObjectTree *objTree = m_xshHandle->getXsheet()->getStageObjectTree();
if (!objTree) return;
int i;
for (i = 0; i < m_objsId.size(); i++) {
TStageObject *obj = objTree->getStageObject(m_objsId[i], false);
if (!obj) continue;
obj->removeGroupName(m_positions[i]);
obj->removeGroupId(m_positions[i]);
}
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof *this; }
};
//===================================================================
//
// UndoRenameGroup
//
//your_sha256_hash---
class UndoRenameGroup final : public TUndo {
QList<TStageObject *> m_objs;
QList<int> m_positions;
std::wstring m_oldGroupName;
std::wstring m_newGroupName;
TXsheetHandle *m_xshHandle;
public:
UndoRenameGroup(const QList<TStageObject *> &objs,
const QList<int> &positions, const std::wstring &newName,
const std::wstring &oldName, TXsheetHandle *xshHandle)
: m_objs(objs)
, m_newGroupName(newName)
, m_oldGroupName(oldName)
, m_xshHandle(xshHandle)
, m_positions(positions) {
assert(objs.size() > 0);
int i;
for (i = 0; i < m_objs.size(); i++) m_objs[i]->addRef();
}
~UndoRenameGroup() {
int i;
for (i = 0; i < m_objs.size(); i++) m_objs[i]->release();
}
void undo() const override {
assert(m_objs.size() == m_positions.size());
int i;
for (i = 0; i < m_objs.size(); i++) {
m_objs[i]->removeGroupName(m_positions[i]);
m_objs[i]->setGroupName(m_oldGroupName, m_positions[i]);
}
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
assert(m_objs.size() == m_positions.size());
int i;
for (i = 0; i < m_objs.size(); i++) {
m_objs[i]->removeGroupName(m_positions[i]);
m_objs[i]->setGroupName(m_newGroupName, m_positions[i]);
}
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof *this; }
};
//===================================================================
//
// UndoStatusChange
//
//your_sha256_hash---
class UndoStatusChange final : public TUndo {
TStageObject *m_obj;
TStageObject::Status m_oldStatus, m_newStatus;
TXsheetHandle *m_xshHandle;
public:
UndoStatusChange(TStageObject *obj, TXsheetHandle *xshHandle)
: m_obj(obj), m_xshHandle(xshHandle) {
m_obj->addRef();
// devo fare addref della spline altimenti crasha in uscita
// m_obj non fa addref della spline a lui associata, e quindi crasha perche'
// la spline viene distrutta
// prima di m_obj... sarebbe piu' corretto fare addref della spline quando
// viene settata all'oggetto
// piuttosto che farla qui?
TStageObjectSpline *spline = m_obj->getSpline();
if (spline) spline->addRef();
m_oldStatus = m_obj->getStatus();
}
~UndoStatusChange() {
TStageObjectSpline *spline = m_obj->getSpline();
m_obj->release();
if (spline) spline->release();
}
void onAdd() override { m_newStatus = m_obj->getStatus(); }
void undo() const override {
m_obj->setStatus(m_oldStatus);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
m_obj->setStatus(m_newStatus);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof *this; }
};
//===================================================================
//
// removePegbarNode
//
//your_sha256_hash---
void removeStageObjectNode(const TStageObjectId &id, TXsheetHandle *xshHandle,
TObjectHandle *objHandle, TFxHandle *fxHandle,
bool doUndo = true) {
TXsheet *xsh = xshHandle->getXsheet();
TStageObject *pegbar = xsh->getStageObject(id);
// Lacamera corrente e il tavolo non si devono rimuovere
if (id.isTable() ||
(id.isCamera() && xsh->getStageObjectTree()->getCurrentCameraId() == id))
return;
if (id.isCamera() && xsh->getCameraColumnIndex() == id.getIndex())
xsh->setCameraColumnIndex(
xsh->getStageObjectTree()->getCurrentCameraId().getIndex());
// stacco tutti i figli e li attacco al padre
QList<TStageObjectId> linkedObjects;
int pegbarsCount = xsh->getStageObjectTree()->getStageObjectCount();
int i;
for (i = 0; i < pegbarsCount; ++i) {
TStageObject *other = xsh->getStageObjectTree()->getStageObject(i);
if (other == pegbar) continue;
if (other->getParent() == id) {
other->setParent(pegbar->getParent());
linkedObjects.push_back(other->getId());
}
}
if (id == objHandle->getObjectId())
objHandle->setObjectId(TStageObjectId::TableId);
RemovePegbarNodeUndo *undo = new RemovePegbarNodeUndo(id, xshHandle);
undo->setLinkedObjects(linkedObjects);
if (id.isColumn())
xsh->removeColumn(id.getIndex());
else
xsh->getStageObjectTree()->removeStageObject(id);
if (doUndo)
TUndoManager::manager()->add(undo);
else
delete undo;
}
//===================================================================
//
// removeColumns
//
//your_sha256_hash---
void removeColumns(const QVector<int> &columnIndexes, TXsheetHandle *xshHandle,
TObjectHandle *objHandle, TFxHandle *fxHandle,
bool doUndo = true) {
TXsheet *xsh = xshHandle->getXsheet();
int i;
QMap<TStageObjectId, QList<TFxPort *>> columnFxConnection;
std::set<TFx *> leafesFx;
QList<TFx *> notTerminalColumns;
for (i = columnIndexes.size() - 1; i >= 0; i--) {
TStageObjectId id = TStageObjectId::ColumnId(columnIndexes[i]);
TXshColumnP column = xsh->getColumn(id.getIndex());
if (!column) continue;
TFx *columnFx = column->getFx();
if (!columnFx) continue;
int j;
for (j = 0; j < columnFx->getOutputConnectionCount(); j++)
columnFxConnection[id].append(columnFx->getOutputConnection(j));
leafesFx.insert(columnFx);
if (!xsh->getFxDag()->getTerminalFxs()->containsFx(columnFx))
notTerminalColumns.append(columnFx);
}
std::vector<TFx *> fxsToKill;
std::vector<TFx *> terminalFxsToKill;
TFxSet *fxSet = xsh->getFxDag()->getInternalFxs();
for (i = 0; i < fxSet->getFxCount(); i++) {
TFx *fx = fxSet->getFx(i);
if (canRemoveFx(leafesFx, fx)) {
fxsToKill.push_back(fx);
if (xsh->getFxDag()->getTerminalFxs()->containsFx(fx))
terminalFxsToKill.push_back(fx);
}
}
if (doUndo) {
RemoveColumnsUndo *undo =
new RemoveColumnsUndo(fxsToKill, terminalFxsToKill, columnFxConnection,
notTerminalColumns, xshHandle);
TUndoManager::manager()->add(undo);
}
for (i = 0; i < (int)fxsToKill.size(); i++) {
TFx *fx = fxsToKill[i];
if (fx == fxHandle->getFx()) fxHandle->setFx(0);
if (fx->getLinkedFx() != fx) fx->unlinkParams();
int j, outputPortCount = fx->getOutputConnectionCount();
for (j = outputPortCount - 1; j >= 0; j--) {
TFxPort *port = fx->getOutputConnection(j);
std::vector<TFx *>::iterator it =
std::find(fxsToKill.begin(), fxsToKill.end(), port->getOwnerFx());
std::set<TFx *>::iterator it2 =
std::find(leafesFx.begin(), leafesFx.end(), port->getFx());
if (it == fxsToKill.end() && it2 == leafesFx.end()) port->setFx(0);
}
fxSet->removeFx(fx);
xsh->getFxDag()->getTerminalFxs()->removeFx(fx);
}
for (i = columnIndexes.size() - 1; i >= 0; i--)
removeStageObjectNode(TStageObjectId::ColumnId(columnIndexes[i]), xshHandle,
objHandle, fxHandle, doUndo);
}
//===================================================================
//
// removeSpline
//
//your_sha256_hash---
void removeSpline(TStageObjectSpline *spline, TXsheetHandle *xshHandle,
TObjectHandle *objHandle, bool doUndo = true) {
if (doUndo)
TUndoManager::manager()->add(new RemoveSplineUndo(spline, xshHandle));
TStageObjectTree *pegbarTree = xshHandle->getXsheet()->getStageObjectTree();
for (int i = 0; i < pegbarTree->getStageObjectCount(); i++) {
TStageObject *pegbar = pegbarTree->getStageObject(i);
if (pegbar->getSpline() == spline) {
pegbar->setSpline(0);
if (pegbar->getId() == objHandle->getObjectId())
objHandle->setIsSpline(false);
}
}
pegbarTree->removeSpline(spline);
// xshHandle->notifyXsheetChanged();
}
void removeLink(const QPair<TStageObjectId, TStageObjectId> &link,
TXsheetHandle *xshHandle, TObjectHandle *objHandle,
bool doUndo = true) {
TStageObjectTree *objTree = xshHandle->getXsheet()->getStageObjectTree();
if (link.first ==
link.second) { // is a link connecting a spline with an object
TStageObject *object = objTree->getStageObject(link.first, false);
if (!object) return;
TStageObjectSpline *spline = object->getSpline();
assert(spline);
object->setSpline(0);
if (objHandle->getObjectId() == link.first) objHandle->setIsSpline(false);
if (doUndo) {
TUndo *undo =
new RemoveSplineLinkUndo(link.first, spline, xshHandle, objHandle);
TUndoManager::manager()->add(undo);
}
} else {
TStageObject *object = objTree->getStageObject(link.first, false);
TStageObject *parentObject = objTree->getStageObject(link.second, false);
if (!object || !parentObject || object->isGrouped() ||
parentObject->isGrouped())
return;
assert(object->getParent() == parentObject->getId());
TStageObjectCmd::setParent(object->getId(), TStageObjectId::NoneId, "",
xshHandle, doUndo);
}
}
} // namespace
//===================================================================
//
// SetAttributeUndo & sons
//
//your_sha256_hash---
namespace {
//your_sha256_hash---
template <class T>
class SetAttributeUndo : public TUndo {
TStageObjectId m_id;
T m_oldValue, m_newValue;
TXsheetHandle *m_xshHandle;
public:
SetAttributeUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
T oldValue, T newValue)
: m_id(id)
, m_xshHandle(xshHandle)
, m_oldValue(oldValue)
, m_newValue(newValue) {}
TStageObjectId getId() const { return m_id; }
TStageObject *getStageObject() const {
TStageObject *pegbar = m_xshHandle->getXsheet()->getStageObject(m_id);
assert(pegbar);
return pegbar;
}
virtual void setAttribute(TStageObject *pegbar, T value) const = 0;
void setAttribute(T value) const {
TStageObject *pegbar = getStageObject();
if (pegbar) setAttribute(pegbar, value);
}
void undo() const override {
setAttribute(m_oldValue);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
setAttribute(m_newValue);
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
int getHistoryType() override { return HistoryType::Unidentified; }
QString getHistoryString() override {
return QString("%1 %2 : %3 -> %4")
.arg(getActionName())
.arg(QString::fromStdString(getId().toString()))
.arg(getStringFromValue(m_oldValue))
.arg(getStringFromValue(m_newValue));
}
virtual QString getActionName() { return QString(); }
virtual QString getStringFromValue(T value) { return QString(); }
};
//your_sha256_hash---
class StageObjectRenameUndo final : public SetAttributeUndo<std::string> {
public:
StageObjectRenameUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
std::string oldName, std::string newName)
: SetAttributeUndo<std::string>(id, xshHandle, oldName, newName) {}
void setAttribute(TStageObject *pegbar, std::string name) const override {
pegbar->setName(name);
}
QString getActionName() override { return QString("Rename Object"); }
QString getStringFromValue(std::string value) override {
return QString::fromStdString(value);
}
};
//your_sha256_hash---
class ResetOffsetUndo final : public SetAttributeUndo<TPointD> {
public:
ResetOffsetUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
const TPointD &oldOffset)
: SetAttributeUndo<TPointD>(id, xshHandle, oldOffset, TPointD()) {}
void setAttribute(TStageObject *pegbar, TPointD offset) const override {
pegbar->setOffset(offset);
}
QString getActionName() override { return QString("Reset Center"); }
QString getStringFromValue(TPointD value) override {
return QString("(%1,%2)")
.arg(QString::number(value.x))
.arg(QString::number(value.y));
}
};
//your_sha256_hash---
class ResetCenterAndOffsetUndo final : public SetAttributeUndo<TPointD> {
public:
ResetCenterAndOffsetUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
const TPointD &oldOffset)
: SetAttributeUndo<TPointD>(id, xshHandle, oldOffset, TPointD()) {}
void setAttribute(TStageObject *pegbar, TPointD offset) const override {
pegbar->setCenterAndOffset(offset, offset);
}
QString getActionName() override { return QString("Reset Center"); }
QString getStringFromValue(TPointD value) override {
return QString("(%1,%2)")
.arg(QString::number(value.x))
.arg(QString::number(value.y));
}
};
//your_sha256_hash---
class SetHandleUndo final : public SetAttributeUndo<std::string> {
TPointD m_center, m_offset;
TXsheetHandle *m_xshHandle;
public:
SetHandleUndo(const TStageObjectId &id, std::string oldHandle,
std::string newHandle, TXsheetHandle *xshHandle)
: SetAttributeUndo<std::string>(id, xshHandle, oldHandle, newHandle)
, m_xshHandle(xshHandle) {
TStageObject *pegbar = getStageObject();
if (pegbar) pegbar->getCenterAndOffset(m_center, m_offset);
}
void setAttribute(TStageObject *pegbar, std::string handle) const override {
pegbar->setHandle(handle);
}
void undo() const override {
SetAttributeUndo<std::string>::undo();
TStageObject *pegbar = getStageObject();
if (pegbar) pegbar->setCenterAndOffset(m_center, m_offset);
m_xshHandle->notifyXsheetChanged();
}
QString getActionName() override { return QString("Set Handle"); }
QString getStringFromValue(std::string value) override {
return QString::fromStdString(value);
}
};
//your_sha256_hash---
class SetParentHandleUndo final : public SetAttributeUndo<std::string> {
public:
SetParentHandleUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
std::string oldHandle, std::string newHandle)
: SetAttributeUndo<std::string>(id, xshHandle, oldHandle, newHandle) {}
void setAttribute(TStageObject *pegbar, std::string handle) const override {
pegbar->setParentHandle(handle);
}
QString getActionName() override { return QString("Set Parent Handle"); }
QString getStringFromValue(std::string value) override {
return QString::fromStdString(value);
}
};
//your_sha256_hash---
typedef std::pair<TStageObjectId, std::string> ParentIdAndHandle;
class SetParentUndo final : public SetAttributeUndo<ParentIdAndHandle> {
public:
SetParentUndo(const TStageObjectId &id, TXsheetHandle *xshHandle,
TStageObjectId oldParentId, std::string oldParentHandle,
TStageObjectId newParentId, std::string newParentHandle)
: SetAttributeUndo<ParentIdAndHandle>(
id, xshHandle, ParentIdAndHandle(oldParentId, oldParentHandle),
ParentIdAndHandle(newParentId, newParentHandle)) {}
void setAttribute(TStageObject *pegbar,
ParentIdAndHandle parent) const override {
pegbar->setParent(parent.first);
pegbar->setParentHandle(parent.second);
}
QString getActionName() override { return QString("Set Parent Handle"); }
QString getStringFromValue(ParentIdAndHandle value) override {
return QString("(%1,%2)")
.arg(QString::fromStdString(value.first.toString()))
.arg(QString::fromStdString(value.second));
}
};
//your_sha256_hash---
class ResetPositionUndo final : public TUndo {
TXsheetHandle *m_xshHandle;
TStageObjectId m_id;
TPointD m_center, m_offset;
std::vector<TDoubleKeyframe> m_xKeyframes, m_yKeyframes;
void saveKeyframes(std::vector<TDoubleKeyframe> &keyframes,
const TDoubleParam *param) {
int n = param->getKeyframeCount();
if (n == 0)
keyframes.clear();
else {
keyframes.resize(n);
for (int i = 0; i < n; i++) keyframes[i] = param->getKeyframe(i);
}
}
void deleteAllKeyframes(TDoubleParam *param) const {
while (param->getKeyframeCount() > 0)
param->deleteKeyframe(param->keyframeIndexToFrame(0));
}
void restoreKeyframes(TDoubleParam *param,
const std::vector<TDoubleKeyframe> &keyframes) const {
deleteAllKeyframes(param);
for (int i = 0; i < (int)keyframes.size(); i++)
param->setKeyframe(keyframes[i]);
}
TStageObject *getStageObject() const {
return m_xshHandle->getXsheet()->getStageObject(m_id);
}
public:
ResetPositionUndo(const TStageObjectId &id, TXsheetHandle *xshHandle)
: m_xshHandle(xshHandle), m_id(id) {
TStageObject *stageObject = getStageObject();
if (stageObject) {
stageObject->getCenterAndOffset(m_center, m_offset);
saveKeyframes(m_xKeyframes, stageObject->getParam(TStageObject::T_X));
saveKeyframes(m_yKeyframes, stageObject->getParam(TStageObject::T_Y));
}
}
void undo() const override {
TStageObject *stageObject = getStageObject();
if (!stageObject) return;
stageObject->setCenterAndOffset(m_center, m_offset);
restoreKeyframes(stageObject->getParam(TStageObject::T_X), m_xKeyframes);
restoreKeyframes(stageObject->getParam(TStageObject::T_Y), m_yKeyframes);
m_xshHandle->notifyXsheetChanged();
}
void redo() const override {
TStageObject *stageObject = getStageObject();
if (!stageObject) return;
stageObject->setCenterAndOffset(TPointD(0, 0), TPointD(0, 0));
deleteAllKeyframes(stageObject->getParam(TStageObject::T_X));
deleteAllKeyframes(stageObject->getParam(TStageObject::T_Y));
m_xshHandle->notifyXsheetChanged();
}
int getSize() const override {
return sizeof(*this) + sizeof(TDoubleKeyframe) *
(m_xKeyframes.size() + m_yKeyframes.size());
}
};
//your_sha256_hash---
} // namespace
//===================================================================
//
// pegbar rename
//
//your_sha256_hash---
void TStageObjectCmd::rename(const TStageObjectId &id, std::string name,
TXsheetHandle *xshHandle) {
TStageObject *pegbar = xshHandle->getXsheet()->getStageObject(id);
if (!pegbar) return;
std::string oldName = pegbar->getName();
if (oldName == name) return;
pegbar->setName(name);
TUndoManager::manager()->add(
new StageObjectRenameUndo(id, xshHandle, oldName, name));
}
//===================================================================
//
// resetOffset
//
//your_sha256_hash---
void TStageObjectCmd::resetOffset(const TStageObjectId &id,
TXsheetHandle *xshHandle) {
TStageObject *peg = xshHandle->getXsheet()->getStageObject(id);
if (!peg) return;
TPointD oldOffset = peg->getOffset();
peg->setOffset(TPointD());
TUndoManager::manager()->add(new ResetOffsetUndo(id, xshHandle, oldOffset));
xshHandle->notifyXsheetChanged();
// TNotifier::instance()->notify(TStageChange());
}
//===================================================================
//
// resetCenterAndOffset
//
//your_sha256_hash---
void TStageObjectCmd::resetCenterAndOffset(const TStageObjectId &id,
TXsheetHandle *xshHandle) {
TStageObject *peg = xshHandle->getXsheet()->getStageObject(id);
if (!peg) return;
TPointD oldOffset = peg->getOffset();
peg->setCenterAndOffset(TPointD(), TPointD());
TUndoManager::manager()->add(
new ResetCenterAndOffsetUndo(id, xshHandle, oldOffset));
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// resetPosition
//
//your_sha256_hash---
void TStageObjectCmd::resetPosition(const TStageObjectId &id,
TXsheetHandle *xshHandle) {
TStageObject *obj = xshHandle->getXsheet()->getStageObject(id);
if (!obj) return;
TUndo *undo = new ResetPositionUndo(id, xshHandle);
undo->redo();
TUndoManager::manager()->add(undo);
}
//===================================================================
//
// setHandle
//
//your_sha256_hash---
void TStageObjectCmd::setHandle(const TStageObjectId &id, std::string handle,
TXsheetHandle *xshHandle) {
TStageObject *peg = xshHandle->getXsheet()->getStageObject(id);
if (!peg) return;
std::string oldHandle = peg->getHandle();
TUndoManager::manager()->add(
new SetHandleUndo(id, oldHandle, handle, xshHandle));
peg->setHandle(handle);
}
//===================================================================
//
// setParentHandle
//
//your_sha256_hash---
void TStageObjectCmd::setParentHandle(const std::vector<TStageObjectId> &ids,
std::string handle,
TXsheetHandle *xshHandle) {
for (int i = 0; i < (int)ids.size(); i++) {
TStageObjectId id = ids[i];
TStageObject *peg = xshHandle->getXsheet()->getStageObject(id);
if (!peg) continue;
std::string oldHandle = peg->getParentHandle();
peg->setParentHandle(handle);
TUndoManager::manager()->add(
new SetParentHandleUndo(id, xshHandle, oldHandle, handle));
}
}
//===================================================================
//
// setParent
//
//your_sha256_hash---
void TStageObjectCmd::setParent(const TStageObjectId &id,
TStageObjectId parentId,
std::string parentHandle,
TXsheetHandle *xshHandle, bool doUndo) {
if (parentId == TStageObjectId::NoneId) {
if (id.isColumn() || id.isPegbar()) {
parentId = TStageObjectId::TableId;
parentHandle = "B";
}
}
TStageObject *stageObject = xshHandle->getXsheet()->getStageObject(id);
if (!stageObject) return;
TStageObjectId oldParentId = stageObject->getParent();
std::string oldParentHandle;
if (oldParentId != TStageObjectId::NoneId)
oldParentHandle = stageObject->getParentHandle();
stageObject->setParent(parentId);
stageObject->setParentHandle(parentHandle);
if (doUndo) {
TUndoManager *undoManager = TUndoManager::manager();
TUndoManager::manager()->add(new SetParentUndo(
id, xshHandle, oldParentId, oldParentHandle, parentId, parentHandle));
}
}
//===================================================================
//
// setSplineParent
//
//your_sha256_hash---
void TStageObjectCmd::setSplineParent(TStageObjectSpline *spline,
TStageObject *parentObj,
TXsheetHandle *xshHandle) {
TUndoManager::manager()->add(
new SplineLinkUndo(parentObj->getId(), spline, xshHandle));
parentObj->setSpline(spline);
}
//===================================================================
//
// addNewCamera
//
//your_sha256_hash---
void TStageObjectCmd::addNewCamera(TXsheetHandle *xshHandle,
TObjectHandle *objHandle,
QPointF initialPos) {
TXsheet *xsh = xshHandle->getXsheet();
int cameraIndex = 0;
TStageObjectTree *tree = xsh->getStageObjectTree();
TStageObjectId cameraId;
for (;;) {
cameraId = TStageObjectId::CameraId(cameraIndex);
if (tree->getStageObject(cameraId, false) != 0) {
cameraIndex++;
continue;
}
break;
}
// crea la nuova camera
TStageObject *newCameraPegbar = xsh->getStageObject(cameraId);
// make the new peg at the cursor position
if (!initialPos.isNull())
newCameraPegbar->setDagNodePos(TPointD(initialPos.x(), initialPos.y()));
// settings uguali a quelli della camera corrente
TCamera *currentCamera = tree->getCurrentCamera();
*newCameraPegbar->getCamera() = *currentCamera;
TUndoManager::manager()->add(
new NewCameraUndo(cameraId, xshHandle, objHandle));
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// addNewPegbar
//
//your_sha256_hash---
void TStageObjectCmd::addNewPegbar(TXsheetHandle *xshHandle,
TObjectHandle *objHandle,
QPointF initialPos) {
TXsheet *xsh = xshHandle->getXsheet();
// crea la nuova pegbar
TStageObjectTree *pTree = xsh->getStageObjectTree();
int pegbarIndex = 0;
while (pTree->getStageObject(TStageObjectId::PegbarId(pegbarIndex), false))
pegbarIndex++;
TStageObjectId id = TStageObjectId::PegbarId(pegbarIndex);
TStageObject *obj = pTree->getStageObject(id, true);
if (!initialPos.isNull())
obj->setDagNodePos(TPointD(initialPos.x(), initialPos.y()));
TUndoManager::manager()->add(new NewPegbarUndo(id, xshHandle, objHandle));
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// setAsActiveCamera
//
//your_sha256_hash---
void TStageObjectCmd::setAsActiveCamera(TXsheetHandle *xshHandle,
TObjectHandle *objHandle) {
TXsheet *xsh = xshHandle->getXsheet();
TStageObjectId currentPegbarId = objHandle->getObjectId();
assert(currentPegbarId.isCamera());
TStageObjectId newCameraId = currentPegbarId;
TStageObjectId oldCameraId = xsh->getStageObjectTree()->getCurrentCameraId();
xsh->getStageObjectTree()->setCurrentCameraId(newCameraId);
// make the preview camera same as the final render camera
xsh->getStageObjectTree()->setCurrentPreviewCameraId(newCameraId);
TUndoManager::manager()->add(
new SetActiveCameraUndo(oldCameraId, newCameraId, xshHandle));
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// addNewSpline
//
//your_sha256_hash---
void TStageObjectCmd::addNewSpline(TXsheetHandle *xshHandle,
TObjectHandle *objHandle,
TColumnHandle *colHandle,
QPointF initialPos) {
TXsheet *xsh = xshHandle->getXsheet();
TStageObjectSpline *spline = xsh->getStageObjectTree()->createSpline();
if (!initialPos.isNull())
spline->setDagNodePos(TPointD(initialPos.x(), initialPos.y()));
TStageObjectId objId = objHandle->getObjectId();
if (objId == TStageObjectId::NoneId) {
int col = colHandle->getColumnIndex();
if (col >= 0) objId = TStageObjectId::ColumnId(col);
}
if (objId != TStageObjectId::NoneId) {
TStageObject *pegbar = xsh->getStageObject(objId);
assert(pegbar);
pegbar->setSpline(spline);
TUndoManager::manager()->add(new NewSplineUndo(objId, spline, xshHandle));
}
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// deleteSelection
//
//your_sha256_hash---
void TStageObjectCmd::deleteSelection(
const std::vector<TStageObjectId> &objIds,
const std::list<QPair<TStageObjectId, TStageObjectId>> &links,
const std::list<int> &splineIds, TXsheetHandle *xshHandle,
TObjectHandle *objHandle, TFxHandle *fxHandle, bool doUndo) {
if (doUndo) TUndoManager::manager()->beginBlock();
QVector<int> columnIndexes;
QVector<int> pegbarIndexes;
QVector<int> cameraIndexes;
std::vector<TStageObjectId>::const_iterator it2;
for (it2 = objIds.begin(); it2 != objIds.end(); it2++) {
if (it2->isColumn()) columnIndexes.append(it2->getIndex());
if (it2->isPegbar()) pegbarIndexes.append(it2->getIndex());
if (it2->isCamera()) cameraIndexes.append(it2->getIndex());
}
if (!columnIndexes.isEmpty()) {
std::sort(columnIndexes.begin(), columnIndexes.end());
}
if (!pegbarIndexes.isEmpty()) {
std::sort(pegbarIndexes.begin(), pegbarIndexes.end());
}
if (!cameraIndexes.isEmpty()) {
std::sort(cameraIndexes.begin(), cameraIndexes.end());
}
// remove all selected objects
removeColumns(columnIndexes, xshHandle, objHandle, fxHandle, doUndo);
int i;
for (i = pegbarIndexes.size() - 1; i >= 0; i--)
removeStageObjectNode(TStageObjectId::PegbarId(pegbarIndexes[i]), xshHandle,
objHandle, fxHandle, doUndo);
for (i = cameraIndexes.size() - 1; i >= 0; i--)
removeStageObjectNode(TStageObjectId::CameraId(cameraIndexes[i]), xshHandle,
objHandle, fxHandle, doUndo);
std::list<QPair<TStageObjectId, TStageObjectId>>::const_iterator it1;
for (it1 = links.begin(); it1 != links.end() && objIds.empty(); it1++)
removeLink(*it1, xshHandle, objHandle, doUndo);
std::list<int>::const_iterator it3;
TStageObjectTree *objTree = xshHandle->getXsheet()->getStageObjectTree();
for (it3 = splineIds.begin(); it3 != splineIds.end(); it3++) {
int splineCount = objTree->getSplineCount();
int i;
for (i = 0; i < splineCount; i++) {
TStageObjectSpline *spline = objTree->getSpline(i);
if (spline->getId() == *it3) {
removeSpline(spline, xshHandle, objHandle, doUndo);
break;
}
}
}
if (doUndo) TUndoManager::manager()->endBlock();
xshHandle->notifyXsheetChanged();
}
//===================================================================
//
// group
//
//your_sha256_hash---
void TStageObjectCmd::group(const QList<TStageObjectId> ids,
TXsheetHandle *xshHandle) {
TStageObjectTree *pegTree = xshHandle->getXsheet()->getStageObjectTree();
int groupId = pegTree->getNewGroupId();
int i;
QList<int> positions;
for (i = 0; i < ids.size(); i++) {
TStageObject *obj = pegTree->getStageObject(ids[i], false);
if (obj) {
int position = obj->setGroupId(groupId);
obj->setGroupName(L"Group " + std::to_wstring(groupId));
positions.append(position);
}
}
TUndoManager::manager()->add(
new UndoGroup(ids, groupId, positions, xshHandle));
}
//===================================================================
//
// ungroup
//
//your_sha256_hash---
void TStageObjectCmd::ungroup(int groupId, TXsheetHandle *xshHandle) {
TStageObjectTree *objTree = xshHandle->getXsheet()->getStageObjectTree();
if (!objTree) return;
QList<TStageObject *> objs;
int i;
for (i = 0; i < objTree->getStageObjectCount(); i++) {
TStageObject *obj = objTree->getStageObject(i);
if (!obj) continue;
if (obj->getGroupId() == groupId) objs.push_back(obj);
}
QList<int> positions;
UndoUngroup *undo = new UndoUngroup(objs, xshHandle);
TUndoManager::manager()->add(undo);
for (i = 0; i < objs.size(); i++) {
TStageObject *obj = objs[i];
if (obj) {
obj->removeGroupName();
int position = obj->removeGroupId();
positions.append(position);
}
}
undo->setStackPositions(positions);
}
//===================================================================
//
// renameGroup
//
//your_sha256_hash---
void TStageObjectCmd::renameGroup(const QList<TStageObject *> objs,
const std::wstring &name, bool fromEditor,
TXsheetHandle *xshHandle) {
std::wstring oldName;
TStageObjectTree *pegTree = xshHandle->getXsheet()->getStageObjectTree();
QList<int> positions;
int i;
for (i = 0; i < objs.size(); i++) {
if (i == 0) oldName = objs[i]->getGroupName(fromEditor);
int position = objs[i]->removeGroupName(fromEditor);
objs[i]->setGroupName(name, position);
positions.push_back(position);
}
TUndoManager::manager()->add(
new UndoRenameGroup(objs, positions, name, oldName, xshHandle));
}
//===================================================================
//
// renameGroup
//
//your_sha256_hash---
void TStageObjectCmd::duplicateObject(const QList<TStageObjectId> ids,
TXsheetHandle *xshHandle) {
TXsheet *xsh = xshHandle->getXsheet();
TStageObjectTree *objTree = xsh->getStageObjectTree();
int i, objCount = ids.size();
for (i = 0; i < objCount; i++) {
TStageObjectId id = ids[i];
TStageObject *obj = objTree->getStageObject(id, false);
assert(obj);
TStageObject *duplicatedObj = 0;
if (id.isPegbar() || id.isCamera()) {
int index = 0;
TStageObjectId newId;
for (;;) {
newId = id.isPegbar() ? TStageObjectId::PegbarId(index)
: TStageObjectId::CameraId(index);
if (objTree->getStageObject(newId, false)) {
index++;
continue;
}
break;
}
duplicatedObj = xsh->getStageObject(newId);
TStageObjectParams *params = obj->getParams();
duplicatedObj->assignParams(params);
delete params;
if (id.isCamera()) *(duplicatedObj->getCamera()) = *(obj->getCamera());
}
}
xshHandle->notifyXsheetChanged();
}
//your_sha256_hash---
void TStageObjectCmd::enableSplineAim(TStageObject *obj, int state,
TXsheetHandle *xshHandle) {
UndoStatusChange *undo = new UndoStatusChange(obj, xshHandle);
obj->enableAim(state != 2);
TUndoManager::manager()->add(undo);
}
//your_sha256_hash---
void TStageObjectCmd::enableSplineUppk(TStageObject *obj, bool toggled,
TXsheetHandle *xshHandle) {
UndoStatusChange *undo = new UndoStatusChange(obj, xshHandle);
obj->enableUppk(toggled);
TUndoManager::manager()->add(undo);
}
```
|
```emacs lisp
;;; telega-vvnote.el --- Voice/Video notes support for telega -*- lexical-binding:t -*-
;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;; Created: Mon Jan 21 22:12:55 2019
;; Keywords:
;; telega is free software: you can redistribute it and/or modify
;; (at your option) any later version.
;; telega is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with telega. If not, see <path_to_url
;;; Commentary:
;;
;;; Code:
(require 'bindat) ;binary parsing
(require 'telega-ffplay)
(require 'telega-util) ;`with-telega-symbol-animate'
(defcustom telega-vvnote-voice-max-dur (* 30 60)
"Maximum duration of voice command in seconds."
:type 'number
:group 'telega-vvnote)
(defcustom telega-vvnote-waves-colors '("#006600" . "#229922")
"Colors to display voice note waves."
:type '(cons color color)
:group 'telega-vvnote)
(defcustom telega-vvnote-play-speed 1
"*Playback speed for voice/video notes."
:package-version '(telega . "0.7.52")
:type 'number
:group 'telega-vvnote)
(defcustom telega-vvnote-play-next t
"*After playing voice note continue playing next voice note in the chat."
:package-version '(telega . "0.7.52")
:type 'boolean
:group 'telega-vvnote)
(defconst telega-vvnote--has-audio-inputs
(car (telega-ffplay--check-ffmpeg-output
"-devices" "alsa" "pulse"))
"List of audio inputs supported by telega.")
(defcustom telega-vvnote-voice-record-args
(concat (if (eq system-type 'darwin)
"-f avfoundation -i :default"
;; gnu/linux
(concat "-f " (car telega-vvnote--has-audio-inputs)
" -i default"))
(cond ((telega-ffplay-has-encoder-p "opus")
;; Try OPUS if available, results in 3 times smaller
;; files then AAC version with same sound quality
" -strict -2 -acodec opus -ac 1 -ab 32k")
((telega-ffplay-has-encoder-p "aac")
" -acodec aac -ac 1 -ab 96k")
(t
" -acodec mp3 -ar 44100 -ac 1 -ab 96k")))
"Arguments to ffmpeg to record a voice note."
:package-version '(telega . "0.7.53")
:type 'string
:group 'telega-vvnote)
(defcustom telega-vvnote-video-record-args
(concat (if (eq system-type 'darwin)
"-f avfoundation -s 640x480 -framerate 30 -i default -r 30 -f avfoundation -i :default"
;; gnu/linux
(concat "-f v4l2 -s 320x240 -i /dev/video0 -r 30 "
"-f " (car telega-vvnote--has-audio-inputs) " -i default"))
" -vf format=yuv420p,scale=320:240,crop=240:240:40:0"
" -vcodec " (if (telega-ffplay-has-encoder-p "hevc")
"hevc"
"h264")
" -vb 300k"
(if (telega-ffplay-has-encoder-p "opus")
" -strict -2 -acodec opus -ac 1 -ab 32k"
;; Fallback to aac
" -acodec aac -ac 1 -ab 96k"))
"Arguments to ffmpeg to record a video note."
:package-version '(telega . "0.7.53")
:type 'string
:group 'telega-vvnote)
(defun telega-vvnote--waves-squeeze (waves factor)
"Squeeze the decoded WAVES by FACTOR."
;; Squeeze by averaging and normalizing
(let* ((min-o (apply 'min waves))
(max-o (apply 'max waves))
(nw (mapcar (lambda (p)
(/ (apply '+ p) factor))
(seq-partition waves factor)))
(min-n (apply 'min nw))
(min-normw (mapcar (lambda (v) (- v min-n)) nw))
(n-factor (/ (- max-o min-o) (apply 'max min-normw))))
(mapcar (lambda (v) (+ min-o (* v n-factor))) min-normw)))
(defun telega-vvnote--waves-svg (waves height duration &optional played)
"From decoded WAVES create svg of HEIGHT for DURATION and PLAYED."
(cl-assert (> height 8))
(let* ((w-idx 0)
(wv-width 3) (space-width 2)
(wv-height (- height 6))
(w (* (+ wv-width space-width) (length waves)))
(aw-chars (telega-chars-in-width w))
(cw (telega-chars-xwidth aw-chars))
(svg (telega-svg-create cw height)))
;; bg - "#e1ffc7", fg - "#93d987", fg-played - "#3fc33b"
;; (svg-rectangle svg 0 0 w h :fill-color "#e1ffc7")
(dolist (wv waves)
(let ((xoff (+ wv-width (* (+ wv-width space-width) w-idx)))
(played-p (< (/ (float w-idx) (length waves))
(/ (or played 0) (if (zerop duration) 0.1 duration)))))
(svg-line svg xoff (- height 3 (if played-p 0.5 0)) xoff
(- height 3 (if played-p 0.5 0) (* wv wv-height))
:stroke-color (if played-p
(car telega-vvnote-waves-colors)
(cdr telega-vvnote-waves-colors))
:stroke-width (if played-p (1+ wv-width) wv-width)
:stroke-linecap "round")
(cl-incf w-idx)))
(telega-svg-image svg
:scale 1
:width (telega-cw-width aw-chars)
:mask 'heuristic
:ascent 'center
;; text of correct width
:telega-text (make-string aw-chars ?#))))
;; Encoding and Decoding splits into two situations:
;; head-bits=5 tail-bits=0
;; v v v v v
;; 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
;; * X X X X X * * * * * * * * * *
;; `-- bitoff here bwv1
;; and:
;; head-bits=3 tail-bits=2
;; v v v v v
;; 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
;; * * * * * X X X X X * * * * * *
;; bwv0 `-- bitoff here bwv1
;;
;; Handle them both correctly
(defun telega-vvnote--waveform-decode (waveform &optional raw-p)
"Decode WAVEFORM returning list of heights.
Unless RAW-P is given, heights are normalized to [0-1] values."
(let ((bwv (base64-decode-string waveform))
(bitoff 0)
result)
(while (not (string-empty-p bwv))
(let* ((bwv0 (aref bwv 0))
(bwv1 (if (> (length bwv) 1) (aref bwv 1) 0))
(head-bits (min 5 (- 8 bitoff)))
(tail-bits (- 5 head-bits))
(h-value (ash (logand bwv0 (ash 255 (- bitoff)))
(- (+ bitoff head-bits) 8)))
(t-value (ash bwv1 (- tail-bits 8))))
(setq result (cons (logior (ash h-value tail-bits) t-value) result)
bitoff (+ bitoff 5))
(when (>= bitoff 8)
(cl-assert (= (- bitoff 8) tail-bits))
(setq bwv (substring bwv 1)
bitoff (- bitoff 8)))))
(mapcar (lambda (v) (if raw-p v (/ v 31.0))) (nreverse result))))
(defun telega-vvnote--waveform-encode (waveform)
"Encode WAVEFORM into base64 based form.
WAVEFORM is list of integers each in range [0-31] to fit into 5 bits."
(cl-assert (cl-every (apply-partially #'>= 31) waveform))
(let ((bytes nil) ; resulting bytes
(bitoff 0) ; bit offset inside `value'
(value 0)) ; currently composing value
(dolist (w-value waveform)
(cl-assert (< bitoff 8))
(let* ((head-bits (min 5 (- 8 bitoff)))
(tail-bits (- 5 head-bits))
(h-value (ash (logand w-value (ash 31 tail-bits)) (- tail-bits)))
(t-value (logand w-value (ash 31 (- head-bits)))))
;; Write head-bits
(setq value (logior value (ash h-value (- 8 (+ bitoff head-bits))))
bitoff (+ bitoff 5))
;; Write tail bits
(when (>= bitoff 8)
(cl-assert (= (- bitoff 8) tail-bits))
(setq bytes (cons value bytes)
bitoff (- bitoff 8)
value (ash t-value (- 8 bitoff))))))
(base64-encode-string (apply #'unibyte-string (nreverse bytes)) t)))
(defun telega-vvnote--wav-samples ()
"Parse current buffer as wav file extracting audio samples.
Each sample is in range [-128;128]."
(let* ((wav-data (buffer-string))
(wav-bindat-spec
'((:riff str 4) ;"RIFF"
(:chunk-size u32r)
(:format str 4) ;"WAVE"
(:subchunk1-id str 4) ;"fmt "
(:subchunk1-sz u32r)
(:audio-format u16r)
(:num-channels u16r)
(:sample-rate u32r)
(:byte-rate u32r)
(:block-align u16r)
(:bits-per-sample u16r)
(:subchunk2-id str 4) ;"data" or "LIST"
(:subchunk2-sz u32r)))
(wav-header
(bindat-unpack wav-bindat-spec wav-data))
(data-offset 44)
(data-size (bindat-get-field wav-header :subchunk2-sz)))
(cl-assert (string= "RIFF" (bindat-get-field wav-header :riff)))
(cl-assert (string= "WAVE" (bindat-get-field wav-header :format)))
(cl-assert (string= "fmt " (bindat-get-field wav-header :subchunk1-id)))
(when (string= "LIST" (bindat-get-field wav-header :subchunk2-id))
(let ((data-header (bindat-unpack
`((:skipped fill ,data-size)
(:subchunk3-id str 4)
(:subchunk3-sz u32r))
wav-data data-offset)))
(setq data-offset (+ data-offset data-size 8)
data-size (bindat-get-field data-header :subchunk3-sz))))
(mapcar (lambda (v) (- v 128))
(bindat-get-field (bindat-unpack `((:wave vec ,data-size u8))
wav-data data-offset)
:wave))
))
(defun telega-vvnote--waveform-for-file (filename)
"Create a waveform for audio FILENAME."
(let* ((temp-wav (telega-temp-name "audio" ".wav"))
(samples (progn
;; Use `shell-command-to-string' to avoid noisy
;; message when shell completes
(shell-command-to-string
(telega-docker-exec-cmd
(concat "ffmpeg -v error "
"-i \"" (expand-file-name filename) "\" "
"-ar 8000 -ac 1 "
"-acodec pcm_u8 \"" temp-wav "\"")
'try-host-cmd-first))
(unless (file-exists-p temp-wav)
(error "telega: Can't extract waves from %s" filename))
(unwind-protect
(with-temp-buffer
(set-buffer-multibyte nil)
(insert-file-contents-literally temp-wav)
(telega-vvnote--wav-samples))
(delete-file temp-wav))))
(frac-samples
(seq-partition samples (1+ (/ (length samples) 96))))
;; Calculate loudness as root mean square, this gives "good
;; enough" results, suitable for our needs
(loud-samples
(mapcar (lambda (quant-samples)
(sqrt (/ (cl-reduce #'+ (mapcar (lambda (x) (* x x))
quant-samples))
(length quant-samples))))
frac-samples))
(log10-samples
(mapcar (lambda (ms) (if (> ms 0) (log ms 10) 0)) loud-samples))
;; Normalize values to fit into [0-31] so each value could be
;; encoded into 5bits.
;; NOTE: Avoid division by 0 if all log10-samples are zeroes
(n-factor (/ 31.0 (apply #'max 1 log10-samples)))
(n-waves
(mapcar (lambda (wave-value) (round (* wave-value n-factor)))
log10-samples)))
(cl-assert (cl-every (apply-partially #'>= 31) n-waves))
(telega-vvnote--waveform-encode n-waves)))
(cl-defun telega-vvnote-video--svg (framefile &key as-data-image-type
progress with-noise-p)
"Generate svg image for the video note FRAMEFILE.
PROGRESS is value from 0 to 1 indicating played content.
PROGRESS might be nil, meaning video not is not started.
PROGRESS also can be a cons cell, where car is `paused' and cdr is
value from 0 to 1, meaning video note is paused at given progress.
If AS-DATA-IMAGE-TYPE is non-nil, then FRAMEFILE is actually an image
data and AS-DATA-IMAGE-TYPE specifies type of the image.
If WITH-NOISE-P is non-nil, then use noise filter above the image."
(declare (indent 1))
(let* ((data-p (when as-data-image-type t))
(img-type (or as-data-image-type
(telega-image-supported-file-p framefile)))
(ah-chars (if (consp telega-video-note-height)
(car telega-video-note-height)
telega-video-note-height))
(size (telega-chars-xheight ah-chars))
(h size)
(aw-chars (telega-chars-in-width size))
(w (telega-chars-xwidth aw-chars))
(xoff (/ (- w size) 2))
(yoff (/ (- h size) 2))
(svg (telega-svg-create w h))
(clip (telega-svg-clip-path svg "clip"))
(clip1 (telega-svg-clip-path svg "clip1"))
(playing-p (numberp progress)))
(svg-circle clip (/ w 2) (/ h 2) (/ size 2))
(when with-noise-p
(telega-svg-append-spoiler-node svg "noise"))
(telega-svg-embed svg (if data-p
framefile
(list (file-name-nondirectory framefile)
(file-name-directory framefile)))
(format "image/%S" img-type) data-p
:x xoff :y yoff
:width size :height size
:filter (when with-noise-p
"url(#noise)")
:clip-path "url(#clip)")
(when progress
;; Extract progress number in case progress is in the
;; (paused . progress) form
(when (consp progress)
(cl-assert (and (eq (car progress) 'paused)
(numberp (cdr progress))))
(setq progress (cdr progress)))
(let* ((angle-o (* 2 float-pi progress))
(angle (+ (* 2 float-pi (- progress)) float-pi))
(dx (+ (* (/ size 2) (sin angle)) (/ size 2)))
(dy (+ (* (/ size 2) (cos angle)) (/ size 2))))
;; clip mask for the progress circle
(let ((cp (format "M %d %d L %d %d L %d 0" (/ w 2) (/ h 2) (/ w 2) 0 w)))
(when (> angle-o (/ float-pi 2))
(setq cp (concat cp (format " L %d %d" w h))))
(when (> angle-o float-pi)
(setq cp (concat cp (format " L 0 %d" h))))
(when (> angle-o (/ (* 3 float-pi) 2))
(setq cp (concat cp (format " L 0 0"))))
(setq cp (concat cp (format " L %d %d" (+ dx xoff) (+ dy yoff))))
(setq cp (concat cp " Z"))
(telega-svg-path clip1 cp))
;; Progress circle itself
(svg-circle svg (/ w 2) (/ h 2) (- (/ size 2) 4)
:fill "none"
:stroke-width (/ size 30)
:stroke-opacity "0.35"
:stroke-color "white"
:clip-path "url(#clip1)")))
;; Draw play triangle
(unless playing-p
(let ((play-size (/ h 6)))
(svg-polygon svg (list (cons (/ (- w play-size) 2)
(/ (- h play-size) 2))
(cons (/ (- w play-size) 2)
(/ (+ h play-size) 2))
(cons (/ (+ w play-size) 2)
(/ h 2)))
:fill "red"
:opacity "0.5")))
(telega-svg-image svg
:scale 1.0
:height (telega-ch-height ah-chars)
;; NOTE: Do not use `:telega-nslices' because when watching
;; video note it grows in size
; :telega-nslices ah-chars
:mask 'heuristic
:ascent 'center
:base-uri (if data-p "" framefile)
:telega-text (make-string aw-chars ?#))))
(defun telega-vvnote-video--create-image (note &optional _file with-noise-p)
"Create image for video NOTE frame."
(let* ((thumb (plist-get note :thumbnail))
(thumb-file (telega-file--renew thumb :file))
(minithumb (plist-get note :minithumbnail)))
(cond ((telega-file--downloaded-p thumb-file)
(telega-vvnote-video--svg
(telega--tl-get thumb-file :local :path)
:with-noise-p with-noise-p))
(minithumb
(telega-vvnote-video--svg
(base64-decode-string (plist-get minithumb :data))
:as-data-image-type 'jpeg
:with-noise-p with-noise-p))
(t
(let* ((cheight (if (consp telega-video-note-height)
(car telega-video-note-height)
telega-video-note-height))
(x-size (telega-chars-xheight cheight)))
(telega-media--progress-svg thumb-file x-size x-size cheight))))))
(defun telega-vvnote-video-ttl--create-image (note &optional file)
(telega-vvnote-video--create-image note file :with-noise))
;; Recording notes
(defvar telega-vvnote--record-progress nil
"Current record progress.
Set to nil, when ffplay exists.")
(defun telega-vvnote--record-callback (proc)
"Progress callback for the video/voice note recording."
(let ((proc-plist (process-plist proc)))
(setq telega-vvnote--record-progress
(when (process-live-p proc)
(plist-get proc-plist :progress)))))
(defun telega-vvnote-voice--record ()
"Record a voice note.
Return filename with recorded voice note."
(let* ((telega-vvnote--record-progress 0)
(note-file (telega-temp-name "voice-note" ".mp4"))
(capture-proc (telega-ffplay-run-command
(telega-docker-exec-cmd
(concat "ffmpeg" " " telega-vvnote-voice-record-args
" " note-file)
'try-host-cmd-first)
#'telega-vvnote--record-callback))
(done-key
(progn
;; Wait for ffmpeg process to start
(accept-process-output capture-proc)
;; Capture voice note
(with-telega-symbol-animate 'audio 0.1 audio-sym
;; Animation exit condition
(or (not telega-vvnote--record-progress)
(not (process-live-p capture-proc)))
(let (message-log-max)
(message (concat "telega: "
(propertize "" 'face 'error)
"VoiceNote " audio-sym
" " (telega-duration-human-readable
telega-vvnote--record-progress)
" Press a key when done, C-g to cancel")))))))
;; Gracefully stop capturing and wait ffmpeg for exit
(when (process-live-p capture-proc)
(interrupt-process capture-proc)
(while (process-live-p capture-proc)
(accept-process-output capture-proc)))
(unless (file-exists-p note-file)
(error "telega: Can't capture voice note"))
;; C-g = 7
(when (eq done-key 7)
(delete-file note-file)
(user-error "VoiceNote cancelled"))
note-file))
(defvar telega-vvnote-video--preview nil
"Plist holding preview for video note recording.")
(defun telega-vvnote-video--record-callback (_proc frame)
"Callback when recording video note."
;; NOTE: fps = 30, hardcoded in `telega-vvnote-video-record-args'
(let ((start (plist-get telega-vvnote-video--preview :start-point)))
(with-current-buffer (marker-buffer start)
(unless (= (point) start)
(delete-region start (point)))
(when frame
(setq telega-vvnote--record-progress (/ (car frame) 30.0))
;; Copy first frame
(when (= 1 (car frame))
(let ((first-frame (telega-temp-name "video-note1" ".png")))
(copy-file (cdr frame) first-frame 'ok-if-exists)
(plist-put telega-vvnote-video--preview :first-frame first-frame)))
;; Display frame
(telega-ins--image
(telega-vvnote-video--svg (cdr frame)))))))
(defun telega-vvnote-video--record ()
"Record a video note.
Return filename with recorded video note."
;; Check codecs availability
(when (or (and (not (telega-ffplay-has-encoder-p "opus"))
(not (telega-ffplay-has-encoder-p "aac")))
(and (not (telega-ffplay-has-encoder-p "hevc"))
(not (telega-ffplay-has-encoder-p "h264"))))
(user-error "telega: sorry, your ffmpeg can't record video notes"))
(setq telega-vvnote-video--preview
(list :start-point (copy-marker (point))))
(let* ((telega-vvnote--record-progress 0)
(note-file (telega-temp-name "video-note" ".mp4"))
(ffmpeg-args
(concat telega-vvnote-video-record-args
" " note-file
" -f image2pipe"
" -vf hflip,scale=320:240,crop=240:240:40:0"
" -vcodec png -"))
(capture-proc (telega-ffplay-to-png--internal ffmpeg-args
#'telega-vvnote-video--record-callback))
(done-key
(progn
;; Wait for ffmpeg process to start
(accept-process-output capture-proc)
(with-telega-symbol-animate 'video 0.25 video-sym
;; Animation exit condition
(or (not telega-vvnote--record-progress)
(not (process-live-p capture-proc)))
;; Animation body
(let (message-log-max)
(message (concat "telega: "
(propertize video-sym 'face 'error)
"VideoNote "
(format "%.1fs" telega-vvnote--record-progress)
" Press a key when done, C-g to cancel")))))))
;; Gracefully stop capturing and wait ffmpeg for exit
(when (process-live-p capture-proc)
(internal-default-interrupt-process capture-proc)
(while (process-live-p capture-proc)
(accept-process-output capture-proc)))
(unless (file-exists-p note-file)
(error "telega: Can't capture video note"))
;; C-g = 7
(when (eq done-key 7)
(delete-file note-file)
(user-error "VideoNote cancelled"))
note-file))
;; Callbacks for ffplay controls, used by `telega-msg-button-map'
(defun telega-msg--vvnote-play-speed-toggle (msg)
"Toggle playback speed for the media message.
Only two modes are available: normal speed and x2 speed."
(interactive (list (telega-msg-for-interactive)))
(when-let ((proc (plist-get msg :telega-ffplay-proc)))
(if (equal telega-vvnote-play-speed 1)
(setq telega-vvnote-play-speed 1.8)
(setq telega-vvnote-play-speed 1))
(telega-msg-redisplay msg)
;; Restart ffplay by reopenning message content
(when (telega-ffplay-playing-p proc)
(telega-ffplay-pause proc nil 'ignore-callback)
(telega-msg-open-content msg))))
(defun telega-msg--vvnote-stop (msg)
"Stop playing media message."
(interactive (list (telega-msg-for-interactive)))
(when-let ((proc (plist-get msg :telega-ffplay-proc)))
(telega-ffplay-stop proc)
;; Force stop for possibly paused process
(when (telega-ffplay-paused-p proc)
(plist-put msg :telega-ffplay-frame nil)
(plist-put msg :telega-ffplay-proc nil)
(telega-msg-redisplay msg))))
(defun telega-msg--vvnote-rewind (msg step)
"Rewind current ffplay position by STEP."
(let ((proc (plist-get msg :telega-ffplay-proc)))
(when (telega-ffplay-playing-p proc)
(telega-ffplay-pause
proc (+ step (or (telega-ffplay-progress proc) 0)) 'ignore-callback)
(telega-msg-open-content msg))))
(defun telega-msg--vvnote-rewind-10-forward (msg)
"Rewind 10 seconds forward."
(interactive (list (telega-msg-for-interactive)))
(telega-msg--vvnote-rewind msg 10))
(defun telega-msg--vvnote-rewind-10-backward (msg)
"Rewind 10 seconds backward."
(interactive (list (telega-msg-for-interactive)))
(telega-msg--vvnote-rewind msg -10))
(defun telega-msg--vvnote-rewind-part (msg)
"Rewind to the N's 10 part of the message duration.
I.e. if you press 7, then you will jump to 70% of the message
duration."
(interactive (list (telega-msg-for-interactive)))
(when-let ((proc (plist-get msg :telega-ffplay-proc)))
(let* ((content (plist-get msg :content))
(duration (cl-case (telega--tl-type content)
(messageVoiceNote
(telega--tl-get content :voice_note :duration))
(messageVideoNote
(telega--tl-get content :video_note :duration))
(messageAudio
(telega--tl-get content :audio :duration))
(t
;; Possibly a element embedded into webpage
(let ((web-page (plist-get content :web_page)))
(plist-get (or (plist-get web-page :audio)
(plist-get web-page :video_note)
(plist-get web-page :voice_note))
:duration)))))
(n-part (string-to-number (this-command-keys))))
(cl-assert (< 0 n-part 10))
(when (and (telega-ffplay-playing-p proc) duration)
(telega-ffplay-pause
proc (floor (* (/ n-part 10.0) duration)) 'ignore-callback)
(telega-msg-open-content msg)))))
(provide 'telega-vvnote)
;;; telega-vvnote.el ends here
```
|
```html
<!--
(See accompanying file LICENSE.md or copy at path_to_url
-->
<!-- boost-no-inspect -->
<!-- HTML header for doxygen 1.8.9.1-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url">
<html xmlns="path_to_url">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Boost.Hana: User Manual</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
// (See accompanying file LICENSE.md or copy at path_to_url
MathJax.Hub.Config({
"HTML-CSS": {
linebreaks: {
automatic: true,
width: "75% container"
}
}
});
</script><script type="text/javascript" src="path_to_url"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<!-- Additional javascript for drawing charts. -->
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="highcharts-data.js"></script>
<script type="text/javascript" src="highcharts-exporting.js"></script>
<script type="text/javascript" src="chart.js"></script>
<script type="text/javascript" src="hana.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="Boost.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Boost.Hana
 <span id="projectnumber">1.3.0</span>
</div>
<div id="projectbrief">Your standard library for metaprogramming</div>
</td>
<td> <div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('index.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">User Manual </div> </div>
</div><!--header-->
<div class="contents">
<div class="toc"><h3>Table of Contents</h3>
<ul><li class="level1"><a href="#tutorial-description">Description</a></li>
<li class="level1"><a href="#tutorial-installation">Prerequisites and installation</a><ul><li class="level2"><a href="#tutorial-installation-cmake">Note for CMake users</a></li>
<li class="level2"><a href="#tutorial-installation-requirements">Compiler requirements</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-support">Support</a></li>
<li class="level1"><a href="#tutorial-introduction">Introduction</a><ul><li class="level2"><a href="#tutorial-introduction-quadrants">C++ computational quadrants</a></li>
<li class="level2"><a href="#tutorial-quadrants-about">What is this library about?</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-quickstart">Quick start</a><ul><li class="level2"><a href="#tutorial-quickstart-any">A real world example</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-cheatsheet">Cheatsheet</a></li>
<li class="level1"><a href="#tutorial-assert">Assertions</a></li>
<li class="level1"><a href="#tutorial-integral">Compile-time numbers</a><ul><li class="level2"><a href="#tutorial-integral-arithmetic">Compile-time arithmetic</a></li>
<li class="level2"><a href="#tutorial-integral-distance">Example: Euclidean distance</a></li>
<li class="level2"><a href="#tutorial-integral-branching">Compile-time branching</a></li>
<li class="level2"><a href="#tutorial-integral-more">Why stop here?</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-type">Type computations</a><ul><li class="level2"><a href="#tutorial-type-objects">Types as objects</a></li>
<li class="level2"><a href="#tutorial-type-benefits">Benefits of this representation</a></li>
<li class="level2"><a href="#tutorial-type-working">Working with this representation</a></li>
<li class="level2"><a href="#tutorial-type-lifting">The generic lifting process</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-introspection">Introspection</a><ul><li class="level2"><a href="#tutorial-introspection-is_valid">Checking expression validity</a><ul><li class="level3"><a href="#tutorial-introspection-is_valid-non_static">Non-static members</a></li>
<li class="level3"><a href="#tutorial-introspection-is_valid-static">Static members</a></li>
<li class="level3"><a href="#tutorial-introspection-is_valid-typename">Nested type names</a></li>
<li class="level3"><a href="#tutorial-introspection-is_valid-template">Nested templates</a></li>
</ul>
</li>
<li class="level2"><a href="#tutorial-introspection-sfinae">Taking control of SFINAE</a></li>
<li class="level2"><a href="#tutorial-introspection-adapting">Introspecting user-defined types</a></li>
<li class="level2"><a href="#tutorial-introspection-json">Example: generating JSON</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-containers">Generalities on containers</a><ul><li class="level2"><a href="#tutorial-containers-creating">Container creation</a></li>
<li class="level2"><a href="#tutorial-containers-types">Container types</a><ul><li class="level3"><a href="#tutorial-containers-types-overloading">Overloading on container types</a></li>
</ul>
</li>
<li class="level2"><a href="#tutorial-containers-elements">Container elements</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-algorithms">Generalities on algorithms</a><ul><li class="level2"><a href="#tutorial-algorithms-value">By-value semantics</a></li>
<li class="level2"><a href="#tutorial-algorithms-laziness">(Non-)Laziness</a></li>
<li class="level2"><a href="#tutorial-algorithms-codegen">What is generated?</a></li>
<li class="level2"><a href="#tutorial-algorithms-effects">Side effects and purity</a></li>
<li class="level2"><a href="#tutorial-algorithms-cross_phase">Cross-phase algorithms</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-performance">Performance considerations</a><ul><li class="level2"><a href="#tutorial-performance-compile">Compile-time performance</a></li>
<li class="level2"><a href="#tutorial-performance-runtime">Runtime performance</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-ext">Integration with external libraries</a></li>
<li class="level1"><a href="#tutorial-core">Hana's core</a><ul><li class="level2"><a href="#tutorial-core-tags">Tags</a></li>
<li class="level2"><a href="#tutorial-core-tag_dispatching">Tag dispatching</a></li>
<li class="level2"><a href="#tutorial-core-concepts">Emulation of C++ concepts</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-header_organization">Header organization</a></li>
<li class="level1"><a href="#tutorial-conclusion">Conclusion</a><ul><li class="level2"><a href="#tutorial-conclusion-warning">Fair warning: functional programming ahead</a></li>
<li class="level2"><a href="#tutorial-conclusion-related_material">Related material</a></li>
<li class="level2"><a href="#tutorial-conclusion-projects_using_hana">Projects using Hana</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-reference">Using the reference</a><ul><li class="level2"><a href="#tutorial-reference-signatures">Function signatures</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-acknowledgements">Acknowledgements</a></li>
<li class="level1"><a href="#tutorial-glossary">Glossary</a></li>
<li class="level1"><a href="#tutorial-rationales">Rationales/FAQ</a><ul><li class="level2"><a href="#tutorial-rationales-dependencies">Why restrict usage of external dependencies?</a></li>
<li class="level2"><a href="#tutorial-rationales-iterators">Why no iterators?</a></li>
<li class="level2"><a href="#tutorial-rationales-container_representation">Why leave some container's representation implementation-defined?</a></li>
<li class="level2"><a href="#tutorial-rationales-why_Hana">Why Hana?</a></li>
<li class="level2"><a href="#tutorial-rationales-tuple">Why define our own tuple?</a></li>
<li class="level2"><a href="#tutorial-rationales-naming">How are names chosen?</a></li>
<li class="level2"><a href="#tutorial-rationales-parameters">How is the parameter order decided?</a></li>
<li class="level2"><a href="#tutorial-rationales-tag_dispatching">Why tag dispatching?</a></li>
<li class="level2"><a href="#tutorial-rationales-zip_longest">Why not provide zip_longest?</a></li>
<li class="level2"><a href="#tutorial-rationales-concepts">Why aren't concepts constexpr functions?</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-appendix-constexpr">Appendix I: Advanced constexpr</a><ul><li class="level2"><a href="#tutorial-appendix-constexpr-stripping">Constexpr stripping</a></li>
<li class="level2"><a href="#tutorial-tutorial-appendix-constexpr-preservation">Constexpr preservation</a></li>
<li class="level2"><a href="#tutorial-appendix-constexpr-effects">Side effects</a></li>
</ul>
</li>
<li class="level1"><a href="#tutorial-appendix-MPL">Appendix II: A minimal MPL</a></li>
</ul>
</div>
<div class="textblock"><h1><a class="anchor" id="tutorial-description"></a>
Description</h1>
<hr/>
<p> Hana is a header-only library for C++ metaprogramming suited for computations on both types and values. The functionality it provides is a superset of what is provided by the well established <a href="path_to_url">Boost.MPL</a> and <a href="path_to_url">Boost.Fusion</a> libraries. By leveraging C++11/14 implementation techniques and idioms, Hana boasts faster compilation times and runtime performance on par or better than previous metaprogramming libraries, while noticeably increasing the level of expressiveness in the process. Hana is easy to extend in a ad-hoc manner and it provides out-of-the-box inter-operation with Boost.Fusion, Boost.MPL and the standard library.</p>
<h1><a class="anchor" id="tutorial-installation"></a>
Prerequisites and installation</h1>
<hr/>
<p> Hana is a header-only library without external dependencies (not even the rest of Boost). Hence, using Hana in your own project is very easy. Basically, just download the project and add the <code>include/</code> directory to your compiler's header search path and you are done. However, if you want to cleanly install Hana, you have a couple of options:</p>
<ol type="1">
<li><b>Install Boost</b><br />
Hana is included in the <a href="path_to_url">Boost</a> distribution starting from Boost 1.61.0, so installing that will give you access to Hana.</li>
<li><b>Use Homebrew</b><br />
On Mac OS, Hana can be installed with <a href="path_to_url">Homebrew</a>: <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> brew install hana</div></div><!-- fragment --></li>
<li><b>Install manually</b><br />
You can download the code from the official GitHub <a href="path_to_url">repository</a> and install the library manually by issuing the following commands from the root of the project (requires <a href="path_to_url">CMake</a>): <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> mkdir build && cd build</div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span> cmake ..</div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span> cmake --build . --target install</div></div><!-- fragment --> This will install Hana to the default install-directory for your platform (<code>/usr/local</code> for Unix, <code>C:/Program Files</code> for Windows). If you want to install Hana in a custom location, you can use <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> cmake .. -DCMAKE_INSTALL_PREFIX=/custom/install/prefix</div></div><!-- fragment --></li>
</ol>
<p>If you just want to contribute to Hana, you can see how to best setup your environment for development in the <a href="path_to_url#hacking-on-hana">README</a>.</p>
<dl class="section note"><dt>Note</dt><dd><ul>
<li>Both the manual installation and the Homebrew installation will also install a <code>HanaConfig.cmake</code> file for use with CMake and a <code>hana.pc</code> file for use with <a href="path_to_url">pkg-config</a>.</li>
<li>Do not mix a system-wide installation of Hana with a system-wide installation of Boost, because both installations will clash. You won't know which version of Hana is being used, and that could break libraries that depend on the version of Hana provided with Boost (or vice-versa). Generally speaking, you should favor local installations whenever possible.</li>
</ul>
</dd></dl>
<h2><a class="anchor" id="tutorial-installation-cmake"></a>
Note for CMake users</h2>
<p>If you use <a href="path_to_url">CMake</a>, depending on Hana has never been so easy. When installed, Hana creates a <code>HanaConfig.cmake</code> file that exports the <code>hana</code> interface library target with all the required settings. All you need is to install Hana (through Homebrew or manually), use <code>find_package(Hana)</code>, and then link your own targets against the <code>hana</code> target. Here is a minimal example of doing this:</p>
<div class="fragment"><div class="line">cmake_minimum_required(VERSION 3.0)</div><div class="line">project(external CXX)</div><div class="line"></div><div class="line">find_package(Hana REQUIRED)</div><div class="line">add_executable(external main.cpp)</div><div class="line">target_link_libraries(external hana)</div></div><!-- fragment --><p> If you have installed Hana in a non-standard place, you might need to play with <code>CMAKE_PREFIX_PATH</code>. For example, this can happen if you "manually" install Hana locally to another project. In this case, you'll need to tell CMake where to find the <code>HanaConfig.cmake</code> file by using</p>
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> list(APPEND CMAKE_PREFIX_PATH "${INSTALLATION_PREFIX_FOR_HANA}")</div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span> or</div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span> cmake ... -DCMAKE_PREFIX_PATH=${INSTALLATION_PREFIX_FOR_HANA}</div></div><!-- fragment --><p>where <code>INSTALLATION_PREFIX_FOR_HANA</code> is the path to the place where Hana was installed.</p>
<h2><a class="anchor" id="tutorial-installation-requirements"></a>
Compiler requirements</h2>
<p>The library relies on a C++14 compiler and standard library, but nothing else is required. Here is a table of the current C++14 compilers/toolchains with comments regarding support for Hana:</p>
<table class="doxtable">
<tr>
<th>Compiler/Toolchain </th><th>Status </th></tr>
<tr>
<td>Clang >= 3.5.0 </td><td>Fully working; tested on each push to GitHub </td></tr>
<tr>
<td>Xcode >= 6.3 </td><td>Fully working; tested on each push to GitHub </td></tr>
<tr>
<td>GCC >= 6.0.0 </td><td>Fully working; tested on each push to GitHub </td></tr>
</table>
<p>More specifically, Hana requires a compiler/standard library supporting the following C++14 features (non-exhaustively):</p><ul>
<li>Generic lambdas</li>
<li>Generalized <code>constexpr</code></li>
<li>Variable templates</li>
<li>Automatically deduced return type</li>
<li>All the C++14 type traits from the <code><type_traits></code> header</li>
</ul>
<p>More information for specific platforms is available on <a href="path_to_url">the wiki</a>.</p>
<h1><a class="anchor" id="tutorial-support"></a>
Support</h1>
<hr/>
<p>If you have a problem, please review the <a class="el" href="index.html#tutorial-rationales">FAQ</a> and <a href="path_to_url">the wiki</a>. Searching <a href="path_to_url">the issues</a> for your problem is also a good idea. If that doesn't help, feel free to chat with us in <a href="path_to_url">Gitter</a>, or open a new issue. <a href="path_to_url">StackOverflow</a> with the <a href="path_to_url">boost-hana</a> tag is the preferred place to ask questions on usage. If you are encountering what you think is a bug, please open an issue.</p>
<h1><a class="anchor" id="tutorial-introduction"></a>
Introduction</h1>
<hr/>
<p> When Boost.MPL first appeared, it provided C++ programmers with a huge relief by abstracting tons of template hackery behind a workable interface. This breakthrough greatly contributed to making C++ template metaprogramming more mainstream, and today the discipline is deeply rooted in many serious projects. Recently, C++11 and C++14 brought many major changes to the language, some of which make metaprogramming much easier, while others drastically widen the design space for libraries. A natural question then arises: is it still desirable to have abstractions for metaprogramming, and if so, which ones? After investigating different options like the <a href="path_to_url">MPL11</a>, the answer eventually came by itself in the form of a library; Hana. The key insight to Hana is that the manipulation of types and values are nothing but two sides of the same coin. By unifying both concepts, metaprogramming becomes easier and new exciting possibilities open before us.</p>
<h2><a class="anchor" id="tutorial-introduction-quadrants"></a>
C++ computational quadrants</h2>
<p>But to really understand what is Hana all about, it is essential to understand the different types of computations in C++. We will focus our attention on four different kinds of computations, even though a finer grained separation would be possible. First, we have runtime computations, which are the usual computations we use in C++. In that world, we have runtime containers, runtime functions and runtime algorithms:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> f = [](<span class="keywordtype">int</span> i) -> std::string {</div><div class="line"> <span class="keywordflow">return</span> std::to_string(i * i);</div><div class="line">};</div><div class="line"></div><div class="line">std::vector<int> ints{1, 2, 3, 4};</div><div class="line">std::vector<std::string> strings;</div><div class="line"><a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">std::transform</a>(ints.begin(), ints.end(), std::back_inserter(strings), f);</div><div class="line"></div><div class="line">assert((strings == std::vector<std::string>{<span class="stringliteral">"1"</span>, <span class="stringliteral">"4"</span>, <span class="stringliteral">"9"</span>, <span class="stringliteral">"16"</span>}));</div></div><!-- fragment --><p> The usual toolbox for programming within this quadrant is the C++ standard library, which provides reusable algorithms and containers operating at runtime. Since C++11, a second kind of computation is possible: <code>constexpr</code> computations. There, we have <code>constexpr</code> containers, <code>constexpr</code> functions and <code>constexpr</code> algorithms:</p>
<div class="fragment"><div class="line">constexpr <span class="keywordtype">int</span> factorial(<span class="keywordtype">int</span> n) {</div><div class="line"> <span class="keywordflow">return</span> n == 0 ? 1 : n * factorial(n - 1);</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, std::<span class="keywordtype">size_t</span> N, <span class="keyword">typename</span> F></div><div class="line"> constexpr <a class="code" href="structstd_1_1array.html">std::array<std::result_of_t<F(T)></a>, N></div><div class="line"><a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">transform</a>(<a class="code" href="structstd_1_1array.html">std::array<T, N></a> array, F f) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">}</div><div class="line"></div><div class="line">constexpr <a class="code" href="structstd_1_1array.html">std::array<int, 4></a> ints{{1, 2, 3, 4}};</div><div class="line">constexpr <a class="code" href="structstd_1_1array.html">std::array<int, 4></a> facts = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">transform</a>(ints, factorial);</div><div class="line">static_assert(facts == <a class="code" href="structstd_1_1array.html">std::array<int, 4></a>{{1, 2, 6, 24}}, <span class="stringliteral">""</span>);</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>For the above code to actually work, <code><a class="el" href="structstd_1_1array.html" title="Adaptation of std::array for Hana. ">std::array</a></code>'s <code>operator==</code> would have to be marked <code>constexpr</code>, which is not the case (even in C++14).</dd></dl>
<p>Basically, a <code>constexpr</code> computation is different from a runtime computation in that it is simple enough to be evaluated (interpreted, really) by the compiler. In general, any function that does not perform anything too <em>unfriendly</em> to the compiler's evaluator (like throwing or allocating memory) can be marked <code>constexpr</code> without any further change. This makes <code>constexpr</code> computations very similar to runtime computations, except <code>constexpr</code> computations are more restricted and they gain the ability to be evaluated at compile-time. Unfortunately, there is no commonly used toolbox for <code>constexpr</code>-programming, i.e. there is no widely adopted "standard library" for <code>constexpr</code> programming. However, the <a href="path_to_url">Sprout</a> library may be worth checking out for those with some interest in <code>constexpr</code> computations.</p>
<p>The third kind of computations are heterogeneous computations. Heterogeneous computations differ from normal computations in that instead of having containers holding homogeneous objects (all objects having the same type), the containers may hold objects with different types. Furthermore, functions in this quadrant of computation are <em>heterogeneous</em> functions, which is a complicated way of talking about template functions. Similarly, we have heterogeneous algorithms that manipulate heterogeneous containers and functions:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> to_string = [](<span class="keyword">auto</span> t) {</div><div class="line"> std::stringstream ss;</div><div class="line"> ss << t;</div><div class="line"> <span class="keywordflow">return</span> ss.str();</div><div class="line">};</div><div class="line"></div><div class="line">fusion::vector<int, std::string, float> seq{1, <span class="stringliteral">"abc"</span>, 3.4f};</div><div class="line">fusion::vector<std::string, std::string, std::string></div><div class="line"> strings = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">fusion::transform</a>(seq, to_string);</div><div class="line"></div><div class="line">assert(strings == fusion::make_vector(<span class="stringliteral">"1"</span>s, <span class="stringliteral">"abc"</span>s, <span class="stringliteral">"3.4"</span>s));</div></div><!-- fragment --><p> If manipulating heterogeneous containers seems overly weird to you, just think of it as glorified <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> manipulation. In a C++03 world, the go-to library for doing this kind of computation is <a href="path_to_url">Boost.Fusion</a>, which provides several data structures and algorithms to manipulate heterogeneous collections of data. The fourth and last quadrant of computation that we'll be considering here is the quadrant of type-level computations. In this quadrant, we have type-level containers, type-level functions (usually called metafunctions) and type-level algorithms. Here, everything operates on types: containers hold types and metafunctions take types as arguments and return types as results.</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>add_const_pointer {</div><div class="line"> <span class="keyword">using</span> type = T <span class="keyword">const</span>*;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">using</span> types = mpl::vector<int, char, float, void>;</div><div class="line"><span class="keyword">using</span> pointers = mpl::transform<types, add_const_pointer<mpl::_1>>::type;</div><div class="line"></div><div class="line">static_assert(<a class="code" href="group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547">mpl::equal</a><</div><div class="line"> pointers,</div><div class="line"> mpl::vector<int const*, char const*, float const*, void const*></div><div class="line">>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> The realm of type-level computations has been explored quite extensively, and the de-facto solution for type-level computations in C++03 is a library named <a href="path_to_url">Boost.MPL</a>, which provides type-level containers and algorithms. For low-level type transformations, the metafunctions provided by the <code><type_traits></code> standard header can also be used since C++11.</p>
<h2><a class="anchor" id="tutorial-quadrants-about"></a>
What is this library about?</h2>
<p>So all is good, but what is this library actually about? Now that we have set the table by clarifying the kinds of computations available to us in C++, the answer might strike you as very simple. <b>The purpose of Hana is to merge the 3rd and the 4th quadrants of computation</b>. More specifically, Hana is a (long-winded) constructive proof that heterogeneous computations are strictly more powerful than type-level computations, and that we can therefore express any type-level computation by an equivalent heterogeneous computation. This construction is done in two steps. First, Hana is a fully featured library of heterogeneous algorithms and containers, a bit like a modernized Boost.Fusion. Secondly, Hana provides a way of translating any type-level computation into its equivalent heterogeneous computation and back, which allows the full machinery of heterogeneous computations to be reused for type-level computations without any code duplication. Of course, the biggest advantage of this unification is seen by the user, as you will witness by yourself.</p>
<h1><a class="anchor" id="tutorial-quickstart"></a>
Quick start</h1>
<hr/>
<p> The goal of this section is to introduce the main concepts of the library from a very high level and at a fairly rapid pace; don't worry if you don't understand everything that's about to be thrown at you. However, this tutorial assumes the reader is already at least <em>familiar</em> with basic metaprogramming and the <a href="path_to_url">C++14 standard</a>. First, let's include the library:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="hana_8hpp.html">boost/hana.hpp</a>></span></div><div class="line"><span class="keyword">namespace </span>hana = <a class="code" href="namespaceboost_1_1hana.html">boost::hana</a>;</div></div><!-- fragment --><p> Unless specified otherwise, the documentation assumes the above lines to be present before examples and code snippets. Also note that finer grained headers are provided and will be explained in the <a class="el" href="index.html#tutorial-header_organization">Header organization</a> section. For the purpose of the quickstart, let's now include some additional headers and define some lovely animal types that we'll need below:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <cassert></span></div><div class="line"><span class="preprocessor">#include <iostream></span></div><div class="line"><span class="preprocessor">#include <string></span></div><div class="line"></div><div class="line"><span class="keyword">struct </span>Fish { std::string name; };</div><div class="line"><span class="keyword">struct </span>Cat { std::string name; };</div><div class="line"><span class="keyword">struct </span>Dog { std::string name; };</div></div><!-- fragment --><p> If you are reading this documentation, chances are you already know <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> and <code>std::make_tuple</code>. Hana provides its own tuple and <code>make_tuple</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> animals = hana::make_tuple(Fish{<span class="stringliteral">"Nemo"</span>}, Cat{<span class="stringliteral">"Garfield"</span>}, Dog{<span class="stringliteral">"Snoopy"</span>});</div></div><!-- fragment --><p> This creates a tuple, which is like an array, except that it can hold elements with different types. Containers that can hold elements with different types such as this are called heterogeneous containers. While the standard library provides very few operations to manipulate <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>s, Hana provides several operations and algorithms to manipulate its own tuples:</p>
<div class="fragment"><div class="line"><span class="keyword">using namespace </span>hana::literals;</div><div class="line"></div><div class="line"><span class="comment">// Access tuple elements with operator[] instead of std::get.</span></div><div class="line">Cat garfield = animals[1_c];</div><div class="line"></div><div class="line"><span class="comment">// Perform high level algorithms on tuples (this is like std::transform)</span></div><div class="line"><span class="keyword">auto</span> names = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(animals, [](<span class="keyword">auto</span> a) {</div><div class="line"> <span class="keywordflow">return</span> a.name;</div><div class="line">});</div><div class="line"></div><div class="line">assert(<a class="code" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">hana::reverse</a>(names) == hana::make_tuple(<span class="stringliteral">"Snoopy"</span>, <span class="stringliteral">"Garfield"</span>, <span class="stringliteral">"Nemo"</span>));</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd><code>1_c</code> is a <a href="path_to_url#User-defined_literals">C++14 user-defined literal</a> creating a <a class="el" href="index.html#tutorial-integral">compile-time number</a>. These user-defined literals are contained in the <code><a class="el" href="namespaceboost_1_1hana_1_1literals.html" title="Namespace containing C++14 user-defined literals provided by Hana. ">boost::hana::literals</a></code> namespace, hence the <code>using</code> directive.</dd></dl>
<p>Notice how we pass a <a href="path_to_url#Generic_lambdas">C++14 generic lambda</a> to <code>transform</code>; this is required because the lambda will first be called with a <code>Fish</code>, then a <code>Cat</code>, and finally a <code>Dog</code>, which all have different types. Hana provides most of the algorithms provided by the C++ standard library, except they work on tuples and related heterogeneous containers instead of <code>std::vector</code> & friends. In addition to working with heterogeneous values, Hana makes it possible to perform type-level computations with a natural syntax, all at compile-time and with no overhead whatsoever. This compiles and does just what you would expect:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> animal_types = hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Cat&>, hana::type_c<Dog>);</div><div class="line"></div><div class="line"><span class="keyword">auto</span> no_pointers = <a class="code" href="group__group-MonadPlus.html#ga9700169a45664d50377c1be9d58accd3">hana::remove_if</a>(animal_types, [](<span class="keyword">auto</span> a) {</div><div class="line"> <span class="keywordflow">return</span> hana::traits::is_pointer(a);</div><div class="line">});</div><div class="line"></div><div class="line">static_assert(no_pointers == hana::make_tuple(hana::type_c<Cat&>, hana::type_c<Dog>), <span class="stringliteral">""</span>);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd><code>type_c<...></code> is not a type! It is a <a href="path_to_url#Variable_templates">C++14 variable template</a> yielding an object representing a type for Hana. This is explained in the section on <a class="el" href="index.html#tutorial-type">type computations</a>.</dd></dl>
<p>In addition to heterogeneous and compile-time sequences, Hana provides several features to make your metaprogramming nightmares a thing of the past. For example, one can check for the existence of a struct member with one easy line instead of relying on <a href="path_to_url">clunky SFINAE hacks</a>:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_name = hana::is_valid([](<span class="keyword">auto</span>&& x) -> decltype((<span class="keywordtype">void</span>)x.name) { });</div><div class="line"></div><div class="line">static_assert(has_name(garfield), <span class="stringliteral">""</span>);</div><div class="line">static_assert(!has_name(1), <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> Writing a serialization library? Stop crying, we've got you covered. Reflection can be added to user-defined types very easily. This allows iterating over the members of a user-defined type, querying members with a programmatic interface and much more, without any runtime overhead:</p>
<div class="fragment"><div class="line"><span class="comment">// 1. Give introspection capabilities to 'Person'</span></div><div class="line"><span class="keyword">struct </span>Person {</div><div class="line"> BOOST_HANA_DEFINE_STRUCT(Person,</div><div class="line"> (std::string, name),</div><div class="line"> (<span class="keywordtype">int</span>, age)</div><div class="line"> );</div><div class="line">};</div><div class="line"></div><div class="line"><span class="comment">// 2. Write a generic serializer (bear with std::ostream for the example)</span></div><div class="line"><span class="keyword">auto</span> serialize = [](std::ostream& os, <span class="keyword">auto</span> <span class="keyword">const</span>& object) {</div><div class="line"> <a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(<a class="code" href="group__group-Struct.html#gad301dd8e9fb4639d7874619c97d6d427">hana::members</a>(<span class="keywordtype">object</span>), [&](<span class="keyword">auto</span> member) {</div><div class="line"> os << member << std::endl;</div><div class="line"> });</div><div class="line">};</div><div class="line"></div><div class="line"><span class="comment">// 3. Use it</span></div><div class="line">Person john{<span class="stringliteral">"John"</span>, 30};</div><div class="line">serialize(std::cout, john);</div><div class="line"></div><div class="line"><span class="comment">// output:</span></div><div class="line"><span class="comment">// John</span></div><div class="line"><span class="comment">// 30</span></div></div><!-- fragment --><p> That's cool, but I can already hear you complaining about incomprehensible error messages. However, it turns out Hana was built for humans, not professional template metaprogrammers, and this shows. Let's intentionally screw up and see what kind of mess is thrown at us. First, the mistake:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> serialize = [](std::ostream& os, <span class="keyword">auto</span> <span class="keyword">const</span>& object) {</div><div class="line"> <a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(os, [&](<span class="keyword">auto</span> member) {</div><div class="line"> <span class="comment">// ^^ oopsie daisy!</span></div><div class="line"> os << member << std::endl;</div><div class="line"> });</div><div class="line">};</div></div><!-- fragment --><p> Now, the punishment:</p>
<div class="fragment"><div class="line">error: static_assert failed <span class="stringliteral">"hana::for_each(xs, f) requires 'xs' to be Foldable"</span></div><div class="line"> static_assert(<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">Foldable<S>::value</a>,</div><div class="line"> ^ ~~~~~~~~~~~~~~~~~~</div><div class="line">note: <a class="code" href="group__group-Searchable.html#ga0d9456ceda38b6ca664998e79d7c45b7">in</a> instantiation of <span class="keyword">function</span> <span class="keyword">template</span> specialization</div><div class="line"> <span class="stringliteral">'boost::hana::for_each_t::operator()<</span></div><div class="line"><span class="stringliteral"> std::__1::basic_ostream<char> &, (lambda at [snip])>'</span> requested here</div><div class="line"> <a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(os, [&](<span class="keyword">auto</span> member) {</div><div class="line"> ^</div><div class="line">note: <a class="code" href="group__group-Searchable.html#ga0d9456ceda38b6ca664998e79d7c45b7">in</a> instantiation of <span class="keyword">function</span> <span class="keyword">template</span> specialization</div><div class="line"> <span class="stringliteral">'main()::(anonymous class)::operator()<Person>'</span> requested here</div><div class="line">serialize(std::cout, john);</div><div class="line"> ^</div></div><!-- fragment --><p>Not that bad, right? However, since small examples are very good to show off without actually doing something useful, let's examine a real world example.</p>
<h2><a class="anchor" id="tutorial-quickstart-any"></a>
A real world example</h2>
<p>In this section our goal will be to implement a kind of <code>switch</code> statement able to process <code>boost::any</code>s. Given a <code>boost::any</code>, the goal is to dispatch to the function associated to the dynamic type of the <code>any</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Searchable.html#gab7d632b9319b10b1eb7e98f9e1cf8a28">boost::any</a> a = <span class="charliteral">'x'</span>;</div><div class="line">std::string r = switch_(a)(</div><div class="line"> case_<int>([](<span class="keyword">auto</span> i) { <span class="keywordflow">return</span> <span class="stringliteral">"int: "</span>s + std::to_string(i); }),</div><div class="line"> case_<char>([](<span class="keyword">auto</span> c) { <span class="keywordflow">return</span> <span class="stringliteral">"char: "</span>s + std::string{c}; }),</div><div class="line"> default_([] { <span class="keywordflow">return</span> <span class="stringliteral">"unknown"</span>s; })</div><div class="line">);</div><div class="line"></div><div class="line">assert(r == <span class="stringliteral">"char: x"</span>s);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>In the documentation, we will often use the <code>s</code> suffix on string literals to create <code>std::string</code>s without syntactic overhead. This is a standard-defined <a href="path_to_url#User-defined_literals">C++14 user-defined literal</a>.</dd></dl>
<p>Since the any holds a <code>char</code>, the second function is called with the <code>char</code> inside it. If the <code>any</code> had held an <code>int</code> instead, the first function would have been called with the <code>int</code> inside it. When the dynamic type of the <code>any</code> does not match any of the covered cases, the <code>default_</code> function is called instead. Finally, the result of the <code>switch</code> is the result of calling the function associated to the <code>any</code>'s dynamic type. The type of that result is inferred to be the common type of the result of all the provided functions:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Searchable.html#gab7d632b9319b10b1eb7e98f9e1cf8a28">boost::any</a> a = <span class="charliteral">'x'</span>;</div><div class="line"><span class="keyword">auto</span> r = switch_(a)(</div><div class="line"> case_<int>([](<span class="keyword">auto</span>) -> <span class="keywordtype">int</span> { <span class="keywordflow">return</span> 1; }),</div><div class="line"> case_<char>([](<span class="keyword">auto</span>) -> <span class="keywordtype">long</span> { <span class="keywordflow">return</span> 2l; }),</div><div class="line"> default_([]() -> <span class="keywordtype">long</span> <span class="keywordtype">long</span> { <span class="keywordflow">return</span> 3ll; })</div><div class="line">);</div><div class="line"></div><div class="line"><span class="comment">// r is inferred to be a long long</span></div><div class="line">static_assert(std::is_same<decltype(r), <span class="keywordtype">long</span> <span class="keywordtype">long</span>>{}, <span class="stringliteral">""</span>);</div><div class="line">assert(r == 2ll);</div></div><!-- fragment --><p> We'll now look at how this utility can be implemented using Hana. The first step is to associate each type to a function. To do so, we represent each <code>case_</code> as a <code>hana::pair</code> whose first element is a type and whose second element is a function. Furthermore, we (arbitrarily) decide to represent the <code>default_</code> case as a <code>hana::pair</code> mapping a dummy type to a function:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> case_ = [](<span class="keyword">auto</span> f) {</div><div class="line"> <span class="keywordflow">return</span> hana::make_pair(hana::type_c<T>, f);</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">struct </span>default_t;</div><div class="line"><span class="keyword">auto</span> default_ = case_<default_t>;</div></div><!-- fragment --><p> To provide the interface we showed above, <code>switch_</code> will have to return a function taking the cases. In other words, <code>switch_(a)</code> must be a function taking any number of cases (which are <code>hana::pair</code>s), and performing the logic to dispatch <code>a</code> to the right function. This can easily be achieved by having <code>switch_</code> return a C++14 generic lambda:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p>However, since parameter packs are not very flexible, we'll put the cases into a tuple so we can manipulate them:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"> <span class="comment">// ...</span></div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p>Notice how the <code>auto</code> keyword is used when defining <code>cases</code>; it is often easier to let the compiler deduce the type of the tuple and use <code>make_tuple</code> instead of working out the types manually. The next step is to separate the default case from the rest of the cases. This is where things start to get interesting. To do so, we use Hana's <code>find_if</code> algorithm, which works a bit like <code>std::find_if</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> default_ = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) == hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="comment">// ...</span></div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p><code>find_if</code> takes a <code>tuple</code> and a predicate, and returns the first element of the tuple which satisfies the predicate. The result is returned as a <code>hana::optional</code>, which is very similar to a <code>std::optional</code>, except whether that optional value is empty or not is known at compile-time. If the predicate is not satisfied for any element of the <code>tuple</code>, <code>find_if</code> returns <code>nothing</code> (an empty value). Otherwise, it returns <code>just(x)</code> (a non-empty value), where <code>x</code> is the first element satisfying the predicate. Unlike predicates used in STL algorithms, the predicate used here must be generic because the tuple's elements are heterogeneous. Furthermore, that predicate must return what Hana calls an <code>IntegralConstant</code>, which means that the predicate's result must be known at compile-time. These details are explained in the section on <a class="el" href="index.html#tutorial-algorithms-cross_phase">cross-phase algorithms</a>. Inside the predicate, we simply compare the type of the case's first element to <code>type_c<default_t></code>. If you recall that we were using <code>hana::pair</code>s to encode cases, this simply means that we're finding the default case among all of the provided cases. But what if no default case was provided? We should fail at compile-time, of course!</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> default_ = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) == hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"> static_assert(default_ != hana::nothing,</div><div class="line"> <span class="stringliteral">"switch is missing a default_ case"</span>);</div><div class="line"></div><div class="line"> <span class="comment">// ...</span></div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p>Notice how we can use <code>static_assert</code> on the result of the comparison with <code>nothing</code>, even though <code>default_</code> is a non-<code>constexpr</code> object? Boldly, Hana makes sure that no information that's known at compile-time is lost to the runtime, which is clearly the case of the presence of a <code>default_</code> case. The next step is to gather the set of non-default cases. To achieve this, we use the <code>filter</code> algorithm, which keeps only the elements of the sequence satisfying the predicate:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> default_ = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) == hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"> static_assert(default_ != hana::nothing,</div><div class="line"> <span class="stringliteral">"switch is missing a default_ case"</span>);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> rest = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) != hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="comment">// ...</span></div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p>The next step is to find the first case matching the dynamic type of the <code>any</code>, and then call the function associated to that case. The simplest way to do this is to use classic recursion with variadic parameter packs. Of course, we could probably intertwine Hana algorithms in a convoluted way to achieve this, but sometimes the best way to do something is to write it from scratch using basic techniques. To do so, we'll call an implementation function with the contents of the <code>rest</code> tuple by using the <code>unpack</code> function:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> default_ = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) == hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"> static_assert(default_ != hana::nothing,</div><div class="line"> <span class="stringliteral">"switch is missing a default_ case"</span>);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> rest = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) != hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Foldable.html#ga7b0c23944364ce61136e10b978ae2170">hana::unpack</a>(rest, [&](<span class="keyword">auto</span>& ...rest) {</div><div class="line"> <span class="keywordflow">return</span> process(a, a.type(), <a class="code" href="group__group-Product.html#ga7bb979d59ffc3ab862cb7d9dc7730077">hana::second</a>(*default_), rest...);</div><div class="line"> });</div><div class="line"> };</div><div class="line">}</div></div><!-- fragment --><p> <code>unpack</code> takes a <code>tuple</code> and a function, and calls the function with the content of the <code>tuple</code> as arguments. The result of <code>unpack</code> is the result of calling that function. In our case, the function is a generic lambda which in turn calls the <code>process</code> function. Our reason for using <code>unpack</code> here was to turn the <code>rest</code> tuple into a parameter pack of arguments, which are easier to process recursively than tuples. Before we move on to the <code>process</code> function, it is worthwhile to explain what <code>second(*default_)</code> is all about. As we explained earlier, <code>default_</code> is an optional value. Like <code>std::optional</code>, this optional value overloads the dereference operator (and the arrow operator) to allow accessing the value inside the <code>optional</code>. If the optional is empty (<code>nothing</code>), a compile-time error is triggered. Since we know <code>default_</code> is not empty (we checked that just above), what we're doing is simply pass the function associated to the default case to the <code>process</code> function. We're now ready for the final step, which is the implementation of the <code>process</code> function:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any, <span class="keyword">typename</span> Default></div><div class="line"><span class="keyword">auto</span> process(Any&, std::type_index <span class="keyword">const</span>&, Default& default_) {</div><div class="line"> <span class="keywordflow">return</span> default_();</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any, <span class="keyword">typename</span> Default, <span class="keyword">typename</span> Case, <span class="keyword">typename</span> ...Rest></div><div class="line"><span class="keyword">auto</span> process(Any& a, std::type_index <span class="keyword">const</span>& t, Default& default_,</div><div class="line"> Case& case_, Rest& ...rest)</div><div class="line">{</div><div class="line"> <span class="keyword">using</span> T = <span class="keyword">typename</span> decltype(+<a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(case_))::type;</div><div class="line"> <span class="keywordflow">return</span> t == <span class="keyword">typeid</span>(T) ? <a class="code" href="group__group-Product.html#ga7bb979d59ffc3ab862cb7d9dc7730077">hana::second</a>(case_)(*boost::unsafe_any_cast<T>(&a))</div><div class="line"> : process(a, t, default_, rest...);</div><div class="line">}</div></div><!-- fragment --><p> There are two overloads of this function: an overload for when there is at least one case to process, and the base case overload for when there's only the default case. As we would expect, the base case simply calls the default function and returns that result. The other overload is slightly more interesting. First, we retrieve the type associated to that case and store it in <code>T</code>. This <code>decltype(...)::type</code> dance might seem convoluted, but it is actually quite simple. Roughly speaking, this takes a type represented as an object (a <code>type<T></code>) and pulls it back down to the type level (a <code>T</code>). The details are explained in the section on <a class="el" href="index.html#tutorial-type">type-level computations</a>. Then, we compare whether the dynamic type of the <code>any</code> matches this case, and if so we call the function associated to this case with the <code>any</code> casted to the proper type. Otherwise, we simply call <code>process</code> recursively with the rest of the cases. Pretty simple, wasn't it? Here's the final solution:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="hana_8hpp.html">boost/hana.hpp</a>></span></div><div class="line"></div><div class="line"><span class="preprocessor">#include <boost/any.hpp></span></div><div class="line"><span class="preprocessor">#include <cassert></span></div><div class="line"><span class="preprocessor">#include <string></span></div><div class="line"><span class="preprocessor">#include <typeindex></span></div><div class="line"><span class="preprocessor">#include <typeinfo></span></div><div class="line"><span class="preprocessor">#include <utility></span></div><div class="line"><span class="keyword">namespace </span>hana = <a class="code" href="namespaceboost_1_1hana.html">boost::hana</a>;</div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">//! [cases]</span></div><div class="line"><span class="comment"></span><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> case_ = [](<span class="keyword">auto</span> f) {</div><div class="line"> <span class="keywordflow">return</span> hana::make_pair(hana::type_c<T>, f);</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">struct </span>default_t;</div><div class="line"><span class="keyword">auto</span> default_ = case_<default_t>;<span class="comment"></span></div><div class="line"><span class="comment">//! [cases]</span></div><div class="line"><span class="comment"></span><span class="comment"></span></div><div class="line"><span class="comment">//! [process]</span></div><div class="line"><span class="comment"></span><span class="keyword">template</span> <<span class="keyword">typename</span> Any, <span class="keyword">typename</span> Default></div><div class="line"><span class="keyword">auto</span> process(Any&, std::type_index <span class="keyword">const</span>&, Default& default_) {</div><div class="line"> <span class="keywordflow">return</span> default_();</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Any, <span class="keyword">typename</span> Default, <span class="keyword">typename</span> Case, <span class="keyword">typename</span> ...Rest></div><div class="line"><span class="keyword">auto</span> process(Any& a, std::type_index <span class="keyword">const</span>& t, Default& default_,</div><div class="line"> Case& case_, Rest& ...rest)</div><div class="line">{</div><div class="line"> <span class="keyword">using</span> T = <span class="keyword">typename</span> decltype(+<a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(case_))::type;</div><div class="line"> <span class="keywordflow">return</span> t == <span class="keyword">typeid</span>(T) ? <a class="code" href="group__group-Product.html#ga7bb979d59ffc3ab862cb7d9dc7730077">hana::second</a>(case_)(*boost::unsafe_any_cast<T>(&a))</div><div class="line"> : process(a, t, default_, rest...);</div><div class="line">}<span class="comment"></span></div><div class="line"><span class="comment">//! [process]</span></div><div class="line"><span class="comment"></span><span class="comment"></span></div><div class="line"><span class="comment">//! [switch_]</span></div><div class="line"><span class="comment"></span><span class="keyword">template</span> <<span class="keyword">typename</span> Any></div><div class="line"><span class="keyword">auto</span> switch_(Any& a) {</div><div class="line"> <span class="keywordflow">return</span> [&a](<span class="keyword">auto</span> ...cases_) {</div><div class="line"> <span class="keyword">auto</span> cases = hana::make_tuple(cases_...);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> default_ = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) == hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"> static_assert(default_ != hana::nothing,</div><div class="line"> <span class="stringliteral">"switch is missing a default_ case"</span>);</div><div class="line"></div><div class="line"> <span class="keyword">auto</span> rest = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(cases, [](<span class="keyword">auto</span> <span class="keyword">const</span>& c) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(c) != hana::type_c<default_t>;</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Foldable.html#ga7b0c23944364ce61136e10b978ae2170">hana::unpack</a>(rest, [&](<span class="keyword">auto</span>& ...rest) {</div><div class="line"> <span class="keywordflow">return</span> process(a, a.type(), <a class="code" href="group__group-Product.html#ga7bb979d59ffc3ab862cb7d9dc7730077">hana::second</a>(*default_), rest...);</div><div class="line"> });</div><div class="line"> };</div><div class="line">}<span class="comment"></span></div><div class="line"><span class="comment">//! [switch_]</span></div></div><!-- fragment --><p> That's it for the quick start! This example only introduced a couple of useful algorithms (<code>find_if</code>, <code>filter</code>, <code>unpack</code>) and heterogeneous containers (<code>tuple</code>, <code>optional</code>), but rest assured that there is much more. The next sections of the tutorial gradually introduce general concepts pertaining to Hana in a friendly way, but you may use the following cheatsheet for quick reference if you want to start coding right away. This cheatsheet contains the most frequently used algorithms and containers, along with a short description of what each of them does.</p>
<h1><a class="anchor" id="tutorial-cheatsheet"></a>
Cheatsheet</h1>
<h3>Remarks</h3>
<ul>
<li>Most algorithms work on both types and values (see the section on <a class="el" href="index.html#tutorial-type">type computations</a>)</li>
<li>Algorithms always return their result as a new container; no in-place mutation is ever performed (see the section on <a class="el" href="index.html#tutorial-algorithms">algorithms</a>)</li>
<li>All algorithms are <code>constexpr</code> function objects</li>
</ul>
<table class="doxtable">
<tr>
<th align="left">container </th><th align="left">description </th></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1tuple.html">tuple</a></code> </td><td align="left">General purpose index-based heterogeneous sequence with a fixed length. Use this as a <code>std::vector</code> for heterogeneous objects. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1optional.html">optional</a></code> </td><td align="left">Represents an optional value, i.e. a value that can be empty. This is a bit like <code>std::optional</code>, except that the emptiness is known at compile-time. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1map.html">map</a></code> </td><td align="left">Unordered associative array mapping (unique) compile-time entities to arbitrary objects. This is like <code>std::unordered_map</code> for heterogeneous objects. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1set.html">set</a></code> </td><td align="left">Unordered container holding unique keys that must be compile-time entities. This is like <code>std::unordered_set</code> for heterogeneous objects. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1range.html">range</a></code> </td><td align="left">Represents an interval of compile-time numbers. This is like <code><a class="el" href="structstd_1_1integer__sequence.html" title="Adaptation of std::integer_sequence for Hana. ">std::integer_sequence</a></code>, but better. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1pair.html">pair</a></code> </td><td align="left">Container holding two heterogeneous objects. Like <code><a class="el" href="structstd_1_1pair.html" title="Adaptation of std::pair for Hana. ">std::pair</a></code>, but compresses the storage of empty types. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1string.html">string</a></code> </td><td align="left">Compile-time string. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1type.html">type</a></code> </td><td align="left">Container representing a C++ type. This is the root of the unification between types and values, and is of interest for MPL-style computations (type-level computations). </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1integral__constant.html">integral_constant</a></code> </td><td align="left">Represents a compile-time number. This is very similar to <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code>, except that <code>hana::integral_constant</code> also defines operators and more syntactic sugar. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1lazy.html">lazy</a></code> </td><td align="left">Encapsulates a lazy value or computation. </td></tr>
<tr>
<td align="left"><code><a class="el" href="structboost_1_1hana_1_1basic__tuple.html">basic_tuple</a></code> </td><td align="left">Stripped-down version of <code>hana::tuple</code>. Not standards conforming, but more compile-time efficient. </td></tr>
</table>
<table class="doxtable">
<tr>
<th align="left">function </th><th align="left">description </th></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#ga7cc731e67ebc1f5303be1a97b2d5e0cd">adjust</a>(sequence, value, f)</code> </td><td align="left">Apply a function to each element of a sequence that compares equal to some value and return the result. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#gaa0490f57047c1b0d75fbe233688358f4">adjust_if</a>(sequence, predicate, f)</code> </td><td align="left">Apply a function to each element of a sequence satisfying some predicate and return the result. </td></tr>
<tr>
<td align="left"><code>{<a class="el" href="group__group-Searchable.html#ga81ae9764dd7818ad36270c6419fb1082">all</a>,<a class="el" href="group__group-Searchable.html#gab7d632b9319b10b1eb7e98f9e1cf8a28">any</a>,<a class="el" href="group__group-Searchable.html#ga614ff1e575806f59246b17006e19d479">none</a>}(sequence)</code> </td><td align="left">Returns whether all/any/none of the elements of a sequence are true-valued. </td></tr>
<tr>
<td align="left"><code>{<a class="el" href="group__group-Searchable.html#ga3a168950082f38afd9edf256f336c8ba">all</a>,<a class="el" href="group__group-Searchable.html#ga5f7ff0125c448983e1b96c3ffb84f646">any</a>,<a class="el" href="group__group-Searchable.html#ga43954c791b5b1351fb009e2a643d00f5">none</a>}_of(sequence, predicate)</code> </td><td align="left">Returns whether all/any/none of the elements of the sequence satisfy some predicate. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#ga08624924fe05f0cfbfbd6e439db01873">append</a>(sequence, value)</code> </td><td align="left">Append an element to a sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga8a484304380eae38f3d9663d98860129">at</a>(sequence, index)</code> </td><td align="left">Returns the n-th element of a sequence. The index must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#gab3f4d0035345a453284e46303862d463">back</a>(sequence)</code> </td><td align="left">Returns the last element of a non-empty sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#ga1946e96c3b4c178c7ae8703724c29c37">concat</a>(sequence1, sequence2)</code> </td><td align="left">Concatenate two sequences. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Searchable.html#ga38e7748956cbc9f3d9bb035ac8577906">contains</a>(sequence, value)</code> </td><td align="left">Returns whether a sequence contains the given object. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga3159cfa41be18a396926741b0a3fdefd">count</a>(sequence, value)</code> </td><td align="left">Returns the number of elements that compare equal to the given value. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga39d71be65d5b98e7d035a3e5c607e1b4">count_if</a>(sequence, predicate)</code> </td><td align="left">Returns the number of elements that satisfy the predicate. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#gad23ce0a4906e2bb0a52f38837b134757">drop_front</a>(sequence[, n])</code> </td><td align="left">Drop the first <code>n</code> elements from a sequence, or the whole sequence if <code>length(sequence) <= n</code>. <code>n</code> must be an <code>IntegralConstant</code>. When not provided, <code>n</code> defaults to 1. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga4dbc6a82f03ca35b7ac418ca30889cc4">drop_front_exactly</a>(sequence[, n])</code> </td><td align="left">Drop the first <code>n</code> elements from a sequence. <code>n</code> must be an <code>IntegralConstant</code> and the sequence must have at least <code>n</code> elements. When not provided, <code>n</code> defaults to 1. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gac10231310abc86b056585ea0d0e96ef7">drop_back</a>(sequence[, n])</code> </td><td align="left">Drop the last <code>n</code> elements from a sequence, or the whole sequence if <code>length(sequence) <= n</code>. <code>n</code> must be an <code>IntegralConstant</code>. When not provided, <code>n</code> defaults to 1. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga9f1d02c74a6bdc1db260e0d6a8f1ee56">drop_while</a>(sequence, predicate)</code> </td><td align="left">Drops elements from a sequence while a predicate is satisfied. The predicate must return an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#ga2ce68d315f981ef35751c4dc25ad5642">fill</a>(sequence, value)</code> </td><td align="left">Replace all the elements of a sequence with some value. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">filter</a>(sequence, predicate)</code> </td><td align="left">Remove all the elements that do not satisfy a predicate. The predicate must return an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Searchable.html#ga6b6cdd69942b0fe3bf5254247f9c861e">find</a>(sequence, value)</code> </td><td align="left">Find the first element of a sequence which compares equal to some value and return <code>just</code> it, or return <code>nothing</code>. See <code>hana::optional</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">find_if</a>(sequence, predicate)</code> </td><td align="left">Find the first element of a sequence satisfying the predicate and return <code>just</code> it, or return <code>nothing</code>. See <code>hana::optional</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Monad.html#gaa5fec6fb418de5da3ecb500fd6cc54dd">flatten</a>(sequence)</code> </td><td align="left">Flatten a sequence of sequences, a bit like <code>std::tuple_cat</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga38c6b3f6b1cbadb9b8432a05ff16b7d2">fold_left</a>(sequence[, state], f)</code> </td><td align="left">Accumulates the elements of a sequence from the left, optionally with a provided initial state. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga77d43badebd59b046cf93598733649b4">fold_right</a>(sequence[, state], f)</code> </td><td align="left">Accumulates the elements of a sequence from the right, optionally with a provided initial state. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#gaa0fde17f3b947a0678a1c0c01232f2cc">fold</a>(sequence[, state], f)</code> </td><td align="left">Equivalent to <code>fold_left</code>; provided for consistency with Boost.MPL and Boost.Fusion. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">for_each</a>(sequence, f)</code> </td><td align="left">Call a function on each element of a sequence. Returns <code>void</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga8a67ea10e8082dbe6705e573fa978444">front</a>(sequence)</code> </td><td align="left">Returns the first element of a non-empty sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gacefca884b3580664b63238cf8ba33fd3">group</a>(sequence[, predicate])</code> </td><td align="left">Group adjacent elements of a sequence which all satisfy (or all do not satisfy) some predicate. The predicate defaults to equality, in which case the elements must be <code>Comparable</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga5332fd1dd82edf08379958ba21d57a87">index_if</a>(sequence, predicate)</code> </td><td align="left">Find the index of the first element in a sequence satisfying the predicate and return <code>just</code> it, or return <code>nothing</code>. See <code>hana::optional</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gae22a1a184b1b2dd550fa4fa619bed2e9">insert</a>(sequence, index, element)</code> </td><td align="left">Insert an element at a given index. The index must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga3410ba833cf1ff1d929fcfda4df2eae1">insert_range</a>(sequence, index, elements)</code> </td><td align="left">Insert a sequence of elements at a given index. The index must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga2a05f564f8a7e4afa04fcbc07ad8f394">is_empty</a>(sequence)</code> </td><td align="left">Returns whether a sequence is empty as an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#gaf0f8f717245620dc28cd7d7fa44d7475">length</a>(sequence)</code> </td><td align="left">Returns the length of a sequence as an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Iterable.html#ga660b2649d63ac71dacc64c3852c981e5">lexicographical_compare</a>(sequence1, sequence2[, predicate])</code> </td><td align="left">Performs a lexicographical comparison of two sequences, optionally with a custom predicate, by default with <code>hana::less</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#gaf3861a91607203b63a12708e18a4eac5">maximum</a>(sequence[, predicate])</code> </td><td align="left">Returns the greatest element of a sequence, optionally according to a predicate. The elements must be <code>Orderable</code> if no predicate is provided. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga347429451fdb15f9f7a7fc0de293be1a">minimum</a>(sequence[, predicate])</code> </td><td align="left">Returns the smallest element of a sequence, optionally according to a predicate. The elements must be <code>Orderable</code> if no predicate is provided. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga5e84ac3f1eb09c637b6b38ef42dccd8d">partition</a>(sequence, predicate)</code> </td><td align="left">Partition a sequence into a pair of elements that satisfy some predicate, and elements that do not satisfy it. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#ga69afbfd4e91125e3e52fcb409135ca7c">prepend</a>(sequence, value)</code> </td><td align="left">Prepend an element to a sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#gae3cc0d6e0d8feb3d677bd1da64da6f43">remove</a>(sequence, value)</code> </td><td align="left">Remove all the elements that are equal to a given value. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga80724ec8ecf319a1e695988a69e22f87">remove_at</a>(sequence, index)</code> </td><td align="left">Remove the element at the given index. The index must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-MonadPlus.html#ga9700169a45664d50377c1be9d58accd3">remove_if</a>(sequence, predicate)</code> </td><td align="left">Remove all the elements that satisfy a predicate. The predicate must return an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga6f6d5c1f335780c91d29626fde615c78">remove_range</a>(sequence, from, to)</code> </td><td align="left">Remove the elements at indices in the given <code>[from, to)</code> half-open interval. The indices must be <code>IntegralConstant</code>s. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#ga94cd3a75d59d70d77cfce144c4acf8ab">replace</a>(sequence, oldval, newval)</code> </td><td align="left">Replace the elements of a sequence that compare equal to some value by some other value. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#ga1d21b4bccd16367d164fbe0d9ef52150">replace_if</a>(sequence, predicate, newval)</code> </td><td align="left">Replace the elements of a sequence that satisfy some predicate by some value. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">reverse</a>(sequence)</code> </td><td align="left">Reverse the order of the elements in a sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga947602718a53bd7fcd5c20477694cdcd">reverse_fold</a>(sequence[, state], f)</code> </td><td align="left">Equivalent to <code>fold_right</code>; provided for consistency with Boost.MPL and Boost.Fusion. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga8ec3ac9a6f5014db943f61ebc9e1e36e">size</a>(sequence)</code> </td><td align="left">Equivalent to <code>length</code>; provided for consistency with the C++ standard library. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga245d8abaf6ba67e64020be51c8366081">slice</a>(sequence, indices)</code> </td><td align="left">Returns a new sequence containing the elements at the given indices of the original sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gae1f6a2a9cb70564d43c6b3c663b25dd7">slice_c</a><from, to>(sequence)</code> </td><td align="left">Returns a new sequence containing the elements at indices contained in <code>[from, to)</code> of the original sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gac000a79eb7b9d44ecc8982c93daa40e5">sort</a>(sequence[, predicate])</code> </td><td align="left">Sort (stably) the elements of a sequence, optionally according to a predicate. The elements must be <code>Orderable</code> if no predicate is provided. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga8d302de01b94b4b17f3bd81e09f42920">take_back</a>(sequence, number)</code> </td><td align="left">Take the last n elements of a sequence, or the whole sequence if <code>length(sequence) <= n</code>. n must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga5112e6070d29b4f7fde3f44825da3316">take_front</a>(sequence, number)</code> </td><td align="left">Take the first n elements of a sequence, or the whole sequence if <code>length(sequence) <= n</code>. n must be an <code>IntegralConstant</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga2d4db4ec5ec5bc16fe74f57de12697fd">take_while</a>(sequence, predicate)</code> </td><td align="left">Take elements of a sequence while some predicate is satisfied, and return that. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">transform</a>(sequence, f)</code> </td><td align="left">Apply a function to each element of a sequence and return the result. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga35349be79e646c4f5bdd74ec96a846ab">unique</a>(sequence[, predicate])</code> </td><td align="left">Removes all consecutive duplicates from a sequence. The predicate defaults to equality, in which case the elements must be <code>Comparable</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Foldable.html#ga7b0c23944364ce61136e10b978ae2170">unpack</a>(sequence, f)</code> </td><td align="left">Calls a function with the contents of a sequence. Equivalent to <code>f(x1, ..., xN)</code>. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gaa5a378d4e71a91e0d6cd3959d9818e8a">zip</a>(s1, ..., sN)</code> </td><td align="left">Zip <code>N</code> sequences into a sequence of tuples. All the sequences must have the same length. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gade78593b3ff51fc5479e1da97142fef5">zip_shortest</a>(s1, ..., sN)</code> </td><td align="left">Zip <code>N</code> sequences into a sequence of tuples. The resulting sequence has the length of the shortest input sequence. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#ga6a4bf8549ce69b5b5b7377aec225a0e3">zip_with</a>(f, s1, ..., sN)</code> </td><td align="left">Zip <code>N</code> sequences with a <code>N</code>-ary function. All the sequences must have the same length. </td></tr>
<tr>
<td align="left"><code><a class="el" href="group__group-Sequence.html#gae7a51104a77db79a0407d7d67b034667">zip_shortest_with</a>(f, s1, ..., sN)</code> </td><td align="left">Zip <code>N</code> sequences with a <code>N</code>-ary function. The resulting sequence has the length of the shortest input sequence. </td></tr>
</table>
<h1><a class="anchor" id="tutorial-assert"></a>
Assertions</h1>
<hr/>
<p> In the rest of this tutorial, you will come across code snippets where different kinds of assertions like <code>BOOST_HANA_RUNTIME_CHECK</code> and <code>BOOST_HANA_CONSTANT_CHECK</code> are used. Like any sensible <code>assert</code> macro, they basically check that the condition they are given is satisfied. However, in the context of heterogeneous programming, some informations are known at compile-time, while others are known only at runtime. The exact type of assertion that's used in a context tells you whether the condition that's asserted upon can be known at compile-time or if it must be computed at runtime, which is a very precious piece of information. Here are the different kinds of assertions used in the tutorial, with a small description of their particularities. For more details, you should check the <a class="el" href="group__group-assertions.html">reference on assertions</a>.</p>
<table class="doxtable">
<tr>
<th align="left">assertion </th><th align="left">description </th></tr>
<tr>
<td align="left"><code>BOOST_HANA_RUNTIME_CHECK</code> </td><td align="left">Assertion on a condition that is not known until runtime. This assertion provides the weakest form of guarantee. </td></tr>
<tr>
<td align="left"><code>BOOST_HANA_CONSTEXPR_CHECK</code> </td><td align="left">Assertion on a condition that would be <code>constexpr</code> if lambdas were allowed inside constant expressions. In other words, the only reason for it not being a <code>static_assert</code> is the language limitation that lambdas can't appear in constant expressions, which <a href="path_to_url">might be lifted</a> in C++17. </td></tr>
<tr>
<td align="left"><code>static_assert</code> </td><td align="left">Assertion on a <code>constexpr</code> condition. This is stronger than <code>BOOST_HANA_CONSTEXPR_CHECK</code> in that it requires the condition to be a constant expression, and it hence assures that the algorithms used in the expression are <code>constexpr</code>-friendly. </td></tr>
<tr>
<td align="left"><code>BOOST_HANA_CONSTANT_CHECK</code> </td><td align="left">Assertion on a boolean <code>IntegralConstant</code>. This assertion provides the strongest form of guarantee, because an <code>IntegralConstant</code> can be converted to a <code>constexpr</code> value even if it is not <code>constexpr</code> itself. </td></tr>
</table>
<h1><a class="anchor" id="tutorial-integral"></a>
Compile-time numbers</h1>
<hr/>
<p> This section introduces the important notion of <code>IntegralConstant</code> and the philosophy behind Hana's metaprogramming paradigm. Let's start with a rather odd question. What is an <code>integral_constant</code>?</p>
<div class="fragment"><div class="line"><span class="keyword">template</span><<span class="keyword">class</span> T, T v></div><div class="line"><span class="keyword">struct </span>integral_constant {</div><div class="line"> <span class="keyword">static</span> constexpr T <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a> = v;</div><div class="line"> <span class="keyword">typedef</span> T value_type;</div><div class="line"> <span class="keyword">typedef</span> integral_constant type;</div><div class="line"> constexpr <span class="keyword">operator</span> value_type() const noexcept { <span class="keywordflow">return</span> <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>; }</div><div class="line"> constexpr value_type operator()() const noexcept { <span class="keywordflow">return</span> <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>; }</div><div class="line">};</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>If this is totally new to you, you might want to take a look at the <a href="path_to_url">documentation</a> for <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code>.</dd></dl>
<p>One valid answer is that <code>integral_constant</code> represents a type-level encoding of a number, or more generally any object of an integral type. For illustration, we could define a successor function on numbers in that representation very easily by using a template alias:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> N></div><div class="line"><span class="keyword">using</span> succ = integral_constant<int, N::value + 1>;</div><div class="line"></div><div class="line"><span class="keyword">using</span> <a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a> = integral_constant<int, 1>;</div><div class="line"><span class="keyword">using</span> two = succ<one>;</div><div class="line"><span class="keyword">using</span> three = succ<two>;</div><div class="line"><span class="comment">// ...</span></div></div><!-- fragment --><p>This is the way <code>integral_constant</code>s are usually thought of; as <em>type-level</em> entities that can be used for template metaprogramming. Another way to see an <code>integral_constant</code> is as a runtime object representing a <code>constexpr</code> value of an integral type:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> <a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a> = integral_constant<int, 1>{};</div></div><!-- fragment --><p>Here, while <code>one</code> is not marked as <code>constexpr</code>, the abstract value it holds (a <code>constexpr 1</code>) is still available at compile-time, because that value is encoded in the type of <code>one</code>. Indeed, even if <code>one</code> is not <code>constexpr</code>, we can use <code>decltype</code> to retrieve the compile-time value it represents:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> <a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a> = integral_constant<int, 1>{};</div><div class="line">constexpr <span class="keywordtype">int</span> one_constexpr = decltype(<a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a>)::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>;</div></div><!-- fragment --><p>But why on earth would we want to consider <code>integral_constant</code>s as objects instead of type-level entities? To see why, consider how we could now implement the same successor function as before:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> N></div><div class="line"><span class="keyword">auto</span> succ(N) {</div><div class="line"> <span class="keywordflow">return</span> integral_constant<int, N::value + 1>{};</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">auto</span> <a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a> = integral_constant<int, 1>{};</div><div class="line"><span class="keyword">auto</span> two = succ(<a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a>);</div><div class="line"><span class="keyword">auto</span> three = succ(two);</div><div class="line"><span class="comment">// ...</span></div></div><!-- fragment --><p>Did you notice anything new? The difference is that instead of implementing <code>succ</code> at the type-level with a template alias, we're now implementing it at the value-level with a template function. Furthermore, we can now perform compile-time arithmetic using the same syntax as that of normal C++. This way of seeing compile-time entities as objects instead of types is the key to Hana's expressive power.</p>
<h2><a class="anchor" id="tutorial-integral-arithmetic"></a>
Compile-time arithmetic</h2>
<p>The MPL defines <a href="path_to_url">arithmetic operators</a> that can be used to do compile-time computations with <code>integral_constant</code>s. A typical example of such an operation is <code>plus</code>, which is implemented roughly as:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> X, <span class="keyword">typename</span> Y></div><div class="line"><span class="keyword">struct </span><a class="code" href="group__group-Monoid.html#gaeb5d4a1e967e319712f9e4791948896c">plus</a> {</div><div class="line"> <span class="keyword">using</span> type = integral_constant<</div><div class="line"> decltype(<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">X::value</a> + <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">Y::value</a>),</div><div class="line"> <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">X::value</a> + <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">Y::value</a></div><div class="line"> >;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">using</span> three = plus<integral_constant<int, 1>,</div><div class="line"> integral_constant<int, 2>>::type;</div></div><!-- fragment --><p>By viewing <code>integral_constant</code>s as objects instead of types, the translation from a metafunction to a function is very straightforward:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> V, V v, <span class="keyword">typename</span> U, U u></div><div class="line">constexpr <span class="keyword">auto</span></div><div class="line">operator+(integral_constant<V, v>, integral_constant<U, u>)</div><div class="line">{ <span class="keywordflow">return</span> integral_constant<decltype(v + u), v + u>{}; }</div><div class="line"></div><div class="line"><span class="keyword">auto</span> three = integral_constant<int, 1>{} + integral_constant<int, 2>{};</div></div><!-- fragment --><p>It is very important to emphasize the fact that this operator does not return a normal integer. Instead, it returns a value-initialized object whose type contains the result of the addition. The only useful information contained in that object is actually in its type, and we're creating an object because it allows us to use this nice value-level syntax. It turns out that we can make this syntax even better by using a <a href="path_to_url#Variable_templates">C++14 variable template</a> to simplify the creation of an <code>integral_constant</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keywordtype">int</span> i></div><div class="line">constexpr integral_constant<int, i> <a class="code" href="structboost_1_1hana_1_1integral__constant.html#a8669179fa3d068951014b3be07a7d673">int_c</a>{};</div><div class="line"></div><div class="line"><span class="keyword">auto</span> three = int_c<1> + int_c<2>;</div></div><!-- fragment --><p>Now we're talking about a visible gain in expressiveness over the initial type-level approach, aren't we? But there's more; we can also use <a href="path_to_url#User-defined_literals">C++14 user defined literals</a> to make this process even simpler:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keywordtype">char</span> ...digits></div><div class="line">constexpr <span class="keyword">auto</span> <span class="keyword">operator</span><span class="stringliteral">""</span> _c() {</div><div class="line"> <span class="comment">// parse the digits and return an integral_constant</span></div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">auto</span> three = 1_c + 3_c;</div></div><!-- fragment --><p>Hana provides its own <code>integral_constant</code>s, which define arithmetic operators just like we showed above. Hana also provides variable templates to easily create different kinds of <code>integral_constant</code>s: <code>int_c</code>, <code>long_c</code>, <code>bool_c</code>, etc... This allows you to omit the trailing <code>{}</code> braces otherwise required to value-initialize these objects. Of course, the <code>_c</code> suffix is also provided; it is part of the <code>hana::literals</code> namespace, and you must import it into your namespace before using it:</p>
<div class="fragment"><div class="line"><span class="keyword">using namespace </span>hana::literals;</div><div class="line"></div><div class="line"><span class="keyword">auto</span> three = 1_c + 3_c;</div></div><!-- fragment --><p>This way, you may do compile-time arithmetic without having to struggle with awkward type-level idiosyncrasies, and your coworkers will now be able to understand what's going on.</p>
<h2><a class="anchor" id="tutorial-integral-distance"></a>
Example: Euclidean distance</h2>
<p>To illustrate how good it gets, let's implement a function computing a 2-D euclidean distance at compile-time. As a reminder, the euclidean distance of two points in the 2-D plane is given by</p>
<p class="formulaDsp">
\[ \mathrm{distance}\left((x_1, y_1), (x_2, y_2)\right) := \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2} \]
</p>
<p>First, here's how it looks like with a type-level approach (using the MPL):</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> P1, <span class="keyword">typename</span> P2></div><div class="line"><span class="keyword">struct </span>distance {</div><div class="line"> <span class="keyword">using</span> xs = <span class="keyword">typename</span> <a class="code" href="group__group-Group.html#ga2020c526324f361a2b990fe8d1b07c20">mpl::minus</a><<span class="keyword">typename</span> P1::x,</div><div class="line"> <span class="keyword">typename</span> P2::x>::type;</div><div class="line"> <span class="keyword">using</span> ys = <span class="keyword">typename</span> <a class="code" href="group__group-Group.html#ga2020c526324f361a2b990fe8d1b07c20">mpl::minus</a><<span class="keyword">typename</span> P1::y,</div><div class="line"> <span class="keyword">typename</span> P2::y>::type;</div><div class="line"> <span class="keyword">using</span> type = <span class="keyword">typename</span> sqrt<</div><div class="line"> <span class="keyword">typename</span> <a class="code" href="group__group-Monoid.html#gaeb5d4a1e967e319712f9e4791948896c">mpl::plus</a><</div><div class="line"> <span class="keyword">typename</span> mpl::multiplies<xs, xs>::type,</div><div class="line"> <span class="keyword">typename</span> mpl::multiplies<ys, ys>::type</div><div class="line"> >::type</div><div class="line"> >::type;</div><div class="line">};</div><div class="line"></div><div class="line">static_assert(mpl::equal_to<</div><div class="line"> distance<point<mpl::int_<3>, mpl::int_<5>>,</div><div class="line"> point<mpl::int_<7>, mpl::int_<2>>>::type,</div><div class="line"> mpl::int_<5></div><div class="line">>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> Yeah... Now, let's implement it with the value-level approach presented above:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> P1, <span class="keyword">typename</span> P2></div><div class="line">constexpr <span class="keyword">auto</span> distance(P1 p1, P2 p2) {</div><div class="line"> <span class="keyword">auto</span> xs = p1.x - p2.x;</div><div class="line"> <span class="keyword">auto</span> ys = p1.y - p2.y;</div><div class="line"> <span class="keywordflow">return</span> sqrt(xs*xs + ys*ys);</div><div class="line">}</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(distance(point(3_c, 5_c), point(7_c, 2_c)) == 5_c);</div></div><!-- fragment --><p> This version looks arguably cleaner. However, this is not all. Notice how the <code>distance</code> function looks exactly as the one you would have written for computing the euclidean distance on dynamic values? Indeed, because we're using the same syntax for dynamic and compile-time arithmetic, generic functions written for one will work for both!</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> p1 = point(3, 5); <span class="comment">// dynamic values now</span></div><div class="line"><span class="keyword">auto</span> p2 = point(7, 2); <span class="comment">//</span></div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(distance(p1, p2) == 5); <span class="comment">// same function works!</span></div></div><!-- fragment --><p> <b>Without changing any code</b>, we can use our <code>distance</code> function on runtime values and everything just works. Now that's DRY.</p>
<h2><a class="anchor" id="tutorial-integral-branching"></a>
Compile-time branching</h2>
<p>Once we have compile-time arithmetic, the next thing that might come to mind is compile-time branching. When metaprogramming, it is often useful to have one piece of code be compiled if some condition is true, and a different one otherwise. If you have heard of <a href="path_to_url">static_if</a>, this should sound very familiar, and indeed it is exactly what we are talking about. Otherwise, if you don't know why we might want to branch at compile-time, consider the following code (adapted from <a href="path_to_url">N4461</a>):</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line"> std::enable_if_t<std::is_constructible<T, Args...><a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">::value</a>,</div><div class="line">std::unique_ptr<T>> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(args)...));</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line"> std::enable_if_t<!std::is_constructible<T, Args...><a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">::value</a>,</div><div class="line">std::unique_ptr<T>> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(args)...});</div><div class="line">}</div></div><!-- fragment --><p>This code creates a <code>std::unique_ptr</code> using the correct form of syntax for the constructor. To achieve this, it uses <a href="path_to_url">SFINAE</a> and requires two different overloads. Now, anyone sane seeing this for the first time would ask why it is not possible to simply write:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line">std::unique_ptr<T> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">if</span> (<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">std::is_constructible<T, Args...>::value</a>)</div><div class="line"> <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(args)...));</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(args)...});</div><div class="line">}</div></div><!-- fragment --><p>The reason is that the compiler is required to compile both branches of the <code>if</code> statement, regardless of the condition (even though it is known at compile-time). But when <code>T</code> is <em>not</em> constructible from <code>Args...</code>, the second branch will fail to compile, which will cause a hard compilation error. What we need really is a way to tell the compiler <b>not to compile</b> the second branch when the condition is true, and the first branch when the condition is false.</p>
<p>To emulate this, Hana provides an <code>if_</code> function that works a bit like a normal <code>if</code> statement, except except it takes a condition that can be an <code>IntegralConstant</code> and returns the one of two values (which may have different types) chosen by the condition. If the condition is true, the first value is returned, and otherwise the second value is returned. A somewhat vain example is the following:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> one_two_three = <a class="code" href="group__group-Logical.html#gafd655d2222367131e7a63616e93dd080">hana::if_</a>(hana::true_c, 123, <span class="stringliteral">"hello"</span>);</div><div class="line"><span class="keyword">auto</span> hello = <a class="code" href="group__group-Logical.html#gafd655d2222367131e7a63616e93dd080">hana::if_</a>(hana::false_c, 123, <span class="stringliteral">"hello"</span>);</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd><code>hana::true_c</code> and <code>hana::false_c</code> are just boolean <code>IntegralConstant</code>s representing a compile-time true value and a compile-time false value, respectively.</dd></dl>
<p>Here, <code>one_two_three</code> is equal to <code>123</code>, and <code>hello</code> is equal to <code>"hello"</code>. In other words, <code>if_</code> is a little bit like the ternary conditional operator <code>? :</code>, except that both sides of the <code>:</code> can have different types:</p>
<div class="fragment"><div class="line"><span class="comment">// fails in both cases because both branches have incompatible types</span></div><div class="line"><span class="keyword">auto</span> one_two_three = hana::true_c ? 123 : <span class="stringliteral">"hello"</span>;</div><div class="line"><span class="keyword">auto</span> hello = hana::false_c ? 123 : <span class="stringliteral">"hello"</span>;</div></div><!-- fragment --><p>Ok, so this is neat, but how can it actually help us write complete branches that are lazily instantiated by the compiler? The answer is to represent both branches of the <code>if</code> statement we'd like to write as generic lambdas, and to use <code>hana::if_</code> to return the branch that we'd like to execute. Here's how we could rewrite <code>make_unique</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line">std::unique_ptr<T> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Logical.html#gafd655d2222367131e7a63616e93dd080">hana::if_</a>(std::is_constructible<T, Args...>{},</div><div class="line"> [](<span class="keyword">auto</span>&& ...x) { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(x)...)); },</div><div class="line"> [](<span class="keyword">auto</span>&& ...x) { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(x)...}); }</div><div class="line"> )(std::forward<Args>(args)...);</div><div class="line">}</div></div><!-- fragment --><p> Here, the first value given to <code>hana::if_</code> is a generic lambda representing the branch we want to execute if the condition is true, and the second value is the branch we want to execute otherwise. <code>hana::if_</code> simply returns the branch chosen by the condition, and we call that branch (which is a generic lambda) immediately with <code>std::forward<Args>(args)...</code>. Hence, the proper generic lambda ends up being called, with <code>x...</code> being <code>args...</code>, and we return the result of that call.</p>
<p>The reason why this approach works is because the body of each branch can only be instantiated when the types of all <code>x...</code> are known. Indeed, since the branch is a generic lambda, the type of the argument is not known until the lambda is called, and the compiler must wait for the types of <code>x...</code> to be known before type-checking the lambda's body. Since the erroneous lambda is never called when the condition is not satisfied (<code>hana::if_</code> takes care of that), the body of the lambda that would fail is never type-checked and no compilation error happens.</p>
<dl class="section note"><dt>Note</dt><dd>The branches inside the <code>if_</code> are lambdas. As such, they really are different functions from the <code>make_unique</code> function. The variables appearing inside those branches have to be either captured by the lambdas or passed to them as arguments, and so they are affected by the way they are captured or passed (by value, by reference, etc..).</dd></dl>
<p>Since this pattern of expressing branches as lambdas and then calling them is very common, Hana provides a <code>eval_if</code> function whose purpose is to make compile-time branching easier. <code>eval_if</code> comes from the fact that in a lambda, one can either receive input data as arguments or capture it from the context. However, for the purpose of emulating a language level <code>if</code> statement, implicitly capturing variables from the enclosing scope is usually more natural. Hence, what we would prefer writing is</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line">std::unique_ptr<T> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Logical.html#gafd655d2222367131e7a63616e93dd080">hana::if_</a>(std::is_constructible<T, Args...>{},</div><div class="line"> [&] { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(args)...)); },</div><div class="line"> [&] { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(args)...}); }</div><div class="line"> );</div><div class="line">}</div></div><!-- fragment --><p>Here, we're capturing the <code>args...</code> variables from the enclosing scope, which prevents us from having to introduce the new <code>x...</code> variables and passing them as arguments to the branches. However, this has two problems. First, this will not achieve the right result, since <code>hana::if_</code> will end up returning a lambda instead of returning the result of calling that lambda. To fix this, we can use <code>hana::eval_if</code> instead of <code>hana::if_</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line">std::unique_ptr<T> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Logical.html#gab64636f84de983575aac0208f5fa840c">hana::eval_if</a>(std::is_constructible<T, Args...>{},</div><div class="line"> [&] { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(args)...)); },</div><div class="line"> [&] { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(args)...}); }</div><div class="line"> );</div><div class="line">}</div></div><!-- fragment --><p>Here, we capture the enclosing <code>args...</code> by reference using <code>[&]</code>, and we do not need to receive any arguments. Also, <code>hana::eval_if</code> assumes that its arguments are branches that can be called, and it will take care of calling the branch that is selected by the condition. However, this will still cause a compilation failure, because the bodies of the lambdas are not dependent anymore, and semantic analysis will be done for both branches even though only one would end up being used. The solution to this problem is to make the bodies of the lambdas artificially dependent on something, to prevent the compiler from being able to perform semantic analysis before the lambda is actually used. To make this possible, <code>hana::eval_if</code> will call the selected branch with an identity function (a function that returns its argument unchanged), if the branch accepts such an argument:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> ...Args></div><div class="line">std::unique_ptr<T> make_unique(Args&&... args) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Logical.html#gab64636f84de983575aac0208f5fa840c">hana::eval_if</a>(std::is_constructible<T, Args...>{},</div><div class="line"> [&](<span class="keyword">auto</span> <a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">_</a>) { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T(std::forward<Args>(<a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">_</a>(args))...)); },</div><div class="line"> [&](<span class="keyword">auto</span> <a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">_</a>) { <span class="keywordflow">return</span> std::unique_ptr<T>(<span class="keyword">new</span> T{std::forward<Args>(<a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">_</a>(args))...}); }</div><div class="line"> );</div><div class="line">}</div></div><!-- fragment --><p> Here, the bodies of the branches take an additional argument called <code>_</code> by convention. This argument will be provided by <code>hana::eval_if</code> to the branch that was selected. Then, we use <code>_</code> as a function on the variables that we want to make dependent within the body of each branch. What happens is that <code>_</code> will always be a function that returns its argument unchanged. However, the compiler can't possibly know it before the lambda has actually been called, so it can't know the type of <code>_(args)</code>. This prevents the compiler from being able to perform semantic analysis, and no compilation error happens. Plus, since <code>_(x)</code> is guaranteed to be equivalent to <code>x</code>, we know that we're not actually changing the semantics of the branches by using this trick.</p>
<p>While using this trick may seem cumbersome, it can be very useful when dealing with many variables inside a branch. Furthermore, it is not required to wrap all variables with <code>_</code>; only variables that are involved in an expression whose type-checking has to be delayed must be wrapped, but the other ones are not required. There are still a few things to know about compile-time branching in Hana, but you can dig deeper by looking at the reference for <code>hana::eval_if</code>, <code>hana::if_</code> and <code>hana::lazy</code>.</p>
<h2><a class="anchor" id="tutorial-integral-more"></a>
Why stop here?</h2>
<p>Why should we limit ourselves to arithmetic operations and branching? When you start considering <code>IntegralConstant</code>s as objects, it becomes sensible to augment their interface with more functions that are generally useful. For example, Hana's <code>IntegralConstant</code>s define a <code>times</code> member function that can be used to invoke a function a certain number of times, which is especially useful for loop unrolling:</p>
<div class="fragment"><div class="line">__attribute__((noinline)) void f() { }</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main() {</div><div class="line"> hana::int_c<10>.times(f);</div><div class="line">}</div></div><!-- fragment --><p>In the above code, the 10 calls to <code>f</code> are expanded at compile-time. In other words, this is equivalent to writing</p>
<div class="fragment"><div class="line">f(); f(); ... f(); <span class="comment">// 10 times</span></div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>Always <a href="path_to_url">be careful</a> about manually unrolling loops or doing other such optimizations manually. In most cases, your compiler is probably better than you at optimizing. When in doubt, benchmark.</dd></dl>
<p>Another nice use of <code>IntegralConstant</code>s is to define good-looking operators for indexing heterogeneous sequences. Whereas <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> must be accessed with <code>std::get</code>, <code>hana::tuple</code> can be accessed using the familiar <code>operator[]</code> used for standard library containers:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> <a class="code" href="structboost_1_1hana_1_1map.html#a2e016a68e3ec6eb25868fadb7ce80132">values</a> = hana::make_tuple(1, <span class="charliteral">'x'</span>, 3.4f);</div><div class="line"><span class="keywordtype">char</span> x = <a class="code" href="structboost_1_1hana_1_1map.html#a2e016a68e3ec6eb25868fadb7ce80132">values</a>[1_c];</div></div><!-- fragment --><p>How this works is very simple. Basically, <code>hana::tuple</code> defines an <code>operator[]</code> taking an <code>IntegralConstant</code> instead of a normal integer, in a way similar to</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> N></div><div class="line">constexpr decltype(<span class="keyword">auto</span>) operator[](N const&) {</div><div class="line"> <span class="keywordflow">return</span> std::get<N::value>(*this);</div><div class="line">}</div></div><!-- fragment --><p>This is the end of the section on <code>IntegralConstant</code>s. This section introduced the feel behind Hana's new way of metaprogramming; if you liked what you've seen so far, the rest of this tutorial should feel just like home.</p>
<h1><a class="anchor" id="tutorial-type"></a>
Type computations</h1>
<hr/>
<p> At this point, if you are interested in doing type-level computations as with the MPL, you might be wondering how is Hana going to help you. Do not despair. Hana provides a way to perform type-level computations with a great deal of expressiveness by representing types as values, just like we represented compile-time numbers as values. This is a completely new way of approaching metaprogramming, and you should try to set your old MPL habits aside for a bit if you want to become proficient with Hana.</p>
<p>However, please be aware that modern C++ features like <a href="path_to_url#Function_return_type_deduction">auto-deduced return type</a> remove the need for type computations in many cases. Hence, before even considering to do a type computation, you should ask yourself whether there's a simpler way to achieve what you're trying to achieve. In most cases, the answer will be yes. However, when the answer is no, Hana will provide you with nuclear-strength facilities to do what needs to be done.</p>
<h2><a class="anchor" id="tutorial-type-objects"></a>
Types as objects</h2>
<p>The key behind Hana's approach to type-level computations is essentially the same as the approach to compile-time arithmetic. Basically, the idea is to represent compile-time entities as objects by wrapping them into some kind of container. For <code>IntegralConstant</code>s, the compile-time entities were constant expressions of an integral type and the wrapper we used was <code>integral_constant</code>. In this section, the compile-time entities will be types and the wrapper we'll be using is called <code>type</code>. Just like we did for <code>IntegralConstant</code>s, let's start by defining a dummy template that could be used to represent a type:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>basic_type {</div><div class="line"> <span class="comment">// empty (for now)</span></div><div class="line">};</div><div class="line"></div><div class="line">basic_type<int> Int{};</div><div class="line">basic_type<char> Char{};</div><div class="line"><span class="comment">// ...</span></div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>We're using the name <code>basic_type</code> here because we're only building a naive version of the actual functionality provided by Hana.</dd></dl>
<p>While this may seem completely useless, it is actually enough to start writing metafunctions that look like functions. Indeed, consider the following alternate implementations of <code>std::add_pointer</code> and <code>std::is_pointer</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr basic_type<T*> add_pointer(basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> {}; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> is_pointer(basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::bool_c<false>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> is_pointer(basic_type<T*> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::bool_c<true>; }</div></div><!-- fragment --><p>We've just written metafunctions that look like functions, just like we wrote compile-time arithmetic metafunctions as heterogeneous C++ operators in the previous section. Here's how we can use them:</p>
<div class="fragment"><div class="line">basic_type<int> t{};</div><div class="line"><span class="keyword">auto</span> p = add_pointer(t);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(is_pointer(p));</div></div><!-- fragment --><p>Notice how we can now use a normal function call syntax to perform type-level computations? This is analogous to how using values for compile-time numbers allowed us to use normal C++ operators to perform compile-time computations. Like we did for <code>integral_constant</code>, we can also go one step further and use C++14 variable templates to provide syntactic sugar for creating types:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr basic_type<T> <a class="code" href="structboost_1_1hana_1_1type.html#ae35139e732c4b75e91061513cf445628">type_c</a>{};</div><div class="line"></div><div class="line"><span class="keyword">auto</span> t = type_c<int>;</div><div class="line"><span class="keyword">auto</span> p = add_pointer(t);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(is_pointer(p));</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>This is not exactly how the <code>hana::type_c</code> variable template is implemented because of some subtleties; things were dumbed down here for the sake of the explanation. Please check the reference for <code>hana::type</code> to know exactly what you can expect from a <code>hana::type_c<...></code>.</dd></dl>
<h2><a class="anchor" id="tutorial-type-benefits"></a>
Benefits of this representation</h2>
<p>But what does that buy us? Well, since a <code>type_c<...></code> is just an object, we can store it in a heterogeneous sequence like a tuple, we can move it around and pass it to (or return it from) functions, and we can do basically anything else that requires an object:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> types = hana::make_tuple(hana::type_c<int*>, hana::type_c<char&>, hana::type_c<void>);</div><div class="line"><span class="keyword">auto</span> char_ref = types[1_c];</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(char_ref == hana::type_c<char&>);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>Writing <code>make_tuple(type_c<T>...)</code> can be annoying when there are several types. For this reason, Hana provides the <code>tuple_t<T...></code> variable template, which is syntactic sugar for <code>make_tuple(type_c<T>...)</code>.</dd></dl>
<p>Also, notice that since the above tuple is really just a normal heterogeneous sequence, we can apply heterogeneous algorithms on that sequence just like we could on a tuple of <code>int</code>s, for example. Furthermore, since we're just manipulating objects, we can now use the full language instead of just the small subset available at the type-level. For example, consider the task of removing all the types that are not a reference or a pointer from a sequence of types. With the MPL, we would have to use a placeholder expression to express the predicate, which is clunky:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> types = mpl::vector<int, char&, void*>;</div><div class="line"><span class="keyword">using</span> ts = mpl::copy_if<types, mpl::or_<std::is_pointer<mpl::_1>,</div><div class="line"> std::is_reference<mpl::_1>>>::type;</div><div class="line"><span class="comment">// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</span></div><div class="line"><span class="comment">// placeholder expression</span></div><div class="line"></div><div class="line">static_assert(<a class="code" href="group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547">mpl::equal</a><ts, mpl::vector<char&, void*>>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> Now, since we're manipulating objects, we can use the full language and use a generic lambda instead, which leads to much more readable code:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> types = hana::tuple_t<int*, char&, void>;</div><div class="line"></div><div class="line"><span class="keyword">auto</span> ts = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(types, [](<span class="keyword">auto</span> t) {</div><div class="line"> <span class="keywordflow">return</span> is_pointer(t) || is_reference(t);</div><div class="line">});</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(ts == hana::tuple_t<int*, char&>);</div></div><!-- fragment --><p> Since Hana handles all heterogeneous containers uniformly, this approach of representing types as values also has the benefit that a single library is now needed for both heterogeneous computations and type level computations. Indeed, whereas we would normally need two different libraries to perform almost identical tasks, we now need a single library. Again, consider the task of filtering a sequence with a predicate. With MPL and Fusion, this is what we must do:</p>
<div class="fragment"><div class="line"><span class="comment">// types (MPL)</span></div><div class="line"><span class="keyword">using</span> types = mpl::vector<int*, char&, void>;</div><div class="line"><span class="keyword">using</span> ts = mpl::copy_if<types, mpl::or_<std::is_pointer<mpl::_1>,</div><div class="line"> std::is_reference<mpl::_1>>>::type;</div><div class="line"></div><div class="line"><span class="comment">// values (Fusion)</span></div><div class="line"><span class="keyword">auto</span> <a class="code" href="structboost_1_1hana_1_1map.html#a2e016a68e3ec6eb25868fadb7ce80132">values</a> = fusion::make_vector(1, <span class="charliteral">'c'</span>, <span class="keyword">nullptr</span>, 3.5);</div><div class="line"><span class="keyword">auto</span> vs = fusion::filter_if<std::is_integral<mpl::_1>>(<a class="code" href="structboost_1_1hana_1_1map.html#a2e016a68e3ec6eb25868fadb7ce80132">values</a>);</div></div><!-- fragment --><p> With Hana, a single library is required. Notice how we use the same <code>filter</code> algorithm and the same container, and only tweak the predicate so it can operate on values:</p>
<div class="fragment"><div class="line"><span class="comment">// types</span></div><div class="line"><span class="keyword">auto</span> types = hana::tuple_t<int*, char&, void>;</div><div class="line"><span class="keyword">auto</span> ts = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(types, [](<span class="keyword">auto</span> t) {</div><div class="line"> <span class="keywordflow">return</span> is_pointer(t) || is_reference(t);</div><div class="line">});</div><div class="line"></div><div class="line"><span class="comment">// values</span></div><div class="line"><span class="keyword">auto</span> <a class="code" href="structboost_1_1hana_1_1map.html#a2e016a68e3ec6eb25868fadb7ce80132">values</a> = hana::make_tuple(1, <span class="charliteral">'c'</span>, <span class="keyword">nullptr</span>, 3.5);</div><div class="line"><span class="keyword">auto</span> vs = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(values, [](<span class="keyword">auto</span> <span class="keyword">const</span>& t) {</div><div class="line"> <span class="keywordflow">return</span> is_integral(hana::typeid_(t));</div><div class="line">});</div></div><!-- fragment --><p> But that is not all. Indeed, having a unified syntax for type-level and value-level computations allows us to achieve greater consistency in the interface of heterogeneous containers. For example, consider the simple task of creating a heterogeneous map associating types to values, and then accessing an element of it. With Fusion, what's happening is far from obvious to the untrained eye:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> map = fusion::make_map<char, int, long, float, double, void>(</div><div class="line"> <span class="stringliteral">"char"</span>, <span class="stringliteral">"int"</span>, <span class="stringliteral">"long"</span>, <span class="stringliteral">"float"</span>, <span class="stringliteral">"double"</span>, <span class="stringliteral">"void"</span></div><div class="line">);</div><div class="line"></div><div class="line">std::string Int = fusion::at_key<int>(map);</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(Int == <span class="stringliteral">"int"</span>);</div></div><!-- fragment --><p> However, with a unified syntax for types and values, the same thing becomes much clearer:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> map = hana::make_map(</div><div class="line"> hana::make_pair(hana::type_c<char>, <span class="stringliteral">"char"</span>),</div><div class="line"> hana::make_pair(hana::type_c<int>, <span class="stringliteral">"int"</span>),</div><div class="line"> hana::make_pair(hana::type_c<long>, <span class="stringliteral">"long"</span>),</div><div class="line"> hana::make_pair(hana::type_c<float>, <span class="stringliteral">"float"</span>),</div><div class="line"> hana::make_pair(hana::type_c<double>, <span class="stringliteral">"double"</span>)</div><div class="line">);</div><div class="line"></div><div class="line">std::string Int = map[hana::type_c<int>];</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(Int == <span class="stringliteral">"int"</span>);</div></div><!-- fragment --><p> While Hana's way takes more lines of codes, it is also arguably more readable and closer to how someone would expect to initialize a map.</p>
<h2><a class="anchor" id="tutorial-type-working"></a>
Working with this representation</h2>
<p>So far, we can represent types as values and perform type-level computations on those objects using the usual C++ syntax. This is nice, but it is not very useful because we have no way to get back a normal C++ type from an object representation. For example, how could we declare a variable whose type is the result of a type computation?</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> t = add_pointer(hana::type_c<int>); <span class="comment">// could be a complex type computation</span></div><div class="line"><span class="keyword">using</span> T = the-type-represented-by-t;</div><div class="line"></div><div class="line">T var = ...;</div></div><!-- fragment --><p>Right now, there is no easy way to do it. To make this easier to achieve, we enrich the interface of the <code>basic_type</code> container that we defined above. Instead of being an empty <code>struct</code>, we now define it as</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>basic_type {</div><div class="line"> <span class="keyword">using</span> type = T;</div><div class="line">};</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>This is equivalent to making <code>basic_type</code> a metafunction in the MPL sense.</dd></dl>
<p>This way, we can use <code>decltype</code> to easily access the actual C++ type represented by a <code>type_c<...></code> object:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> t = add_pointer(hana::type_c<int>);</div><div class="line"><span class="keyword">using</span> T = decltype(t)::type; <span class="comment">// fetches basic_type<T>::type</span></div><div class="line"></div><div class="line">T var = ...;</div></div><!-- fragment --><p>In general, doing type-level metaprogramming with Hana is a three step process:</p>
<ol type="1">
<li>Represent types as objects by wrapping them with <code>hana::type_c<...></code></li>
<li>Perform type transformations with value syntax</li>
<li>Unwrap the result with <code>decltype(...)::type</code></li>
</ol>
<p>Now, you must be thinking that this is incredibly cumbersome. In reality, it is very manageable for several reasons. First, this wrapping and unwrapping only needs to happen at some very thin boundaries.</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> t = hana::type_c<T>;</div><div class="line"><span class="keyword">auto</span> result = huge_type_computation(t);</div><div class="line"><span class="keyword">using</span> Result = decltype(result)::type;</div></div><!-- fragment --><p>Furthermore, since you get the advantage of working with objects (without having to wrap/unwrap) inside the computation, the cost of wrapping and unwrapping is amortized on the whole computation. Hence, for complex type computations, the syntactic noise of this three step process quickly becomes negligible in light of the expressiveness gain of working with values inside that computation. Also, using values instead of types means that we can avoid typing <code>typename</code> and <code>template</code> all around the place, which accounted for a lot of syntactic noise in classic metaprogramming.</p>
<p>Another point is that the three full steps are not always required. Indeed, sometimes one just needs to do a type-level computation and query something about the result, without necessarily fetching the result as a normal C++ type:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> t = hana::type_c<T>;</div><div class="line"><span class="keyword">auto</span> result = type_computation(t);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(is_pointer(result)); <span class="comment">// third step skipped</span></div></div><!-- fragment --><p>In this case, we were able to skip the third step because we did not need to access the actual type represented by <code>result</code>. In other cases, the first step can be avoided, like when using <code>tuple_t</code>, which has no more syntactic noise than any other pure type-level approach:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> types = hana::tuple_t<int*, char&, void>; <span class="comment">// first step skipped</span></div><div class="line"></div><div class="line"><span class="keyword">auto</span> pointers = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(types, [](<span class="keyword">auto</span> t) {</div><div class="line"> <span class="keywordflow">return</span> add_pointer(t);</div><div class="line">});</div></div><!-- fragment --><p> For skeptical readers, let's consider the task of finding the smallest type in a sequence of types. This is a very good example of a short type-only computation, which is where we would expect the new paradigm to suffer the most. As you will see, things stay manageable even for small computations. First, let's implement it with the MPL:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...T></div><div class="line"><span class="keyword">struct </span>smallest</div><div class="line"> : mpl::deref<</div><div class="line"> typename mpl::min_element<</div><div class="line"> mpl::vector<T...>,</div><div class="line"> mpl::less<mpl::sizeof_<mpl::_1>, mpl::sizeof_<mpl::_2>></div><div class="line"> >::type</div><div class="line"> ></div><div class="line">{ };</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...T></div><div class="line"><span class="keyword">using</span> smallest_t = <span class="keyword">typename</span> smallest<T...>::type;</div><div class="line"></div><div class="line">static_assert(std::is_same<</div><div class="line"> smallest_t<char, long, long double>,</div><div class="line"> <span class="keywordtype">char</span></div><div class="line">>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> The result is quite readable (for anyone familiar with the MPL). Let's now implement the same thing using Hana:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...T></div><div class="line"><span class="keyword">auto</span> smallest = <a class="code" href="group__group-Foldable.html#ga347429451fdb15f9f7a7fc0de293be1a">hana::minimum</a>(hana::make_tuple(hana::type_c<T>...), [](<span class="keyword">auto</span> t, <span class="keyword">auto</span> u) {</div><div class="line"> <span class="keywordflow">return</span> hana::sizeof_(t) < hana::sizeof_(u);</div><div class="line">});</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...T></div><div class="line"><span class="keyword">using</span> smallest_t = <span class="keyword">typename</span> decltype(smallest<T...>)::type;</div><div class="line"></div><div class="line">static_assert(std::is_same<</div><div class="line"> smallest_t<char, long, long double>, <span class="keywordtype">char</span></div><div class="line">>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> As you can witness, the syntactic noise of the 3-step process is almost completely hidden by the rest of the computation.</p>
<h2><a class="anchor" id="tutorial-type-lifting"></a>
The generic lifting process</h2>
<p>The first type-level computation that we introduced in the form of a function looked like:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> add_pointer(hana::basic_type<T> <span class="keyword">const</span>&) {</div><div class="line"> <span class="keywordflow">return</span> hana::type<T*>;</div><div class="line">}</div></div><!-- fragment --><p>While it looks more complicated, we could also write it as:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> add_pointer(hana::basic_type<T> <span class="keyword">const</span>&) {</div><div class="line"> <span class="keywordflow">return</span> hana::type_c<typename std::add_pointer<T>::type>;</div><div class="line">}</div></div><!-- fragment --><p>However, this implementation emphasizes the fact that we're really emulating an existing metafunction and simply representing it as a function. In other words, we're <em>lifting</em> a metafunction (<code>std::add_pointer</code>) to the world of values by creating our own <code>add_pointer</code> function. It turns out that this lifting process is a generic one. Indeed, given any metafunction, we could write almost the same thing:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> add_const(hana::basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<typename std::add_const<T>::type>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> add_volatile(hana::basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<typename std::add_volatile<T>::type>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> add_lvalue_reference(hana::basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<typename std::add_lvalue_reference<T>::type>; }</div><div class="line"></div><div class="line"><span class="comment">// etc...</span></div></div><!-- fragment --><p>This mechanical transformation is easy to abstract into a generic lifter that can handle any <a href="path_to_url">MPL Metafunction</a> as follows:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">template</span> <<span class="keyword">typename</span>> <span class="keyword">class </span>F, <span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keyword">auto</span> <a class="code" href="group__group-Metafunction.html#gaaa4f85cb8cbce21f5c04ef40ca35cc6a">metafunction</a>(hana::basic_type<T> <span class="keyword">const</span>&)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<typename F<T>::type>; }</div><div class="line"></div><div class="line"><span class="keyword">auto</span> t = hana::type_c<int>;</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(metafunction<std::add_pointer>(t) == hana::type_c<int*>);</div></div><!-- fragment --><p> More generally, we'll want to allow metafunctions with any number of arguments, which brings us to the following less naive implementation:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">template</span> <<span class="keyword">typename</span> ...> <span class="keyword">class </span>F, <span class="keyword">typename</span> ...T></div><div class="line">constexpr <span class="keyword">auto</span> <a class="code" href="group__group-Metafunction.html#gaaa4f85cb8cbce21f5c04ef40ca35cc6a">metafunction</a>(hana::basic_type<T> <span class="keyword">const</span>& ...)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<<span class="keyword">typename</span> F<T...>::type>; }</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(</div><div class="line"> metafunction<std::common_type>(hana::type_c<int>, hana::type_c<long>) == hana::type_c<long></div><div class="line">);</div></div><!-- fragment --><p> Hana provides a similar generic metafunction lifter called <code>hana::metafunction</code>. One small improvement is that <code>hana::metafunction<F></code> is a function object instead of an overloaded function, so one can pass it to higher-order algorithms. It is also a model of the slightly more powerful concept of <code>Metafunction</code>, but this can safely be ignored for now. The process we explored in this section does not only apply to metafunctions; it also applies to templates. Indeed, we could define:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">template</span> <<span class="keyword">typename</span> ...> <span class="keyword">class </span>F, <span class="keyword">typename</span> ...T></div><div class="line">constexpr <span class="keyword">auto</span> <a class="code" href="group__group-Metafunction.html#ga246419f6c3263b648412f346106e6543">template_</a>(hana::basic_type<T> <span class="keyword">const</span>& ...)</div><div class="line">{ <span class="keywordflow">return</span> hana::type_c<F<T...>>; }</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(</div><div class="line"> template_<std::vector>(hana::type_c<int>) == hana::type_c<std::vector<int>></div><div class="line">);</div></div><!-- fragment --><p> Hana provides a generic lifter for templates named <code>hana::template_</code>, and it also provides a generic lifter for <a href="path_to_url">MPL MetafunctionClasses</a> named <code>hana::metafunction_class</code>. This gives us a way to uniformly represent "legacy" type-level computations as functions, so that any code written using a classic type-level metaprogramming library can almost trivially be used with Hana. For example, say you have a large chunk of MPL-based code and you'd like to interface with Hana. The process of doing so is no harder than wrapping your metafunctions with the lifter provided by Hana:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>legacy {</div><div class="line"> <span class="keyword">using</span> type = ...; <span class="comment">// something you really don't want to mess with</span></div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">auto</span> types = hana::make_tuple(...);</div><div class="line"><span class="keyword">auto</span> use = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(types, hana::metafunction<legacy>);</div></div><!-- fragment --><p>However, note that not all type-level computations can be lifted as-is with the tools provided by Hana. For example, <code>std::extent</code> can't be lifted because it requires non-type template parameters. Since there is no way to deal with non-type template parameters uniformly in C++, one must resort to using a hand-written function object specific to that type-level computation:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> extent = [](<span class="keyword">auto</span> t, <span class="keyword">auto</span> n) {</div><div class="line"> <span class="keywordflow">return</span> std::extent<typename decltype(t)::type, hana::value(n)>{};</div><div class="line">};</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(extent(hana::type_c<char>, hana::int_c<1>) == hana::size_c<0>);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(extent(hana::type_c<<span class="keywordtype">char</span>[1][2]>, hana::int_c<1>) == hana::size_c<2>);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>Do not forget to include the bridge header for <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code>s (<code><<a class="el" href="ext_2std_2integral__constant_8hpp.html" title="Adapts std::integral_constant for use with Hana. ">boost/hana/ext/std/integral_constant.hpp</a>></code>) when using type traits from <code><type_traits></code> directly.</dd></dl>
<p>In practice, however, this should not be a problem since the vast majority of type-level computations can be lifted easily. Finally, since metafunctions provided by the <code><type_traits></code> header are used so frequently, Hana provides a lifted version for every one of them. Those lifted traits are in the <code>hana::traits</code> namespace, and they live in the <code><<a class="el" href="traits_8hpp.html" title="Defines function-like equivalents to the standard <type_traits>, and also to some utilities like std:...">boost/hana/traits.hpp</a>></code> header:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(hana::traits::add_pointer(hana::type_c<int>) == hana::type_c<int*>);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(hana::traits::common_type(hana::type_c<int>, hana::type_c<long>) == hana::type_c<long>);</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(hana::traits::is_integral(hana::type_c<int>));</div><div class="line"></div><div class="line"><span class="keyword">auto</span> types = hana::tuple_t<int, char, long>;</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(<a class="code" href="group__group-Searchable.html#ga3a168950082f38afd9edf256f336c8ba">hana::all_of</a>(types, hana::traits::is_integral));</div></div><!-- fragment --><p> This is the end of the section on type computations. While this new paradigm for type level programming might be difficult to grok at first, it will make more sense as you use it more and more. You will also come to appreciate how it blurs the line between types and values, opening new exciting possibilities and simplifying many tasks.</p>
<dl class="section note"><dt>Note</dt><dd>Curious or skeptical readers should consider checking the minimal reimplementation of the MPL presented in the <a class="el" href="index.html#tutorial-appendix-MPL">appendices</a>.</dd></dl>
<h1><a class="anchor" id="tutorial-introspection"></a>
Introspection</h1>
<hr/>
<p> Static introspection, as we will discuss it here, is the ability of a program to examine the type of an object at compile-time. In other words, it is a programmatic interface to interact with types at compile-time. For example, have you ever wanted to check whether some unknown type has a member named <code>foo</code>? Or perhaps at some point you have needed to iterate on the members of a <code>struct</code>?</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Person {</div><div class="line"> std::string name;</div><div class="line"> <span class="keywordtype">int</span> age;</div><div class="line">};</div><div class="line"></div><div class="line">Person john{<span class="stringliteral">"John"</span>, 30};</div><div class="line"><span class="keywordflow">for</span> (<span class="keyword">auto</span>& member : john)</div><div class="line"> std::cout << member.name << <span class="stringliteral">": "</span> << member.value << std::endl;</div><div class="line"></div><div class="line"><span class="comment">// name: John</span></div><div class="line"><span class="comment">// age: 30</span></div></div><!-- fragment --><p>If you have written a bit of templates in your life, chances are very high that you came across the first problem of checking for a member. Also, anyone having tried to implement object serialization or even just pretty printing has come across the second problem. In most dynamic languages like Python, Ruby or JavaScript, these problems are completely solved and introspection is used every day by programmers to make a lot of tasks simpler. However, as a C++ programmer, we do not have language support for those things, which makes several tasks much harder than they should be. While language support would likely be needed to properly tackle this problem, Hana makes some common introspection patterns much more accessible.</p>
<h2><a class="anchor" id="tutorial-introspection-is_valid"></a>
Checking expression validity</h2>
<p>Given an object of an unknown type, it is sometimes desirable to check whether this object has a member (or member function) with some name. This can be used to perform sophisticated flavors of overloading. For example, consider the problem of calling a <code>toString</code> method on objects that support it, but providing another default implementation for objects that do not support it:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">std::string optionalToString(T <span class="keyword">const</span>& obj) {</div><div class="line"> <span class="keywordflow">if</span> (obj.toString() is a valid expression)</div><div class="line"> <span class="keywordflow">return</span> obj.toString();</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> <span class="stringliteral">"toString not defined"</span>;</div><div class="line">}</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>While most use cases for this technique will be addressed by <a href="path_to_url">concepts lite</a> in future revisions of the standard, there will still be cases where a quick and dirty check is more convenient than creating a full blown concept.</dd></dl>
<p>How could we implement a check for the validity of <code>obj.toString()</code> as above in a generic fashion (so it can be reused in other functions, for example)? Normally, we would be stuck writing some kind of SFINAE-based detection:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T, <span class="keyword">typename</span> = <span class="keywordtype">void</span>></div><div class="line"><span class="keyword">struct </span>has_toString</div><div class="line"> : std::false_type</div><div class="line">{ };</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>has_toString<T, decltype((void)<a class="code" href="namespacestd.html">std</a>::declval<T>().toString())></div><div class="line"> : std::true_type</div><div class="line">{ };</div></div><!-- fragment --><p> This works, but the intent is not very clear and most people without a deep knowledge of template metaprogramming would think this is black magic. Then, we could implement <code>optionalToString</code> as</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">std::string optionalToString(T <span class="keyword">const</span>& obj) {</div><div class="line"> <span class="keywordflow">if</span> (<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">has_toString<T>::value</a>)</div><div class="line"> <span class="keywordflow">return</span> obj.toString();</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> <span class="stringliteral">"toString not defined"</span>;</div><div class="line">}</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>Of course, this implementation won't actually work because both branches of the <code>if</code> statement will be compiled. If <code>obj</code> does not have a <code>toString</code> method, the compilation of the <code>if</code> branch will fail. We will address this issue in a moment.</dd></dl>
<p>Instead of the above SFINAE trick, Hana provides a <code>is_valid</code> function that can be combined with <a href="path_to_url#Generic_lambdas">C++14 generic lambdas</a> to obtain a much cleaner implementation of the same thing:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_toString = hana::is_valid([](<span class="keyword">auto</span>&& obj) -> decltype(obj.toString()) { });</div></div><!-- fragment --><p> This leaves us with a function object <code>has_toString</code> which returns whether the given expression is valid on the argument we pass to it. The result is returned as an <code>IntegralConstant</code>, so <code>constexpr</code>-ness is not an issue here because the result of the function is represented as a type anyway. Now, in addition to being less verbose (that's a one liner!), the intent is much clearer. Other benefits are the fact that <code>has_toString</code> can be passed to higher order algorithms and it can also be defined at function scope, so there is no need to pollute the namespace scope with implementation details. Here is how we would now write <code>optionalToString</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">std::string optionalToString(T <span class="keyword">const</span>& obj) {</div><div class="line"> <span class="keywordflow">if</span> (has_toString(obj))</div><div class="line"> <span class="keywordflow">return</span> obj.toString();</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> <span class="stringliteral">"toString not defined"</span>;</div><div class="line">}</div></div><!-- fragment --><p>Much cleaner, right? However, as we said earlier, this implementation won't actually work because both branches of the <code>if</code> always have to be compiled, regardless of whether <code>obj</code> has a <code>toString</code> method. There are several possible options, but the most classical one is to use <code>std::enable_if</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> optionalToString(T <span class="keyword">const</span>& obj)</div><div class="line"> -> std::enable_if_t<decltype(has_toString(obj))::value, std::string></div><div class="line">{ <span class="keywordflow">return</span> obj.toString(); }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> optionalToString(T <span class="keyword">const</span>& obj)</div><div class="line"> -> std::enable_if_t<decltype(!has_toString(obj))::value, std::string></div><div class="line">{ <span class="keywordflow">return</span> <span class="stringliteral">"toString not defined"</span>; }</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>We're using the fact that <code>has_toString</code> returns an <code>IntegralConstant</code> to write <code>decltype(...)::value</code>, which is a constant expression. For some reason, <code>has_toString(obj)</code> is not considered a constant expression, even though I think it should be one because we never read from <code>obj</code> (see the section on <a class="el" href="index.html#tutorial-appendix-constexpr">advanced constexpr</a>).</dd></dl>
<p>While this implementation is perfectly valid, it is still pretty cumbersome because it requires writing two different functions and going through the hoops of SFINAE explicitly by using <code>std::enable_if</code>. However, as you might remember from the section on <a class="el" href="index.html#tutorial-integral-branching">compile-time branching</a>, Hana provides an <code>if_</code> function that can be used to emulate the functionality of <a href="path_to_url">static_if</a>. Here is how we could write <code>optionalToString</code> with <code>hana::if_</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">std::string optionalToString(T <span class="keyword">const</span>& obj) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Logical.html#gafd655d2222367131e7a63616e93dd080">hana::if_</a>(has_toString(obj),</div><div class="line"> [](<span class="keyword">auto</span>& x) { <span class="keywordflow">return</span> x.toString(); },</div><div class="line"> [](<span class="keyword">auto</span>& x) { <span class="keywordflow">return</span> <span class="stringliteral">"toString not defined"</span>; }</div><div class="line"> )(obj);</div><div class="line">}</div></div><!-- fragment --><p> Now, the previous example covered only the specific case of checking for the presence of a non-static member function. However, <code>is_valid</code> can be used to detect the validity of almost any kind of expression. For completeness, we now present a list of common use cases for validity checking along with how to use <code>is_valid</code> to implement them.</p>
<h3><a class="anchor" id="tutorial-introspection-is_valid-non_static"></a>
Non-static members</h3>
<p>The first idiom we'll look at is checking for the presence of a non-static member. We can do it in a similar way as we did for the previous example:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_member = hana::is_valid([](<span class="keyword">auto</span>&& x) -> decltype((<span class="keywordtype">void</span>)x.member) { });</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Foo { <span class="keywordtype">int</span> member[4]; };</div><div class="line"><span class="keyword">struct </span>Bar { };</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(has_member(Foo{}));</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!has_member(Bar{}));</div></div><!-- fragment --><p> Notice how we cast the result of <code>x.member</code> to <code>void</code>? This is to make sure that our detection also works for types that can't be returned from functions, like array types. Also, it is important to use a reference as the parameter to our generic lambda, because that would otherwise require <code>x</code> to be <a href="path_to_url">CopyConstructible</a>, which is not what we're trying to check. This approach is simple and the most convenient when an object is available. However, when the checker is intended to be used with no object around, the following alternate implementation can be better suited:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_member = hana::is_valid([](<span class="keyword">auto</span> t) -> decltype(</div><div class="line"> (<span class="keywordtype">void</span>)hana::traits::declval(t).member</div><div class="line">) { });</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Foo { <span class="keywordtype">int</span> member[4]; };</div><div class="line"><span class="keyword">struct </span>Bar { };</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(has_member(hana::type_c<Foo>));</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!has_member(hana::type_c<Bar>));</div></div><!-- fragment --><p> This validity checker is different from what we saw earlier because the generic lambda is not expecting an usual object anymore; it is now expecting a <code>type</code> (which is an object, but still represents a type). We then use the <code>hana::traits::declval</code> <em>lifted metafunction</em> from the <code><<a class="el" href="traits_8hpp.html" title="Defines function-like equivalents to the standard <type_traits>, and also to some utilities like std:...">boost/hana/traits.hpp</a>></code> header to create an rvalue of the type represented by <code>t</code>, which we can then use to check for a non-static member. Finally, instead of passing an actual object to <code>has_member</code> (like <code>Foo{}</code> or <code>Bar{}</code>), we now pass a <code>type_c<...></code>. This implementation is ideal for when no object is lying around.</p>
<h3><a class="anchor" id="tutorial-introspection-is_valid-static"></a>
Static members</h3>
<p>Checking for a static member is easy, and it is provided for completeness:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_member = hana::is_valid([](<span class="keyword">auto</span> t) -> decltype(</div><div class="line"> (<span class="keywordtype">void</span>)decltype(t)::type::member</div><div class="line">) { });</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Foo { <span class="keyword">static</span> <span class="keywordtype">int</span> member[4]; };</div><div class="line"><span class="keyword">struct </span>Bar { };</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(has_member(hana::type_c<Foo>));</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!has_member(hana::type_c<Bar>));</div></div><!-- fragment --><p> Again, we expect a <code>type</code> to be passed to the checker. Inside the generic lambda, we use <code>decltype(t)::type</code> to fetch the actual C++ type represented by the <code>t</code> object, as explained in the section on <a class="el" href="index.html#tutorial-type-working">type computations</a>. Then, we fetch the static member inside that type and cast it to <code>void</code>, for the same reason as we did for non-static members.</p>
<h3><a class="anchor" id="tutorial-introspection-is_valid-typename"></a>
Nested type names</h3>
<p>Checking for a nested type name is not hard, but it is slightly more convoluted than the previous cases:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_member = hana::is_valid([](<span class="keyword">auto</span> t) -> hana::type<</div><div class="line"> <span class="keyword">typename</span> decltype(t)::type::member</div><div class="line"><span class="comment">//^^^^^^^^ needed because of the dependent context</span></div><div class="line">> { });</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Foo { <span class="keyword">struct </span>member; <span class="comment">/* not defined! */</span> };</div><div class="line"><span class="keyword">struct </span>Bar { };</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(has_member(hana::type_c<Foo>));</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!has_member(hana::type_c<Bar>));</div></div><!-- fragment --><p> One might wonder why we use <code>-> hana::type<typename-expression></code> instead of simply <code>-> typename-expression</code>. Again, the reason is that we want to support types that can't be returned from functions, like array types or incomplete types.</p>
<h3><a class="anchor" id="tutorial-introspection-is_valid-template"></a>
Nested templates</h3>
<p>Checking for a nested template name is similar to checking for a nested type name, except we use the <code>template_<...></code> variable template instead of <code>type<...></code> in the generic lambda:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> has_member = hana::is_valid([](<span class="keyword">auto</span> t) -> decltype(<a class="code" href="group__group-Metafunction.html#ga246419f6c3263b648412f346106e6543">hana::template_</a><</div><div class="line"> decltype(t)::type::template member</div><div class="line"> <span class="comment">// ^^^^^^^^ needed because of the dependent context</span></div><div class="line">>) { });</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Foo { <span class="keyword">template</span> <<span class="keyword">typename</span> ...> <span class="keyword">struct </span>member; };</div><div class="line"><span class="keyword">struct </span>Bar { };</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(has_member(hana::type_c<Foo>));</div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!has_member(hana::type_c<Bar>));</div></div><!-- fragment --><h2><a class="anchor" id="tutorial-introspection-sfinae"></a>
Taking control of SFINAE</h2>
<p>Doing something only if an expression is well-formed is a very common pattern in C++. Indeed, the <code>optionalToString</code> function is just one instance of the following pattern, which is very general:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> f(T x) {</div><div class="line"> <span class="keywordflow">if</span> (some expression involving x is well-formed)</div><div class="line"> <span class="keywordflow">return</span> something involving x;</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> something <span class="keywordflow">else</span>;</div><div class="line">}</div></div><!-- fragment --><p>To encapsulate this pattern, Hana provides the <code>sfinae</code> function, which allows executing an expression, but only if it is well-formed:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> maybe_add = hana::sfinae([](<span class="keyword">auto</span> x, <span class="keyword">auto</span> y) -> decltype(x + y) {</div><div class="line"> <span class="keywordflow">return</span> x + y;</div><div class="line">});</div><div class="line"></div><div class="line">maybe_add(1, 2); <span class="comment">// hana::just(3)</span></div><div class="line"></div><div class="line">std::vector<int> v;</div><div class="line">maybe_add(v, <span class="stringliteral">"foobar"</span>); <span class="comment">// hana::nothing</span></div></div><!-- fragment --><p> Here, we create a <code>maybe_add</code> function, which is simply a generic lambda wrapped with Hana's <code>sfinae</code> function. <code>maybe_add</code> is a function which takes two inputs and returns <code>just</code> the result of the generic lambda if that call is well-formed, and <code>nothing</code> otherwise. <code>just(...)</code> and <code>nothing</code> both belong to a type of container called <code>hana::optional</code>, which is essentially a compile-time <code>std::optional</code>. All in all, <code>maybe_add</code> is morally equivalent to the following function returning a <code>std::optional</code>, except that the check is done at compile-time:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> maybe_add = [](<span class="keyword">auto</span> x, <span class="keyword">auto</span> y) {</div><div class="line"> <span class="keywordflow">if</span> (x + y is well formed)</div><div class="line"> <span class="keywordflow">return</span> std::optional<decltype(x + y)>{x + y};</div><div class="line"> <span class="keywordflow">else</span></div><div class="line"> <span class="keywordflow">return</span> std::optional<???>{};</div><div class="line">};</div></div><!-- fragment --><p>It turns out that we can take advantage of <code>sfinae</code> and <code>optional</code> to implement the <code>optionalToString</code> function as follows:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">std::string optionalToString(T <span class="keyword">const</span>& obj) {</div><div class="line"> <span class="keyword">auto</span> maybe_toString = hana::sfinae([](<span class="keyword">auto</span>&& x) -> decltype(x.toString()) {</div><div class="line"> <span class="keywordflow">return</span> x.toString();</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> maybe_toString(obj).value_or(<span class="stringliteral">"toString not defined"</span>);</div><div class="line">}</div></div><!-- fragment --><p> First, we wrap <code>toString</code> with the <code>sfinae</code> function. Hence, <code>maybe_toString</code> is a function which either returns <code>just(x.toString())</code> if that is well-formed, or <code>nothing</code> otherwise. Secondly, we use the <code>.value_or()</code> function to extract the optional value from the container. If the optional value is <code>nothing</code>, <code>.value_or()</code> returns the default value given to it; otherwise, it returns the value inside the <code>just</code> (here <code>x.toString()</code>). This way of seeing SFINAE as a special case of computations that might fail is very clean and powerful, especially since <code>sfinae</code>'d functions can be combined through the <code>hana::optional</code> <code>Monad</code>, which is left to the reference documentation.</p>
<h2><a class="anchor" id="tutorial-introspection-adapting"></a>
Introspecting user-defined types</h2>
<p>Have you ever wanted to iterate over the members of a user-defined type? The goal of this section is to show you how Hana can be used to do it quite easily. To allow working with user-defined types, Hana defines the <code>Struct</code> concept. Once a user-defined type is a model of that concept, one can iterate over the members of an object of that type and query other useful information. To turn a user-defined type into a <code>Struct</code>, a couple of options are available. First, you may define the members of your user-defined type with the <code>BOOST_HANA_DEFINE_STRUCT</code> macro:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Person {</div><div class="line"> BOOST_HANA_DEFINE_STRUCT(Person,</div><div class="line"> (std::string, name),</div><div class="line"> (<span class="keywordtype">int</span>, age)</div><div class="line"> );</div><div class="line">};</div></div><!-- fragment --><p> This macro defines two members (<code>name</code> and <code>age</code>) with the given types. Then, it defines some boilerplate inside a <code>Person::hana</code> nested <code>struct</code>, which is required to make <code>Person</code> a model of the <code>Struct</code> concept. No constructors are defined (so <a href="path_to_url">POD-ness</a> is retained), the members are defined in the same order as they appear here and the macro can be used with template <code>struct</code>s just as well, and at any scope. Also note that you are free to add more members to the <code>Person</code> type after or before you use the macro. However, only members defined with the macro will be picked up when introspecting the <code>Person</code> type. Easy enough? Now, a <code>Person</code> can be accessed programmatically:</p>
<div class="fragment"><div class="line">Person john{<span class="stringliteral">"John"</span>, 30};</div><div class="line"></div><div class="line"><a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(john, [](<span class="keyword">auto</span> pair) {</div><div class="line"> std::cout << hana::to<char const*>(<a class="code" href="group__group-Product.html#ga34bbf4281de06dc3540441e8b2bd24f4">hana::first</a>(pair)) << <span class="stringliteral">": "</span></div><div class="line"> << <a class="code" href="group__group-Product.html#ga7bb979d59ffc3ab862cb7d9dc7730077">hana::second</a>(pair) << std::endl;</div><div class="line">});</div><div class="line"></div><div class="line"><span class="comment">// name: John</span></div><div class="line"><span class="comment">// age: 30</span></div></div><!-- fragment --><p> Iteration over a <code>Struct</code> is done as if the <code>Struct</code> was a sequence of pairs, where the first element of a pair is the key associated to a member, and the second element is the member itself. When a <code>Struct</code> is defined through the <code>BOOST_HANA_DEFINE_STRUCT</code> macro, the key associated to any member is a compile-time <code>hana::string</code> representing the name of that member. This is why the function used with <code>for_each</code> takes a single argument <code>pair</code>, and then uses <code>first</code> and <code>second</code> to access the subparts of the pair. Also, notice how the <code>to<char const*></code> function is used on the name of the member? This converts the compile-time string to a <code>constexpr char const*</code> so it can <code>cout</code>ed. Since it can be annoying to always use <code>first</code> and <code>second</code> to fetch the subparts of the pair, we can also use the <code>fuse</code> function to wrap our lambda and make it a binary lambda instead:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(john, <a class="code" href="group__group-Foldable.html#ga19fcf61d8d1179903952c0f564c538aa">hana::fuse</a>([](<span class="keyword">auto</span> name, <span class="keyword">auto</span> member) {</div><div class="line"> std::cout << hana::to<char const*>(name) << <span class="stringliteral">": "</span> << member << std::endl;</div><div class="line">}));</div></div><!-- fragment --><p> Now, it looks much cleaner. As we just mentioned, <code>Struct</code>s are seen as a kind of sequence of pairs for the purpose of iteration. In fact, a <code>Struct</code> can even be searched like an associative data structure whose keys are the names of the members, and whose values are the members themselves:</p>
<div class="fragment"><div class="line">std::string name = <a class="code" href="group__group-Searchable.html#ga3c1826aee6c6eb577810bb99c5c3e53d">hana::at_key</a>(john, <span class="stringliteral">"name"</span>_s);</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(name == <span class="stringliteral">"John"</span>);</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> age = <a class="code" href="group__group-Searchable.html#ga3c1826aee6c6eb577810bb99c5c3e53d">hana::at_key</a>(john, <span class="stringliteral">"age"</span>_s);</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(age == 30);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>The <code>_s</code> user-defined literal creates a compile-time <code>hana::string</code>. It is located in the <code><a class="el" href="namespaceboost_1_1hana_1_1literals.html" title="Namespace containing C++14 user-defined literals provided by Hana. ">boost::hana::literals</a></code> namespace. Note that it is not part of the standard yet, but it is supported by Clang and GCC. If you want to stay 100% standard, you can use the <code>BOOST_HANA_STRING</code> macro instead.</dd></dl>
<p>The main difference between a <code>Struct</code> and a <code>hana::map</code> is that a map can be modified (keys can be added and removed), while a <code>Struct</code> is immutable. However, you can easily convert a <code>Struct</code> into a <code>hana::map</code> with <code>to<map_tag></code>, and then you can manipulate it in a more flexible way.</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> map = <a class="code" href="group__group-Sequence.html#gae22a1a184b1b2dd550fa4fa619bed2e9">hana::insert</a>(hana::to<hana::map_tag>(john), hana::make_pair(<span class="stringliteral">"last name"</span>_s, <span class="stringliteral">"Doe"</span>s));</div><div class="line"></div><div class="line">std::string name = map[<span class="stringliteral">"name"</span>_s];</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(name == <span class="stringliteral">"John"</span>);</div><div class="line"></div><div class="line">std::string last_name = map[<span class="stringliteral">"last name"</span>_s];</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(last_name == <span class="stringliteral">"Doe"</span>);</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> age = map[<span class="stringliteral">"age"</span>_s];</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(age == 30);</div></div><!-- fragment --><p> Using the <code>BOOST_HANA_DEFINE_STRUCT</code> macro to adapt a <code>struct</code> is convenient, but sometimes one can't modify the type that needs to be adapted. In these cases, the <code>BOOST_HANA_ADAPT_STRUCT</code> macro can be used to adapt a <code>struct</code> in a ad-hoc manner:</p>
<div class="fragment"><div class="line"><span class="keyword">namespace </span>not_my_namespace {</div><div class="line"> <span class="keyword">struct </span>Person {</div><div class="line"> std::string name;</div><div class="line"> <span class="keywordtype">int</span> age;</div><div class="line"> };</div><div class="line">}</div><div class="line"></div><div class="line">BOOST_HANA_ADAPT_STRUCT(not_my_namespace::Person, name, age);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>The <code>BOOST_HANA_ADAPT_STRUCT</code> macro must be used at global scope.</dd></dl>
<p>The effect is exactly the same as with the <code>BOOST_HANA_DEFINE_STRUCT</code> macro, except you do not need to modify the type you want to adapt, which is sometimes useful. Finally, it is also possible to define custom accessors by using the <code>BOOST_HANA_ADAPT_ADT</code> macro:</p>
<div class="fragment"><div class="line"><span class="keyword">namespace </span>also_not_my_namespace {</div><div class="line"> <span class="keyword">struct </span>Person {</div><div class="line"> std::string get_name();</div><div class="line"> <span class="keywordtype">int</span> get_age();</div><div class="line"> };</div><div class="line">}</div><div class="line"></div><div class="line">BOOST_HANA_ADAPT_ADT(also_not_my_namespace::Person,</div><div class="line"> (name, [](<span class="keyword">auto</span> <span class="keyword">const</span>& p) { <span class="keywordflow">return</span> p.get_name(); }),</div><div class="line"> (age, [](<span class="keyword">auto</span> <span class="keyword">const</span>& p) { <span class="keywordflow">return</span> p.get_age(); })</div><div class="line">);</div></div><!-- fragment --><p> This way, the names used to access the members of the <code>Struct</code> will be those specified, and the associated function will be called on the <code>Struct</code> when retrieving that member. Before we move on to a concrete example of using these introspection features, it should also be mentioned that <code>struct</code>s can be adapted without using macros. This advanced interface for defining <code>Struct</code>s can be used for example to specify keys that are not compile-time strings. The advanced interface is described in the documentation of the <code>Struct</code> concept.</p>
<h2><a class="anchor" id="tutorial-introspection-json"></a>
Example: generating JSON</h2>
<p>Let's now move on with a concrete example of using the introspection capabilities we just presented for printing custom objects as JSON. Our end goal is to have something like this:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Car {</div><div class="line"> BOOST_HANA_DEFINE_STRUCT(Car,</div><div class="line"> (std::string, brand),</div><div class="line"> (std::string, model)</div><div class="line"> );</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">struct </span>Person {</div><div class="line"> BOOST_HANA_DEFINE_STRUCT(Person,</div><div class="line"> (std::string, name),</div><div class="line"> (std::string, last_name),</div><div class="line"> (<span class="keywordtype">int</span>, age)</div><div class="line"> );</div><div class="line">};</div><div class="line"></div><div class="line">Car bmw{<span class="stringliteral">"BMW"</span>, <span class="stringliteral">"Z3"</span>}, audi{<span class="stringliteral">"Audi"</span>, <span class="stringliteral">"A4"</span>};</div><div class="line">Person john{<span class="stringliteral">"John"</span>, <span class="stringliteral">"Doe"</span>, 30};</div><div class="line"></div><div class="line"><span class="keyword">auto</span> tuple = hana::make_tuple(john, audi, bmw);</div><div class="line">std::cout << to_json(tuple) << std::endl;</div></div><!-- fragment --><p> And the output, after passing it through a JSON pretty-printer, should look like</p>
<div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> [</div><div class="line"><a name="l00002"></a><span class="lineno"> 2</span>  {</div><div class="line"><a name="l00003"></a><span class="lineno"> 3</span>  "name": "John",</div><div class="line"><a name="l00004"></a><span class="lineno"> 4</span>  "last_name": "Doe",</div><div class="line"><a name="l00005"></a><span class="lineno"> 5</span>  "age": 30</div><div class="line"><a name="l00006"></a><span class="lineno"> 6</span>  },</div><div class="line"><a name="l00007"></a><span class="lineno"> 7</span>  {</div><div class="line"><a name="l00008"></a><span class="lineno"> 8</span>  "brand": "Audi",</div><div class="line"><a name="l00009"></a><span class="lineno"> 9</span>  "model": "A4"</div><div class="line"><a name="l00010"></a><span class="lineno"> 10</span>  },</div><div class="line"><a name="l00011"></a><span class="lineno"> 11</span>  {</div><div class="line"><a name="l00012"></a><span class="lineno"> 12</span>  "brand": "BMW",</div><div class="line"><a name="l00013"></a><span class="lineno"> 13</span>  "model": "Z3"</div><div class="line"><a name="l00014"></a><span class="lineno"> 14</span>  }</div><div class="line"><a name="l00015"></a><span class="lineno"> 15</span> ]</div></div><!-- fragment --><p>First, let's define a couple of utility functions to make string manipulation easier:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Xs></div><div class="line">std::string join(Xs&& xs, std::string sep) {</div><div class="line"> <span class="keywordflow">return</span> <a class="code" href="group__group-Foldable.html#gaa0fde17f3b947a0678a1c0c01232f2cc">hana::fold</a>(<a class="code" href="group__group-Sequence.html#gaa18061cd0f63cfaae89abf43ff92b79e">hana::intersperse</a>(std::forward<Xs>(xs), sep), <span class="stringliteral">""</span>, <a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">hana::_</a> + <a class="code" href="group__group-functional.html#gaefe9fd152cba94be71c2b5b9de689d23">hana::_</a>);</div><div class="line">}</div><div class="line"></div><div class="line">std::string quote(std::string s) { <span class="keywordflow">return</span> <span class="stringliteral">"\""</span> + s + <span class="stringliteral">"\""</span>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">auto</span> to_json(T <span class="keyword">const</span>& x) -> decltype(std::to_string(x)) {</div><div class="line"> <span class="keywordflow">return</span> std::to_string(x);</div><div class="line">}</div><div class="line"></div><div class="line">std::string to_json(<span class="keywordtype">char</span> c) { <span class="keywordflow">return</span> quote({c}); }</div><div class="line">std::string to_json(std::string s) { <span class="keywordflow">return</span> quote(s); }</div></div><!-- fragment --><p> The <code>quote</code> and the <code>to_json</code> overloads are pretty self-explanatory. The <code>join</code> function, however, might need a bit of explanation. Basically, the <code>intersperse</code> function takes a sequence and a separator, and returns a new sequence with the separator in between each pair of elements of the original sequence. In other words, we take a sequence of the form <code>[x1, ..., xn]</code> and turn it into a sequence of the form <code>[x1, sep, x2, sep, ..., sep, xn]</code>. Finally, we fold the resulting sequence with the <code>_ + _</code> function object, which is equivalent to <code>std::plus<>{}</code>. Since our sequence contains <code>std::string</code>s (we assume it does), this has the effect of concatenating all the strings of the sequence into one big string. Now, let's define how to print a <code>Sequence</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Xs></div><div class="line"> <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">std::enable_if_t<hana::Sequence<Xs>::value</a>,</div><div class="line">std::string> to_json(Xs <span class="keyword">const</span>& xs) {</div><div class="line"> <span class="keyword">auto</span> json = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(xs, [](<span class="keyword">auto</span> <span class="keyword">const</span>& x) {</div><div class="line"> <span class="keywordflow">return</span> to_json(x);</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> <span class="stringliteral">"["</span> + join(std::move(json), <span class="stringliteral">", "</span>) + <span class="stringliteral">"]"</span>;</div><div class="line">}</div></div><!-- fragment --><p> First, we use the <code>transform</code> algorithm to turn our sequence of objects into a sequence of <code>std::string</code>s in JSON format. Then, we join that sequence with commas and we enclose it with <code>[]</code> to denote a sequence in JSON notation. Simple enough? Let's now take a look at how to print user-defined types:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"> <a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">std::enable_if_t<hana::Struct<T>::value</a>,</div><div class="line">std::string> to_json(T <span class="keyword">const</span>& x) {</div><div class="line"> <span class="keyword">auto</span> json = <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(<a class="code" href="group__group-Struct.html#gaf8c7199742581e6e66c8397def68e2d3">hana::keys</a>(x), [&](<span class="keyword">auto</span> name) {</div><div class="line"> <span class="keyword">auto</span> <span class="keyword">const</span>& member = <a class="code" href="group__group-Searchable.html#ga3c1826aee6c6eb577810bb99c5c3e53d">hana::at_key</a>(x, name);</div><div class="line"> <span class="keywordflow">return</span> quote(hana::to<char const*>(name)) + <span class="stringliteral">" : "</span> + to_json(member);</div><div class="line"> });</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> <span class="stringliteral">"{"</span> + join(std::move(json), <span class="stringliteral">", "</span>) + <span class="stringliteral">"}"</span>;</div><div class="line">}</div></div><!-- fragment --><p> Here, we use the <code>keys</code> method to retrieve a <code>tuple</code> containing the names of the members of the user-defined type. Then, we <code>transform</code> that sequence into a sequence of <code>"name" : member</code> strings, which we then <code>join</code> and enclose with <code>{}</code>, which is used to denote objects in JSON notation. And that's it!</p>
<h1><a class="anchor" id="tutorial-containers"></a>
Generalities on containers</h1>
<hr/>
<p> This section explains several important notions about Hana's containers: how to create them, the lifetime of their elements and other concerns.</p>
<h2><a class="anchor" id="tutorial-containers-creating"></a>
Container creation</h2>
<p>While the usual way of creating an object in C++ is to use its constructor, heterogeneous programming makes things a bit more complicated. Indeed, in most cases, one is not interested in (or even aware of) the actual type of the heterogeneous container to be created. At other times, one could write out that type explicitly, but it would be redundant or cumbersome to do so. For this reason, Hana uses a different approach borrowed from <code>std::make_tuple</code> to create new containers. Much like one can create a <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> with <code>std::make_tuple</code>, a <code>hana::tuple</code> can be created with <code>hana::make_tuple</code>. However, more generally, containers in Hana may be created with the <code>make</code> function:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make<hana::tuple_tag>(1, 2.2, <span class="charliteral">'a'</span>, <span class="stringliteral">"bcde"</span>s);</div></div><!-- fragment --><p> In fact, <code>make_tuple</code> is just a shortcut for <code>make<tuple_tag></code> so you don't have to type <code><a class="el" href="group__group-core.html#ga1d92480f0af1029878e773dafa3e2f60" title="Create an object of the given tag with the given arguments. ">boost::hana::make</a><<a class="el" href="structboost_1_1hana_1_1tuple__tag.html" title="Tag representing hana::tuples. ">boost::hana::tuple_tag</a>></code> when you are out of Hana's namespace. Simply put, <code>make<...></code> is is used all around the library to create different types of objects, thus generalizing the <code>std::make_xxx</code> family of functions. For example, one can create a <code>hana::range</code> of compile-time integers with <code>make<range_tag></code>:</p>
<div class="fragment"><div class="line">constexpr <span class="keyword">auto</span> r = hana::make<hana::range_tag>(hana::int_c<3>, hana::int_c<10>);</div><div class="line">static_assert(r == hana::make_range(hana::int_c<3>, hana::int_c<10>), <span class="stringliteral">""</span>);</div></div><!-- fragment --> <blockquote class="doxtable">
<p>These types with a trailing <code>_tag</code> are dummy types <b>representing</b> a family of heterogeneous containers (<code>hana::tuple</code>, <code>hana::map</code>, etc..). Tags are documented in the section on <a class="el" href="index.html#tutorial-core-tags">Hana's core</a>. </p>
</blockquote>
<p>For convenience, whenever a component of Hana provides a <code>make<xxx_tag></code> function, it also provides the <code>make_xxx</code> shortcut to reduce typing. Also, an interesting point that can be raised in this example is the fact that <code>r</code> is <code>constexpr</code>. In general, whenever a container is initialized with constant expressions only (which is the case for <code>r</code>), that container may be marked as <code>constexpr</code>.</p>
<p>So far, we have only created containers with the <code>make_xxx</code> family of functions. However, some containers do provide constructors as part of their interface. For example, one can create a <code>hana::tuple</code> just like one would create a <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>:</p>
<div class="fragment"><div class="line">hana::tuple<int, double, char, std::string> xs{1, 2.2, <span class="charliteral">'a'</span>, <span class="stringliteral">"bcde"</span>s};</div></div><!-- fragment --><p> When constructors (or any member function really) are part of the public interface, they will be documented on a per-container basis. However, in the general case, one should not take for granted that a container can be constructed as the tuple was constructed above. For example, trying to create a <code>hana::range</code> that way will <b>not</b> work:</p>
<div class="fragment"><div class="line">hana::range<???> xs{hana::int_c<3>, hana::int_c<10>};</div></div><!-- fragment --><p>In fact, we can't even specify the type of the object we'd like to create in that case, because the exact type of a <code>hana::range</code> is implementation-defined, which brings us to the next section.</p>
<h2><a class="anchor" id="tutorial-containers-types"></a>
Container types</h2>
<p>The goal of this section is to clarify what can be expected from the types of Hana's containers. Indeed, so far, we always let the compiler deduce the actual type of containers by using the <code>make_xxx</code> family of functions along with <code>auto</code>. But in general, what can we say about the type of a container?</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(1, <span class="charliteral">'2'</span>, <span class="stringliteral">"345"</span>);</div><div class="line"><span class="keyword">auto</span> ints = hana::make_range(hana::int_c<0>, hana::int_c<100>);</div><div class="line"><span class="comment">// what can we say about the types of `xs` and `ints`?</span></div></div><!-- fragment --><p> The answer is that it depends. Some containers have well defined types, while others do not specify their representation. In this example, the type of the object returned by <code>make_tuple</code> is well-defined, while the type returned by <code>make_range</code> is implementation-defined:</p>
<div class="fragment"><div class="line">hana::tuple<int, char, char const*> xs = hana::make_tuple(1, <span class="charliteral">'2'</span>, <span class="stringliteral">"345"</span>);</div><div class="line"><span class="keyword">auto</span> ints = hana::make_range(hana::int_c<0>, hana::int_c<100>);</div><div class="line"><span class="comment">// can't specify the type of ints, however</span></div></div><!-- fragment --><p> This is documented on a per-container basis; when a container has an implementation-defined representation, a note explaining exactly what can be expected from that representation is included in the container's description. There are several reasons for leaving the representation of a container unspecified; they are explained in the <a class="el" href="index.html#tutorial-rationales-container_representation">rationales</a>. When the representation of a container is implementation-defined, one must be careful not to make any assumptions about it, unless those assumption are explicitly allowed in the documentation of the container.</p>
<h3><a class="anchor" id="tutorial-containers-types-overloading"></a>
Overloading on container types</h3>
<p>While necessary, leaving the type of some containers unspecified makes some things very difficult to achieve, like overloading functions on heterogeneous containers:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keywordtype">void</span> f(std::vector<T> xs) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...???></div><div class="line"><span class="keywordtype">void</span> f(unspecified-range-type<???> r) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">}</div></div><!-- fragment --><p>The <code>is_a</code> utility is provided for this reason (and others). <code>is_a</code> allows checking whether a type is a precise kind of container using its tag, regardless of the actual type of the container. For example, the above example could be rewritten as</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keywordtype">void</span> f(std::vector<T> xs) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> R, <span class="keyword">typename</span> = std::enable_if_t<hana::is_a<hana::range_tag, R>()>></div><div class="line"><span class="keywordtype">void</span> f(R r) {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">}</div></div><!-- fragment --><p> This way, the second overload of <code>f</code> will only match when <code>R</code> is a type whose tag is <code>range_tag</code>, regardless of the exact representation of that range. Of course, <code>is_a</code> can be used with any kind of container: <code>tuple</code>, <code>map</code>, <code>set</code> and so on.</p>
<h2><a class="anchor" id="tutorial-containers-elements"></a>
Container elements</h2>
<p>In Hana, containers own their elements. When a container is created, it makes a <em>copy</em> of the elements used to initialize it and stores them inside the container. Of course, unnecessary copies are avoided by using move semantics. Because of those owning semantics, the lifetime of the objects inside the container is the same as that of the container.</p>
<div class="fragment"><div class="line">std::string hello = <span class="stringliteral">"Hello"</span>;</div><div class="line">std::vector<char> world = {<span class="charliteral">'W'</span>, <span class="charliteral">'o'</span>, <span class="charliteral">'r'</span>, <span class="charliteral">'l'</span>, <span class="charliteral">'d'</span>};</div><div class="line"></div><div class="line"><span class="comment">// hello is copied, world is moved-in</span></div><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(hello, std::move(world));</div><div class="line"></div><div class="line"><span class="comment">// s is a reference to the copy of hello inside xs.</span></div><div class="line"><span class="comment">// It becomes a dangling reference as soon as xs is destroyed.</span></div><div class="line">std::string& s = xs[0_c];</div></div><!-- fragment --><p> Much like containers in the standard library, containers in Hana expect their elements to be objects. For this reason, references <em>may not</em> be stored in them. When references must be stored inside a container, one should use a <code>std::reference_wrapper</code> instead:</p>
<div class="fragment"><div class="line">std::vector<int> ints = { <span class="comment">/* huge vector of ints */</span> };</div><div class="line">std::vector<std::string> strings = { <span class="comment">/* huge vector of strings */</span> };</div><div class="line"></div><div class="line"><span class="keyword">auto</span> map = hana::make_map(</div><div class="line"> hana::make_pair(hana::type_c<int>, std::ref(ints)),</div><div class="line"> hana::make_pair(hana::type_c<std::string>, std::ref(strings))</div><div class="line">);</div><div class="line"></div><div class="line"><span class="keyword">auto</span>& v = map[hana::type_c<int>].get();</div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(&v == &ints);</div></div><!-- fragment --><h1><a class="anchor" id="tutorial-algorithms"></a>
Generalities on algorithms</h1>
<hr/>
<p> Much like the previous section introduced general but important notions about heterogeneous containers, this section introduces general notions about heterogeneous algorithms.</p>
<h2><a class="anchor" id="tutorial-algorithms-value"></a>
By-value semantics</h2>
<p>Algorithms in Hana always return a new container holding the result. This allows one to easily chain algorithms by simply using the result of the first as the input of the second. For example, to apply a function to every element of a tuple and then reverse the result, one simply has to connect the <code>reverse</code> and <code>transform</code> algorithms:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> to_str = [](<span class="keyword">auto</span> <span class="keyword">const</span>& x) {</div><div class="line"> std::stringstream ss;</div><div class="line"> ss << x;</div><div class="line"> <span class="keywordflow">return</span> ss.str();</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(1, 2.2, <span class="charliteral">'a'</span>, <span class="stringliteral">"bcde"</span>);</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(</div><div class="line"> <a class="code" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">hana::reverse</a>(<a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(xs, to_str)) == hana::make_tuple(<span class="stringliteral">"bcde"</span>, <span class="stringliteral">"a"</span>, <span class="stringliteral">"2.2"</span>, <span class="stringliteral">"1"</span>)</div><div class="line">);</div></div><!-- fragment --><p> This is different from the algorithms of the standard library, where one has to provide iterators to the underlying sequence. For reasons documented in the <a class="el" href="index.html#tutorial-rationales-iterators">rationales</a>, an iterator-based design was considered but was quickly dismissed in favor of composable and efficient abstractions better suited to the very particular context of heterogeneous programming.</p>
<p>One might also think that returning full sequences that own their elements from an algorithm would lead to tons of undesirable copies. For example, when using <code>reverse</code> and <code>transform</code>, one could think that an intermediate copy is made after the call to <code>transform</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">hana::reverse</a>(</div><div class="line"> <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(xs, to_str) <span class="comment">// <-- copy into reverse(...) here?</span></div><div class="line">);</div></div><!-- fragment --><p> To make sure this does not happen, Hana uses perfect forwarding and move semantics heavily so it can provide an almost optimal runtime performance. So instead of doing a copy, a move occurs between <code>reverse</code> and <code>transform</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">hana::reverse</a>(</div><div class="line"> <a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(xs, to_str) <span class="comment">// <-- nope, move from the temporary instead!</span></div><div class="line">);</div></div><!-- fragment --><p> Ultimately, the goal is that code written using Hana should be equivalent to clever hand-written code, except it should be enjoyable to write. Performance considerations are explained in depth in their own <a class="el" href="index.html#tutorial-performance">section</a>.</p>
<h2><a class="anchor" id="tutorial-algorithms-laziness"></a>
(Non-)Laziness</h2>
<p>Algorithms in Hana are not lazy. When an algorithm is called, it does its job and returns a new sequence containing the result, end of the story. For example, calling the <code>permutations</code> algorithm on a large sequence is a stupid idea, because Hana will actually compute all the permutations:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> perms = <a class="code" href="group__group-Sequence.html#gac1e182ac088f1990edd739424d30ea07">hana::permutations</a>(hana::make_tuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));</div><div class="line"><span class="comment">// perms has 3 628 800 elements, and your compiler just crashed</span></div></div><!-- fragment --><p>To contrast, algorithms in Boost.Fusion return views which hold the original sequence by reference and apply the algorithm on demand, as the elements of the sequence are accessed. This leads to subtle lifetime issues, like having a view that refers to a sequence that was destroyed. Hana's design assumes that most of the time, we want to access all or almost all the elements in a sequence anyway, and hence performance is not a big argument in favor of laziness.</p>
<h2><a class="anchor" id="tutorial-algorithms-codegen"></a>
What is generated?</h2>
<p>Algorithms in Hana are a bit special with respect to the runtime code they are expanded into. The goal of this subsection is not to explain exactly what code is generated, which depends on the compiler anyway, but to give a feel for things. Basically, a Hana algorithm is like an unrolled version of an equivalent classical algorithm. Indeed, since the bounds of the processed sequence are known at compile-time, it makes sense that we can unroll the loop over the sequence. For example, let's consider the <code>for_each</code> algorithm:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(0, 1, 2, 3);</div><div class="line"><a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(xs, f);</div></div><!-- fragment --><p>If <code>xs</code> was a runtime sequence instead of a tuple, its length would only be known at runtime and the above code would have to be implemented as a loop:</p>
<div class="fragment"><div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i < xs.size(); ++i) {</div><div class="line"> f(xs[i]);</div><div class="line">}</div></div><!-- fragment --><p>However, in our case, the length of the sequence is known at compile-time and so we don't have to check the index at each iteration. Hence, we can just write:</p>
<div class="fragment"><div class="line">f(xs[0_c]);</div><div class="line">f(xs[1_c]);</div><div class="line">f(xs[2_c]);</div><div class="line">f(xs[3_c]);</div></div><!-- fragment --><p>The main difference here is that no bound checking and index increment is done at each step, because there is no index anymore; the loop was effectively unrolled. In some cases, this can be desirable for performance reasons. In other cases, this can be detrimental to performance because it causes the code size to grow. As always, performance is a tricky subject and whether you actually want loop unrolling to happen should be tackled on a case-by-case basis. As a rule of thumb, algorithms processing all (or a subset) of the elements of a container are unrolled. In fact, if you think about it, this unrolling is the only way to go for heterogeneous sequences, because different elements of the sequence may have different types. As you might have noticed, we're not using normal indices into the tuple, but compile-time indices, which can't be generated by a normal <code>for</code> loop. In other words, the following does not make sense:</p>
<div class="fragment"><div class="line"><span class="keywordflow">for</span> (??? i = 0_c; i < xs.size(); ++i) {</div><div class="line"> f(xs[i]);</div><div class="line">}</div></div><!-- fragment --><h2><a class="anchor" id="tutorial-algorithms-effects"></a>
Side effects and purity</h2>
<p>By default, Hana assumes functions to be pure. A pure function is a function that has no side-effects at all. In other words, it is a function whose effect on the program is solely determined by its return value. In particular, such a function may not access any state that outlives a single invocation of the function. These functions have very nice properties, like the ability to reason mathematically about them, to reorder or even eliminate calls, and so on. Except where specified otherwise, all functions used with Hana (i.e. used in higher order algorithms) should be pure. In particular, functions passed to higher order algorithms are not guaranteed to be called any specific number of times. Furthermore, the order of execution is generally not specified and should therefore not be taken for granted. If this lack of guarantees about function invocations seems crazy, consider the following use of the <code>any_of</code> algorithm:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> r = <a class="code" href="group__group-Searchable.html#ga5f7ff0125c448983e1b96c3ffb84f646">hana::any_of</a>(hana::make_tuple(<span class="stringliteral">"hello"</span>s, 1.2, 3), [](<span class="keyword">auto</span> x) {</div><div class="line"> <span class="keywordflow">return</span> std::is_integral<decltype(x)>{};</div><div class="line">});</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(r);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>For this to work, the external adapters for <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code> contained in <code><<a class="el" href="ext_2std_2integral__constant_8hpp.html" title="Adapts std::integral_constant for use with Hana. ">boost/hana/ext/std/integral_constant.hpp</a>></code> must be included.</dd></dl>
<p>According to the previous section on unrolling, this algorithm should be expanded into something like:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(<span class="stringliteral">"hello"</span>s, 1.2, 3);</div><div class="line"><span class="keyword">auto</span> pred = [](<span class="keyword">auto</span> x) { <span class="keywordflow">return</span> std::is_integral<decltype(x)>{}; };</div><div class="line"></div><div class="line"><span class="keyword">auto</span> r = hana::bool_c<</div><div class="line"> pred(xs[0_c]) ? <span class="keyword">true</span> :</div><div class="line"> pred(xs[1_c]) ? <span class="keyword">true</span> :</div><div class="line"> pred(xs[2_c]) ? <span class="keyword">true</span> :</div><div class="line"> <span class="keyword">false</span></div><div class="line">>;</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(r);</div></div><!-- fragment --><p>Of course, the above code can't work as-is, because we're calling <code>pred</code> inside something that would have to be a constant expression, but <code>pred</code> is a lambda (and lambdas can't be called in constant expressions). However, whether any of these objects has an integral type is clearly known at compile-time, and hence we would expect that computing the answer only involves compile-time computations. In fact, this is exactly what Hana does, and the above algorithm is expanded into something like:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(<span class="stringliteral">"hello"</span>s, 1.2, 3);</div><div class="line"><span class="keyword">auto</span> pred = [](<span class="keyword">auto</span> x) { <span class="keywordflow">return</span> std::is_integral<decltype(x)>{}; };</div><div class="line"></div><div class="line"><span class="keyword">auto</span> r = hana::bool_c<</div><div class="line"> decltype(pred(xs[0_c]))::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a> ? true :</div><div class="line"> decltype(pred(xs[1_c]))::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a> ? true :</div><div class="line"> decltype(pred(xs[2_c]))::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a> ? true :</div><div class="line"> false</div><div class="line">>;</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(r);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>As you will be able to deduce from the next section on cross-phase computations, the implementation of <code>any_of</code> must actually be more general than this. However, this <a href="path_to_url">lie-to-children</a> is perfect for educational purposes.</dd></dl>
<p>As you can see, the predicate is never even executed; only its result type on a particular object is used. Regarding the order of evaluation, consider the <code>transform</code> algorithm, which is specified (for tuples) as:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Functor.html#ga5a8975f6e55375d5b6038a9c36ee63e7">hana::transform</a>(hana::make_tuple(x1, ..., xn), f) == hana::make_tuple(f(x1), ..., f(xn))</div></div><!-- fragment --><p>Since <code>make_tuple</code> is a function, and since the evaluation order for the arguments of a function is unspecified, the order in which <code>f</code> is called on each element of the tuple is unspecified too. If one sticks to pure functions, everything works fine and the resulting code is often easier to understand. However, some exceptional algorithms like <code>for_each</code> do expect impure functions, and they guarantee an order of evaluation. Indeed, a <code>for_each</code> algorithm that would only take pure functions would be pretty much useless. When an algorithm can accept an impure function or guarantees some order of evaluation, the documentation for that algorithm will mention it explicitly. However, by default, no guarantees may be taken for granted.</p>
<h2><a class="anchor" id="tutorial-algorithms-cross_phase"></a>
Cross-phase algorithms</h2>
<p>This section introduces the notion of cross-phase computations and algorithms. In fact, we have already used cross-phase algorithms in the <a class="el" href="index.html#tutorial-quickstart">quick start</a>, for example with <code>filter</code>, but we did not explain exactly what was happening at that time. But before we introduce cross-phase algorithms, let's define what we mean by <em>cross-phase</em>. The phases we're referring to here are the compilation and the execution of a program. In C++ as in most statically typed languages, there is a clear distinction between compile-time and runtime; this is called phase distinction. When we speak of a cross-phase computation, we mean a computation that is somehow performed across those phases; i.e. that is partly executed at compile-time and partly executed at runtime.</p>
<p>Like we saw in earlier examples, some functions are able to return something that can be used at compile-time even when they are called on a runtime value. For example, let's consider the <code>length</code> function applied to a non-<code>constexpr</code> container:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Fish { std::string name; };</div><div class="line"><span class="keyword">struct </span>Cat { std::string name; };</div><div class="line"><span class="keyword">struct </span>Dog { std::string name; };</div><div class="line"></div><div class="line"><span class="keyword">auto</span> animals = hana::make_tuple(Fish{<span class="stringliteral">"Nemo"</span>}, Cat{<span class="stringliteral">"Garfield"</span>}, Dog{<span class="stringliteral">"Snoopy"</span>});</div><div class="line"><span class="comment">// ^^^^^^^ not a compile-time value</span></div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(<a class="code" href="group__group-Foldable.html#gaf0f8f717245620dc28cd7d7fa44d7475">hana::length</a>(animals) == hana::size_c<3>);</div><div class="line"><span class="comment">// ^^^^^^^^^^^^^^^^^^^^^ assertion done at compile-time</span></div></div><!-- fragment --><p> Obviously, the tuple can't be made <code>constexpr</code>, since it contains runtime <code>std::string</code>s. Still, even though it is not called on a constant expression, <code>length</code> returns something that can be used at compile-time. If you think of it, the size of the tuple is known at compile-time regardless of its content, and hence it would only make sense for this information to be available to us at compile-time. If that seems surprising, think about <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> and <code>std::tuple_size</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="structstd_1_1tuple.html">std::tuple<int, char, std::string></a> xs{1, <span class="charliteral">'2'</span>, std::string{<span class="stringliteral">"345"</span>}};</div><div class="line">static_assert(std::tuple_size<decltype(xs)>::<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">value</a> == 3u, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> Since the size of the tuple is encoded in its type, it is always available at compile-time regardless of whether the tuple is <code>constexpr</code> or not. In Hana, this is implemented by having <code>length</code> return an <code>IntegralConstant</code>. Since an <code>IntegralConstant</code>'s value is encoded in its type, the result of <code>length</code> is contained in the type of the object it returns, and the length is therefore known at compile-time. Because <code>length</code> goes from a runtime value (the container) to a compile-time value (the <code>IntegralConstant</code>), <code>length</code> is a trivial example of a cross-phase algorithm (trivial because it does not really manipulate the tuple). Another algorithm that is very similar to <code>length</code> is the <code>is_empty</code> algorithm, which returns whether a container is empty:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(!<a class="code" href="group__group-Iterable.html#ga2a05f564f8a7e4afa04fcbc07ad8f394">hana::is_empty</a>(animals));</div><div class="line"><span class="comment">// ^^^^^^^^^^^^^^^^^^^^^^^ assertion done at compile-time</span></div></div><!-- fragment --><p> More generally, any algorithm that takes a container whose value is known at runtime but queries something that can be known at compile-time should be able to return an <code>IntegralConstant</code> or another similar compile-time value. Let's make things slightly more complicated by considering the <code>any_of</code> algorithm, which we already encountered in the previous section:</p>
<div class="fragment"><div class="line"><span class="keywordtype">bool</span> any_garfield = <a class="code" href="group__group-Searchable.html#ga5f7ff0125c448983e1b96c3ffb84f646">hana::any_of</a>(animals, [](<span class="keyword">auto</span> animal) {</div><div class="line"> <span class="keywordflow">return</span> animal.name == <span class="stringliteral">"Garfield"</span>s;</div><div class="line">});</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga29b2b21ffa5513e5b706c50ffee980af">BOOST_HANA_RUNTIME_CHECK</a>(any_garfield);</div></div><!-- fragment --><p> In this example, the result can't be known at compile-time, because the predicate returns a <code>bool</code> that is the result of comparing two <code>std::string</code>s. Since <code>std::string</code>s can't be compared at compile-time, the predicate must operate at runtime, and the overall result of the algorithm can then only be known at runtime too. However, let's say we used <code>any_of</code> with the following predicate instead:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> any_cat = <a class="code" href="group__group-Searchable.html#ga5f7ff0125c448983e1b96c3ffb84f646">hana::any_of</a>(animals, [](<span class="keyword">auto</span> x) {</div><div class="line"> <span class="keywordflow">return</span> std::is_same<decltype(x), Cat>{};</div><div class="line">});</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(any_cat);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>For this to work, the external adapters for <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code> contained in <code><<a class="el" href="ext_2std_2integral__constant_8hpp.html" title="Adapts std::integral_constant for use with Hana. ">boost/hana/ext/std/integral_constant.hpp</a>></code> must be included.</dd></dl>
<p>First, since the predicate is only querying information about the type of each element of the tuple, it is clear that its result can be known at compile-time. Since the number of elements in the tuple is also known at compile-time, the overall result of the algorithm can, in theory, be known at compile-time. More precisely, what happens is that the predicate returns a value initialized <code>std::is_same<...></code>, which inherits from <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a></code>. Hana recognizes these objects, and the algorithm is written in such a way that it preserves the <code>compile-time</code>ness of the predicate's result. In the end, <code>any_of</code> hence returns an <code>IntegralConstant</code> holding the result of the algorithm, and we use the compiler's type deduction in a clever way to make it look easy. Hence, it would be equivalent to write (but then you would need to already know the result of the algorithm!):</p>
<div class="fragment"><div class="line">hana::integral_constant<bool, true> any_cat = <a class="code" href="group__group-Searchable.html#ga5f7ff0125c448983e1b96c3ffb84f646">hana::any_of</a>(animals, [](<span class="keyword">auto</span> x) {</div><div class="line"> <span class="keywordflow">return</span> std::is_same<decltype(x), Cat>{};</div><div class="line">});</div><div class="line"></div><div class="line"><a class="code" href="group__group-assertions.html#ga4bf9e0c46c44e21fbe5c5fbb3ace8356">BOOST_HANA_CONSTANT_CHECK</a>(any_cat);</div></div><!-- fragment --><p> Ok, so some algorithms are able to return compile-time values when their input satisfies some constraints with respect to <code>compile-time</code>ness. However, other algorithms are more restrictive and they <em>require</em> their inputs to satisfy some constraints regarding <code>compile-time</code>ness, without which they are not able to operate at all. An example of this is <code>filter</code>, which takes a sequence and a predicate, and returns a new sequence containing only those elements for which the predicate is satisfied. <code>filter</code> requires the predicate to return an <code>IntegralConstant</code>. While this requirement may seem stringent, it really makes sense if you think about it. Indeed, since we're removing some elements from the heterogeneous sequence, the type of the resulting sequence depends on the result of the predicate. Hence, the result of the predicate has to be known at compile-time for the compiler to be able to assign a type to the returned sequence. For example, consider what happens when we try to filter a heterogeneous sequence as follows:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> animals = hana::make_tuple(Fish{<span class="stringliteral">"Nemo"</span>}, Cat{<span class="stringliteral">"Garfield"</span>}, Dog{<span class="stringliteral">"Snoopy"</span>});</div><div class="line"></div><div class="line"><span class="keyword">auto</span> no_garfield = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(animals, [](<span class="keyword">auto</span> animal) {</div><div class="line"> <span class="keywordflow">return</span> animal.name != <span class="stringliteral">"Garfield"</span>s;</div><div class="line">});</div></div><!-- fragment --><p>Clearly, we know that the predicate will only return false on the second element, and hence the result <em>should be</em> a <code>[Fish, Dog]</code> tuple. However, the compiler has no way of knowing this since the predicate's result is the result of a runtime computation, which happens way after the compiler has finished its job. Hence, the compiler does not have enough information to determine the return type of the algorithm. However, we could <code>filter</code> the same sequence with any predicate whose result is available at compile-time:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> mammals = <a class="code" href="group__group-MonadPlus.html#ga65cc6d9f522fb9e8e3b28d80ee5c822a">hana::filter</a>(animals, [](<span class="keyword">auto</span> animal) {</div><div class="line"> <span class="keywordflow">return</span> hana::type_c<decltype(animal)> != hana::type_c<Fish>;</div><div class="line">});</div></div><!-- fragment --><p> Since the predicate returns an <code>IntegralConstant</code>, we know which elements of the heterogeneous sequence we'll be keeping at compile-time. Hence, the compiler is able to figure out the return type of the algorithm. Other algorithms like <code>partition</code> and <code>sort</code> work similarly; special algorithm requirements are always documented, just read the reference documentation of an algorithm before using it to avoid surprises.</p>
<p>This is the end of the section on algorithms. While this constitutes a fairly complete explanation of phase interaction inside algorithms, a deeper understanding can be gained by reading the <a class="el" href="index.html#tutorial-appendix-constexpr">advanced section</a> on <code>constexpr</code> and the reference for <code>Constant</code> and <code>IntegralConstant</code>.</p>
<dl class="section warning"><dt>Warning</dt><dd>Hana's algorithms are <code>constexpr</code> function objects instead of being template functions. This allows passing them to higher-order algorithms, which is very useful. However, since those function objects are defined at namespace scope in the header files, this causes each translation unit to see a different algorithm object. Hence, the address of an algorithm function object is not guaranteed to be unique across translation units, which can cause an ODR violation if one relies on such an address. So, in short, do not rely on the uniqueness of the address of any global object provided by Hana, which does not make sense in the general case anyway because such objects are <code>constexpr</code>. See <a href="path_to_url">issue #76</a> for more information.</dd></dl>
<h1><a class="anchor" id="tutorial-performance"></a>
Performance considerations</h1>
<hr/>
<p> C++ programmers love performance, so here's a whole section dedicated to it. Since Hana lives on the frontier between runtime and compile-time computations, we are not only interested in runtime performance, but also compile-time performance. Since both topics are pretty much disjoint, we treat them separately below.</p>
<dl class="section note"><dt>Note</dt><dd>The benchmarks presented in this section are updated automatically when we push to the repository. If you notice results that do not withstand the claims made here, open a <a href="path_to_url">GitHub issue</a>; it could be a performance regression.</dd></dl>
<dl class="section warning"><dt>Warning</dt><dd>As of writing this, not all of Hana's containers are optimized. Implementing Hana was a big enough challenge that containers were initially written naively and are now in the process of being rigorously optimized. In particular, the associative containers (<code>hana::map</code> and <code>hana::set</code>) have a pretty bad compile-time behavior because of their naive implementation, and their runtime behavior also seems to be problematic in some cases. Improving this situation is in the TODO list.</dd></dl>
<h2><a class="anchor" id="tutorial-performance-compile"></a>
Compile-time performance</h2>
<p>C++ metaprogramming brings its share of awful things. One of the most annoying and well-known problem associated to it is interminable compilation times. Hana claims to be more compile-time efficient than its predecessors; this is a bold claim and we will now try to back it. Of course, Hana can't do miracles; metaprogramming is a byproduct of the C++ template system and the compiler is not meant to be used as an interpreter for some meta language. However, by using cutting edge and intensely benchmarked techniques, Hana is able to minimize the strain on the compiler.</p>
<dl class="section note"><dt>Note</dt><dd>While Hana has better compile-times than pre-C++11 metaprogramming libraries, modern libraries supporting only type-level computations (such as <a href="path_to_url">Brigand</a>) can provide better compile-times, at the cost of generality. Indeed, Hana's ability to manipulate runtime values comes at a compile-time cost, no matter how hard we try to mitigate it. If you want to use Hana for intensive type-level computations, you should benchmark and see whether it suits you.</dd></dl>
<p>Before we dive, let me make a quick note on the methodology used to measure compile-time performance in Hana. Previous metaprogramming libraries measured the compile-time complexity of their meta-algorithms and meta-sequences by looking at the number of instantiations the compiler had to perform. While easy to understand, this way of measuring the compile-time complexity actually does not give us a lot of information regarding the compilation time, which is what we're interested in minimizing at the end of the day. Basically, the reason for this is that template metaprogramming is such a twisted model of computation that it's very hard to find a standard way of measuring the performance of algorithms. Hence, instead of presenting meaningless complexity analyses, we prefer to benchmark everything on every supported compiler and to pick the best implementation on that compiler. Also note that the benchmarks we present here are quite precise. Indeed, even though we do not take multiple measurements and take their mean or something similar to reduce incertitude, the benchmarks are very stable when they are regenerated, which suggests a reasonably good precision. Now, let's dive.</p>
<p>First, Hana minimizes its dependency on the preprocessor. In addition to yielding cleaner error messages in many cases, this reduces the overall parsing and preprocessing time for header files. Also, because Hana only supports cutting edge compilers, there are very few workarounds in the library, which results in a cleaner and smaller library. Finally, Hana minimizes reliance on any kind of external dependencies. In particular, it only uses other Boost libraries in a few specific cases, and it does not rely on the standard library for the largest part. There are several reasons (other than include times) for doing so; they are documented in the <a class="el" href="index.html#tutorial-rationales-dependencies">rationales</a>.</p>
<p>Below is a chart showing the time required to include different libraries. The chart shows the time for including everything in the (non-external) public API of each library. For example, for Hana this means the <code><<a class="el" href="hana_8hpp.html" title="Includes all the library components except the adapters for external libraries. ">boost/hana.hpp</a>></code> header, which excludes the external adapters. For other libraries like Boost.Fusion, this means including all the public headers in the <code>boost/fusion/</code> directory, but not the adapters for external libraries like the MPL.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.including.compile.json"> </div><p>In addition to reduced preprocessing times, Hana uses modern techniques to implement heterogeneous sequences and algorithms in the most compile-time efficient way possible. Before jumping to the compile-time performance of the algorithms, we will have a look at the compile-time cost of creating heterogeneous sequences. Indeed, since we will be presenting algorithms that work on sequences, we must be aware of the cost of creating the sequences themselves, since that will influence the benchmarks for the algorithms. The following chart presents the compile-time cost of creating a sequence of <code>n</code> heterogeneous elements.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.make.compile.json"> </div><dl class="section note"><dt>Note</dt><dd>You can zoom on the chart by selecting an area to zoom into. Also, you can hide a series of points by clicking on it in the legend on the right.</dd></dl>
<p>The benchmark methodology is to always create the sequences in the most efficient way possible. For Hana and <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>, this simply means using the appropriate <code>make_tuple</code> function. However, for the MPL, this means creating a <code>mpl::vectorN</code> of size up to 20, and then using <code>mpl::push_back</code> to create larger vectors. We use a similar technique for Fusion sequences. The reason for doing so is that Fusion and MPL sequences have fixed size limits, and the techniques used here have been found to be the fastest way to create longer sequences.</p>
<p>For completeness, we also present the compile-time cost of creating a <code><a class="el" href="structstd_1_1array.html" title="Adaptation of std::array for Hana. ">std::array</a></code> with <code>n</code> elements. However, note that <code><a class="el" href="structstd_1_1array.html" title="Adaptation of std::array for Hana. ">std::array</a></code> can only hold elements with a single type, so we're comparing apples and oranges here. As you can see, the cost of creating a <code><a class="el" href="structstd_1_1array.html" title="Adaptation of std::array for Hana. ">std::array</a></code> is constant and essentially inexistent (the non-zero overhead is that of simply including the <code><array></code> header). Hence, while Hana provides improved compile-times over other heterogeneous containers, please stick with normal homogeneous containers if that's all you need for your application; your compile-times will be much faster that way.</p>
<p>You can also see that creating sequences has a non-negligible cost. Actually, this is really the most expensive part of doing heterogeneous computations, as you will see in the following charts. Hence, when you look at the charts below, keep in mind the cost of merely creating the sequences. Also note that only the most important algorithms will be presented here, but the <a href="path_to_url">Metabench</a> project provides micro benchmarks for compile-time performance for almost all of Hana's algorithms. Also, the benchmarks we present compare several different libraries. However, since Hana and Fusion can work with values and not only types, comparing their algorithms with type-only libraries like MPL is not really fair. Indeed, Hana and Fusion algorithms are more powerful since they also allow runtime effects to be performed. However, the comparison between Fusion and Hana is fair, because both libraries are just as powerful (strictly speaking). Finally, we can't show benchmarks of the algorithms for <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>, because the standard does not provide equivalent algorithms. Of course, we could use Hana's external adapters, but that would not be a faithful comparison.</p>
<p>The first algorithm which is ubiquitous in metaprogramming is <code>transform</code>. It takes a sequence and a function, and returns a new sequence containing the result of applying the function to each element. The following chart presents the compile-time performance of applying <code>transform</code> to a sequence of <code>n</code> elements. The <code>x</code> axis represents the number of elements in the sequence, and the <code>y</code> axis represents the compilation time in seconds. Also note that we're using the <code>transform</code> equivalent in each library; we're not using Hana's <code>transform</code> through the Boost.Fusion adapters, for example, because we really want to benchmark their implementation against ours.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.transform.compile.json"> </div><p>Here, we can see that Hana's tuple performs better than all the other alternatives. This is mainly due to the fact that we use C++11 variadic parameter pack expansion to implement this algorithm under the hood, which is quite efficient.</p>
<p>Before we move on, it is important to mention something regarding the benchmark methodology for Fusion algorithms. Some algorithms in Fusion are lazy, which means that they don't actually perform anything, but simply return a modified view to the original data. This is the case of <code>fusion::transform</code>, which simply returns a transformed view that applies the function to each element of the original sequence as those elements are accessed. If we want to benchmark anything at all, we need to force the evaluation of that view, as would eventually happen when accessing the elements of the sequence in real code. However, for complex computations with multiple layers, a lazy approach may yield a substantially different compile-time profile. Of course, this difference is poorly represented in micro benchmarks, so keep in mind that these benchmarks only give a part of the big picture. For completeness in the rest of the section, we will mention when a Fusion algorithm is lazy, so that you know when we're <em>artificially</em> forcing the evaluation of the algorithm for the purpose of benchmarking.</p>
<dl class="section note"><dt>Note</dt><dd>We are currently considering adding lazy views to Hana. If this feature is important to you, please let us know by commenting <a href="path_to_url">this issue</a>.</dd></dl>
<p>The second important class of algorithms are folds. Folds can be used to implement many other algorithms like <code>count_if</code>, <code>minimum</code> and so on. Hence, a good compile-time performance for fold algorithms ensures a good compile-time performance for those derived algorithms, which is why we're only presenting folds here. Also note that all the non-monadic fold variants are somewhat equivalent in terms of compile-time, so we only present the left folds. The following chart presents the compile-time performance of applying <code>fold_left</code> to a sequence of <code>n</code> elements. The <code>x</code> axis represents the number of elements in the sequence, and the <code>y</code> axis represents the compilation time in seconds. The function used for folding is a dummy function that does nothing. In real code, you would likely fold with a nontrivial operation, so the curves would be worse than that. However, these are micro benchmarks and hence they only show the performance of the algorithm itself.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.fold_left.compile.json"> </div><p>The third and last algorithm that we present here is the <code>find_if</code> algorithm. This algorithm is difficult to implement efficiently, because it requires stopping at the first element which satisfies the given predicate. For the same reason, modern techniques don't really help us here, so this algorithm constitutes a good test of the implementation quality of Hana, without taking into account the free lunch given to use by C++14.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.find_if.compile.json"> </div><p>As you can see, Hana performs better than Fusion, and as well as MPL, yet Hana's <code>find_if</code> can be used with values too, unlike MPL's. This concludes the section on compile-time performance. In case you want to see the performance of an algorithm that we have not presented here, the <a href="path_to_url">Metabench</a> project provides compile-time benchmarks for most of Hana's algorithms.</p>
<h2><a class="anchor" id="tutorial-performance-runtime"></a>
Runtime performance</h2>
<p>Hana was designed to be very efficient at runtime. But before we dive into the details, let's clarify one thing. Hana being a metaprogramming library which allows manipulating both types and values, it does not always make sense to even talk about runtime performance. Indeed, for type-level computations and computations on <code>IntegralConstant</code>s, runtime performance is simply not a concern, because the result of the computation is contained in a <em>type</em>, which is a purely compile-time entity. In other words, these computations involve only compile-time work, and no code is even generated to perform these computations at runtime. The only case where it makes sense to discuss runtime performance is when manipulating runtime values in heterogeneous containers and algorithms, because this is the only case where the compiler has to generate some runtime code. It is therefore only computations of this sort that we will be studying in the remainder of this section.</p>
<p>Like we did for compile-time benchmarks, the methodology used to measure runtime performance in Hana is data driven rather than analytical. In other words, instead of trying to determine the complexity of an algorithm by counting the number of basic operations it does as a function of the input size, we simply take measurements for the most interesting cases and see how it behaves. There are a couple of reasons for doing so. First, we do not expect Hana's algorithms to be called on large inputs since those algorithms work on heterogeneous sequences whose length must be known at compile-time. For example, if you tried to call the <code>find_if</code> algorithm on a sequence of 100k elements, your compiler would simply die while trying to generate the code for this algorithm. Hence, algorithms can't be called on very large inputs and the analytical approach then loses a lot of its attractiveness. Secondly, processors have evolved into pretty complex beasts, and the actual performance you'll be able to squeeze out is actually controlled by much more than the mere number of steps your algorithm is doing. For example, bad cache behavior or branch misprediction could turn a theoretically efficient algorithm into a slowpoke, especially for small inputs. Since Hana causes a lot of unrolling to happen, these factors must be considered even more carefully and any analytical approach would probably only comfort us into thinking we're efficient. Instead, we want hard data, and pretty charts to display it!</p>
<dl class="section note"><dt>Note</dt><dd>Like for compile-time performance, we're forcing the evaluation of some Fusion algorithms that are normally lazy. Again, depending on the complexity of the computation, a lazy algorithm may cause substantially different code to be generated or a different design to be used, for better or worse. Keep this in mind when you look at these runtime benchmarks. If performance is absolutely critical to your application, you should profile <em>before</em> and <em>after</em> switching from Fusion to Hana. And let us know if Hana performs worse; we'll fix it!</dd></dl>
<p>There are a couple of different aspects we will want to benchmark. First, we will obviously want to benchmark the execution time of the algorithms. Secondly, because of the by-value semantics used throughout the library, we will also want to make sure that the minimum amount of data is copied around. Finally, we will want to make sure that using Hana does not cause too much code bloat because of unrolling, as explained in the <a class="el" href="index.html#tutorial-algorithms-codegen">section</a> on algorithms.</p>
<p>Just like we studied only a couple of key algorithms for compile-time performance, we will focus on the runtime performance of a few algorithms. For each benchmarked aspect, we will compare the algorithm as implemented by different libraries. Our goal is to always be at least as efficient as Boost.Fusion, which is near from optimality in terms of runtime performance. For comparison, we also show the same algorithm as executed on a runtime sequence, and on a sequence whose length is known at compile-time but whose <code>transform</code> algorithm does not use explicit loop unrolling. All the benchmarks presented here are done in a <em>Release</em> CMake configuration, which takes care of passing the proper optimization flags (usually <code>-O3</code>). Let's start with the following chart, which shows the execution time required to <code>transform</code> different kinds of sequences:</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.transform.execute.json"> </div><dl class="section note"><dt>Note</dt><dd>Keep in mind that <code>fusion::transform</code> is usually lazy, and we're forcing its evaluation for the purpose of benchmarking.</dd></dl>
<p>As you can see, Hana and Fusion are pretty much on the same line. <code><a class="el" href="structstd_1_1array.html" title="Adaptation of std::array for Hana. ">std::array</a></code> is slightly slower for larger collections data sets, and <code>std::vector</code> is noticeably slower for larger collections. Since we also want to look out for code bloat, let's take a look at the size of the executable generated for the exact same scenario:</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.transform.bloat.json"> </div><p>As you can see, code bloat does not seem to be an issue, at least not one that can be detected in micro benchmarks such as this one. Let's now take a look at the <code>fold</code> algorithm, which is used very frequently:</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.fold_left.execute.json"> </div><p>Here, you can see that everybody is performing pretty much the same, which is a good sign that Hana is at least not screwing things up. Again, let's look at the executable size:</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.fold_left.bloat.json"> </div><p>Here again, the code size did not explode. So at least for moderate usages of Hana (and Fusion for that matter, since they have the same problem), code bloat should not be a major concern. The containers in the charts we just presented contain randomly generated <code>int</code>s, which is cheap to copy around and lends itself well to micro benchmarks. However, what happens when we chain multiple algorithms on a container whose elements are expensive to copy? More generally, the question is: when an algorithm is passed a temporary object, does it seize the opportunity to avoid unnecessary copies? Consider:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> xs = hana::make_tuple(<span class="stringliteral">"some"</span>s, <span class="stringliteral">"huge"</span>s, <span class="stringliteral">"string"</span>s);</div><div class="line"></div><div class="line"><span class="comment">// No copy of xs's elements should be made: they should only be moved around.</span></div><div class="line"><span class="keyword">auto</span> ys = <a class="code" href="group__group-Sequence.html#ga28037560e8f224c53cf6ac168d03a067">hana::reverse</a>(std::move(xs));</div></div><!-- fragment --><p>To answer this question, we'll look at the chart generated when benchmarking the above code for strings of about 1k characters. However, note that it does not really make sense to benchmark this for standard library algorithms, because they do not return containers.</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.reverse.move.json"> </div><dl class="section note"><dt>Note</dt><dd>Keep in mind that <code>fusion::reverse</code> is usually lazy, and we're forcing its evaluation for the purpose of benchmarking.</dd></dl>
<p>As you can see, Hana is faster than Fusion, probably because of a more consistent use of move semantics in the implementation. If we had not provided a temporary container to <code>reverse</code>, no move could have been performed by Hana and both libraries would have performed similarly:</p>
<div class="benchmark-chart" style="min-width: 310px; height: 400px; margin: 0 auto" data-dataset="benchmark.reverse.nomove.json"> </div><p>This concludes the section on runtime performance. Hopefully you are now convinced that Hana was built for speed. Performance is important to us: if you ever encounter a scenario where Hana causes bad code to be generated (and the fault is not on the compiler), please open an <a href="path_to_url">issue</a> so the problem can be addressed.</p>
<h1><a class="anchor" id="tutorial-ext"></a>
Integration with external libraries</h1>
<hr/>
<p>Hana provides out-of-the-box integration with some existing libraries. Specifically, this means that you can use some containers from these libraries in Hana's algorithms by simply including the appropriate header making the bridge between Hana and the external component. This can be very useful for porting existing code from e.g. Fusion/MPL to Hana:</p>
<div class="fragment"><div class="line"><span class="comment">// In the old code, this used to receive a Fusion sequence.</span></div><div class="line"><span class="comment">// Now, it can be either a Hana sequence or a Fusion sequence.</span></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Sequence></div><div class="line"><span class="keywordtype">void</span> f(Sequence <span class="keyword">const</span>& seq) {</div><div class="line"> <a class="code" href="group__group-Foldable.html#ga2af382f7e644ce3707710bbad313e9c2">hana::for_each</a>(seq, [](<span class="keyword">auto</span> <span class="keyword">const</span>& element) {</div><div class="line"> std::cout << element << std::endl;</div><div class="line"> });</div><div class="line">}</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>At this time, only adapters to use data types from other libraries inside Hana are provided; adapters for the other way around (using Hana containers inside other libraries) are not provided.</dd></dl>
<p>However, using external adapters has a couple of pitfalls. For example, after a while using Hana, you might become used to comparing Hana tuples using the normal comparison operators, or doing arithmetic with Hana <code>integral_constant</code>s. Of course, nothing guarantees that these operators are defined for external adapters too (and in general they won't be). Hence, you'll have to stick to the functions provided by Hana that implement these operators. For example:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> r = <a class="code" href="classstd_1_1ratio.html">std::ratio<3, 4></a>{} + <a class="code" href="classstd_1_1ratio.html">std::ratio<4, 5></a>{}; <span class="comment">// error, the operator is not defined!</span></div></div><!-- fragment --><p>Instead, you should use the following:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="ratio_8hpp.html">boost/hana/ext/std/ratio.hpp</a>></span></div><div class="line"><span class="preprocessor">#include <<a class="code" href="plus_8hpp.html">boost/hana/plus.hpp</a>></span></div><div class="line"></div><div class="line"><span class="preprocessor">#include <ratio></span></div><div class="line"><span class="keyword">namespace </span>hana = <a class="code" href="namespaceboost_1_1hana.html">boost::hana</a>;</div><div class="line"></div><div class="line"><span class="keyword">auto</span> r = <a class="code" href="group__group-Monoid.html#gaeb5d4a1e967e319712f9e4791948896c">hana::plus</a>(<a class="code" href="classstd_1_1ratio.html">std::ratio<3, 4></a>{}, <a class="code" href="classstd_1_1ratio.html">std::ratio<4, 5></a>{});</div></div><!-- fragment --><p> But sometimes, it's much worse. Some external components define operators, but they don't necessarily have the same semantics as those from Hana. For example, comparing two <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>s of different lengths will give an error when using <code>operator==</code>:</p>
<div class="fragment"><div class="line">std::make_tuple(1, 2, 3) == std::make_tuple(1, 2); <span class="comment">// compiler error</span></div></div><!-- fragment --><p>On the other hand, comparing Hana tuples of different lengths will just return a false <code>IntegralConstant</code>:</p>
<div class="fragment"><div class="line">hana::make_tuple(1, 2, 3) == hana::make_tuple(1, 2); <span class="comment">// hana::false_c</span></div></div><!-- fragment --><p>This is because <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> defines its own operators, and their semantics are different from that of Hana's operators. The solution is to stick with Hana's named functions instead of using operators when you know you'll have to work with other libraries:</p>
<div class="fragment"><div class="line"><a class="code" href="group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547">hana::equal</a>(std::make_tuple(1, 2, 3), std::make_tuple(1, 2)); <span class="comment">// hana::false_c</span></div></div><!-- fragment --><p>When using external adapters, one should also be careful not to forget including the proper bridge headers. For example, suppose I want to use a Boost.MPL vector with Hana. I include the appropriate bridge header:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="boost_2mpl_2vector_8hpp.html">boost/hana/ext/boost/mpl/vector.hpp</a>></span> <span class="comment">// bridge header</span></div><div class="line"></div><div class="line"><span class="keyword">using</span> Vector = mpl::vector<int, char, float>;</div><div class="line">static_assert(<a class="code" href="group__group-Iterable.html#ga8a67ea10e8082dbe6705e573fa978444">hana::front</a>(Vector{}) == hana::type_c<int>, <span class="stringliteral">""</span>);</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>The exact layout of these bridge headers is documented in the section about <a class="el" href="index.html#tutorial-header_organization">Header organization</a>.</dd></dl>
<p>Now, however, suppose that I use <code>mpl::size</code> to query the size of the vector and then compare it to some value. I could also use <code>hana::length</code> and everything would be fine, but bear with me for the sake of the example:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> Size = mpl::size<Vector>::type;</div><div class="line">static_assert(<a class="code" href="group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547">hana::equal</a>(Size{}, hana::int_c<3>), <span class="stringliteral">""</span>); <span class="comment">// breaks!</span></div></div><!-- fragment --><p> The reason why this breaks is that <code>mpl::size</code> returns a MPL IntegralConstant, and Hana has no way of knowing about these unless you include the proper bridge header. Hence, you should do the following instead:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="integral__c_8hpp.html">boost/hana/ext/boost/mpl/integral_c.hpp</a>></span></div><div class="line"></div><div class="line"><span class="keyword">using</span> Size = mpl::size<Vector>::type;</div><div class="line">static_assert(<a class="code" href="group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547">hana::equal</a>(Size{}, hana::int_c<3>), <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> The morale is that when working with external libraries, you have to be a bit careful about what objects you are manipulating. The final pitfall is about implementation limits in external libraries. Many older libraries have limits regarding the maximum size of the heterogeneous containers that can be created with them. For example, one may not create a Fusion list of more than <code>FUSION_MAX_LIST_SIZE</code> elements in it. Obviously, these limits are inherited by Hana and for example, trying to compute the permutations of a <code>fusion::list</code> containing 5 elements (the resulting list would contain 120 elements) will fail in a gruesome way:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> list = fusion::make_list(1, 2, 3, 4, 5);</div><div class="line"><span class="keyword">auto</span> oh_jeez = <a class="code" href="group__group-Sequence.html#gac1e182ac088f1990edd739424d30ea07">hana::permutations</a>(list); <span class="comment">// probably won't make it</span></div></div><!-- fragment --><p>Apart from the pitfalls explained in this section, using external adapters should be just as straightforward as using normal Hana containers. Of course, whenever possible, you should try to stick with Hana's containers because they are usually more friendly to work with and are often more optimized.</p>
<h1><a class="anchor" id="tutorial-core"></a>
Hana's core</h1>
<hr/>
<p> The goal of this section is to give a high-level overview of Hana's core. This core is based on the notion of <em>tag</em>, which is borrowed from the Boost.Fusion and Boost.MPL libraries but taken much further by Hana. These tags are then used for several purposes, like algorithm customization, documentation grouping, improving error messages and converting containers into other containers. Because of its modular design, Hana can be extended in a ad-hoc manner very easily. In fact, all the functionality of the library is provided through an ad-hoc customization mechanism, which is explained here.</p>
<h2><a class="anchor" id="tutorial-core-tags"></a>
Tags</h2>
<p>Heterogeneous programming is basically programming with objects having different types. However, it is clear that some families of objects, while having different representations (C++ types), are strongly related. For example, the <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a><int, n></code> types are different for each different <code>n</code>, but conceptually they all represent the same thing; a compile-time number. The fact that <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a><int, 1>{}</code> and <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a><int, 2>{}</code> have different types is just a side effect of the fact that we're using their type to encode the <em>value</em> of these objects. Indeed, when manipulating a sequence of <code><a class="el" href="structstd_1_1integral__constant.html" title="Adapter for std::integral_constants. ">std::integral_constant</a><int, ...></code>s, chances are that you actually think of it as a homogeneous sequence of an imaginary <code>integral_constant</code> type, disregarding the actual types of the objects and pretending they are all just <code>integral_constant</code>s with different values.</p>
<p>To reflect this reality, Hana provides <em>tags</em> representing its heterogeneous containers and other compile-time entities. For example, all of Hana's <code>integral_constant<int, ...></code>s have different types, but they all share the same tag, <code>integral_constant_tag<int></code>. This allows the programmer to think in terms of that single type instead of trying to think in terms of the actual types of the objects. Concretely, tags are implemented as empty <code>struct</code>s. To make them stand out, Hana adopts the convention of naming these tags by adding the <code>_tag</code> suffix.</p>
<dl class="section note"><dt>Note</dt><dd>The tag of an object of type <code>T</code> can be obtained by using <code>tag_of<T>::type</code>, or equivalently <code>tag_of_t<T></code>.</dd></dl>
<p>Tags are an extension to normal C++ types. Indeed, by default, the tag of a type <code>T</code> is <code>T</code> itself, and the core of the library is designed to work in those cases. For example, <code>hana::make</code> expects either a tag or an actual type; if you send it a type <code>T</code>, it will do the logical thing and construct an object of type <code>T</code> with the arguments you pass it. If you pass a tag to it, however, you should specialize <code>make</code> for that tag and provide your own implementation, as explained below. Because tags are an extension to usual types, we end up mostly reasoning in terms of tags instead of usual types, and the documentation sometimes uses the words <em>type</em>, <em>data type</em> and <em>tag</em> interchangeably.</p>
<h2><a class="anchor" id="tutorial-core-tag_dispatching"></a>
Tag dispatching</h2>
<p>Tag dispatching is a generic programming technique for picking the right implementation of a function depending on the type of the arguments passed to the function. The usual mechanism for overriding a function's behavior is overloading. Unfortunately, this mechanism is not always convenient when dealing with families of related types having different base templates, or when the kind of template parameters is not known (is it a type or a non-type template parameter?). For example, consider trying to overload a function for all Boost.Fusion vectors:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> ...T></div><div class="line"><span class="keywordtype">void</span> <span class="keyword">function</span>(<a class="code" href="structboost_1_1fusion_1_1vector.html">boost::fusion::vector</a><T...> v) {</div><div class="line"> <span class="comment">// whatever</span></div><div class="line">}</div></div><!-- fragment --><p>If you know Boost.Fusion, then you probably know that it won't work. This is because Boost.Fusion vectors are not necessarily specializations of the <code><a class="el" href="structboost_1_1fusion_1_1vector.html" title="Adapter for Boost.Fusion vectors. ">boost::fusion::vector</a></code> template. Fusion vectors also exist in numbered forms, which are all of different types:</p>
<div class="fragment"><div class="line">boost::fusion::vector1<T></div><div class="line">boost::fusion::vector2<T, U></div><div class="line">boost::fusion::vector3<T, U, V></div><div class="line">...</div></div><!-- fragment --><p>This is an implementation detail required by the lack of variadic templates in C++03 that leaks into the interface. This is unfortunate, but we need a way to work around it. To do so, we use an infrastructure with three distinct components:</p>
<ol type="1">
<li>A metafunction associating a single tag to every type in a family of related types. In Hana, this tag can be accessed using the <code>tag_of</code> metafunction. Specifically, for any type <code>T</code>, <code>tag_of<T>::type</code> is the tag used to dispatch it.</li>
<li>A function belonging to the public interface of the library, for which we'd like to be able to provide a customized implementation. In Hana, these functions are the algorithms associated to a concept, like <code>transform</code> or <code>unpack</code>.</li>
<li>An implementation for the function, parameterized with the tag(s) of the argument(s) passed to the function. In Hana, this is usually done by having a separate template called <code>xxx_impl</code> (for an interface function <code>xxx</code>) with a nested <code>apply</code> static function, as will be shown below.</li>
</ol>
<p>When the public interface function <code>xxx</code> is called, it will get the tag of the argument(s) it wishes to dispatch the call on, and then forward the call to the <code>xxx_impl</code> implementation associated to those tags. For example, let's implement a basic setup for tag dispatching of a function that prints its argument to a stream. First, we define the public interface function and the implementation that can be specialized:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Tag></div><div class="line"><span class="keyword">struct </span>print_impl {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> X></div><div class="line"> <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">apply</a>(std::ostream&, X <span class="keyword">const</span>&) {</div><div class="line"> <span class="comment">// possibly some default implementation</span></div><div class="line"> }</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> X></div><div class="line"><span class="keywordtype">void</span> <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>(std::ostream& os, X x) {</div><div class="line"> <span class="keyword">using</span> Tag = <span class="keyword">typename</span> hana::tag_of<X>::type;</div><div class="line"> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">print_impl<Tag>::apply</a>(os, x);</div><div class="line">}</div></div><!-- fragment --><p> Now, let's define a type that needs tag dispatching to customize the behavior of <code>print</code>. While some C++14 examples exist, they are too complicated to show in this tutorial and we will therefore use a C++03 tuple implemented as several different types to illustrate the technique:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>vector_tag;</div><div class="line"></div><div class="line"><span class="keyword">struct </span>vector0 {</div><div class="line"> <span class="keyword">using</span> hana_tag = vector_tag;</div><div class="line"> <span class="keyword">static</span> constexpr std::size_t <a class="code" href="group__group-Foldable.html#ga8ec3ac9a6f5014db943f61ebc9e1e36e">size</a> = 0;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T1></div><div class="line"><span class="keyword">struct </span>vector1 {</div><div class="line"> T1 t1;</div><div class="line"> <span class="keyword">using</span> hana_tag = vector_tag;</div><div class="line"> <span class="keyword">static</span> constexpr std::size_t <a class="code" href="group__group-Foldable.html#ga8ec3ac9a6f5014db943f61ebc9e1e36e">size</a> = 1;</div><div class="line"></div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> Index></div><div class="line"> <span class="keyword">auto</span> <span class="keyword">const</span>& operator[](Index i)<span class="keyword"> const </span>{</div><div class="line"> static_assert(i == 0u, <span class="stringliteral">"index out of bounds"</span>);</div><div class="line"> <span class="keywordflow">return</span> t1;</div><div class="line"> }</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T1, <span class="keyword">typename</span> T2></div><div class="line"><span class="keyword">struct </span>vector2 {</div><div class="line"> T1 t1; T2 t2;</div><div class="line"> <span class="keyword">using</span> hana_tag = vector_tag;</div><div class="line"> <span class="keyword">static</span> constexpr std::size_t <a class="code" href="group__group-Foldable.html#ga8ec3ac9a6f5014db943f61ebc9e1e36e">size</a> = 2;</div><div class="line"></div><div class="line"> <span class="comment">// Using Hana as a backend to simplify the example.</span></div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> Index></div><div class="line"> <span class="keyword">auto</span> <span class="keyword">const</span>& operator[](Index i)<span class="keyword"> const </span>{</div><div class="line"> <span class="keywordflow">return</span> *hana::make_tuple(&t1, &t2)[i];</div><div class="line"> }</div><div class="line">};</div><div class="line"></div><div class="line"><span class="comment">// and so on...</span></div></div><!-- fragment --><p> The nested <code>using hana_tag = vector_tag;</code> part is a terse way of controling the result of the <code>tag_of</code> metafunction, and hence the tag of the <code>vectorN</code> type. This is explained in the reference for <code>tag_of</code>. Finally, if you wanted to customize the behavior of the <code>print</code> function for all the <code>vectorN</code> types, you would normally have to write something along the lines of</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>(std::ostream& os, vector0)</div><div class="line">{ os << <span class="stringliteral">"[]"</span>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T1></div><div class="line"><span class="keywordtype">void</span> <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>(std::ostream& os, vector1<T1> v)</div><div class="line">{ os << <span class="stringliteral">"["</span> << v.t1 << <span class="stringliteral">"]"</span>; }</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T1, <span class="keyword">typename</span> T2></div><div class="line"><span class="keywordtype">void</span> <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>(std::ostream& os, vector2<T1, T2> v)</div><div class="line">{ os << <span class="stringliteral">"["</span> << v.t1 << <span class="stringliteral">", "</span> << v.t2 << <span class="stringliteral">"]"</span>; }</div><div class="line"></div><div class="line"><span class="comment">// and so on...</span></div></div><!-- fragment --><p> Now, with tag dispatching, you can rely on the <code>vectorN</code>s all sharing the same tag and specialize only the <code>print_impl</code> struct instead:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <></div><div class="line"><span class="keyword">struct </span>print_impl<vector_tag> {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> vectorN></div><div class="line"> <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">apply</a>(std::ostream& os, vectorN xs) {</div><div class="line"> <span class="keyword">auto</span> N = hana::size_c<vectorN::size>;</div><div class="line"></div><div class="line"> os << <span class="stringliteral">"["</span>;</div><div class="line"> N.times.with_index([&](<span class="keyword">auto</span> i) {</div><div class="line"> os << xs[i];</div><div class="line"> <span class="keywordflow">if</span> (i != N - hana::size_c<1>) os << <span class="stringliteral">", "</span>;</div><div class="line"> });</div><div class="line"> os << <span class="stringliteral">"]"</span>;</div><div class="line"> }</div><div class="line">};</div></div><!-- fragment --><p> One upside is that all <code>vectorN</code>s can now be treated uniformly by the <code>print</code> function, at the cost of some boilerplate when creating the data structure (to specify the tag of each <code>vectorN</code>) and when creating the initial <code>print</code> function (to setup the tag dispatching system with <code>print_impl</code>). There are also other advantages to this technique, like the ability to check for preconditions in the interface function without having to do it in each custom implementation, which would be tedious:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> X></div><div class="line"><span class="keywordtype">void</span> <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>(std::ostream& os, X x) {</div><div class="line"> <span class="comment">// **** check some precondition ****</span></div><div class="line"></div><div class="line"> <span class="comment">// The precondition only has to be checked here; implementations</span></div><div class="line"> <span class="comment">// can assume their arguments to always be sane.</span></div><div class="line"></div><div class="line"> <span class="keyword">using</span> Tag = <span class="keyword">typename</span> hana::tag_of<X>::type;</div><div class="line"> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">print_impl<Tag>::apply</a>(os, x);</div><div class="line">}</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>Checking preconditions does not make much sense for a <code>print</code> function, but consider for example a function to get the <code>n</code>th element of a sequence; you might want to make sure that the index is not out-of-bounds.</dd></dl>
<p>This technique also makes it easier to provide interface functions as function objects instead of normal overloaded functions, because only the interface function itself must go through the trouble of defining a function object. Function objects have several advantages over overloaded functions, like the ability to be used in higher order algorithms or as variables:</p>
<div class="fragment"><div class="line"><span class="comment">// Defining a function object is only needed once and implementations do not</span></div><div class="line"><span class="comment">// have to worry about static initialization and other painful tricks.</span></div><div class="line"><span class="keyword">struct </span>print_t {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> X></div><div class="line"> <span class="keywordtype">void</span> operator()(std::ostream& os, X x)<span class="keyword"> const </span>{</div><div class="line"> <span class="keyword">using</span> Tag = <span class="keyword">typename</span> hana::tag_of<X>::type;</div><div class="line"> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">print_impl<Tag>::apply</a>(os, x);</div><div class="line"> }</div><div class="line">};</div><div class="line">constexpr print_t <a class="code" href="group__group-experimental.html#ga660c0769106006a86948b5b355fad050">print</a>{};</div></div><!-- fragment --><p> As you are probably aware of, being able to implement an algorithm for many types at the same time is tremendously useful (that's precisely the goal of C++ templates!). However, even more useful is the ability to implement an algorithm for many types <em>that satisfy some condition</em>. C++ templates are currently missing this ability to constrain their template parameters, but a language feature called <a href="path_to_url">concepts</a> is being rolled out with the goal of addressing this issue.</p>
<p>With something similar in mind, Hana's algorithms support an additional layer of tag-dispatching to what was explained above. This layer allows us to "specialize" an algorithm for all types that satisfy some predicate. For example, let's say we wanted to implement the <code>print</code> function above for all types that represent some kind of sequence. Right now, we wouldn't have an easy way to do this. However, the tag dispatching for Hana's algorithms is set up slightly differently than what was shown above, and we could hence write the following:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Tag></div><div class="line"><span class="keyword">struct </span>print_impl<Tag, hana::when<Tag represents some kind of sequence>> {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> Seq></div><div class="line"> <span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">apply</a>(std::ostream& os, Seq xs) {</div><div class="line"> <span class="comment">// Some implementation for any sequence</span></div><div class="line"> }</div><div class="line">};</div></div><!-- fragment --><p> where <code>Tag represents some kind of sequence</code> would only need to be a boolean expression representing whether <code>Tag</code> is a sequence. We'll see how such predicates can be created in the next section, but for now let's assume that it <em>just works</em>. Without going into the details of how this tag-dispatching is set up, the above specialization will only be picked up when the predicate is satisfied, and if no better match can be found. Hence, for example, if our <code>vector_tag</code> was to satisfy the predicate, our initial implementation for <code>vector_tag</code> would still be preferred over the <code>hana::when</code>-based specialization, because it represents a better match. In general, any specialization (whether explicit or partial) <em>not</em> using <code>hana::when</code> will be preferred over a specialization using <code>hana::when</code>, which was designed to be as unsurprising as possible from a user point of view. This covers pretty much all there's to say about tag-dispatching in Hana. The next section will explain how we can create C++ concepts for metaprogramming, which could then be used in conjunction with <code>hana::when</code> to achieve a great deal of expressiveness.</p>
<h2><a class="anchor" id="tutorial-core-concepts"></a>
Emulation of C++ concepts</h2>
<p>The implementation of concepts in Hana is very simple. At its heart, a concept is just a template <code>struct</code> that inherits from a boolean <code>integral_constant</code> representing whether the given type is a <em>model</em> of the concept:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>Concept</div><div class="line"> : hana::integral_constant<bool, whether T models Concept></div><div class="line">{ };</div></div><!-- fragment --><p>Then, one can test whether a type <code>T</code> is a model of <code>Concept</code> by looking at <code>Concept<T>::value</code>. Simple enough, right? Now, while the way one might implement the check does not have to be anything specific as far as Hana is concerned, the rest of this section will explain how it is usually done in Hana, and how it interacts with tag dispatching. You should then be able to define your own concepts if you so desire, or at least to understand better how Hana works internally.</p>
<p>Usually, a concept defined by Hana will require that any model implements some tag-dispatched functions. For example, the <code>Foldable</code> concept requires that any model defines at least one of <code>hana::unpack</code> and <code>hana::fold_left</code>. Of course, concepts usually also define semantic requirements (called laws) that must be satisfied by their models, but these laws are not (and couldn't be) checked by the concept. But how do we check that some functions are properly implemented? For this, we'll have to slightly modify the way we defined tag-dispatched methods as shown in the previous section. Let's go back to our <code>print</code> example and try to define a <code>Printable</code> concept for those objects that can be <code>print</code>ed. Our end goal is to have a template struct such as</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>Printable</div><div class="line"> : hana::integral_constant<bool, whether print_impl<tag of T> is defined></div><div class="line">{ };</div></div><!-- fragment --><p>To know whether <code>print_impl<...></code> has been defined, we'll modify <code>print_impl</code> so that it inherits from a special base class when it is not overridden, and we'll simply check whether <code>print_impl<T></code> inherits from that base class:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>special_base_class { };</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>print_impl : special_base_class {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> ...Args></div><div class="line"> <span class="keyword">static</span> constexpr <span class="keyword">auto</span> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">apply</a>(Args&& ...) = <span class="keyword">delete</span>;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>Printable</div><div class="line"> : hana::integral_constant<bool,</div><div class="line"> !std::is_base_of<special_base_class, print_impl<hana::tag_of_t<T>>>::value</div><div class="line"> ></div><div class="line">{ };</div></div><!-- fragment --><p> Of course, when we specialize <code>print_impl</code> with a custom type, we don't inherit from that <code>special_base_class</code> type:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Person { std::string name; };</div><div class="line"></div><div class="line"><span class="keyword">template</span> <></div><div class="line"><span class="keyword">struct </span>print_impl<Person> <span class="comment">/* don't inherit from special_base_class */</span> {</div><div class="line"> <span class="comment">// ... implementation ...</span></div><div class="line">};</div><div class="line"></div><div class="line">static_assert(<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">Printable<Person>::value</a>, <span class="stringliteral">""</span>);</div><div class="line">static_assert(!<a class="code" href="group__group-Constant.html#ga1687520692a6b0c49e3a69de2980f388">Printable<void>::value</a>, <span class="stringliteral">""</span>);</div></div><!-- fragment --><p> As you can see, <code>Printable<T></code> really only checks whether the <code>print_impl<T></code> struct was specialized by a custom type. In particular, it does not even check whether the nested <code>::apply</code> function is defined or if it is syntactically valid. It is assumed that if one specializes <code>print_impl</code> for a custom type, the nested <code>::apply</code> function exists and is correct. If it is not, a compilation error will be triggered when one tries to call <code>print</code> on an object of that type. Concepts in Hana make the same assumptions.</p>
<p>Since this pattern of inheriting from a special base class is quite abundant in Hana, the library provides a dummy type called <code>hana::default_</code> that can be used in place of <code>special_base_class</code>. Then, instead of using <code>std::is_base_of</code>, one can use <code>hana::is_default</code>, which looks nicer. With this syntactic sugar, the code now becomes:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>print_impl : hana::default_ {</div><div class="line"> <span class="keyword">template</span> <<span class="keyword">typename</span> ...Args></div><div class="line"> <span class="keyword">static</span> constexpr <span class="keyword">auto</span> <a class="code" href="group__group-functional.html#ga30027c383676084be151ef3c6cf2829f">apply</a>(Args&& ...) = <span class="keyword">delete</span>;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keyword">struct </span>Printable</div><div class="line"> : hana::integral_constant<bool,</div><div class="line"> !hana::is_default<print_impl<hana::tag_of_t<T>>>::value</div><div class="line"> ></div><div class="line">{ };</div></div><!-- fragment --><p> This is all that there's to know about the interaction between tag-dispatched functions and concepts. However, some concepts in Hana do not rely solely on the definition of specific tag-dispatched functions to determine if a type is a model of the concept. This can happen when a concept merely introduces semantic guarantees through laws and refined concepts, but no additional syntactic requirements. Defining such a concept can be useful for several reasons. First, it sometimes happen that an algorithm can be implemented more efficiently if we can assume some semantic guarantees X or Y, so we might create a concept to enforce those guarantees. Secondly, it is sometimes possible to automatically define the models for several concepts when we have additional semantic guarantees, which saves the user the trouble of defining those models manually. For example, this is the case of the <code>Sequence</code> concept, which basically adds semantic guarantees to <code>Iterable</code> and <code>Foldable</code>, and in turn allows us to define the models for a myriad of concepts ranging from <code>Comparable</code> to <code>Monad</code>.</p>
<p>For these concepts, it is usually necessary to specialize the corresponding template struct in the <code><a class="el" href="namespaceboost_1_1hana.html" title="Namespace containing everything in the library. ">boost::hana</a></code> namespace to provide a model for a custom type. Doing so is like providing a seal saying that the semantic guarantees required by the concept are respected by the custom type. The concepts that require being explicitly specialized will document that fact. So that's it! This is all that there's to know about concepts in Hana, which ends this section about the core of Hana.</p>
<h1><a class="anchor" id="tutorial-header_organization"></a>
Header organization</h1>
<hr/>
<p> The library is designed to be modular while keeping the number of headers that must be included to get basic functionality reasonably low. The structure of the library was also intentionally kept simple, because we all love simplicity. What follows is a general overview of the header organization. A list of all the headers provided by the library is also available in the panel on the left (under the <a href="files.html">Headers</a> label) in case you need more details.</p>
<ul>
<li><code><a class="el" href="hana_8hpp.html" title="Includes all the library components except the adapters for external libraries. ">boost/hana.hpp</a></code><br />
This is the master header of the library, which includes the whole public interface of the library. Note that external adapters, experimental features and implementation details are not included by this header, however, since some of them require additional dependencies.</li>
<li><code>boost/hana/</code><br />
This is the main directory of the library containing the definitions of everything provided by the library. Each algorithm and container provided by the library has its own header. For a container or an algorithm named <code>XXX</code>, the corresponding header is <code>boost/hana/XXX.hpp</code>.<ul>
<li><code>boost/hana/concept/</code><br />
This subdirectory contains the definition of Hana's concepts. These headers provide a way to check whether an object is a model of the corresponding concept, and they sometimes also provide default implementations for other related concepts, which are documented on a per-concept basis. They also include all the algorithms associated to that concept.</li>
<li><code>boost/hana/core/</code><br />
This subdirectory contains the machinery for tag dispatching and other related utilities like <code>make</code> and <code>to</code>.</li>
<li><code>boost/hana/fwd/</code><br />
This subdirectory contains the forward declaration of everything in the library. It is essentially a mirror of the <code>boost/hana/</code> directory, except all the headers contain only forward declarations and documentation. For example, to include the <code>hana::tuple</code> container, one can use the <code><a class="el" href="tuple_8hpp.html" title="Defines boost::hana::tuple. ">boost/hana/tuple.hpp</a></code> header. However, if one only wants the forward declaration of that container, the <code><a class="el" href="fwd_2tuple_8hpp.html" title="Forward declares boost::hana::tuple. ">boost/hana/fwd/tuple.hpp</a></code> header can be used instead. Note that forward declarations for headers in <code>boost/hana/ext/</code> and <code>boost/hana/functional/</code> are not provided.</li>
<li><code>boost/hana/functional/</code><br />
This subdirectory contains various function objects that are often useful, but that do not necessarily belong to a concept.</li>
<li><p class="startli"><code>boost/hana/ext/</code><br />
This directory contains adapters for external libraries. For a component named <code>xxx</code> in a namespace <code>ns</code>, the external adapter lives in the <code>boost/hana/ext/ns/xxx.hpp</code> header. For example, the external adapter for <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> lives in the <code><a class="el" href="ext_2std_2tuple_8hpp.html" title="Adapts std::tuple for use with Hana. ">boost/hana/ext/std/tuple.hpp</a></code> header, while the external adapter for <code><a class="el" href="structboost_1_1mpl_1_1vector.html" title="Adapter for Boost.MPL vectors. ">boost::mpl::vector</a></code> is in <code><a class="el" href="boost_2mpl_2vector_8hpp.html" title="Adapts boost::mpl::vector for use with Hana. ">boost/hana/ext/boost/mpl/vector.hpp</a></code>.</p>
<p class="startli">Note that only the strict minimum required to adapt the external components is included in these headers (e.g. a forward declaration). This means that the definition of the external component should still be included when one wants to use it. For example: </p><div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="ext_2std_2tuple_8hpp.html">boost/hana/ext/std/tuple.hpp</a>></span></div><div class="line"><span class="preprocessor">#include <<a class="code" href="front_8hpp.html">boost/hana/front.hpp</a>></span></div><div class="line"><span class="preprocessor">#include <tuple></span> <span class="comment">// still required to create a tuple</span></div><div class="line"><span class="keyword">namespace </span>hana = <a class="code" href="namespaceboost_1_1hana.html">boost::hana</a>;</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main() {</div><div class="line"> constexpr <a class="code" href="structstd_1_1tuple.html">std::tuple<int, char, float></a> xs{1, <span class="charliteral">'2'</span>, 3.0f};</div><div class="line"> static_assert(<a class="code" href="group__group-Iterable.html#ga8a67ea10e8082dbe6705e573fa978444">hana::front</a>(xs) == 1, <span class="stringliteral">""</span>);</div><div class="line">}</div></div><!-- fragment --></li>
<li><p class="startli"><code>boost/hana/experimental/</code><br />
This directory contains experimental features that may or may not make it into the library at some point, but that were deemed useful enough to be made available to the public. Features in this subdirectory reside in the <code>hana::experimental</code> namespace. Also, do not expect these features to be stable; they may be moved, renamed, changed or removed between releases of the library. These features may also require additional external dependencies; each feature documents the additional dependencies it requires, if any.</p>
<p class="startli">Because of the potential additional dependencies, these headers are also not included by the master header of the library.</p>
</li>
<li><code>boost/hana/detail/</code><br />
This directory contains utilities required internally. Nothing in <code>detail/</code> is guaranteed to be stable, so you should not use it.</li>
</ul>
</li>
</ul>
<h1><a class="anchor" id="tutorial-conclusion"></a>
Conclusion</h1>
<hr/>
<p> You now have everything you need to start using the library. From this point forward, mastering the library is only a matter of understanding how to use the general purpose concepts and containers provided with it, which is best done by looking at the reference documentation. At some point, you will probably also want to create your own concepts and data types that fit your needs better; go ahead, the library was designed to be used that way.</p>
<h2><a class="anchor" id="tutorial-conclusion-warning"></a>
Fair warning: functional programming ahead</h2>
<p>Programming with heterogeneous objects is inherently functional – since it is impossible to modify the type of an object, a new object must be introduced instead, which rules out mutation. Unlike previous metaprogramming libraries whose design was modeled on the STL, Hana uses a functional style of programming which is the source for a good portion of its expressiveness. However, as a result, many concepts presented in the reference will be unfamiliar to C++ programmers without a knowledge of functional programming. The reference attempts to make these concepts approachable by using intuition whenever possible, but bear in mind that the highest rewards are usually the fruit of some effort.</p>
<h2><a class="anchor" id="tutorial-conclusion-related_material"></a>
Related material</h2>
<p>Through the years, I have produced some material about Hana and metaprogramming more generally. You may find some of it useful:</p>
<ul>
<li>Keynote on metaprogramming at <a href="path_to_url">Meeting C++</a> 2016 (<a href="path_to_url">slides</a>/<a href="path_to_url">video</a>)</li>
<li>Talk on advanced metaprogramming techniques used in Hana at <a href="path_to_url">C++Now</a> 2016 (<a href="path_to_url">slides</a>/<a href="path_to_url">video</a>)</li>
<li>Introduction to metaprogramming with Hana at <a href="path_to_url">C++Now</a> 2016 (<a href="path_to_url">slides</a>/<a href="path_to_url">video</a>)</li>
<li>Talk on the <a href="path_to_url">MPL11</a> library at <a href="path_to_url">C++Now</a> 2014. This is how Hana started out. (<a href="path_to_url">slides</a>/<a href="path_to_url">video</a>)</li>
<li>My bachelor's thesis was a formalization of C++ metaprogramming using category theory. The thesis is available <a href="path_to_url">here</a>, and the slides of a related presentation are available <a href="path_to_url">here</a>. Unfortunately, both are in french only.</li>
</ul>
<p>The complete list of talks I've done on Hana and metaprogramming is <a href="path_to_url">here</a>. There is also an unofficial translation of Hana's documentation to Chinese available <a href="path_to_url">here</a>.</p>
<h2><a class="anchor" id="tutorial-conclusion-projects_using_hana"></a>
Projects using Hana</h2>
<p>There is a growing number of projects using Hana. It can be useful to look at them to get a sense of how to best use the library. Here's a few of those projects (<a href="path_to_url">open an issue</a> if you want your project to be listed here):</p>
<ul>
<li><a href="path_to_url">Dyno</a>: A policy-based type erasure library. Uses Hana for vtable generation and concept map emulation under the hood.</li>
<li><a href="path_to_url">yap</a>: An expression template library built on top of Hana.</li>
<li><a href="path_to_url">NBDL</a>: Library for managing application state across network. Uses Hana for some things under the hood.</li>
<li><a href="path_to_url">ECST</a>: An experimental multithreaded compile-time entity-component system using Hana under the hood for a few things.</li>
</ul>
<p>This finishes the tutorial part of the documentation. I hope you enjoy using the library, and please consider <a href="path_to_url#how-to-contribute">contributing</a> to make it even better!</p>
<p>– Louis</p>
<h1><a class="anchor" id="tutorial-reference"></a>
Using the reference</h1>
<hr/>
<p> As for most generic libraries, algorithms in Hana are documented by the concept to which they belong (<code>Foldable</code>, <code>Iterable</code>, <code>Searchable</code>, <code>Sequence</code>, etc...). The different containers are then documented on their own page, and the concepts that they model are documented there. The concepts modeled by some container defines what algorithms can be used with such a container.</p>
<p>More specifically, the structure of the reference (available in the menu to the left) goes as follow:</p>
<ul>
<li><a class="el" href="group__group-core.html">Core</a><br />
Documentation for the core module, which contains everything needed to create concepts, data types and related utilities. This is relevant if you need to extend the library, but otherwise you can probably ignore this.</li>
<li><a class="el" href="group__group-concepts.html">Concepts</a><br />
Documentation for all the concepts provided with the library. Each concept:<ul>
<li>Documents which functions must be implemented absolutely in order to model that concept. The set of functions that must be provided is called a <em>minimal complete definition</em>.</li>
<li>Documents semantic constraints that any model of that concept must satisfy. These constraints are usually called laws and they are expressed in a semi-formal mathematical language. Of course, those laws can't be checked automatically but you should still make sure you satisfy them.</li>
<li>Documents the concept(s) it refines, if any. Sometimes, a concept is powerful enough to provide a model of a concept it refines, or at least the implementation for some of its associated functions. When this is the case, the concept will document which functions of the refined concept it provides, and how it does so. Also, it is sometimes possible that the model for a refined concept is unique, in which case it can be provided automatically. When this happens, it will be documented but you don't have to do anything special to get that model.</li>
</ul>
</li>
<li><a class="el" href="group__group-datatypes.html">Data types</a><br />
Documentation for all the data structures provided with the library. Each data structure documents the concept(s) it models, and how it does so. It also documents the methods tied to it but not to any concept, for example <code>maybe</code> for <code>optional</code>.</li>
<li><a class="el" href="group__group-functional.html">Functional</a><br />
General purpose function objects that are generally useful in a purely functional setting. These are currently not tied to any concept or container.</li>
<li><a class="el" href="group__group-ext.html">External adapters</a><br />
Documentation for all the adapters for external libraries. These adapters are documented as if they were native types provided by Hana, but obviously Hana only provides the compatibility layer between them and the library.</li>
<li><a class="el" href="group__group-config.html">Configuration options</a><br />
Macros that can be used to tweak the global behavior of the library.</li>
<li><a class="el" href="group__group-assertions.html">Assertions</a><br />
Macros to perform various types of assertions.</li>
<li><a href="functions.html"><b>Alphabetical index</b></a><br />
Alphabetical index of everything provided in the library.</li>
<li><a href="files.html"><b>Headers</b></a><br />
A list of all the headers provided by the library.</li>
<li><a class="el" href="group__group-details.html">Details</a><br />
Implementation details; don't go there. Anything not documented at all or documented in this group is not guaranteed to be stable.</li>
</ul>
<p>After you get to know Hana a bit better, it will probably happen that you just want to find the reference for a precise function, concept or container. If you know the name of what you're looking for, you can use the <em>search</em> box located in the upper right corner of any page of the documentation. My personal experience is that this is by far the quickest way of finding what you want when you already know its name.</p>
<h2><a class="anchor" id="tutorial-reference-signatures"></a>
Function signatures</h2>
<p>As you will see in the reference, several functions provide signatures documented in a semi-formal mathematical language. We are in the process of documenting all functions in this way, but this may take a while. The notation used is the usual mathematical notation for defining functions. Specifically, a function <code>Return f(Arg1, ..., ArgN);</code> can be defined equivalently using mathematical notation as</p>
<p class="formulaDsp">
\[ \mathtt{f} : \mathtt{Arg}_1 \times \dots \times \mathtt{Arg}_n \to \mathtt{Return} \]
</p>
<p>However, instead of documenting the actual argument and return types of functions, those signatures are written in terms of argument and return tags. This is done because of the heterogeneous setting, where the actual type of an object is usually pretty meaningless and does not help to reason about what's being returned or taken by a function. For example, instead of documenting the <code>equal</code> function for <code>integral_constant</code>s as</p>
<p class="formulaDsp">
\[ \mathtt{equal} : \mathtt{integral\_constant<T, n>} \times \mathtt{integral\_constant<T, m>} \to \mathtt{integral\_constant<bool, n == m>} \]
</p>
<p>which is not really helpful (as it really presents nothing but the implementation), it is instead documented using <code>integral_constant_tag</code>, which acts as the "type" of all <code>integral_constant</code>s. Note that since <code>equal</code> is part of the <code>Comparable</code> concept, it is not <em>actually</em> documented for <code>hana::integral_constant</code> specifically, but the idea is there:</p>
<p class="formulaDsp">
\[ \mathtt{equal} : \mathtt{integral\_constant\_tag<T>} \times \mathtt{integral\_constant\_tag<T>} \to \mathtt{integral\_constant\_tag<bool>} \]
</p>
<p>This clearly conveys the intention that comparing two <code>integral_constant</code>s gives back another <code>integral_constant</code> holding a <code>bool</code>. In general, this abstraction of the actual representation of objects makes it possible for us to reason in a high level manner about functions, even though their actual return and argument types are heterogeneous and not helpful. Finally, most functions expect container elements to have some properties. For example, this is the case of the <code>sort</code> algorithm, which obviously requires the container elements to be <code>Orderable</code>. Normally, we would write the signature for the non-predicated version of <code>sort</code> as</p>
<p class="formulaDsp">
\[ \mathtt{sort} : \mathtt{S} \to \mathtt{S} \\ \text{where S is a Sequence} \]
</p>
<p>However, this fails to express the requirement that the contents of <code>S</code> are <code>Orderable</code>. To express this, we use the following notation:</p>
<p class="formulaDsp">
\[ \mathtt{sort} : \mathtt{S(T)} \to \mathtt{S(T)} \\ \text{where S is a Sequence and T is Orderable} \]
</p>
<p>One way to see this is to pretend that <code>S</code>, the sequence tag, is actually parameterized by the tag of the sequence's elements, <code>T</code>. We're also pretending that the elements all have the same tag <code>T</code>, which is not the case in general. Now, by stating that <code>T</code> must be <code>Orderable</code>, we're expressing the fact that the sequence's elements must be <code>Orderable</code>. This notation is used in different flavors to express different kinds of requirements. For example, the <code>cartesian_product</code> algorithm takes a sequence of sequences and returns the cartesian product of those sequences as a sequence of sequences. Using our notation, this can be conveyed very easily:</p>
<p class="formulaDsp">
\[ \mathtt{cartesian\_product} : \mathtt{S(S(T))} \to \mathtt{S(S(T))} \\ \text{where S is a Sequence} \]
</p>
<h1><a class="anchor" id="tutorial-acknowledgements"></a>
Acknowledgements</h1>
<hr/>
<p> I'd like to thank the following persons and organizations for contributing to Hana in one way or another:</p>
<ul>
<li>Zach Laine and Matt Calabrese for the original idea of using function call syntax to do type-level computations, as presented in their BoostCon <a href="path_to_url">presentation</a> (<a href="path_to_url">slides 1</a>) (<a href="path_to_url">slides 2</a>).</li>
<li>Joel Falcou for mentoring me two consecutive years during my work on Hana as part of the <a href="path_to_url">Google Summer of Code</a> program, Niall Douglas for being the GSoC admin for Boost and helping me get in the program, and finally Google for their awesome GSoC program.</li>
<li>The <a href="path_to_url">Boost Steering committee</a> for unlocking a grant for me to work on Hana in the winter of 2015, as an extension to the previous year's GSoC.</li>
<li>Several <a href="path_to_url">C++Now</a> attendees and members of the <a href="path_to_url">Boost mailing list</a> for insightful conversations, comments and questions about the project.</li>
</ul>
<h1><a class="anchor" id="tutorial-glossary"></a>
Glossary</h1>
<hr/>
<p> The reference documentation uses a couple of terms that are specific to this library. Also, a simplified implementation of functions is sometimes provided in pseudo-code, the actual implementation sometimes being slightly hard to understand. This section defines terms used in the reference and in the pseudo-code used to describe some functions.</p>
<p><a class="anchor" id="tutorial-glossary-forwarded"></a></p><h4><code>forwarded(x)</code></h4>
<p>Means that the object is forwarded optimally. This means that if <code>x</code> is a parameter, it is <code>std::forward</code>ed, and if it is a captured variable, it is moved from whenever the enclosing lambda is an rvalue.</p>
<p>Also note that when <code>x</code> can be moved from, the statement <code>return forwarded(x);</code> in a function with <code>decltype(auto)</code> does not mean that an rvalue reference to <code>x</code> will be returned, which would create a dangling reference. Rather, it means that <code>x</code> is returned by value, the value being constructed with the <code>std::forward</code>ed <code>x</code>.</p>
<p><a class="anchor" id="tutorial-glossary-perfect_capture"></a></p><h4><code>perfect-capture</code></h4>
<p>This is used in lambdas to signify that the captured variables are initialized using perfect forwarding, as if <code>[x(forwarded(x))...]() { }</code> had been used.</p>
<p><a class="anchor" id="tutorial-glossary-tag_dispatched"></a></p><h4><code>tag-dispatched</code></h4>
<p>This means that the documented function uses <a class="el" href="index.html#tutorial-core-tag_dispatching">tag dispatching</a>, and hence the exact implementation depends on the model of the concept associated to the function.</p>
<p><a class="anchor" id="tutorial-glossary-implementation_defined"></a></p><h4><code>implementation-defined</code></h4>
<p>This expresses the fact that the exact implementation of an entity (usually a type) should not be relied upon by users. In particular, this means that one can not assume anything beyond what is written explicitly in the documentation. Usually, the concepts satisfied by an implementation-defined entity will be documented, because one could otherwise do nothing with it. Concretely, assuming too much about an implementation-defined entity will probably not kill you, but it will very probably break your code when you update to a newer version of Hana.</p>
<h1><a class="anchor" id="tutorial-rationales"></a>
Rationales/FAQ</h1>
<hr/>
<p> This section documents the rationale for some design choices. It also serves as a FAQ for some (not so) frequently asked questions. If you think something should be added to this list, open a GitHub issue and we'll consider either improving the documentation or adding the question here.</p>
<h2><a class="anchor" id="tutorial-rationales-dependencies"></a>
Why restrict usage of external dependencies?</h2>
<p>There are several reasons for doing so. First, Hana is a very fundamental library; we are basically reimplementing the core language and the standard library with support for heterogeneous types. When going through the code, one quickly realizes that other libraries are rarely needed, and that almost everything has to be implemented from scratch. Also, since Hana is very fundamental, there is even more incentive for keeping the dependencies minimal, because those dependencies will be handed down to the users. Regarding the minimal reliance on Boost in particular, one big argument for using it is portability. However, as a cutting edge library, Hana only targets very recent compilers. Hence, we can afford to depend on modern constructs and the portability given to us by using Boost would mostly represent dead weight.</p>
<h2><a class="anchor" id="tutorial-rationales-iterators"></a>
Why no iterators?</h2>
<p>Iterator based designs have their own merits, but they are also known to reduce the composability of algorithms. Furthermore, the context of heterogeneous programming brings a lot of points that make iterators much less interesting. For example, incrementing an iterator would have to return a new iterator with a different type, because the type of the new object it is pointing to in the sequence might be different. It also turns out that implementing most algorithms in terms of iterators leads to a worse compile-time performance, simply because the execution model of metaprogramming (using the compiler as an interpreter) is so different from the runtime execution model of C++ (a processor accessing contiguous memory).</p>
<h2><a class="anchor" id="tutorial-rationales-container_representation"></a>
Why leave some container's representation implementation-defined?</h2>
<p>First, it gives much more wiggle room for the implementation to perform compile-time and runtime optimizations by using clever representations for specific containers. For example, a tuple containing homogeneous objects of type <code>T</code> could be implemented as an array of type <code>T</code> instead, which is more efficient at compile-time. Secondly, and most importantly, it turns out that knowing the type of a <em>heterogeneous</em> container is not as useful as you would think. Indeed, in the context of heterogeneous programming, the type of the object returned by a computation is usually part of the computation too. In other words, there is no way to know the type of the object returned by an algorithm without actually performing the algorithm. For example, consider the <code>find_if</code> algorithm:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> tuple = hana::make_tuple(1, <span class="charliteral">'x'</span>, 3.4f);</div><div class="line"></div><div class="line"><span class="keyword">auto</span> result = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(tuple, [](<span class="keyword">auto</span> <span class="keyword">const</span>& x) {</div><div class="line"> <span class="keywordflow">return</span> hana::traits::is_integral(hana::typeid_(x));</div><div class="line">});</div></div><!-- fragment --><p> If the predicate is satisfied for some element of the tuple, result will be equal to <code>just(x)</code>. Otherwise, <code>result</code> will be equal to <code>nothing</code>. However, the <code>nothing</code>ness of the result is known at compile-time, which requires <code>just(x)</code> and <code>nothing</code> to have different types. Now, say you wanted to explicitly write the type of the result:</p>
<div class="fragment"><div class="line">some_type result = <a class="code" href="group__group-Searchable.html#ga7f99b80672aa80a7eb8b223955ce546f">hana::find_if</a>(tuple, [](<span class="keyword">auto</span> <span class="keyword">const</span>& x) {</div><div class="line"> <span class="keywordflow">return</span> hana::traits::is_integral(hana::typeid_(x));</div><div class="line">});</div></div><!-- fragment --><p> In order to possess the knowledge of what <code>some_type</code> is, you would need to actually perform the algorithm, because <code>some_type</code> depends on whether the predicate is satisfied or not for some element in the container. In other words, if you were able to write the above, then you would already know what the result of the algorithm is and you would not need to perform the algorithm in the first place. In Boost.Fusion, this problem is addressed by having a separate <code>result_of</code> namespace, which contains a metafunction computing the result type of any algorithm given the types of the arguments passed to it. For example, the above example could be rewritten with Fusion as:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> Container = fusion::result_of::make_vector<int, char, float>::type;</div><div class="line">Container tuple = fusion::make_vector(1, <span class="charliteral">'x'</span>, 3.4f);</div><div class="line"></div><div class="line"><span class="keyword">using</span> Predicate = mpl::quote1<std::is_integral>;</div><div class="line"><span class="keyword">using</span> Result = fusion::result_of::find_if<Container, Predicate>::type;</div><div class="line">Result result = fusion::find_if<Predicate>(tuple);</div></div><!-- fragment --><p> Notice that we're basically doing the computation twice; once in the <code>result_of</code> namespace and once in the normal <code>fusion</code> namespace, which is highly redundant. Before the days of <code>auto</code> and <code>decltype</code>, such techniques were necessary to perform heterogeneous computations. However, since the advent of modern C++, the need for explicit return types in the context of heterogeneous programming is largely obsolete, and knowing the actual type of containers is usually not that useful.</p>
<h2><a class="anchor" id="tutorial-rationales-why_Hana"></a>
Why Hana?</h2>
<p>No, it isn't the name of my girlfriend! I just needed a short and good looking name that people would easily remember, and Hana came up. It also came to my attention that Hana means <em>flower</em> in Japanese, and <em>one</em> in Korean. Since Hana is pretty and it unifies type-level and heterogeneous programming under a single paradigm, the name appears to be quite well chosen in retrospect :-).</p>
<h2><a class="anchor" id="tutorial-rationales-tuple"></a>
Why define our own tuple?</h2>
<p>Since Hana defines a lot of algorithms on tuples, a possible way to go would have been to simply use <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> and provide the algorithms only, instead of also providing our own tuple. The reason for providing our own tuple is principally performance. Indeed, all the <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code> implementations tested so far have a very bad compile-time performance. Also, to get truly amazing compile-time performance, we need to take advantage of the tuple's internal representation in some algorithms, which requires defining our own. Finally, some sugar like <code>operator[]</code> could not be provided if we were using a <code><a class="el" href="structstd_1_1tuple.html" title="Adapter for std::tuples. ">std::tuple</a></code>, since that operator must be defined as a member function.</p>
<h2><a class="anchor" id="tutorial-rationales-naming"></a>
How are names chosen?</h2>
<p>When deciding upon a name <code>X</code>, I try to balance the following things (in no specific order):</p>
<ul>
<li>How idiomatic is <code>X</code> in C++?</li>
<li>How idiomatic is <code>X</code> in the rest of the programming world?</li>
<li>How good of a name <code>X</code> <em>actually is</em>, regardless of historical reasons</li>
<li>How do I, as the library author, feel about <code>X</code></li>
<li>How do users of the library feel about <code>X</code></li>
<li>Are there technical reasons not to use <code>X</code>, like name clashes or names reserved by the standard</li>
</ul>
<p>Of course, good naming is and will always be hard. Names are and will always be tainted by the author's own bias. Still, I try to choose names in a reasonable manner.</p>
<h2><a class="anchor" id="tutorial-rationales-parameters"></a>
How is the parameter order decided?</h2>
<p>Unlike naming, which is fairly subjective, the order of the parameters of a function is usually pretty straightforward to determine. Basically, the rule of thumb is "the container goes first". It has always been this way in Fusion and MPL, and this is intuitive for most C++ programmers. Also, in higher-order algorithms, I try to put the function parameter last, so that multi-line lambdas look nice:</p>
<div class="fragment"><div class="line">algorithm(container, [](<span class="keyword">auto</span> x) {</div><div class="line"> <span class="keywordflow">return</span> ...;</div><div class="line">});</div><div class="line"></div><div class="line"><span class="comment">// is nicer than</span></div><div class="line"></div><div class="line">algorithm([](<span class="keyword">auto</span> x) {</div><div class="line"> <span class="keywordflow">return</span> ...;</div><div class="line">}, container);</div></div><!-- fragment --><h2><a class="anchor" id="tutorial-rationales-tag_dispatching"></a>
Why tag dispatching?</h2>
<p>There are several different techniques we could have used to provide customization points in the library, and tag-dispatching was chosen. Why? First, I wanted a two-layer dispatching system because this allows functions from the first layer (the ones that are called by users) to actually be function objects, which allows passing them to higher-order algorithms. Using a dispatching system with two layers also allows adding some compile-time sanity checks to the first layer, which improves error messages.</p>
<p>Now, tag-dispatching was chosen over other techniques with two layers for a couple of reasons. First, having to explicitly state how some tag is a model of a concept gives the responsibility of making sure that the semantic requirements of the concept are respected to the user. Secondly, when checking whether a type is a model of some concept, we basically check that some key functions are implemented. In particular, we check that the functions from the minimal complete definition of that concept are implemented. For example, <code>Iterable<T></code> checks whether the <code>is_empty</code>, <code>at</code> and <code>drop_front</code> functions implemented for <code>T</code>. However, the only way to detect this without tag-dispatching is to basically check whether the following expressions are valid in a SFINAE-able context:</p>
<div class="fragment"><div class="line">implementation_of_at(std::declval<T>(), std::declval<N>())</div><div class="line">implementation_of_is_empty(<a class="code" href="namespacestd.html">std</a>::declval<T>())</div><div class="line">implementation_of_drop_front(<a class="code" href="namespacestd.html">std</a>::declval<T>())</div></div><!-- fragment --><p>Unfortunately, this requires actually doing the algorithms, which might either trigger a hard compile-time error or hurt compile-time performance. Also, this requires picking an arbitrary index <code>N</code> to call <code>at</code> with: what if the <code>Iterable</code> is empty? With tag dispatching, we can just ask whether <code>at_impl<T></code>, <code>is_empty_impl<T></code> and <code>drop_front_impl<T></code> are defined, and nothing happens until we actually call their nested <code>::apply</code> function.</p>
<h2><a class="anchor" id="tutorial-rationales-zip_longest"></a>
Why not provide zip_longest?</h2>
<p>It would require either (1) padding the shortest sequences with an arbitrary object, or (2) padding the shortest sequences with an object provided by the user when calling <code>zip_longest</code>. Since there is no requirement that all the zipped sequences have elements of similar types, there is no way to provide a single consistent padding object in all cases. A tuple of padding objects should be provided, but I find it perhaps too complicated to be worth it for now. If you need this functionality, open a GitHub issue.</p>
<h2><a class="anchor" id="tutorial-rationales-concepts"></a>
Why aren't concepts constexpr functions?</h2>
<p>Since the C++ concept proposal maps concepts to boolean <code>constexpr</code> functions, it would make sense that Hana defines its concepts as such too, instead of as structs with a nested <code>::value</code>. Indeed, this was the first choice, but it had to be revised because template functions have one limitation that makes them less flexible. Specifically, a template function can't be passed to a higher-order metafunction. In other words, it is not possible to write the following</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <??? Concept></div><div class="line"><span class="keyword">struct </span>some_metafunction {</div><div class="line"> <span class="comment">// ...</span></div><div class="line">};</div></div><!-- fragment --><p>This sort of code is very useful in some contexts, such as checking whether two types have a common embedding modeling a concept:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <??? Concept, <span class="keyword">typename</span> T, <span class="keyword">typename</span> U></div><div class="line"><span class="keyword">struct </span>have_common_embedding {</div><div class="line"> <span class="comment">// whether T and U both model Concept, and share a common type that also models Concept</span></div><div class="line">};</div></div><!-- fragment --><p>With concepts as boolean <code>constexpr</code> functions, this can't be written generically. When concepts are just template structs, however, we can use template template parameters:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">template</span> <<span class="keyword">typename</span> ...> <span class="keyword">class </span>Concept, <span class="keyword">typename</span> T, <span class="keyword">typename</span> U></div><div class="line"><span class="keyword">struct </span>have_common_embedding {</div><div class="line"> <span class="comment">// whether T and U both model Concept, and share a common type that also models Concept</span></div><div class="line">};</div></div><!-- fragment --><h1><a class="anchor" id="tutorial-appendix-constexpr"></a>
Appendix I: Advanced constexpr</h1>
<hr/>
<p> In C++, the border between compile-time and runtime is hazy, a fact that is even more true with the introduction of <a href="path_to_url#constexpr_.E2.80.93_Generalized_constant_expressions">generalized constant expressions</a> in C++14. However, being able to manipulate heterogeneous objects is all about understanding that border and then crossing it at one's will. The goal of this section is to set things straight with <code>constexpr</code>; to understand which problems it can solve and which ones it can't. This section covers advanced concepts about to constant expressions; only readers with a good understanding of <code>constexpr</code> should attempt to read this.</p>
<h2><a class="anchor" id="tutorial-appendix-constexpr-stripping"></a>
Constexpr stripping</h2>
<p>Let's start with a challenging question. Should the following code compile?</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keywordtype">void</span> f(T t) {</div><div class="line"> static_assert(t == 1, <span class="stringliteral">""</span>);</div><div class="line">}</div><div class="line"></div><div class="line">constexpr <span class="keywordtype">int</span> <a class="code" href="group__group-Ring.html#gadea531feb3b0a1c5c3d777f7ab45e932">one</a> = 1;</div><div class="line">f(one);</div></div><!-- fragment --><p>The answer is no, and the error given by Clang goes like</p>
<div class="fragment"><div class="line">error: static_assert expression is not an <a class="code" href="group__group-Metafunction.html#gaf7045fe6a627f88f5f646dad22d37aae">integral</a> constant expression</div><div class="line"> static_assert(t == 1, <span class="stringliteral">""</span>);</div><div class="line"> ^~~~~~</div></div><!-- fragment --><p>The explanation is that inside of <code>f</code>'s body, <code>t</code> is not a constant expression, and hence it can't be used as the operand to a <code>static_assert</code>. The reason is that such a function simply can't be generated by the compiler. To understand the issue, consider what should happen when we instantiate the <code>f</code> template with a concrete type:</p>
<div class="fragment"><div class="line"><span class="comment">// Here, the compiler should generate the code for f<int> and store the</span></div><div class="line"><span class="comment">// address of that code into fptr.</span></div><div class="line">void (*fptr)(int) = f<int>;</div></div><!-- fragment --><p>Clearly, the compiler can't generate <code>f<int></code>'s code, which should trigger a <code>static_assert</code> if <code>t != 1</code>, because we haven't specified <code>t</code> yet. Even worse, the generated function should work on both constant and non-constant expressions:</p>
<div class="fragment"><div class="line">void (*fptr)(int) = f<int>; <span class="comment">// assume this was possible</span></div><div class="line"><span class="keywordtype">int</span> i = ...; <span class="comment">// user input</span></div><div class="line">fptr(i);</div></div><!-- fragment --><p>Clearly, <code>fptr</code>'s code can't be generated, because it would require being able to <code>static_assert</code> on a runtime value, which does not make sense. Furthermore, note that it does not matter whether you make the function <code>constexpr</code> or not; making <code>f</code> <code>constexpr</code> would only state that the <em>result</em> of <code>f</code> is a constant expression whenever its argument is a constant expression, but it still does not give you the ability to know whether you were called with a constant expression from <code>f</code>'s body. In other words, what we would want is something like:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line"><span class="keywordtype">void</span> f(constexpr T t) {</div><div class="line"> static_assert(t == 1, <span class="stringliteral">""</span>);</div><div class="line">}</div><div class="line"></div><div class="line">constexpr <span class="keywordtype">int</span> one = 1;</div><div class="line">f(one);</div></div><!-- fragment --><p>In this hypothetical scenario, the compiler would know that <code>t</code> is a constant expression from the body of <code>f</code>, and the <code>static_assert</code> could be made to work. However, <code>constexpr</code> parameters do not exist in the current language, and adding them would bring up very challenging design and implementation issues. The conclusion of this little experiment is that <b>argument passing strips away <code>constexpr</code>-ness</b>. What might be unclear by now are the consequences of this stripping, which are explained next.</p>
<h2><a class="anchor" id="tutorial-tutorial-appendix-constexpr-preservation"></a>
Constexpr preservation</h2>
<p>The fact that an argument is not a constant expression means that we can't use it as a non-type template parameter, as an array bound, inside a <code>static_assert</code> or anything else that requires a constant expression. In addition, this means that the return type of a function can't depend on the <em>value</em> of an argument which is nothing new if you think about it:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keywordtype">int</span> i></div><div class="line"><span class="keyword">struct </span>foo { };</div><div class="line"></div><div class="line"><span class="keyword">auto</span> f(<span class="keywordtype">int</span> i) -> foo<i>; <span class="comment">// obviously won't work</span></div></div><!-- fragment --><p>In fact, the return type of a function may only depend on the types of its arguments, and <code>constexpr</code> can't change this fact. This is of utmost importance to us, because we're interested in manipulating heterogeneous objects, which eventually means returning objects with different types depending on the argument of the function. For example, a function might want to return an object of type <code>T</code> in one case and an object of type <code>U</code> in the other; from our analysis, we now know that these "cases" will have to depend on information encoded in the <em>types</em> of the arguments, not in their <em>values</em>.</p>
<p>To preserve <code>constexpr</code>-ness through argument passing, we have to encode the <code>constexpr</code> value into a type, and then pass a not-necessarily-<code>constexpr</code> object of that type to the function. The function, which must be a template, may then access the <code>constexpr</code> value encoded inside that type.</p>
<dl class="todo"><dt><b><a class="el" href="todo.html#_todo000012">Todo:</a></b></dt><dd>Improve this explanation and talk about non-integral constant expressions wrapped into types.</dd></dl>
<h2><a class="anchor" id="tutorial-appendix-constexpr-effects"></a>
Side effects</h2>
<p>Let me ask a tricky question. Is the following code valid?</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keywordtype">int</span> f(T& n) { <span class="keywordflow">return</span> 1; }</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> n = 0;</div><div class="line">constexpr <span class="keywordtype">int</span> i = f(n);</div></div><!-- fragment --><p>The answer is <em>yes</em>, but the reason might not be obvious at first. What happens here is that we have a non-<code>constexpr</code> <code>int n</code>, and a <code>constexpr</code> function <code>f</code> taking a reference to its argument. The reason why most people think it shouldn't work is that <code>n</code> is not <code>constexpr</code>. However, we're not doing anything with <code>n</code> inside of <code>f</code>, so there is no actual reason why this shouldn't work! This is a bit like <code>throw</code>ing inside of a <code>constexpr</code> function:</p>
<div class="fragment"><div class="line">constexpr <span class="keywordtype">int</span> sqrt(<span class="keywordtype">int</span> i) {</div><div class="line"> <span class="keywordflow">if</span> (i < 0) <span class="keywordflow">throw</span> <span class="stringliteral">"i should be non-negative"</span>;</div><div class="line"></div><div class="line"> <span class="keywordflow">return</span> ...;</div><div class="line">}</div><div class="line"></div><div class="line">constexpr <span class="keywordtype">int</span> two = sqrt(4); <span class="comment">// ok: did not attempt to throw</span></div><div class="line">constexpr <span class="keywordtype">int</span> error = sqrt(-4); <span class="comment">// error: can't throw in a constant expression</span></div></div><!-- fragment --><p>As long as the code path where <code>throw</code> appears is not executed, the result of the invocation can be a constant expression. Similarly, we can do whatever we want inside of <code>f</code>, as long as we don't execute a code path that requires accessing its argument <code>n</code>, which is not a constant expression:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keywordtype">int</span> f(T& n, <span class="keywordtype">bool</span> touch_n) {</div><div class="line"> <span class="keywordflow">if</span> (touch_n) n + 1;</div><div class="line"> <span class="keywordflow">return</span> 1;</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> n = 0;</div><div class="line">constexpr <span class="keywordtype">int</span> i = f(n, <span class="keyword">false</span>); <span class="comment">// ok</span></div><div class="line">constexpr <span class="keywordtype">int</span> j = f(n, <span class="keyword">true</span>); <span class="comment">// error</span></div></div><!-- fragment --><p>The error given by Clang for the second invocation is</p>
<div class="fragment"><div class="line">error: constexpr variable <span class="charliteral">'j'</span> must be initialized by a constant expression</div><div class="line">constexpr <span class="keywordtype">int</span> j = f(n, <span class="keyword">true</span>); <span class="comment">// error</span></div><div class="line"> ^ ~~~~~~~~~~</div><div class="line">note: read of non-<span class="keyword">const</span> variable <span class="charliteral">'n'</span> is not allowed <a class="code" href="group__group-Searchable.html#ga0d9456ceda38b6ca664998e79d7c45b7">in</a> a constant expression</div><div class="line"> <span class="keywordflow">if</span> (touch_n) n + 1;</div><div class="line"> ^</div></div><!-- fragment --><p>Let's now step the game up a bit and consider a more subtle example. Is the following code valid?</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> T></div><div class="line">constexpr <span class="keywordtype">int</span> f(T n) { <span class="keywordflow">return</span> 1; }</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> n = 0;</div><div class="line">constexpr <span class="keywordtype">int</span> i = f(n);</div></div><!-- fragment --><p>The only difference with our initial scenario is that <code>f</code> now takes its argument by value instead of by reference. However, this makes a world of difference. Indeed, we're now asking the compiler to make a copy of <code>n</code> and to pass this copy to <code>f</code>. However, <code>n</code> is not <code>constexpr</code>, so its value is only known at runtime. How could the compiler make a copy (at compile-time) of a variable whose value is only known at runtime? Of course, it can't. Indeed, the error message given by Clang is pretty explicit about what's happening:</p>
<div class="fragment"><div class="line">error: constexpr variable <span class="charliteral">'i'</span> must be initialized by a constant expression</div><div class="line">constexpr <span class="keywordtype">int</span> i = f(n);</div><div class="line"> ^ ~~~~</div><div class="line">note: read of non-<span class="keyword">const</span> variable <span class="charliteral">'n'</span> is not allowed <a class="code" href="group__group-Searchable.html#ga0d9456ceda38b6ca664998e79d7c45b7">in</a> a constant expression</div><div class="line">constexpr <span class="keywordtype">int</span> i = f(n);</div><div class="line"> ^</div></div><!-- fragment --><dl class="todo"><dt><b><a class="el" href="todo.html#_todo000013">Todo:</a></b></dt><dd>Explain how side-effects may not appear inside constant expressions, even if the expression they yield are not accessed.</dd></dl>
<h1><a class="anchor" id="tutorial-appendix-MPL"></a>
Appendix II: A minimal MPL</h1>
<hr/>
<p> This section presents a mini reimplementation of the MPL library. The goal is to be as backward compatible as possible with the MPL, while still using Hana under the hood. Only the "Algorithms" part of the MPL is implemented as a case study, but it should be possible to implement many (but not all) metafunctions of the MPL.</p>
<p>Scroll down to the <code>main</code> function to see the tests. The tests are exactly the examples in the MPL documentation that were copy/pasted and then modified as little as possible to work with this reimplementation.</p>
</div><!-- doc-content -->
<!--
(See accompanying file LICENSE.md or copy at path_to_url
-->
<!-- boost-no-inspect -->
<!-- HTML footer for doxygen 1.8.9.1-->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
</ul>
</div>
</body>
</html>
```
|
Kallipefki (Greek: Καλλιπεύκη) is a village located on a plateau on the west side of the lower Mount of Olympus, in the prefecture of Larissa and the municipality of Gonni. Kallipefki has a population of about 540 and is located 1.054 metres (3.458 feet) above sea level. It is about 9 kilometers from ancient Leivithra, 23 kilometers from the town of Gonnoi, 58 kilometers from Larissa , and 130 kilometers from Thessaloniki.
The name derives from the word "kalli" which means fair/good and "pefko" which means pine, due to the beautiful pine forests that surround it. The old name of the village before 1927 was "Nezeros", which probably derives from the Slavic word "ezer", which means lake. The soil of the plateau of Kalipefki that is fit for cultivation today was created in 1911 after the Askouris (Askourida) lake had been drained. The size of the lake was approximately 5.500 acres.
Kallipefki was founded in late Roman times and was one of the 10th century AD bishop dioceses, dependent on the bishop of Larissa. Due to its strategic location in the lower Olympus mountain, it became an important position of Greek resistance ("thieves") during the Turkish occupation.
Stergios Hatzikostas, a trader who lived in Vienna and is most known for being the editor, publisher and friend of Rigas Feraios was born in Kallipefki in 1760.
Some of the touristic sights are "Agia Triada" and "Patomeni"
The "Olympus Storytelling Festival," is held in Kallipefki every two years as a collaboration between the University of Thessaly, the Hellenic Group of Storytelling Friends (POFA) and the Cultural Association of Kallipefki (MESAK).
References
Καλλιπεύκη Λάρισας
Populated places in Larissa (regional unit)
Tempi (municipality)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.