| Package | Description |
|---|---|
| org.bitcoinj.core |
The core package contains classes for network messages like
Block and
Transaction , peer connectivity via PeerGroup ,
and block chain management. |
| org.bitcoinj.crypto |
The crypto package contains classes that work with key derivation algorithms like scrypt (passwords to AES keys),
BIP 32 hierarchies (chains of keys from a root seed), X.509 utilities for the payment protocol and other general
cryptography tasks.
|
| org.bitcoinj.kits |
High level wrapper APIs around the bitcoinj building blocks.
|
| org.bitcoinj.net.discovery |
Classes that know how to discover peers in the P2P network using DNS, IRC or DNS via Tor (orchid).
|
| org.bitcoinj.params |
Network parameters encapsulate some of the differences between different Bitcoin networks such as the main
network, the testnet, regtest mode, unit testing params and so on.
|
| org.bitcoinj.protocols.payments |
The BIP70 payment protocol wraps Bitcoin transactions and adds various useful features like memos, refund addresses
and authentication.
|
| org.bitcoinj.script |
Classes for working with and executing Bitcoin script programs, as embedded in inputs and outputs.
|
| org.bitcoinj.store |
Block stores persist blockchain data downloaded from remote peers.
|
| org.bitcoinj.uri |
Parsing and handling of bitcoin: textual URIs as found in qr codes and web links.
|
| org.bitcoinj.utils |
Formatting monetary amounts, representing exchange rates, a program for loading Bitcoin Core saved block files,
a class to control how bitcoinj uses threads and misc other utility classes that don't fit anywhere else.
|
| org.bitcoinj.wallet |
Classes that support the
Wallet , which knows how to find and save transactions relevant to
a set of keys or scripts, calculate balances, and spend money: the wallet has many features and can be extended
in various ways, please refer to the website for documentation on how to use it. |
| Modifier and Type | Field and Description |
|---|---|
protected NetworkParameters |
Message.params |
protected NetworkParameters |
AbstractBlockChain.params |
protected NetworkParameters |
CheckpointManager.params |
protected NetworkParameters |
PeerGroup.params |
| Modifier and Type | Method and Description |
|---|---|
static NetworkParameters |
NetworkParameters.fromID(String id)
Returns the network parameters for the given string ID or NULL if not recognized.
|
static NetworkParameters |
NetworkParameters.fromPmtProtocolID(String pmtProtocolId)
Returns the network parameters for the given string paymentProtocolID or NULL if not recognized.
|
NetworkParameters |
BitcoinSerializer.getParameters()
Get the network parameters for this serializer.
|
NetworkParameters |
Address.getParameters()
Examines the version byte of the address and attempts to find a matching NetworkParameters.
|
static NetworkParameters |
Address.getParametersFromAddress(String address)
Given an address, examines the version byte and attempts to find a matching NetworkParameters.
|
NetworkParameters |
Message.getParams()
Network parameters this message was created with.
|
NetworkParameters |
UTXOProvider.getParams()
The
NetworkParameters of this provider. |
NetworkParameters |
Context.getParams()
Returns the
NetworkParameters specified when this context was (auto) created. |
static NetworkParameters |
NetworkParameters.prodNet()
Deprecated.
|
static NetworkParameters |
NetworkParameters.regTests()
Deprecated.
|
static NetworkParameters |
NetworkParameters.testNet()
Deprecated.
|
static NetworkParameters |
NetworkParameters.testNet2()
Deprecated.
|
static NetworkParameters |
NetworkParameters.testNet3()
Deprecated.
|
static NetworkParameters |
NetworkParameters.unitTests()
Deprecated.
|
| Modifier and Type | Method and Description |
|---|---|
static PartialMerkleTree |
PartialMerkleTree.buildFromLeaves(NetworkParameters params,
byte[] includeBits,
List<Sha256Hash> allLeafHashes)
Calculates a PMT given the list of leaf hashes and which leaves need to be included.
|
static void |
CheckpointManager.checkpoint(NetworkParameters params,
InputStream checkpoints,
BlockStore store,
long time)
Convenience method that creates a CheckpointManager, loads the given data, gets the checkpoint for the given
time, then inserts it into the store and sets that to be the chain head.
|
static StoredBlock |
StoredBlock.deserializeCompact(NetworkParameters params,
ByteBuffer buffer)
De-serializes the stored block from a custom packed format.
|
void |
ECKey.formatKeyWithAddress(boolean includePrivateKeys,
StringBuilder builder,
NetworkParameters params) |
static DumpedPrivateKey |
DumpedPrivateKey.fromBase58(NetworkParameters params,
String base58)
Construct a private key from its Base58 representation.
|
static Address |
Address.fromBase58(NetworkParameters params,
String base58)
Construct an address from its Base58 representation.
|
static Address |
Address.fromP2SHHash(NetworkParameters params,
byte[] hash160)
Returns an Address that represents the given P2SH script hash.
|
static Address |
Address.fromP2SHScript(NetworkParameters params,
Script scriptPubKey)
Returns an Address that represents the script hash extracted from the given scriptPubKey
|
Address |
TransactionOutput.getAddressFromP2PKHScript(NetworkParameters networkParameters)
If the output script pays to an address as in
P2PKH, return the address of the receiver, i.e., a base58 encoded hash of the public key in the script.
|
Address |
TransactionOutput.getAddressFromP2SH(NetworkParameters networkParameters)
If the output script pays to a redeem script, return the address of the redeem script as described by,
i.e., a base58 encoding of [one-byte version][20-byte hash][4-byte checksum], where the 20-byte hash refers to
the redeem script.
|
static Context |
Context.getOrCreate(NetworkParameters params) |
String |
ECKey.getPrivateKeyAsWiF(NetworkParameters params) |
DumpedPrivateKey |
ECKey.getPrivateKeyEncoded(NetworkParameters params)
Exports the private key in the form used by Bitcoin Core's "dumpprivkey" and "importprivkey" commands.
|
static PeerAddress |
PeerAddress.localhost(NetworkParameters params) |
static PeerGroup |
PeerGroup.newWithTor(NetworkParameters params,
AbstractBlockChain chain,
com.subgraph.orchid.TorClient torClient)
|
static InputStream |
CheckpointManager.openStream(NetworkParameters params)
Returns a checkpoints stream pointing to inside the bitcoinj JAR
|
Address |
ECKey.toAddress(NetworkParameters params)
Returns the address that corresponds to the public part of this ECKey.
|
String |
ECKey.toStringWithPrivate(NetworkParameters params)
Produce a string rendering of the ECKey INCLUDING the private key.
|
| Constructor and Description |
|---|
AbstractBlockChain(NetworkParameters params,
List<? extends Wallet> transactionReceivedListeners,
BlockStore blockStore)
|
Address(NetworkParameters params,
byte[] hash160)
Construct an address from parameters and the hash160 form.
|
Address(NetworkParameters params,
int version,
byte[] hash160)
Construct an address from parameters, the address version, and the hash160 form.
|
Address(NetworkParameters params,
String address)
Deprecated.
|
AlertMessage(NetworkParameters params,
byte[] payloadBytes) |
BitcoinSerializer(NetworkParameters params,
boolean parseRetain)
Constructs a BitcoinSerializer with the given behavior.
|
Block(NetworkParameters params,
byte[] payloadBytes)
Deprecated.
Use
MessageSerializer.makeBlock(byte[]) instead. |
Block(NetworkParameters params,
byte[] payloadBytes,
int offset,
Message parent,
MessageSerializer serializer,
int length)
Construct a block object from the Bitcoin wire format.
|
Block(NetworkParameters params,
byte[] payloadBytes,
int offset,
MessageSerializer serializer,
int length)
Construct a block object from the Bitcoin wire format.
|
Block(NetworkParameters params,
byte[] payloadBytes,
MessageSerializer serializer,
int length)
Construct a block object from the Bitcoin wire format.
|
Block(NetworkParameters params,
long version,
Sha256Hash prevBlockHash,
Sha256Hash merkleRoot,
long time,
long difficultyTarget,
long nonce,
List<Transaction> transactions)
Construct a block initialized with all the given fields.
|
BlockChain(NetworkParameters params,
BlockStore blockStore)
|
BlockChain(NetworkParameters params,
List<? extends Wallet> wallets,
BlockStore blockStore)
|
BlockChain(NetworkParameters params,
Wallet wallet,
BlockStore blockStore)
|
BloomFilter(NetworkParameters params,
byte[] payloadBytes)
Construct a BloomFilter by deserializing payloadBytes
|
CheckpointManager(NetworkParameters params,
InputStream inputStream)
Loads the checkpoints from the given stream
|
ChildMessage(NetworkParameters params) |
ChildMessage(NetworkParameters params,
byte[] payload,
int offset) |
ChildMessage(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion) |
ChildMessage(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion,
Message parent,
MessageSerializer setSerializer,
int length) |
ChildMessage(NetworkParameters params,
byte[] payload,
int offset,
Message parent,
MessageSerializer setSerializer,
int length) |
Context(NetworkParameters params)
Creates a new context object.
|
Context(NetworkParameters params,
int eventHorizon,
Coin feePerKb,
boolean ensureMinRequiredFee)
Creates a new custom context object.
|
DumpedPrivateKey(NetworkParameters params,
String encoded)
Deprecated.
|
EmptyMessage(NetworkParameters params) |
EmptyMessage(NetworkParameters params,
byte[] payload,
int offset) |
FilteredBlock(NetworkParameters params,
Block header,
PartialMerkleTree pmt) |
FilteredBlock(NetworkParameters params,
byte[] payloadBytes) |
FullPrunedBlockChain(NetworkParameters params,
FullPrunedBlockStore blockStore)
|
FullPrunedBlockChain(NetworkParameters params,
List<Wallet> listeners,
FullPrunedBlockStore blockStore)
|
FullPrunedBlockChain(NetworkParameters params,
Wallet wallet,
FullPrunedBlockStore blockStore)
Constructs a block chain connected to the given wallet and store.
|
GetAddrMessage(NetworkParameters params) |
GetBlocksMessage(NetworkParameters params,
byte[] payload) |
GetBlocksMessage(NetworkParameters params,
List<Sha256Hash> locator,
Sha256Hash stopHash) |
GetDataMessage(NetworkParameters params) |
GetDataMessage(NetworkParameters params,
byte[] payloadBytes) |
GetDataMessage(NetworkParameters params,
byte[] payload,
MessageSerializer serializer,
int length)
Deserializes a 'getdata' message.
|
GetHeadersMessage(NetworkParameters params,
byte[] payload) |
GetHeadersMessage(NetworkParameters params,
List<Sha256Hash> locator,
Sha256Hash stopHash) |
GetUTXOsMessage(NetworkParameters params,
byte[] payloadBytes) |
GetUTXOsMessage(NetworkParameters params,
List<TransactionOutPoint> outPoints,
boolean includeMempool) |
HeadersMessage(NetworkParameters params,
Block... headers) |
HeadersMessage(NetworkParameters params,
byte[] payload) |
HeadersMessage(NetworkParameters params,
List<Block> headers) |
InventoryMessage(NetworkParameters params) |
InventoryMessage(NetworkParameters params,
byte[] bytes) |
InventoryMessage(NetworkParameters params,
byte[] payload,
MessageSerializer serializer,
int length)
Deserializes an 'inv' message.
|
ListMessage(NetworkParameters params) |
ListMessage(NetworkParameters params,
byte[] bytes) |
ListMessage(NetworkParameters params,
byte[] payload,
MessageSerializer serializer,
int length) |
Message(NetworkParameters params) |
Message(NetworkParameters params,
byte[] payload,
int offset) |
Message(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion) |
Message(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion,
MessageSerializer serializer,
int length) |
Message(NetworkParameters params,
byte[] payload,
int offset,
MessageSerializer serializer,
int length) |
NotFoundMessage(NetworkParameters params) |
NotFoundMessage(NetworkParameters params,
byte[] payloadBytes) |
NotFoundMessage(NetworkParameters params,
List<InventoryItem> items) |
PartialMerkleTree(NetworkParameters params,
byte[] payloadBytes,
int offset) |
PartialMerkleTree(NetworkParameters params,
byte[] bits,
List<Sha256Hash> hashes,
int origTxCount)
Constructs a new PMT with the given bit set (little endian) and the raw list of hashes including internal hashes,
taking ownership of the list.
|
Peer(NetworkParameters params,
AbstractBlockChain blockChain,
PeerAddress peerAddress,
String thisSoftwareName,
String thisSoftwareVersion)
Construct a peer that reads/writes from the given chain.
|
Peer(NetworkParameters params,
VersionMessage ver,
AbstractBlockChain chain,
PeerAddress remoteAddress)
Construct a peer that reads/writes from the given block chain.
|
Peer(NetworkParameters params,
VersionMessage ver,
PeerAddress remoteAddress,
AbstractBlockChain chain)
Construct a peer that reads/writes from the given block chain.
|
Peer(NetworkParameters params,
VersionMessage ver,
PeerAddress remoteAddress,
AbstractBlockChain chain,
int downloadTxDependencyDepth)
Construct a peer that reads/writes from the given block chain.
|
PeerAddress(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion)
Construct a peer address from a serialized payload.
|
PeerAddress(NetworkParameters params,
byte[] payload,
int offset,
int protocolVersion,
Message parent,
MessageSerializer serializer)
Construct a peer address from a serialized payload.
|
PeerAddress(NetworkParameters params,
InetAddress addr)
Constructs a peer address from the given IP address.
|
PeerAddress(NetworkParameters params,
InetAddress addr,
int port)
Constructs a peer address from the given IP address and port.
|
PeerAddress(NetworkParameters params,
InetSocketAddress addr)
Constructs a peer address from an
InetSocketAddress . |
PeerAddress(NetworkParameters params,
String hostname,
int port)
Constructs a peer address from a stringified hostname+port.
|
PeerGroup(NetworkParameters params)
|
PeerGroup(NetworkParameters params,
AbstractBlockChain chain)
|
PeerGroup(NetworkParameters params,
AbstractBlockChain chain,
ClientConnectionManager connectionManager)
|
PeerSocketHandler(NetworkParameters params,
InetSocketAddress remoteIp) |
PeerSocketHandler(NetworkParameters params,
PeerAddress peerAddress) |
Ping(NetworkParameters params,
byte[] payloadBytes) |
Pong(NetworkParameters params,
byte[] payloadBytes) |
RejectMessage(NetworkParameters params,
byte[] payload) |
RejectMessage(NetworkParameters params,
RejectMessage.RejectCode code,
Sha256Hash hash,
String message,
String reason)
Constructs a reject message that fingers the object with the given hash as rejected for the given reason.
|
Transaction(NetworkParameters params) |
Transaction(NetworkParameters params,
byte[] payloadBytes)
Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
|
Transaction(NetworkParameters params,
byte[] payload,
int offset)
Creates a transaction by reading payload starting from offset bytes in.
|
Transaction(NetworkParameters params,
byte[] payload,
int offset,
Message parent,
MessageSerializer setSerializer,
int length)
Creates a transaction by reading payload starting from offset bytes in.
|
Transaction(NetworkParameters params,
byte[] payload,
Message parent,
MessageSerializer setSerializer,
int length)
Creates a transaction by reading payload.
|
TransactionInput(NetworkParameters params,
Transaction parentTransaction,
byte[] scriptBytes)
Creates an input that connects to nothing - used only in creation of coinbase transactions.
|
TransactionInput(NetworkParameters params,
Transaction parentTransaction,
byte[] payload,
int offset)
Deserializes an input message.
|
TransactionInput(NetworkParameters params,
Transaction parentTransaction,
byte[] payload,
int offset,
MessageSerializer serializer)
Deserializes an input message.
|
TransactionInput(NetworkParameters params,
Transaction parentTransaction,
byte[] scriptBytes,
TransactionOutPoint outpoint) |
TransactionInput(NetworkParameters params,
Transaction parentTransaction,
byte[] scriptBytes,
TransactionOutPoint outpoint,
Coin value) |
TransactionOutPoint(NetworkParameters params,
byte[] payload,
int offset)
/**
Deserializes the message.
|
TransactionOutPoint(NetworkParameters params,
byte[] payload,
int offset,
Message parent,
MessageSerializer serializer)
Deserializes the message.
|
TransactionOutPoint(NetworkParameters params,
long index,
Sha256Hash hash) |
TransactionOutPoint(NetworkParameters params,
long index,
Transaction fromTx) |
TransactionOutPoint(NetworkParameters params,
TransactionOutput connectedOutput) |
TransactionOutput(NetworkParameters params,
Transaction parent,
byte[] payload,
int offset)
Deserializes a transaction output message.
|
TransactionOutput(NetworkParameters params,
Transaction parent,
byte[] payload,
int offset,
MessageSerializer serializer)
Deserializes a transaction output message.
|
TransactionOutput(NetworkParameters params,
Transaction parent,
Coin value,
Address to)
Creates an output that sends 'value' to the given address (public key hash).
|
TransactionOutput(NetworkParameters params,
Transaction parent,
Coin value,
byte[] scriptBytes) |
TransactionOutput(NetworkParameters params,
Transaction parent,
Coin value,
ECKey to)
Creates an output that sends 'value' to the given public key using a simple CHECKSIG script (no addresses).
|
UnknownMessage(NetworkParameters params,
String name,
byte[] payloadBytes) |
UTXOsMessage(NetworkParameters params,
byte[] payloadBytes) |
UTXOsMessage(NetworkParameters params,
List<TransactionOutput> outputs,
long[] heights,
Sha256Hash chainHead,
long height)
Provide an array of output objects, with nulls indicating that the output was missing.
|
VersionAck(NetworkParameters params,
byte[] payload) |
VersionMessage(NetworkParameters params,
byte[] payload) |
VersionMessage(NetworkParameters params,
int newBestHeight) |
| Modifier and Type | Field and Description |
|---|---|
NetworkParameters |
BIP38PrivateKey.params |
| Modifier and Type | Method and Description |
|---|---|
static DeterministicKey |
DeterministicKey.deserialize(NetworkParameters params,
byte[] serializedKey)
Deserialize an HD Key with no parent
|
static DeterministicKey |
DeterministicKey.deserialize(NetworkParameters params,
byte[] serializedKey,
DeterministicKey parent)
Deserialize an HD Key.
|
static DeterministicKey |
DeterministicKey.deserializeB58(DeterministicKey parent,
String base58,
NetworkParameters params)
Deserialize a base-58-encoded HD Key.
|
static DeterministicKey |
DeterministicKey.deserializeB58(String base58,
NetworkParameters params)
Deserialize a base-58-encoded HD Key with no parent
|
void |
DeterministicKey.formatKeyWithAddress(boolean includePrivateKeys,
StringBuilder builder,
NetworkParameters params) |
static BIP38PrivateKey |
BIP38PrivateKey.fromBase58(NetworkParameters params,
String base58)
Construct a password-protected private key from its Base58 representation.
|
byte[] |
DeterministicKey.serializePrivate(NetworkParameters params) |
String |
DeterministicKey.serializePrivB58(NetworkParameters params) |
String |
DeterministicKey.serializePubB58(NetworkParameters params) |
byte[] |
DeterministicKey.serializePublic(NetworkParameters params) |
| Constructor and Description |
|---|
BIP38PrivateKey(NetworkParameters params,
String encoded)
Deprecated.
|
| Modifier and Type | Field and Description |
|---|---|
protected NetworkParameters |
WalletAppKit.params |
| Modifier and Type | Method and Description |
|---|---|
NetworkParameters |
WalletAppKit.params() |
| Constructor and Description |
|---|
WalletAppKit(NetworkParameters params,
File directory,
String filePrefix)
Creates a new WalletAppKit, with a newly created
Context . |
| Modifier and Type | Field and Description |
|---|---|
protected NetworkParameters |
MultiplexingDiscovery.netParams |
| Modifier and Type | Method and Description |
|---|---|
static MultiplexingDiscovery |
MultiplexingDiscovery.forServices(NetworkParameters params,
long services)
Builds a suitable set of peer discoveries.
|
| Constructor and Description |
|---|
DnsDiscovery(NetworkParameters netParams)
Supports finding peers through DNS A records.
|
DnsDiscovery(String[] dnsSeeds,
NetworkParameters params)
Supports finding peers through DNS A records.
|
DnsSeedDiscovery(NetworkParameters params,
String hostname) |
HttpDiscovery(NetworkParameters params,
HttpDiscovery.Details details)
Constructs a discovery object that will read data from the given HTTP[S] URI and, if a public key is provided,
will check the signature using that key.
|
HttpDiscovery(NetworkParameters params,
HttpDiscovery.Details details,
com.squareup.okhttp.OkHttpClient client) |
HttpDiscovery(NetworkParameters params,
URI uri,
ECKey pubkey)
Constructs a discovery object that will read data from the given HTTP[S] URI and, if a public key is provided,
will check the signature using that key.
|
MultiplexingDiscovery(NetworkParameters params,
List<PeerDiscovery> seeds)
Will query the given seeds in parallel before producing a merged response.
|
SeedPeers(int[] seedAddrs,
NetworkParameters params)
Supports finding peers by IP addresses
|
SeedPeers(NetworkParameters params)
Supports finding peers by IP addresses
|
TorDiscovery(NetworkParameters netParams,
com.subgraph.orchid.TorClient torClient)
Supports finding peers through Tor.
|
TorDiscovery(String[] hostNames,
NetworkParameters netParams,
com.subgraph.orchid.TorClient torClient)
Supports finding peers through Tor.
|
| Modifier and Type | Class and Description |
|---|---|
class |
AbstractBitcoinNetParams
Parameters for Bitcoin-like networks.
|
class |
MainNetParams
Parameters for the main production network on which people trade goods and services.
|
class |
RegTestParams
Network parameters for the regression test mode of bitcoind in which all blocks are trivially solvable.
|
class |
TestNet2Params
Parameters for the old version 2 testnet.
|
class |
TestNet3Params
Parameters for the testnet, a separate public instance of Bitcoin that has relaxed rules suitable for development
and testing of applications and new Bitcoin versions.
|
class |
UnitTestParams
Network parameters used by the bitcoinj unit tests (and potentially your own).
|
| Modifier and Type | Method and Description |
|---|---|
static Set<? extends NetworkParameters> |
Networks.get() |
| Modifier and Type | Method and Description |
|---|---|
static void |
Networks.register(NetworkParameters network) |
static void |
Networks.unregister(NetworkParameters network) |
| Modifier and Type | Method and Description |
|---|---|
static void |
Networks.register(Collection<? extends NetworkParameters> networks) |
| Modifier and Type | Method and Description |
|---|---|
NetworkParameters |
PaymentSession.getNetworkParameters()
Gets the params as read from the PaymentRequest.network field: main is the default if missing.
|
| Modifier and Type | Method and Description |
|---|---|
static Protos.PaymentRequest.Builder |
PaymentProtocol.createPaymentRequest(NetworkParameters params,
Coin amount,
Address toAddress,
String memo,
String paymentUrl,
byte[] merchantData)
Create a payment request with one standard pay to address output.
|
static Protos.PaymentRequest.Builder |
PaymentProtocol.createPaymentRequest(NetworkParameters params,
List<Protos.Output> outputs,
String memo,
String paymentUrl,
byte[] merchantData)
Create a payment request.
|
static List<Transaction> |
PaymentProtocol.parseTransactionsFromPaymentMessage(NetworkParameters params,
Protos.Payment paymentMessage)
Parse transactions from payment message.
|
| Modifier and Type | Method and Description |
|---|---|
Address |
Script.getFromAddress(NetworkParameters params)
Deprecated.
|
Address |
Script.getToAddress(NetworkParameters params)
Gets the destination address from this script, if it's in the required form (see getPubKey).
|
Address |
Script.getToAddress(NetworkParameters params,
boolean forcePayToPubKey)
Gets the destination address from this script, if it's in the required form (see getPubKey).
|
| Modifier and Type | Field and Description |
|---|---|
protected NetworkParameters |
SPVBlockStore.params |
protected NetworkParameters |
DatabaseFullPrunedBlockStore.params |
| Modifier and Type | Method and Description |
|---|---|
NetworkParameters |
MemoryBlockStore.getParams() |
NetworkParameters |
LevelDBBlockStore.getParams() |
NetworkParameters |
LevelDBFullPrunedBlockStore.getParams() |
NetworkParameters |
BlockStore.getParams()
Get the
NetworkParameters of this store. |
NetworkParameters |
MemoryFullPrunedBlockStore.getParams() |
NetworkParameters |
SPVBlockStore.getParams() |
NetworkParameters |
DatabaseFullPrunedBlockStore.getParams() |
| Constructor and Description |
|---|
DatabaseFullPrunedBlockStore(NetworkParameters params,
String connectionURL,
int fullStoreDepth,
String username,
String password,
String schemaName)
Create a new DatabaseFullPrunedBlockStore, using the full connection URL instead of a hostname and password,
and optionally allowing a schema to be specified.
|
H2FullPrunedBlockStore(NetworkParameters params,
String dbName,
int fullStoreDepth)
Creates a new H2FullPrunedBlockStore
|
H2FullPrunedBlockStore(NetworkParameters params,
String dbName,
int fullStoreDepth,
int cacheSize)
Creates a new H2FullPrunedBlockStore with the given cache size
|
H2FullPrunedBlockStore(NetworkParameters params,
String dbName,
String username,
String password,
int fullStoreDepth)
Creates a new H2FullPrunedBlockStore, with given credentials for H2 database
|
LevelDBFullPrunedBlockStore(NetworkParameters params,
String filename,
int blockCount) |
LevelDBFullPrunedBlockStore(NetworkParameters params,
String filename,
int blockCount,
long leveldbReadCache,
int leveldbWriteCache,
int openOutCache,
boolean instrument,
int exitBlock) |
MemoryBlockStore(NetworkParameters params) |
MemoryFullPrunedBlockStore(NetworkParameters params,
int fullStoreDepth)
Set up the MemoryFullPrunedBlockStore
|
MySQLFullPrunedBlockStore(NetworkParameters params,
int fullStoreDepth,
String hostname,
String dbName,
String username,
String password)
Creates a new MySQLFullPrunedBlockStore.
|
PostgresFullPrunedBlockStore(NetworkParameters params,
int fullStoreDepth,
String hostname,
String dbName,
String username,
String password)
Creates a new PostgresFullPrunedBlockStore.
|
PostgresFullPrunedBlockStore(NetworkParameters params,
int fullStoreDepth,
String hostname,
String dbName,
String username,
String password,
String schemaName)
Create a new PostgresFullPrunedBlockStore, storing the tables in the schema specified.
|
SPVBlockStore(NetworkParameters params,
File file)
Creates and initializes an SPV block store.
|
| Modifier and Type | Method and Description |
|---|---|
static String |
BitcoinURI.convertToBitcoinURI(NetworkParameters params,
String address,
Coin amount,
String label,
String message)
Simple Bitcoin URI builder using known good fields.
|
| Constructor and Description |
|---|
BitcoinURI(NetworkParameters params,
String input)
Constructs a new object by trying to parse the input as a valid Bitcoin URI.
|
| Constructor and Description |
|---|
BlockFileLoader(NetworkParameters params,
List<File> files) |
VersionTally(NetworkParameters params) |
| Modifier and Type | Field and Description |
|---|---|
protected NetworkParameters |
Wallet.params |
| Modifier and Type | Method and Description |
|---|---|
NetworkParameters |
Wallet.getNetworkParameters() |
NetworkParameters |
Wallet.getParams()
Returns the parameters this wallet was created with.
|
| Modifier and Type | Method and Description |
|---|---|
Wallet |
WalletProtobufSerializer.WalletFactory.create(NetworkParameters params,
KeyChainGroup keyChainGroup) |
protected void |
MarriedKeyChain.formatAddresses(boolean includePrivateKeys,
NetworkParameters params,
StringBuilder builder2) |
protected void |
DeterministicKeyChain.formatAddresses(boolean includePrivateKeys,
NetworkParameters params,
StringBuilder builder2) |
static Wallet |
Wallet.fromKeys(NetworkParameters params,
List<ECKey> keys)
Creates a wallet containing a given set of keys.
|
static KeyChainGroup |
KeyChainGroup.fromProtobufEncrypted(NetworkParameters params,
List<Protos.Key> keys,
KeyCrypter crypter,
KeyChainFactory factory) |
static KeyChainGroup |
KeyChainGroup.fromProtobufUnencrypted(NetworkParameters params,
List<Protos.Key> keys,
KeyChainFactory factory) |
static Wallet |
Wallet.fromSeed(NetworkParameters params,
DeterministicSeed seed) |
static Wallet |
Wallet.fromWatchingKey(NetworkParameters params,
DeterministicKey watchKey)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.
|
static Wallet |
Wallet.fromWatchingKeyB58(NetworkParameters params,
String watchKeyB58,
long creationTimeSeconds)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.
|
Wallet |
WalletProtobufSerializer.readWallet(NetworkParameters params,
WalletExtension[] extensions,
Protos.Wallet walletProto)
Loads wallet data from the given protocol buffer and inserts it into the given Wallet object.
|
Wallet |
WalletProtobufSerializer.readWallet(NetworkParameters params,
WalletExtension[] extensions,
Protos.Wallet walletProto,
boolean forceReset)
Loads wallet data from the given protocol buffer and inserts it into the given Wallet object.
|
static SendRequest |
SendRequest.to(NetworkParameters params,
ECKey destination,
Coin value)
Creates a new SendRequest to the given pubkey for the given value.
|
static SendRequest |
SendRequest.toCLTVPaymentChannel(NetworkParameters params,
BigInteger time,
ECKey from,
ECKey to,
Coin value) |
static SendRequest |
SendRequest.toCLTVPaymentChannel(NetworkParameters params,
Date releaseTime,
ECKey from,
ECKey to,
Coin value) |
static SendRequest |
SendRequest.toCLTVPaymentChannel(NetworkParameters params,
int releaseBlock,
ECKey from,
ECKey to,
Coin value) |
String |
DeterministicKeyChain.toString(boolean includePrivateKeys,
NetworkParameters params) |
| Constructor and Description |
|---|
KeyChainGroup(NetworkParameters params)
Creates a keychain group with no basic chain, and a single, lazily created HD chain.
|
KeyChainGroup(NetworkParameters params,
DeterministicKey watchKey)
Creates a keychain group with no basic chain, and an HD chain that is watching the given watching key.
|
KeyChainGroup(NetworkParameters params,
DeterministicSeed seed)
Creates a keychain group with no basic chain, and an HD chain initialized from the given seed.
|
Wallet(NetworkParameters params)
Creates a new, empty wallet with a randomly chosen seed and no transactions.
|
Wallet(NetworkParameters params,
KeyChainGroup keyChainGroup) |
Copyright © 2022. All rights reserved.


{# Copyright 2013 Dev in Cachu authors. All rights reserved. #} {# Use of this source code is governed by a BSD-style #} {# license that can be found in the LICENSE file. #} {% load compress %}


Section 51 WHERE Statements
#!pip install ipython-sql
!git clone https://github.com/thomasnield/oreilly_getting_started_with_sql.git
Cloning into 'oreilly_getting_started_with_sql'...
remote: Enumerating objects: 3, done.[K
remote: Counting objects: 100% (3/3), done.[K
remote: Compressing objects: 100% (3/3), done.[K
remote: Total 60 (delta 0), reused 0 (delta 0), pack-reused 57
Unpacking objects: 100% (60/60), done.
%load_ext sql
The sql extension is already loaded. To reload it, use:
%reload_ext sql
%sql sqlite:///oreilly_getting_started_with_sql/weather_stations.db
'Connected: @oreilly_getting_started_with_sql/weather_stations.db'
51.1 WHERE
Over the next few weeks, we will be adding more functionalities to the SELECT statement. A very common task when working with data is filtering for records based on criteria, which can be done with a WHERE statement.
We will be learning more functions and using them in the WHERE clause, but we can also use them in SELECT statements, as discussed in the previous chapter. For the most part, expressions and functions can be used in any part of a SQL statement.
51.2 Filtering Records
%%sql
* FROM station_data; SELECT
%%sql
* FROM station_data
SELECT = 2010; WHERE year
Conversely, you can use != or <> to get everything but 2010.
%%sql
* FROM station_data
SELECT != 2010; WHERE year
We can also qualify inclusive ranges using a BETWEEN statement:
%%sql
* FROM station_data
SELECT 2005 AND 2010; WHERE year BETWEEN
51.3 AND, OR, and IN Statements
A BETWEEN can alternatively be expressed using greater than or equal to and less than or equal to expressions and an AND statement.
%%sql
* FROM station_data
SELECT >= 2005 AND year <= 2010; WHERE year
If we wanted everything between 2005 and 2010 exclusively — i.e., not including those two years — we would just get rid of the = characters. Only 2006, 2007, 2008, and 2009 would then qualify:
%%sql
* FROM station_data
SELECT > 2005 AND year < 2010; WHERE year
We also have the option of using OR. In an OR statement, at least one of the criteria must be true for the record to qualify. If we wanted only records with months 3, 6, 9, or 12, we could use an OR to accomplish that:
%%sql
* FROM station_data
SELECT = 3
WHERE MONTH = 6
OR MONTH = 9
OR MONTH = 12; OR MONTH
A more effient way is to use the IN statement.
%%sql
* FROM station_data
SELECT 3,6,9,12); WHERE MONTH IN (
If we want everything except 3,6,9,12, we use the NOT IN:
%%sql
* FROM station_data
SELECT 3,6,9,12); WHERE MONTH NOT IN (
We could also leverage some logic:
%%sql
* FROM station_data
SELECT % 3 = 0; WHERE MONTH
51.4 Using Where on Text
The rules for qualifying text fields follow the same structure, although there are subtle differences. You can use =, AND, OR, and IN statements with text. However, when using text, you must wrap literals (or text values you specify) in single quotes. For example, if you wanted to filter for a specific report_code, you could run this query:
%%sql
* FROM station_data
SELECT = '513A63'; WHERE report_code
* sqlite:///oreilly_getting_started_with_sql/weather_stations.db
Done.
| station_number | report_code | year | month | day | dew_point | station_pressure | visibility | wind_speed | temperature | precipitation | snow_depth | fog | rain | hail | thunder | tornado |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 702223 | 513A63 | 2010 | 1 | 22 | -23.1 | None | 10 | 0.8 | -15.6 | 0 | None | 0 | 0 | 0 | 0 | 0 |
This single-quote rule applies to all text operations, including this IN operation:
%%sql
* FROM station_data
SELECT '513A63','1F8A7B','EF616A'); WHERE report_code IN (
* sqlite:///oreilly_getting_started_with_sql/weather_stations.db
Done.
| station_number | report_code | year | month | day | dew_point | station_pressure | visibility | wind_speed | temperature | precipitation | snow_depth | fog | rain | hail | thunder | tornado |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 470160 | EF616A | 1967 | 7 | 29 | 65.6 | None | 9.2 | 1.2 | 72.4 | 0.04 | None | 0 | 0 | 0 | 0 | 0 |
| 821930 | 1F8A7B | 1953 | 6 | 18 | 72.8 | 1007.1 | 12.4 | 3.6 | 81.3 | 0 | None | 0 | 0 | 0 | 0 | 0 |
| 702223 | 513A63 | 2010 | 1 | 22 | -23.1 | None | 10 | 0.8 | -15.6 | 0 | None | 0 | 0 | 0 | 0 | 0 |
The length function will count the number of characters for a given value:
%%sql
* FROM station_data
SELECT != 6; WHERE length(report_code)
* sqlite:///oreilly_getting_started_with_sql/weather_stations.db
Done.
| station_number | report_code | year | month | day | dew_point | station_pressure | visibility | wind_speed | temperature | precipitation | snow_depth | fog | rain | hail | thunder | tornado |
|---|
Another common operation is to use wildcards with a LIKE expression, where % is any number of characters and _ is any single character. Any other character is interpreted literally. So, if you wanted to find all report codes that start with the letter “A,” you would run this statement to find “A” followed by any characters:
%%sql
* FROM station_data
SELECT 'A%'; WHERE report_code LIKE
If you wanted to find all report codes that have a “B” as the first character and a “C” as the third character, you would specify an underscore (_) for the second position, and follow with any number of characters after the “C”:
%%sql
* FROM station_data
SELECT 'B_C%' WHERE report_code LIKE
51.5 WHERE on Booleans
%%sql
* FROM station_data
SELECT = 1 AND hail = 1; WHERE tornado
SQLite only supports using 1 for true and 0 for false.
%%sql
* FRPM station_data
SELECT =0 AND hail = 1; WHERE tornado
51.6 Handling NULL
Some columns such as station_pressure
and snow_depth
, have null values. A null is a value that has no value. It is the complete absence of any content.
%%sql
* FROM station_data
SELECT ; WHERE snow_depth IS NULL
Nulls can be hard to handle when composing WHERE statements. I fyou wanted to query all records where `precipitation is less than 0.5, you could write:
%%sql
* FROM station_data
SELECT <= 0.5; WHERE precipitation
But you must consider the null values. If you wanted the nulls to be included you need to use an OR statment.
%%sql
* FROM station_data
SELECT <= 0.5; WHERE precipitation IS NULL OR precipitation
A more elegant way is to use coalesce()
. If you wanted nulls to be treated as 0 within our condition, we could coalesce()
the precipitation field to convert null to 0:
%%sql
* FROM station_data
SELECT 0) <= 0.5; WHERE coalesce(precipitation,
51.7 Grouping Conditions
When chaining AND and OR together, it is good to group them.
Make sure that you organize each set of conditions between each OR in a way that groups related conditions.
%%sql
* FROM station_data
SELECT = 1 AND temperature <=32
WHERE rain >0; OR snow_depth
While this technically works, there is a degree of ambiguity.
%%sql
* FROM station_data
SELECT =1 AND temperature <=32)
WHERE (rain>0; OR snow_depth
Here we group the expression within paretheses so it is calculated as a single unit, and temperature is not mixed up with the OR operator and accidentally mangled with the snow_depth.


{{extend 'zlayout.html'}}
* {{=XML(T('Preferences have been updated'))}}. *
{{pass}} {{if request.vars.up_topics_1:}}* {{=XML(T('Profile topics have been updated'))}}. *
{{pass}} {{if request.vars.up_topics_2:}}* {{=XML(T('Bookmarked topics have been updated'))}}. *
{{pass}}


Trolly Poozleh!
Trolly Poozleh!
Click on green squares!
You start with 3 lives. Click on the color of death and you'll lose one!
Start Game
You Win!!!
You are amazing, how do you do it?
Next Level
Game Over!
 Sad.
Start
Score Board
Score 0
Lives 3


Overview
Frontend form validation
Parsley is a javascript form validation library. It helps you provide your users feedback on their form submission before sending it to your server. It saves you bandwidth, server load and it saves time for your user.
Javascript form validation is not necessary, and if used, it does not replace a strong backend server validation.
That's why Parsley is here: to let you define your general form validation, implement it on the backend side, and simply port it frontend-side, with maximum respect to user experience best practices.
Parsley 1.x versions
Parsley's current stable and supported versions are 2.x. If you still use a 1.x version, here is the related doc. But don't forget to upgrade!
Data attributes
Parsley uses a specific DOM API which allows you to configure pretty much everything directly from your DOM, without writing a single javascript configuration line or custom function. Parsley's default DOM API is data-parsley-
. That means that if in config you see a foo
property, it could be set/modified via DOM with data-parsley-foo="value"
.
More on Parsley DOM API
- For composed property names, Parsley uses camelization, like jQuery
$.data()
does. That means thatdata-parsley-composed-property
will correspond in code tocomposedProperty
, and vice versa. - Every property set in DOM will be stored in
this.options
for each Parsley instance. - You can change the DOM API namespace directly in DOM (inception), by doing
data-parsley-namespace="data-my-namespace-"
and then your Parsley DOM attributes will look likedata-my-namespace-property="value"
. - Special chars: if you need to reference names with special characters, like
id="this:is:a:special:id"
, you'll need to use this syntax in the DOM API:data-parsley-errors-container='div[id="this:is:a:special:id"]'
otherwise it won't work.
Configuration
You'll see along this documentation and through examples various available configuration options. You can also view here all of Parsley's default configuration options.
Installation
Basic installation
Parsley relies on jQuery (>= 1.8), and it would need to be included before including Parsley.
Then, you can either use parsley.js
unminified file or parsley.min.js
minified one. These files and other builds (Remote, Extras ..) are available here.
Finally, add data-parsley-validate
to each <form>
you want to be validated.
That would look pretty much like this:

<form data-parsley-validate>
...
</form>
Parsley CSS
Parsley adds many classes and elements in the DOM when it validates. You are strongly encouraged to customize them in your own stylesheets, but here is the "standard" Parsley css file that is used here on the documentation and examples, if you want to use it to bootstrap your projects with Parsley.
Javascript installation
Like for Basic installation, first include jQuery and Parsley. Then, simply use $('#form').parsley(options);
or new Parsley('#form', options);
(where options
is an optional configuration object) to manually bind Parsley to your forms.
That would look pretty much like this:

<form id="form">
...
</form>

Do not add data-parsley-validate
to your forms
Please be aware that Parsley looks at all data-parsley-validate
occurrences in DOM on document load and automatically binds them if valid.
Once a form or field instance is bound by Parsley, default instantiation options cannot be easily updated, only the ones defined in the DOM would work. Which means that if this DOM validation attribute is present, doing $('#form').parsley(options);
would just return the automatically bound instance, and not the one you would expect with the options
you wanted to set.
Localization
Parsley comes with various error messages for its built-in validators. They are shipped in English by default, but many other languages are available, thanks to the awesome international Parsley community. See the available localizations here.
To load a different locale and its messages, you have two possibilities:
-
Load your needed localization before parsley, then select the one you need once Parsley is loaded and if you want to switch from the English default. In this example, we'll load both French and Italian translations, and use French:

-
Load your needed localization after parsley. The last loaded file will automatically set the messages locale for ParsleyValidator. In this example, we'll load both French and Italian translations, and use Italian:

Plugins
Parsley strives to be highly decoupled and modular. It uses events and inheritance, that allows various plugins.
Current available plugins are:
- Parsley Remote: provides an ajax validator and asynchronous validation
- Parsley Extras: provides some extras and useful validators
Usage
Overview
Parsley is a decoupled library that uses different classes to do the heavy work. You'll see here the different protagonists involved and how you can configure them to fit your desired validation.
| $ API | Return |
|---|---|
$('#existingForm').parsley(options) |
parsleyFormInstance |
$('#existingInput').parsley(options) |
parsleyFieldInstance |
$('#notExistingDOMElement').parsley(options) |
undefined |
$('.multipleElements').parsley(options) |
Array[Instances] |
Look at the source code!
Of course, this documentation tries to be the most exhaustive possible and relatively easy to understand. This documentation also provides the complete annotated source. Please take 5 minutes of your time to have a quick glance at it, and at least understand the architecture (Parsley, ParsleyForm, ParsleyField, ParsleyValidator, ParsleyUI, Utils, Pub/Sub..), it will heavily ease the lecture below.
Form
When doing $('#target').parsley()
or new Parsley('#target');
on a <form id="target">
element, it will bind the whole form and its various inputs and return you a ParsleyForm
instance.
Field options inheritance
All the options you pass through DOM or constructor for a form will be inherited by every ParsleyField
input instance that belongs to the form. This is a handy way to configure all your form's inputs in a row by passing their config through form.
Options
| Property | Default | Description |
|---|---|---|
data-parsley-namespace |
data-parsley- |
Namespace used by Parsley DOM API to bind options from DOM. See more |
data-parsley-validate |
Auto bind your form with Parsley validation on document load. | |
data-parsley-priority-enabled |
true |
Either validate higher priority constraints first and stop on first failure (true ), or validate all constraints simultaneously and show all the failing ones (false ). |
data-parsley-excluded |
input[type=button], input[type=submit], input[type=reset], input[type=hidden] |
Form fields that won't be validated by Parsley. For example, if you want to add disabled and hidden fields to the existing list, use: data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden" |
Methods
| Method | Returns | Description |
|---|---|---|
isValid(group, force) |
boolean |
Returns if the Form is valid or not. Does not affect UI nor fires events. If group is given, it only validates fields that belong to this group. If force is given, it force validates even non required fields (See example) |
validate(group, force) |
boolean
|
Validate form. Prevents submission if not valid. Fires events and affects UI.. You can only validate a certain group of fields by specifying optional group string parameter. If group is given, it only validates fields that belong to this group. If force is given, it force validates even non required fields (See example) |
reset() |
Reset UI for this form and for its fields. | |
destroy() |
Disable and destroy Parsley for this form and its fields. |
UI
See UI for Form section.Field
When doing $('#target').parsley()
or new Parsley('#target');
on a <input id="target">
element (or <textarea>
, <select>
), it will bind the field and return you a ParsleyField
instance. Except for input types radio and checkbox that does not have a name
attribute or a data-parsley-multiple
attribute, they won't be bound (ignored) and would eventually raise a warning in the console.
Options
| Property | Description |
|---|---|
data-parsley-value |
Set a specific field value for Parsley validation, dissociated from the real one. eg: data-parsley-value="foo" |
data-parsley-group |
Assign a group to a field for specific group validation. eg: data-parsley-group="signup" . This way, you could only validate a portion of a form and not all the fields. |
data-parsley-multiple |
You can add this attribute to radio / checkboxes elements like this: data-parsley-multiple="mymultiplelink" to link them together even if they don't share the same name. |
data-parsley-validate-if-empty |
A field is by default not validated if it is not required and empty. By adding data-parsley-validate-if-empty , validation will be done even if field is empty. Useful if you need some custom validators that check something particular when a field is empty. |
data-parsley-trim-value |
Trim field value only for Parsley validation (and not inside the input itself, data sent by your form won't be trimmed). Useful if your backend already does so and if trailing spaces could unnecessarily mess with your validation. Use: data-parsley-trim-value="true" . |
data-parsley-ui-enabled |
If set to false , Parsley will not affect UI for this field. |
data-parsley-errors-messages-disabled |
Add parsley-success and parsley-error classes on field, but no error message. |
Checkbox, radio and select multiple
These fields are a bit different than regular input
, textarea
or simple select
. They need to have either a name
or an id
attribute to be correctly bound and validated by Parsley. Otherwise, they would be ignored and a warning will be put in the console.
Methods
| Method | Returns | Description |
|---|---|---|
isValid(force) |
boolean |
Returns if the Field is valid or not. Does not affect UI nor fires events. If force is given, it forces validation even on non required fields (See example) |
validate(force) |
true if all ok[] if empty optional field[Violation [, Violation..]] if fails
|
Validate Field. Fires events and affects UI. If force is given, force validate even non required fields (See example) |
reset() |
Reset UI for this field. | |
destroy() |
Disable and destroy Parsley for this field. |
UI
See UI for Field section.Global configuration
It is possible to configure Parsley options globally and avoid passing them to each form on your site. To do so, you'll need to define a window.ParsleyConfig = {}
object before calling Parsley file.
For example, if you want to customize the field errors and use div and spans instead of ul and lis, use this snippet:
window.ParsleyConfig = {
errorsWrapper: '

',
errorTemplate: ''
};

Built-in validators
Overview
Parsley 2.x is now based on validator.js that ships commonly used validators and simplifies group and priority validation. That way, Parsley mutualize validators with validators.js and define new ones using the Callback()
Assert.
Use Validator.js in your Parsley projects
Parsley let you use validator.js in window.ParsleyValidator.Validator
Validators list
These validators are shipped in parsley.js
. Have a look at Parsley Remote plugin and Parsley Extras for more validators.
Craft yours!
Of course, Parsley built-in validators are commonly used validators, and you'll need some more that fit your specific forms and validations. That's why Parsley lets you easily create your own validators.
Here again, like localizations, configuring your custom validators and error messages comes with two flavors:
- By registering them in some globals before calling
parsley.js
:<input type="text" data-parsley-multiple="3" /> [...]
- By registering them in
ParsleyValidator
after thatparsley.js
is loaded:<input type="text" data-parsley-multiple="3" /> [...]
UI/UX
Overview
Parsley ships a UI/UX component that is the only one responsible for classes, error messages, focus or trigger events that alter your page. It strives to be the most UX friendly. Here are the main mottos for ParsleyUI:
- Min char validation: Parsley by default does not proceed with field validation when less than 3 chars have been input. Do not assault your users with error messages too soon!.
- One error at the time: constraints are prioritized in Parsley, and if many of them are not met for a field on validation, only show the most important one.
- Quick error removal: when a field is detected and shown as invalid, further checks are done on each keypress to try to quickly remove error messages once the field is ok.
- Control focusing on error: on form submission, the first error field is focused to allow the user to easily start fixing errors.
Naturally, all this is absolutely customizable, you'll see below how to configure your desired UX behavior.
Classes and templates
Parsley adds its share of classes and elements, to ease nice UI validation result display. By default, it will add parsley-success
and parsley-error
classes depending on the validation result, on the input itself for a simple text, textarea and select input, and on the parent for radio / checkboxes inputs.
Customize your classes
You could change these classes' names in configuration, and the class holder element too.
UI for form
| Name | API | Description |
|---|---|---|
| UI Enabled |
data-parsley-ui-enabled="false" |
Activate or deactivate UI |
| Focus |
data-parsley-focus="first" |
Focus failing field on form validation. Possible values: 'first' | 'last' | 'none' |
UI for field
| Name | API | Description |
|---|---|---|
| Trigger |
data-parsley-trigger="change" |
Specify one or many javascript events that will trigger item validation. To set multiple events, separate them by a space data-parsley-trigger="focusin focusout" . See the various events supported by jQuery. |
No focus |
data-parsley-no-focus |
If this field fails, do not focus on it (if first focus strategy is on, next field would be focused, if last strategy is on, previous field would be focused) |
| Validation threshold |
data-parsley-validation-threshold="10" |
Used with trigger option above, for all key - events, do not validate until field have a certain number of characters. Default is 3 |
| Class handler |
data-parsley-class-handler="#element" |
Specify the existing DOM container where ParsleyUI should add error and success classes. It is also possible to configure it with a callback function from javascript, see the annotated source. |
| Errors container |
data-parsley-errors-container="#element" |
Specify the existing DOM container where ParsleyUI should put the errors. It is also possible to configure it with a callback function from javascript, see the annotated source. |
| Error message |
data-parsley-error-message="my message" |
Customize a unique global message for the field. |
| Validator error message |
data-parsley-`constraint`-message="my message" |
Customize the error message for the field constraint. eg: data-parsley-required-message="this field is required" |
UI for javascript
| Name | Method | Description |
|---|---|---|
| Add error |
window.ParsleyUI.addError(parsleyInstance, name, message); |
Manually add an error message. | Update error |
window.ParsleyUI.updateError(parsleyInstance, name, message); |
Manually edit an error message. | Remove error |
window.ParsleyUI.removeError(parsleyInstance, name); |
Manually remove an error message. | Get errors messages |
window.ParsleyUI.getErrorsMessages(parsleyInstance); |
Returns an array of the field errors messages displayed once validated. |
Events
Overview
Parsley comes with a tiny pub/sub mechanism that allows ParsleyUI to work. Further more, it could allow you to do some powerful magic if you listen properly to the right events!
Events List
| Name | Instance | Fired by | Description |
|---|---|---|---|
parsley:form:init |
ParsleyForm |
new Parsley() |
Fired when a Form is bound for the first time. |
parsley:form:validate |
ParsleyForm |
.validate() |
Fired when a form validation is triggered, before its validation. |
parsley:form:validated |
ParsleyForm |
.validate() |
Fired when a form validation is triggered, after its validation. |
parsley:field:init |
ParsleyField |
new Parsley() |
Fired when a Field is bound for the first time. |
parsley:field:validate |
ParsleyField |
.validate() |
Fired when a field validation is triggered, before its validation. |
parsley:field:success |
ParsleyField |
.validate() |
Fired when a field validation succeeds. |
parsley:field:error |
ParsleyField |
.validate() |
Fired when a field validation fails. |
Usage
| Method | Description |
|---|---|
$.listen('name', callback) |
Listen to a specific event. Fire a callback function. |
$.listen('name', context, callback) |
Listen to a specific event. Fire a callback function that would have a specific context. |
.subscribe('name', callback) |
On a ParsleyField , it would only be fired if the specific event is fired by the specific field. On a ParsleyForm , it would be fired if the event is fired by the form, or by any of its fields. |
.unsubscribe('name') |
Unsubscribe all callbacks subscribed to an event name. |
$.emit('name') |
Emit an event for listeners and subscribers. |
Parsley Remote
Parsley remote is a handy plugin that adds a unique ajax asynchronous validator.
To use this plugin, either load parsley.remote.js
before loading parsley.js
, or directly load parsley.remote.js
.
Options
| Name | API | Description |
|---|---|---|
| Remote validator | data-parsley-remote |
Define the url that would be called to validate the entered content. eg: data-parsley-remote="http://url.ext" |
| Reverse | data-parsley-remote-reverse |
By default, all 2xx ajax returs are considered valid, all others failure. Sometimes (when a call is needed to see if an email, a pseudo is available for example) a 404 API answer could be the right answer. Using data-parsley-remote-reverse="true" will consider 200 response is an error, and 404 one is correct. |
| Options | data-parsley-remote-options |
You could pass a json object to the $.ajax() method used by remote validator. eg: data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp", "data": { "token": "value" } }'Warning: you must format your JSON string wrapping all the keys/values with " like above otherwise it won't be correctly parsed by $.parseJSON() used behind the scenes by remote validator (See jQuery doc) |
| Validator | data-parsley-remote-validator |
Use a specific remote validator. By default, there are 2 built-in remote validators: default and reverse . Default one is used by default and Reverse one used when data-parsley-remote-reverse is set to true. (this is an alias, you could use data-parsley-remote-validator="reverse" ). To learn how to craft your custom remote validators, go here. |
Methods
| Method | Description |
|---|---|
asyncIsValid() |
Asynchronously get if field or form is valid or not. Returns a jQuery promise. |
asyncValidate() |
Asynchronously validate a field or a form and display UI errors. Returns a jQuery promise. |
addAsyncValidator(name, fn) |
Add a new custom remote validator. |
Custom remote validators
Configuring your custom remote validators comes with two solutions:
- By registering them in some globals before calling
parsley.remote.js
:<input name="q" type="text" data-parsley-remote data-parsley-remote-validator='mycustom' value="foo" /> [...]
- By registering them after
parsley.remote.js
is loaded:<input name="q" type="text" data-parsley-remote data-parsley-remote-validator='mycustom' value="foo" /> [...]
Parsley Extras
You'll find in the src/extra/
directory in Parsley .zip or Github projects many more or less useful validators crafted by the community. A doc here is coming.


Exactly one regular Neutron port. Has to be provided when the trunk is created. Cannot be changed during the trunk's life.
The parent port is the port you have to add to the instance at launch. Do not try to add the trunk or any of the subports to the instance directly.
Inside the instance the parent port's network will always be presented as the untagged network. It will be available early from the moment of bootup.
Note that some Neutron backends (notably the Open vSwitch based backend) only allow trunk creation before an instance is launched on the parent port. Other backends may allow trunk creation at any time during the life of a port.
Must not be the parent or a subport of any other trunks.


{% extends "_base.html" %} {% block title %}Travel Resources{% endblock %} {% block description %}Helfpul travel resources and links from Aldine Travel, a Virtuoso-certified group of luxury travel advisors.{% endblock %} {% block page_core %}
Tips & tricks from Aldine's luxury travel agents
Browse our elite collection of all-inclusive Virtuoso luxury travel packages from cruises to guided tours and active travel.
Double-check any security warnings and register for the STEP traveler program through the U.S. Department of State.
Expect the best, but plan for the worst. Be sure to grab travel insurance for any unexpected hiccups on your journey.
Truly make your trip a luxury with one of our Virtuoso-certified travel advisors. Send us a message today.
Going some place exotic? Be sure to get all the recommended vaccines in advance. See the travel health site from the CDC.
Meet other travelers and browse through photos of our client's amazing journeys on Facebook.


Nuclear Binding Energy Notes and Questions
Binding Energy and Mass defect
The nuclear binding energy is the energy that is required to break apart a nucleus into its constituent nucleons (protons and neutrons). For example: it is the energy required to split a Helium nucleus (otherwise known as an \(\alpha\) particle) into the two protons and two neutrons that it is made of.
The fact that it requires energy to break apart a nucleus means there is a force keeping the neutrons and protons bound together, and as neutrons are not electrically charged, this force is not just the electromagnetic force alone. We collect the nuclear forces together to talk about the Nuclear force. We know today that there are in fact two different nuclear forces, the weak and strong nuclear forces, as well as the electromagnetic force, however we don’t distinguish them here.
The notion of binding energy and the mass of a nucleus are very much intertwined. They are really just different ways to express the same physics, but the distinction is a useful one. This should hopefully be clear by the end of this set of notes.
Taking the \(\alpha\) particle
example from above, we have that protons have a mass The values of the mass are take from the Wikipedia
pages for Protons and Neutrons respectively on 19/4/2019.
of \(1.007276466879u\)
and a neutron has mass of \(1.00866491588u\), where \(u\) is the atomic mass unit. The atomic
mass unit, \(u\), is defined to be
\(1/12\)-th of the mass of carbon-12.
This has the consequence that a carbon-12 nucleus has mass of exactly
\(12 u\). In kilograms we have that
\(u = 1.660539040(20)\times 10^{-27}\
kg\), which is incredibly tiny.
So we have that the constituents of an \(\alpha\) particle have a combined mass of
\[ \underbrace{(2\times 1.007276466879 u)}_{\text{protons}} + \underbrace{(2 \times 1.00866491588 u)}_{\text{neutrons}} = 4.031882766u \]
Whereas the actual mass of an alpha particle is found to be \(4.001506179127u\). So there is a
discrepancy between the masses. We seem to have lost mass when forming a
nucleus. This is a process we don’t usually encounter in every day life.
What is happening is that some of the mass of the constituents gets
converted into a different type of energy. This is one of the great
realisations by Einstein that mass is just another form of energy, and
the exchange rate is givenThere is some subtlety in this equation, the mass here
is what is called the rest mass. The mass of the object when it’s not
moving. When an object is moving it actually gets heavier, another one
of the bizarre realisations of Einstein.
by \(E = mc^2\).
Well, where does this lost mass go? We have that \(\Delta m = m_{\text{before}} - m_{\text{after}} = 0.030376587 u\). So this mass defect has to be accounted for and it must be converted into another type of energy, for instance kinetic energy carried away by a photon. If the mass defect energy is large enough to create a particle, say an electron, it could cause an electron to be emitted with a smaller kinetic energy. But the energy must always be carried away.
Okay so what does this have to do with binding energy? Well, binding energy is the energy required to reverse this process. To take an \(\alpha\) nucleus and break it into it’s constituents. So we need to give enough energy to the system to account for the mass that is need to be created, as the nucleus has a smaller mass than its constituent protons and neutrons.
\[ ^4_2He^{+2} + \text{energy} \to 2 p^+ + 2 n^0 \]
Well the mass defect for this equation is now \(\Delta m = m_{\text{before}} - m_{\text{after}} = - 0.030376587 u\). So for this process to ever have the chance of working, we need to give it enough energy to create this much mass. So the binding energy is just exactly the mass defect expressed as energy using \(E = mc^2\). For this case we have that the binding energy is \(E_{b} = 0.030376587 u \times c^2 =4.527297829\times 10^{-12}J = 28.295611429 \ MeV\).
A useful expression for \(u\) is that \(u =<PHONE_NUMBER>\ MeV/c^2\), so that \(u\times c^2 =<PHONE_NUMBER>\ MeV\).
So what does it mean for a nucleus to have a larger binding energy than an \(\alpha\) particle? Well, it means that we have to supply more energy to break it apart. Then that means that the mass defect has to be larger. Which means that when the nucleus is formed, it will emit a lot of energy (either as kinetic energy (photons) or as a particle if it has released enough energy to make one using \(E = mc^2\)).
- The most common isotope of Uranium is \(^{238}_{92}U\), and has an atomic mass of \(238.050783u\). Calculate the mass defect, binding energy and the binding energy per nucleon.
- Calculate the total binding energy and the binding energy per
nucleon of \(^{12}_{6}C\) . What
percentage of the rest mass of this nucleus is its total binding
energy.
- What is the maximum wavelength a \(\gamma\)-ray that could break a deuteron (\(^2_1H^{+1}\)) into a proton and neutron. This process is called photo-disintegration.
- A photon with wavelength of \(3.50\times 10^{-13}m\) strikes a deuteron \(^2_1H^{+1}\), splitting it into a proton and neutron. Calculate the kinetic energy released in this interactions. Assuming that the particles share the kinetic energy equally, calculate their speeds.
Nuclear Fission
The situation above has always been that it requires energy to break apart a nucleus, and that is true for small nuclei. However, for large nuclei such as uranium energy is actually released when it breaks apart into two smaller pieces. How can we understand this fact using the knowledge we developed above. To give us an example to work with, it is known that \(^{238}_{92}U\) decays spontaneously/randomly via \(\alpha\) radiation to \(^{234}_{90}Th\) and releases energy via a photon. If we compare the mass before an afterwards we have that \(^{238}_{92}U\) has an atomic mass of \(238.050788u\) and \(^{234}_{90}Th\) has an atomic mass of \(234.043601u\).
So the mass before is just that of the uranium nucleus: \(238.050788u\). Afterwards we have a thorium nucleus and an alpha particle so the mass is: \(234.043601u + 4.001506u = 238.04510u\). So we have that \(\Delta m = m_{\text{before}} - m_{\text{after}} = 238.050788u - 238.045107u = 0.005681u\). So we have lost some mass, this must be converted into another form of energy, i.e. a photon for it to be carried away.
Lets have a look at the binding energy of this process. Uranium-238 has a binding energy of \((m_{\text{constituents}} - m_{\text{actual}})\times c^2\) which is:
\[ (\underbrace{(92\times 1.007 276 u}_{\text{protons}} + \underbrace{((238-92) \times 1.008 664 u)}_{\text{neutrons}} - 238.050788u)\times c^2 = 1.883548u \times c^2 = 1754.51384\ MeV \]
Thorium-234 has a binding energy of:
\[ (\underbrace{(90\times 1.007 276 u}_{\text{protons}} + \underbrace{((234-90) \times 1.008 664 u)}_{\text{neutrons}} - 234.043601u)\times c^2 = 1.858855u \times c^2 = 1731.512457\ MeV \]
and the \(\alpha\) particle has a binding energy of: \(28.295 611 \ MeV\) from above.
 So the total binding energy as gone up.
But we haven’t given the system any extra energy? How can we have more of an energy afterwards? This is the source of most of the confusion about binding energy.
The binding energy should always increase with a spontaneous nuclear process. This is because the binding energy is the amount of energy we as the experimenter would have to put in to the system to break apart the nuclei. This is not an energy that the nuclei themselves have, but the energy we would need to put in to split them up into their individual protons and neutrons. So a larger binding energy afterwards, means it would take more energy to break the nucleus’ apart, which means that the system is in a more stable state.
- Calculate the total energy released in the spontaneous \(\alpha\) decay of Uranium-238 to Thorium-234 described in the text above.
- Is the decay \(n^0 \to p^+ + \beta^- + \bar{\nu}_e\) energetically possible? If it is not, explain why not. If it is, calculate the amount of energy released. Is the decay \(p^+ \to n^0 + \beta^+ + \nu_e\) energetically possible, if not, explain why not. If it is calculate the total energy released.
- The atomic mass of Carbon-14 is \(14.003242u\), show that \(\beta^-\) decay is energetically possible and calculate the energy released in the decay.


LOGIN
Join
AMS Home
Mobile Pairing
Admin
Help
Facebook
Twitter
YouTube
RSS
Advanced Search
J
OURNALS
O
NLINE
Journals
Publish
Subscribe
About


layout: post tags: leadership date: 2013-03-20 13:37:00
Scott Cook, founder of financial software giant Intuit and one of the most thoughtful leaders in the industry, recently spoke about his approach to innovation at the SxSW conference.
His approach to, what he calls, game changing entrepreneurship is spot on and one of the most concise ways to describe it I’ve seen so far:
The focus on finding an important and unsolved customer problem stands in an interesting contrast to what a lot of startups do these days: They start with an idea or technology and try to either find a market or create a market.
Idea first vs problem first.
Guess which approach is more reliably successful?


| r1c1 | r1c2 (rowspan = 2) |
| r2c1 (colspan = 2) |
Input: 2x2 table except one cell specifies an extra row and another an extra (overlapping) column.
Expectation: undefined
Spec: not in CSS 2.1 (?) but in HTML4 tables. Calculate # cols based on biggest row (in isolation, looking at colspans in that row), giving 3. However, it would have to be added to the beginning of row 2, but this is only allowed at the end.


This is a sample block to read a list of names, order them and also create a random ordered list. The code even allows to drag and drop files into the text area for easier manipulation of long lists, and also to avoid storing any data on our server - because there is no need to do it.
The working area is next and below that is the description of the code
Ordered
Randomized
Description of the code
Javascript file in github
To read the names, the code takes the contents of the textarea and puts it into an array line by line to be able to manipulate it. JQuery makes it easy by using the textarea locator, retrieving the value and the using split() by newline, then sorting is native in javascript for an array:
Javascript provides a pseudo-random number generator that produces number in the range (0, 1). For the case presented here we need an integer number in the range [0, names.length] for that we can write a simple function to take an upper boundary and produce a pseudo-random integer in that range:
To be able to generate a random list, the code needs to iterate through the whole list of names and randomly select a new position for every entry:
Handling files
To be able to manipulate files, the browser will generate events related to drag and drop, for which the program needs to handle dragOver, dragEnter, and drop. Within the drop handler, the program can instantiate the HTML5 FileReader object, that will read the local file. The reader works on events to avoid blocking the main (and only) thread executing the script. Within the handler of the reader, I load the contents of the file into the textarea using JQuery $.text() method.
Conclusion
Reading a file is now part HTML5, array manipulation is done easily with javascript, and that includes the sort method, as well as a pseudo-random number generator. Javascript provides also handling of the DOM but in this case I opted for JQuery which in my opinion is easier to read.


fooof.FOOOF¶
-
class
fooof.
FOOOF
(peak_width_limits=(0.5, 12.0), max_n_peaks=inf, min_peak_height=0.0, peak_threshold=2.0, aperiodic_mode='fixed', verbose=True)[source]¶ Model a physiological power spectrum as a combination of aperiodic and periodic components.
WARNING: FOOOF expects frequency and power values in linear space.
Passing in logged frequencies and/or power spectra is not detected, and will silently produce incorrect results.
- Parameters
- peak_width_limitstuple of (float, float), optional, default: (0.5, 12.0)
Limits on possible peak width, in Hz, as (lower_bound, upper_bound).
- max_n_peaksint, optional, default: inf
Maximum number of peaks to fit.
- min_peak_heightfloat, optional, default: 0
Absolute threshold for detecting peaks, in units of the input data.
- peak_thresholdfloat, optional, default: 2.0
Relative threshold for detecting peaks, in units of standard deviation of the input data.
- aperiodic_mode{‘fixed’, ‘knee’}
Which approach to take for fitting the aperiodic component.
- verbosebool, optional, default: True
Verbosity mode. If True, prints out warnings and general status updates.
Notes
Commonly used abbreviations used in this module include: CF: center frequency, PW: power, BW: Bandwidth, AP: aperiodic
Input power spectra must be provided in linear scale. Internally they are stored in log10 scale, as this is what the model operates upon.
Input power spectra should be smooth, as overly noisy power spectra may lead to bad fits. For example, raw FFT inputs are not appropriate. Where possible and appropriate, use longer time segments for power spectrum calculation to get smoother power spectra, as this will give better model fits.
The gaussian params are those that define the gaussian of the fit, where as the peak params are a modified version, in which the CF of the peak is the mean of the gaussian, the PW of the peak is the height of the gaussian over and above the aperiodic component, and the BW of the peak, is 2*std of the gaussian (as ‘two sided’ bandwidth).
- Attributes
- freqs1d array
Frequency values for the power spectrum.
- power_spectrum1d array
Power values, stored internally in log10 scale.
- freq_rangelist of [float, float]
Frequency range of the power spectrum, as [lowest_freq, highest_freq].
- freq_resfloat
Frequency resolution of the power spectrum.
- fooofed_spectrum_1d array
The full model fit of the power spectrum, in log10 scale.
- aperiodic_params_1d array
Parameters that define the aperiodic fit. As [Offset, (Knee), Exponent]. The knee parameter is only included if aperiodic component is fit with a knee.
- peak_params_2d array
Fitted parameter values for the peaks. Each row is a peak, as [CF, PW, BW].
- gaussian_params_2d array
Parameters that define the gaussian fit(s). Each row is a gaussian, as [mean, height, standard deviation].
- r_squared_float
R-squared of the fit between the input power spectrum and the full model fit.
- error_float
Error of the full model fit.
n_peaks_
intHow many peaks were fit in the model.
has_data
boolIndicator for if the object contains data.
has_model
boolIndicator for if the object contains a model fit.
-
__init__
(self, peak_width_limits=(0.5, 12.0), max_n_peaks=inf, min_peak_height=0.0, peak_threshold=2.0, aperiodic_mode='fixed', verbose=True)[source]¶ Initialize object with desired settings.
Methods
__init__
(self[, peak_width_limits, …])Initialize object with desired settings.
add_data
(self, freqs, power_spectrum[, …])Add data (frequencies, and power spectrum values) to the current object.
add_meta_data
(self, fooof_meta_data)Add data information into object from a FOOOFMetaData object.
add_results
(self, fooof_result)Add results data into object from a FOOOFResults object.
add_settings
(self, fooof_settings)Add settings into object from a FOOOFSettings object.
copy
(self)Return a copy of the current object.
fit
(self[, freqs, power_spectrum, freq_range])Fit the full power spectrum as a combination of periodic and aperiodic components.
get_meta_data
(self)Return data information from the current object.
get_params
(self, name[, col])Return model fit parameters for specified feature(s).
get_results
(self)Return model fit parameters and goodness of fit metrics.
get_settings
(self)Return user defined settings of the current object.
load
(self, file_name[, file_path, regenerate])Load in a FOOOF formatted JSON file to the current object.
plot
(self[, plot_peaks, plot_aperiodic, …])Plot the power spectrum and model fit results from a FOOOF object.
print_report_issue
([concise])Prints instructions on how to report bugs and/or problematic fits.
print_results
(self[, concise])Print out model fitting results.
print_settings
(self[, description, concise])Print out the current settings.
report
(self[, freqs, power_spectrum, …])Run model fit, and display a report, which includes a plot, and printed results.
save
(self, file_name[, file_path, append, …])Save out data, results and/or settings from a FOOOF object into a JSON file.
save_report
(self, file_name[, file_path, …])Generate and save out a PDF report for a power spectrum model fit.
set_debug_mode
(self, debug)Set whether debug mode, wherein an error is raised if fitting is unsuccessful.
Attributes
Indicator for if the object contains data.
Indicator for if the object contains a model fit.
How many peaks were fit in the model.
-
add_data
(self, freqs, power_spectrum, freq_range=None)[source]¶ Add data (frequencies, and power spectrum values) to the current object.
- Parameters
- freqs1d array
Frequency values for the power spectrum, in linear space.
- power_spectrum1d array
Power spectrum values, which must be input in linear space.
- freq_rangelist of [float, float], optional
Frequency range to restrict power spectrum to. If not provided, keeps the entire range.
Notes
If called on an object with existing data and/or results they will be cleared by this method call.
-
add_meta_data
(self, fooof_meta_data)[source]¶ Add data information into object from a FOOOFMetaData object.
- Parameters
- fooof_meta_dataFOOOFMetaData
A meta data object containing meta data information.
-
add_results
(self, fooof_result)[source]¶ Add results data into object from a FOOOFResults object.
- Parameters
- fooof_resultFOOOFResults
A data object containing the results from fitting a FOOOF model.
-
add_settings
(self, fooof_settings)[source]¶ Add settings into object from a FOOOFSettings object.
- Parameters
- fooof_settingsFOOOFSettings
A data object containing the settings for a FOOOF model.
-
fit
(self, freqs=None, power_spectrum=None, freq_range=None)[source]¶ Fit the full power spectrum as a combination of periodic and aperiodic components.
- Parameters
- freqs1d array, optional
Frequency values for the power spectrum, in linear space.
- power_spectrum1d array, optional
Power values, which must be input in linear space.
- freq_rangelist of [float, float], optional
Frequency range to restrict power spectrum to. If not provided, keeps the entire range.
- Raises
- NoDataError
If no data is available to fit.
- FitError
If model fitting fails to fit. Only raised in debug mode.
Notes
Data is optional, if data has already been added to the object.
-
get_meta_data
(self)[source]¶ Return data information from the current object.
- Returns
- FOOOFMetaData
Object containing meta data from the current object.
-
get_params
(self, name, col=None)[source]¶ Return model fit parameters for specified feature(s).
- Parameters
- name{‘aperiodic_params’, ‘peak_params’, ‘gaussian_params’, ‘error’, ‘r_squared’}
Name of the data field to extract.
- col{‘CF’, ‘PW’, ‘BW’, ‘offset’, ‘knee’, ‘exponent’} or int, optional
Column name / index to extract from selected data, if requested. Only used for name of {‘aperiodic_params’, ‘peak_params’, ‘gaussian_params’}.
- Returns
- outfloat or 1d array
Requested data.
- Raises
- NoModelError
If there are no model fit parameters available to return.
Notes
For further description of the data you can extract, check the FOOOFResults documentation.
If there is no data on periodic features, this method will return NaN.
-
get_results
(self)[source]¶ Return model fit parameters and goodness of fit metrics.
- Returns
- FOOOFResults
Object containing the model fit results from the current object.
-
get_settings
(self)[source]¶ Return user defined settings of the current object.
- Returns
- FOOOFSettings
Object containing the settings from the current object.
-
has_data
¶ Indicator for if the object contains data.
-
has_model
¶ Indicator for if the object contains a model fit.
Notes
This check uses the aperiodic params, which are:
nan if no model has been fit
necessarily defined, as floats, if model has been fit
-
load
(self, file_name, file_path=None, regenerate=True)[source]¶ Load in a FOOOF formatted JSON file to the current object.
- Parameters
- file_namestr or FileObject
File to load data from.
- file_pathstr or None, optional
Path to directory to load from. If None, loads from current directory.
- regeneratebool, optional, default: True
Whether to regenerate the model fit from the loaded data, if data is available.
-
n_peaks_
¶ How many peaks were fit in the model.
-
plot
(self, plot_peaks=None, plot_aperiodic=True, plt_log=False, add_legend=True, save_fig=False, file_name=None, file_path=None, ax=None, plot_style=<function style_spectrum_plot at 0x7f94941557a0>, data_kwargs=None, model_kwargs=None, aperiodic_kwargs=None, peak_kwargs=None)[source]¶ Plot the power spectrum and model fit results from a FOOOF object.
- Parameters
- plot_peaksNone or {‘shade’, ‘dot’, ‘outline’, ‘line’}, optional
What kind of approach to take to plot peaks. If None, peaks are not specifically plotted. Can also be a combination of approaches, separated by ‘-‘, for example: ‘shade-line’.
- plot_aperiodicboolean, optional, default: True
Whether to plot the aperiodic component of the model fit.
- plt_logboolean, optional, default: False
Whether to plot the frequency values in log10 spacing.
- add_legendboolean, optional, default: False
Whether to add a legend describing the plot components.
- save_figbool, optional, default: False
Whether to save out a copy of the plot.
- file_namestr, optional
Name to give the saved out file.
- file_pathstr, optional
Path to directory to save to. If None, saves to current directory.
- axmatplotlib.Axes, optional
Figure axes upon which to plot.
- plot_stylecallable, optional, default: style_spectrum_plot
A function to call to apply styling & aesthetics to the plot.
- data_kwargs, model_kwargs, aperiodic_kwargs, peak_kwargsNone or dict, optional
Keyword arguments to pass into the plot call for each plot element.
Notes
Since FOOOF objects store power values in log spacing, the y-axis (power) is plotted in log spacing by default.
-
static
print_report_issue
(concise=False)[source]¶ Prints instructions on how to report bugs and/or problematic fits.
- Parameters
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
-
print_results
(self, concise=False)[source]¶ Print out model fitting results.
- Parameters
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
-
print_settings
(self, description=False, concise=False)[source]¶ Print out the current settings.
- Parameters
- descriptionbool, optional, default: False
Whether to print out a description with current settings.
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
-
report
(self, freqs=None, power_spectrum=None, freq_range=None, plt_log=False)[source]¶ Run model fit, and display a report, which includes a plot, and printed results.
- Parameters
- freqs1d array, optional
Frequency values for the power spectrum.
- power_spectrum1d array, optional
Power values, which must be input in linear space.
- freq_rangelist of [float, float], optional
Desired frequency range to fit the model to. If not provided, fits across the entire given range.
- plt_logbool, optional, default: False
Whether or not to plot the frequency axis in log space.
Notes
Data is optional, if data has already been added to the object.
-
save
(self, file_name, file_path=None, append=False, save_results=False, save_settings=False, save_data=False)[source]¶ Save out data, results and/or settings from a FOOOF object into a JSON file.
- Parameters
- file_namestr or FileObject
File to save data to.
- file_pathstr, optional
Path to directory to save to. If None, saves to current directory.
- appendbool, optional, default: False
Whether to append to an existing file, if available. This option is only valid (and only used) if ‘file_name’ is a str.
- save_resultsbool, optional
Whether to save out FOOOF model fit results.
- save_settingsbool, optional
Whether to save out FOOOF settings.
- save_databool, optional
Whether to save out input data.
- Raises
- ValueError
If the save file is not understood.
-
save_report
(self, file_name, file_path=None, plt_log=False)[source]¶ Generate and save out a PDF report for a power spectrum model fit.
- Parameters
- file_namestr
Name to give the saved out file.
- file_pathstr, optional
Path to directory to save to. If None, saves to current directory.
- plt_logbool, optional, default: False
Whether or not to plot the frequency axis in log space.


Truth or Dare?
Truth
Or
Dare
Your EPQ
0
Reach 5 EPQs +1 to earn a reward!
Congrats! 5 EPQs!
Prudential Insurance Gh Ltd will contact you to discuss further!
Claim Reward
Ignore


Bradlee Speice, Wed 03 February 2016, Blog
My previous class in Stochastic Calculus covered a lot of interesting topics, and the important one for today is the Gambler's Ruin problem. If you're interested in some of the theory behind it, also make sure to check out random walks. The important bit is that we studied the Martingale Betting Strategy, which describes for us a guaranteed way to eventually make money.
The strategy goes like this: You are going to toss a fair coin with a friend. If you guess heads or tails correctly, you get back double the money you bet. If you guess incorrectly, you lose money. How should you bet?
The correct answer is that you should double your bet each time you lose.  Consider the scenario:
Mathematically, we can prove that as long as you have unlimited money to bet, you are guaranteed to make money.
But we're all realistic people, and once you start talking about "unlimited money" eyebrows should be raised. Even still, this is an interesting strategy to investigate, and I want to apply it to the stock market. As long as we can guarantee there's a single day in which the stock goes up, we should be able to make money right? The question is just how much we have to invest to guarantee this.
Now it's time for the math. We'll use the following definitions:
With those definitions in place, I'd like to present the formula that is guaranteed to make you money. I call it Bradlee's Investment Formula:
$c_n \sum_{i=1}^n \frac{d_i}{o_i} > \sum_{i=1}^{n} d_i$
It might not look like much, but if you can manage to make it so that this formula holds true, you will be guaranteed to make money. The intuition behind the formula is this: The closing share price times the number of shares you have purchased ends up greater than the amount of money you invested.
That is, on day $n$, if you know what the closing price will be you can set up the amount of money you invest that day to guarantee you make money. I'll even teach you to figure out how much money that is! Take a look:
$ \begin{align} c_n \sum_{i=1}^{n-1} \frac{d_i}{o_i} + \frac{c_nd_n}{o_n} &> \sum_{i=1}^{n-1}d_i + d_n\\ \frac{c_nd_n}{o_n} - d_n &> \sum_{i=1}^{n-1}(d_i - \frac{c_nd_i}{o_i})\\ d_n (\frac{c_n - o_n}{o_n}) &> \sum_{i=1}^{n-1} d_i(1 - \frac{c_n}{o_i})\\ d_n &> \frac{o_n}{c_n - o_n} \sum_{i=1}^{n-1} d_i(1 - \frac{1}{o_i}) \end{align}$
If you invest exactly $d_n$ that day, you'll break even. But if you can make sure the money you invest is greater than that quantity on the right (which requires that you have a crystal ball tell you the stock's closing price) you are guaranteed to make money!
On a more serious note though, the formula above tells us a couple of interesting things:
So now that we've defined our investment formula,we need to tweak a couple things in order to make an investment strategy we can actually work with. There are two issues we need to address:
Now that we've defined our bias and expectation, we can actually build a strategy we can simulate.
Now, let's get to the code!
using Quandl
api_key = ""
daily_investment = function(current_open, current_close, purchase_history, open_history)
# We're not going to safeguard against divide by 0 - that's the user's responsibility
t1 = current_close / current_open - 1
t2 = sum(purchase_history - purchase_history*current_close ./ open_history)
return t2 / t1
end;
And let's code a way to run simulations quickly:
is_profitable = function(current_price, purchase_history, open_history)
shares = sum(purchase_history ./ open_history)
return current_price*shares > sum(purchase_history)
end
simulate = function(name, start, init, expected, bias)
ticker_info = quandlget(name, from=start, api_key=api_key)
open_vals = ticker_info["Open"].values
close_vals = ticker_info["Close"].values
invested = [init]
# The simulation stops once we've made a profit
day = 1
profitable = is_profitable(close_vals[day], invested, open_vals[1:length(invested)]) ||
is_profitable(open_vals[day+1], invested, open_vals[1:length(invested)])
while !profitable
expected_close = open_vals[day+1] * expected
todays_purchase = daily_investment(open_vals[day+1], expected_close, invested, open_vals[1:day])
invested = [invested; todays_purchase + bias]
# expected_profit = expected_close * sum(invested ./ open_vals[1:length(invested)]) - sum(invested)
day += 1
profitable = is_profitable(close_vals[day], invested, open_vals[1:length(invested)]) ||
is_profitable(open_vals[day+1], invested, open_vals[1:length(invested)])
end
shares = sum(invested ./ open_vals[1:length(invested)])
max_profit = max(close_vals[day], open_vals[day+1])
profit = shares * max_profit - sum(invested)
return (invested, profit)
end
sim_summary = function(investments, profit)
leverages = [sum(investments[1:i]) for i=1:length(investments)]
max_leverage = maximum(leverages) / investments[1]
println("Max leverage: $(max_leverage)")
println("Days invested: $(length(investments))")
println("Profit: $profit")
end;
Now, let's get some data and run a simulation! Our first test:
investments, profit = simulate("YAHOO/LMT", Date(2015, 11, 29), 100, 1.01, 10)
sim_summary(investments, profit)
The result: We need to invest 5.6x our initial position over a period of 5 days to make approximately .69¢
investments, profit = simulate("YAHOO/LMT", Date(2015, 11, 29), 100, 1.02, 10)
sim_summary(investments, profit)
In this example, we only get up to a 1.85x leveraged position, but it takes 25 days to turn a profit of 8¢
We've defined an investment strategy that can tell us how much to invest when we know what the closing position of a stock will be. We can tweak the strategy to actually make money, but plenty of work needs to be done so that we can optimize the money invested.
In the next post I'm going to post more information about some backtests and strategy tests on this strategy (unless of course this experiment actually produces a significant profit potential, and then I'm keeping it for myself).
The claims made in this presentation about being able to guarantee making money are intended as a joke and do not constitute investment advice of any sort.


libcurl - the multiprotocol file transfer library
libcurl is a free and easy-to-use client-side URL transfer library, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos), file transfer resume, http proxy tunneling and more!
libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more...
libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported, fast, thoroughly documented and is already used by many known, big and successful companies.
Download
Go to the regular curl download page and get the latest curl package, or one of the specific libcurl packages listed.
API
You use libcurl with the provided C API. The curl team works hard to keep the API and ABI stable. If you prefer using libcurl from your other favorite language, chances are there's already a binding written for it.
Howto
Check out our using libcurl page for general hints and advice, the free HTTP client library comparison. or read the comparisons against libwww and WinInet.
libcurl is most probably the most portable, most powerful and most often used C-based multi-platform file transfer library on this planet - be it open source or commercial.


BUILD WITH US
HOME
COMPANY
CREATE PRO ACOUNT
SINGUP/LOGIN
SUPPORT
YOU BELIEVE WE CONNECT!
Location
rajamundry
Hyderabad
Vizag


#include <MouseHandler.h>
The update method is called by the input manager, and the input handler increases events by calling the input manager's increaseEventQuantity method.
Definition at line 26 of file MouseHandler.h.
Public Member Functions | |
| int | getDoubleClickDelay () |
| Returns the maximum time between clicks to accept them as double clicks. | |
| int | getDoubleClickDistance () |
| The maximum X and Y distance between clicks to accept them as double clicks. | |
| virtual void | initialize () |
| Initializes the input handler. | |
| bool | isEnabled () |
| Returns whether the handler is enabled (processes inputs). | |
| MouseHandler () | |
| Creates a new mouse handler. | |
| virtual void | resetHelds () |
| Resets all information about held keys, buttons, etc. | |
| void | setDoubleClickDelay (int doubleClickDelay) |
| Returns the maximum time between clicks to accept them as double clicks. | |
| void | setDoubleClickDistance (int doubleClickDistance) |
| The maximum X and Y distance between clicks to accept them as double clicks. | |
| void | setEnabled (bool enabled) |
| Sets whether the handler is enabled (processes inputs). | |
| virtual void | shutDown ()=NULL |
| Shuts down the input handler. | |
| virtual void | update ()=NULL |
| Handles all input and updates event quantities. | |
| virtual void | updateExclusive () |
| Updates the handler when the scene's exclusive changes. | |
| virtual | ~MouseHandler () |
| Destroys the mouse handler. | |
Protected Attributes | |
| bool | buttonWasPressed [3] |
| Whether the mouse buttons were pressed last frame. | |
| bool | enabled |
| Whether the handler is enabled (processes inputs). |
|
|
Creates a new mouse handler.
|
|
|
Destroys the mouse handler.
|
|
|
Returns the maximum time between clicks to accept them as double clicks.
|
|
|
The maximum X and Y distance between clicks to accept them as double clicks.
|
|
|
Initializes the input handler.
|
|
|
Returns whether the handler is enabled (processes inputs). Defaults to true.
|
|
|
Resets all information about held keys, buttons, etc.
|
|
|
Returns the maximum time between clicks to accept them as double clicks.
|
|
|
The maximum X and Y distance between clicks to accept them as double clicks.
|
|
|
Sets whether the handler is enabled (processes inputs). Defaults to true.
|
|
|
Shuts down the input handler.
|
|
|
Handles all input and updates event quantities.
|
|
|
Updates the handler when the scene's exclusive changes.
|
|
|
Whether the mouse buttons were pressed last frame. The index is the button number. Definition at line 38 of file MouseHandler.h. |
|
|
Whether the handler is enabled (processes inputs). Defaults to true. Definition at line 43 of file MouseHandler.h. |