text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
package org.apache.calcite.runtime;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.annotation.Nonnull;
/**
* List that consists of a head element and an immutable non-empty list.
*
* @param <E> Element type
*/
public class ConsList<E> extends AbstractImmutableList<E> {
private final E first;
private final List<E> rest;
/** Creates a ConsList.
* It consists of an element pre-pended to another list.
* If the other list is mutable, creates an immutable copy. */
public static <E> List<E> of(E first, List<E> rest) {
if (rest instanceof ConsList
|| rest instanceof ImmutableList
&& !rest.isEmpty()) {
return new ConsList<>(first, rest);
} else {
return ImmutableList.<E>builder().add(first).addAll(rest).build();
}
}
private ConsList(E first, List<E> rest) {
this.first = first;
this.rest = rest;
}
public E get(int index) {
for (ConsList<E> c = this;; c = (ConsList<E>) c.rest) {
if (index == 0) {
return c.first;
}
--index;
if (!(c.rest instanceof ConsList)) {
return c.rest.get(index);
}
}
}
public int size() {
int s = 1;
for (ConsList c = this;; c = (ConsList) c.rest, ++s) {
if (!(c.rest instanceof ConsList)) {
return s + c.rest.size();
}
}
}
@Override public int hashCode() {
return toList().hashCode();
}
@Override public boolean equals(Object o) {
return o == this
|| o instanceof List
&& toList().equals(o);
}
@Override public String toString() {
return toList().toString();
}
protected final List<E> toList() {
final List<E> list = new ArrayList<>();
for (ConsList<E> c = this;; c = (ConsList<E>) c.rest) {
list.add(c.first);
if (!(c.rest instanceof ConsList)) {
list.addAll(c.rest);
return list;
}
}
}
@Override @Nonnull public ListIterator<E> listIterator() {
return toList().listIterator();
}
@Override @Nonnull public Iterator<E> iterator() {
return toList().iterator();
}
@Override @Nonnull public ListIterator<E> listIterator(int index) {
return toList().listIterator(index);
}
@Nonnull public Object[] toArray() {
return toList().toArray();
}
@Nonnull public <T> T[] toArray(@Nonnull T[] a) {
final int s = size();
if (s > a.length) {
a = Arrays.copyOf(a, s);
} else if (s < a.length) {
a[s] = null;
}
int i = 0;
for (ConsList c = this;; c = (ConsList) c.rest) {
//noinspection unchecked
a[i++] = (T) c.first;
if (!(c.rest instanceof ConsList)) {
Object[] a2 = c.rest.toArray();
//noinspection SuspiciousSystemArraycopy
System.arraycopy(a2, 0, a, i, a2.length);
return a;
}
}
}
public int indexOf(Object o) {
return toList().indexOf(o);
}
public int lastIndexOf(Object o) {
return toList().lastIndexOf(o);
}
}
// End ConsList.java
| {'content_hash': '97f823528a4321bcc1b0183020d2d3ff', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 72, 'avg_line_length': 23.83206106870229, 'alnum_prop': 0.596732863549007, 'repo_name': 'adeshr/incubator-calcite', 'id': 'a30af847a62fc96fcbc5c2230f466308a91fb665', 'size': '3919', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/apache/calcite/runtime/ConsList.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2881'}, {'name': 'CSS', 'bytes': '73120'}, {'name': 'FreeMarker', 'bytes': '2154'}, {'name': 'HTML', 'bytes': '37481'}, {'name': 'Java', 'bytes': '14144773'}, {'name': 'Protocol Buffer', 'bytes': '15428'}, {'name': 'Ruby', 'bytes': '3550'}, {'name': 'Shell', 'bytes': '7947'}]} |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _GitHubApi = _interopRequireDefault(require("./GitHubApi"));
var _NpmApi = _interopRequireDefault(require("./NpmApi"));
var _StackExchangeApi = _interopRequireDefault(require("./StackExchangeApi"));
var _StatCounterApi = _interopRequireDefault(require("./StatCounterApi"));
var RouterApi = {
GH: _GitHubApi["default"],
NPM: _NpmApi["default"],
SE: _StackExchangeApi["default"],
ST: _StatCounterApi["default"]
};
var _default = RouterApi;
exports["default"] = _default;
//# sourceMappingURL=RouterApi.js.map | {'content_hash': 'f6eca9d10ce3562f36d4bc629aa7d85b', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 85, 'avg_line_length': 28.375, 'alnum_prop': 0.7283406754772394, 'repo_name': 'ZhnZhn/library-watch', 'id': '34ce3ea83865f0d145f188a9f52e972a516cba11', 'size': '681', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'js/api/RouterApi.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20037'}, {'name': 'EJS', 'bytes': '13965'}, {'name': 'HTML', 'bytes': '6666'}, {'name': 'JavaScript', 'bytes': '336931'}]} |
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="RolePlayingGameData.CharacterClass">
<Name>Barbarian</Name>
<InitialStatistics>
<HealthPoints>50</HealthPoints>
<MagicPoints>0</MagicPoints>
<PhysicalOffense>15</PhysicalOffense>
<PhysicalDefense>5</PhysicalDefense>
<MagicalOffense>0</MagicalOffense>
<MagicalDefense>1</MagicalDefense>
</InitialStatistics>
<LevelingStatistics>
<HealthPointsIncrease>15</HealthPointsIncrease>
<LevelsPerHealthPointsIncrease>1</LevelsPerHealthPointsIncrease>
<MagicPointsIncrease>0</MagicPointsIncrease>
<LevelsPerMagicPointsIncrease>0</LevelsPerMagicPointsIncrease>
<PhysicalOffenseIncrease>4</PhysicalOffenseIncrease>
<LevelsPerPhysicalOffenseIncrease>1</LevelsPerPhysicalOffenseIncrease>
<PhysicalDefenseIncrease>1</PhysicalDefenseIncrease>
<LevelsPerPhysicalDefenseIncrease>1</LevelsPerPhysicalDefenseIncrease>
<MagicalOffenseIncrease>0</MagicalOffenseIncrease>
<LevelsPerMagicalOffenseIncrease>0</LevelsPerMagicalOffenseIncrease>
<MagicalDefenseIncrease>1</MagicalDefenseIncrease>
<LevelsPerMagicalDefenseIncrease>2</LevelsPerMagicalDefenseIncrease>
</LevelingStatistics>
<LevelEntries>
<Item>
<ExperiencePoints>100</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>150</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>200</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>250</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>300</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>350</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>400</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>450</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>500</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>550</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>600</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>650</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>700</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>750</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>800</ExperiencePoints>
<SpellContentNames />
</Item>
<Item>
<ExperiencePoints>0</ExperiencePoints>
<SpellContentNames />
</Item>
</LevelEntries>
<BaseExperienceValue>20</BaseExperienceValue>
<BaseGoldValue>10</BaseGoldValue>
</Asset>
</XnaContent> | {'content_hash': '595d129582eee12cc889af8f6af95614', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 76, 'avg_line_length': 32.291666666666664, 'alnum_prop': 0.6564516129032258, 'repo_name': 'DDReaper/XNAGameStudio', 'id': '656fbefc2a9514e7d5874ec1186dad5b384cde59', 'size': '3102', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/RolePlayingGame_4_0_Phone/RolePlayingGameContentWindowsPhone/CharacterClasses/Barbarian.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '77207'}]} |
package com.nhnsoft.bitcoin.protocols.channels;
import com.nhnsoft.bitcoin.core.*;
import com.nhnsoft.bitcoin.protocols.channels.PaymentChannelCloseException.CloseReason;
import com.nhnsoft.bitcoin.utils.Threading;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.protobuf.ByteString;
import net.jcip.annotations.GuardedBy;
import org.bitcoin.paymentchannel.Protos;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>A handler class which handles most of the complexity of creating a payment channel connection by providing a
* simple in/out interface which is provided with protobufs from the client and which generates protobufs which should
* be sent to the client.</p>
*
* <p>Does all required verification of messages and properly stores state objects in the wallet-attached
* {@link StoredPaymentChannelServerStates} so that they are automatically closed when necessary and payment
* transactions are not lost if the application crashes before it unlocks.</p>
*/
public class PaymentChannelServer {
//TODO: Update JavaDocs with notes for communication over stateless protocols
private static final org.slf4j.Logger log = LoggerFactory.getLogger(PaymentChannelServer.class);
protected final ReentrantLock lock = Threading.lock("channelserver");
// The step in the initialization process we are in, some of this is duplicated in the PaymentChannelServerState
private enum InitStep {
WAITING_ON_CLIENT_VERSION,
WAITING_ON_UNSIGNED_REFUND,
WAITING_ON_CONTRACT,
WAITING_ON_MULTISIG_ACCEPTANCE,
CHANNEL_OPEN
}
@GuardedBy("lock") private InitStep step = InitStep.WAITING_ON_CLIENT_VERSION;
/**
* Implements the connection between this server and the client, providing an interface which allows messages to be
* sent to the client, requests for the connection to the client to be closed, and callbacks which occur when the
* channel is fully open or the client completes a payment.
*/
public interface ServerConnection {
/**
* <p>Requests that the given message be sent to the client. There are no blocking requirements for this method,
* however the order of messages must be preserved.</p>
*
* <p>If the send fails, no exception should be thrown, however
* {@link PaymentChannelServer#connectionClosed()} should be called immediately.</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*/
public void sendToClient(Protos.TwoWayChannelMessage msg);
/**
* <p>Requests that the connection to the client be closed</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param reason The reason for the closure, see the individual values for more details.
* It is usually safe to ignore this value.
*/
public void destroyConnection(CloseReason reason);
/**
* <p>Triggered when the channel is opened and payments can begin</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param contractHash A unique identifier which represents this channel (actually the hash of the multisig contract)
*/
public void channelOpen(Sha256Hash contractHash);
/**
* <p>Called when the payment in this channel was successfully incremented by the client</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param by The increase in total payment
* @param to The new total payment to us (not including fees which may be required to claim the payment)
* @param info Information about this payment increase, used to extend this protocol.
* @return An ack message that will be included in the PaymentAck message to the client. Use null for no ack message.
*/
@Nullable
public ByteString paymentIncrease(Coin by, Coin to, @Nullable ByteString info);
}
private final ServerConnection conn;
// Used to keep track of whether or not the "socket" ie connection is open and we can generate messages
@GuardedBy("lock") private boolean connectionOpen = false;
// Indicates that no further messages should be sent and we intend to settle the connection
@GuardedBy("lock") private boolean channelSettling = false;
// The wallet and peergroup which are used to complete/broadcast transactions
private final Wallet wallet;
private final TransactionBroadcaster broadcaster;
// The key used for multisig in this channel
@GuardedBy("lock") private ECKey myKey;
// The minimum accepted channel value
private final Coin minAcceptedChannelSize;
// The state manager for this channel
@GuardedBy("lock") private PaymentChannelServerState state;
// The time this channel expires (ie the refund transaction's locktime)
@GuardedBy("lock") private long expireTime;
/**
* <p>The amount of time we request the client lock in their funds.</p>
*
* <p>The value defaults to 24 hours - 60 seconds and should always be greater than 2 hours plus the amount of time
* the channel is expected to be used and smaller than 24 hours minus the client <-> server latency minus some
* factor to account for client clock inaccuracy.</p>
*/
public long timeWindow = 24*60*60 - 60;
/**
* Creates a new server-side state manager which handles a single client connection.
*
* @param broadcaster The PeerGroup on which transactions will be broadcast - should have multiple connections.
* @param wallet The wallet which will be used to complete transactions.
* Unlike {@link PaymentChannelClient}, this does not have to already contain a StoredState manager
* @param minAcceptedChannelSize The minimum value the client must lock into this channel. A value too large will be
* rejected by clients, and a value too low will require excessive channel reopening
* and may cause fees to be require to settle the channel. A reasonable value depends
* entirely on the expected maximum for the channel, and should likely be somewhere
* between a few bitcents and a bitcoin.
* @param conn A callback listener which represents the connection to the client (forwards messages we generate to
* the client and will close the connection on request)
*/
public PaymentChannelServer(TransactionBroadcaster broadcaster, Wallet wallet,
Coin minAcceptedChannelSize, ServerConnection conn) {
this.broadcaster = checkNotNull(broadcaster);
this.wallet = checkNotNull(wallet);
this.minAcceptedChannelSize = checkNotNull(minAcceptedChannelSize);
this.conn = checkNotNull(conn);
}
/**
* Returns the underlying {@link PaymentChannelServerState} object that is being manipulated. This object allows
* you to learn how much money has been transferred, etc. May be null if the channel wasn't negotiated yet.
*/
@Nullable
public PaymentChannelServerState state() {
return state;
}
@GuardedBy("lock")
private void receiveVersionMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_ON_CLIENT_VERSION && msg.hasClientVersion());
if (msg.getClientVersion().getMajor() != 1) {
error("This server needs protocol v1", Protos.Error.ErrorCode.NO_ACCEPTABLE_VERSION,
CloseReason.NO_ACCEPTABLE_VERSION);
return;
}
Protos.ServerVersion.Builder versionNegotiationBuilder = Protos.ServerVersion.newBuilder()
.setMajor(1).setMinor(0);
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.SERVER_VERSION)
.setServerVersion(versionNegotiationBuilder)
.build());
ByteString reopenChannelContractHash = msg.getClientVersion().getPreviousChannelContractHash();
if (reopenChannelContractHash != null && reopenChannelContractHash.size() == 32) {
Sha256Hash contractHash = new Sha256Hash(reopenChannelContractHash.toByteArray());
log.info("New client that wants to resume {}", contractHash);
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)
wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
if (channels != null) {
StoredServerChannel storedServerChannel = channels.getChannel(contractHash);
if (storedServerChannel != null) {
final PaymentChannelServer existingHandler = storedServerChannel.setConnectedHandler(this, false);
if (existingHandler != this) {
log.warn(" ... and that channel is already in use, disconnecting other user.");
existingHandler.close();
storedServerChannel.setConnectedHandler(this, true);
}
log.info("Got resume version message, responding with VERSIONS and CHANNEL_OPEN");
state = storedServerChannel.getOrCreateState(wallet, broadcaster);
step = InitStep.CHANNEL_OPEN;
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CHANNEL_OPEN)
.build());
conn.channelOpen(contractHash);
return;
} else {
log.error(" ... but we do not have any record of that contract! Resume failed.");
}
} else {
log.error(" ... but we do not have any stored channels! Resume failed.");
}
}
log.info("Got initial version message, responding with VERSIONS and INITIATE: min value={}",
minAcceptedChannelSize.value);
myKey = new ECKey();
wallet.freshReceiveKey();
expireTime = Utils.currentTimeSeconds() + timeWindow;
step = InitStep.WAITING_ON_UNSIGNED_REFUND;
Protos.Initiate.Builder initiateBuilder = Protos.Initiate.newBuilder()
.setMultisigKey(ByteString.copyFrom(myKey.getPubKey()))
.setExpireTimeSecs(expireTime)
.setMinAcceptedChannelSize(minAcceptedChannelSize.value)
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value);
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(initiateBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.INITIATE)
.build());
}
@GuardedBy("lock")
private void receiveRefundMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_ON_UNSIGNED_REFUND && msg.hasProvideRefund());
log.info("Got refund transaction, returning signature");
Protos.ProvideRefund providedRefund = msg.getProvideRefund();
state = new PaymentChannelServerState(broadcaster, wallet, myKey, expireTime);
byte[] signature = state.provideRefundTransaction(new Transaction(wallet.getParams(), providedRefund.getTx().toByteArray()),
providedRefund.getMultisigKey().toByteArray());
step = InitStep.WAITING_ON_CONTRACT;
Protos.ReturnRefund.Builder returnRefundBuilder = Protos.ReturnRefund.newBuilder()
.setSignature(ByteString.copyFrom(signature));
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setReturnRefund(returnRefundBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.RETURN_REFUND)
.build());
}
private void multisigContractPropogated(Protos.ProvideContract providedContract, Sha256Hash contractHash) {
lock.lock();
try {
if (!connectionOpen || channelSettling)
return;
state.storeChannelInWallet(PaymentChannelServer.this);
try {
receiveUpdatePaymentMessage(providedContract.getInitialPayment(), false /* no ack msg */);
} catch (VerificationException e) {
log.error("Initial payment failed to verify", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
return;
} catch (ValueOutOfRangeException e) {
log.error("Initial payment value was out of range", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
return;
} catch (InsufficientMoneyException e) {
// This shouldn't happen because the server shouldn't allow itself to get into this situation in the
// first place, by specifying a min up front payment.
log.error("Tried to settle channel and could not afford the fees whilst updating payment", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
return;
}
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CHANNEL_OPEN)
.build());
step = InitStep.CHANNEL_OPEN;
conn.channelOpen(contractHash);
} finally {
lock.unlock();
}
}
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
final Protos.ProvideContract providedContract = msg.getProvideContract();
//TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
final Transaction multisigContract = new Transaction(wallet.getParams(), providedContract.getTx().toByteArray());
step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
state.provideMultiSigContract(multisigContract)
.addListener(new Runnable() {
@Override
public void run() {
multisigContractPropogated(providedContract, multisigContract.getHash());
}
}, Threading.SAME_THREAD);
}
@GuardedBy("lock")
private void receiveUpdatePaymentMessage(Protos.UpdatePayment msg, boolean sendAck) throws VerificationException, ValueOutOfRangeException, InsufficientMoneyException {
log.info("Got a payment update");
Coin lastBestPayment = state.getBestValueToMe();
final Coin refundSize = Coin.valueOf(msg.getClientChangeValue());
boolean stillUsable = state.incrementPayment(refundSize, msg.getSignature().toByteArray());
Coin bestPaymentChange = state.getBestValueToMe().subtract(lastBestPayment);
ByteString ackInfo = null;
if (bestPaymentChange.signum() > 0) {
ByteString info = (msg.hasInfo()) ? msg.getInfo() : null;
ackInfo = conn.paymentIncrease(bestPaymentChange, state.getBestValueToMe(), info);
}
if (sendAck) {
Protos.TwoWayChannelMessage.Builder ack = Protos.TwoWayChannelMessage.newBuilder();
ack.setType(Protos.TwoWayChannelMessage.MessageType.PAYMENT_ACK);
if (ackInfo != null) ack.setPaymentAck(ack.getPaymentAckBuilder().setInfo(ackInfo));
conn.sendToClient(ack.build());
}
if (!stillUsable) {
log.info("Channel is now fully exhausted, closing/initiating settlement");
settlePayment(CloseReason.CHANNEL_EXHAUSTED);
}
}
/**
* Called when a message is received from the client. Processes the given message and generates events based on its
* content.
*/
public void receiveMessage(Protos.TwoWayChannelMessage msg) {
lock.lock();
try {
checkState(connectionOpen);
if (channelSettling)
return;
// If we generate an error, we set errorBuilder and closeReason and break, otherwise we return
Protos.Error.Builder errorBuilder;
CloseReason closeReason;
try {
switch (msg.getType()) {
case CLIENT_VERSION:
receiveVersionMessage(msg);
return;
case PROVIDE_REFUND:
receiveRefundMessage(msg);
return;
case PROVIDE_CONTRACT:
receiveContractMessage(msg);
return;
case UPDATE_PAYMENT:
checkState(step == InitStep.CHANNEL_OPEN && msg.hasUpdatePayment());
receiveUpdatePaymentMessage(msg.getUpdatePayment(), true);
return;
case CLOSE:
receiveCloseMessage();
return;
case ERROR:
checkState(msg.hasError());
log.error("Client sent ERROR {} with explanation {}", msg.getError().getCode().name(),
msg.getError().hasExplanation() ? msg.getError().getExplanation() : "");
conn.destroyConnection(CloseReason.REMOTE_SENT_ERROR);
return;
default:
final String errorText = "Got unknown message type or type that doesn't apply to servers.";
error(errorText, Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} catch (VerificationException e) {
log.error("Caught verification exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (ValueOutOfRangeException e) {
log.error("Caught value out of range exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (InsufficientMoneyException e) {
log.error("Caught insufficient money exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (IllegalStateException e) {
log.error("Caught illegal state exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} finally {
lock.unlock();
}
}
private void error(String message, Protos.Error.ErrorCode errorCode, CloseReason closeReason) {
log.error(message);
Protos.Error.Builder errorBuilder;
errorBuilder = Protos.Error.newBuilder()
.setCode(errorCode)
.setExplanation(message);
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setError(errorBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.ERROR)
.build());
conn.destroyConnection(closeReason);
}
@GuardedBy("lock")
private void receiveCloseMessage() throws InsufficientMoneyException {
log.info("Got CLOSE message, closing channel");
if (state != null) {
settlePayment(CloseReason.CLIENT_REQUESTED_CLOSE);
} else {
conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
}
}
@GuardedBy("lock")
private void settlePayment(final CloseReason clientRequestedClose) throws InsufficientMoneyException {
// Setting channelSettling here prevents us from sending another CLOSE when state.close() calls
// close() on us here below via the stored channel state.
// TODO: Strongly separate the lifecycle of the payment channel from the TCP connection in these classes.
channelSettling = true;
Futures.addCallback(state.close(), new FutureCallback<Transaction>() {
@Override
public void onSuccess(Transaction result) {
// Send the successfully accepted transaction back to the client.
final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
msg.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE);
if (result != null) {
// Result can be null on various error paths, like if we never actually opened
// properly and so on.
msg.getSettlementBuilder().setTx(ByteString.copyFrom(result.bitcoinSerialize()));
log.info("Sending CLOSE back with broadcast settlement tx.");
} else {
log.info("Sending CLOSE back without broadcast settlement tx.");
}
conn.sendToClient(msg.build());
conn.destroyConnection(clientRequestedClose);
}
@Override
public void onFailure(Throwable t) {
log.error("Failed to broadcast settlement tx", t);
conn.destroyConnection(clientRequestedClose);
}
});
}
/**
* <p>Called when the connection terminates. Notifies the {@link StoredServerChannel} object that we can attempt to
* resume this channel in the future and stops generating messages for the client.</p>
*
* <p>Note that this <b>MUST</b> still be called even after either
* {@link ServerConnection#destroyConnection(CloseReason)} or
* {@link PaymentChannelServer#close()} is called to actually handle the connection close logic.</p>
*/
public void connectionClosed() {
lock.lock();
try {
log.info("Server channel closed.");
connectionOpen = false;
try {
if (state != null && state.getMultisigContract() != null) {
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)
wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
if (channels != null) {
StoredServerChannel storedServerChannel = channels.getChannel(state.getMultisigContract().getHash());
if (storedServerChannel != null) {
storedServerChannel.clearConnectedHandler();
}
}
}
} catch (IllegalStateException e) {
// Expected when we call getMultisigContract() sometimes
}
} finally {
lock.unlock();
}
}
/**
* Called to indicate the connection has been opened and messages can now be generated for the client.
*/
public void connectionOpen() {
lock.lock();
try {
log.info("New server channel active.");
connectionOpen = true;
} finally {
lock.unlock();
}
}
/**
* <p>Closes the connection by generating a settle message for the client and calls
* {@link ServerConnection#destroyConnection(CloseReason)}. Note that this does not broadcast
* the payment transaction and the client may still resume the same channel if they reconnect</p>
*
* <p>Note that {@link PaymentChannelServer#connectionClosed()} must still be called after the connection fully
* closes.</p>
*/
public void close() {
lock.lock();
try {
if (connectionOpen && !channelSettling) {
final Protos.TwoWayChannelMessage.Builder msg = Protos.TwoWayChannelMessage.newBuilder();
msg.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE);
conn.sendToClient(msg.build());
conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
}
} finally {
lock.unlock();
}
}
}
| {'content_hash': 'bb6bdfd18fdda66283f2149753ef3ae5', 'timestamp': '', 'source': 'github', 'line_count': 506, 'max_line_length': 172, 'avg_line_length': 50.06521739130435, 'alnum_prop': 0.6387715627837208, 'repo_name': 'Kangmo/bitcoinj', 'id': '4b47f606f1cff0e7867435acf207ac4d45b44ed6', 'size': '25956', 'binary': False, 'copies': '1', 'ref': 'refs/heads/bitcoinj-scala', 'path': 'core/src/main/scala/com/nhnsoft/bitcoin/protocols/channels/PaymentChannelServer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1257'}, {'name': 'Java', 'bytes': '3881323'}, {'name': 'Scala', 'bytes': '121253'}]} |
using System;
namespace FinancialControl.Model
{
public class ModelException : Exception
{
public ModelException() { }
public ModelException(string message) : base(message) { }
public ModelException(string message, Exception inner) : base(message, inner) { }
}
}
| {'content_hash': '1874a08a82474c5b069279024d2d3a8a', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 83, 'avg_line_length': 25.90909090909091, 'alnum_prop': 0.7087719298245614, 'repo_name': 'brheringer/FinancialControl', 'id': '0401607bc55374aeb7c044fed41ce57f51e0ff97', 'size': '287', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Model/ModelException.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '161109'}, {'name': 'CSS', 'bytes': '11605'}, {'name': 'HTML', 'bytes': '162513'}, {'name': 'JavaScript', 'bytes': '197108'}, {'name': 'SCSS', 'bytes': '3530'}, {'name': 'TypeScript', 'bytes': '186954'}]} |
package com.sun.jini.test.impl.fiddler.joinadmin;
import net.jini.core.discovery.LookupLocator;
import java.net.MalformedURLException;
/**
* This class determines whether or not the lookup discovery service can
* successfully replace set of locators with which it has been configured
* to join with a new set of locators.
*
* This test attempts to replace a non-empty set of locators with which the
* service is currently configured with an empty set of locators.
*
* Note that this test class is a sub-class of the class
* <code>SetLookupLocatorss</code>. That parent class performs almost
* all of the processing for this test. This is because the only
* difference between this test and the test being performed by the
* parent class is in the contents of the set of locators with which
* the test and/or the lookup discovery service under test is configured.
* Rather than running one test multiple times, editing a single shared
* configuration file for each run, running separate tests that perform
* identical functions but which are associated with different configuration
* files allows for efficient batching of the test runs. Thus, providing
* one parent test class from which all other related tests are sub-classed
* provides for efficient code re-use.
*
* @see <code>com.sun.jini.test.impl.fiddler.joinadmin.SetLookupGroups</code>
*
* @see <code>net.jini.discovery.DiscoveryLocatorManagement</code>
*/
public class SetLookupLocatorsFiniteToEmpty extends SetLookupLocators {
/** Constructs and returns the set of locators with which to replace
* the service's current set of locators (overrides the parent class'
* version of this method)
*/
LookupLocator[] getTestLocatorSet() throws MalformedURLException {
return new LookupLocator[0];
}
}
| {'content_hash': 'ba0470cad642faa45d8fb6896abc0205', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 78, 'avg_line_length': 41.5, 'alnum_prop': 0.7628696604600219, 'repo_name': 'cdegroot/river', 'id': 'e33a0365ee514960858c8fc1641081e11b674797', 'size': '2632', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'qa/src/com/sun/jini/test/impl/fiddler/joinadmin/SetLookupLocatorsFiniteToEmpty.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2047'}, {'name': 'Groovy', 'bytes': '16876'}, {'name': 'Java', 'bytes': '22265383'}, {'name': 'Shell', 'bytes': '117083'}]} |
<?php
declare(strict_types=1);
namespace EdmondsCommerce\DoctrineStaticMeta\Tests\Small\Validation\Constraints\FieldConstraints;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Validation\Constraints\FieldConstraints\DomainName;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Validation\Constraints\FieldConstraints\DomainNameValidator;
use Generator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @small
* @covers \EdmondsCommerce\DoctrineStaticMeta\Entity\Validation\Constraints\FieldConstraints\DomainNameValidator
*/
class DomainNameValidatorTest extends ConstraintValidatorTestCase
{
public const VALID = [
'domainname.com' .
'edmondscommerce.co.uk',
'www.edmondscommerce.co.uk',
];
public const INVALID = [
'nodots',
'//isurl.com',
'999',
];
public function provideValid(): Generator
{
foreach (self::VALID as $value) {
yield $value => [$value];
}
}
/**
* @test
* @small
*
* @param string $value
*
* @dataProvider provideValid
*/
public function noViolationsForValidValues(string $value): void
{
$this->validator->validate($value, new DomainName());
$this->assertNoViolation();
}
public function provideInvalid(): Generator
{
foreach (self::INVALID as $value) {
yield $value => [$value];
}
}
/**
* @test
* @small
*
* @param string $value
*
* @dataProvider provideInvalid
*/
public function violationsForInvalidValues(string $value): void
{
$this->validator->validate($value, new DomainName());
$this->buildViolation(sprintf(DomainName::MESSAGE, '"' . $value . '"'))
->setParameter('{{ value }}', '"' . $value . '"')
->setCode(DomainName::INVALID_DOMAIN_ERROR)
->assertRaised();
}
protected function createValidator()
{
return new DomainNameValidator();
}
}
| {'content_hash': 'a605279af3be879ced3491f08ad716cd', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 113, 'avg_line_length': 25.160493827160494, 'alnum_prop': 0.626594700686948, 'repo_name': 'edmondscommerce/doctrine-static-meta', 'id': '6e2b5f50c9428ce902bc074e9648dabe602a6820', 'size': '2038', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Small/Validation/Constraints/FieldConstraints/DomainNameValidatorTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '1831729'}, {'name': 'Shell', 'bytes': '8486'}]} |
`Ajax` is a droplab plugin that allows for retrieving and rendering list data from a server.
## Usage
Add the `Ajax` object to the plugins array of a `DropLab.prototype.init` or `DropLab.prototype.addHook` call.
`Ajax` requires 2 config values, the `endpoint` and `method`.
* `endpoint` should be a URL to the request endpoint.
* `method` should be `setData` or `addData`.
* `setData` completely replaces the dropdown with the response data.
* `addData` appends the response data to the current dropdown list.
```html
<a href="#" id="trigger" data-dropdown-trigger="#list">Toggle</a>
<ul id="list" data-dropdown><!-- ... --><ul>
```
```js
const droplab = new DropLab();
const trigger = document.getElementById('trigger');
const list = document.getElementById('list');
droplab.addHook(trigger, list, [Ajax], {
Ajax: {
endpoint: '/some-endpoint',
method: 'setData',
},
});
```
Optionally you can set `loadingTemplate` to a HTML string. This HTML string will
replace the dropdown list whilst the request is pending.
Additionally, you can set `onError` to a function to catch any XHR errors.
| {'content_hash': '4ccb5a65bb3914c657f3567029f169ba', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 109, 'avg_line_length': 32.2, 'alnum_prop': 0.7036379769299024, 'repo_name': 'htve/GitlabForChinese', 'id': '9c7e56fa448f020cadb960ae7d53177f6bdd2173', 'size': '1135', 'binary': False, 'copies': '9', 'ref': 'refs/heads/9-2-zh', 'path': 'doc/development/fe_guide/droplab/plugins/ajax.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '499575'}, {'name': 'Gherkin', 'bytes': '140955'}, {'name': 'HTML', 'bytes': '979335'}, {'name': 'JavaScript', 'bytes': '1909827'}, {'name': 'Ruby', 'bytes': '10590735'}, {'name': 'Shell', 'bytes': '26903'}, {'name': 'Vue', 'bytes': '81150'}]} |
package com.mhuang.wechat.common.utils;
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
| {'content_hash': '125f21b60e0aa63cb56790deb5f23f7f', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 74, 'avg_line_length': 29.15, 'alnum_prop': 0.6312178387650086, 'repo_name': 'huangmiao/wechat', 'id': 'db27f2259b30a10a18f564a68a4cf05b3d8c6a47', 'size': '1166', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/mhuang/wechat/common/utils/MD5Util.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '95498'}]} |
<!DOCTYPE html>
<html dir="ltr" lang="pl">
<head>
<title>IO - Rubinius</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content='pl' http-equiv='content-language'>
<meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
<link href='/' rel='home'>
<link href='/' rel='start'>
<link href='/doc/pl/systems/concurrency' rel='prev' title='Concurrency'>
<link href='/doc/pl/systems/c-api' rel='next' title='C-API'>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]-->
<script src="/javascripts/jquery-1.3.2.js"></script>
<script src="/javascripts/paging_keys.js"></script>
<script src="/javascripts/application.js"></script>
<style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style>
<link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" />
<!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" />
</head>
<body>
<div class='container'>
<div class='span-21 doc_menu'>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a id="blog" href="/blog">Blog</a></li>
<li><a id="documentation" href="/doc/en">Documentation</a></li>
<li><a href="/projects">Projects</a></li>
<li><a href="/roadmap">Roadmap</a></li>
<li><a href="/releases">Releases</a></li>
</ul>
</nav>
</header>
</div>
<div class='span-3 last'>
<div id='version'>
<a href="/releases/1.2.4">1.2.4</a>
</div>
</div>
</div>
<div class="container languages">
<nav>
<span class="label">Język:</span>
<ul>
<li><a href="/doc/de/systems/io/"
>de</a></li>
<li><a href="/doc/en/systems/io/"
>en</a></li>
<li><a href="/doc/es/systems/io/"
>es</a></li>
<li><a href="/doc/fr/systems/io/"
>fr</a></li>
<li><a href="/doc/ja/systems/io/"
>ja</a></li>
<li><a href="/doc/pl/systems/io/"
class="current"
>pl</a></li>
<li><a href="/doc/pt-br/systems/io/"
>pt-br</a></li>
<li><a href="/doc/ru/systems/io/"
>ru</a></li>
</ul>
</nav>
</div>
<div class="container doc_page_nav">
<span class="label">Wstecz:</span>
<a href="/doc/pl/systems/concurrency">Concurrency</a>
<span class="label">Do góry:</span>
<a href="/doc/pl/">Spis treści</a>
<span class="label">Dalej:</span>
<a href="/doc/pl/systems/c-api">C-API</a>
</div>
<div class="container documentation">
<h2>IO</h2>
<div class="review">
<p>This topic has missing or partial documentation. Please help us improve it.</p>
<p>
See <a href="/doc/pl/how-to/write-documentation">How-To - Write Documentation</a>
</p>
</div>
</div>
<div class="container doc_page_nav">
<span class="label">Wstecz:</span>
<a href="/doc/pl/systems/concurrency">Concurrency</a>
<span class="label">Do góry:</span>
<a href="/doc/pl/">Spis treści</a>
<span class="label">Dalej:</span>
<a href="/doc/pl/systems/c-api">C-API</a>
</div>
<div class="container">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'rubinius';
var disqus_identifier = '/doc/pl/systems/io/';
var disqus_url = 'http://rubini.us/doc/pl/systems/io/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
<footer>
<div class='container'>
<nav>
<ul>
<li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li>
<li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li>
<li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li>
</ul>
</nav>
</div>
</footer>
<script>
var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
| {'content_hash': 'a8dac97ffb0d7312fc0d0bc0f7f8ae8b', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 338, 'avg_line_length': 25.919811320754718, 'alnum_prop': 0.5885350318471337, 'repo_name': 'PragTob/rubinius', 'id': 'aa8f509cf8567d06f15987fbc42dfdd7066688c8', 'size': '5500', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/_site/doc/pl/systems/io/index.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
package com.cloudworkers.cloudworker.repository;
import com.cloudworkers.cloudworker.domain.PersistentAuditEvent;
import java.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the PersistentAuditEvent entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfter(String principal, LocalDateTime after);
List<PersistentAuditEvent> findAllByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate);
}
| {'content_hash': '6d4984009b93c0b65015e2bd6c9fa117', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 108, 'avg_line_length': 35.0, 'alnum_prop': 0.8385714285714285, 'repo_name': 'CloudWorkers/cloudworker', 'id': '6499369d12d3ab550a8e031e151172a56327e860', 'size': '700', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/src/main/java/com/cloudworkers/cloudworker/repository/PersistenceAuditEventRepository.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3798'}, {'name': 'HTML', 'bytes': '134085'}, {'name': 'Java', 'bytes': '295705'}, {'name': 'JavaScript', 'bytes': '199286'}, {'name': 'Python', 'bytes': '17505'}, {'name': 'Scala', 'bytes': '22642'}]} |
package de.taimos.dvalin.monitoring;
import de.taimos.daemon.spring.annotations.TestComponent;
@TestComponent
public class SysoutMetricSender implements MetricSender {
@Override
public void sendMetric(MetricInfo metric, Double value) {
String s = String.format("Sending metric %s/%s with value %s %s %s", metric.getNamespace(), metric.getMetric(), value, metric.getUnit(), metric.getDimensions().toString());
System.out.println(s);
}
}
| {'content_hash': '53f2ec4ce17bd10f8289504b0308f240', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 180, 'avg_line_length': 31.266666666666666, 'alnum_prop': 0.7270788912579957, 'repo_name': 'taimos/dvalin', 'id': 'cae093f3b0d73ee2c23e1e53746b3872543a2578', 'size': '1130', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'monitoring/core/src/test/java/de/taimos/dvalin/monitoring/SysoutMetricSender.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '533'}, {'name': 'HTML', 'bytes': '3736'}, {'name': 'Java', 'bytes': '1249209'}, {'name': 'Shell', 'bytes': '1497'}]} |
<?php
namespace backend\tests\unit\hint;
use backend\modules\hint\models\HintCityForm;
use backend\tests\unit\Unit;
use common\fixtures\helpers\HintFixtureHelper;
use common\fixtures\helpers\TerytFixtureHelper;
use common\models\hint\HintCity;
use common\tests\_support\UnitModelTrait;
use yii\base\Model;
class HintCityFormTest extends Unit {
use UnitModelTrait;
private HintCityForm $model;
public function _fixtures(): array {
return array_merge(
TerytFixtureHelper::fixtures(),
HintFixtureHelper::city(),
HintFixtureHelper::user()
);
}
public function testEmpty(): void {
$this->giveModel([]);
$this->thenUnsuccessValidate();
$this->thenSeeError('City cannot be blank.', 'city_id');
$this->thenSeeError('User cannot be blank.', 'user_id');
}
public function testCityWithoutHint(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'details' => 'New lebork hint.',
]);
$this->thenSuccessSave();
$this->thenSeeRecord([
'city_id' => TerytFixtureHelper::SIMC_ID_BIELSKO_BIALA,
'user_id' => 1,
'status' => HintCity::STATUS_NEW,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
}
public function testAbandonedWithoutDetails(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'status' => HintCity::STATUS_ABANDONED,
]);
$this->thenUnsuccessValidate();
$this->thenSeeError('Details cannot be blank when status is abandoned.', 'details');
}
public function testAbandonedWithDetails(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'status' => HintCity::STATUS_ABANDONED,
'details' => 'Not found active targets.',
]);
$this->thenSuccessSave();
$this->thenSeeRecord([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'status' => HintCity::STATUS_ABANDONED,
'details' => 'Not found active targets.',
]);
}
public function testSameTypeUserAndCity(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
$this->thenSuccessSave();
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
$this->thenUnsuccessValidate();
$this->tester->assertTrue($this->getModel()->hasErrors('user_id'));
$this->tester->assertTrue($this->getModel()->hasErrors('type'));
$this->tester->assertTrue($this->getModel()->hasErrors('city_id'));
}
public function testSameTypeUserAndOtherCity(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
$this->thenSuccessSave();
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_CEWICE,
'user_id' => 1,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
$this->thenSuccessSave();
}
public function testSameUserAndCityWithOtherType(): void {
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'type' => HintCity::TYPE_CARE_BENEFITS,
]);
$this->thenSuccessSave();
$this->giveModel([
'city_id' => TerytFixtureHelper::SIMC_ID_LEBORK,
'user_id' => 1,
'type' => HintCity::TYPE_COMMISSION_REFUNDS,
]);
$this->thenSuccessSave();
}
public function testEmptyType(): void {
$this->giveModel(['type' => '']);
$this->thenUnsuccessValidate();
$this->thenSeeError('Type cannot be blank.', 'type');
}
public function testEmptyStatus(): void {
$this->giveModel(['status' => '']);
$this->thenUnsuccessValidate();
$this->thenSeeError('Status cannot be blank.', 'status');
}
private function thenSeeRecord(array $attributes): void {
$this->tester->seeRecord(HintCity::class, $attributes);
}
private function giveModel(array $config): void {
$this->model = new HintCityForm($config);
}
public function getModel(): Model {
return $this->model;
}
}
| {'content_hash': 'fad37ebc359030a15f57bc3b6540a9c9', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 86, 'avg_line_length': 26.589403973509935, 'alnum_prop': 0.6657534246575343, 'repo_name': 'edzima/VestraTele', 'id': '0ed6518be51c429ccf9315e916ababb60c3d1ad2', 'size': '4015', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'backend/tests/unit/hint/HintCityFormTest.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '970'}, {'name': 'CSS', 'bytes': '6759'}, {'name': 'Dockerfile', 'bytes': '327'}, {'name': 'HTML', 'bytes': '7549'}, {'name': 'JavaScript', 'bytes': '27669'}, {'name': 'PHP', 'bytes': '3099238'}, {'name': 'Shell', 'bytes': '3173'}, {'name': 'TypeScript', 'bytes': '5231'}, {'name': 'Vue', 'bytes': '34794'}]} |
package org.jclouds.vcloud.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.http.HttpUtils.releasePayload;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.vcloud.VCloudToken;
import org.jclouds.vcloud.domain.ReferenceType;
import org.jclouds.vcloud.domain.VCloudSession;
import org.jclouds.vcloud.endpoints.Org;
import org.jclouds.vcloud.xml.OrgListHandler;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.net.HttpHeaders;
/**
* This parses {@link VCloudSession} from HTTP headers.
*/
@Singleton
public class ParseLoginResponseFromHeaders implements Function<HttpResponse, VCloudSession> {
static final Pattern pattern = Pattern.compile("(vcloud-token)=?([^;]+)(;.*)?");
private final ParseSax.Factory factory;
private final Provider<OrgListHandler> orgHandlerProvider;
@Inject
private ParseLoginResponseFromHeaders(Factory factory, Provider<OrgListHandler> orgHandlerProvider) {
this.factory = factory;
this.orgHandlerProvider = orgHandlerProvider;
}
/**
* parses the http response headers to create a new {@link VCloudSession} object.
*/
public VCloudSession apply(HttpResponse from) {
try {
final String token = parseTokenFromHeaders(from);
final Map<String, ReferenceType> org = factory.create(orgHandlerProvider.get()).parse(
checkNotNull(from.getPayload().getInput(), "no payload in http response to login request %s", from));
return new VCloudSession() {
@VCloudToken
public String getVCloudToken() {
return token;
}
@Org
public Map<String, ReferenceType> getOrgs() {
return org;
}
};
} finally {
releasePayload(from);
}
}
public String parseTokenFromHeaders(HttpResponse from) {
String cookieHeader = from.getFirstHeaderOrNull("x-vcloud-authorization");
if (cookieHeader != null) {
Matcher matcher = pattern.matcher(cookieHeader);
return matcher.find() ? matcher.group(2) : cookieHeader;
} else {
try {
cookieHeader = Iterables.find(from.getHeaders().get(HttpHeaders.SET_COOKIE), Predicates.contains(pattern));
Matcher matcher = pattern.matcher(cookieHeader);
matcher.find();
return matcher.group(2);
} catch (NoSuchElementException e) {
throw new HttpResponseException(String.format("Header %s or %s must be present", "x-vcloud-authorization",
HttpHeaders.SET_COOKIE), null, from);
}
}
}
}
| {'content_hash': '9745daf4cc5a253dae6889401c06f834', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 119, 'avg_line_length': 35.45454545454545, 'alnum_prop': 0.6958333333333333, 'repo_name': 'agentmilindu/stratos', 'id': 'd9900fd24743d7e0e3c28d438d645feebd3ecb6d', 'size': '3921', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'dependencies/jclouds/apis/vcloud/1.8.1-stratos/src/main/java/org/jclouds/vcloud/functions/ParseLoginResponseFromHeaders.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '27195'}, {'name': 'CSS', 'bytes': '78732'}, {'name': 'HTML', 'bytes': '42426'}, {'name': 'Handlebars', 'bytes': '107928'}, {'name': 'Java', 'bytes': '5852567'}, {'name': 'JavaScript', 'bytes': '748255'}, {'name': 'Python', 'bytes': '516805'}, {'name': 'Ruby', 'bytes': '3546'}, {'name': 'Shell', 'bytes': '157268'}]} |
namespace v8 {
namespace internal {
template <typename T>
void ZoneList<T>::Add(const T& element, Zone* zone) {
if (length_ < capacity_) {
data_[length_++] = element;
} else {
ZoneList<T>::ResizeAdd(element, ZoneAllocationPolicy(zone));
}
}
template <typename T>
void ZoneList<T>::AddAll(const ZoneList<T>& other, Zone* zone) {
AddAll(other.ToVector(), zone);
}
template <typename T>
void ZoneList<T>::AddAll(const Vector<T>& other, Zone* zone) {
int result_length = length_ + other.length();
if (capacity_ < result_length)
Resize(result_length, ZoneAllocationPolicy(zone));
if (std::is_fundamental<T>()) {
memcpy(data_ + length_, other.start(), sizeof(*data_) * other.length());
} else {
for (int i = 0; i < other.length(); i++) data_[length_ + i] = other.at(i);
}
length_ = result_length;
}
// Use two layers of inlining so that the non-inlined function can
// use the same implementation as the inlined version.
template <typename T>
void ZoneList<T>::ResizeAdd(const T& element, ZoneAllocationPolicy alloc) {
ResizeAddInternal(element, alloc);
}
template <typename T>
void ZoneList<T>::ResizeAddInternal(const T& element,
ZoneAllocationPolicy alloc) {
DCHECK(length_ >= capacity_);
// Grow the list capacity by 100%, but make sure to let it grow
// even when the capacity is zero (possible initial case).
int new_capacity = 1 + 2 * capacity_;
// Since the element reference could be an element of the list, copy
// it out of the old backing storage before resizing.
T temp = element;
Resize(new_capacity, alloc);
data_[length_++] = temp;
}
template <typename T>
void ZoneList<T>::Resize(int new_capacity, ZoneAllocationPolicy alloc) {
DCHECK_LE(length_, new_capacity);
T* new_data = NewData(new_capacity, alloc);
if (length_ > 0) {
MemCopy(new_data, data_, length_ * sizeof(T));
}
ZoneList<T>::DeleteData(data_);
data_ = new_data;
capacity_ = new_capacity;
}
template <typename T>
Vector<T> ZoneList<T>::AddBlock(T value, int count, Zone* zone) {
int start = length_;
for (int i = 0; i < count; i++) Add(value, zone);
return Vector<T>(&data_[start], count);
}
template <typename T>
void ZoneList<T>::Set(int index, const T& elm) {
DCHECK(index >= 0 && index <= length_);
data_[index] = elm;
}
template <typename T>
void ZoneList<T>::InsertAt(int index, const T& elm, Zone* zone) {
DCHECK(index >= 0 && index <= length_);
Add(elm, zone);
for (int i = length_ - 1; i > index; --i) {
data_[i] = data_[i - 1];
}
data_[index] = elm;
}
template <typename T>
T ZoneList<T>::Remove(int i) {
T element = at(i);
length_--;
while (i < length_) {
data_[i] = data_[i + 1];
i++;
}
return element;
}
template <typename T>
void ZoneList<T>::Clear() {
DeleteData(data_);
// We don't call Initialize(0) since that requires passing a Zone,
// which we don't really need.
data_ = nullptr;
capacity_ = 0;
length_ = 0;
}
template <typename T>
void ZoneList<T>::Rewind(int pos) {
DCHECK(0 <= pos && pos <= length_);
length_ = pos;
}
template <typename T>
template <class Visitor>
void ZoneList<T>::Iterate(Visitor* visitor) {
for (int i = 0; i < length_; i++) visitor->Apply(&data_[i]);
}
template <typename T>
template <typename CompareFunction>
void ZoneList<T>::Sort(CompareFunction cmp) {
ToVector().Sort(cmp, 0, length_);
#ifdef DEBUG
for (int i = 1; i < length_; i++) {
DCHECK_LE(cmp(&data_[i - 1], &data_[i]), 0);
}
#endif
}
template <typename T>
template <typename CompareFunction>
void ZoneList<T>::StableSort(CompareFunction cmp, size_t s, size_t l) {
ToVector().StableSort(cmp, s, l);
#ifdef DEBUG
for (size_t i = s + 1; i < l; i++) {
DCHECK_LE(cmp(&data_[i - 1], &data_[i]), 0);
}
#endif
}
} // namespace internal
} // namespace v8
#endif // V8_ZONE_ZONE_LIST_INL_H_
| {'content_hash': '123d8b8feeae98984cd908dfba29f44f', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 78, 'avg_line_length': 26.717241379310344, 'alnum_prop': 0.6399070727929789, 'repo_name': 'weolar/miniblink49', 'id': 'a0e4b1950bd01bfcaa791c33e4a20cd5cc396c81', 'size': '4232', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'v8_7_5/src/zone/zone-list-inl.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '11324372'}, {'name': 'Batchfile', 'bytes': '52488'}, {'name': 'C', 'bytes': '32157305'}, {'name': 'C++', 'bytes': '280103993'}, {'name': 'CMake', 'bytes': '88548'}, {'name': 'CSS', 'bytes': '20839'}, {'name': 'DIGITAL Command Language', 'bytes': '226954'}, {'name': 'HTML', 'bytes': '202637'}, {'name': 'JavaScript', 'bytes': '32539485'}, {'name': 'Lua', 'bytes': '32432'}, {'name': 'M4', 'bytes': '125191'}, {'name': 'Makefile', 'bytes': '1517330'}, {'name': 'NASL', 'bytes': '42'}, {'name': 'Objective-C', 'bytes': '5320'}, {'name': 'Objective-C++', 'bytes': '35037'}, {'name': 'POV-Ray SDL', 'bytes': '307541'}, {'name': 'Perl', 'bytes': '3283676'}, {'name': 'Prolog', 'bytes': '29177'}, {'name': 'Python', 'bytes': '4331616'}, {'name': 'R', 'bytes': '10248'}, {'name': 'Scheme', 'bytes': '25457'}, {'name': 'Shell', 'bytes': '264021'}, {'name': 'TypeScript', 'bytes': '166033'}, {'name': 'Vim Script', 'bytes': '11362'}, {'name': 'XS', 'bytes': '4319'}, {'name': 'eC', 'bytes': '4383'}]} |
package com.intellij.debugger.engine;
import com.intellij.debugger.engine.SuspendContextImpl;
public interface SuspendContextRunnable {
void run(SuspendContextImpl suspendContext) throws Exception;
}
| {'content_hash': '7927bbdf9682d5bd7546e4e14a3d127c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 63, 'avg_line_length': 25.75, 'alnum_prop': 0.8349514563106796, 'repo_name': 'liveqmock/platform-tools-idea', 'id': '6df6a1463d7170211cbfe29881abde9b1bab7b1d', 'size': '806', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextRunnable.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '182'}, {'name': 'C', 'bytes': '174455'}, {'name': 'C#', 'bytes': '326'}, {'name': 'C++', 'bytes': '76245'}, {'name': 'CSS', 'bytes': '10373'}, {'name': 'Cucumber', 'bytes': '14485'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'FLUX', 'bytes': '57'}, {'name': 'Groff', 'bytes': '35084'}, {'name': 'Groovy', 'bytes': '1838147'}, {'name': 'HTML', 'bytes': '1209876'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '116762135'}, {'name': 'JavaScript', 'bytes': '112'}, {'name': 'Objective-C', 'bytes': '18984'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6570'}, {'name': 'Python', 'bytes': '2787996'}, {'name': 'Shell', 'bytes': '68627'}, {'name': 'Smalltalk', 'bytes': '64'}, {'name': 'XSLT', 'bytes': '113040'}]} |
require('./required.test');
require('./pattern.test');
require('./min-length.test');
require('./email.test'); | {'content_hash': '906fc9861cda28c36e306c4750ac89e2', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 29, 'avg_line_length': 27.25, 'alnum_prop': 0.6697247706422018, 'repo_name': 'toxa16/strategic-routing', 'id': '8c89a5fc8d11416379640d5438dcb502099a3438', 'size': '109', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/_parameter-decorators/index.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'TypeScript', 'bytes': '41440'}]} |
require('../../modules/es.array-buffer.constructor');
require('../../modules/es.array-buffer.slice');
require('../../modules/es.typed-array.uint8-array');
require('./methods');
var global = require('../../internals/global');
module.exports = global.Uint8Array;
| {'content_hash': '944acb2b1747a73fc84a360736a60660', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 53, 'avg_line_length': 37.42857142857143, 'alnum_prop': 0.6870229007633588, 'repo_name': 'GoogleCloudPlatform/prometheus-engine', 'id': '7b547c19af3e3b7a42378977327a671da4d0b98c', 'size': '262', 'binary': False, 'copies': '12', 'ref': 'refs/heads/main', 'path': 'third_party/prometheus_ui/base/web/ui/node_modules/core-js/es/typed-array/uint8-array.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '4035'}, {'name': 'Go', 'bytes': '574177'}, {'name': 'Makefile', 'bytes': '5189'}, {'name': 'Shell', 'bytes': '11915'}]} |
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;
use un\unece\uncefact\data\specification\UnqualifiedDataTypesSchemaModule\_2;
/**
* @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
* @xmlType IdentifierType
* @xmlName MarkingIDType
* @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\MarkingIDType
*/
class MarkingIDType extends _2\IdentifierType
{
} // end class MarkingIDType
| {'content_hash': 'f027105fb83af9ef4742932b0898f5ae', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 86, 'avg_line_length': 33.785714285714285, 'alnum_prop': 0.8118393234672304, 'repo_name': 'intuit/QuickBooks-V3-PHP-SDK', 'id': '03f675555ade9d0a3d433c17e76a3b0a8543c384', 'size': '473', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/XSD2PHP/test/data/expected/ContactCompany/oasis/names/specification/ubl/schema/xsd/CommonBasicComponents_2/MarkingIDType.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9685'}, {'name': 'HTML', 'bytes': '586385'}, {'name': 'PHP', 'bytes': '6194516'}, {'name': 'Shell', 'bytes': '99'}, {'name': 'XSLT', 'bytes': '12092'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>maven-archetype-templates</artifactId>
<groupId>com.evangel</groupId>
<!--suppress MavenPropertyInParent -->
<version>${maven-archetype-templates.version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.evangel</groupId>
<artifactId>dubbo-wusc</artifactId>
<packaging>pom</packaging>
<modules>
<module>edu-common-parent</module>
<module>edu-demo</module>
<module>edu-facade-user</module>
<module>edu-service-user</module>
<module>edu-web-boss</module>
<module>edu-common</module>
<module>edu-common-config</module>
<module>edu-common-core</module>
<module>edu-common-web</module>
</modules>
</project> | {'content_hash': '3ea9be24af1c3fba0f76e16f36620fda', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 102, 'avg_line_length': 32.03448275862069, 'alnum_prop': 0.7147470398277718, 'repo_name': 'T5750/maven-archetype-templates', 'id': 'a7f45146467d17676e1207e15a039fe375c03e38', 'size': '929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dubbo-wusc/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3130'}, {'name': 'CSS', 'bytes': '519607'}, {'name': 'FreeMarker', 'bytes': '117915'}, {'name': 'HTML', 'bytes': '141189'}, {'name': 'Java', 'bytes': '1270173'}, {'name': 'JavaScript', 'bytes': '1490538'}, {'name': 'Shell', 'bytes': '1474'}]} |
ActiveRecord::Schema.define(version: 20141212054824) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "builds", force: true do |t|
t.text "violations"
t.integer "repo_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "uuid", null: false
t.integer "merge_request_id"
t.string "commit_sha"
end
add_index "builds", ["merge_request_id", "commit_sha"], name: "index_builds_on_merge_request_id_and_commit_sha", unique: true, using: :btree
add_index "builds", ["repo_id"], name: "index_builds_on_repo_id", using: :btree
add_index "builds", ["uuid"], name: "index_builds_on_uuid", unique: true, using: :btree
create_table "memberships", force: true do |t|
t.integer "user_id", null: false
t.integer "repo_id", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "memberships", ["repo_id", "user_id"], name: "index_memberships_on_repo_id_and_user_id", using: :btree
create_table "repos", force: true do |t|
t.integer "gitlab_id", null: false
t.boolean "active", default: false, null: false
t.integer "hook_id"
t.string "full_gitlab_name", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "private"
end
add_index "repos", ["active"], name: "index_repos_on_active", using: :btree
add_index "repos", ["gitlab_id"], name: "index_repos_on_gitlab_id", using: :btree
create_table "users", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "gitlab_username", null: false
t.string "remember_token", null: false
t.boolean "refreshing_repos", default: false
t.string "email_address"
end
add_index "users", ["remember_token"], name: "index_users_on_remember_token", using: :btree
end
| {'content_hash': 'ae4ad08b651358f7b9ae335bd6ecc050', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 142, 'avg_line_length': 39.43396226415094, 'alnum_prop': 0.6086124401913876, 'repo_name': 'larrylv/hound-gitlab', 'id': '6aff400f7a7ae84babedd1c3fb81a1a3c8672c59', 'size': '2831', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/schema.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20398'}, {'name': 'CoffeeScript', 'bytes': '387'}, {'name': 'JavaScript', 'bytes': '274'}, {'name': 'Ruby', 'bytes': '178684'}, {'name': 'Shell', 'bytes': '309'}]} |
[non-automatic.xml]
<transcripts>
<transcript id="18" title="Healthy Recipes- Honey Almond Protein Crisps - Bars " url="https://www.youtube.com/watch?v=0gMPVegmz8E" mode="non-automatic">
[music] Hi, I'm Jamie Eason, and I'm in the bodybuilding.com kitchen today, and I'm excited 'cause I'm gonna show you how to make my <entity type="Recipe">Honey Almond Protein Crisps</entity>.<s>
I've showed you guys how to make chocolate protein bars, lemon protein bars, carrot cake.<s>
They're all kind of, like, cakey, so I wanted something with a little bit of crunch, and this is super, super simple and tastes really, really good.<s>
So let's get started.<s>
For this recipe we're gonna need <entity type="Amount">3</entity> <entity type="Unit">cups</entity> of <entity type="Ingredient">crispy brown rice</entity>.<s>
We're gonna need <entity type="Amount">1</entity> <entity type="Unit">cup</entity> of <entity type="Ingredient">whole oats</entity>.<s>
We're gonna also need <entity type="Amount">a</entity> <entity type="Unit">scoop</entity> of <entity type="Ingredient">vanilla protein</entity>, whichever kind you like.<s>
We'll also need <entity type="Amount">a fourth</entity> of a <entity type="Unit">cup</entity> of chopped <entity type="Ingredient">almonds</entity>.<s>
You can either just use whole <entity type="Ingredient">almonds</entity> and break 'em up yourself, or you can buy the chopped <entity type="Ingredient">almonds</entity> at the store.<s>
And then for our wet ingredients, we're gonna do <entity type="Ingredient">almond butter</entity>.<s>
We're gonna have <entity type="Ingredient">honey</entity>, and this isn't actually wet, but it's gonna go in the wet ingredients.<s>
That's our <entity type="Ingredient">xylitol brown sugar blend</entity>.<s>
This recipe is super easy, and it comes together really, really quickly.<s>
All you're gonna need is basically a large bowl so you can dump all the ingredients in, and we need a smaller bowl so that we can actually just microwave to heat it up just a little bit, so that it's easier to actually mix into our dry ingredients.<s>
And once you do that, it's pretty much done, and we stick it in the freezer.<s>
No baking at all, and you can eat it in about 30 minutes.<s>
To begin with, we've added already <entity type="Amount">3</entity> <entity type="Unit">cups</entity> of the <entity type="Ingredient">crispy brown rice</entity>.<s>
Now, you can hopefully find this at one of your local grocery stores.<s>
I've seen it at Whole Foods almost every time.<s>
The reason I like this, it's gluten free.<s>
It's really got very few ingredients.<s>
It does have some natural sugar in it, but it's from evaporated cane juice and it's organic molasses.<s>
So it's only got 2 grams of sugar per serving, which is 3/4ths of a cup, and we've got <entity type="Amount">3</entity> <entity type="Unit">cups</entity> in here, so you're looking at less than 5 grams of sugar for the entire batch, and you're not supposed to eat the entire batch.<s>
So <entity type="Amount">3</entity> <entity type="Unit">cups</entity> go in the bowl, and then we've got <entity type="Amount">1</entity> <entity type="Unit">cup</entity> of <entity type="Ingredient">whole oats</entity>...<s>
So we're gonna dump that on top.<s>
And then we're gonna add <entity type="Amount">a fourth</entity> of a <entity type="Unit">scoop</entity> of crushed <entity type="Ingredient">almonds</entity>.<s>
So you can actually do your own if you'd like and just use your trusty rolling pin and, you know, beat 'em down that way.<s>
Or you can buy 'em already chopped at the store, which is what we have...<s>
So I'm gonna add <entity type="Amount">a fourth</entity> of a <entity type="Unit">cup</entity>.<s>
And I kind of sprinkle it around, because we don't want to actually mix it up too much until we have the rest of our ingredients ready.<s>
And the last ingredient for our dry ingredients is <entity type="Amount">one</entity> <entity type="Unit">scoop</entity> of <entity type="Ingredient">protein</entity>...<s>
So I'm putting that in.<s>
And a lot of you guys always ask me, "What kind of <entity type="Ingredient">protein</entity> do I use?<s>
" Whatever kind of <entity type="Ingredient">protein</entity> you like.<s>
I just like something that's got a good vanilla flavor 'cause it's usually a good base for everything.<s>
And I always look for the fewer ingredients, the better, but whichever one you like.<s>
Some people like it with added <entity type="Ingredient">aminos</entity>, and all kinds of extra little things so that they can get, you know, added nutrition in <entity type="Amount">one</entity> little easy <entity type="Unit">scoop</entity>, so all right.<s>
I'm just gonna give it a gentle shake.<s>
Don't mix it up yet, because it'll all settle to the bottom.<s>
Set that aside.<s>
And now I'm gonna start with my wet ingredients.<s>
So we are gonna start with <entity type="Ingredient">almond butter</entity>.<s>
Now, when you buy this stuff at the store, make sure that you're getting the one that is just <entity type="Ingredient">almonds</entity> and <entity type="Ingredient">salt</entity>, or just <entity type="Ingredient">almonds</entity>.<s>
Don't get anything that has, like, added oils.<s>
As you can see, there's a ton of oil already on top.<s>
I like to pour off just a little bit.<s>
Don't pour it all off, though, because you'll have a really hard time mixing it up all the way to the bottom.<s>
So I'm gonna mix it up just a little bit... and once I get that going, we are gonna need three-fourths of a cup of this.<s>
So I like to use my one-fourth scoop.<s>
I feel like it's a little bit more manageable, so I'll just pour that in... and we'll do that three times.<s>
So I'll get that going.<s>
I have my little rubber spatula to get it out...<s>
I need three.<s>
And now you can--one of the best parts of this recipe is that it's really whatever you want to put in it, so if you wanted to use, you know, <entity type="Ingredient">peanut butter</entity> or <entity type="Ingredient">tahini</entity>, which is crushed sesame seeds, or any kind of nut butters that you like, really.<s>
You can use anything, and that goes for the nuts that you choose as well.<s>
You can choose whatever you wanted.<s>
So one more.<s>
And as you can see, this is a lot of healthy fats.<s>
You're forewarned at this point that this is not something you need every single day, but it's a great snack.<s>
And we have actually an event tomorrow where we'll be running and burning a lot of calories, so this would be great for that, because it's great for energy.<s>
All right.<s>
And it's being a little stubborn, but I think we got it all.<s>
Okay.<s>
So that goes in.<s>
So we've got our <entity type="Amount">three-fourths</entity> of a <entity type="Unit">cup</entity>.<s>
And then we're gonna need <entity type="Amount">2</entity> <entity type="Unit">cups</entity> of <entity type="Ingredient">honey</entity>.<s>
And <entity type="Ingredient">honey</entity>, of course, will still spike your blood sugar, but <entity type="Ingredient">honey</entity> is so good for you.<s>
It's loaded with antioxidants.<s>
There's all sorts of benefits to it...so we're gonna add that in.<s>
Again, this isn't for everyday consumption, but it's gonna be an awesome treat.<s>
It tastes unbelievable, actually, for so few ingredients.<s>
So we'll get that in, and one more...<s>
There we go.<s>
And actually, <entity type="Ingredient">honey</entity> is kind of fun, too, because at the store, you'll find, like, all different kinds of varieties.<s>
You might find one that's, like, lavender flavored.<s>
I got one that was rose flavored once.<s>
Not so much.<s>
I really felt like I was chewing on the lawn or something.<s>
Not good, so all right.<s>
We got that.<s>
And then to this, I'm gonna add a half a cup of <entity type="Ingredient">xylitol brown sugar blend</entity>.<s>
You don't have to use this if you don't want to, because you're fine with that amount of <entity type="Ingredient">honey</entity>.<s>
This will kind of kick up the intensity a little bit and make it a little sweeter.<s>
I think it really adds a lot to it.<s>
And it does add some calories, but unlike sugar, which is like 3.7 or something like that for sugar, this is only 2-point-something.<s>
So it's less, and actually, it's approved for diabetics, because it spikes your blood sugar less.<s>
So we're gonna throw that in there...but I do want to show you this one other alternative.<s>
Some of you may or may not be familiar with <entity type="Ingredient">sucanat</entity>.<s>
It's actually a brown sugar substitute as well.<s>
If you taste it, it's really granular, but it does have a little bit of a hint of a molasses flavor added to it without extra sugar or anything.<s>
So this is definitely an option for you.<s>
So once we've put this in the bowl, I'm gonna put it in the microwave... [beeping sound] And we're just gonna do 30-second intervals is all we need.<s>
And I'm gonna move this back over here, 'cause we're gonna need it to start mixing this together.<s>
[beeping sound] Sometimes it just takes one.<s>
Sometimes it takes a little longer.<s>
I'm gonna actually go to the bigger spatula now.<s>
Actually, that heated it up pretty well...<s>
Mix it all together... and you really, you're just heating it just enough just so that it'll spread easily inside here.<s>
I think that's actually pretty good.<s>
If you needed to, you could do another 30 seconds in the microwave.<s>
So I'm gonna go ahead and pour that in.<s>
You want to kind of spread it out a little bit and get all of it out.<s>
It's gonna seem like there's really not enough to kind of go around at first, but you just kind of have to really work it in.<s>
So now I can start working it together.<s>
I like to kind of use this little fold-over technique... so it doesn't stick to my spatula...All right.<s>
So then you kind of start chopping into it.<s>
Now, you could actually add <entity type="Ingredient">dried fruits</entity> if you wanted to, if this was for your kids.<s>
You know, I know a lot of us stay away from dried fruits, but you could do all kinds of <entity type="Ingredient">nuts</entity>, actually.<s>
<entity type="Ingredient">Walnuts</entity>.<s>
You could do <entity type="Ingredient">peanuts</entity>, whatever you'd like.<s>
All right.<s>
I think we're looking pretty good.<s>
I see a few dry spots, but I think I can fix that when it put it into the bowl.<s>
So I want to use a 9 x 13 Pyrex dish.<s>
You can use whichever dish you'd like.<s>
I just find that works well because I don't need to spray it or anything.<s>
There's enough healthy fats in here that you don't have to add any nonstick sprays or anything like that.<s>
All right.<s>
I'm gonna grab my dish and pour this in... All right.<s>
And you kind of get it started--I'll move that so you can see.<s>
Kind of get it started with your spatula... and then I like to finish it with my fingers.<s>
I think it's easier to really get it pushed down in there.<s>
So wet your fingers just a little bit...so it doesn't stick, and just start really pushing it down...<s>
I could put the towel down underneath this.<s>
It wouldn't be so noisy.<s>
So I'm just really pushing it in good...and that's it.<s>
And just so you know, one of my favorite things, actually, is you can use the same technique and actually use cookie cutters, which is kind of fun, and make like little shapes and stuff for the kids.<s>
And now I'm just gonna put this in the freezer and then in about an hour to check on it... All right.<s>
It's been about an hour, so I'm gonna go ahead and get the <entity type="Recipe">Honey Almond Protein Crisps</entity> out of the freezer.<s>
All right.<s>
It is definitely cold.<s>
It's pretty hard.<s>
So you can either at this point cut it into squares and sometimes, I don't even like to go to all that trouble, so I just break pieces off.<s>
I recommend you store it actually in the freezer, because it'll keep the texture nice and hard, and it doesn't get too hard to bite into.<s>
But if you cut it into 18 squares, each one is about 154 calories, about 8 grams, all of good fat, 21 grams of carbs, and about 4 grams of protein.<s>
So I guarantee you will like this.<s>
It's really good stuff, and I hope you will come back next time whenever I'm making something new.<s>
For more content like this, check out bodybuilding.com.<s>
[music]<s>
</transcript>
</transcripts> | {'content_hash': '42b0dc2d52abd0befd42370c096f5c77', 'timestamp': '', 'source': 'github', 'line_count': 144, 'max_line_length': 319, 'avg_line_length': 86.54861111111111, 'alnum_prop': 0.7397897777421166, 'repo_name': 'idf/RecipeIngredients', 'id': '0c9374168c571e55f078141d893e53d38db14757', 'size': '12463', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'relation/non-auto/18.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '24854'}, {'name': 'HTML', 'bytes': '82374'}, {'name': 'Makefile', 'bytes': '964'}, {'name': 'Perl', 'bytes': '5969'}, {'name': 'Python', 'bytes': '312218'}, {'name': 'Shell', 'bytes': '13854'}]} |
using System;
using System.Reactive.Linq;
using JetBrains.Annotations;
using ObservableData.Structures.Collections.Updates;
using ObservableData.Structures.Utils;
namespace ObservableData.Structures
{
public static class CollectionExtensions
{
[NotNull]
public static IObservable<IChange<ICollectionOperation<T>>> AsObservable<T>(
[NotNull] this IObservableReadOnlyCollection<T> list) =>
list.WhenUpdated.StartWith(new CollectionInsertBatchOperation<T>(list)).NotNull();
}
}
| {'content_hash': 'b377a3c21afdfadaa7300663de585c90', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 94, 'avg_line_length': 33.0625, 'alnum_prop': 0.7466918714555766, 'repo_name': 'kalinau/ObservableDataQuerying', 'id': '6712fe9ece3ff24a7bd28c3f3a2964314f9cbfe2', 'size': '531', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ObservableData/ObservableData.Structures/CollectionExtensions.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '113691'}]} |
package com.lzf.learn.javap;
public class NativeClassJavaPCode{
public native void h();//该方法和abstract修饰的方法一样,只有签名。
static{
System.loadLibrary("hello");//不写文件的后缀,程序会自动加上.dll的。
}
public static void main(String[] args){
new NativeClassJavaPCode().h();//调用
}
}
| {'content_hash': '1c1062e8fed4ddff09c855e1fe81cd4c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 59, 'avg_line_length': 23.384615384615383, 'alnum_prop': 0.6447368421052632, 'repo_name': 'jamfliu/lzflearn', 'id': 'b80febcdaaea65f8c79816bd4bab3709087ef33f', 'size': '376', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/TestJVM/src/main/java/com/lzf/learn/javap/NativeClassJavaPCode.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '669'}, {'name': 'C', 'bytes': '267'}, {'name': 'C++', 'bytes': '3093'}, {'name': 'HTML', 'bytes': '299'}, {'name': 'Java', 'bytes': '447670'}, {'name': 'SWIG', 'bytes': '12622'}, {'name': 'Shell', 'bytes': '2107'}, {'name': 'TSQL', 'bytes': '1668'}]} |
import {PlatformTest} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import "@tsed/platform-express";
import {expect} from "chai";
import SuperTest from "supertest";
import {Server} from "./app/Server";
describe("GraphQL", () => {
let request: SuperTest.SuperTest<SuperTest.Test>;
before(
PlatformTest.bootstrap(Server, {
platform: PlatformExpress
})
);
before(() => {
request = SuperTest(PlatformTest.callback());
});
after(PlatformTest.reset);
it("should try login", async () => {
const response = await request.post("/api/graphql").send({
"operationName": null,
"variables": {},
"query": "mutation {\n login(email: \"[email protected]\", password: \"[email protected]\") {\n email\n password\n }\n}\n"
}).expect(200);
expect(response.body).to.deep.eq({
"data": {
"login": {
"email": "[email protected]",
"password": "[email protected]"
}
}
});
});
it("should throw error", async () => {
const response = await request.post("/api/graphql").send({
"operationName": null,
"variables": {},
"query": "mutation {\n login(email: \"[email protected]\", password: \"[email protected]\") {\n email\n password\n }\n}\n"
}).expect(200);
expect(response.body).to.deep.eq({
"data": null,
"errors": [
{
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"headers": {},
"name": "UNAUTHORIZED",
"status": 401,
"type": "HTTP_EXCEPTION"
}
},
"locations": [
{
"column": 3,
"line": 2
}
],
"message": "Wrong credentials",
"path": [
"login"
]
}
]
});
});
});
| {'content_hash': '5982696173c918e4aad2ccd42097e8a5', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 129, 'avg_line_length': 26.676056338028168, 'alnum_prop': 0.5010559662090813, 'repo_name': 'Romakita/ts-express-decorators', 'id': '2cbbfbe7695995a06c499bdae3cbcb3c4279e44e', 'size': '1894', 'binary': False, 'copies': '1', 'ref': 'refs/heads/production', 'path': 'packages/graphql/typegraphql/test/graphql-passport.spec.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'EJS', 'bytes': '24557'}, {'name': 'HTML', 'bytes': '3710'}, {'name': 'JavaScript', 'bytes': '33370'}, {'name': 'Shell', 'bytes': '376'}, {'name': 'TypeScript', 'bytes': '2723318'}]} |
<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
<livescribe>
<domains>
<www>
<name>www-test.livescribe.com</name>
<auth>
<user>wwwscriber</user>
<password>wwwlspen</password>
</auth>
</www>
<admin>
<name>admin-test.livescribe.com</name>
<auth>
<user>wwwscriber</user>
<password>wwwlspen</password>
</auth>
</admin>
</domains>
</livescribe>
</configuration>
| {'content_hash': 'a166fed1be1669ba329b3c7e09064fba', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 46, 'avg_line_length': 21.565217391304348, 'alnum_prop': 0.5282258064516129, 'repo_name': 'jackstraw66/web', 'id': 'a492a39db23e12c2cf3ee61605f8910f353cf6d7', 'size': '496', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'livescribe/lswebutils/src/main/resources/configuration/dev/webutils-config.xml', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '12519'}, {'name': 'FreeMarker', 'bytes': '586195'}, {'name': 'HTML', 'bytes': '8445'}, {'name': 'Java', 'bytes': '3072798'}, {'name': 'JavaScript', 'bytes': '6722'}, {'name': 'Shell', 'bytes': '16332'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using homeControl.Domain.Events;
using homeControl.Domain.Events.Switches;
using homeControl.NooliteF.SwitchController;
using JetBrains.Annotations;
using Serilog;
namespace homeControl.NooliteF
{
[UsedImplicitly]
internal sealed class SwitchEventsProcessorF : IDisposable
{
private readonly ISwitchController _switchController;
private readonly IEventReceiver _receiver;
private readonly ILogger _log;
public SwitchEventsProcessorF(ISwitchController switchController, IEventReceiver receiver, ILogger log)
{
Guard.DebugAssertArgumentNotNull(switchController, nameof(switchController));
Guard.DebugAssertArgumentNotNull(receiver, nameof(receiver));
Guard.DebugAssertArgumentNotNull(log, nameof(log));
_switchController = switchController;
_receiver = receiver;
_log = log;
}
private readonly List<SwitchEventsObserverF> _observers = new List<SwitchEventsObserverF>();
private readonly SemaphoreSlim _completionSemaphore = new SemaphoreSlim(0, 1);
public void Start(CancellationToken ct)
{
_log.Debug("Starting events processing.");
var eventReceiver = _receiver.ReceiveEvents<AbstractSwitchEvent>();
eventReceiver
.GroupBy(e => e.SwitchId)
.ForEachAsync(switchObservable =>
{
_log.Debug("Received new SwitchId={SwitchId}, creating observer.", switchObservable.Key);
var observer = new SwitchEventsObserverF(_switchController, _log.ForContext<SwitchEventsObserverF>(), ct);
_observers.Add(observer);
switchObservable.Subscribe(observer);
}, ct)
.ContinueWith(t => _completionSemaphore.Release(), ct);
}
public async Task Completion(CancellationToken ct)
{
_log.Debug("Awaiting completion.");
await _completionSemaphore.WaitAsync(ct);
await Task.WhenAll(_observers.Select(o => o.Completion(ct)));
_log.Debug("Complete!");
}
public void Dispose()
{
_completionSemaphore?.Dispose();
foreach (var observer in _observers)
{
observer.Dispose();
}
}
}
}
| {'content_hash': '6cbb3288395ef00e5ecbbdd6e0dc52d1', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 126, 'avg_line_length': 36.85507246376812, 'alnum_prop': 0.6323240267400708, 'repo_name': 'svtz/homeControl', 'id': 'f3c61f17b30f87ade75d0f85b3daaa7e695ecf07', 'size': '2545', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/homeControl.NooliteF/SwitchEventsProcessorF.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '493676'}, {'name': 'Dockerfile', 'bytes': '3860'}, {'name': 'Shell', 'bytes': '2076'}]} |
"""Test utilities for message testing.
Includes module interface test to ensure that public parts of module are
correctly declared in __all__.
Includes message types that correspond to those defined in
services_test.proto.
Includes additional test utilities to make sure encoding/decoding libraries
conform.
"""
import cgi
import datetime
import inspect
import os
import re
import socket
import types
import six
from six.moves import range # pylint: disable=redefined-builtin
import unittest2 as unittest
from apitools.base.protorpclite import message_types
from apitools.base.protorpclite import messages
from apitools.base.protorpclite import util
# Unicode of the word "Russian" in cyrillic.
RUSSIAN = u'\u0440\u0443\u0441\u0441\u043a\u0438\u0439'
# All characters binary value interspersed with nulls.
BINARY = b''.join(six.int2byte(value) + b'\0' for value in range(256))
class TestCase(unittest.TestCase):
def assertRaisesWithRegexpMatch(self,
exception,
regexp,
function,
*params,
**kwargs):
"""Check that exception is raised and text matches regular expression.
Args:
exception: Exception type that is expected.
regexp: String regular expression that is expected in error message.
function: Callable to test.
params: Parameters to forward to function.
kwargs: Keyword arguments to forward to function.
"""
try:
function(*params, **kwargs)
self.fail('Expected exception %s was not raised' %
exception.__name__)
except exception as err:
match = bool(re.match(regexp, str(err)))
self.assertTrue(match, 'Expected match "%s", found "%s"' % (regexp,
err))
def assertHeaderSame(self, header1, header2):
"""Check that two HTTP headers are the same.
Args:
header1: Header value string 1.
header2: header value string 2.
"""
value1, params1 = cgi.parse_header(header1)
value2, params2 = cgi.parse_header(header2)
self.assertEqual(value1, value2)
self.assertEqual(params1, params2)
def assertIterEqual(self, iter1, iter2):
"""Check two iterators or iterables are equal independent of order.
Similar to Python 2.7 assertItemsEqual. Named differently in order to
avoid potential conflict.
Args:
iter1: An iterator or iterable.
iter2: An iterator or iterable.
"""
list1 = list(iter1)
list2 = list(iter2)
unmatched1 = list()
while list1:
item1 = list1[0]
del list1[0]
for index in range(len(list2)):
if item1 == list2[index]:
del list2[index]
break
else:
unmatched1.append(item1)
error_message = []
for item in unmatched1:
error_message.append(
' Item from iter1 not found in iter2: %r' % item)
for item in list2:
error_message.append(
' Item from iter2 not found in iter1: %r' % item)
if error_message:
self.fail('Collections not equivalent:\n' +
'\n'.join(error_message))
class ModuleInterfaceTest(object):
"""Test to ensure module interface is carefully constructed.
A module interface is the set of public objects listed in the
module __all__ attribute. Modules that that are considered public
should have this interface carefully declared. At all times, the
__all__ attribute should have objects intended to be publically
used and all other objects in the module should be considered
unused.
Protected attributes (those beginning with '_') and other imported
modules should not be part of this set of variables. An exception
is for variables that begin and end with '__' which are implicitly
part of the interface (eg. __name__, __file__, __all__ itself,
etc.).
Modules that are imported in to the tested modules are an
exception and may be left out of the __all__ definition. The test
is done by checking the value of what would otherwise be a public
name and not allowing it to be exported if it is an instance of a
module. Modules that are explicitly exported are for the time
being not permitted.
To use this test class a module should define a new class that
inherits first from ModuleInterfaceTest and then from
test_util.TestCase. No other tests should be added to this test
case, making the order of inheritance less important, but if setUp
for some reason is overidden, it is important that
ModuleInterfaceTest is first in the list so that its setUp method
is invoked.
Multiple inheritance is required so that ModuleInterfaceTest is
not itself a test, and is not itself executed as one.
The test class is expected to have the following class attributes
defined:
MODULE: A reference to the module that is being validated for interface
correctness.
Example:
Module definition (hello.py):
import sys
__all__ = ['hello']
def _get_outputter():
return sys.stdout
def hello():
_get_outputter().write('Hello\n')
Test definition:
import unittest
from protorpc import test_util
import hello
class ModuleInterfaceTest(test_util.ModuleInterfaceTest,
test_util.TestCase):
MODULE = hello
class HelloTest(test_util.TestCase):
... Test 'hello' module ...
if __name__ == '__main__':
unittest.main()
"""
def setUp(self):
"""Set up makes sure that MODULE and IMPORTED_MODULES is defined.
This is a basic configuration test for the test itself so does not
get it's own test case.
"""
if not hasattr(self, 'MODULE'):
self.fail(
"You must define 'MODULE' on ModuleInterfaceTest sub-class "
"%s." % type(self).__name__)
def testAllExist(self):
"""Test that all attributes defined in __all__ exist."""
missing_attributes = []
for attribute in self.MODULE.__all__:
if not hasattr(self.MODULE, attribute):
missing_attributes.append(attribute)
if missing_attributes:
self.fail('%s of __all__ are not defined in module.' %
missing_attributes)
def testAllExported(self):
"""Test that all public attributes not imported are in __all__."""
missing_attributes = []
for attribute in dir(self.MODULE):
if not attribute.startswith('_'):
if (attribute not in self.MODULE.__all__ and
not isinstance(getattr(self.MODULE, attribute),
types.ModuleType) and
attribute != 'with_statement'):
missing_attributes.append(attribute)
if missing_attributes:
self.fail('%s are not modules and not defined in __all__.' %
missing_attributes)
def testNoExportedProtectedVariables(self):
"""Test that there are no protected variables listed in __all__."""
protected_variables = []
for attribute in self.MODULE.__all__:
if attribute.startswith('_'):
protected_variables.append(attribute)
if protected_variables:
self.fail('%s are protected variables and may not be exported.' %
protected_variables)
def testNoExportedModules(self):
"""Test that no modules exist in __all__."""
exported_modules = []
for attribute in self.MODULE.__all__:
try:
value = getattr(self.MODULE, attribute)
except AttributeError:
# This is a different error case tested for in testAllExist.
pass
else:
if isinstance(value, types.ModuleType):
exported_modules.append(attribute)
if exported_modules:
self.fail('%s are modules and may not be exported.' %
exported_modules)
class NestedMessage(messages.Message):
"""Simple message that gets nested in another message."""
a_value = messages.StringField(1, required=True)
class HasNestedMessage(messages.Message):
"""Message that has another message nested in it."""
nested = messages.MessageField(NestedMessage, 1)
repeated_nested = messages.MessageField(NestedMessage, 2, repeated=True)
class HasDefault(messages.Message):
"""Has a default value."""
a_value = messages.StringField(1, default=u'a default')
class OptionalMessage(messages.Message):
"""Contains all message types."""
class SimpleEnum(messages.Enum):
"""Simple enumeration type."""
VAL1 = 1
VAL2 = 2
double_value = messages.FloatField(1, variant=messages.Variant.DOUBLE)
float_value = messages.FloatField(2, variant=messages.Variant.FLOAT)
int64_value = messages.IntegerField(3, variant=messages.Variant.INT64)
uint64_value = messages.IntegerField(4, variant=messages.Variant.UINT64)
int32_value = messages.IntegerField(5, variant=messages.Variant.INT32)
bool_value = messages.BooleanField(6, variant=messages.Variant.BOOL)
string_value = messages.StringField(7, variant=messages.Variant.STRING)
bytes_value = messages.BytesField(8, variant=messages.Variant.BYTES)
enum_value = messages.EnumField(SimpleEnum, 10)
class RepeatedMessage(messages.Message):
"""Contains all message types as repeated fields."""
class SimpleEnum(messages.Enum):
"""Simple enumeration type."""
VAL1 = 1
VAL2 = 2
double_value = messages.FloatField(1,
variant=messages.Variant.DOUBLE,
repeated=True)
float_value = messages.FloatField(2,
variant=messages.Variant.FLOAT,
repeated=True)
int64_value = messages.IntegerField(3,
variant=messages.Variant.INT64,
repeated=True)
uint64_value = messages.IntegerField(4,
variant=messages.Variant.UINT64,
repeated=True)
int32_value = messages.IntegerField(5,
variant=messages.Variant.INT32,
repeated=True)
bool_value = messages.BooleanField(6,
variant=messages.Variant.BOOL,
repeated=True)
string_value = messages.StringField(7,
variant=messages.Variant.STRING,
repeated=True)
bytes_value = messages.BytesField(8,
variant=messages.Variant.BYTES,
repeated=True)
enum_value = messages.EnumField(SimpleEnum,
10,
repeated=True)
class HasOptionalNestedMessage(messages.Message):
nested = messages.MessageField(OptionalMessage, 1)
repeated_nested = messages.MessageField(OptionalMessage, 2, repeated=True)
# pylint:disable=anomalous-unicode-escape-in-string
class ProtoConformanceTestBase(object):
"""Protocol conformance test base class.
Each supported protocol should implement two methods that support encoding
and decoding of Message objects in that format:
encode_message(message) - Serialize to encoding.
encode_message(message, encoded_message) - Deserialize from encoding.
Tests for the modules where these functions are implemented should extend
this class in order to support basic behavioral expectations. This ensures
that protocols correctly encode and decode message transparently to the
caller.
In order to support these test, the base class should also extend
the TestCase class and implement the following class attributes
which define the encoded version of certain protocol buffers:
encoded_partial:
<OptionalMessage
double_value: 1.23
int64_value: -100000000000
string_value: u"a string"
enum_value: OptionalMessage.SimpleEnum.VAL2
>
encoded_full:
<OptionalMessage
double_value: 1.23
float_value: -2.5
int64_value: -100000000000
uint64_value: 102020202020
int32_value: 1020
bool_value: true
string_value: u"a string\u044f"
bytes_value: b"a bytes\xff\xfe"
enum_value: OptionalMessage.SimpleEnum.VAL2
>
encoded_repeated:
<RepeatedMessage
double_value: [1.23, 2.3]
float_value: [-2.5, 0.5]
int64_value: [-100000000000, 20]
uint64_value: [102020202020, 10]
int32_value: [1020, 718]
bool_value: [true, false]
string_value: [u"a string\u044f", u"another string"]
bytes_value: [b"a bytes\xff\xfe", b"another bytes"]
enum_value: [OptionalMessage.SimpleEnum.VAL2,
OptionalMessage.SimpleEnum.VAL 1]
>
encoded_nested:
<HasNestedMessage
nested: <NestedMessage
a_value: "a string"
>
>
encoded_repeated_nested:
<HasNestedMessage
repeated_nested: [
<NestedMessage a_value: "a string">,
<NestedMessage a_value: "another string">
]
>
unexpected_tag_message:
An encoded message that has an undefined tag or number in the stream.
encoded_default_assigned:
<HasDefault
a_value: "a default"
>
encoded_nested_empty:
<HasOptionalNestedMessage
nested: <OptionalMessage>
>
encoded_invalid_enum:
<OptionalMessage
enum_value: (invalid value for serialization type)
>
"""
encoded_empty_message = ''
def testEncodeInvalidMessage(self):
message = NestedMessage()
self.assertRaises(messages.ValidationError,
self.PROTOLIB.encode_message, message)
def CompareEncoded(self, expected_encoded, actual_encoded):
"""Compare two encoded protocol values.
Can be overridden by sub-classes to special case comparison.
For example, to eliminate white space from output that is not
relevant to encoding.
Args:
expected_encoded: Expected string encoded value.
actual_encoded: Actual string encoded value.
"""
self.assertEquals(expected_encoded, actual_encoded)
def EncodeDecode(self, encoded, expected_message):
message = self.PROTOLIB.decode_message(type(expected_message), encoded)
self.assertEquals(expected_message, message)
self.CompareEncoded(encoded, self.PROTOLIB.encode_message(message))
def testEmptyMessage(self):
self.EncodeDecode(self.encoded_empty_message, OptionalMessage())
def testPartial(self):
"""Test message with a few values set."""
message = OptionalMessage()
message.double_value = 1.23
message.int64_value = -100000000000
message.int32_value = 1020
message.string_value = u'a string'
message.enum_value = OptionalMessage.SimpleEnum.VAL2
self.EncodeDecode(self.encoded_partial, message)
def testFull(self):
"""Test all types."""
message = OptionalMessage()
message.double_value = 1.23
message.float_value = -2.5
message.int64_value = -100000000000
message.uint64_value = 102020202020
message.int32_value = 1020
message.bool_value = True
message.string_value = u'a string\u044f'
message.bytes_value = b'a bytes\xff\xfe'
message.enum_value = OptionalMessage.SimpleEnum.VAL2
self.EncodeDecode(self.encoded_full, message)
def testRepeated(self):
"""Test repeated fields."""
message = RepeatedMessage()
message.double_value = [1.23, 2.3]
message.float_value = [-2.5, 0.5]
message.int64_value = [-100000000000, 20]
message.uint64_value = [102020202020, 10]
message.int32_value = [1020, 718]
message.bool_value = [True, False]
message.string_value = [u'a string\u044f', u'another string']
message.bytes_value = [b'a bytes\xff\xfe', b'another bytes']
message.enum_value = [RepeatedMessage.SimpleEnum.VAL2,
RepeatedMessage.SimpleEnum.VAL1]
self.EncodeDecode(self.encoded_repeated, message)
def testNested(self):
"""Test nested messages."""
nested_message = NestedMessage()
nested_message.a_value = u'a string'
message = HasNestedMessage()
message.nested = nested_message
self.EncodeDecode(self.encoded_nested, message)
def testRepeatedNested(self):
"""Test repeated nested messages."""
nested_message1 = NestedMessage()
nested_message1.a_value = u'a string'
nested_message2 = NestedMessage()
nested_message2.a_value = u'another string'
message = HasNestedMessage()
message.repeated_nested = [nested_message1, nested_message2]
self.EncodeDecode(self.encoded_repeated_nested, message)
def testStringTypes(self):
"""Test that encoding str on StringField works."""
message = OptionalMessage()
message.string_value = 'Latin'
self.EncodeDecode(self.encoded_string_types, message)
def testEncodeUninitialized(self):
"""Test that cannot encode uninitialized message."""
required = NestedMessage()
self.assertRaisesWithRegexpMatch(messages.ValidationError,
"Message NestedMessage is missing "
"required field a_value",
self.PROTOLIB.encode_message,
required)
def testUnexpectedField(self):
"""Test decoding and encoding unexpected fields."""
loaded_message = self.PROTOLIB.decode_message(
OptionalMessage, self.unexpected_tag_message)
# Message should be equal to an empty message, since unknown
# values aren't included in equality.
self.assertEquals(OptionalMessage(), loaded_message)
# Verify that the encoded message matches the source, including the
# unknown value.
self.assertEquals(self.unexpected_tag_message,
self.PROTOLIB.encode_message(loaded_message))
def testDoNotSendDefault(self):
"""Test that default is not sent when nothing is assigned."""
self.EncodeDecode(self.encoded_empty_message, HasDefault())
def testSendDefaultExplicitlyAssigned(self):
"""Test that default is sent when explcitly assigned."""
message = HasDefault()
message.a_value = HasDefault.a_value.default
self.EncodeDecode(self.encoded_default_assigned, message)
def testEncodingNestedEmptyMessage(self):
"""Test encoding a nested empty message."""
message = HasOptionalNestedMessage()
message.nested = OptionalMessage()
self.EncodeDecode(self.encoded_nested_empty, message)
def testEncodingRepeatedNestedEmptyMessage(self):
"""Test encoding a nested empty message."""
message = HasOptionalNestedMessage()
message.repeated_nested = [OptionalMessage(), OptionalMessage()]
self.EncodeDecode(self.encoded_repeated_nested_empty, message)
def testContentType(self):
self.assertTrue(isinstance(self.PROTOLIB.CONTENT_TYPE, str))
def testDecodeInvalidEnumType(self):
# Since protos need to be able to add new enums, a message should be
# successfully decoded even if the enum value is invalid. Encoding the
# decoded message should result in equivalence with the original
# encoded message containing an invalid enum.
decoded = self.PROTOLIB.decode_message(OptionalMessage,
self.encoded_invalid_enum)
message = OptionalMessage()
self.assertEqual(message, decoded)
encoded = self.PROTOLIB.encode_message(decoded)
self.assertEqual(self.encoded_invalid_enum, encoded)
def testDateTimeNoTimeZone(self):
"""Test that DateTimeFields are encoded/decoded correctly."""
class MyMessage(messages.Message):
value = message_types.DateTimeField(1)
value = datetime.datetime(2013, 1, 3, 11, 36, 30, 123000)
message = MyMessage(value=value)
decoded = self.PROTOLIB.decode_message(
MyMessage, self.PROTOLIB.encode_message(message))
self.assertEquals(decoded.value, value)
def testDateTimeWithTimeZone(self):
"""Test DateTimeFields with time zones."""
class MyMessage(messages.Message):
value = message_types.DateTimeField(1)
value = datetime.datetime(2013, 1, 3, 11, 36, 30, 123000,
util.TimeZoneOffset(8 * 60))
message = MyMessage(value=value)
decoded = self.PROTOLIB.decode_message(
MyMessage, self.PROTOLIB.encode_message(message))
self.assertEquals(decoded.value, value)
def pick_unused_port():
"""Find an unused port to use in tests.
Derived from Damon Kohlers example:
http://code.activestate.com/recipes/531822-pick-unused-port
"""
temp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
temp.bind(('localhost', 0))
port = temp.getsockname()[1]
finally:
temp.close()
return port
def get_module_name(module_attribute):
"""Get the module name.
Args:
module_attribute: An attribute of the module.
Returns:
The fully qualified module name or simple module name where
'module_attribute' is defined if the module name is "__main__".
"""
if module_attribute.__module__ == '__main__':
module_file = inspect.getfile(module_attribute)
default = os.path.basename(module_file).split('.')[0]
return default
return module_attribute.__module__
| {'content_hash': '72bfd9921e1fc26e6ad58be8be1a8cb0', 'timestamp': '', 'source': 'github', 'line_count': 632, 'max_line_length': 79, 'avg_line_length': 36.3623417721519, 'alnum_prop': 0.613854923632566, 'repo_name': 'houglum/apitools', 'id': '43345fc48c60255e3abdd809b9dce039f181eeb7', 'size': '23583', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'apitools/base/protorpclite/test_util.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '819131'}]} |
static const CGSize FORMDatePopoverSize = { 320.0f, 284.0f };
@interface FORMDateFieldCell () <FORMTextFieldDelegate,
UIPopoverControllerDelegate, FORMFieldValuesTableViewControllerDelegate>
@property (nonatomic) UIDatePicker *datePicker;
@end
@implementation FORMDateFieldCell
#pragma mark - Initializers
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame contentViewController:self.fieldValuesController
andContentSize:FORMDatePopoverSize];
if (!self) return nil;
self.fieldValuesController.delegate = self;
self.fieldValuesController.customHeight = 197.0f;
self.fieldValuesController.tableView.scrollEnabled = NO;
[self.fieldValuesController.headerView addSubview:self.datePicker];
return self;
}
#pragma mark - Getters
- (CGRect)datePickerFrame {
return CGRectMake(0.0f, 25.0f, FORMDatePopoverSize.width, 196);
}
- (UIDatePicker *)datePicker {
if (_datePicker) return _datePicker;
_datePicker = [[UIDatePicker alloc] initWithFrame:[self datePickerFrame]];
_datePicker.datePickerMode = UIDatePickerModeDate;
_datePicker.backgroundColor = [UIColor clearColor];
[_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
return _datePicker;
}
#pragma mark - Setters
- (void)setDate:(NSDate *)date {
_date = date;
if (_date) self.datePicker.date = _date;
}
- (void)setMinimumDate:(NSDate *)minimumDate {
_minimumDate = minimumDate;
self.datePicker.minimumDate = _minimumDate;
}
- (void)setMaximumDate:(NSDate *)maximumDate {
_maximumDate = maximumDate;
self.datePicker.maximumDate = _maximumDate;
}
#pragma mark - Actions
- (void)dateChanged:(UIDatePicker *)datePicker {
self.date = datePicker.date;
}
#pragma mark - FORMBaseFormFieldCell
- (void)updateWithField:(FORMField *)field {
[super updateWithField:field];
FORMFieldValue *confirmValue = [FORMFieldValue new];
confirmValue.title = NSLocalizedString(@"Confirm", nil);
confirmValue.valueID = [NSDate date];
confirmValue.value = @YES;
FORMFieldValue *clearValue = [FORMFieldValue new];
clearValue.title = NSLocalizedString(@"Clear", nil);
clearValue.valueID = [NSDate date];
clearValue.value = @NO;
field.values = @[confirmValue, clearValue];
if (field.value) {
self.fieldValueLabel.text = [NSDateFormatter localizedStringFromDate:field.value
dateStyle:[self dateStyleForField:field]
timeStyle:[self timeStyleForField:field]];
} else {
self.fieldValueLabel.text = nil;
}
self.iconImageView.image = [self fieldIcon];
}
- (NSDateFormatterStyle)dateStyleForField:(FORMField *)field {
switch (field.type) {
case FORMFieldTypeDate:
return NSDateFormatterMediumStyle;
break;
case FORMFieldTypeDateTime:
return NSDateFormatterMediumStyle;
break;
default:
return NSDateFormatterNoStyle;
break;
}
}
- (NSDateFormatterStyle)timeStyleForField:(FORMField *)field {
switch (field.type) {
case FORMFieldTypeDate:
return NSDateFormatterNoStyle;
break;
case FORMFieldTypeDateTime:
return NSDateFormatterShortStyle;
break;
default:
return NSDateFormatterShortStyle;
break;
}
}
- (UIImage *)fieldIcon {
NSString *bundlePath = [[[NSBundle bundleForClass:self.class] resourcePath] stringByAppendingPathComponent:@"Form.bundle"];
NSBundle *bundle = [NSBundle bundleWithPath: bundlePath];
UITraitCollection *trait = [UITraitCollection traitCollectionWithDisplayScale:2.0];
switch (self.field.type) {
case FORMFieldTypeDate:
case FORMFieldTypeDateTime:
return [UIImage imageNamed:@"calendar"
inBundle:bundle
compatibleWithTraitCollection:trait];
break;
case FORMFieldTypeTime:
return [UIImage imageNamed:@"clock"
inBundle:bundle
compatibleWithTraitCollection:trait];
break;
default:
return nil;
break;
}
}
#pragma mark - FORMPopoverFormFieldCell
- (void)updateContentViewController:(UIViewController *)contentViewController withField:(FORMField *)field {
self.fieldValuesController.field = self.field;
if (self.field.info) {
CGRect frame = self.datePicker.frame;
frame.origin.y = 50.0f;
frame.size.height -= 25.0f;
[self.datePicker setFrame:frame];
}
if (self.field.value) {
self.datePicker.date = self.field.value;
}
if (self.field.minimumDate) {
self.datePicker.minimumDate = self.field.minimumDate;
}
if (self.field.maximumDate) {
self.datePicker.maximumDate = self.field.maximumDate;
}
switch (self.field.type) {
case FORMFieldTypeDate:
self.datePicker.datePickerMode = UIDatePickerModeDate;
break;
case FORMFieldTypeDateTime:
self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
break;
case FORMFieldTypeTime:
self.datePicker.datePickerMode = UIDatePickerModeTime;
break;
default:
break;
}
}
#pragma mark - FORMFieldValuesTableViewControllerDelegate
- (void)fieldValuesTableViewController:(FORMFieldValuesTableViewController *)fieldValuesTableViewController
didSelectedValue:(FORMFieldValue *)selectedValue {
if ([selectedValue.value boolValue] == YES) {
self.field.value = self.datePicker.date;
} else {
self.field.value = nil;
}
[self updateWithField:self.field];
[self validate];
[self.popoverController dismissPopoverAnimated:YES];
if ([self.delegate respondsToSelector:@selector(fieldCell:updatedWithField:)]) {
[self.delegate fieldCell:self updatedWithField:self.field];
}
}
@end
| {'content_hash': '1cebcac8395ea1b6b4976c02720b985c', 'timestamp': '', 'source': 'github', 'line_count': 213, 'max_line_length': 127, 'avg_line_length': 29.0, 'alnum_prop': 0.662619394528088, 'repo_name': 'kalsariyac/Form', 'id': 'e4b5a0fb33abeb43b8feb40ae901ad2379bbdbdf', 'size': '6235', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Source/Cells/Popover/FORMDateFieldCell.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '177'}, {'name': 'Objective-C', 'bytes': '418009'}, {'name': 'Ruby', 'bytes': '2338'}, {'name': 'Swift', 'bytes': '4618'}]} |
@call "E:\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86
@call C:\Python27\Scripts\scons.bat spawn_jobs=yes platform=windows tools=no target=release_debug tools=no theora=no speex=no pvr=no openssl=no musepack=no disable_3d=yes webp=no pvr=no squish=no opus=no etc1=no phys=no freetype=no
pause | {'content_hash': '24bd7e9f8bc474b945395d5a38e93a37', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 231, 'avg_line_length': 75.0, 'alnum_prop': 0.7866666666666666, 'repo_name': 'huziyizero/godot', 'id': 'cdc5a97b9bdb4eff6414b1c50157d90daa7004bd', 'size': '300', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '!build windows.bat', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1176'}, {'name': 'C', 'bytes': '682913'}, {'name': 'C++', 'bytes': '11948885'}, {'name': 'Java', 'bytes': '493485'}, {'name': 'Objective-C', 'bytes': '30531'}, {'name': 'Objective-C++', 'bytes': '143259'}, {'name': 'Python', 'bytes': '131537'}, {'name': 'Shell', 'bytes': '266'}]} |
namespace simcom {
constexpr char generic_at::CMGF[];
constexpr char generic_at::TCP[];
constexpr char generic_at::UDP[];
constexpr char generic_at::ANDTHEN[];
// scoped only to this CPP, convenient for reducing verbosity
typedef generic_at::ip ip;
typedef generic_at::sms sms;
typedef generic_at::http http;
constexpr char ip::start::CMD[];
constexpr char ip::ssl::CMD[];
constexpr char ip::mux::CMD[];
constexpr char ip::send::CMD[];
constexpr char ip::receive::CMD[];
constexpr char ip::shutdown::CMD[];
constexpr char generic_at::http_action::CMD[];
constexpr char generic_at::http_read::CMD[];
constexpr char generic_at::http_head::CMD[];
constexpr char generic_at::http_para::CMD[];
constexpr char generic_at::http_init::CMD[];
constexpr char generic_at::http_data::CMD[];
constexpr char http::term::CMD[];
constexpr char generic_at::http_ssl::CMD[];
constexpr char generic_at::bringup_wireless::CMD[];
constexpr char generic_at::apn_credentials::CMD[];
constexpr char generic_at::get_local_ip_address::CMD[];
constexpr char generic_at::bearer_settings::CMD[];
constexpr char sms::send::CMD[];
constexpr char sms::receive::CMD[];
constexpr char generic_at::pdp_deact::CMD[];
// FIX: rename this to be something like push_handler or receive_push
void generic_at::statemachine(ATC atc, experimental_statemachine_output* output)
{
// TODO: assert output is not null
// FIX: change this from >= 0 to something more sensible
if(atc.getsome() >= 0)
{
// FIX: this is locking us until we rid ourselves of OLD_WHITESPACE_IGNORE
atc.ignore_whitespace_and_newlines();
}
// If we get this, we have a PUSH from sim808
if(atc.getsome() == '+')
{
static const char* keywords[] =
{
#ifdef FEATURE_PUSH_PDP_DEACT
generic_at::pdp_deact::CMD,
#endif
ip::receive::CMD,
nullptr
};
atc.debug_context.set("PUSH");
const char* matched = atc.input_match(keywords);
output->cmd = matched;
if(matched == ip::receive::CMD)
{
atc >> ": 1,1";
fstd::clog << "Statemachine got " << ip::receive::CMD << fstd::endl;
// Getting here means we are alerted to the presence of data
output->ip_receive.channel = 1;
atc.input_newline();
}
#ifdef FEATURE_PUSH_PDP_DEACT
else if(matched == generic_at::pdp_deact::CMD)
{
atc.input_newline();
}
#endif
else
{
// TODO: make a verion of input_match which remembers
// findings in an output buffer so that if no match
// is found, we still have our hands on what we tried
// to match against
// ignore remainder of line since we don't recognize
// this PUSH directive
char dump[128];
atc.getline(dump, sizeof(dump) - 1);
fstd::clog << "Statemachine default: " << dump << fstd::endl;
}
//atc.ignore_whitespace_and_newlines();
}
}
}
| {'content_hash': '1e264086fc00fe26f6d3f52fdc36f23d', 'timestamp': '', 'source': 'github', 'line_count': 103, 'max_line_length': 82, 'avg_line_length': 29.776699029126213, 'alnum_prop': 0.6194978806651451, 'repo_name': 'malachi-iot/atcommander', 'id': '4e03e0f66ccdb67eeb9f3f5d91bb4d6f12bd2f89', 'size': '3129', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/target/simcom.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '115848'}, {'name': 'CMake', 'bytes': '3572'}, {'name': 'Python', 'bytes': '2658'}, {'name': 'Shell', 'bytes': '306'}]} |
# HTTP Responses
- [Basic Responses](#basic-responses)
- [Redirects](#redirects)
- [Other Responses](#other-responses)
- [Response Macros](#response-macros)
<a name="basic-responses"></a>
## Basic Responses
#### Returning Strings From Routes
The most basic response from a Laravel route is a string:
Route::get('/', function()
{
return 'Hello World';
});
#### Creating Custom Responses
However, for most routes and controller actions, you will be returning a full `Illuminate\Http\Response` instance or a [view](/docs/{{version}}/views). Returning a full `Response` instance allows you to customize the response's HTTP status code and headers. A `Response` instance inherits from the `Symfony\Component\HttpFoundation\Response` class, providing a variety of methods for building HTTP responses:
use Illuminate\Http\Response;
return (new Response($content, $status))
->header('Content-Type', $value);
For convenience, you may also use the `response` helper:
return response($content, $status)
->header('Content-Type', $value);
> **Note:** For a full list of available `Response` methods, check out its [API documentation](http://laravel.com/api/master/Illuminate/Http/Response.html) and the [Symfony API documentation](http://api.symfony.com/2.5/Symfony/Component/HttpFoundation/Response.html).
#### Sending A View In A Response
If you need access to the `Response` class methods, but want to return a view as the response content, you may use the `view` method for convenience:
return response()->view('hello')->header('Content-Type', $type);
#### Attaching Cookies To Responses
return response($content)->withCookie(cookie('name', 'value'));
#### Method Chaining
Keep in mind that most `Response` methods are chainable, allowing for the fluent building of responses:
return response()->view('hello')->header('Content-Type', $type)
->withCookie(cookie('name', 'value'));
<a name="redirects"></a>
## Redirects
Redirect responses are typically instances of the `Illuminate\Http\RedirectResponse` class, and contain the proper headers needed to redirect the user to another URL.
#### Returning A Redirect
There are several ways to generate a `RedirectResponse` instance. The simplest method is to use the `redirect` helper method. When testing, it is not common to mock the creation of a redirect response, so using the helper method is almost always acceptable:
return redirect('user/login');
#### Returning A Redirect With Flash Data
Redirecting to a new URL and [flashing data to the session](/docs/{{version}}/session) are typically done at the same time. So, for convenience, you may create a `RedirectResponse` instance **and** flash data to the session in a single method chain:
return redirect('user/login')->with('message', 'Login Failed');
#### Redirecting To The Previous URL
You may wish to redirect the user to their previous location, for example, after a form submission. You can do so by using the `back` method:
return redirect()->back();
return redirect()->back()->withInput();
#### Returning A Redirect To A Named Route
When you call the `redirect` helper with no parameters, an instance of `Illuminate\Routing\Redirector` is returned, allowing you to call any method on the `Redirector` instance. For example, to generate a `RedirectResponse` to a named route, you may use the `route` method:
return redirect()->route('login');
#### Returning A Redirect To A Named Route With Parameters
If your route has parameters, you may pass them as the second argument to the `route` method.
// For a route with the following URI: profile/{id}
return redirect()->route('profile', [1]);
If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may simply pass the model itself. The ID will be extracted automatically:
return redirect()->route('profile', [$user]);
#### Returning A Redirect To A Named Route Using Named Parameters
// For a route with the following URI: profile/{user}
return redirect()->route('profile', ['user' => 1]);
#### Returning A Redirect To A Controller Action
Similarly to generating `RedirectResponse` instances to named routes, you may also generate redirects to [controller actions](/docs/{{version}}/controllers):
return redirect()->action('App\Http\Controllers\HomeController@index');
> **Note:** You do not need to specify the full namespace to the controller if you have registered a root controller namespace via `URL::setRootControllerNamespace`.
#### Returning A Redirect To A Controller Action With Parameters
return redirect()->action('App\Http\Controllers\UserController@profile', [1]);
#### Returning A Redirect To A Controller Action Using Named Parameters
return redirect()->action('App\Http\Controllers\UserController@profile', ['user' => 1]);
<a name="other-responses"></a>
## Other Responses
The `response` helper may be used to conveniently generate other types of response instances. When the `response` helper is called without arguments, an implementation of the `Illuminate\Contracts\Routing\ResponseFactory` [contract](/docs/{{version}}/contracts) is returned. This contract provides several helpful methods for generating responses.
#### Creating A JSON Response
The `json` method will automatically set the `Content-Type` header to `application/json`:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
#### Creating A JSONP Response
return response()->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
#### Creating A File Download Response
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend(true);
> **Note:** Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name.
<a name="response-macros"></a>
## Response Macros
If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the `macro` method on an implementation of `Illuminate\Contracts\Routing\ResponseFactory`.
For example, from a [service provider's](/docs/{{version}}/providers) `boot` method:
<?php namespace App\Providers;
use Response;
use Illuminate\Support\ServiceProvider;
class ResponseMacroServiceProvider extends ServiceProvider {
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Response::macro('caps', function($value)
{
return Response::make(strtoupper($value));
});
}
}
The `macro` function accepts a name as its first argument, and a Closure as its second. The macro's Closure will be executed when calling the macro name from a `ResponseFactory` implementation or the `response` helper:
return response()->caps('foo');
| {'content_hash': '4794bad1bd0a125742551e7a9555fb09', 'timestamp': '', 'source': 'github', 'line_count': 175, 'max_line_length': 408, 'avg_line_length': 39.72571428571428, 'alnum_prop': 0.7350402761795167, 'repo_name': 'shuttzz/laravel-docs-pt-br', 'id': '3c311664f217b1c7988594bbf481e36bef3e1db6', 'size': '6952', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'responses.md', 'mode': '33188', 'license': 'mit', 'language': []} |
#ifndef art_Framework_Core_PtrRemapper_h
#define art_Framework_Core_PtrRemapper_h
////////////////////////////////////////////////////////////////////////
// PtrRemapper
//
// Class to aid in remapping Ptrs in various settings from items in one
// branch to (presumably the equivalent) items in another branch of the
// same type.
//
// This class is primarily for use in product mixing and will be
// properly initialized by the time it is provided as an argument to the
// user-supplied mixing function.
//
// PtrRemapper is a function object, so all of its work is done with the
// apply operator -- operator(). This means that if your mixing function
// has an argument (e.g.)
//
// art::PtrRemapper const &remap
//
// then the usage is:
//
// remap(...)
//
// There are several signatures to operator() and because they are all
// templates, they can look fairly impenetrable. It is recommended
// tberefore to use this header documentation to decide what signature
// is most appropriate for your use rather than looking below at the
// prototypes or the implementation: there really are "No
// User-serviceable Parts."
//
// Notes common to several signatures.
//
// * With the exception of the (rarely required) signature 10 (see its
// specific documentation), all template arguments are deducible from
// the function arguments and therefore it is not necessary to specify
// them in <>.
//
// * Commonly-used arguments:
//
// * std::vector<COLLECTION<PROD> const *> const &in
//
// * OutIter &out
//
// OutIter is a variable of category insert_iterator (usually
// created by, for instance std::back_inserter(container)) into a
// container of Ptr (either PtrVector or some other collection of
// Ptr).
//
// * offset is a single offset into the container into which the Ptr
// points. It should be of type
// convertible-to-container::size::type.
//
// * offsets is an arbitrary container of such offsets as described
// in the documentation in
// art/Persistency/Common/CollectionUtilities.h.
//
//
// Available signatures to operator() and example usage:
//
// 1. Remap a single Ptr.
//
// Ptr<A> newPtr(remap(oldPtr, offset));
//
// 2. Remap a single PtrVector.
//
// PtrVector<A> newPV(remap(oldPV, offset));
//
// 3. Remap a compatible collection (including PtrVector) of Ptr
// providing begin, end iteratorsq. (This will also remap a compatible
// collection of PtrVector, but not of PtrVector const * -- for the
// latter, see 4-10.)
//
// PtrVector<A> newPV;
// remap(oldPV.begin(),
// oldPV.end(),
// std::back_inserter(newPV),
// offset);
//
// 4. Remap and flatten a set of products which are containers of Ptrs
// (which includes PtrVector).
//
// remap(in, out, offsets)
//
// where offsets is likely calculated by the appropriate call to
// art::flattenCollections. See
// art/Persistency/Common/CollectionUtilities for details.
//
// 5. Remap and flatten a set of containers of Ptrs (including
// PtrVector) which may be obtained from a component of the provided
// product. Provide a free function of the correct signature to return a
// reference to the container of Ptrs given a secondary product, e.g.:
//
// PtrVector<B> const &myfunc(A const *prod) {
// return prod->myBs();
// }
//
// remap(in, out, offsets, &myfunc);
//
// 6. Remap and flatten a set of containers of Ptrs (including
// PtrVector) which may be obtained from a component of the provided
// product. Provide the name of a member function of the provided
// product which is an accessor for the container (taking no arguments).
//
// remap(in, out, offsets, &A::myBs);
//
// 7. Remap and flatten a set of containers of Ptrs (including
// PtrVector) which may be obtained from a component of the provided
// product. Provide the name of a member datum of the provided product
// which is the container.
//
// remap(in, out, offsets, &A::myBs_);
//
// 8. Remap and flatten a set of containers of Ptrs (including
// PtrVector) which is a component of the provided product using the
// provided accessor member function of a class which is not the
// product.
//
// class Aprocessor {
// public:
// B const &myBs(A const *);
// };
//
// Aprocessor myAp;
//
// remap(in, out, offsets, Aprocessor::myBs, myAp);
//
// Note: if the compiler complains about an unresolved overload set
// for this signature, try an explicit:
//
// const_cast<Aprocessor &>(myAp);
//
// 9. Remap and flatten a set of containers of Ptrs (including
// PtrVector) which is a component of the provided product using the
// provided const accessor member function of a class which is not the
// product.
//
// class Aprocessor {
// public:
// B const &myBs(A const *) const;
// };
//
// Aprocessor myAp;
//
// remap(in, out, offsets, Aprocessor::myBs, myAp);
//
// Note: if the compiler complains about an unresolved overload set
// for this signature, try an explicit:
//
// const_cast<Aprocessor const &>(myAp);
//
// 10. More general version of 5-9. that takes a final argument which is
// of arbitrary type provided it or its operator() has the correct
// signature. The drawback is that one of the template arguments (CONT,
// specifying the type of the collection of Ptrs you wish to remap) is
// not deducible, meaning that instead of:
//
// remap(...);
//
// one must type (e.g.):
//
// remap.operator()<std::vector<art::Ptr<B> > >(...)
//
// Therefore, 4-9. are the recommended signatures for
// straightforward client code -- this one is provided for maximum
// flexibility.
//
////////////////////////////////////////////////////////////////////////
#include "art/Framework/Principal/Event.h"
#include "art/Persistency/Common/CollectionUtilities.h"
#include "canvas/Persistency/Common/EDProductGetter.h"
#include "canvas/Persistency/Common/Ptr.h"
#include "canvas/Persistency/Common/PtrVector.h"
#include "canvas/Persistency/Provenance/ProductID.h"
#include "cetlib/exempt_ptr.h"
#include <map>
namespace art {
class PtrRemapper;
class ProdToProdMapBuilder;
namespace PtrRemapperDetail {
// Function template used by 4.
template <typename PROD>
PROD const &simpleProdReturner (PROD const *prod) { return *prod; }
// Function object used by 10.
template <typename CONT, typename PROD, typename CALLBACK>
class ContReturner {
public:
explicit ContReturner(CALLBACK callback) : callback_(callback) { }
CONT const &operator() (PROD const *prod) const {
return callback_(prod);
}
private:
CALLBACK callback_;
};
template <typename CONT, typename PROD>
class ContReturner<CONT, PROD, CONT const &(PROD::*)() const> {
public:
typedef CONT const &(PROD::*CALLBACK)() const;
explicit ContReturner(CALLBACK callback) : callback_(callback) { }
CONT const &operator()(PROD const *prod) const {
return (prod->*callback_)();
}
private:
CALLBACK callback_;
};
template <typename CONT, typename PROD>
class ContReturner<CONT, PROD, CONT PROD::*const> {
public:
typedef CONT PROD::*const CALLBACK;
explicit ContReturner(CALLBACK callback) : callback_(callback) { }
CONT const &operator()(PROD const *prod) const {
return prod->*callback_;
}
private:
CALLBACK callback_;
};
}
}
class art::PtrRemapper {
public:
PtrRemapper();
//////////////////////////////////////////////////////////////////////
// Signatures for operator() -- see documentation at top of header.
// 1.
template <typename PROD, typename SIZE_TYPE>
Ptr<PROD> operator()(Ptr<PROD> const &oldPtr, SIZE_TYPE offset) const;
// 2.
template <typename PROD, typename SIZE_TYPE>
PtrVector<PROD> operator()(PtrVector<PROD> const &old, SIZE_TYPE offset) const;
// 3.
template <typename InIter, typename OutIter, typename SIZE_TYPE>
void
operator()(InIter beg,
InIter end,
OutIter out,
SIZE_TYPE offset) const;
// 4.
template <typename OutIter, typename PROD, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets) const;
// 5.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (*extractor) (PROD const *)) const;
// 6.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (PROD::*extractor) () const) const;
// 7.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT PROD::*const data) const;
// 8.
template <typename PROD, typename OutIter, typename CONT, typename X, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (X::*extractor) (PROD const *),
X &x) const;
// 9.
template <typename PROD, typename OutIter, typename CONT, typename X, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (X::*extractor) (PROD const *) const,
X const &x) const;
// 10.
template <typename CONT, typename CALLBACK, typename OutIter, typename PROD, typename OFFSETS>
void
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CALLBACK extractor) const;
friend class art::ProdToProdMapBuilder;
private:
typedef std::map<ProductID, ProductID> ProdTransMap_t;
ProdTransMap_t prodTransMap_;
//// cet::exempt_ptr<EDProductGetter const> productGetter_;
cet::exempt_ptr<Event const> event_;
};
inline
art::PtrRemapper::
PtrRemapper() : prodTransMap_(), event_() {}
// 1.
template <typename PROD, typename SIZE_TYPE>
art::Ptr<PROD>
art::PtrRemapper::
operator()(Ptr<PROD> const &oldPtr,
SIZE_TYPE offset) const {
if (oldPtr.id().isValid()) {
ProdTransMap_t::const_iterator iter = prodTransMap_.find(oldPtr.id());
if (iter == prodTransMap_.end()) {
throw Exception(errors::LogicError)
<< "PtrRemapper: could not find old ProductID "
<< oldPtr.id()
<< " in translation table: already translated?\n";
}
return (oldPtr.isNonnull())?
Ptr<PROD>(iter->second,
oldPtr.key() + offset,
event_->productGetter(iter->second)):
Ptr<PROD>(iter->second);
} else { // Default-constructed.
return Ptr<PROD>();
}
}
// 2.
template <typename PROD, typename SIZE_TYPE>
art::PtrVector<PROD>
art::PtrRemapper::
operator()(PtrVector<PROD> const &old,
SIZE_TYPE offset) const {
PtrVector<PROD> result;
result.reserve(old.size());
this->operator()(old.begin(),
old.end(),
std::back_inserter(result), offset); // 3.
return result;
}
// 3.
template <typename InIter, typename OutIter, typename SIZE_TYPE>
void
art::PtrRemapper::
operator()(InIter beg,
InIter end,
OutIter out,
SIZE_TYPE offset) const {
// Need to assume that all Ptr containers and consistent internally
// and with each other due to a lack of productGetters.
// Not using transform here allows instantiation for iterator to
// collection of Ptr or collection of PtrVector.
for (InIter i = beg;
i != end;
++i) {
// Note: this could be signature 1 OR 2 of operator(). If the user
// calls this signature (3) with iterators into a collection of
// PtrVector, then the call order will be 3, 2, 3, 1 due to the
// templates that will be instantiated i.e. the relationship between
// signatures 2 and 3 is *not* infinitely recursive.
*out++ = this->operator()(*i, offset); // 1 OR 2.
}
}
// 4.
template <typename OutIter, typename PROD, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets) const {
this->operator()(in,
out,
offsets,
PtrRemapperDetail::simpleProdReturner<PROD>); // 5.
}
// 5.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (*extractor) (PROD const *)) const {
this->operator()<CONT, CONT const & (*)(PROD const *)>
(in, out, offsets, extractor); // 10.
}
// 6.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (PROD::*extractor) () const) const {
this->operator()<CONT, CONT const & (PROD::*) () const>
(in, out, offsets, extractor); // 10.
}
// 7.
template <typename CONT, typename OutIter, typename PROD, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT PROD::*const data) const {
this->operator()<CONT, CONT PROD::*const>
(in, out, offsets, data); // 10.
}
// 8.
template <typename PROD, typename OutIter, typename CONT, typename X, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (X::*extractor) (PROD const *),
X &x) const {
this->operator()<CONT>(in,
out,
offsets,
[&x](auto& elem){ elem.extractor(x); }); // 10?
}
// 9.
template <typename PROD, typename OutIter, typename CONT, typename X, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CONT const & (X::*extractor) (PROD const *) const,
X const &x) const {
this->operator()<CONT>(in,
out,
offsets,
[&x](auto& elem){ elem.extractor(x); }); // 10.
}
// 10.
template <typename CONT, typename CALLBACK, typename OutIter, typename PROD, typename OFFSETS>
void
art::PtrRemapper::
operator()(std::vector<PROD const *> const &in,
OutIter out,
OFFSETS const &offsets,
CALLBACK extractor) const {
if (in.size() != offsets.size()) {
throw Exception(errors::LogicError)
<< "Collection size of "
<< in.size()
<< " disagrees with offset container size of "
<< offsets.size()
<< ".\n";
}
typename std::vector<PROD const *>::const_iterator
i = in.begin(),
e = in.end();
typename OFFSETS::const_iterator off_iter = offsets.begin();
art::PtrRemapperDetail::ContReturner<CONT, PROD, CALLBACK> returner(extractor);
for (; i != e; ++i, ++off_iter) {
CONT const &cont(returner.operator()(*i));
this->operator()(cont.begin(), cont.end(), out, *off_iter); // 3.
}
}
#endif /* art_Framework_Core_PtrRemapper_h */
// Local Variables:
// mode: c++
// End:
| {'content_hash': '6d6b531b14b2417f4d25456e1ea81f46', 'timestamp': '', 'source': 'github', 'line_count': 493, 'max_line_length': 96, 'avg_line_length': 32.0446247464503, 'alnum_prop': 0.6284972781364729, 'repo_name': 'gartung/fnal-art', 'id': '6050030d341cd8fbd8da1eb74bc4f85511de1d6a', 'size': '15798', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'art/Framework/Core/PtrRemapper.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '90352'}, {'name': 'C++', 'bytes': '2871735'}, {'name': 'CMake', 'bytes': '71747'}, {'name': 'Perl', 'bytes': '23708'}, {'name': 'Shell', 'bytes': '46522'}]} |
package org.docksidestage.install.dbflute.bsentity.dbmeta;
import java.util.List;
import java.util.Map;
import org.dbflute.Entity;
import org.dbflute.dbmeta.AbstractDBMeta;
import org.dbflute.dbmeta.info.*;
import org.dbflute.dbmeta.name.*;
import org.dbflute.dbmeta.property.PropertyGateway;
import org.dbflute.dbway.DBDef;
import org.docksidestage.install.dbflute.allcommon.*;
import org.docksidestage.install.dbflute.exentity.*;
/**
* The DB meta of REGION. (Singleton)
* @author DBFlute(AutoGenerator)
*/
public class RegionDbm extends AbstractDBMeta {
// ===================================================================================
// Singleton
// =========
private static final RegionDbm _instance = new RegionDbm();
private RegionDbm() {}
public static RegionDbm getInstance() { return _instance; }
// ===================================================================================
// Current DBDef
// =============
public String getProjectName() { return DBCurrent.getInstance().projectName(); }
public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); }
public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); }
public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); }
// ===================================================================================
// Property Gateway
// ================
// -----------------------------------------------------
// Column Property
// ---------------
protected final Map<String, PropertyGateway> _epgMap = newHashMap();
{ xsetupEpg(); }
protected void xsetupEpg() {
setupEpg(_epgMap, et -> ((Region)et).getRegionId(), (et, vl) -> ((Region)et).setRegionId(cti(vl)), "regionId");
setupEpg(_epgMap, et -> ((Region)et).getRegionName(), (et, vl) -> ((Region)et).setRegionName((String)vl), "regionName");
}
public PropertyGateway findPropertyGateway(String prop)
{ return doFindEpg(_epgMap, prop); }
// ===================================================================================
// Table Info
// ==========
protected final String _tableDbName = "REGION";
protected final String _tablePropertyName = "region";
protected final TableSqlName _tableSqlName = new TableSqlName("REGION", _tableDbName);
{ _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); }
public String getTableDbName() { return _tableDbName; }
public String getTablePropertyName() { return _tablePropertyName; }
public TableSqlName getTableSqlName() { return _tableSqlName; }
// ===================================================================================
// Column Info
// ===========
protected final ColumnInfo _columnRegionId = cci("REGION_ID", "REGION_ID", null, null, Integer.class, "regionId", null, true, false, true, "INTEGER", 10, 0, null, false, null, null, null, "memberAddressList", null, false);
protected final ColumnInfo _columnRegionName = cci("REGION_NAME", "REGION_NAME", null, null, String.class, "regionName", null, false, false, true, "VARCHAR", 50, 0, null, false, null, null, null, null, null, false);
/**
* REGION_ID: {PK, NotNull, INTEGER(10)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnRegionId() { return _columnRegionId; }
/**
* REGION_NAME: {NotNull, VARCHAR(50)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnRegionName() { return _columnRegionName; }
protected List<ColumnInfo> ccil() {
List<ColumnInfo> ls = newArrayList();
ls.add(columnRegionId());
ls.add(columnRegionName());
return ls;
}
{ initializeInformationResource(); }
// ===================================================================================
// Unique Info
// ===========
// -----------------------------------------------------
// Primary Element
// ---------------
protected UniqueInfo cpui() { return hpcpui(columnRegionId()); }
public boolean hasPrimaryKey() { return true; }
public boolean hasCompoundPrimaryKey() { return false; }
// ===================================================================================
// Relation Info
// =============
// cannot cache because it uses related DB meta instance while booting
// (instead, cached by super's collection)
// -----------------------------------------------------
// Foreign Property
// ----------------
// -----------------------------------------------------
// Referrer Property
// -----------------
/**
* MEMBER_ADDRESS by REGION_ID, named 'memberAddressList'.
* @return The information object of referrer property. (NotNull)
*/
public ReferrerInfo referrerMemberAddressList() {
Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnRegionId(), MemberAddressDbm.getInstance().columnRegionId());
return cri("FK_MEMBER_ADDRESS_REGION", "memberAddressList", this, MemberAddressDbm.getInstance(), mp, false, "region");
}
// ===================================================================================
// Various Info
// ============
// ===================================================================================
// Type Name
// =========
public String getEntityTypeName() { return "org.docksidestage.install.dbflute.exentity.Region"; }
public String getConditionBeanTypeName() { return "org.docksidestage.install.dbflute.cbean.RegionCB"; }
public String getBehaviorTypeName() { return "org.docksidestage.install.dbflute.exbhv.RegionBhv"; }
// ===================================================================================
// Object Type
// ===========
public Class<Region> getEntityType() { return Region.class; }
// ===================================================================================
// Object Instance
// ===============
public Region newEntity() { return new Region(); }
// ===================================================================================
// Map Communication
// =================
public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptPrimaryKeyMap((Region)et, mp); }
public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptAllColumnMap((Region)et, mp); }
public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); }
public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); }
}
| {'content_hash': '6c2eca8eb13b5864bc6fd60a63758842', 'timestamp': '', 'source': 'github', 'line_count': 149, 'max_line_length': 226, 'avg_line_length': 59.12751677852349, 'alnum_prop': 0.41146424517593644, 'repo_name': 'dbflute-test/dbflute-test-env-install', 'id': '79d9e45de1e5d542ec13e2f1592973e0716e45b0', 'size': '8810', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/docksidestage/install/dbflute/bsentity/dbmeta/RegionDbm.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '3590256'}]} |
/**
* @class Ext.form.Field
* @extends Ext.BoxComponent
* Base class for form fields that provides default event handling, sizing, value handling and other functionality.
* @constructor
* Creates a new Field
* @param {Object} config Configuration options
* @xtype field
*/
Ext.form.Field = Ext.extend(Ext.BoxComponent, {
/**
* <p>The label Element associated with this Field. <b>Only available after this Field has been rendered by a
* {@link form Ext.layout.FormLayout} layout manager.</b></p>
* @type Ext.Element
* @property label
*/
/**
* @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults
* to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are
* no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
* is not supported and should be avoided.
*/
/**
* @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
* not those which are built via applyTo (defaults to undefined).
*/
/**
* @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
*/
/**
* @cfg {String} name The field's HTML name attribute (defaults to '').
* <b>Note</b>: this property must be set if this field is to be automatically included with
* {@link Ext.form.BasicForm#submit form submit()}.
*/
/**
* @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to '').
*/
/**
* @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to 'x-form-invalid')
*/
invalidClass : 'x-form-invalid',
/**
* @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
* (defaults to 'The value in this field is invalid')
*/
invalidText : 'The value in this field is invalid',
/**
* @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to 'x-form-focus')
*/
focusClass : 'x-form-focus',
/**
* @cfg {Boolean} preventMark
* <tt>true</tt> to disable {@link #markInvalid marking the field invalid}.
* Defaults to <tt>false</tt>.
*/
/**
* @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
automatic validation (defaults to 'keyup').
*/
validationEvent : 'keyup',
/**
* @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
*/
validateOnBlur : true,
/**
* @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation
* is initiated (defaults to 250)
*/
validationDelay : 250,
/**
* @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
* element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
* See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
* <pre><code>{tag: 'input', type: 'text', size: '20', autocomplete: 'off'}</code></pre>
*/
defaultAutoCreate : {tag: 'input', type: 'text', size: '20', autocomplete: 'off'},
/**
* @cfg {String} fieldClass The default CSS class for the field (defaults to 'x-form-field')
*/
fieldClass : 'x-form-field',
/**
* @cfg {String} msgTarget<p>The location where the message text set through {@link #markInvalid} should display.
* Must be one of the following values:</p>
* <div class="mdetail-params"><ul>
* <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
* <div class="subdesc"><b>{@link Ext.QuickTips#init Ext.QuickTips.init} must have been called for this setting to work.</b></div</li>
* <li><code>title</code> Display the message in a default browser title attribute popup.</li>
* <li><code>under</code> Add a block div beneath the field containing the error message.</li>
* <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
* <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
* </ul></div>
*/
msgTarget : 'qtip',
/**
* @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field
* (defaults to 'normal').
*/
msgFx : 'normal',
/**
* @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
* (defaults to <tt>false</tt>).
* <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
* Setting <code>readOnly=true</code>, for example, will not disable triggering a
* ComboBox or DateField; it gives you the option of forcing the user to choose
* via the trigger without typing in the text box. To hide the trigger use
* <code>{@link Ext.form.TriggerField#hideTrigger hideTrigger}</code>.</p>
*/
readOnly : false,
/**
* @cfg {Boolean} disabled True to disable the field (defaults to false).
* <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
* disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
*/
disabled : false,
/**
* @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
* Defaults to <tt>true</tt>.
*/
submitValue: true,
// private
isFormField : true,
// private
msgDisplay: '',
// private
hasFocus : false,
// private
initComponent : function(){
Ext.form.Field.superclass.initComponent.call(this);
this.addEvents(
/**
* @event focus
* Fires when this field receives input focus.
* @param {Ext.form.Field} this
*/
'focus',
/**
* @event blur
* Fires when this field loses input focus.
* @param {Ext.form.Field} this
*/
'blur',
/**
* @event specialkey
* Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
* To handle other keys see {@link Ext.Panel#keys} or {@link Ext.KeyMap}.
* You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
* For example: <pre><code>
var form = new Ext.form.FormPanel({
...
items: [{
fieldLabel: 'Field 1',
name: 'field1',
allowBlank: false
},{
fieldLabel: 'Field 2',
name: 'field2',
listeners: {
specialkey: function(field, e){
// e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
// e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
var form = field.ownerCt.getForm();
form.submit();
}
}
}
}
],
...
});
* </code></pre>
* @param {Ext.form.Field} this
* @param {Ext.EventObject} e The event object
*/
'specialkey',
/**
* @event change
* Fires just before the field blurs if the field value has changed.
* @param {Ext.form.Field} this
* @param {Mixed} newValue The new value
* @param {Mixed} oldValue The original value
*/
'change',
/**
* @event invalid
* Fires after the field has been marked as invalid.
* @param {Ext.form.Field} this
* @param {String} msg The validation message
*/
'invalid',
/**
* @event valid
* Fires after the field has been validated with no errors.
* @param {Ext.form.Field} this
*/
'valid'
);
},
/**
* Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
* attribute of the field if available.
* @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
*/
getName : function(){
return this.rendered && this.el.dom.name ? this.el.dom.name : this.name || this.id || '';
},
// private
onRender : function(ct, position){
if(!this.el){
var cfg = this.getAutoCreate();
if(!cfg.name){
cfg.name = this.name || this.id;
}
if(this.inputType){
cfg.type = this.inputType;
}
this.autoEl = cfg;
}
Ext.form.Field.superclass.onRender.call(this, ct, position);
if(this.submitValue === false){
this.el.dom.removeAttribute('name');
}
var type = this.el.dom.type;
if(type){
if(type == 'password'){
type = 'text';
}
this.el.addClass('x-form-'+type);
}
if(this.readOnly){
this.setReadOnly(true);
}
if(this.tabIndex !== undefined){
this.el.dom.setAttribute('tabIndex', this.tabIndex);
}
this.el.addClass([this.fieldClass, this.cls]);
},
// private
getItemCt : function(){
return this.itemCt;
},
// private
initValue : function(){
if(this.value !== undefined){
this.setValue(this.value);
}else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
this.setValue(this.el.dom.value);
}
/**
* The original value of the field as configured in the {@link #value} configuration, or
* as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
* setting is <code>true</code>.
* @type mixed
* @property originalValue
*/
this.originalValue = this.getValue();
},
/**
* <p>Returns true if the value of this Field has been changed from its original value.
* Will return false if the field is disabled or has not been rendered yet.</p>
* <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with
* {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
* then the <i>original value</i> is updated when the values are loaded by
* {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p>
* @return {Boolean} True if this field has been changed from its original value (and
* is not disabled), false otherwise.
*/
isDirty : function() {
if(this.disabled || !this.rendered) {
return false;
}
return String(this.getValue()) !== String(this.originalValue);
},
/**
* Sets the read only state of this field.
* @param {Boolean} readOnly Whether the field should be read only.
*/
setReadOnly : function(readOnly){
if(this.rendered){
this.el.dom.readOnly = readOnly;
}
this.readOnly = readOnly;
},
// private
afterRender : function(){
Ext.form.Field.superclass.afterRender.call(this);
this.initEvents();
this.initValue();
},
// private
fireKey : function(e){
if(e.isSpecialKey()){
this.fireEvent('specialkey', this, e);
}
},
/**
* Resets the current field value to the originally loaded value and clears any validation messages.
* See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
*/
reset : function(){
this.setValue(this.originalValue);
this.clearInvalid();
},
// private
initEvents : function(){
this.mon(this.el, Ext.EventManager.useKeydown ? 'keydown' : 'keypress', this.fireKey, this);
this.mon(this.el, 'focus', this.onFocus, this);
// standardise buffer across all browsers + OS-es for consistent event order.
// (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
this.mon(this.el, 'blur', this.onBlur, this, this.inEditor ? {buffer:10} : null);
},
// private
preFocus: Ext.emptyFn,
// private
onFocus : function(){
this.preFocus();
if(this.focusClass){
this.el.addClass(this.focusClass);
}
if(!this.hasFocus){
this.hasFocus = true;
/**
* <p>The value that the Field had at the time it was last focused. This is the value that is passed
* to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p>
* <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p>
* @type mixed
* @property startValue
*/
this.startValue = this.getValue();
this.fireEvent('focus', this);
}
},
// private
beforeBlur : Ext.emptyFn,
// private
onBlur : function(){
this.beforeBlur();
if(this.focusClass){
this.el.removeClass(this.focusClass);
}
this.hasFocus = false;
if(this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')){
this.validate();
}
var v = this.getValue();
if(String(v) !== String(this.startValue)){
this.fireEvent('change', this, v, this.startValue);
}
this.fireEvent('blur', this);
this.postBlur();
},
// private
postBlur : Ext.emptyFn,
/**
* Returns whether or not the field value is currently valid by
* {@link #validateValue validating} the {@link #processValue processed value}
* of the field. <b>Note</b>: {@link #disabled} fields are ignored.
* @param {Boolean} preventMark True to disable marking the field invalid
* @return {Boolean} True if the value is valid, else false
*/
isValid : function(preventMark){
if(this.disabled){
return true;
}
var restore = this.preventMark;
this.preventMark = preventMark === true;
var v = this.validateValue(this.processValue(this.getRawValue()));
this.preventMark = restore;
return v;
},
/**
* Validates the field value
* @return {Boolean} True if the value is valid, else false
*/
validate : function(){
if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
this.clearInvalid();
return true;
}
return false;
},
/**
* This method should only be overridden if necessary to prepare raw values
* for validation (see {@link #validate} and {@link #isValid}). This method
* is expected to return the processed value for the field which will
* be used for validation (see validateValue method).
* @param {Mixed} value
*/
processValue : function(value){
return value;
},
/**
* @private
* Subclasses should provide the validation implementation by overriding this
* @param {Mixed} value
*/
validateValue : function(value){
return true;
},
/**
* Gets the active error message for this field.
* @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
*/
getActiveError : function(){
return this.activeError || '';
},
/**
* <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
* display the message and applying {@link #invalidClass} to the field's UI element.</p>
* <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
* if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
* submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
* {@link #isValid invalid}.
* @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
*/
markInvalid : function(msg){
if(!this.rendered || this.preventMark){ // not rendered
return;
}
msg = msg || this.invalidText;
var mt = this.getMessageHandler();
if(mt){
mt.mark(this, msg);
}else if(this.msgTarget){
this.el.addClass(this.invalidClass);
var t = Ext.getDom(this.msgTarget);
if(t){
t.innerHTML = msg;
t.style.display = this.msgDisplay;
}
}
this.activeError = msg;
this.fireEvent('invalid', this, msg);
},
/**
* Clear any invalid styles/messages for this field
*/
clearInvalid : function(){
if(!this.rendered || this.preventMark){ // not rendered
return;
}
this.el.removeClass(this.invalidClass);
var mt = this.getMessageHandler();
if(mt){
mt.clear(this);
}else if(this.msgTarget){
this.el.removeClass(this.invalidClass);
var t = Ext.getDom(this.msgTarget);
if(t){
t.innerHTML = '';
t.style.display = 'none';
}
}
delete this.activeError;
this.fireEvent('valid', this);
},
// private
getMessageHandler : function(){
return Ext.form.MessageTargets[this.msgTarget];
},
// private
getErrorCt : function(){
return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
},
// Alignment for 'under' target
alignErrorEl : function(){
this.errorEl.setWidth(this.getErrorCt().getWidth(true) - 20);
},
// Alignment for 'side' target
alignErrorIcon : function(){
this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
},
/**
* Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}.
* @return {Mixed} value The field value
*/
getRawValue : function(){
var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
return v;
},
/**
* Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
* @return {Mixed} value The field value
*/
getValue : function(){
if(!this.rendered) {
return this.value;
}
var v = this.el.getValue();
if(v === this.emptyText || v === undefined){
v = '';
}
return v;
},
/**
* Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
* @param {Mixed} value The value to set
* @return {Mixed} value The field value that is set
*/
setRawValue : function(v){
return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
},
/**
* Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}.
* @param {Mixed} value The value to set
* @return {Ext.form.Field} this
*/
setValue : function(v){
this.value = v;
if(this.rendered){
this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
this.validate();
}
return this;
},
// private, does not work for all fields
append : function(v){
this.setValue([this.getValue(), v].join(''));
}
/**
* @cfg {Boolean} autoWidth @hide
*/
/**
* @cfg {Boolean} autoHeight @hide
*/
/**
* @cfg {String} autoEl @hide
*/
});
Ext.form.MessageTargets = {
'qtip' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
field.el.dom.qtip = msg;
field.el.dom.qclass = 'x-form-invalid-tip';
if(Ext.QuickTips){ // fix for floating editors interacting with DND
Ext.QuickTips.enable();
}
},
clear: function(field){
field.el.removeClass(field.invalidClass);
field.el.dom.qtip = '';
}
},
'title' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
field.el.dom.title = msg;
},
clear: function(field){
field.el.dom.title = '';
}
},
'under' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
if(!field.errorEl){
var elp = field.getErrorCt();
if(!elp){ // field has no container el
field.el.dom.title = msg;
return;
}
field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
field.on('resize', field.alignErrorEl, field);
field.on('destroy', function(){
Ext.destroy(this.errorEl);
}, field);
}
field.alignErrorEl();
field.errorEl.update(msg);
Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
},
clear: function(field){
field.el.removeClass(field.invalidClass);
if(field.errorEl){
Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
}else{
field.el.dom.title = '';
}
}
},
'side' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
if(!field.errorIcon){
var elp = field.getErrorCt();
if(!elp){ // field has no container el
field.el.dom.title = msg;
return;
}
field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
field.on('resize', field.alignErrorIcon, field);
field.on('destroy', function(){
Ext.destroy(this.errorIcon);
}, field);
}
field.alignErrorIcon();
field.errorIcon.dom.qtip = msg;
field.errorIcon.dom.qclass = 'x-form-invalid-tip';
field.errorIcon.show();
},
clear: function(field){
field.el.removeClass(field.invalidClass);
if(field.errorIcon){
field.errorIcon.dom.qtip = '';
field.errorIcon.hide();
}else{
field.el.dom.title = '';
}
}
}
};
// anything other than normal should be considered experimental
Ext.form.Field.msgFx = {
normal : {
show: function(msgEl, f){
msgEl.setDisplayed('block');
},
hide : function(msgEl, f){
msgEl.setDisplayed(false).update('');
}
},
slide : {
show: function(msgEl, f){
msgEl.slideIn('t', {stopFx:true});
},
hide : function(msgEl, f){
msgEl.slideOut('t', {stopFx:true,useDisplay:true});
}
},
slideRight : {
show: function(msgEl, f){
msgEl.fixDisplay();
msgEl.alignTo(f.el, 'tl-tr');
msgEl.slideIn('l', {stopFx:true});
},
hide : function(msgEl, f){
msgEl.slideOut('l', {stopFx:true,useDisplay:true});
}
}
};
Ext.reg('field', Ext.form.Field);
/**
* @class Ext.form.TextField
* @extends Ext.form.Field
* <p>Basic text field. Can be used as a direct replacement for traditional text inputs,
* or as the base class for more sophisticated input controls (like {@link Ext.form.TextArea}
* and {@link Ext.form.ComboBox}).</p>
* <p><b><u>Validation</u></b></p>
* <p>The validation procedure is described in the documentation for {@link #validateValue}.</p>
* <p><b><u>Alter Validation Behavior</u></b></p>
* <p>Validation behavior for each field can be configured:</p>
* <div class="mdetail-params"><ul>
* <li><code>{@link Ext.form.TextField#invalidText invalidText}</code> : the default validation message to
* show if any validation step above does not provide a message when invalid</li>
* <li><code>{@link Ext.form.TextField#maskRe maskRe}</code> : filter out keystrokes before any validation occurs</li>
* <li><code>{@link Ext.form.TextField#stripCharsRe stripCharsRe}</code> : filter characters after being typed in,
* but before being validated</li>
* <li><code>{@link Ext.form.Field#invalidClass invalidClass}</code> : alternate style when invalid</li>
* <li><code>{@link Ext.form.Field#validateOnBlur validateOnBlur}</code>,
* <code>{@link Ext.form.Field#validationDelay validationDelay}</code>, and
* <code>{@link Ext.form.Field#validationEvent validationEvent}</code> : modify how/when validation is triggered</li>
* </ul></div>
*
* @constructor Creates a new TextField
* @param {Object} config Configuration options
*
* @xtype textfield
*/
Ext.form.TextField = Ext.extend(Ext.form.Field, {
/**
* @cfg {String} vtypeText A custom error message to display in place of the default message provided
* for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>''</tt>). <b>Note</b>:
* only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
*/
/**
* @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
* before validation (defaults to <tt>null</tt>).
*/
/**
* @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
* (defaults to <tt>false</tt>)
*/
grow : false,
/**
* @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
* to <tt>30</tt>)
*/
growMin : 30,
/**
* @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
* to <tt>800</tt>)
*/
growMax : 800,
/**
* @cfg {String} vtype A validation type name as defined in {@link Ext.form.VTypes} (defaults to <tt>null</tt>)
*/
vtype : null,
/**
* @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
* not match (defaults to <tt>null</tt>)
*/
maskRe : null,
/**
* @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
* to <tt>false</tt>)
*/
disableKeyFilter : false,
/**
* @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
* <tt>true</tt>)
*/
allowBlank : true,
/**
* @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
*/
minLength : 0,
/**
* @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
* This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
* and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
* entered into the field use <tt><b>{@link Ext.form.Field#autoCreate autoCreate}</b></tt> to add
* any attributes you want to a field, for example:<pre><code>
var myField = new Ext.form.NumberField({
id: 'mobile',
anchor:'90%',
fieldLabel: 'Mobile',
maxLength: 16, // for validation
autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'off', maxlength: '10'}
});
</code></pre>
*/
maxLength : Number.MAX_VALUE,
/**
* @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
* validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
*/
minLengthText : 'The minimum length for this field is {0}',
/**
* @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
* validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
*/
maxLengthText : 'The maximum length for this field is {0}',
/**
* @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
* receives input focus (defaults to <tt>false</tt>)
*/
selectOnFocus : false,
/**
* @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
* fails (defaults to <tt>'This field is required'</tt>)
*/
blankText : 'This field is required',
/**
* @cfg {Function} validator
* <p>A custom validation function to be called during field validation ({@link #validateValue})
* (defaults to <tt>null</tt>). If specified, this function will be called first, allowing the
* developer to override the default validation process.</p>
* <br><p>This function will be passed the following Parameters:</p>
* <div class="mdetail-params"><ul>
* <li><code>value</code>: <i>Mixed</i>
* <div class="sub-desc">The current field value</div></li>
* </ul></div>
* <br><p>This function is to Return:</p>
* <div class="mdetail-params"><ul>
* <li><code>true</code>: <i>Boolean</i>
* <div class="sub-desc"><code>true</code> if the value is valid</div></li>
* <li><code>msg</code>: <i>String</i>
* <div class="sub-desc">An error message if the value is invalid</div></li>
* </ul></div>
*/
validator : null,
/**
* @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
* (defaults to <tt>null</tt>). If the test fails, the field will be marked invalid using
* <b><tt>{@link #regexText}</tt></b>.
*/
regex : null,
/**
* @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
* test fails during validation (defaults to <tt>''</tt>)
*/
regexText : '',
/**
* @cfg {String} emptyText The default text to place into an empty field (defaults to <tt>null</tt>).
* <b>Note</b>: that this value will be submitted to the server if this field is enabled and configured
* with a {@link #name}.
*/
emptyText : null,
/**
* @cfg {String} emptyClass The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
* (defaults to <tt>'x-form-empty-field'</tt>). This class is automatically added and removed as needed
* depending on the current field value.
*/
emptyClass : 'x-form-empty-field',
/**
* @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input
* field (defaults to <tt>false</tt>)
*/
initComponent : function(){
Ext.form.TextField.superclass.initComponent.call(this);
this.addEvents(
/**
* @event autosize
* Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered. The field may or
* may not have actually changed size according to the default logic, but this event provides
* a hook for the developer to apply additional logic at runtime to resize the field if needed.
* @param {Ext.form.Field} this This text field
* @param {Number} width The new field width
*/
'autosize',
/**
* @event keydown
* Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
* is set to true.
* @param {Ext.form.TextField} this This text field
* @param {Ext.EventObject} e
*/
'keydown',
/**
* @event keyup
* Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
* is set to true.
* @param {Ext.form.TextField} this This text field
* @param {Ext.EventObject} e
*/
'keyup',
/**
* @event keypress
* Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
* is set to true.
* @param {Ext.form.TextField} this This text field
* @param {Ext.EventObject} e
*/
'keypress'
);
},
// private
initEvents : function(){
Ext.form.TextField.superclass.initEvents.call(this);
if(this.validationEvent == 'keyup'){
this.validationTask = new Ext.util.DelayedTask(this.validate, this);
this.mon(this.el, 'keyup', this.filterValidation, this);
}
else if(this.validationEvent !== false && this.validationEvent != 'blur'){
this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
}
if(this.selectOnFocus || this.emptyText){
this.mon(this.el, 'mousedown', this.onMouseDown, this);
if(this.emptyText){
this.applyEmptyText();
}
}
if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){
this.mon(this.el, 'keypress', this.filterKeys, this);
}
if(this.grow){
this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
this.mon(this.el, 'click', this.autoSize, this);
}
if(this.enableKeyEvents){
this.mon(this.el, {
scope: this,
keyup: this.onKeyUp,
keydown: this.onKeyDown,
keypress: this.onKeyPress
});
}
},
onMouseDown: function(e){
if(!this.hasFocus){
this.mon(this.el, 'mouseup', Ext.emptyFn, this, { single: true, preventDefault: true });
}
},
processValue : function(value){
if(this.stripCharsRe){
var newValue = value.replace(this.stripCharsRe, '');
if(newValue !== value){
this.setRawValue(newValue);
return newValue;
}
}
return value;
},
filterValidation : function(e){
if(!e.isNavKeyPress()){
this.validationTask.delay(this.validationDelay);
}
},
//private
onDisable: function(){
Ext.form.TextField.superclass.onDisable.call(this);
if(Ext.isIE){
this.el.dom.unselectable = 'on';
}
},
//private
onEnable: function(){
Ext.form.TextField.superclass.onEnable.call(this);
if(Ext.isIE){
this.el.dom.unselectable = '';
}
},
// private
onKeyUpBuffered : function(e){
if(this.doAutoSize(e)){
this.autoSize();
}
},
// private
doAutoSize : function(e){
return !e.isNavKeyPress();
},
// private
onKeyUp : function(e){
this.fireEvent('keyup', this, e);
},
// private
onKeyDown : function(e){
this.fireEvent('keydown', this, e);
},
// private
onKeyPress : function(e){
this.fireEvent('keypress', this, e);
},
/**
* Resets the current field value to the originally-loaded value and clears any validation messages.
* Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
* original value was blank.
*/
reset : function(){
Ext.form.TextField.superclass.reset.call(this);
this.applyEmptyText();
},
applyEmptyText : function(){
if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
this.setRawValue(this.emptyText);
this.el.addClass(this.emptyClass);
}
},
// private
preFocus : function(){
var el = this.el;
if(this.emptyText){
if(el.dom.value == this.emptyText){
this.setRawValue('');
}
el.removeClass(this.emptyClass);
}
if(this.selectOnFocus){
el.dom.select();
}
},
// private
postBlur : function(){
this.applyEmptyText();
},
// private
filterKeys : function(e){
if(e.ctrlKey){
return;
}
var k = e.getKey();
if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
return;
}
var cc = String.fromCharCode(e.getCharCode());
if(!Ext.isGecko && e.isSpecialKey() && !cc){
return;
}
if(!this.maskRe.test(cc)){
e.stopEvent();
}
},
setValue : function(v){
if(this.emptyText && this.el && !Ext.isEmpty(v)){
this.el.removeClass(this.emptyClass);
}
Ext.form.TextField.superclass.setValue.apply(this, arguments);
this.applyEmptyText();
this.autoSize();
return this;
},
/**
* <p>Validates a value according to the field's validation rules and marks the field as invalid
* if the validation fails. Validation rules are processed in the following order:</p>
* <div class="mdetail-params"><ul>
*
* <li><b>1. Field specific validator</b>
* <div class="sub-desc">
* <p>A validator offers a way to customize and reuse a validation specification.
* If a field is configured with a <code>{@link #validator}</code>
* function, it will be passed the current field value. The <code>{@link #validator}</code>
* function is expected to return either:
* <div class="mdetail-params"><ul>
* <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
* <li>a String to represent the invalid message if invalid (validation halts).</li>
* </ul></div>
* </div></li>
*
* <li><b>2. Basic Validation</b>
* <div class="sub-desc">
* <p>If the <code>{@link #validator}</code> has not halted validation,
* basic validation proceeds as follows:</p>
*
* <div class="mdetail-params"><ul>
*
* <li><code>{@link #allowBlank}</code> : (Invalid message =
* <code>{@link #emptyText}</code>)<div class="sub-desc">
* Depending on the configuration of <code>{@link #allowBlank}</code>, a
* blank field will cause validation to halt at this step and return
* Boolean true or false accordingly.
* </div></li>
*
* <li><code>{@link #minLength}</code> : (Invalid message =
* <code>{@link #minLengthText}</code>)<div class="sub-desc">
* If the passed value does not satisfy the <code>{@link #minLength}</code>
* specified, validation halts.
* </div></li>
*
* <li><code>{@link #maxLength}</code> : (Invalid message =
* <code>{@link #maxLengthText}</code>)<div class="sub-desc">
* If the passed value does not satisfy the <code>{@link #maxLength}</code>
* specified, validation halts.
* </div></li>
*
* </ul></div>
* </div></li>
*
* <li><b>3. Preconfigured Validation Types (VTypes)</b>
* <div class="sub-desc">
* <p>If none of the prior validation steps halts validation, a field
* configured with a <code>{@link #vtype}</code> will utilize the
* corresponding {@link Ext.form.VTypes VTypes} validation function.
* If invalid, either the field's <code>{@link #vtypeText}</code> or
* the VTypes vtype Text property will be used for the invalid message.
* Keystrokes on the field will be filtered according to the VTypes
* vtype Mask property.</p>
* </div></li>
*
* <li><b>4. Field specific regex test</b>
* <div class="sub-desc">
* <p>If none of the prior validation steps halts validation, a field's
* configured <code>{@link #regex}</code> test will be processed.
* The invalid message for this test is configured with
* <code>{@link #regexText}</code>.</p>
* </div></li>
*
* @param {Mixed} value The value to validate
* @return {Boolean} True if the value is valid, else false
*/
validateValue : function(value){
if(Ext.isFunction(this.validator)){
var msg = this.validator(value);
if(msg !== true){
this.markInvalid(msg);
return false;
}
}
if(value.length < 1 || value === this.emptyText){ // if it's blank
if(this.allowBlank){
this.clearInvalid();
return true;
}else{
this.markInvalid(this.blankText);
return false;
}
}
if(value.length < this.minLength){
this.markInvalid(String.format(this.minLengthText, this.minLength));
return false;
}
if(value.length > this.maxLength){
this.markInvalid(String.format(this.maxLengthText, this.maxLength));
return false;
}
if(this.vtype){
var vt = Ext.form.VTypes;
if(!vt[this.vtype](value, this)){
this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
return false;
}
}
if(this.regex && !this.regex.test(value)){
this.markInvalid(this.regexText);
return false;
}
return true;
},
/**
* Selects text in this field
* @param {Number} start (optional) The index where the selection should start (defaults to 0)
* @param {Number} end (optional) The index where the selection should end (defaults to the text length)
*/
selectText : function(start, end){
var v = this.getRawValue();
var doFocus = false;
if(v.length > 0){
start = start === undefined ? 0 : start;
end = end === undefined ? v.length : end;
var d = this.el.dom;
if(d.setSelectionRange){
d.setSelectionRange(start, end);
}else if(d.createTextRange){
var range = d.createTextRange();
range.moveStart('character', start);
range.moveEnd('character', end-v.length);
range.select();
}
doFocus = Ext.isGecko || Ext.isOpera;
}else{
doFocus = true;
}
if(doFocus){
this.focus();
}
},
/**
* Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
* This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
*/
autoSize : function(){
if(!this.grow || !this.rendered){
return;
}
if(!this.metrics){
this.metrics = Ext.util.TextMetrics.createInstance(this.el);
}
var el = this.el;
var v = el.dom.value;
var d = document.createElement('div');
d.appendChild(document.createTextNode(v));
v = d.innerHTML;
Ext.removeNode(d);
d = null;
v += ' ';
var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
this.el.setWidth(w);
this.fireEvent('autosize', this, w);
},
onDestroy: function(){
if(this.validationTask){
this.validationTask.cancel();
this.validationTask = null;
}
Ext.form.TextField.superclass.onDestroy.call(this);
}
});
Ext.reg('textfield', Ext.form.TextField);
/**
* @class Ext.form.TriggerField
* @extends Ext.form.TextField
* Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
* The trigger has no default action, so you must assign a function to implement the trigger click handler by
* overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
* for which you can provide a custom implementation. For example:
* <pre><code>
var trigger = new Ext.form.TriggerField();
trigger.onTriggerClick = myTriggerFn;
trigger.applyToMarkup('my-field');
</code></pre>
*
* However, in general you will most likely want to use TriggerField as the base class for a reusable component.
* {@link Ext.form.DateField} and {@link Ext.form.ComboBox} are perfect examples of this.
*
* @constructor
* Create a new TriggerField.
* @param {Object} config Configuration options (valid {@Ext.form.TextField} config options will also be applied
* to the base TextField)
* @xtype trigger
*/
Ext.form.TriggerField = Ext.extend(Ext.form.TextField, {
/**
* @cfg {String} triggerClass
* An additional CSS class used to style the trigger button. The trigger will always get the
* class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
*/
/**
* @cfg {Mixed} triggerConfig
* <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the
* trigger element for this Field. (Optional).</p>
* <p>Specify this when you need a customized element to act as the trigger button for a TriggerField.</p>
* <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing, positioning
* and appearance of the trigger. Defaults to:</p>
* <pre><code>{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}</code></pre>
*/
/**
* @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
* element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
* See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
* <pre><code>{tag: "input", type: "text", size: "16", autocomplete: "off"}</code></pre>
*/
defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
/**
* @cfg {Boolean} hideTrigger <tt>true</tt> to hide the trigger element and display only the base
* text field (defaults to <tt>false</tt>)
*/
hideTrigger:false,
/**
* @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field,
* the field will only respond to a click on the trigger to set the value. (defaults to <tt>true</tt>).
*/
editable: true,
/**
* @cfg {Boolean} readOnly <tt>true</tt> to prevent the user from changing the field, and
* hides the trigger. Superceeds the editable and hideTrigger options if the value is true.
* (defaults to <tt>false</tt>)
*/
readOnly: false,
/**
* @cfg {String} wrapFocusClass The class added to the to the wrap of the trigger element. Defaults to
* <tt>x-trigger-wrap-focus</tt>.
*/
wrapFocusClass: 'x-trigger-wrap-focus',
/**
* @hide
* @method autoSize
*/
autoSize: Ext.emptyFn,
// private
monitorTab : true,
// private
deferHeight : true,
// private
mimicing : false,
actionMode: 'wrap',
defaultTriggerWidth: 17,
// private
onResize : function(w, h){
Ext.form.TriggerField.superclass.onResize.call(this, w, h);
var tw = this.getTriggerWidth();
if(Ext.isNumber(w)){
this.el.setWidth(w - tw);
}
this.wrap.setWidth(this.el.getWidth() + tw);
},
getTriggerWidth: function(){
var tw = this.trigger.getWidth();
if(!this.hideTrigger && tw === 0){
tw = this.defaultTriggerWidth;
}
return tw;
},
// private
alignErrorIcon : function(){
if(this.wrap){
this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
}
},
// private
onRender : function(ct, position){
this.doc = Ext.isIE ? Ext.getBody() : Ext.getDoc();
Ext.form.TriggerField.superclass.onRender.call(this, ct, position);
this.wrap = this.el.wrap({cls: 'x-form-field-wrap x-form-field-trigger-wrap'});
this.trigger = this.wrap.createChild(this.triggerConfig ||
{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});
this.initTrigger();
if(!this.width){
this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
}
this.resizeEl = this.positionEl = this.wrap;
},
updateEditState: function(){
if(this.rendered){
if (this.readOnly) {
this.el.dom.readOnly = true;
this.el.addClass('x-trigger-noedit');
this.mun(this.el, 'click', this.onTriggerClick, this);
this.trigger.setDisplayed(false);
} else {
if (!this.editable) {
this.el.dom.readOnly = true;
this.el.addClass('x-trigger-noedit');
this.mon(this.el, 'click', this.onTriggerClick, this);
} else {
this.el.dom.readOnly = false;
this.el.removeClass('x-trigger-noedit');
this.mun(this.el, 'click', this.onTriggerClick, this);
}
this.trigger.setDisplayed(!this.hideTrigger);
}
this.onResize(this.width || this.wrap.getWidth());
}
},
setHideTrigger: function(hideTrigger){
if(hideTrigger != this.hideTrigger){
this.hideTrigger = hideTrigger;
this.updateEditState();
}
},
/**
* @param {Boolean} value True to allow the user to directly edit the field text
* Allow or prevent the user from directly editing the field text. If false is passed,
* the user will only be able to modify the field using the trigger. Will also add
* a click event to the text field which will call the trigger. This method
* is the runtime equivalent of setting the 'editable' config option at config time.
*/
setEditable: function(editable){
if(editable != this.editable){
this.editable = editable;
this.updateEditState();
}
},
/**
* @param {Boolean} value True to prevent the user changing the field and explicitly
* hide the trigger.
* Setting this to true will superceed settings editable and hideTrigger.
* Setting this to false will defer back to editable and hideTrigger. This method
* is the runtime equivalent of setting the 'readOnly' config option at config time.
*/
setReadOnly: function(readOnly){
if(readOnly != this.readOnly){
this.readOnly = readOnly;
this.updateEditState();
}
},
afterRender : function(){
Ext.form.TriggerField.superclass.afterRender.call(this);
this.updateEditState();
},
// private
initTrigger : function(){
this.mon(this.trigger, 'click', this.onTriggerClick, this, {preventDefault:true});
this.trigger.addClassOnOver('x-form-trigger-over');
this.trigger.addClassOnClick('x-form-trigger-click');
},
// private
onDestroy : function(){
Ext.destroy(this.trigger, this.wrap);
if (this.mimicing){
this.doc.un('mousedown', this.mimicBlur, this);
}
delete this.doc;
Ext.form.TriggerField.superclass.onDestroy.call(this);
},
// private
onFocus : function(){
Ext.form.TriggerField.superclass.onFocus.call(this);
if(!this.mimicing){
this.wrap.addClass(this.wrapFocusClass);
this.mimicing = true;
this.doc.on('mousedown', this.mimicBlur, this, {delay: 10});
if(this.monitorTab){
this.on('specialkey', this.checkTab, this);
}
}
},
// private
checkTab : function(me, e){
if(e.getKey() == e.TAB){
this.triggerBlur();
}
},
// private
onBlur : Ext.emptyFn,
// private
mimicBlur : function(e){
if(!this.isDestroyed && !this.wrap.contains(e.target) && this.validateBlur(e)){
this.triggerBlur();
}
},
// private
triggerBlur : function(){
this.mimicing = false;
this.doc.un('mousedown', this.mimicBlur, this);
if(this.monitorTab && this.el){
this.un('specialkey', this.checkTab, this);
}
Ext.form.TriggerField.superclass.onBlur.call(this);
if(this.wrap){
this.wrap.removeClass(this.wrapFocusClass);
}
},
beforeBlur : Ext.emptyFn,
// private
// This should be overriden by any subclass that needs to check whether or not the field can be blurred.
validateBlur : function(e){
return true;
},
/**
* The function that should handle the trigger's click event. This method does nothing by default
* until overridden by an implementing function. See Ext.form.ComboBox and Ext.form.DateField for
* sample implementations.
* @method
* @param {EventObject} e
*/
onTriggerClick : Ext.emptyFn
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
});
/**
* @class Ext.form.TwinTriggerField
* @extends Ext.form.TriggerField
* TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
* to be extended by an implementing class. For an example of implementing this class, see the custom
* SearchField implementation here:
* <a href="http://extjs.com/deploy/ext/examples/form/custom.html">http://extjs.com/deploy/ext/examples/form/custom.html</a>
*/
Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, {
/**
* @cfg {Mixed} triggerConfig
* <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the trigger elements
* for this Field. (Optional).</p>
* <p>Specify this when you need a customized element to contain the two trigger elements for this Field.
* Each trigger element must be marked by the CSS class <tt>x-form-trigger</tt> (also see
* <tt>{@link #trigger1Class}</tt> and <tt>{@link #trigger2Class}</tt>).</p>
* <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing,
* positioning and appearance of the triggers.</p>
*/
/**
* @cfg {String} trigger1Class
* An additional CSS class used to style the trigger button. The trigger will always get the
* class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
*/
/**
* @cfg {String} trigger2Class
* An additional CSS class used to style the trigger button. The trigger will always get the
* class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
*/
initComponent : function(){
Ext.form.TwinTriggerField.superclass.initComponent.call(this);
this.triggerConfig = {
tag:'span', cls:'x-form-twin-triggers', cn:[
{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
]};
},
getTrigger : function(index){
return this.triggers[index];
},
initTrigger : function(){
var ts = this.trigger.select('.x-form-trigger', true);
var triggerField = this;
ts.each(function(t, all, index){
var triggerIndex = 'Trigger'+(index+1);
t.hide = function(){
var w = triggerField.wrap.getWidth();
this.dom.style.display = 'none';
triggerField.el.setWidth(w-triggerField.trigger.getWidth());
this['hidden' + triggerIndex] = true;
};
t.show = function(){
var w = triggerField.wrap.getWidth();
this.dom.style.display = '';
triggerField.el.setWidth(w-triggerField.trigger.getWidth());
this['hidden' + triggerIndex] = false;
};
if(this['hide'+triggerIndex]){
t.dom.style.display = 'none';
this['hidden' + triggerIndex] = true;
}
this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});
t.addClassOnOver('x-form-trigger-over');
t.addClassOnClick('x-form-trigger-click');
}, this);
this.triggers = ts.elements;
},
getTriggerWidth: function(){
var tw = 0;
Ext.each(this.triggers, function(t, index){
var triggerIndex = 'Trigger' + (index + 1),
w = t.getWidth();
if(w === 0 && !this['hidden' + triggerIndex]){
tw += this.defaultTriggerWidth;
}else{
tw += w;
}
}, this);
return tw;
},
// private
onDestroy : function() {
Ext.destroy(this.triggers);
Ext.form.TwinTriggerField.superclass.onDestroy.call(this);
},
/**
* The function that should handle the trigger's click event. This method does nothing by default
* until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
* for additional information.
* @method
* @param {EventObject} e
*/
onTrigger1Click : Ext.emptyFn,
/**
* The function that should handle the trigger's click event. This method does nothing by default
* until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
* for additional information.
* @method
* @param {EventObject} e
*/
onTrigger2Click : Ext.emptyFn
});
Ext.reg('trigger', Ext.form.TriggerField);
/**
* @class Ext.form.TextArea
* @extends Ext.form.TextField
* Multiline text field. Can be used as a direct replacement for traditional textarea fields, plus adds
* support for auto-sizing.
* @constructor
* Creates a new TextArea
* @param {Object} config Configuration options
* @xtype textarea
*/
Ext.form.TextArea = Ext.extend(Ext.form.TextField, {
/**
* @cfg {Number} growMin The minimum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
* (defaults to <tt>60</tt>)
*/
growMin : 60,
/**
* @cfg {Number} growMax The maximum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
* (defaults to <tt>1000</tt>)
*/
growMax: 1000,
growAppend : ' \n ',
enterIsSpecial : false,
/**
* @cfg {Boolean} preventScrollbars <tt>true</tt> to prevent scrollbars from appearing regardless of how much text is
* in the field. This option is only relevant when {@link #grow} is <tt>true</tt>. Equivalent to setting overflow: hidden, defaults to
* <tt>false</tt>.
*/
preventScrollbars: false,
/**
* @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
* element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
* See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
* <pre><code>{tag: "textarea", style: "width:100px;height:60px;", autocomplete: "off"}</code></pre>
*/
// private
onRender : function(ct, position){
if(!this.el){
this.defaultAutoCreate = {
tag: "textarea",
style:"width:100px;height:60px;",
autocomplete: "off"
};
}
Ext.form.TextArea.superclass.onRender.call(this, ct, position);
if(this.grow){
this.textSizeEl = Ext.DomHelper.append(document.body, {
tag: "pre", cls: "x-form-grow-sizer"
});
if(this.preventScrollbars){
this.el.setStyle("overflow", "hidden");
}
this.el.setHeight(this.growMin);
}
},
onDestroy : function(){
Ext.removeNode(this.textSizeEl);
Ext.form.TextArea.superclass.onDestroy.call(this);
},
fireKey : function(e){
if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){
this.fireEvent("specialkey", this, e);
}
},
// private
doAutoSize : function(e){
return !e.isNavKeyPress() || e.getKey() == e.ENTER;
},
/**
* Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
* This only takes effect if grow = true, and fires the {@link #autosize} event if the height changes.
*/
autoSize: function(){
if(!this.grow || !this.textSizeEl){
return;
}
var el = this.el,
v = Ext.util.Format.htmlEncode(el.dom.value),
ts = this.textSizeEl,
h;
Ext.fly(ts).setWidth(this.el.getWidth());
if(v.length < 1){
v = "  ";
}else{
v += this.growAppend;
if(Ext.isIE){
v = v.replace(/\n/g, ' <br />');
}
}
ts.innerHTML = v;
h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
if(h != this.lastHeight){
this.lastHeight = h;
this.el.setHeight(h);
this.fireEvent("autosize", this, h);
}
}
});
Ext.reg('textarea', Ext.form.TextArea);/**
* @class Ext.form.NumberField
* @extends Ext.form.TextField
* Numeric text field that provides automatic keystroke filtering and numeric validation.
* @constructor
* Creates a new NumberField
* @param {Object} config Configuration options
* @xtype numberfield
*/
Ext.form.NumberField = Ext.extend(Ext.form.TextField, {
/**
* @cfg {RegExp} stripCharsRe @hide
*/
/**
* @cfg {RegExp} maskRe @hide
*/
/**
* @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
*/
fieldClass: "x-form-field x-form-num-field",
/**
* @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
*/
allowDecimals : true,
/**
* @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
*/
decimalSeparator : ".",
/**
* @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
*/
decimalPrecision : 2,
/**
* @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
*/
allowNegative : true,
/**
* @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
*/
minValue : Number.NEGATIVE_INFINITY,
/**
* @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
*/
maxValue : Number.MAX_VALUE,
/**
* @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
*/
minText : "The minimum value for this field is {0}",
/**
* @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
*/
maxText : "The maximum value for this field is {0}",
/**
* @cfg {String} nanText Error text to display if the value is not a valid number. For example, this can happen
* if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
*/
nanText : "{0} is not a valid number",
/**
* @cfg {String} baseChars The base set of characters to evaluate as valid numbers (defaults to '0123456789').
*/
baseChars : "0123456789",
// private
initEvents : function(){
var allowed = this.baseChars + '';
if (this.allowDecimals) {
allowed += this.decimalSeparator;
}
if (this.allowNegative) {
allowed += '-';
}
this.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']');
Ext.form.NumberField.superclass.initEvents.call(this);
},
// private
validateValue : function(value){
if(!Ext.form.NumberField.superclass.validateValue.call(this, value)){
return false;
}
if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
return true;
}
value = String(value).replace(this.decimalSeparator, ".");
if(isNaN(value)){
this.markInvalid(String.format(this.nanText, value));
return false;
}
var num = this.parseValue(value);
if(num < this.minValue){
this.markInvalid(String.format(this.minText, this.minValue));
return false;
}
if(num > this.maxValue){
this.markInvalid(String.format(this.maxText, this.maxValue));
return false;
}
return true;
},
getValue : function(){
return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this)));
},
setValue : function(v){
v = Ext.isNumber(v) ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
return Ext.form.NumberField.superclass.setValue.call(this, v);
},
/**
* Replaces any existing {@link #minValue} with the new value.
* @param {Number} value The minimum value
*/
setMinValue : function(value){
this.minValue = Ext.num(value, Number.NEGATIVE_INFINITY);
},
/**
* Replaces any existing {@link #maxValue} with the new value.
* @param {Number} value The maximum value
*/
setMaxValue : function(value){
this.maxValue = Ext.num(value, Number.MAX_VALUE);
},
// private
parseValue : function(value){
value = parseFloat(String(value).replace(this.decimalSeparator, "."));
return isNaN(value) ? '' : value;
},
// private
fixPrecision : function(value){
var nan = isNaN(value);
if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
return nan ? '' : value;
}
return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
},
beforeBlur : function(){
var v = this.parseValue(this.getRawValue());
if(!Ext.isEmpty(v)){
this.setValue(this.fixPrecision(v));
}
}
});
Ext.reg('numberfield', Ext.form.NumberField);/**
* @class Ext.form.DateField
* @extends Ext.form.TriggerField
* Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation.
* @constructor
* Create a new DateField
* @param {Object} config
* @xtype datefield
*/
Ext.form.DateField = Ext.extend(Ext.form.TriggerField, {
/**
* @cfg {String} format
* The default date format string which can be overriden for localization support. The format must be
* valid according to {@link Date#parseDate} (defaults to <tt>'m/d/Y'</tt>).
*/
format : "m/d/Y",
/**
* @cfg {String} altFormats
* Multiple date formats separated by "<tt>|</tt>" to try when parsing a user input value and it
* does not match the defined format (defaults to
* <tt>'m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d'</tt>).
*/
altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d",
/**
* @cfg {String} disabledDaysText
* The tooltip to display when the date falls on a disabled day (defaults to <tt>'Disabled'</tt>)
*/
disabledDaysText : "Disabled",
/**
* @cfg {String} disabledDatesText
* The tooltip text to display when the date falls on a disabled date (defaults to <tt>'Disabled'</tt>)
*/
disabledDatesText : "Disabled",
/**
* @cfg {String} minText
* The error text to display when the date in the cell is before <tt>{@link #minValue}</tt> (defaults to
* <tt>'The date in this field must be after {minValue}'</tt>).
*/
minText : "The date in this field must be equal to or after {0}",
/**
* @cfg {String} maxText
* The error text to display when the date in the cell is after <tt>{@link #maxValue}</tt> (defaults to
* <tt>'The date in this field must be before {maxValue}'</tt>).
*/
maxText : "The date in this field must be equal to or before {0}",
/**
* @cfg {String} invalidText
* The error text to display when the date in the field is invalid (defaults to
* <tt>'{value} is not a valid date - it must be in the format {format}'</tt>).
*/
invalidText : "{0} is not a valid date - it must be in the format {1}",
/**
* @cfg {String} triggerClass
* An additional CSS class used to style the trigger button. The trigger will always get the
* class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
* (defaults to <tt>'x-form-date-trigger'</tt> which displays a calendar icon).
*/
triggerClass : 'x-form-date-trigger',
/**
* @cfg {Boolean} showToday
* <tt>false</tt> to hide the footer area of the DatePicker containing the Today button and disable
* the keyboard handler for spacebar that selects the current date (defaults to <tt>true</tt>).
*/
showToday : true,
/**
* @cfg {Date/String} minValue
* The minimum allowed date. Can be either a Javascript date object or a string date in a
* valid format (defaults to null).
*/
/**
* @cfg {Date/String} maxValue
* The maximum allowed date. Can be either a Javascript date object or a string date in a
* valid format (defaults to null).
*/
/**
* @cfg {Array} disabledDays
* An array of days to disable, 0 based (defaults to null). Some examples:<pre><code>
// disable Sunday and Saturday:
disabledDays: [0, 6]
// disable weekdays:
disabledDays: [1,2,3,4,5]
* </code></pre>
*/
/**
* @cfg {Array} disabledDates
* An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
* expression so they are very powerful. Some examples:<pre><code>
// disable these exact dates:
disabledDates: ["03/08/2003", "09/16/2003"]
// disable these days for every year:
disabledDates: ["03/08", "09/16"]
// only match the beginning (useful if you are using short years):
disabledDates: ["^03/08"]
// disable every day in March 2006:
disabledDates: ["03/../2006"]
// disable every day in every March:
disabledDates: ["^03"]
* </code></pre>
* Note that the format of the dates included in the array should exactly match the {@link #format} config.
* In order to support regular expressions, if you are using a {@link #format date format} that has "." in
* it, you will have to escape the dot when restricting dates. For example: <tt>["03\\.08\\.03"]</tt>.
*/
/**
* @cfg {String/Object} autoCreate
* A {@link Ext.DomHelper DomHelper element specification object}, or <tt>true</tt> for the default element
* specification object:<pre><code>
* autoCreate: {tag: "input", type: "text", size: "10", autocomplete: "off"}
* </code></pre>
*/
// private
defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
initComponent : function(){
Ext.form.DateField.superclass.initComponent.call(this);
this.addEvents(
/**
* @event select
* Fires when a date is selected via the date picker.
* @param {Ext.form.DateField} this
* @param {Date} date The date that was selected
*/
'select'
);
if(Ext.isString(this.minValue)){
this.minValue = this.parseDate(this.minValue);
}
if(Ext.isString(this.maxValue)){
this.maxValue = this.parseDate(this.maxValue);
}
this.disabledDatesRE = null;
this.initDisabledDays();
},
initEvents: function() {
Ext.form.DateField.superclass.initEvents.call(this);
this.keyNav = new Ext.KeyNav(this.el, {
"down": function(e) {
this.onTriggerClick();
},
scope: this,
forceKeyDown: true
});
},
// private
initDisabledDays : function(){
if(this.disabledDates){
var dd = this.disabledDates,
len = dd.length - 1,
re = "(?:";
Ext.each(dd, function(d, i){
re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
if(i != len){
re += '|';
}
}, this);
this.disabledDatesRE = new RegExp(re + ')');
}
},
/**
* Replaces any existing disabled dates with new values and refreshes the DatePicker.
* @param {Array} disabledDates An array of date strings (see the <tt>{@link #disabledDates}</tt> config
* for details on supported values) used to disable a pattern of dates.
*/
setDisabledDates : function(dd){
this.disabledDates = dd;
this.initDisabledDays();
if(this.menu){
this.menu.picker.setDisabledDates(this.disabledDatesRE);
}
},
/**
* Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
* @param {Array} disabledDays An array of disabled day indexes. See the <tt>{@link #disabledDays}</tt>
* config for details on supported values.
*/
setDisabledDays : function(dd){
this.disabledDays = dd;
if(this.menu){
this.menu.picker.setDisabledDays(dd);
}
},
/**
* Replaces any existing <tt>{@link #minValue}</tt> with the new value and refreshes the DatePicker.
* @param {Date} value The minimum date that can be selected
*/
setMinValue : function(dt){
this.minValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
if(this.menu){
this.menu.picker.setMinDate(this.minValue);
}
},
/**
* Replaces any existing <tt>{@link #maxValue}</tt> with the new value and refreshes the DatePicker.
* @param {Date} value The maximum date that can be selected
*/
setMaxValue : function(dt){
this.maxValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
if(this.menu){
this.menu.picker.setMaxDate(this.maxValue);
}
},
// private
validateValue : function(value){
value = this.formatDate(value);
if(!Ext.form.DateField.superclass.validateValue.call(this, value)){
return false;
}
if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
return true;
}
var svalue = value;
value = this.parseDate(value);
if(!value){
this.markInvalid(String.format(this.invalidText, svalue, this.format));
return false;
}
var time = value.getTime();
if(this.minValue && time < this.minValue.getTime()){
this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
return false;
}
if(this.maxValue && time > this.maxValue.getTime()){
this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
return false;
}
if(this.disabledDays){
var day = value.getDay();
for(var i = 0; i < this.disabledDays.length; i++) {
if(day === this.disabledDays[i]){
this.markInvalid(this.disabledDaysText);
return false;
}
}
}
var fvalue = this.formatDate(value);
if(this.disabledDatesRE && this.disabledDatesRE.test(fvalue)){
this.markInvalid(String.format(this.disabledDatesText, fvalue));
return false;
}
return true;
},
// private
// Provides logic to override the default TriggerField.validateBlur which just returns true
validateBlur : function(){
return !this.menu || !this.menu.isVisible();
},
/**
* Returns the current date value of the date field.
* @return {Date} The date value
*/
getValue : function(){
return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
},
/**
* Sets the value of the date field. You can pass a date object or any string that can be
* parsed into a valid date, using <tt>{@link #format}</tt> as the date format, according
* to the same rules as {@link Date#parseDate} (the default format used is <tt>"m/d/Y"</tt>).
* <br />Usage:
* <pre><code>
//All of these calls set the same date value (May 4, 2006)
//Pass a date object:
var dt = new Date('5/4/2006');
dateField.setValue(dt);
//Pass a date string (default format):
dateField.setValue('05/04/2006');
//Pass a date string (custom format):
dateField.format = 'Y-m-d';
dateField.setValue('2006-05-04');
</code></pre>
* @param {String/Date} date The date or valid date string
* @return {Ext.form.Field} this
*/
setValue : function(date){
return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
},
// private
parseDate : function(value){
if(!value || Ext.isDate(value)){
return value;
}
var v = Date.parseDate(value, this.format);
if(!v && this.altFormats){
if(!this.altFormatsArray){
this.altFormatsArray = this.altFormats.split("|");
}
for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
v = Date.parseDate(value, this.altFormatsArray[i]);
}
}
return v;
},
// private
onDestroy : function(){
Ext.destroy(this.menu, this.keyNav);
Ext.form.DateField.superclass.onDestroy.call(this);
},
// private
formatDate : function(date){
return Ext.isDate(date) ? date.dateFormat(this.format) : date;
},
/**
* @method onTriggerClick
* @hide
*/
// private
// Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
onTriggerClick : function(){
if(this.disabled){
return;
}
if(this.menu == null){
this.menu = new Ext.menu.DateMenu({
hideOnClick: false,
focusOnSelect: false
});
}
this.onFocus();
Ext.apply(this.menu.picker, {
minDate : this.minValue,
maxDate : this.maxValue,
disabledDatesRE : this.disabledDatesRE,
disabledDatesText : this.disabledDatesText,
disabledDays : this.disabledDays,
disabledDaysText : this.disabledDaysText,
format : this.format,
showToday : this.showToday,
minText : String.format(this.minText, this.formatDate(this.minValue)),
maxText : String.format(this.maxText, this.formatDate(this.maxValue))
});
this.menu.picker.setValue(this.getValue() || new Date());
this.menu.show(this.el, "tl-bl?");
this.menuEvents('on');
},
//private
menuEvents: function(method){
this.menu[method]('select', this.onSelect, this);
this.menu[method]('hide', this.onMenuHide, this);
this.menu[method]('show', this.onFocus, this);
},
onSelect: function(m, d){
this.setValue(d);
this.fireEvent('select', this, d);
this.menu.hide();
},
onMenuHide: function(){
this.focus(false, 60);
this.menuEvents('un');
},
// private
beforeBlur : function(){
var v = this.parseDate(this.getRawValue());
if(v){
this.setValue(v);
}
}
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
/**
* @hide
* @method autoSize
*/
});
Ext.reg('datefield', Ext.form.DateField);/**
* @class Ext.form.DisplayField
* @extends Ext.form.Field
* A display-only text field which is not validated and not submitted.
* @constructor
* Creates a new DisplayField.
* @param {Object} config Configuration options
* @xtype displayfield
*/
Ext.form.DisplayField = Ext.extend(Ext.form.Field, {
validationEvent : false,
validateOnBlur : false,
defaultAutoCreate : {tag: "div"},
/**
* @cfg {String} fieldClass The default CSS class for the field (defaults to <tt>"x-form-display-field"</tt>)
*/
fieldClass : "x-form-display-field",
/**
* @cfg {Boolean} htmlEncode <tt>false</tt> to skip HTML-encoding the text when rendering it (defaults to
* <tt>false</tt>). This might be useful if you want to include tags in the field's innerHTML rather than
* rendering them as string literals per the default logic.
*/
htmlEncode: false,
// private
initEvents : Ext.emptyFn,
isValid : function(){
return true;
},
validate : function(){
return true;
},
getRawValue : function(){
var v = this.rendered ? this.el.dom.innerHTML : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
if(this.htmlEncode){
v = Ext.util.Format.htmlDecode(v);
}
return v;
},
getValue : function(){
return this.getRawValue();
},
getName: function() {
return this.name;
},
setRawValue : function(v){
if(this.htmlEncode){
v = Ext.util.Format.htmlEncode(v);
}
return this.rendered ? (this.el.dom.innerHTML = (Ext.isEmpty(v) ? '' : v)) : (this.value = v);
},
setValue : function(v){
this.setRawValue(v);
return this;
}
/**
* @cfg {String} inputType
* @hide
*/
/**
* @cfg {Boolean} disabled
* @hide
*/
/**
* @cfg {Boolean} readOnly
* @hide
*/
/**
* @cfg {Boolean} validateOnBlur
* @hide
*/
/**
* @cfg {Number} validationDelay
* @hide
*/
/**
* @cfg {String/Boolean} validationEvent
* @hide
*/
});
Ext.reg('displayfield', Ext.form.DisplayField);
/**
* @class Ext.form.ComboBox
* @extends Ext.form.TriggerField
* <p>A combobox control with support for autocomplete, remote-loading, paging and many other features.</p>
* <p>A ComboBox works in a similar manner to a traditional HTML <select> field. The difference is
* that to submit the {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input
* field to hold the value of the valueField. The <i>{@link #displayField}</i> is shown in the text field
* which is named according to the {@link #name}.</p>
* <p><b><u>Events</u></b></p>
* <p>To do something when something in ComboBox is selected, configure the select event:<pre><code>
var cb = new Ext.form.ComboBox({
// all of your config options
listeners:{
scope: yourScope,
'select': yourFunction
}
});
// Alternatively, you can assign events after the object is created:
var cb = new Ext.form.ComboBox(yourOptions);
cb.on('select', yourFunction, yourScope);
* </code></pre></p>
*
* <p><b><u>ComboBox in Grid</u></b></p>
* <p>If using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a {@link Ext.grid.Column#renderer renderer}
* will be needed to show the displayField when the editor is not active. Set up the renderer manually, or implement
* a reusable render, for example:<pre><code>
// create reusable renderer
Ext.util.Format.comboRenderer = function(combo){
return function(value){
var record = combo.findRecord(combo.{@link #valueField}, value);
return record ? record.get(combo.{@link #displayField}) : combo.{@link #valueNotFoundText};
}
}
// create the combo instance
var combo = new Ext.form.ComboBox({
{@link #typeAhead}: true,
{@link #triggerAction}: 'all',
{@link #lazyRender}:true,
{@link #mode}: 'local',
{@link #store}: new Ext.data.ArrayStore({
id: 0,
fields: [
'myId',
'displayText'
],
data: [[1, 'item1'], [2, 'item2']]
}),
{@link #valueField}: 'myId',
{@link #displayField}: 'displayText'
});
// snippet of column model used within grid
var cm = new Ext.grid.ColumnModel([{
...
},{
header: "Some Header",
dataIndex: 'whatever',
width: 130,
editor: combo, // specify reference to combo instance
renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
},
...
]);
* </code></pre></p>
*
* <p><b><u>Filtering</u></b></p>
* <p>A ComboBox {@link #doQuery uses filtering itself}, for information about filtering the ComboBox
* store manually see <tt>{@link #lastQuery}</tt>.</p>
* @constructor
* Create a new ComboBox.
* @param {Object} config Configuration options
* @xtype combo
*/
Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
/**
* @cfg {Mixed} transform The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
* Note that if you specify this and the combo is going to be in an {@link Ext.form.BasicForm} or
* {@link Ext.form.FormPanel}, you must also set <tt>{@link #lazyRender} = true</tt>.
*/
/**
* @cfg {Boolean} lazyRender <tt>true</tt> to prevent the ComboBox from rendering until requested
* (should always be used when rendering into an {@link Ext.Editor} (e.g. {@link Ext.grid.EditorGridPanel Grids}),
* defaults to <tt>false</tt>).
*/
/**
* @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or <tt>true</tt> for a default
* element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
* See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>
* <pre><code>{tag: "input", type: "text", size: "24", autocomplete: "off"}</code></pre>
*/
/**
* @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
* Acceptable values for this property are:
* <div class="mdetail-params"><ul>
* <li><b>any {@link Ext.data.Store Store} subclass</b></li>
* <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally,
* automatically generating {@link Ext.data.Field#name field names} to work with all data components.
* <div class="mdetail-params"><ul>
* <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
* A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
* {@link #valueField} and {@link #displayField})</div></li>
* <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
* For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
* {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
* </div></li></ul></div></li></ul></div>
* <p>See also <tt>{@link #mode}</tt>.</p>
*/
/**
* @cfg {String} title If supplied, a header element is created containing this text and added into the top of
* the dropdown list (defaults to undefined, with no header element)
*/
// private
defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
/**
* @cfg {Number} listWidth The width (used as a parameter to {@link Ext.Element#setWidth}) of the dropdown
* list (defaults to the width of the ComboBox field). See also <tt>{@link #minListWidth}
*/
/**
* @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
* ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field1'</tt> if
* {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
* the store configuration}).
* <p>See also <tt>{@link #valueField}</tt>.</p>
* <p><b>Note</b>: if using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a
* {@link Ext.grid.Column#renderer renderer} will be needed to show the displayField when the editor is not
* active.</p>
*/
/**
* @cfg {String} valueField The underlying {@link Ext.data.Field#name data value name} to bind to this
* ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field2'</tt> if
* {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
* the store configuration}).
* <p><b>Note</b>: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
* mapped. See also <tt>{@link #hiddenName}</tt>, <tt>{@link #hiddenValue}</tt>, and <tt>{@link #displayField}</tt>.</p>
*/
/**
* @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
* field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
* post during a form submission. See also {@link #valueField}.
* <p><b>Note</b>: the hidden field's id will also default to this name if {@link #hiddenId} is not specified.
* The ComboBox {@link Ext.Component#id id} and the <tt>{@link #hiddenId}</tt> <b>should be different</b>, since
* no two DOM nodes should share the same id. So, if the ComboBox <tt>{@link Ext.form.Field#name name}</tt> and
* <tt>hiddenName</tt> are the same, you should specify a unique <tt>{@link #hiddenId}</tt>.</p>
*/
/**
* @cfg {String} hiddenId If <tt>{@link #hiddenName}</tt> is specified, <tt>hiddenId</tt> can also be provided
* to give the hidden field a unique id (defaults to the <tt>{@link #hiddenName}</tt>). The <tt>hiddenId</tt>
* and combo {@link Ext.Component#id id} should be different, since no two DOM
* nodes should share the same id.
*/
/**
* @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
* specified to contain the selected {@link #valueField}, from the Store. Defaults to the configured
* <tt>{@link Ext.form.Field#value value}</tt>.
*/
/**
* @cfg {String} listClass The CSS class to add to the predefined <tt>'x-combo-list'</tt> class
* applied the dropdown list element (defaults to '').
*/
listClass : '',
/**
* @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list
* (defaults to <tt>'x-combo-selected'</tt>)
*/
selectedClass : 'x-combo-selected',
/**
* @cfg {String} listEmptyText The empty text to display in the data view if no items are found.
* (defaults to '')
*/
listEmptyText: '',
/**
* @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always
* get the class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
* (defaults to <tt>'x-form-arrow-trigger'</tt> which displays a downward arrow icon).
*/
triggerClass : 'x-form-arrow-trigger',
/**
* @cfg {Boolean/String} shadow <tt>true</tt> or <tt>"sides"</tt> for the default effect, <tt>"frame"</tt> for
* 4-way shadow, and <tt>"drop"</tt> for bottom-right
*/
shadow : 'sides',
/**
* @cfg {String/Array} listAlign A valid anchor position value. See <tt>{@link Ext.Element#alignTo}</tt> for details
* on supported anchor positions and offsets. To specify x/y offsets as well, this value
* may be specified as an Array of <tt>{@link Ext.Element#alignTo}</tt> method arguments.</p>
* <pre><code>[ 'tl-bl?', [6,0] ]</code></pre>(defaults to <tt>'tl-bl?'</tt>)
*/
listAlign : 'tl-bl?',
/**
* @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown
* (defaults to <tt>300</tt>)
*/
maxHeight : 300,
/**
* @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
* distance to the viewport edges (defaults to <tt>90</tt>)
*/
minHeight : 90,
/**
* @cfg {String} triggerAction The action to execute when the trigger is clicked.
* <div class="mdetail-params"><ul>
* <li><b><tt>'query'</tt></b> : <b>Default</b>
* <p class="sub-desc">{@link #doQuery run the query} using the {@link Ext.form.Field#getRawValue raw value}.</p></li>
* <li><b><tt>'all'</tt></b> :
* <p class="sub-desc">{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option</p></li>
* </ul></div>
* <p>See also <code>{@link #queryParam}</code>.</p>
*/
triggerAction : 'query',
/**
* @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
* {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #mode} = 'remote'</tt> or <tt>0</tt> if
* <tt>{@link #mode} = 'local'</tt>, does not apply if
* <tt>{@link Ext.form.TriggerField#editable editable} = false</tt>).
*/
minChars : 4,
/**
* @cfg {Boolean} autoSelect <tt>true</tt> to select the first result gathered by the data store (defaults
* to <tt>true</tt>). A false value would require a manual selection from the dropdown list to set the components value
* unless the value of ({@link #typeAheadDelay}) were true.
*/
autoSelect : true,
/**
* @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
* typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
* to <tt>false</tt>)
*/
typeAhead : false,
/**
* @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
* sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #mode} = 'remote'</tt>
* or <tt>10</tt> if <tt>{@link #mode} = 'local'</tt>)
*/
queryDelay : 500,
/**
* @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.PagingToolbar} is displayed in the
* footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
* {@link Ext.PagingToolbar#pageSize limit} parameters. Only applies when <tt>{@link #mode} = 'remote'</tt>
* (defaults to <tt>0</tt>).
*/
pageSize : 0,
/**
* @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
* Only applies when <tt>{@link Ext.form.TriggerField#editable editable} = true</tt> (defaults to
* <tt>false</tt>).
*/
selectOnFocus : false,
/**
* @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
* as it will be passed on the querystring (defaults to <tt>'query'</tt>)
*/
queryParam : 'query',
/**
* @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies
* when <tt>{@link #mode} = 'remote'</tt> (defaults to <tt>'Loading...'</tt>)
*/
loadingText : 'Loading...',
/**
* @cfg {Boolean} resizable <tt>true</tt> to add a resize handle to the bottom of the dropdown list
* (creates an {@link Ext.Resizable} with 'se' {@link Ext.Resizable#pinned pinned} handles).
* Defaults to <tt>false</tt>.
*/
resizable : false,
/**
* @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if
* <tt>{@link #resizable} = true</tt> (defaults to <tt>8</tt>)
*/
handleHeight : 8,
/**
* @cfg {String} allQuery The text query to send to the server to return all records for the list
* with no filtering (defaults to '')
*/
allQuery: '',
/**
* @cfg {String} mode Acceptable values are:
* <div class="mdetail-params"><ul>
* <li><b><tt>'remote'</tt></b> : <b>Default</b>
* <p class="sub-desc">Automatically loads the <tt>{@link #store}</tt> the <b>first</b> time the trigger
* is clicked. If you do not want the store to be automatically loaded the first time the trigger is
* clicked, set to <tt>'local'</tt> and manually load the store. To force a requery of the store
* <b>every</b> time the trigger is clicked see <tt>{@link #lastQuery}</tt>.</p></li>
* <li><b><tt>'local'</tt></b> :
* <p class="sub-desc">ComboBox loads local data</p>
* <pre><code>
var combo = new Ext.form.ComboBox({
renderTo: document.body,
mode: 'local',
store: new Ext.data.ArrayStore({
id: 0,
fields: [
'myId', // numeric value is the key
'displayText'
],
data: [[1, 'item1'], [2, 'item2']] // data is local
}),
valueField: 'myId',
displayField: 'displayText',
triggerAction: 'all'
});
* </code></pre></li>
* </ul></div>
*/
mode: 'remote',
/**
* @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to <tt>70</tt>, will
* be ignored if <tt>{@link #listWidth}</tt> has a higher value)
*/
minListWidth : 70,
/**
* @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
* <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
*/
forceSelection : false,
/**
* @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
* if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
*/
typeAheadDelay : 250,
/**
* @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
* the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
* default text is used, it means there is no value set and no validation will occur on this field.
*/
/**
* @cfg {Boolean} lazyInit <tt>true</tt> to not initialize the list for this combo until the field is focused
* (defaults to <tt>true</tt>)
*/
lazyInit : true,
/**
* @cfg {Boolean} clearFilterOnReset <tt>true</tt> to clear any filters on the store (when in local mode) when reset is called
* (defaults to <tt>true</tt>)
*/
clearFilterOnReset : true,
/**
* @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
* If a hiddenName is specified, setting this to true will cause both the hidden field and the element to be submitted.
* Defaults to <tt>undefined</tt>.
*/
submitValue: undefined,
/**
* The value of the match string used to filter the store. Delete this property to force a requery.
* Example use:
* <pre><code>
var combo = new Ext.form.ComboBox({
...
mode: 'remote',
...
listeners: {
// delete the previous query in the beforequery event or set
// combo.lastQuery = null (this will reload the store the next time it expands)
beforequery: function(qe){
delete qe.combo.lastQuery;
}
}
});
* </code></pre>
* To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
* configure the combo with <tt>lastQuery=''</tt>. Example use:
* <pre><code>
var combo = new Ext.form.ComboBox({
...
mode: 'local',
triggerAction: 'all',
lastQuery: ''
});
* </code></pre>
* @property lastQuery
* @type String
*/
// private
initComponent : function(){
Ext.form.ComboBox.superclass.initComponent.call(this);
this.addEvents(
/**
* @event expand
* Fires when the dropdown list is expanded
* @param {Ext.form.ComboBox} combo This combo box
*/
'expand',
/**
* @event collapse
* Fires when the dropdown list is collapsed
* @param {Ext.form.ComboBox} combo This combo box
*/
'collapse',
/**
* @event beforeselect
* Fires before a list item is selected. Return false to cancel the selection.
* @param {Ext.form.ComboBox} combo This combo box
* @param {Ext.data.Record} record The data record returned from the underlying store
* @param {Number} index The index of the selected item in the dropdown list
*/
'beforeselect',
/**
* @event select
* Fires when a list item is selected
* @param {Ext.form.ComboBox} combo This combo box
* @param {Ext.data.Record} record The data record returned from the underlying store
* @param {Number} index The index of the selected item in the dropdown list
*/
'select',
/**
* @event beforequery
* Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
* cancel property to true.
* @param {Object} queryEvent An object that has these properties:<ul>
* <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li>
* <li><code>query</code> : String <div class="sub-desc">The query</div></li>
* <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
* <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
* </ul>
*/
'beforequery'
);
if(this.transform){
var s = Ext.getDom(this.transform);
if(!this.hiddenName){
this.hiddenName = s.name;
}
if(!this.store){
this.mode = 'local';
var d = [], opts = s.options;
for(var i = 0, len = opts.length;i < len; i++){
var o = opts[i],
value = (o.hasAttribute ? o.hasAttribute('value') : o.getAttributeNode('value').specified) ? o.value : o.text;
if(o.selected && Ext.isEmpty(this.value, true)) {
this.value = value;
}
d.push([value, o.text]);
}
this.store = new Ext.data.ArrayStore({
'id': 0,
fields: ['value', 'text'],
data : d,
autoDestroy: true
});
this.valueField = 'value';
this.displayField = 'text';
}
s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
if(!this.lazyRender){
this.target = true;
this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
this.render(this.el.parentNode, s);
}
Ext.removeNode(s);
}
//auto-configure store from local array data
else if(this.store){
this.store = Ext.StoreMgr.lookup(this.store);
if(this.store.autoCreated){
this.displayField = this.valueField = 'field1';
if(!this.store.expandData){
this.displayField = 'field2';
}
this.mode = 'local';
}
}
this.selectedIndex = -1;
if(this.mode == 'local'){
if(!Ext.isDefined(this.initialConfig.queryDelay)){
this.queryDelay = 10;
}
if(!Ext.isDefined(this.initialConfig.minChars)){
this.minChars = 0;
}
}
},
// private
onRender : function(ct, position){
if(this.hiddenName && !Ext.isDefined(this.submitValue)){
this.submitValue = false;
}
Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
if(this.hiddenName){
this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
id: (this.hiddenId||this.hiddenName)}, 'before', true);
}
if(Ext.isGecko){
this.el.dom.setAttribute('autocomplete', 'off');
}
if(!this.lazyInit){
this.initList();
}else{
this.on('focus', this.initList, this, {single: true});
}
},
// private
initValue : function(){
Ext.form.ComboBox.superclass.initValue.call(this);
if(this.hiddenField){
this.hiddenField.value =
Ext.value(Ext.isDefined(this.hiddenValue) ? this.hiddenValue : this.value, '');
}
},
// private
initList : function(){
if(!this.list){
var cls = 'x-combo-list',
listParent = Ext.getDom(this.getListParent() || Ext.getBody()),
zindex = parseInt(Ext.fly(listParent).getStyle('z-index') ,10);
if (this.ownerCt && !zindex){
this.findParentBy(function(ct){
zindex = parseInt(ct.getPositionEl().getStyle('z-index'), 10);
return !!zindex;
});
}
this.list = new Ext.Layer({
parentEl: listParent,
shadow: this.shadow,
cls: [cls, this.listClass].join(' '),
constrain:false,
zindex: (zindex || 12000) + 5
});
var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
this.list.setSize(lw, 0);
this.list.swallowEvent('mousewheel');
this.assetHeight = 0;
if(this.syncFont !== false){
this.list.setStyle('font-size', this.el.getStyle('font-size'));
}
if(this.title){
this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
this.assetHeight += this.header.getHeight();
}
this.innerList = this.list.createChild({cls:cls+'-inner'});
this.mon(this.innerList, 'mouseover', this.onViewOver, this);
this.mon(this.innerList, 'mousemove', this.onViewMove, this);
this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
if(this.pageSize){
this.footer = this.list.createChild({cls:cls+'-ft'});
this.pageTb = new Ext.PagingToolbar({
store: this.store,
pageSize: this.pageSize,
renderTo:this.footer
});
this.assetHeight += this.footer.getHeight();
}
if(!this.tpl){
/**
* @cfg {String/Ext.XTemplate} tpl <p>The template string, or {@link Ext.XTemplate} instance to
* use to display each item in the dropdown list. The dropdown list is displayed in a
* DataView. See {@link #view}.</p>
* <p>The default template string is:</p><pre><code>
'<tpl for="."><div class="x-combo-list-item">{' + this.displayField + '}</div></tpl>'
* </code></pre>
* <p>Override the default value to create custom UI layouts for items in the list.
* For example:</p><pre><code>
'<tpl for="."><div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}</div></tpl>'
* </code></pre>
* <p>The template <b>must</b> contain one or more substitution parameters using field
* names from the Combo's</b> {@link #store Store}. In the example above an
* <pre>ext:qtip</pre> attribute is added to display other fields from the Store.</p>
* <p>To preserve the default visual look of list items, add the CSS class name
* <pre>x-combo-list-item</pre> to the template's container element.</p>
* <p>Also see {@link #itemSelector} for additional details.</p>
*/
this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
/**
* @cfg {String} itemSelector
* <p>A simple CSS selector (e.g. div.some-class or span:first-child) that will be
* used to determine what nodes the {@link #view Ext.DataView} which handles the dropdown
* display will be working with.</p>
* <p><b>Note</b>: this setting is <b>required</b> if a custom XTemplate has been
* specified in {@link #tpl} which assigns a class other than <pre>'x-combo-list-item'</pre>
* to dropdown list items</b>
*/
}
/**
* The {@link Ext.DataView DataView} used to display the ComboBox's options.
* @type Ext.DataView
*/
this.view = new Ext.DataView({
applyTo: this.innerList,
tpl: this.tpl,
singleSelect: true,
selectedClass: this.selectedClass,
itemSelector: this.itemSelector || '.' + cls + '-item',
emptyText: this.listEmptyText,
deferEmptyText: false
});
this.mon(this.view, {
containerclick : this.onViewClick,
click : this.onViewClick,
scope :this
});
this.bindStore(this.store, true);
if(this.resizable){
this.resizer = new Ext.Resizable(this.list, {
pinned:true, handles:'se'
});
this.mon(this.resizer, 'resize', function(r, w, h){
this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
this.listWidth = w;
this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
this.restrictHeight();
}, this);
this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
}
}
},
/**
* <p>Returns the element used to house this ComboBox's pop-up list. Defaults to the document body.</p>
* A custom implementation may be provided as a configuration option if the floating list needs to be rendered
* to a different Element. An example might be rendering the list inside a Menu so that clicking
* the list does not hide the Menu:<pre><code>
var store = new Ext.data.ArrayStore({
autoDestroy: true,
fields: ['initials', 'fullname'],
data : [
['FF', 'Fred Flintstone'],
['BR', 'Barney Rubble']
]
});
var combo = new Ext.form.ComboBox({
store: store,
displayField: 'fullname',
emptyText: 'Select a name...',
forceSelection: true,
getListParent: function() {
return this.el.up('.x-menu');
},
iconCls: 'no-icon', //use iconCls if placing within menu to shift to right side of menu
mode: 'local',
selectOnFocus: true,
triggerAction: 'all',
typeAhead: true,
width: 135
});
var menu = new Ext.menu.Menu({
id: 'mainMenu',
items: [
combo // A Field in a Menu
]
});
</code></pre>
*/
getListParent : function() {
return document.body;
},
/**
* Returns the store associated with this combo.
* @return {Ext.data.Store} The store
*/
getStore : function(){
return this.store;
},
// private
bindStore : function(store, initial){
if(this.store && !initial){
if(this.store !== store && this.store.autoDestroy){
this.store.destroy();
}else{
this.store.un('beforeload', this.onBeforeLoad, this);
this.store.un('load', this.onLoad, this);
this.store.un('exception', this.collapse, this);
}
if(!store){
this.store = null;
if(this.view){
this.view.bindStore(null);
}
if(this.pageTb){
this.pageTb.bindStore(null);
}
}
}
if(store){
if(!initial) {
this.lastQuery = null;
if(this.pageTb) {
this.pageTb.bindStore(store);
}
}
this.store = Ext.StoreMgr.lookup(store);
this.store.on({
scope: this,
beforeload: this.onBeforeLoad,
load: this.onLoad,
exception: this.collapse
});
if(this.view){
this.view.bindStore(store);
}
}
},
reset : function(){
Ext.form.ComboBox.superclass.reset.call(this);
if(this.clearFilterOnReset && this.mode == 'local'){
this.store.clearFilter();
}
},
// private
initEvents : function(){
Ext.form.ComboBox.superclass.initEvents.call(this);
this.keyNav = new Ext.KeyNav(this.el, {
"up" : function(e){
this.inKeyMode = true;
this.selectPrev();
},
"down" : function(e){
if(!this.isExpanded()){
this.onTriggerClick();
}else{
this.inKeyMode = true;
this.selectNext();
}
},
"enter" : function(e){
this.onViewClick();
},
"esc" : function(e){
this.collapse();
},
"tab" : function(e){
this.collapse();
return true;
},
scope : this,
doRelay : function(e, h, hname){
if(hname == 'down' || this.scope.isExpanded()){
// this MUST be called before ComboBox#fireKey()
var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
if(!Ext.isIE && Ext.EventManager.useKeydown){
// call Combo#fireKey() for browsers which use keydown event (except IE)
this.scope.fireKey(e);
}
return relay;
}
return true;
},
forceKeyDown : true,
defaultEventAction: 'stopEvent'
});
this.queryDelay = Math.max(this.queryDelay || 10,
this.mode == 'local' ? 10 : 250);
this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
if(this.typeAhead){
this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
}
if(!this.enableKeyEvents){
this.mon(this.el, 'keyup', this.onKeyUp, this);
}
},
// private
onDestroy : function(){
if (this.dqTask){
this.dqTask.cancel();
this.dqTask = null;
}
this.bindStore(null);
Ext.destroy(
this.resizer,
this.view,
this.pageTb,
this.list
);
Ext.destroyMembers(this, 'hiddenField');
Ext.form.ComboBox.superclass.onDestroy.call(this);
},
// private
fireKey : function(e){
if (!this.isExpanded()) {
Ext.form.ComboBox.superclass.fireKey.call(this, e);
}
},
// private
onResize : function(w, h){
Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
if(this.isVisible() && this.list){
this.doResize(w);
}else{
this.bufferSize = w;
}
},
doResize: function(w){
if(!Ext.isDefined(this.listWidth)){
var lw = Math.max(w, this.minListWidth);
this.list.setWidth(lw);
this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
}
},
// private
onEnable : function(){
Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
if(this.hiddenField){
this.hiddenField.disabled = false;
}
},
// private
onDisable : function(){
Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
if(this.hiddenField){
this.hiddenField.disabled = true;
}
},
// private
onBeforeLoad : function(){
if(!this.hasFocus){
return;
}
this.innerList.update(this.loadingText ?
'<div class="loading-indicator">'+this.loadingText+'</div>' : '');
this.restrictHeight();
this.selectedIndex = -1;
},
// private
onLoad : function(){
if(!this.hasFocus){
return;
}
if(this.store.getCount() > 0 || this.listEmptyText){
this.expand();
this.restrictHeight();
if(this.lastQuery == this.allQuery){
if(this.editable){
this.el.dom.select();
}
if(this.autoSelect !== false && !this.selectByValue(this.value, true)){
this.select(0, true);
}
}else{
if(this.autoSelect !== false){
this.selectNext();
}
if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
this.taTask.delay(this.typeAheadDelay);
}
}
}else{
this.collapse();
}
},
// private
onTypeAhead : function(){
if(this.store.getCount() > 0){
var r = this.store.getAt(0);
var newValue = r.data[this.displayField];
var len = newValue.length;
var selStart = this.getRawValue().length;
if(selStart != len){
this.setRawValue(newValue);
this.selectText(selStart, newValue.length);
}
}
},
// private
assertValue : function(){
var val = this.getRawValue(),
rec = this.findRecord(this.displayField, val);
if(!rec && this.forceSelection){
if(val.length > 0 && val != this.emptyText){
this.el.dom.value = Ext.value(this.lastSelectionText, '');
this.applyEmptyText();
}else{
this.clearValue();
}
}else{
if(rec){
val = rec.get(this.valueField || this.displayField);
}
this.setValue(val);
}
},
// private
onSelect : function(record, index){
if(this.fireEvent('beforeselect', this, record, index) !== false){
this.setValue(record.data[this.valueField || this.displayField]);
this.collapse();
this.fireEvent('select', this, record, index);
}
},
// inherit docs
getName: function(){
var hf = this.hiddenField;
return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
},
/**
* Returns the currently selected field value or empty string if no value is set.
* @return {String} value The selected value
*/
getValue : function(){
if(this.valueField){
return Ext.isDefined(this.value) ? this.value : '';
}else{
return Ext.form.ComboBox.superclass.getValue.call(this);
}
},
/**
* Clears any text/value currently set in the field
*/
clearValue : function(){
if(this.hiddenField){
this.hiddenField.value = '';
}
this.setRawValue('');
this.lastSelectionText = '';
this.applyEmptyText();
this.value = '';
},
/**
* Sets the specified value into the field. If the value finds a match, the corresponding record text
* will be displayed in the field. If the value does not match the data value of an existing item,
* and the valueNotFoundText config option is defined, it will be displayed as the default field text.
* Otherwise the field will be blank (although the value will still be set).
* @param {String} value The value to match
* @return {Ext.form.Field} this
*/
setValue : function(v){
var text = v;
if(this.valueField){
var r = this.findRecord(this.valueField, v);
if(r){
text = r.data[this.displayField];
}else if(Ext.isDefined(this.valueNotFoundText)){
text = this.valueNotFoundText;
}
}
this.lastSelectionText = text;
if(this.hiddenField){
this.hiddenField.value = Ext.value(v, '');
}
Ext.form.ComboBox.superclass.setValue.call(this, text);
this.value = v;
return this;
},
// private
findRecord : function(prop, value){
var record;
if(this.store.getCount() > 0){
this.store.each(function(r){
if(r.data[prop] == value){
record = r;
return false;
}
});
}
return record;
},
// private
onViewMove : function(e, t){
this.inKeyMode = false;
},
// private
onViewOver : function(e, t){
if(this.inKeyMode){ // prevent key nav and mouse over conflicts
return;
}
var item = this.view.findItemFromChild(t);
if(item){
var index = this.view.indexOf(item);
this.select(index, false);
}
},
// private
onViewClick : function(doFocus){
var index = this.view.getSelectedIndexes()[0],
s = this.store,
r = s.getAt(index);
if(r){
this.onSelect(r, index);
}else {
this.collapse();
}
if(doFocus !== false){
this.el.focus();
}
},
// private
restrictHeight : function(){
this.innerList.dom.style.height = '';
var inner = this.innerList.dom,
pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
h = Math.min(h, space, this.maxHeight);
this.innerList.setHeight(h);
this.list.beginUpdate();
this.list.setHeight(h+pad);
this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
this.list.endUpdate();
},
/**
* Returns true if the dropdown list is expanded, else false.
*/
isExpanded : function(){
return this.list && this.list.isVisible();
},
/**
* Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
* The store must be loaded and the list expanded for this function to work, otherwise use setValue.
* @param {String} value The data value of the item to select
* @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
* selected item if it is not currently in view (defaults to true)
* @return {Boolean} True if the value matched an item in the list, else false
*/
selectByValue : function(v, scrollIntoView){
if(!Ext.isEmpty(v, true)){
var r = this.findRecord(this.valueField || this.displayField, v);
if(r){
this.select(this.store.indexOf(r), scrollIntoView);
return true;
}
}
return false;
},
/**
* Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
* The store must be loaded and the list expanded for this function to work, otherwise use setValue.
* @param {Number} index The zero-based index of the list item to select
* @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
* selected item if it is not currently in view (defaults to true)
*/
select : function(index, scrollIntoView){
this.selectedIndex = index;
this.view.select(index);
if(scrollIntoView !== false){
var el = this.view.getNode(index);
if(el){
this.innerList.scrollChildIntoView(el, false);
}
}
},
// private
selectNext : function(){
var ct = this.store.getCount();
if(ct > 0){
if(this.selectedIndex == -1){
this.select(0);
}else if(this.selectedIndex < ct-1){
this.select(this.selectedIndex+1);
}
}
},
// private
selectPrev : function(){
var ct = this.store.getCount();
if(ct > 0){
if(this.selectedIndex == -1){
this.select(0);
}else if(this.selectedIndex !== 0){
this.select(this.selectedIndex-1);
}
}
},
// private
onKeyUp : function(e){
var k = e.getKey();
if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
this.lastKey = k;
this.dqTask.delay(this.queryDelay);
}
Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
},
// private
validateBlur : function(){
return !this.list || !this.list.isVisible();
},
// private
initQuery : function(){
this.doQuery(this.getRawValue());
},
// private
beforeBlur : function(){
this.assertValue();
},
// private
postBlur : function(){
Ext.form.ComboBox.superclass.postBlur.call(this);
this.collapse();
this.inKeyMode = false;
},
/**
* Execute a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the
* query allowing the query action to be canceled if needed.
* @param {String} query The SQL query to execute
* @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
* characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option. It
* also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
*/
doQuery : function(q, forceAll){
q = Ext.isEmpty(q) ? '' : q;
var qe = {
query: q,
forceAll: forceAll,
combo: this,
cancel:false
};
if(this.fireEvent('beforequery', qe)===false || qe.cancel){
return false;
}
q = qe.query;
forceAll = qe.forceAll;
if(forceAll === true || (q.length >= this.minChars)){
if(this.lastQuery !== q){
this.lastQuery = q;
if(this.mode == 'local'){
this.selectedIndex = -1;
if(forceAll){
this.store.clearFilter();
}else{
this.store.filter(this.displayField, q);
}
this.onLoad();
}else{
this.store.baseParams[this.queryParam] = q;
this.store.load({
params: this.getParams(q)
});
this.expand();
}
}else{
this.selectedIndex = -1;
this.onLoad();
}
}
},
// private
getParams : function(q){
var p = {};
//p[this.queryParam] = q;
if(this.pageSize){
p.start = 0;
p.limit = this.pageSize;
}
return p;
},
/**
* Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
*/
collapse : function(){
if(!this.isExpanded()){
return;
}
this.list.hide();
Ext.getDoc().un('mousewheel', this.collapseIf, this);
Ext.getDoc().un('mousedown', this.collapseIf, this);
this.fireEvent('collapse', this);
},
// private
collapseIf : function(e){
if(!e.within(this.wrap) && !e.within(this.list)){
this.collapse();
}
},
/**
* Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
*/
expand : function(){
if(this.isExpanded() || !this.hasFocus){
return;
}
if(this.bufferSize){
this.doResize(this.bufferSize);
delete this.bufferSize;
}
this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
this.list.show();
if(Ext.isGecko2){
this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
}
this.mon(Ext.getDoc(), {
scope: this,
mousewheel: this.collapseIf,
mousedown: this.collapseIf
});
this.fireEvent('expand', this);
},
/**
* @method onTriggerClick
* @hide
*/
// private
// Implements the default empty TriggerField.onTriggerClick function
onTriggerClick : function(){
if(this.readOnly || this.disabled){
return;
}
if(this.isExpanded()){
this.collapse();
this.el.focus();
}else {
this.onFocus({});
if(this.triggerAction == 'all') {
this.doQuery(this.allQuery, true);
} else {
this.doQuery(this.getRawValue());
}
this.el.focus();
}
}
/**
* @hide
* @method autoSize
*/
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
});
Ext.reg('combo', Ext.form.ComboBox);
/**
* @class Ext.form.Checkbox
* @extends Ext.form.Field
* Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
* @constructor
* Creates a new Checkbox
* @param {Object} config Configuration options
* @xtype checkbox
*/
Ext.form.Checkbox = Ext.extend(Ext.form.Field, {
/**
* @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
*/
focusClass : undefined,
/**
* @cfg {String} fieldClass The default CSS class for the checkbox (defaults to 'x-form-field')
*/
fieldClass : 'x-form-field',
/**
* @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
*/
checked : false,
/**
* @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
* {tag: 'input', type: 'checkbox', autocomplete: 'off'})
*/
defaultAutoCreate : { tag: 'input', type: 'checkbox', autocomplete: 'off'},
/**
* @cfg {String} boxLabel The text that appears beside the checkbox
*/
/**
* @cfg {String} inputValue The value that should go into the generated input element's value attribute
*/
/**
* @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
* handling the check event). The handler is passed the following parameters:
* <div class="mdetail-params"><ul>
* <li><b>checkbox</b> : Ext.form.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
* <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
* </ul></div>
*/
/**
* @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
* (defaults to this Checkbox).
*/
// private
actionMode : 'wrap',
// private
initComponent : function(){
Ext.form.Checkbox.superclass.initComponent.call(this);
this.addEvents(
/**
* @event check
* Fires when the checkbox is checked or unchecked.
* @param {Ext.form.Checkbox} this This checkbox
* @param {Boolean} checked The new checked value
*/
'check'
);
},
// private
onResize : function(){
Ext.form.Checkbox.superclass.onResize.apply(this, arguments);
if(!this.boxLabel && !this.fieldLabel){
this.el.alignTo(this.wrap, 'c-c');
}
},
// private
initEvents : function(){
Ext.form.Checkbox.superclass.initEvents.call(this);
this.mon(this.el, {
scope: this,
click: this.onClick,
change: this.onClick
});
},
/**
* @hide
* Overridden and disabled. The editor element does not support standard valid/invalid marking.
* @method
*/
markInvalid : Ext.emptyFn,
/**
* @hide
* Overridden and disabled. The editor element does not support standard valid/invalid marking.
* @method
*/
clearInvalid : Ext.emptyFn,
// private
onRender : function(ct, position){
Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
if(this.inputValue !== undefined){
this.el.dom.value = this.inputValue;
}
this.wrap = this.el.wrap({cls: 'x-form-check-wrap'});
if(this.boxLabel){
this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
}
if(this.checked){
this.setValue(true);
}else{
this.checked = this.el.dom.checked;
}
// Need to repaint for IE, otherwise positioning is broken
if(Ext.isIE){
this.wrap.repaint();
}
this.resizeEl = this.positionEl = this.wrap;
},
// private
onDestroy : function(){
Ext.destroy(this.wrap);
Ext.form.Checkbox.superclass.onDestroy.call(this);
},
// private
initValue : function() {
this.originalValue = this.getValue();
},
/**
* Returns the checked state of the checkbox.
* @return {Boolean} True if checked, else false
*/
getValue : function(){
if(this.rendered){
return this.el.dom.checked;
}
return this.checked;
},
// private
onClick : function(){
if(this.el.dom.checked != this.checked){
this.setValue(this.el.dom.checked);
}
},
/**
* Sets the checked state of the checkbox, fires the 'check' event, and calls a
* <code>{@link #handler}</code> (if configured).
* @param {Boolean/String} checked The following values will check the checkbox:
* <code>true, 'true', '1', or 'on'</code>. Any other value will uncheck the checkbox.
* @return {Ext.form.Field} this
*/
setValue : function(v){
var checked = this.checked ;
this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
if(this.rendered){
this.el.dom.checked = this.checked;
this.el.dom.defaultChecked = this.checked;
}
if(checked != this.checked){
this.fireEvent('check', this, this.checked);
if(this.handler){
this.handler.call(this.scope || this, this, this.checked);
}
}
return this;
}
});
Ext.reg('checkbox', Ext.form.Checkbox);
/**
* @class Ext.form.CheckboxGroup
* @extends Ext.form.Field
* <p>A grouping container for {@link Ext.form.Checkbox} controls.</p>
* <p>Sample usage:</p>
* <pre><code>
var myCheckboxGroup = new Ext.form.CheckboxGroup({
id:'myGroup',
xtype: 'checkboxgroup',
fieldLabel: 'Single Column',
itemCls: 'x-check-group-alt',
// Put all controls in a single column with width 100%
columns: 1,
items: [
{boxLabel: 'Item 1', name: 'cb-col-1'},
{boxLabel: 'Item 2', name: 'cb-col-2', checked: true},
{boxLabel: 'Item 3', name: 'cb-col-3'}
]
});
* </code></pre>
* @constructor
* Creates a new CheckboxGroup
* @param {Object} config Configuration options
* @xtype checkboxgroup
*/
Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
/**
* @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
* to arrange in the group.
*/
/**
* @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
* checkbox/radio controls using automatic layout. This config can take several types of values:
* <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
* of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
* <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
* created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
* <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer
* (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
* be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
* values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
* container you should do so.</p></li></ul>
*/
columns : 'auto',
/**
* @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
* top to bottom before starting on the next column. The number of controls in each column will be automatically
* calculated to keep columns as even as possible. The default value is false, so that controls will be added
* to columns one at a time, completely filling each row left to right before starting on the next row.
*/
vertical : false,
/**
* @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
* If no items are selected at validation time, {@link @blankText} will be used as the error text.
*/
allowBlank : true,
/**
* @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
* select at least one item in this group")
*/
blankText : "You must select at least one item in this group",
// private
defaultType : 'checkbox',
// private
groupCls : 'x-form-check-group',
// private
initComponent: function(){
this.addEvents(
/**
* @event change
* Fires when the state of a child checkbox changes.
* @param {Ext.form.CheckboxGroup} this
* @param {Array} checked An array containing the checked boxes.
*/
'change'
);
this.on('change', this.validate, this);
Ext.form.CheckboxGroup.superclass.initComponent.call(this);
},
// private
onRender : function(ct, position){
if(!this.el){
var panelCfg = {
autoEl: {
id: this.id
},
cls: this.groupCls,
layout: 'column',
renderTo: ct,
bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.
};
var colCfg = {
xtype: 'container',
defaultType: this.defaultType,
layout: 'form',
defaults: {
hideLabel: true,
anchor: '100%'
}
};
if(this.items[0].items){
// The container has standard ColumnLayout configs, so pass them in directly
Ext.apply(panelCfg, {
layoutConfig: {columns: this.items.length},
defaults: this.defaults,
items: this.items
});
for(var i=0, len=this.items.length; i<len; i++){
Ext.applyIf(this.items[i], colCfg);
}
}else{
// The container has field item configs, so we have to generate the column
// panels first then move the items into the columns as needed.
var numCols, cols = [];
if(typeof this.columns == 'string'){ // 'auto' so create a col per item
this.columns = this.items.length;
}
if(!Ext.isArray(this.columns)){
var cs = [];
for(var i=0; i<this.columns; i++){
cs.push((100/this.columns)*.01); // distribute by even %
}
this.columns = cs;
}
numCols = this.columns.length;
// Generate the column configs with the correct width setting
for(var i=0; i<numCols; i++){
var cc = Ext.apply({items:[]}, colCfg);
cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
if(this.defaults){
cc.defaults = Ext.apply(cc.defaults || {}, this.defaults)
}
cols.push(cc);
};
// Distribute the original items into the columns
if(this.vertical){
var rows = Math.ceil(this.items.length / numCols), ri = 0;
for(var i=0, len=this.items.length; i<len; i++){
if(i>0 && i%rows==0){
ri++;
}
if(this.items[i].fieldLabel){
this.items[i].hideLabel = false;
}
cols[ri].items.push(this.items[i]);
};
}else{
for(var i=0, len=this.items.length; i<len; i++){
var ci = i % numCols;
if(this.items[i].fieldLabel){
this.items[i].hideLabel = false;
}
cols[ci].items.push(this.items[i]);
};
}
Ext.apply(panelCfg, {
layoutConfig: {columns: numCols},
items: cols
});
}
this.panel = new Ext.Container(panelCfg);
this.panel.ownerCt = this;
this.el = this.panel.getEl();
if(this.forId && this.itemCls){
var l = this.el.up(this.itemCls).child('label', true);
if(l){
l.setAttribute('htmlFor', this.forId);
}
}
var fields = this.panel.findBy(function(c){
return c.isFormField;
}, this);
this.items = new Ext.util.MixedCollection();
this.items.addAll(fields);
}
Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
},
initValue : function(){
if(this.value){
this.setValue.apply(this, this.buffered ? this.value : [this.value]);
delete this.buffered;
delete this.value;
}
},
afterRender : function(){
Ext.form.CheckboxGroup.superclass.afterRender.call(this);
this.eachItem(function(item){
item.on('check', this.fireChecked, this);
item.inGroup = true;
});
},
// private
doLayout: function(){
//ugly method required to layout hidden items
if(this.rendered){
this.panel.forceLayout = this.ownerCt.forceLayout;
this.panel.doLayout();
}
},
// private
fireChecked: function(){
var arr = [];
this.eachItem(function(item){
if(item.checked){
arr.push(item);
}
});
this.fireEvent('change', this, arr);
},
// private
validateValue : function(value){
if(!this.allowBlank){
var blank = true;
this.eachItem(function(f){
if(f.checked){
return (blank = false);
}
});
if(blank){
this.markInvalid(this.blankText);
return false;
}
}
return true;
},
// private
isDirty: function(){
//override the behaviour to check sub items.
if (this.disabled || !this.rendered) {
return false;
}
var dirty = false;
this.eachItem(function(item){
if(item.isDirty()){
dirty = true;
return false;
}
});
return dirty;
},
// private
onDisable : function(){
this.eachItem(function(item){
item.disable();
});
},
// private
onEnable : function(){
this.eachItem(function(item){
item.enable();
});
},
// private
doLayout: function(){
if(this.rendered){
this.panel.forceLayout = this.ownerCt.forceLayout;
this.panel.doLayout();
}
},
// private
onResize : function(w, h){
this.panel.setSize(w, h);
this.panel.doLayout();
},
// inherit docs from Field
reset : function(){
this.eachItem(function(c){
if(c.reset){
c.reset();
}
});
// Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
// Important because reset is being called on both the group and the individual items.
(function() {
this.clearInvalid();
}).defer(50, this);
},
/**
* {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items
* in the group. Examples illustrating how this method may be called:
* <pre><code>
// call with name and value
myCheckboxGroup.setValue('cb-col-1', true);
// call with an array of boolean values
myCheckboxGroup.setValue([true, false, false]);
// call with an object literal specifying item:value pairs
myCheckboxGroup.setValue({
'cb-col-2': false,
'cb-col-3': true
});
// use comma separated string to set items with name to true (checked)
myCheckboxGroup.setValue('cb-col-1,cb-col-3');
* </code></pre>
* See {@link Ext.form.Checkbox#setValue} for additional information.
* @param {Mixed} id The checkbox to check, or as described by example shown.
* @param {Boolean} value (optional) The value to set the item.
* @return {Ext.form.CheckboxGroup} this
*/
setValue: function(){
if(this.rendered){
this.onSetValue.apply(this, arguments);
}else{
this.buffered = true;
this.value = arguments;
}
return this;
},
onSetValue: function(id, value){
if(arguments.length == 1){
if(Ext.isArray(id)){
// an array of boolean values
Ext.each(id, function(val, idx){
var item = this.items.itemAt(idx);
if(item){
item.setValue(val);
}
}, this);
}else if(Ext.isObject(id)){
// set of name/value pairs
for(var i in id){
var f = this.getBox(i);
if(f){
f.setValue(id[i]);
}
}
}else{
this.setValueForItem(id);
}
}else{
var f = this.getBox(id);
if(f){
f.setValue(value);
}
}
},
// private
beforeDestroy: function(){
Ext.destroy(this.panel);
Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this);
},
setValueForItem : function(val){
val = String(val).split(',');
this.eachItem(function(item){
if(val.indexOf(item.inputValue)> -1){
item.setValue(true);
}
});
},
// private
getBox : function(id){
var box = null;
this.eachItem(function(f){
if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){
box = f;
return false;
}
});
return box;
},
/**
* Gets an array of the selected {@link Ext.form.Checkbox} in the group.
* @return {Array} An array of the selected checkboxes.
*/
getValue : function(){
var out = [];
this.eachItem(function(item){
if(item.checked){
out.push(item);
}
});
return out;
},
// private
eachItem: function(fn){
if(this.items && this.items.each){
this.items.each(fn, this);
}
},
/**
* @cfg {String} name
* @hide
*/
/**
* @method getRawValue
* @hide
*/
getRawValue : Ext.emptyFn,
/**
* @method setRawValue
* @hide
*/
setRawValue : Ext.emptyFn
});
Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);
/**
* @class Ext.form.Radio
* @extends Ext.form.Checkbox
* Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type.
* Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
* @constructor
* Creates a new Radio
* @param {Object} config Configuration options
* @xtype radio
*/
Ext.form.Radio = Ext.extend(Ext.form.Checkbox, {
inputType: 'radio',
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
markInvalid : Ext.emptyFn,
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
clearInvalid : Ext.emptyFn,
/**
* If this radio is part of a group, it will return the selected value
* @return {String}
*/
getGroupValue : function(){
var p = this.el.up('form') || Ext.getBody();
var c = p.child('input[name='+this.el.dom.name+']:checked', true);
return c ? c.value : null;
},
// private
onClick : function(){
if(this.el.dom.checked != this.checked){
var els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
els.each(function(el){
if(el.dom.id == this.id){
this.setValue(true);
}else{
Ext.getCmp(el.dom.id).setValue(false);
}
}, this);
}
},
/**
* Sets either the checked/unchecked status of this Radio, or, if a string value
* is passed, checks a sibling Radio of the same name whose value is the value specified.
* @param value {String/Boolean} Checked value, or the value of the sibling radio button to check.
* @return {Ext.form.Field} this
*/
setValue : function(v){
if (typeof v == 'boolean') {
Ext.form.Radio.superclass.setValue.call(this, v);
} else if (this.rendered) {
var r = this.getCheckEl().child('input[name=' + this.el.dom.name + '][value=' + v + ']', true);
if(r){
Ext.getCmp(r.id).setValue(true);
}
}
return this;
},
// private
getCheckEl: function(){
if(this.inGroup){
return this.el.up('.x-form-radio-group')
}
return this.el.up('form') || Ext.getBody();
}
});
Ext.reg('radio', Ext.form.Radio);
/**
* @class Ext.form.RadioGroup
* @extends Ext.form.CheckboxGroup
* A grouping container for {@link Ext.form.Radio} controls.
* @constructor
* Creates a new RadioGroup
* @param {Object} config Configuration options
* @xtype radiogroup
*/
Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
/**
* @cfg {Array} items An Array of {@link Ext.form.Radio Radio}s or Radio config objects
* to arrange in the group.
*/
/**
* @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true).
* If allowBlank = false and no items are selected at validation time, {@link @blankText} will
* be used as the error text.
*/
allowBlank : true,
/**
* @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
* (defaults to 'You must select one item in this group')
*/
blankText : 'You must select one item in this group',
// private
defaultType : 'radio',
// private
groupCls : 'x-form-radio-group',
/**
* @event change
* Fires when the state of a child radio changes.
* @param {Ext.form.RadioGroup} this
* @param {Ext.form.Radio} checked The checked radio
*/
/**
* Gets the selected {@link Ext.form.Radio} in the group, if it exists.
* @return {Ext.form.Radio} The selected radio.
*/
getValue : function(){
var out = null;
this.eachItem(function(item){
if(item.checked){
out = item;
return false;
}
});
return out;
},
/**
* Sets the checked radio in the group.
* @param {String/Ext.form.Radio} id The radio to check.
* @param {Boolean} value The value to set the radio.
* @return {Ext.form.RadioGroup} this
*/
onSetValue : function(id, value){
if(arguments.length > 1){
var f = this.getBox(id);
if(f){
f.setValue(value);
if(f.checked){
this.eachItem(function(item){
if (item !== f){
item.setValue(false);
}
});
}
}
}else{
this.setValueForItem(id);
}
},
setValueForItem : function(val){
val = String(val).split(',')[0];
this.eachItem(function(item){
item.setValue(val == item.inputValue);
});
},
// private
fireChecked : function(){
if(!this.checkTask){
this.checkTask = new Ext.util.DelayedTask(this.bufferChecked, this);
}
this.checkTask.delay(10);
},
// private
bufferChecked : function(){
var out = null;
this.eachItem(function(item){
if(item.checked){
out = item;
return false;
}
});
this.fireEvent('change', this, out);
},
onDestroy : function(){
if(this.checkTask){
this.checkTask.cancel();
this.checkTask = null;
}
Ext.form.RadioGroup.superclass.onDestroy.call(this);
}
});
Ext.reg('radiogroup', Ext.form.RadioGroup);
/**
* @class Ext.form.Hidden
* @extends Ext.form.Field
* A basic hidden field for storing hidden values in forms that need to be passed in the form submit.
* @constructor
* Create a new Hidden field.
* @param {Object} config Configuration options
* @xtype hidden
*/
Ext.form.Hidden = Ext.extend(Ext.form.Field, {
// private
inputType : 'hidden',
// private
onRender : function(){
Ext.form.Hidden.superclass.onRender.apply(this, arguments);
},
// private
initEvents : function(){
this.originalValue = this.getValue();
},
// These are all private overrides
setSize : Ext.emptyFn,
setWidth : Ext.emptyFn,
setHeight : Ext.emptyFn,
setPosition : Ext.emptyFn,
setPagePosition : Ext.emptyFn,
markInvalid : Ext.emptyFn,
clearInvalid : Ext.emptyFn
});
Ext.reg('hidden', Ext.form.Hidden);/**
* @class Ext.form.BasicForm
* @extends Ext.util.Observable
* <p>Encapsulates the DOM <form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
* input field management, validation, submission, and form loading services.</p>
* <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
* To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
* <p><b><u>File Uploads</u></b></p>
* <p>{@link #fileUpload File uploads} are not performed using Ajax submission, that
* is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
* manner with the DOM <tt><form></tt> element temporarily modified to have its
* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
* server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
* <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
* "<" as "&lt;", "&" as "&amp;" etc.</p>
* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
* @constructor
* @param {Mixed} el The form element or its id
* @param {Object} config Configuration options
*/
Ext.form.BasicForm = Ext.extend(Ext.util.Observable, {
constructor: function(el, config){
Ext.apply(this, config);
if(Ext.isString(this.paramOrder)){
this.paramOrder = this.paramOrder.split(/[\s,|]/);
}
/**
* A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
* @type MixedCollection
* @property items
*/
this.items = new Ext.util.MixedCollection(false, function(o){
return o.getItemId();
});
this.addEvents(
/**
* @event beforeaction
* Fires before any action is performed. Return false to cancel the action.
* @param {Form} this
* @param {Action} action The {@link Ext.form.Action} to be performed
*/
'beforeaction',
/**
* @event actionfailed
* Fires when an action fails.
* @param {Form} this
* @param {Action} action The {@link Ext.form.Action} that failed
*/
'actionfailed',
/**
* @event actioncomplete
* Fires when an action is completed.
* @param {Form} this
* @param {Action} action The {@link Ext.form.Action} that completed
*/
'actioncomplete'
);
if(el){
this.initEl(el);
}
Ext.form.BasicForm.superclass.constructor.call(this);
},
/**
* @cfg {String} method
* The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
*/
/**
* @cfg {DataReader} reader
* An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
* data when executing 'load' actions. This is optional as there is built-in
* support for processing JSON. For additional information on using an XMLReader
* see the example provided in examples/form/xml-form.html.
*/
/**
* @cfg {DataReader} errorReader
* <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
* read field error messages returned from 'submit' actions. This is optional
* as there is built-in support for processing JSON.</p>
* <p>The Records which provide messages for the invalid Fields must use the
* Field name (or id) as the Record ID, and must contain a field called 'msg'
* which contains the error message.</p>
* <p>The errorReader does not have to be a full-blown implementation of a
* DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
* which returns an Array of Records in an object with the following
* structure:</p><pre><code>
{
records: recordArray
}
</code></pre>
*/
/**
* @cfg {String} url
* The URL to use for form actions if one isn't supplied in the
* <code>{@link #doAction doAction} options</code>.
*/
/**
* @cfg {Boolean} fileUpload
* Set to true if this form is a file upload.
* <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
* performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
* DOM <tt><form></tt> element temporarily modified to have its
* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
* server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
* <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
* "<" as "&lt;", "&" as "&amp;" etc.</p>
* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
*/
/**
* @cfg {Object} baseParams
* <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
* <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
*/
/**
* @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
*/
timeout: 30,
/**
* @cfg {Object} api (Optional) If specified load and submit actions will be handled
* with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
* Methods which have been imported by Ext.Direct can be specified here to load and submit
* forms.
* Such as the following:<pre><code>
api: {
load: App.ss.MyProfile.load,
submit: App.ss.MyProfile.submit
}
</code></pre>
* <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
* to customize how the load method is invoked.
* Submit actions will always use a standard form submit. The formHandler configuration must
* be set on the associated server-side method which has been imported by Ext.Direct</p>
*/
/**
* @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
* Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
* <code>load</code> configuration.</p>
* <br><p>Specify the params in the order in which they must be executed on the
* server-side as either (1) an Array of String values, or (2) a String of params
* delimited by either whitespace, comma, or pipe. For example,
* any of the following would be acceptable:</p><pre><code>
paramOrder: ['param1','param2','param3']
paramOrder: 'param1 param2 param3'
paramOrder: 'param1,param2,param3'
paramOrder: 'param1|param2|param'
</code></pre>
*/
paramOrder: undefined,
/**
* @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
* <code>load</code> configuration. Send parameters as a collection of named
* arguments (defaults to <tt>false</tt>). Providing a
* <tt>{@link #paramOrder}</tt> nullifies this configuration.
*/
paramsAsHash: false,
/**
* @cfg {String} waitTitle
* The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
*/
waitTitle: 'Please Wait...',
// private
activeAction : null,
/**
* @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
* or {@link #setValues}() data instead of when the form was first created. Defaults to <tt>false</tt>.
*/
trackResetOnLoad : false,
/**
* @cfg {Boolean} standardSubmit
* <p>If set to <tt>true</tt>, standard HTML form submits are used instead
* of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
* <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
* <code>options</code> to <code>{@link #submit}</code> are ignored because
* Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
* <code>baseParams</code> and <code>params</code>), utilize hidden fields
* to submit extra data, for example:</p>
* <pre><code>
new Ext.FormPanel({
standardSubmit: true,
baseParams: {
foo: 'bar'
},
{@link url}: 'myProcess.php',
items: [{
xtype: 'textfield',
name: 'userName'
}],
buttons: [{
text: 'Save',
handler: function(){
var fp = this.ownerCt.ownerCt,
form = fp.getForm();
if (form.isValid()) {
// check if there are baseParams and if
// hiddent items have been added already
if (fp.baseParams && !fp.paramsAdded) {
// add hidden items for all baseParams
for (i in fp.baseParams) {
fp.add({
xtype: 'hidden',
name: i,
value: fp.baseParams[i]
});
}
fp.doLayout();
// set a custom flag to prevent re-adding
fp.paramsAdded = true;
}
form.{@link #submit}();
}
}
}]
});
* </code></pre>
*/
/**
* By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
* element by passing it or its id or mask the form itself by passing in true.
* @type Mixed
* @property waitMsgTarget
*/
// private
initEl : function(el){
this.el = Ext.get(el);
this.id = this.el.id || Ext.id();
if(!this.standardSubmit){
this.el.on('submit', this.onSubmit, this);
}
this.el.addClass('x-form');
},
/**
* Get the HTML form Element
* @return Ext.Element
*/
getEl: function(){
return this.el;
},
// private
onSubmit : function(e){
e.stopEvent();
},
// private
destroy: function() {
this.items.each(function(f){
Ext.destroy(f);
});
if(this.el){
this.el.removeAllListeners();
this.el.remove();
}
this.purgeListeners();
},
/**
* Returns true if client-side validation on the form is successful.
* @return Boolean
*/
isValid : function(){
var valid = true;
this.items.each(function(f){
if(!f.validate()){
valid = false;
}
});
return valid;
},
/**
* <p>Returns true if any fields in this form have changed from their original values.</p>
* <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
* Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
* or {@link #loadRecord}.</p>
* @return Boolean
*/
isDirty : function(){
var dirty = false;
this.items.each(function(f){
if(f.isDirty()){
dirty = true;
return false;
}
});
return dirty;
},
/**
* Performs a predefined action ({@link Ext.form.Action.Submit} or
* {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
* to perform application-specific processing.
* @param {String/Object} actionName The name of the predefined action type,
* or instance of {@link Ext.form.Action} to perform.
* @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
* All of the config options listed below are supported by both the
* {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
* actions unless otherwise noted (custom actions could also accept
* other config options):<ul>
*
* <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
* to the form's {@link #url}.)</div></li>
*
* <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
* to the form's method, or POST if not defined)</div></li>
*
* <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
* (defaults to the form's baseParams, or none if not defined)</p>
* <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
*
* <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
* (defaults to the form's default headers)</div></li>
*
* <li><b>success</b> : Function<div class="sub-desc">The callback that will
* be invoked after a successful response (see top of
* {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
* for a description of what constitutes a successful response).
* The function is passed the following parameters:<ul>
* <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
* <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
* <div class="sub-desc">The action object contains these properties of interest:<ul>
* <li><tt>{@link Ext.form.Action#response response}</tt></li>
* <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
* <li><tt>{@link Ext.form.Action#type type}</tt></li>
* </ul></div></li></ul></div></li>
*
* <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
* failed transaction attempt. The function is passed the following parameters:<ul>
* <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
* <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
* <div class="sub-desc">The action object contains these properties of interest:<ul>
* <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
* <li><tt>{@link Ext.form.Action#response response}</tt></li>
* <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
* <li><tt>{@link Ext.form.Action#type type}</tt></li>
* </ul></div></li></ul></div></li>
*
* <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
* callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
*
* <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
* Determines whether a Form's fields are validated in a final call to
* {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
* to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
*
* @return {BasicForm} this
*/
doAction : function(action, options){
if(Ext.isString(action)){
action = new Ext.form.Action.ACTION_TYPES[action](this, options);
}
if(this.fireEvent('beforeaction', this, action) !== false){
this.beforeAction(action);
action.run.defer(100, action);
}
return this;
},
/**
* Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
* @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
* <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
* <p>The following code:</p><pre><code>
myFormPanel.getForm().submit({
clientValidation: true,
url: 'updateConsignment.php',
params: {
newStatus: 'delivered'
},
success: function(form, action) {
Ext.Msg.alert('Success', action.result.msg);
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
}
}
});
</code></pre>
* would process the following server response for a successful submission:<pre><code>
{
"success":true, // note this is Boolean, not string
"msg":"Consignment updated"
}
</code></pre>
* and the following server response for a failed submission:<pre><code>
{
"success":false, // note this is Boolean, not string
"msg":"You do not have permission to perform this operation"
}
</code></pre>
* @return {BasicForm} this
*/
submit : function(options){
if(this.standardSubmit){
var v = this.isValid();
if(v){
var el = this.el.dom;
if(this.url && Ext.isEmpty(el.action)){
el.action = this.url;
}
el.submit();
}
return v;
}
var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
this.doAction(submitAction, options);
return this;
},
/**
* Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
* @param {Object} options The options to pass to the action (see {@link #doAction} for details)
* @return {BasicForm} this
*/
load : function(options){
var loadAction = String.format('{0}load', this.api ? 'direct' : '');
this.doAction(loadAction, options);
return this;
},
/**
* Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
* @param {Record} record The record to edit
* @return {BasicForm} this
*/
updateRecord : function(record){
record.beginEdit();
var fs = record.fields;
fs.each(function(f){
var field = this.findField(f.name);
if(field){
record.set(f.name, field.getValue());
}
}, this);
record.endEdit();
return this;
},
/**
* Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
* {@link Ext.data.Record#data record data}.
* See also {@link #trackResetOnLoad}.
* @param {Record} record The record to load
* @return {BasicForm} this
*/
loadRecord : function(record){
this.setValues(record.data);
return this;
},
// private
beforeAction : function(action){
var o = action.options;
if(o.waitMsg){
if(this.waitMsgTarget === true){
this.el.mask(o.waitMsg, 'x-mask-loading');
}else if(this.waitMsgTarget){
this.waitMsgTarget = Ext.get(this.waitMsgTarget);
this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
}else{
Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
}
}
},
// private
afterAction : function(action, success){
this.activeAction = null;
var o = action.options;
if(o.waitMsg){
if(this.waitMsgTarget === true){
this.el.unmask();
}else if(this.waitMsgTarget){
this.waitMsgTarget.unmask();
}else{
Ext.MessageBox.updateProgress(1);
Ext.MessageBox.hide();
}
}
if(success){
if(o.reset){
this.reset();
}
Ext.callback(o.success, o.scope, [this, action]);
this.fireEvent('actioncomplete', this, action);
}else{
Ext.callback(o.failure, o.scope, [this, action]);
this.fireEvent('actionfailed', this, action);
}
},
/**
* Find a {@link Ext.form.Field} in this form.
* @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
* {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
* @return Field
*/
findField : function(id){
var field = this.items.get(id);
if(!Ext.isObject(field)){
this.items.each(function(f){
if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
field = f;
return false;
}
});
}
return field || null;
},
/**
* Mark fields in this form invalid in bulk.
* @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
* @return {BasicForm} this
*/
markInvalid : function(errors){
if(Ext.isArray(errors)){
for(var i = 0, len = errors.length; i < len; i++){
var fieldError = errors[i];
var f = this.findField(fieldError.id);
if(f){
f.markInvalid(fieldError.msg);
}
}
}else{
var field, id;
for(id in errors){
if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
field.markInvalid(errors[id]);
}
}
}
return this;
},
/**
* Set values for fields in this form in bulk.
* @param {Array/Object} values Either an array in the form:<pre><code>
[{id:'clientName', value:'Fred. Olsen Lines'},
{id:'portOfLoading', value:'FXT'},
{id:'portOfDischarge', value:'OSL'} ]</code></pre>
* or an object hash of the form:<pre><code>
{
clientName: 'Fred. Olsen Lines',
portOfLoading: 'FXT',
portOfDischarge: 'OSL'
}</code></pre>
* @return {BasicForm} this
*/
setValues : function(values){
if(Ext.isArray(values)){ // array of objects
for(var i = 0, len = values.length; i < len; i++){
var v = values[i];
var f = this.findField(v.id);
if(f){
f.setValue(v.value);
if(this.trackResetOnLoad){
f.originalValue = f.getValue();
}
}
}
}else{ // object hash
var field, id;
for(id in values){
if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
field.setValue(values[id]);
if(this.trackResetOnLoad){
field.originalValue = field.getValue();
}
}
}
}
return this;
},
/**
* <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
* If multiple fields exist with the same name they are returned as an array.</p>
* <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
* the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
* value can potentially be the emptyText of a field.</p>
* @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
* @return {String/Object}
*/
getValues : function(asString){
var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
if(asString === true){
return fs;
}
return Ext.urlDecode(fs);
},
/**
* Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
* If multiple fields exist with the same name they are returned as an array.
* @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
* @return {Object} The values in the form
*/
getFieldValues : function(dirtyOnly){
var o = {},
n,
key,
val;
this.items.each(function(f){
if(dirtyOnly !== true || f.isDirty()){
n = f.getName();
key = o[n];
val = f.getValue();
if(Ext.isDefined(key)){
if(Ext.isArray(key)){
o[n].push(val);
}else{
o[n] = [key, val];
}
}else{
o[n] = val;
}
}
});
return o;
},
/**
* Clears all invalid messages in this form.
* @return {BasicForm} this
*/
clearInvalid : function(){
this.items.each(function(f){
f.clearInvalid();
});
return this;
},
/**
* Resets this form.
* @return {BasicForm} this
*/
reset : function(){
this.items.each(function(f){
f.reset();
});
return this;
},
/**
* Add Ext.form Components to this form's Collection. This does not result in rendering of
* the passed Component, it just enables the form to validate Fields, and distribute values to
* Fields.
* <p><b>You will not usually call this function. In order to be rendered, a Field must be added
* to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
* The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
* collection.</b></p>
* @param {Field} field1
* @param {Field} field2 (optional)
* @param {Field} etc (optional)
* @return {BasicForm} this
*/
add : function(){
this.items.addAll(Array.prototype.slice.call(arguments, 0));
return this;
},
/**
* Removes a field from the items collection (does NOT remove its markup).
* @param {Field} field
* @return {BasicForm} this
*/
remove : function(field){
this.items.remove(field);
return this;
},
/**
* Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
* checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
* @return {BasicForm} this
*/
render : function(){
this.items.each(function(f){
if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
f.applyToMarkup(f.id);
}
});
return this;
},
/**
* Calls {@link Ext#apply} for all fields in this form with the passed object.
* @param {Object} values
* @return {BasicForm} this
*/
applyToFields : function(o){
this.items.each(function(f){
Ext.apply(f, o);
});
return this;
},
/**
* Calls {@link Ext#applyIf} for all field in this form with the passed object.
* @param {Object} values
* @return {BasicForm} this
*/
applyIfToFields : function(o){
this.items.each(function(f){
Ext.applyIf(f, o);
});
return this;
},
callFieldMethod : function(fnName, args){
args = args || [];
this.items.each(function(f){
if(Ext.isFunction(f[fnName])){
f[fnName].apply(f, args);
}
});
return this;
}
});
// back compat
Ext.BasicForm = Ext.form.BasicForm;/**
* @class Ext.form.FormPanel
* @extends Ext.Panel
* <p>Standard form container.</p>
*
* <p><b><u>Layout</u></b></p>
* <p>By default, FormPanel is configured with <tt>layout:'form'</tt> to use an {@link Ext.layout.FormLayout}
* layout manager, which styles and renders fields and labels correctly. When nesting additional Containers
* within a FormPanel, you should ensure that any descendant Containers which host input Fields use the
* {@link Ext.layout.FormLayout} layout manager.</p>
*
* <p><b><u>BasicForm</u></b></p>
* <p>Although <b>not listed</b> as configuration options of FormPanel, the FormPanel class accepts all
* of the config options required to configure its internal {@link Ext.form.BasicForm} for:
* <div class="mdetail-params"><ul>
* <li>{@link Ext.form.BasicForm#fileUpload file uploads}</li>
* <li>functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form</li>
* </ul></div>
*
* <p><b>Note</b>: If subclassing FormPanel, any configuration options for the BasicForm must be applied to
* the <tt><b>initialConfig</b></tt> property of the FormPanel. Applying {@link Ext.form.BasicForm BasicForm}
* configuration settings to <b><tt>this</tt></b> will <b>not</b> affect the BasicForm's configuration.</p>
*
* <p><b><u>Form Validation</u></b></p>
* <p>For information on form validation see the following:</p>
* <div class="mdetail-params"><ul>
* <li>{@link Ext.form.TextField}</li>
* <li>{@link Ext.form.VTypes}</li>
* <li>{@link Ext.form.BasicForm#doAction BasicForm.doAction <b>clientValidation</b> notes}</li>
* <li><tt>{@link Ext.form.FormPanel#monitorValid monitorValid}</tt></li>
* </ul></div>
*
* <p><b><u>Form Submission</u></b></p>
* <p>By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}. To enable normal browser
* submission of the {@link Ext.form.BasicForm BasicForm} contained in this FormPanel, see the
* <tt><b>{@link Ext.form.BasicForm#standardSubmit standardSubmit}</b></tt> option.</p>
*
* @constructor
* @param {Object} config Configuration options
* @xtype form
*/
Ext.FormPanel = Ext.extend(Ext.Panel, {
/**
* @cfg {String} formId (optional) The id of the FORM tag (defaults to an auto-generated id).
*/
/**
* @cfg {Boolean} hideLabels
* <p><tt>true</tt> to hide field labels by default (sets <tt>display:none</tt>). Defaults to
* <tt>false</tt>.</p>
* <p>Also see {@link Ext.Component}.<tt>{@link Ext.Component#hideLabel hideLabel}</tt>.
*/
/**
* @cfg {Number} labelPad
* The default padding in pixels for field labels (defaults to <tt>5</tt>). <tt>labelPad</tt> only
* applies if <tt>{@link #labelWidth}</tt> is also specified, otherwise it will be ignored.
*/
/**
* @cfg {String} labelSeparator
* See {@link Ext.Component}.<tt>{@link Ext.Component#labelSeparator labelSeparator}</tt>
*/
/**
* @cfg {Number} labelWidth The width of labels in pixels. This property cascades to child containers
* and can be overridden on any child container (e.g., a fieldset can specify a different <tt>labelWidth</tt>
* for its fields) (defaults to <tt>100</tt>).
*/
/**
* @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
*/
/**
* @cfg {Array} buttons
* An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.<br>
* <p>Buttons in the footer of a FormPanel may be configured with the option <tt>formBind: true</tt>. This causes
* the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on
* the form's valid/invalid state.</p>
*/
/**
* @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to <tt>75</tt>).
*/
minButtonWidth : 75,
/**
* @cfg {String} labelAlign The label alignment value used for the <tt>text-align</tt> specification
* for the <b>container</b>. Valid values are <tt>"left</tt>", <tt>"top"</tt> or <tt>"right"</tt>
* (defaults to <tt>"left"</tt>). This property cascades to child <b>containers</b> and can be
* overridden on any child <b>container</b> (e.g., a fieldset can specify a different <tt>labelAlign</tt>
* for its fields).
*/
labelAlign : 'left',
/**
* @cfg {Boolean} monitorValid If <tt>true</tt>, the form monitors its valid state <b>client-side</b> and
* regularly fires the {@link #clientvalidation} event passing that state.<br>
* <p>When monitoring valid state, the FormPanel enables/disables any of its configured
* {@link #buttons} which have been configured with <code>formBind: true</code> depending
* on whether the {@link Ext.form.BasicForm#isValid form is valid} or not. Defaults to <tt>false</tt></p>
*/
monitorValid : false,
/**
* @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
*/
monitorPoll : 200,
/**
* @cfg {String} layout Defaults to <tt>'form'</tt>. Normally this configuration property should not be altered.
* For additional details see {@link Ext.layout.FormLayout} and {@link Ext.Container#layout Ext.Container.layout}.
*/
layout : 'form',
// private
initComponent : function(){
this.form = this.createForm();
Ext.FormPanel.superclass.initComponent.call(this);
this.bodyCfg = {
tag: 'form',
cls: this.baseCls + '-body',
method : this.method || 'POST',
id : this.formId || Ext.id()
};
if(this.fileUpload) {
this.bodyCfg.enctype = 'multipart/form-data';
}
this.initItems();
this.addEvents(
/**
* @event clientvalidation
* If the monitorValid config option is true, this event fires repetitively to notify of valid state
* @param {Ext.form.FormPanel} this
* @param {Boolean} valid true if the form has passed client-side validation
*/
'clientvalidation'
);
this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']);
},
// private
createForm : function(){
var config = Ext.applyIf({listeners: {}}, this.initialConfig);
return new Ext.form.BasicForm(null, config);
},
// private
initFields : function(){
var f = this.form;
var formPanel = this;
var fn = function(c){
if(formPanel.isField(c)){
f.add(c);
}else if(c.findBy && c != formPanel){
formPanel.applySettings(c);
//each check required for check/radio groups.
if(c.items && c.items.each){
c.items.each(fn, this);
}
}
};
this.items.each(fn, this);
},
// private
applySettings: function(c){
var ct = c.ownerCt;
Ext.applyIf(c, {
labelAlign: ct.labelAlign,
labelWidth: ct.labelWidth,
itemCls: ct.itemCls
});
},
// private
getLayoutTarget : function(){
return this.form.el;
},
/**
* Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains.
* @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains.
*/
getForm : function(){
return this.form;
},
// private
onRender : function(ct, position){
this.initFields();
Ext.FormPanel.superclass.onRender.call(this, ct, position);
this.form.initEl(this.body);
},
// private
beforeDestroy : function(){
this.stopMonitoring();
/*
* Don't move this behaviour to BasicForm because it can be used
* on it's own.
*/
Ext.destroy(this.form);
this.form.items.clear();
Ext.FormPanel.superclass.beforeDestroy.call(this);
},
// Determine if a Component is usable as a form Field.
isField : function(c) {
return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid;
},
// private
initEvents : function(){
Ext.FormPanel.superclass.initEvents.call(this);
// Listeners are required here to catch bubbling events from children.
this.on({
scope: this,
add: this.onAddEvent,
remove: this.onRemoveEvent
});
if(this.monitorValid){ // initialize after render
this.startMonitoring();
}
},
// private
onAdd: function(c){
Ext.FormPanel.superclass.onAdd.call(this, c);
this.processAdd(c);
},
// private
onAddEvent: function(ct, c){
if(ct !== this){
this.processAdd(c);
}
},
// private
processAdd : function(c){
// If a single form Field, add it
if(this.isField(c)){
this.form.add(c);
// If a Container, add any Fields it might contain
}else if(c.findBy){
this.applySettings(c);
this.form.add.apply(this.form, c.findBy(this.isField));
}
},
// private
onRemove: function(c){
Ext.FormPanel.superclass.onRemove.call(this, c);
this.processRemove(c);
},
onRemoveEvent: function(ct, c){
if(ct !== this){
this.processRemove(c);
}
},
// private
processRemove : function(c){
// If a single form Field, remove it
if(this.isField(c)){
this.form.remove(c);
// If a Container, its already destroyed by the time it gets here. Remove any references to destroyed fields.
}else if(c.findBy){
var isDestroyed = function(o) {
return !!o.isDestroyed;
}
this.form.items.filterBy(isDestroyed, this.form).each(this.form.remove, this.form);
}
},
/**
* Starts monitoring of the valid state of this form. Usually this is done by passing the config
* option "monitorValid"
*/
startMonitoring : function(){
if(!this.validTask){
this.validTask = new Ext.util.TaskRunner();
this.validTask.start({
run : this.bindHandler,
interval : this.monitorPoll || 200,
scope: this
});
}
},
/**
* Stops monitoring of the valid state of this form
*/
stopMonitoring : function(){
if(this.validTask){
this.validTask.stopAll();
this.validTask = null;
}
},
/**
* This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call.
* @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details)
*/
load : function(){
this.form.load.apply(this.form, arguments);
},
// private
onDisable : function(){
Ext.FormPanel.superclass.onDisable.call(this);
if(this.form){
this.form.items.each(function(){
this.disable();
});
}
},
// private
onEnable : function(){
Ext.FormPanel.superclass.onEnable.call(this);
if(this.form){
this.form.items.each(function(){
this.enable();
});
}
},
// private
bindHandler : function(){
var valid = true;
this.form.items.each(function(f){
if(!f.isValid(true)){
valid = false;
return false;
}
});
if(this.fbar){
var fitems = this.fbar.items.items;
for(var i = 0, len = fitems.length; i < len; i++){
var btn = fitems[i];
if(btn.formBind === true && btn.disabled === valid){
btn.setDisabled(!valid);
}
}
}
this.fireEvent('clientvalidation', this, valid);
}
});
Ext.reg('form', Ext.FormPanel);
Ext.form.FormPanel = Ext.FormPanel;
/**
* @class Ext.form.FieldSet
* @extends Ext.Panel
* Standard container used for grouping items within a {@link Ext.form.FormPanel form}.
* <pre><code>
var form = new Ext.FormPanel({
title: 'Simple Form with FieldSets',
labelWidth: 75, // label settings here cascade unless overridden
url: 'save-form.php',
frame:true,
bodyStyle:'padding:5px 5px 0',
width: 700,
renderTo: document.body,
layout:'column', // arrange items in columns
defaults: { // defaults applied to items
layout: 'form',
border: false,
bodyStyle: 'padding:4px'
},
items: [{
// Fieldset in Column 1
xtype:'fieldset',
columnWidth: 0.5,
title: 'Fieldset 1',
collapsible: true,
autoHeight:true,
defaults: {
anchor: '-20' // leave room for error icon
},
defaultType: 'textfield',
items :[{
fieldLabel: 'Field 1'
}, {
fieldLabel: 'Field 2'
}, {
fieldLabel: 'Field 3'
}
]
},{
// Fieldset in Column 2 - Panel inside
xtype:'fieldset',
title: 'Show Panel', // title, header, or checkboxToggle creates fieldset header
autoHeight:true,
columnWidth: 0.5,
checkboxToggle: true,
collapsed: true, // fieldset initially collapsed
layout:'anchor',
items :[{
xtype: 'panel',
anchor: '100%',
title: 'Panel inside a fieldset',
frame: true,
height: 100
}]
}]
});
* </code></pre>
* @constructor
* @param {Object} config Configuration options
* @xtype fieldset
*/
Ext.form.FieldSet = Ext.extend(Ext.Panel, {
/**
* @cfg {Mixed} checkboxToggle <tt>true</tt> to render a checkbox into the fieldset frame just
* in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults
* to <tt>false</tt>).
* <p>A {@link Ext.DomHelper DomHelper} element spec may also be specified to create the checkbox.
* If <tt>true</tt> is specified, the default DomHelper config object used to create the element
* is:</p><pre><code>
* {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}
* </code></pre>
*/
/**
* @cfg {String} checkboxName The name to assign to the fieldset's checkbox if <tt>{@link #checkboxToggle} = true</tt>
* (defaults to <tt>'[checkbox id]-checkbox'</tt>).
*/
/**
* @cfg {Boolean} collapsible
* <tt>true</tt> to make the fieldset collapsible and have the expand/collapse toggle button automatically
* rendered into the legend element, <tt>false</tt> to keep the fieldset statically sized with no collapse
* button (defaults to <tt>false</tt>). Another option is to configure <tt>{@link #checkboxToggle}</tt>.
*/
/**
* @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
*/
/**
* @cfg {String} itemCls A css class to apply to the <tt>x-form-item</tt> of fields (see
* {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} for details).
* This property cascades to child containers.
*/
/**
* @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to <tt>'x-fieldset'</tt>).
*/
baseCls : 'x-fieldset',
/**
* @cfg {String} layout The {@link Ext.Container#layout} to use inside the fieldset (defaults to <tt>'form'</tt>).
*/
layout : 'form',
/**
* @cfg {Boolean} animCollapse
* <tt>true</tt> to animate the transition when the panel is collapsed, <tt>false</tt> to skip the
* animation (defaults to <tt>false</tt>).
*/
animCollapse : false,
// private
onRender : function(ct, position){
if(!this.el){
this.el = document.createElement('fieldset');
this.el.id = this.id;
if (this.title || this.header || this.checkboxToggle) {
this.el.appendChild(document.createElement('legend')).className = this.baseCls + '-header';
}
}
Ext.form.FieldSet.superclass.onRender.call(this, ct, position);
if(this.checkboxToggle){
var o = typeof this.checkboxToggle == 'object' ?
this.checkboxToggle :
{tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
this.checkbox = this.header.insertFirst(o);
this.checkbox.dom.checked = !this.collapsed;
this.mon(this.checkbox, 'click', this.onCheckClick, this);
}
},
// private
onCollapse : function(doAnim, animArg){
if(this.checkbox){
this.checkbox.dom.checked = false;
}
Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg);
},
// private
onExpand : function(doAnim, animArg){
if(this.checkbox){
this.checkbox.dom.checked = true;
}
Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg);
},
/**
* This function is called by the fieldset's checkbox when it is toggled (only applies when
* checkboxToggle = true). This method should never be called externally, but can be
* overridden to provide custom behavior when the checkbox is toggled if needed.
*/
onCheckClick : function(){
this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
}
/**
* @cfg {String/Number} activeItem
* @hide
*/
/**
* @cfg {Mixed} applyTo
* @hide
*/
/**
* @cfg {Boolean} bodyBorder
* @hide
*/
/**
* @cfg {Boolean} border
* @hide
*/
/**
* @cfg {Boolean/Number} bufferResize
* @hide
*/
/**
* @cfg {Boolean} collapseFirst
* @hide
*/
/**
* @cfg {String} defaultType
* @hide
*/
/**
* @cfg {String} disabledClass
* @hide
*/
/**
* @cfg {String} elements
* @hide
*/
/**
* @cfg {Boolean} floating
* @hide
*/
/**
* @cfg {Boolean} footer
* @hide
*/
/**
* @cfg {Boolean} frame
* @hide
*/
/**
* @cfg {Boolean} header
* @hide
*/
/**
* @cfg {Boolean} headerAsText
* @hide
*/
/**
* @cfg {Boolean} hideCollapseTool
* @hide
*/
/**
* @cfg {String} iconCls
* @hide
*/
/**
* @cfg {Boolean/String} shadow
* @hide
*/
/**
* @cfg {Number} shadowOffset
* @hide
*/
/**
* @cfg {Boolean} shim
* @hide
*/
/**
* @cfg {Object/Array} tbar
* @hide
*/
/**
* @cfg {Array} tools
* @hide
*/
/**
* @cfg {Ext.Template/Ext.XTemplate} toolTemplate
* @hide
*/
/**
* @cfg {String} xtype
* @hide
*/
/**
* @property header
* @hide
*/
/**
* @property footer
* @hide
*/
/**
* @method focus
* @hide
*/
/**
* @method getBottomToolbar
* @hide
*/
/**
* @method getTopToolbar
* @hide
*/
/**
* @method setIconClass
* @hide
*/
/**
* @event activate
* @hide
*/
/**
* @event beforeclose
* @hide
*/
/**
* @event bodyresize
* @hide
*/
/**
* @event close
* @hide
*/
/**
* @event deactivate
* @hide
*/
});
Ext.reg('fieldset', Ext.form.FieldSet);
/**
* @class Ext.form.HtmlEditor
* @extends Ext.form.Field
* Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
* automatically hidden when needed. These are noted in the config options where appropriate.
* <br><br>The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
* enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}.
* <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
* supported by this editor.</b>
* <br><br>An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
* any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
* <br><br>Example usage:
* <pre><code>
// Simple example rendered with default options:
Ext.QuickTips.init(); // enable tooltips
new Ext.form.HtmlEditor({
renderTo: Ext.getBody(),
width: 800,
height: 300
});
// Passed via xtype into a container and with custom options:
Ext.QuickTips.init(); // enable tooltips
new Ext.Panel({
title: 'HTML Editor',
renderTo: Ext.getBody(),
width: 600,
height: 300,
frame: true,
layout: 'fit',
items: {
xtype: 'htmleditor',
enableColors: false,
enableAlignments: false
}
});
</code></pre>
* @constructor
* Create a new HtmlEditor
* @param {Object} config
* @xtype htmleditor
*/
Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, {
/**
* @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true)
*/
enableFormat : true,
/**
* @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true)
*/
enableFontSize : true,
/**
* @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true)
*/
enableColors : true,
/**
* @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true)
*/
enableAlignments : true,
/**
* @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
*/
enableLists : true,
/**
* @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true)
*/
enableSourceEdit : true,
/**
* @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true)
*/
enableLinks : true,
/**
* @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true)
*/
enableFont : true,
/**
* @cfg {String} createLinkText The default text for the create link prompt
*/
createLinkText : 'Please enter the URL for the link:',
/**
* @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
*/
defaultLinkValue : 'http:/'+'/',
/**
* @cfg {Array} fontFamilies An array of available font families
*/
fontFamilies : [
'Arial',
'Courier New',
'Tahoma',
'Times New Roman',
'Verdana'
],
defaultFont: 'tahoma',
/**
* @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to   (Non-breaking space) in Opera and IE6, ​ (Zero-width space) in all other browsers).
*/
defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​',
// private properties
actionMode: 'wrap',
validationEvent : false,
deferHeight: true,
initialized : false,
activated : false,
sourceEditMode : false,
onFocus : Ext.emptyFn,
iframePad:3,
hideMode:'offsets',
defaultAutoCreate : {
tag: "textarea",
style:"width:500px;height:300px;",
autocomplete: "off"
},
// private
initComponent : function(){
this.addEvents(
/**
* @event initialize
* Fires when the editor is fully initialized (including the iframe)
* @param {HtmlEditor} this
*/
'initialize',
/**
* @event activate
* Fires when the editor is first receives the focus. Any insertion must wait
* until after this event.
* @param {HtmlEditor} this
*/
'activate',
/**
* @event beforesync
* Fires before the textarea is updated with content from the editor iframe. Return false
* to cancel the sync.
* @param {HtmlEditor} this
* @param {String} html
*/
'beforesync',
/**
* @event beforepush
* Fires before the iframe editor is updated with content from the textarea. Return false
* to cancel the push.
* @param {HtmlEditor} this
* @param {String} html
*/
'beforepush',
/**
* @event sync
* Fires when the textarea is updated with content from the editor iframe.
* @param {HtmlEditor} this
* @param {String} html
*/
'sync',
/**
* @event push
* Fires when the iframe editor is updated with content from the textarea.
* @param {HtmlEditor} this
* @param {String} html
*/
'push',
/**
* @event editmodechange
* Fires when the editor switches edit modes
* @param {HtmlEditor} this
* @param {Boolean} sourceEdit True if source edit, false if standard editing.
*/
'editmodechange'
)
},
// private
createFontOptions : function(){
var buf = [], fs = this.fontFamilies, ff, lc;
for(var i = 0, len = fs.length; i< len; i++){
ff = fs[i];
lc = ff.toLowerCase();
buf.push(
'<option value="',lc,'" style="font-family:',ff,';"',
(this.defaultFont == lc ? ' selected="true">' : '>'),
ff,
'</option>'
);
}
return buf.join('');
},
/*
* Protected method that will not generally be called directly. It
* is called when the editor creates its toolbar. Override this method if you need to
* add custom toolbar buttons.
* @param {HtmlEditor} editor
*/
createToolbar : function(editor){
var items = [];
var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
function btn(id, toggle, handler){
return {
itemId : id,
cls : 'x-btn-icon',
iconCls: 'x-edit-'+id,
enableToggle:toggle !== false,
scope: editor,
handler:handler||editor.relayBtnCmd,
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
overflowText: editor.buttonTips[id].title || undefined,
tabIndex:-1
};
}
if(this.enableFont && !Ext.isSafari2){
var fontSelectItem = new Ext.Toolbar.Item({
autoEl: {
tag:'select',
cls:'x-font-select',
html: this.createFontOptions()
}
});
items.push(
fontSelectItem,
'-'
);
}
if(this.enableFormat){
items.push(
btn('bold'),
btn('italic'),
btn('underline')
);
}
if(this.enableFontSize){
items.push(
'-',
btn('increasefontsize', false, this.adjustFont),
btn('decreasefontsize', false, this.adjustFont)
);
}
if(this.enableColors){
items.push(
'-', {
itemId:'forecolor',
cls:'x-btn-icon',
iconCls: 'x-edit-forecolor',
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined,
tabIndex:-1,
menu : new Ext.menu.ColorMenu({
allowReselect: true,
focus: Ext.emptyFn,
value:'000000',
plain:true,
listeners: {
scope: this,
select: function(cp, color){
this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
this.deferFocus();
}
},
clickEvent:'mousedown'
})
}, {
itemId:'backcolor',
cls:'x-btn-icon',
iconCls: 'x-edit-backcolor',
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined,
tabIndex:-1,
menu : new Ext.menu.ColorMenu({
focus: Ext.emptyFn,
value:'FFFFFF',
plain:true,
allowReselect: true,
listeners: {
scope: this,
select: function(cp, color){
if(Ext.isGecko){
this.execCmd('useCSS', false);
this.execCmd('hilitecolor', color);
this.execCmd('useCSS', true);
this.deferFocus();
}else{
this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
this.deferFocus();
}
}
},
clickEvent:'mousedown'
})
}
);
}
if(this.enableAlignments){
items.push(
'-',
btn('justifyleft'),
btn('justifycenter'),
btn('justifyright')
);
}
if(!Ext.isSafari2){
if(this.enableLinks){
items.push(
'-',
btn('createlink', false, this.createLink)
);
}
if(this.enableLists){
items.push(
'-',
btn('insertorderedlist'),
btn('insertunorderedlist')
);
}
if(this.enableSourceEdit){
items.push(
'-',
btn('sourceedit', true, function(btn){
this.toggleSourceEdit(!this.sourceEditMode);
})
);
}
}
// build the toolbar
var tb = new Ext.Toolbar({
renderTo: this.wrap.dom.firstChild,
items: items
});
if (fontSelectItem) {
this.fontSelect = fontSelectItem.el;
this.mon(this.fontSelect, 'change', function(){
var font = this.fontSelect.dom.value;
this.relayCmd('fontname', font);
this.deferFocus();
}, this);
}
// stop form submits
this.mon(tb.el, 'click', function(e){
e.preventDefault();
});
this.tb = tb;
},
onDisable: function(){
this.wrap.mask();
Ext.form.HtmlEditor.superclass.onDisable.call(this);
},
onEnable: function(){
this.wrap.unmask();
Ext.form.HtmlEditor.superclass.onEnable.call(this);
},
setReadOnly: function(readOnly){
Ext.form.HtmlEditor.superclass.setReadOnly.call(this, readOnly);
if(this.initialized){
this.setDesignMode(!readOnly);
var bd = this.getEditorBody();
if(bd){
bd.style.cursor = this.readOnly ? 'default' : 'text';
}
this.disableItems(readOnly);
}
},
/**
* Protected method that will not generally be called directly. It
* is called when the editor initializes the iframe with HTML contents. Override this method if you
* want to change the initialization markup of the iframe (e.g. to add stylesheets).
*
* Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility
*/
getDocMarkup : function(){
return '<html><head><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>';
},
// private
getEditorBody : function(){
var doc = this.getDoc();
return doc.body || doc.documentElement;
},
// private
getDoc : function(){
return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document);
},
// private
getWin : function(){
return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name];
},
// private
onRender : function(ct, position){
Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position);
this.el.dom.style.border = '0 none';
this.el.dom.setAttribute('tabIndex', -1);
this.el.addClass('x-hidden');
if(Ext.isIE){ // fix IE 1px bogus margin
this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
}
this.wrap = this.el.wrap({
cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
});
this.createToolbar(this);
this.disableItems(true);
this.tb.doLayout();
this.createIFrame();
if(!this.width){
var sz = this.el.getSize();
this.setSize(sz.width, this.height || sz.height);
}
this.resizeEl = this.positionEl = this.wrap;
},
createIFrame: function(){
var iframe = document.createElement('iframe');
iframe.name = Ext.id();
iframe.frameBorder = '0';
iframe.style.overflow = 'auto';
this.wrap.dom.appendChild(iframe);
this.iframe = iframe;
this.monitorTask = Ext.TaskMgr.start({
run: this.checkDesignMode,
scope: this,
interval:100
});
},
initFrame : function(){
Ext.TaskMgr.stop(this.monitorTask);
var doc = this.getDoc();
this.win = this.getWin();
doc.open();
doc.write(this.getDocMarkup());
doc.close();
var task = { // must defer to wait for browser to be ready
run : function(){
var doc = this.getDoc();
if(doc.body || doc.readyState == 'complete'){
Ext.TaskMgr.stop(task);
this.setDesignMode(true);
this.initEditor.defer(10, this);
}
},
interval : 10,
duration:10000,
scope: this
};
Ext.TaskMgr.start(task);
},
checkDesignMode : function(){
if(this.wrap && this.wrap.dom.offsetWidth){
var doc = this.getDoc();
if(!doc){
return;
}
if(!doc.editorInitialized || this.getDesignMode() != 'on'){
this.initFrame();
}
}
},
/* private
* set current design mode. To enable, mode can be true or 'on', off otherwise
*/
setDesignMode : function(mode){
var doc ;
if(doc = this.getDoc()){
if(this.readOnly){
mode = false;
}
doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off';
}
},
// private
getDesignMode : function(){
var doc = this.getDoc();
if(!doc){ return ''; }
return String(doc.designMode).toLowerCase();
},
disableItems: function(disabled){
if(this.fontSelect){
this.fontSelect.dom.disabled = disabled;
}
this.tb.items.each(function(item){
if(item.getItemId() != 'sourceedit'){
item.setDisabled(disabled);
}
});
},
// private
onResize : function(w, h){
Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments);
if(this.el && this.iframe){
if(Ext.isNumber(w)){
var aw = w - this.wrap.getFrameWidth('lr');
this.el.setWidth(aw);
this.tb.setWidth(aw);
this.iframe.style.width = Math.max(aw, 0) + 'px';
}
if(Ext.isNumber(h)){
var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight();
this.el.setHeight(ah);
this.iframe.style.height = Math.max(ah, 0) + 'px';
var bd = this.getEditorBody();
if(bd){
bd.style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px';
}
}
}
},
/**
* Toggles the editor between standard and source edit mode.
* @param {Boolean} sourceEdit (optional) True for source edit, false for standard
*/
toggleSourceEdit : function(sourceEditMode){
if(sourceEditMode === undefined){
sourceEditMode = !this.sourceEditMode;
}
this.sourceEditMode = sourceEditMode === true;
var btn = this.tb.getComponent('sourceedit');
if(btn.pressed !== this.sourceEditMode){
btn.toggle(this.sourceEditMode);
if(!btn.xtbHidden){
return;
}
}
if(this.sourceEditMode){
this.disableItems(true);
this.syncValue();
this.iframe.className = 'x-hidden';
this.el.removeClass('x-hidden');
this.el.dom.removeAttribute('tabIndex');
this.el.focus();
}else{
if(this.initialized){
this.disableItems(this.readOnly);
}
this.pushValue();
this.iframe.className = '';
this.el.addClass('x-hidden');
this.el.dom.setAttribute('tabIndex', -1);
this.deferFocus();
}
var lastSize = this.lastSize;
if(lastSize){
delete this.lastSize;
this.setSize(lastSize);
}
this.fireEvent('editmodechange', this, this.sourceEditMode);
},
// private used internally
createLink : function(){
var url = prompt(this.createLinkText, this.defaultLinkValue);
if(url && url != 'http:/'+'/'){
this.relayCmd('createlink', url);
}
},
// private
initEvents : function(){
this.originalValue = this.getValue();
},
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
markInvalid : Ext.emptyFn,
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
clearInvalid : Ext.emptyFn,
// docs inherit from Field
setValue : function(v){
Ext.form.HtmlEditor.superclass.setValue.call(this, v);
this.pushValue();
return this;
},
/**
* Protected method that will not generally be called directly. If you need/want
* custom HTML cleanup, this is the method you should override.
* @param {String} html The HTML to be cleaned
* @return {String} The cleaned HTML
*/
cleanHtml: function(html) {
html = String(html);
if(Ext.isWebKit){ // strip safari nonsense
html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
}
/*
* Neat little hack. Strips out all the non-digit characters from the default
* value and compares it to the character code of the first character in the string
* because it can cause encoding issues when posted to the server.
*/
if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){
html = html.substring(1);
}
return html;
},
/**
* Protected method that will not generally be called directly. Syncs the contents
* of the editor iframe with the textarea.
*/
syncValue : function(){
if(this.initialized){
var bd = this.getEditorBody();
var html = bd.innerHTML;
if(Ext.isWebKit){
var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
var m = bs.match(/text-align:(.*?);/i);
if(m && m[1]){
html = '<div style="'+m[0]+'">' + html + '</div>';
}
}
html = this.cleanHtml(html);
if(this.fireEvent('beforesync', this, html) !== false){
this.el.dom.value = html;
this.fireEvent('sync', this, html);
}
}
},
//docs inherit from Field
getValue : function() {
this[this.sourceEditMode ? 'pushValue' : 'syncValue']();
return Ext.form.HtmlEditor.superclass.getValue.call(this);
},
/**
* Protected method that will not generally be called directly. Pushes the value of the textarea
* into the iframe editor.
*/
pushValue : function(){
if(this.initialized){
var v = this.el.dom.value;
if(!this.activated && v.length < 1){
v = this.defaultValue;
}
if(this.fireEvent('beforepush', this, v) !== false){
this.getEditorBody().innerHTML = v;
if(Ext.isGecko){
// Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8
this.setDesignMode(false); //toggle off first
}
this.setDesignMode(true);
this.fireEvent('push', this, v);
}
}
},
// private
deferFocus : function(){
this.focus.defer(10, this);
},
// docs inherit from Field
focus : function(){
if(this.win && !this.sourceEditMode){
this.win.focus();
}else{
this.el.focus();
}
},
// private
initEditor : function(){
//Destroying the component during/before initEditor can cause issues.
try{
var dbody = this.getEditorBody(),
ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'),
doc,
fn;
ss['background-attachment'] = 'fixed'; // w3c
dbody.bgProperties = 'fixed'; // ie
Ext.DomHelper.applyStyles(dbody, ss);
doc = this.getDoc();
if(doc){
try{
Ext.EventManager.removeAll(doc);
}catch(e){}
}
/*
* We need to use createDelegate here, because when using buffer, the delayed task is added
* as a property to the function. When the listener is removed, the task is deleted from the function.
* Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors
* is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function.
*/
fn = this.onEditorEvent.createDelegate(this);
Ext.EventManager.on(doc, {
mousedown: fn,
dblclick: fn,
click: fn,
keyup: fn,
buffer:100
});
if(Ext.isGecko){
Ext.EventManager.on(doc, 'keypress', this.applyCommand, this);
}
if(Ext.isIE || Ext.isWebKit || Ext.isOpera){
Ext.EventManager.on(doc, 'keydown', this.fixKeys, this);
}
doc.editorInitialized = true;
this.initialized = true;
this.pushValue();
this.setReadOnly(this.readOnly);
this.fireEvent('initialize', this);
}catch(e){}
},
// private
onDestroy : function(){
if(this.monitorTask){
Ext.TaskMgr.stop(this.monitorTask);
}
if(this.rendered){
Ext.destroy(this.tb);
var doc = this.getDoc();
if(doc){
try{
Ext.EventManager.removeAll(doc);
for (var prop in doc){
delete doc[prop];
}
}catch(e){}
}
if(this.wrap){
this.wrap.dom.innerHTML = '';
this.wrap.remove();
}
}
if(this.el){
this.el.removeAllListeners();
this.el.remove();
}
this.purgeListeners();
},
// private
onFirstFocus : function(){
this.activated = true;
this.disableItems(this.readOnly);
if(Ext.isGecko){ // prevent silly gecko errors
this.win.focus();
var s = this.win.getSelection();
if(!s.focusNode || s.focusNode.nodeType != 3){
var r = s.getRangeAt(0);
r.selectNodeContents(this.getEditorBody());
r.collapse(true);
this.deferFocus();
}
try{
this.execCmd('useCSS', true);
this.execCmd('styleWithCSS', false);
}catch(e){}
}
this.fireEvent('activate', this);
},
// private
adjustFont: function(btn){
var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1,
doc = this.getDoc(),
v = parseInt(doc.queryCommandValue('FontSize') || 2, 10);
if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){
// Safari 3 values
// 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
if(v <= 10){
v = 1 + adjust;
}else if(v <= 13){
v = 2 + adjust;
}else if(v <= 16){
v = 3 + adjust;
}else if(v <= 18){
v = 4 + adjust;
}else if(v <= 24){
v = 5 + adjust;
}else {
v = 6 + adjust;
}
v = v.constrain(1, 6);
}else{
if(Ext.isSafari){ // safari
adjust *= 2;
}
v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0);
}
this.execCmd('FontSize', v);
},
// private
onEditorEvent : function(e){
this.updateToolbar();
},
/**
* Protected method that will not generally be called directly. It triggers
* a toolbar update by reading the markup state of the current selection in the editor.
*/
updateToolbar: function(){
if(this.readOnly){
return;
}
if(!this.activated){
this.onFirstFocus();
return;
}
var btns = this.tb.items.map,
doc = this.getDoc();
if(this.enableFont && !Ext.isSafari2){
var name = (doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase();
if(name != this.fontSelect.dom.value){
this.fontSelect.dom.value = name;
}
}
if(this.enableFormat){
btns.bold.toggle(doc.queryCommandState('bold'));
btns.italic.toggle(doc.queryCommandState('italic'));
btns.underline.toggle(doc.queryCommandState('underline'));
}
if(this.enableAlignments){
btns.justifyleft.toggle(doc.queryCommandState('justifyleft'));
btns.justifycenter.toggle(doc.queryCommandState('justifycenter'));
btns.justifyright.toggle(doc.queryCommandState('justifyright'));
}
if(!Ext.isSafari2 && this.enableLists){
btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist'));
btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist'));
}
Ext.menu.MenuMgr.hideAll();
this.syncValue();
},
// private
relayBtnCmd : function(btn){
this.relayCmd(btn.getItemId());
},
/**
* Executes a Midas editor command on the editor document and performs necessary focus and
* toolbar updates. <b>This should only be called after the editor is initialized.</b>
* @param {String} cmd The Midas command
* @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
*/
relayCmd : function(cmd, value){
(function(){
this.focus();
this.execCmd(cmd, value);
this.updateToolbar();
}).defer(10, this);
},
/**
* Executes a Midas editor command directly on the editor document.
* For visual commands, you should use {@link #relayCmd} instead.
* <b>This should only be called after the editor is initialized.</b>
* @param {String} cmd The Midas command
* @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
*/
execCmd : function(cmd, value){
var doc = this.getDoc();
doc.execCommand(cmd, false, value === undefined ? null : value);
this.syncValue();
},
// private
applyCommand : function(e){
if(e.ctrlKey){
var c = e.getCharCode(), cmd;
if(c > 0){
c = String.fromCharCode(c);
switch(c){
case 'b':
cmd = 'bold';
break;
case 'i':
cmd = 'italic';
break;
case 'u':
cmd = 'underline';
break;
}
if(cmd){
this.win.focus();
this.execCmd(cmd);
this.deferFocus();
e.preventDefault();
}
}
}
},
/**
* Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
* to insert text.
* @param {String} text
*/
insertAtCursor : function(text){
if(!this.activated){
return;
}
if(Ext.isIE){
this.win.focus();
var doc = this.getDoc(),
r = doc.selection.createRange();
if(r){
r.pasteHTML(text);
this.syncValue();
this.deferFocus();
}
}else{
this.win.focus();
this.execCmd('InsertHTML', text);
this.deferFocus();
}
},
// private
fixKeys : function(){ // load time branching for fastest keydown performance
if(Ext.isIE){
return function(e){
var k = e.getKey(),
doc = this.getDoc(),
r;
if(k == e.TAB){
e.stopEvent();
r = doc.selection.createRange();
if(r){
r.collapse(true);
r.pasteHTML(' ');
this.deferFocus();
}
}else if(k == e.ENTER){
r = doc.selection.createRange();
if(r){
var target = r.parentElement();
if(!target || target.tagName.toLowerCase() != 'li'){
e.stopEvent();
r.pasteHTML('<br />');
r.collapse(false);
r.select();
}
}
}
};
}else if(Ext.isOpera){
return function(e){
var k = e.getKey();
if(k == e.TAB){
e.stopEvent();
this.win.focus();
this.execCmd('InsertHTML',' ');
this.deferFocus();
}
};
}else if(Ext.isWebKit){
return function(e){
var k = e.getKey();
if(k == e.TAB){
e.stopEvent();
this.execCmd('InsertText','\t');
this.deferFocus();
}else if(k == e.ENTER){
e.stopEvent();
this.execCmd('InsertHtml','<br /><br />');
this.deferFocus();
}
};
}
}(),
/**
* Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
* @return {Ext.Toolbar}
*/
getToolbar : function(){
return this.tb;
},
/**
* Object collection of toolbar tooltips for the buttons in the editor. The key
* is the command id associated with that button and the value is a valid QuickTips object.
* For example:
<pre><code>
{
bold : {
title: 'Bold (Ctrl+B)',
text: 'Make the selected text bold.',
cls: 'x-html-editor-tip'
},
italic : {
title: 'Italic (Ctrl+I)',
text: 'Make the selected text italic.',
cls: 'x-html-editor-tip'
},
...
</code></pre>
* @type Object
*/
buttonTips : {
bold : {
title: 'Bold (Ctrl+B)',
text: 'Make the selected text bold.',
cls: 'x-html-editor-tip'
},
italic : {
title: 'Italic (Ctrl+I)',
text: 'Make the selected text italic.',
cls: 'x-html-editor-tip'
},
underline : {
title: 'Underline (Ctrl+U)',
text: 'Underline the selected text.',
cls: 'x-html-editor-tip'
},
increasefontsize : {
title: 'Grow Text',
text: 'Increase the font size.',
cls: 'x-html-editor-tip'
},
decreasefontsize : {
title: 'Shrink Text',
text: 'Decrease the font size.',
cls: 'x-html-editor-tip'
},
backcolor : {
title: 'Text Highlight Color',
text: 'Change the background color of the selected text.',
cls: 'x-html-editor-tip'
},
forecolor : {
title: 'Font Color',
text: 'Change the color of the selected text.',
cls: 'x-html-editor-tip'
},
justifyleft : {
title: 'Align Text Left',
text: 'Align text to the left.',
cls: 'x-html-editor-tip'
},
justifycenter : {
title: 'Center Text',
text: 'Center text in the editor.',
cls: 'x-html-editor-tip'
},
justifyright : {
title: 'Align Text Right',
text: 'Align text to the right.',
cls: 'x-html-editor-tip'
},
insertunorderedlist : {
title: 'Bullet List',
text: 'Start a bulleted list.',
cls: 'x-html-editor-tip'
},
insertorderedlist : {
title: 'Numbered List',
text: 'Start a numbered list.',
cls: 'x-html-editor-tip'
},
createlink : {
title: 'Hyperlink',
text: 'Make the selected text a hyperlink.',
cls: 'x-html-editor-tip'
},
sourceedit : {
title: 'Source Edit',
text: 'Switch to source editing mode.',
cls: 'x-html-editor-tip'
}
}
// hide stuff that is not compatible
/**
* @event blur
* @hide
*/
/**
* @event change
* @hide
*/
/**
* @event focus
* @hide
*/
/**
* @event specialkey
* @hide
*/
/**
* @cfg {String} fieldClass @hide
*/
/**
* @cfg {String} focusClass @hide
*/
/**
* @cfg {String} autoCreate @hide
*/
/**
* @cfg {String} inputType @hide
*/
/**
* @cfg {String} invalidClass @hide
*/
/**
* @cfg {String} invalidText @hide
*/
/**
* @cfg {String} msgFx @hide
*/
/**
* @cfg {String} validateOnBlur @hide
*/
/**
* @cfg {Boolean} allowDomMove @hide
*/
/**
* @cfg {String} applyTo @hide
*/
/**
* @cfg {String} autoHeight @hide
*/
/**
* @cfg {String} autoWidth @hide
*/
/**
* @cfg {String} cls @hide
*/
/**
* @cfg {String} disabled @hide
*/
/**
* @cfg {String} disabledClass @hide
*/
/**
* @cfg {String} msgTarget @hide
*/
/**
* @cfg {String} readOnly @hide
*/
/**
* @cfg {String} style @hide
*/
/**
* @cfg {String} validationDelay @hide
*/
/**
* @cfg {String} validationEvent @hide
*/
/**
* @cfg {String} tabIndex @hide
*/
/**
* @property disabled
* @hide
*/
/**
* @method applyToMarkup
* @hide
*/
/**
* @method disable
* @hide
*/
/**
* @method enable
* @hide
*/
/**
* @method validate
* @hide
*/
/**
* @event valid
* @hide
*/
/**
* @method setDisabled
* @hide
*/
/**
* @cfg keys
* @hide
*/
});
Ext.reg('htmleditor', Ext.form.HtmlEditor);/**
* @class Ext.form.TimeField
* @extends Ext.form.ComboBox
* Provides a time input field with a time dropdown and automatic time validation. Example usage:
* <pre><code>
new Ext.form.TimeField({
minValue: '9:00 AM',
maxValue: '6:00 PM',
increment: 30
});
</code></pre>
* @constructor
* Create a new TimeField
* @param {Object} config
* @xtype timefield
*/
Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, {
/**
* @cfg {Date/String} minValue
* The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
* time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
*/
minValue : undefined,
/**
* @cfg {Date/String} maxValue
* The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
* time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
*/
maxValue : undefined,
/**
* @cfg {String} minText
* The error text to display when the date in the cell is before minValue (defaults to
* 'The time in this field must be equal to or after {0}').
*/
minText : "The time in this field must be equal to or after {0}",
/**
* @cfg {String} maxText
* The error text to display when the time is after maxValue (defaults to
* 'The time in this field must be equal to or before {0}').
*/
maxText : "The time in this field must be equal to or before {0}",
/**
* @cfg {String} invalidText
* The error text to display when the time in the field is invalid (defaults to
* '{value} is not a valid time').
*/
invalidText : "{0} is not a valid time",
/**
* @cfg {String} format
* The default time format string which can be overriden for localization support. The format must be
* valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time
* format try 'H:i' instead.
*/
format : "g:i A",
/**
* @cfg {String} altFormats
* Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
* format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H').
*/
altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H",
/**
* @cfg {Number} increment
* The number of minutes between each time value in the list (defaults to 15).
*/
increment: 15,
// private override
mode: 'local',
// private override
triggerAction: 'all',
// private override
typeAhead: false,
// private - This is the date to use when generating time values in the absence of either minValue
// or maxValue. Using the current date causes DST issues on DST boundary dates, so this is an
// arbitrary "safe" date that can be any date aside from DST boundary dates.
initDate: '1/1/2008',
// private
initComponent : function(){
if(Ext.isDefined(this.minValue)){
this.setMinValue(this.minValue, true);
}
if(Ext.isDefined(this.maxValue)){
this.setMaxValue(this.maxValue, true);
}
if(!this.store){
this.generateStore(true);
}
Ext.form.TimeField.superclass.initComponent.call(this);
},
/**
* Replaces any existing {@link #minValue} with the new time and refreshes the store.
* @param {Date/String} value The minimum time that can be selected
*/
setMinValue: function(value, /* private */ initial){
this.setLimit(value, true, initial);
return this;
},
/**
* Replaces any existing {@link #maxValue} with the new time and refreshes the store.
* @param {Date/String} value The maximum time that can be selected
*/
setMaxValue: function(value, /* private */ initial){
this.setLimit(value, false, initial);
return this;
},
// private
generateStore: function(initial){
var min = this.minValue || new Date(this.initDate).clearTime(),
max = this.maxValue || new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1),
times = [];
while(min <= max){
times.push(min.dateFormat(this.format));
min = min.add('mi', this.increment);
}
this.bindStore(times, initial);
},
// private
setLimit: function(value, isMin, initial){
var d;
if(Ext.isString(value)){
d = this.parseDate(value);
}else if(Ext.isDate(value)){
d = value;
}
if(d){
var val = new Date(this.initDate).clearTime();
val.setHours(d.getHours(), d.getMinutes(), isMin ? 0 : 59, 0);
this[isMin ? 'minValue' : 'maxValue'] = val;
if(!initial){
this.generateStore();
}
}
},
// inherited docs
getValue : function(){
var v = Ext.form.TimeField.superclass.getValue.call(this);
return this.formatDate(this.parseDate(v)) || '';
},
// inherited docs
setValue : function(value){
return Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value)));
},
// private overrides
validateValue : Ext.form.DateField.prototype.validateValue,
parseDate : Ext.form.DateField.prototype.parseDate,
formatDate : Ext.form.DateField.prototype.formatDate,
// private
beforeBlur : function(){
var v = this.parseDate(this.getRawValue());
if(v){
this.setValue(v.dateFormat(this.format));
}
Ext.form.TimeField.superclass.beforeBlur.call(this);
}
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
/**
* @hide
* @method autoSize
*/
});
Ext.reg('timefield', Ext.form.TimeField);/**
* @class Ext.form.Label
* @extends Ext.BoxComponent
* Basic Label field.
* @constructor
* Creates a new Label
* @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
* element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
* and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
* @xtype label
*/
Ext.form.Label = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML
* tags within the label's innerHTML, use the {@link #html} config instead.
*/
/**
* @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for'
* attribute. If not specified, the attribute will not be added to the label.
*/
/**
* @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to '').
* Note that if {@link #text} is specified it will take precedence and this value will be ignored.
*/
// private
onRender : function(ct, position){
if(!this.el){
this.el = document.createElement('label');
this.el.id = this.getId();
this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || '');
if(this.forId){
this.el.setAttribute('for', this.forId);
}
}
Ext.form.Label.superclass.onRender.call(this, ct, position);
},
/**
* Updates the label's innerHTML with the specified string.
* @param {String} text The new label text
* @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it
* to the label (defaults to true which encodes the value). This might be useful if you want to include
* tags in the label's innerHTML rather than rendering them as string literals per the default logic.
* @return {Label} this
*/
setText : function(t, encode){
var e = encode === false;
this[!e ? 'text' : 'html'] = t;
delete this[e ? 'text' : 'html'];
if(this.rendered){
this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t;
}
return this;
}
});
Ext.reg('label', Ext.form.Label);/**
* @class Ext.form.Action
* <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
* <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
* the Form needs to perform an action such as submit or load. The Configuration options
* listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
* {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
* <p>The instance of Action which performed the action is passed to the success
* and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
* {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
* and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
* {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
*/
Ext.form.Action = function(form, options){
this.form = form;
this.options = options || {};
};
/**
* Failure type returned when client side validation of the Form fails
* thus aborting a submit action. Client side validation is performed unless
* {@link #clientValidation} is explicitly set to <tt>false</tt>.
* @type {String}
* @static
*/
Ext.form.Action.CLIENT_INVALID = 'client';
/**
* <p>Failure type returned when server side processing fails and the {@link #result}'s
* <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
* <p>In the case of a form submission, field-specific error messages may be returned in the
* {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
* @type {String}
* @static
*/
Ext.form.Action.SERVER_INVALID = 'server';
/**
* Failure type returned when a communication error happens when attempting
* to send a request to the remote server. The {@link #response} may be examined to
* provide further information.
* @type {String}
* @static
*/
Ext.form.Action.CONNECT_FAILURE = 'connect';
/**
* Failure type returned when the response's <tt style="font-weight:bold">success</tt>
* property is set to <tt>false</tt>, or no field values are returned in the response's
* <tt style="font-weight:bold">data</tt> property.
* @type {String}
* @static
*/
Ext.form.Action.LOAD_FAILURE = 'load';
Ext.form.Action.prototype = {
/**
* @cfg {String} url The URL that the Action is to invoke.
*/
/**
* @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
* {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
* <b>before</b> the {@link #success} callback is called and before the Form's
* {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
*/
/**
* @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
* {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
*/
/**
* @cfg {Mixed} params <p>Extra parameter values to pass. These are added to the Form's
* {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's
* input fields.</p>
* <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
*/
/**
* @cfg {Number} timeout The number of seconds to wait for a server response before
* failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified,
* defaults to the configured <tt>{@link Ext.form.BasicForm#timeout timeout}</tt> of the
* {@link Ext.form.BasicForm form}.
*/
/**
* @cfg {Function} success The function to call when a valid success return packet is recieved.
* The function is passed the following parameters:<ul class="mdetail-params">
* <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
* <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul>
*/
/**
* @cfg {Function} failure The function to call when a failure packet was recieved, or when an
* error ocurred in the Ajax communication.
* The function is passed the following parameters:<ul class="mdetail-params">
* <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
* <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax
* error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul>
*/
/**
* @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
* for the callback functions).
*/
/**
* @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}
* during the time the action is being processed.
*/
/**
* @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}
* during the time the action is being processed.
*/
/**
* The type of action this Action instance performs.
* Currently only "submit" and "load" are supported.
* @type {String}
*/
type : 'default',
/**
* The type of failure detected will be one of these: {@link #CLIENT_INVALID},
* {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}. Usage:
* <pre><code>
var fp = new Ext.form.FormPanel({
...
buttons: [{
text: 'Save',
formBind: true,
handler: function(){
if(fp.getForm().isValid()){
fp.getForm().submit({
url: 'form-submit.php',
waitMsg: 'Submitting your data...',
success: function(form, action){
// server responded with success = true
var result = action.{@link #result};
},
failure: function(form, action){
if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
Ext.Msg.alert('Error',
'Status:'+action.{@link #response}.status+': '+
action.{@link #response}.statusText);
}
if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
// server responded with success = false
Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
}
}
});
}
}
},{
text: 'Reset',
handler: function(){
fp.getForm().reset();
}
}]
* </code></pre>
* @property failureType
* @type {String}
*/
/**
* The XMLHttpRequest object used to perform the action.
* @property response
* @type {Object}
*/
/**
* The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
* other, action-specific properties.
* @property result
* @type {Object}
*/
// interface method
run : function(options){
},
// interface method
success : function(response){
},
// interface method
handleResponse : function(response){
},
// default connection failure
failure : function(response){
this.response = response;
this.failureType = Ext.form.Action.CONNECT_FAILURE;
this.form.afterAction(this, false);
},
// private
// shared code among all Actions to validate that there was a response
// with either responseText or responseXml
processResponse : function(response){
this.response = response;
if(!response.responseText && !response.responseXML){
return true;
}
this.result = this.handleResponse(response);
return this.result;
},
// utility functions used internally
getUrl : function(appendParams){
var url = this.options.url || this.form.url || this.form.el.dom.action;
if(appendParams){
var p = this.getParams();
if(p){
url = Ext.urlAppend(url, p);
}
}
return url;
},
// private
getMethod : function(){
return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
},
// private
getParams : function(){
var bp = this.form.baseParams;
var p = this.options.params;
if(p){
if(typeof p == "object"){
p = Ext.urlEncode(Ext.applyIf(p, bp));
}else if(typeof p == 'string' && bp){
p += '&' + Ext.urlEncode(bp);
}
}else if(bp){
p = Ext.urlEncode(bp);
}
return p;
},
// private
createCallback : function(opts){
var opts = opts || {};
return {
success: this.success,
failure: this.failure,
scope: this,
timeout: (opts.timeout*1000) || (this.form.timeout*1000),
upload: this.form.fileUpload ? this.success : undefined
};
}
};
/**
* @class Ext.form.Action.Submit
* @extends Ext.form.Action
* <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
* and processes the returned response.</p>
* <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
* {@link Ext.form.BasicForm#submit submit}ting.</p>
* <p><u><b>Response Packet Criteria</b></u></p>
* <p>A response packet may contain:
* <div class="mdetail-params"><ul>
* <li><b><code>success</code></b> property : Boolean
* <div class="sub-desc">The <code>success</code> property is required.</div></li>
* <li><b><code>errors</code></b> property : Object
* <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
* which is optional, contains error messages for invalid fields.</div></li>
* </ul></div>
* <p><u><b>JSON Packets</b></u></p>
* <p>By default, response packets are assumed to be JSON, so a typical response
* packet may look like this:</p><pre><code>
{
success: false,
errors: {
clientCode: "Client not found",
portOfLoading: "This field must not be null"
}
}</code></pre>
* <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
* or event handler methods. The object decoded from this JSON is available in the
* {@link Ext.form.Action#result result} property.</p>
* <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
errorReader: new Ext.data.XmlReader({
record : 'field',
success: '@success'
}, [
'id', 'msg'
]
)
</code></pre>
* <p>then the results may be sent back in XML format:</p><pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<message success="false">
<errors>
<field>
<id>clientCode</id>
<msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
</field>
<field>
<id>portOfLoading</id>
<msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
</field>
</errors>
</message>
</code></pre>
* <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
* or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
*/
Ext.form.Action.Submit = function(form, options){
Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
};
Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
/**
* @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
* no need for an errorReader.</b></p>
* <p>A Reader which reads a single record from the returned data. The DataReader's
* <b>success</b> property specifies how submission success is determined. The Record's
* data provides the error messages to apply to any invalid form Fields.</p>
*/
/**
* @cfg {boolean} clientValidation Determines whether a Form's fields are validated
* in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
* Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
* is performed.
*/
type : 'submit',
// private
run : function(){
var o = this.options;
var method = this.getMethod();
var isGet = method == 'GET';
if(o.clientValidation === false || this.form.isValid()){
Ext.Ajax.request(Ext.apply(this.createCallback(o), {
form:this.form.el.dom,
url:this.getUrl(isGet),
method: method,
headers: o.headers,
params:!isGet ? this.getParams() : null,
isUpload: this.form.fileUpload
}));
}else if (o.clientValidation !== false){ // client validation failed
this.failureType = Ext.form.Action.CLIENT_INVALID;
this.form.afterAction(this, false);
}
},
// private
success : function(response){
var result = this.processResponse(response);
if(result === true || result.success){
this.form.afterAction(this, true);
return;
}
if(result.errors){
this.form.markInvalid(result.errors);
}
this.failureType = Ext.form.Action.SERVER_INVALID;
this.form.afterAction(this, false);
},
// private
handleResponse : function(response){
if(this.form.errorReader){
var rs = this.form.errorReader.read(response);
var errors = [];
if(rs.records){
for(var i = 0, len = rs.records.length; i < len; i++) {
var r = rs.records[i];
errors[i] = r.data;
}
}
if(errors.length < 1){
errors = null;
}
return {
success : rs.success,
errors : errors
};
}
return Ext.decode(response.responseText);
}
});
/**
* @class Ext.form.Action.Load
* @extends Ext.form.Action
* <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
* <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
* {@link Ext.form.BasicForm#load load}ing.</p>
* <p><u><b>Response Packet Criteria</b></u></p>
* <p>A response packet <b>must</b> contain:
* <div class="mdetail-params"><ul>
* <li><b><code>success</code></b> property : Boolean</li>
* <li><b><code>data</code></b> property : Object</li>
* <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
* The individual value object for each Field is passed to the Field's
* {@link Ext.form.Field#setValue setValue} method.</div></li>
* </ul></div>
* <p><u><b>JSON Packets</b></u></p>
* <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
var myFormPanel = new Ext.form.FormPanel({
title: 'Client and routing info',
items: [{
fieldLabel: 'Client',
name: 'clientName'
}, {
fieldLabel: 'Port of loading',
name: 'portOfLoading'
}, {
fieldLabel: 'Port of discharge',
name: 'portOfDischarge'
}]
});
myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
url: '/getRoutingInfo.php',
params: {
consignmentRef: myConsignmentRef
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
</code></pre>
* a <b>success response</b> packet may look like this:</p><pre><code>
{
success: true,
data: {
clientName: "Fred. Olsen Lines",
portOfLoading: "FXT",
portOfDischarge: "OSL"
}
}</code></pre>
* while a <b>failure response</b> packet may look like this:</p><pre><code>
{
success: false,
errorMessage: "Consignment reference not found"
}</code></pre>
* <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
* callback or event handler methods. The object decoded from this JSON is available in the
* {@link Ext.form.Action#result result} property.</p>
*/
Ext.form.Action.Load = function(form, options){
Ext.form.Action.Load.superclass.constructor.call(this, form, options);
this.reader = this.form.reader;
};
Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
// private
type : 'load',
// private
run : function(){
Ext.Ajax.request(Ext.apply(
this.createCallback(this.options), {
method:this.getMethod(),
url:this.getUrl(false),
headers: this.options.headers,
params:this.getParams()
}));
},
// private
success : function(response){
var result = this.processResponse(response);
if(result === true || !result.success || !result.data){
this.failureType = Ext.form.Action.LOAD_FAILURE;
this.form.afterAction(this, false);
return;
}
this.form.clearInvalid();
this.form.setValues(result.data);
this.form.afterAction(this, true);
},
// private
handleResponse : function(response){
if(this.form.reader){
var rs = this.form.reader.read(response);
var data = rs.records && rs.records[0] ? rs.records[0].data : null;
return {
success : rs.success,
data : data
};
}
return Ext.decode(response.responseText);
}
});
/**
* @class Ext.form.Action.DirectLoad
* @extends Ext.form.Action.Load
* <p>Provides Ext.direct support for loading form data.</p>
* <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
* <pre><code>
var myFormPanel = new Ext.form.FormPanel({
// configs for FormPanel
title: 'Basic Information',
renderTo: document.body,
width: 300, height: 160,
padding: 10,
// configs apply to child items
defaults: {anchor: '100%'},
defaultType: 'textfield',
items: [{
fieldLabel: 'Name',
name: 'name'
},{
fieldLabel: 'Email',
name: 'email'
},{
fieldLabel: 'Company',
name: 'company'
}],
// configs for BasicForm
api: {
// The server-side method to call for load() requests
load: Profile.getBasicInfo,
// The server-side must mark the submit handler as a 'formHandler'
submit: Profile.updateBasicInfo
},
// specify the order for the passed params
paramOrder: ['uid', 'foo']
});
// load the form
myFormPanel.getForm().load({
// pass 2 arguments to server side getBasicInfo method (len=2)
params: {
foo: 'bar',
uid: 34
}
});
* </code></pre>
* The data packet sent to the server will resemble something like:
* <pre><code>
[
{
"action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
"data":[34,"bar"] // note the order of the params
}
]
* </code></pre>
* The form will process a data packet returned by the server that is similar
* to the following format:
* <pre><code>
[
{
"action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
"result":{
"success":true,
"data":{
"name":"Fred Flintstone",
"company":"Slate Rock and Gravel",
"email":"[email protected]"
}
}
}
]
* </code></pre>
*/
Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
constructor: function(form, opts) {
Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
},
type : 'directload',
run : function(){
var args = this.getParams();
args.push(this.success, this);
this.form.api.load.apply(window, args);
},
getParams : function() {
var buf = [], o = {};
var bp = this.form.baseParams;
var p = this.options.params;
Ext.apply(o, p, bp);
var paramOrder = this.form.paramOrder;
if(paramOrder){
for(var i = 0, len = paramOrder.length; i < len; i++){
buf.push(o[paramOrder[i]]);
}
}else if(this.form.paramsAsHash){
buf.push(o);
}
return buf;
},
// Direct actions have already been processed and therefore
// we can directly set the result; Direct Actions do not have
// a this.response property.
processResponse : function(result) {
this.result = result;
return result;
},
success : function(response, trans){
if(trans.type == Ext.Direct.exceptions.SERVER){
response = {};
}
Ext.form.Action.DirectLoad.superclass.success.call(this, response);
}
});
/**
* @class Ext.form.Action.DirectSubmit
* @extends Ext.form.Action.Submit
* <p>Provides Ext.direct support for submitting form data.</p>
* <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
* <pre><code>
var myFormPanel = new Ext.form.FormPanel({
// configs for FormPanel
title: 'Basic Information',
renderTo: document.body,
width: 300, height: 160,
padding: 10,
buttons:[{
text: 'Submit',
handler: function(){
myFormPanel.getForm().submit({
params: {
foo: 'bar',
uid: 34
}
});
}
}],
// configs apply to child items
defaults: {anchor: '100%'},
defaultType: 'textfield',
items: [{
fieldLabel: 'Name',
name: 'name'
},{
fieldLabel: 'Email',
name: 'email'
},{
fieldLabel: 'Company',
name: 'company'
}],
// configs for BasicForm
api: {
// The server-side method to call for load() requests
load: Profile.getBasicInfo,
// The server-side must mark the submit handler as a 'formHandler'
submit: Profile.updateBasicInfo
},
// specify the order for the passed params
paramOrder: ['uid', 'foo']
});
* </code></pre>
* The data packet sent to the server will resemble something like:
* <pre><code>
{
"action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
"result":{
"success":true,
"id":{
"extAction":"Profile","extMethod":"updateBasicInfo",
"extType":"rpc","extTID":"6","extUpload":"false",
"name":"Aaron Conran","email":"[email protected]","company":"Ext JS, LLC"
}
}
}
* </code></pre>
* The form will process a data packet returned by the server that is similar
* to the following:
* <pre><code>
// sample success packet (batched requests)
[
{
"action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
"result":{
"success":true
}
}
]
// sample failure packet (one request)
{
"action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
"result":{
"errors":{
"email":"already taken"
},
"success":false,
"foo":"bar"
}
}
* </code></pre>
* Also see the discussion in {@link Ext.form.Action.DirectLoad}.
*/
Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
constructor : function(form, opts) {
Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
},
type : 'directsubmit',
// override of Submit
run : function(){
var o = this.options;
if(o.clientValidation === false || this.form.isValid()){
// tag on any additional params to be posted in the
// form scope
this.success.params = this.getParams();
this.form.api.submit(this.form.el.dom, this.success, this);
}else if (o.clientValidation !== false){ // client validation failed
this.failureType = Ext.form.Action.CLIENT_INVALID;
this.form.afterAction(this, false);
}
},
getParams : function() {
var o = {};
var bp = this.form.baseParams;
var p = this.options.params;
Ext.apply(o, p, bp);
return o;
},
// Direct actions have already been processed and therefore
// we can directly set the result; Direct Actions do not have
// a this.response property.
processResponse : function(result) {
this.result = result;
return result;
},
success : function(response, trans){
if(trans.type == Ext.Direct.exceptions.SERVER){
response = {};
}
Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
}
});
Ext.form.Action.ACTION_TYPES = {
'load' : Ext.form.Action.Load,
'submit' : Ext.form.Action.Submit,
'directload' : Ext.form.Action.DirectLoad,
'directsubmit' : Ext.form.Action.DirectSubmit
};
/**
* @class Ext.form.VTypes
* <p>This is a singleton object which contains a set of commonly used field validation functions.
* The validations provided are basic and intended to be easily customizable and extended.</p>
* <p>To add custom VTypes specify the <code>{@link Ext.form.TextField#vtype vtype}</code> validation
* test function, and optionally specify any corresponding error text to display and any keystroke
* filtering mask to apply. For example:</p>
* <pre><code>
// custom Vtype for vtype:'time'
var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
Ext.apply(Ext.form.VTypes, {
// vtype validation function
time: function(val, field) {
return timeTest.test(val);
},
// vtype Text property: The error text to display when the validation function returns false
timeText: 'Not a valid time. Must be in the format "12:34 PM".',
// vtype Mask property: The keystroke filter mask
timeMask: /[\d\s:amp]/i
});
* </code></pre>
* Another example:
* <pre><code>
// custom Vtype for vtype:'IPAddress'
Ext.apply(Ext.form.VTypes, {
IPAddress: function(v) {
return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
},
IPAddressText: 'Must be a numeric IP address',
IPAddressMask: /[\d\.]/i
});
* </code></pre>
* @singleton
*/
Ext.form.VTypes = function(){
// closure these in so they are only created once.
var alpha = /^[a-zA-Z_]+$/,
alphanum = /^[a-zA-Z0-9_]+$/,
email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
// All these messages and functions are configurable
return {
/**
* The function used to validate email addresses. Note that this is a very basic validation -- complete
* validation per the email RFC specifications is very complex and beyond the scope of this class, although
* this function can be overridden if a more comprehensive validation scheme is desired. See the validation
* section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
* for additional information. This implementation is intended to validate the following emails:<tt>
* '[email protected]', '[email protected]', '[email protected]', '[email protected]'
* </tt>.
* @param {String} value The email address
* @return {Boolean} true if the RegExp test passed, and false if not.
*/
'email' : function(v){
return email.test(v);
},
/**
* The error text to display when the email validation function returns false. Defaults to:
* <tt>'This field should be an e-mail address in the format "[email protected]"'</tt>
* @type String
*/
'emailText' : 'This field should be an e-mail address in the format "[email protected]"',
/**
* The keystroke filter mask to be applied on email input. See the {@link #email} method for
* information about more complex email validation. Defaults to:
* <tt>/[a-z0-9_\.\-@]/i</tt>
* @type RegExp
*/
'emailMask' : /[a-z0-9_\.\-@]/i,
/**
* The function used to validate URLs
* @param {String} value The URL
* @return {Boolean} true if the RegExp test passed, and false if not.
*/
'url' : function(v){
return url.test(v);
},
/**
* The error text to display when the url validation function returns false. Defaults to:
* <tt>'This field should be a URL in the format "http:/'+'/www.example.com"'</tt>
* @type String
*/
'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
/**
* The function used to validate alpha values
* @param {String} value The value
* @return {Boolean} true if the RegExp test passed, and false if not.
*/
'alpha' : function(v){
return alpha.test(v);
},
/**
* The error text to display when the alpha validation function returns false. Defaults to:
* <tt>'This field should only contain letters and _'</tt>
* @type String
*/
'alphaText' : 'This field should only contain letters and _',
/**
* The keystroke filter mask to be applied on alpha input. Defaults to:
* <tt>/[a-z_]/i</tt>
* @type RegExp
*/
'alphaMask' : /[a-z_]/i,
/**
* The function used to validate alphanumeric values
* @param {String} value The value
* @return {Boolean} true if the RegExp test passed, and false if not.
*/
'alphanum' : function(v){
return alphanum.test(v);
},
/**
* The error text to display when the alphanumeric validation function returns false. Defaults to:
* <tt>'This field should only contain letters, numbers and _'</tt>
* @type String
*/
'alphanumText' : 'This field should only contain letters, numbers and _',
/**
* The keystroke filter mask to be applied on alphanumeric input. Defaults to:
* <tt>/[a-z0-9_]/i</tt>
* @type RegExp
*/
'alphanumMask' : /[a-z0-9_]/i
};
}(); | {'content_hash': '40b67cc665d18fa1494343721c5e2a9e', 'timestamp': '', 'source': 'github', 'line_count': 8247, 'max_line_length': 209, 'avg_line_length': 34.849521037953195, 'alnum_prop': 0.5624904315875909, 'repo_name': 'xenophy/xFrameworkPX', 'id': 'a42e8ede8f1841305dc72858a50809c7a3c396bb', 'size': '287528', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bindtransfer/extjs/pkgs/pkg-forms-debug.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '12667398'}, {'name': 'PHP', 'bytes': '16973398'}, {'name': 'Shell', 'bytes': '1360'}]} |
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, prefix, splitBsProps }
from './utils/bootstrapUtils';
const propTypes = {
striped: React.PropTypes.bool,
bordered: React.PropTypes.bool,
condensed: React.PropTypes.bool,
hover: React.PropTypes.bool,
responsive: React.PropTypes.bool,
};
const defaultProps = {
bordered: false,
condensed: false,
hover: false,
responsive: false,
striped: false,
};
class Table extends React.Component {
render() {
const {
striped,
bordered,
condensed,
hover,
responsive,
className,
...props,
} = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = {
...getClassSet(bsProps),
[prefix(bsProps, 'striped')]: striped,
[prefix(bsProps, 'bordered')]: bordered,
[prefix(bsProps, 'condensed')]: condensed,
[prefix(bsProps, 'hover')]: hover,
};
const table = (
<table
{...elementProps}
className={classNames(className, classes)}
/>
);
if (responsive) {
return (
<div className={prefix(bsProps, 'responsive')}>
{table}
</div>
);
}
return table;
}
}
Table.propTypes = propTypes;
Table.defaultProps = defaultProps;
export default bsClass('table', Table);
| {'content_hash': '9144bbacfe909371bd7276ee478144fa', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 56, 'avg_line_length': 20.34328358208955, 'alnum_prop': 0.6162876008804109, 'repo_name': 'dozoisch/react-bootstrap', 'id': 'e479a9e4eb822568957ffc30511e285578cec03e', 'size': '1363', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Table.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '445377'}]} |
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JSUnresolvedVariable" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
</profile>
</component> | {'content_hash': 'fcec6ffbc38c4c03f127d57f1470a377', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 116, 'avg_line_length': 45.333333333333336, 'alnum_prop': 0.7316176470588235, 'repo_name': 'implydata/plywood-druid-requester', 'id': '135b150e954d41f99751aa3868720b62bdb6d6c2', 'size': '272', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/inspectionProfiles/Project_Default.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '44669'}, {'name': 'TypeScript', 'bytes': '27502'}]} |
/**
* Relaxed
* =======
*
* Typical use for relaxed memory ordering is incrementing counters.
*
* Note: Compile with -std=c++11 -pthread.
*/
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>
/// Copy-list-initialization.
std::atomic_int cnt = {0};
/// Direct-initialization.
// std::atomic_int cnt{0};
void
inc()
{
for (int n = 0; n < 42; ++n) cnt.fetch_add(1, std::memory_order_relaxed);
}
int
main(int argc, const char *argv[])
{
std::vector<std::thread> tv;
// emplace_back avoids extra copy or move operations required by
// push_back.
for (int n = 0; n < 10; ++n) tv.emplace_back(inc);
for (auto& t : tv) t.join();
// The final value must be 420.
std::cout << cnt << std::endl;
return 0;
}
| {'content_hash': '9c09180103847c0a556744ed447af4bc', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 77, 'avg_line_length': 18.878048780487806, 'alnum_prop': 0.603359173126615, 'repo_name': 'anqurvanillapy/cppl', 'id': '6a4a4c62cd99e6581ee007b9e2925d56672d3fda', 'size': '774', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sync/relaxed.cc', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '36837'}, {'name': 'C++', 'bytes': '150256'}, {'name': 'Makefile', 'bytes': '901'}]} |
//
// GTLPlusActivity.m
//
// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
// Google+ API (plus/v1)
// Description:
// The Google+ API enables developers to build on top of the Google+ platform.
// Documentation:
// https://developers.google.com/+/api/
// Classes:
// GTLPlusActivity (0 custom class methods, 20 custom properties)
// GTLPlusActivityActor (0 custom class methods, 5 custom properties)
// GTLPlusActivityObject (0 custom class methods, 10 custom properties)
// GTLPlusActivityProvider (0 custom class methods, 1 custom properties)
// GTLPlusActivityActorImage (0 custom class methods, 1 custom properties)
// GTLPlusActivityActorName (0 custom class methods, 2 custom properties)
// GTLPlusActivityObjectActor (0 custom class methods, 4 custom properties)
// GTLPlusActivityObjectAttachmentsItem (0 custom class methods, 9 custom properties)
// GTLPlusActivityObjectPlusoners (0 custom class methods, 2 custom properties)
// GTLPlusActivityObjectReplies (0 custom class methods, 2 custom properties)
// GTLPlusActivityObjectResharers (0 custom class methods, 2 custom properties)
// GTLPlusActivityObjectActorImage (0 custom class methods, 1 custom properties)
// GTLPlusActivityObjectAttachmentsItemEmbed (0 custom class methods, 2 custom properties)
// GTLPlusActivityObjectAttachmentsItemFullImage (0 custom class methods, 4 custom properties)
// GTLPlusActivityObjectAttachmentsItemImage (0 custom class methods, 4 custom properties)
// GTLPlusActivityObjectAttachmentsItemThumbnailsItem (0 custom class methods, 3 custom properties)
// GTLPlusActivityObjectAttachmentsItemThumbnailsItemImage (0 custom class methods, 4 custom properties)
#import "GTLPlusActivity.h"
#import "GTLPlusAcl.h"
#import "GTLPlusPlace.h"
// ----------------------------------------------------------------------------
//
// GTLPlusActivity
//
@implementation GTLPlusActivity
@dynamic access, actor, address, annotation, crosspostSource, ETag, geocode,
identifier, kind, location, object, placeId, placeName, provider,
published, radius, title, updated, url, verb;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObjectsAndKeys:
@"etag", @"ETag",
@"id", @"identifier",
nil];
return map;
}
+ (void)load {
[self registerObjectClassForKind:@"plus#activity"];
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityActor
//
@implementation GTLPlusActivityActor
@dynamic displayName, identifier, image, name, url;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:@"id"
forKey:@"identifier"];
return map;
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObject
//
@implementation GTLPlusActivityObject
@dynamic actor, attachments, content, identifier, objectType, originalContent,
plusoners, replies, resharers, url;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:@"id"
forKey:@"identifier"];
return map;
}
+ (NSDictionary *)arrayPropertyToClassMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:[GTLPlusActivityObjectAttachmentsItem class]
forKey:@"attachments"];
return map;
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityProvider
//
@implementation GTLPlusActivityProvider
@dynamic title;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityActorImage
//
@implementation GTLPlusActivityActorImage
@dynamic url;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityActorName
//
@implementation GTLPlusActivityActorName
@dynamic familyName, givenName;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectActor
//
@implementation GTLPlusActivityObjectActor
@dynamic displayName, identifier, image, url;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:@"id"
forKey:@"identifier"];
return map;
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItem
//
@implementation GTLPlusActivityObjectAttachmentsItem
@dynamic content, displayName, embed, fullImage, identifier, image, objectType,
thumbnails, url;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:@"id"
forKey:@"identifier"];
return map;
}
+ (NSDictionary *)arrayPropertyToClassMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:[GTLPlusActivityObjectAttachmentsItemThumbnailsItem class]
forKey:@"thumbnails"];
return map;
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectPlusoners
//
@implementation GTLPlusActivityObjectPlusoners
@dynamic selfLink, totalItems;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectReplies
//
@implementation GTLPlusActivityObjectReplies
@dynamic selfLink, totalItems;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectResharers
//
@implementation GTLPlusActivityObjectResharers
@dynamic selfLink, totalItems;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectActorImage
//
@implementation GTLPlusActivityObjectActorImage
@dynamic url;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItemEmbed
//
@implementation GTLPlusActivityObjectAttachmentsItemEmbed
@dynamic type, url;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItemFullImage
//
@implementation GTLPlusActivityObjectAttachmentsItemFullImage
@dynamic height, type, url, width;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItemImage
//
@implementation GTLPlusActivityObjectAttachmentsItemImage
@dynamic height, type, url, width;
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItemThumbnailsItem
//
@implementation GTLPlusActivityObjectAttachmentsItemThumbnailsItem
@dynamic descriptionProperty, image, url;
+ (NSDictionary *)propertyToJSONKeyMap {
NSDictionary *map =
[NSDictionary dictionaryWithObject:@"description"
forKey:@"descriptionProperty"];
return map;
}
@end
// ----------------------------------------------------------------------------
//
// GTLPlusActivityObjectAttachmentsItemThumbnailsItemImage
//
@implementation GTLPlusActivityObjectAttachmentsItemThumbnailsItemImage
@dynamic height, type, url, width;
@end
| {'content_hash': '589826022e79a5abec13914b4fc66491', 'timestamp': '', 'source': 'github', 'line_count': 278, 'max_line_length': 106, 'avg_line_length': 26.906474820143885, 'alnum_prop': 0.5975935828877005, 'repo_name': 'LuizSSB/GoogleApiObjectiveCClient', 'id': '718498c5a61f98b8489795b382aad039a8f995d7', 'size': '8075', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'Services/Plus/Generated/GTLPlusActivity.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '4431'}, {'name': 'C++', 'bytes': '2926'}, {'name': 'Objective-C', 'bytes': '5485763'}, {'name': 'Shell', 'bytes': '3632'}]} |
@class CMAttributeRun;
@interface CMCascadingAttributeStack : NSObject
@property (nonatomic, readonly) NSDictionary *cascadedAttributes;
- (void)push:(CMAttributeRun *)run;
- (CMAttributeRun *)pop;
- (CMAttributeRun *)peek;
@end
| {'content_hash': '54d5eda921fb72fa6473ba8752f6e22c', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 65, 'avg_line_length': 23.2, 'alnum_prop': 0.771551724137931, 'repo_name': 'alvaromb/EventBlankApp', 'id': 'b84ac9f8e438faa6b5acfdf4d79ad78fdb5fca98', 'size': '429', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'EventBlank/Vendor/CocoaMarkdown/CocoaMarkdown/CMCascadingAttributeStack.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '9315'}, {'name': 'HTML', 'bytes': '489'}, {'name': 'Objective-C', 'bytes': '225430'}, {'name': 'Ruby', 'bytes': '968'}, {'name': 'Shell', 'bytes': '8209'}, {'name': 'Swift', 'bytes': '482831'}]} |
Add-Type -AssemblyName System.IO.Compression.FileSystem
# $nodes = @()
# $nodes += @{ 'Name'= 'package1'; 'Dependencies' = @() }
# $nodes += @{ 'Name'= 'package2'; 'Dependencies' = @() }
# $nodes += @{ 'Name'= 'package3'; 'Dependencies' = @('package1') }
# $nodes += @{ 'Name'= 'package4'; 'Dependencies' = @('package1') }
# $nodes += @{ 'Name'= 'package5'; 'Dependencies' = @('package3') }
# # package1
# # - package3
# # - package5
# # - package4
# # package2
# TopologicalSort $nodes
# topological sort
function TopologicalSort {
param(
[Parameter(Mandatory = $true, Position = 0)]
$nodes
)
$nodesIndex = @{}
$nodesDependencyIndex = @{}
$currentNodes = New-Object -TypeName System.Collections.Generic.Stack[object]
for($i = $nodes.Count - 1; $i -ge 0; $i--)
{
$node = $nodes[$i]
if (!$nodesIndex.ContainsKey($node.Name))
{
$nodesIndex.Set_Item($node.Name, $node)
}
else
{
throw ("'{0}' is duplicate" -f $node.Name)
}
if ($node.Dependencies.Count -eq 0)
{
[void]$currentNodes.Push($node.Name)
continue
}
foreach($nodeDependency in $node.Dependencies)
{
if ($nodesDependencyIndex.ContainsKey($nodeDependency))
{
$nodeDependencies = $nodesDependencyIndex.Get_Item($nodeDependency)
}
else
{
$nodeDependencies = @()
}
if ($nodeDependencies.Contains($node.Name))
{
continue
}
$nodeDependencies += $node.Name
$nodesDependencyIndex.Set_Item($nodeDependency, $nodeDependencies)
}
}
# throw error, if node dependency doesn't exist or circular dependency detected between nodes
foreach($node in $nodesIndex.keys)
{
foreach($nodeDependency in $nodesIndex[$node].Dependencies)
{
if (!$nodesIndex.ContainsKey($nodeDependency))
{
throw ("'{0}' dependency '{1}' doesn't exist" -f $node, $nodeDependency)
}
else
{
if ($nodesIndex[$nodeDependency].Contains($node))
{
throw ("Circular dependency between '{0}' and '{1}'" -f $node, $nodeDependency)
}
}
}
}
$topologicallySortedNodes = New-Object System.Collections.ArrayList
while($currentNodes.Count -gt 0)
{
$node = $currentNodes.Pop()
[void]$topologicallySortedNodes.Add($node)
if ($nodesDependencyIndex.ContainsKey($node))
{
$nodesDependencyIndex[$node] | ForEach-Object { [void]$currentNodes.Push($_) }
}
}
return $topologicallySortedNodes
}
# topological sort v2
function TopologicalSortV2 {
param(
[Parameter(Mandatory = $true, Position = 0)]
[hashtable]$nodes
)
$nodeDependenciesIndex = @{}
$currentNodes = New-Object -TypeName System.Collections.Generic.Stack[object]
foreach($node in ($nodes.keys | Sort-Object @{expression={$nodes[$_].SortOrder};Ascending=$false}))
{
if ($nodes[$node].Dependencies.Count -eq 0)
{
[void]$currentNodes.Push($_)
continue
}
foreach($nodeDependency in $nodes[$node].Dependencies)
{
if (!$nodes.ContainsKey($nodeDependency))
{
throw ("'{0}' dependency '{1}' doesn't exist" -f $node, $nodeDependency)
}
else
{
if ($nodes[$nodeDependency].Dependencies.Contains($node))
{
throw ("Circular dependency between '{0}' and '{1}'" -f $node, $nodeDependency)
}
}
if ($nodeDependenciesIndex.ContainsKey($nodeDependency))
{
$nodeDependencies = $nodeDependenciesIndex.Get_Item($nodeDependency)
}
else
{
$nodeDependencies = @()
}
if ($nodeDependencies.Contains($node))
{
continue
}
$nodeDependencies += $node
$nodeDependenciesIndex.Set_Item($nodeDependency, $nodeDependencies)
}
}
foreach($node in $currentNodes)
{
Write-Host $node
}
$topologicallySortedNodes = New-Object System.Collections.ArrayList
while($currentNodes.Count -gt 0)
{
$node = $currentNodes.Pop()
[void]$topologicallySortedNodes.Add($node)
if ($nodeDependenciesIndex.ContainsKey($node))
{
$nodeDependenciesIndex[$node] | ForEach-Object { [void]$currentNodes.Push($_) }
}
}
return $topologicallySortedNodes
}
# get supported amiga os versions
function GetSupportedAmigaOsVersions()
{
return @('3.9', '3.2', '3.1.4', '3.1')
}
# read zip entry text file
function ReadZipEntryTextFile($zipFile, $entryName)
{
# open zip archive
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipFile,"Read")
$zipArchiveEntry = $zipArchive.Entries | Where-Object { $_.FullName -match $entryName } | Select-Object -First 1
# return null, if zip archive entry doesn't exist
if (!$zipArchiveEntry)
{
$zipArchive.Dispose()
return $null
}
# open zip archive entry stream
$entryStream = $zipArchiveEntry.Open()
$streamReader = New-Object System.IO.StreamReader($entryStream)
# read text from stream
$text = $streamReader.ReadToEnd()
# close streams
$streamReader.Close()
$streamReader.Dispose()
# close zip archive
$zipArchive.Dispose()
return $text
}
# zip file contains
function ZipFileContains($zipFile, $pattern)
{
# open zip archive
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipFile,"Read")
# get zip archive entries matching pattern
$matchingZipArchiveEntries = @()
$matchingZipArchiveEntries += $zipArchive.Entries | Where-Object { $_.FullName -match $pattern }
# close zip archive
$zipArchive.Dispose()
return $matchingZipArchiveEntries.Count -gt 0
}
# extract files from zip file
function ExtractFilesFromZipFile($zipFile, $pattern, $outputDir)
{
# open zip archive
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipFile,"Read")
# get zip archive entries matching pattern
$matchingZipArchiveEntries = @()
$matchingZipArchiveEntries += $zipArchive.Entries | Where-Object { $_.FullName -match $pattern }
# extract matching zip archive entries
foreach($zipArchiveEntry in $matchingZipArchiveEntries)
{
# get output file
$outputFile = Join-Path $outputDir -ChildPath $zipArchiveEntry.FullName
# get output file parent dir
$outputFileParentDir = Split-Path $outputFile -Parent
# create entry directory, if it doesn't exist
if (!(Test-Path $outputFileParentDir))
{
mkdir $outputFileParentDir | Out-Null
}
# open zip archive entry stream
$zipArchiveEntryStream = $zipArchiveEntry.Open()
# open file stream and write from entry stream
$outputFileStream = New-Object System.IO.FileStream($outputFile, 'Create')
$zipArchiveEntryStream.CopyTo($outputFileStream)
# close streams
$outputFileStream.Close()
$outputFileStream.Dispose()
$zipArchiveEntryStream.Close()
$zipArchiveEntryStream.Dispose()
}
# close zip archive
$zipArchive.Dispose()
}
# calculate md5 hash from file
function CalculateMd5FromFile($file)
{
try
{
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
return [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file))).ToLower().Replace('-', '')
}
catch
{
throw ('Failed to read MD5 from file ''{0}'': {1}' -f $file, $_.ErrorDetails.Message)
}
}
function IsEncryptedKickstartRom($romBytes)
{
# header for encrypted roms
$header = "AMIROMTYPE1"
if ($romBytes.Count -lt $header.Length)
{
return $false
}
# return if header from rom bytes match
return $header -eq [System.Text.Encoding]::ASCII.GetString($romBytes[0..($header.Length - 1)])
}
function CalculateMd5FromBytes($bytes)
{
try
{
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
return [System.BitConverter]::ToString($md5.ComputeHash($bytes)).ToLower().Replace('-', '')
}
catch
{
throw ('Failed to calculate MD5: {1}' -f $_.ErrorDetails.Message)
}
}
# calculate md5 hash from file
function CalculateDecryptedKickstartMd5FromBytes($romBytes, $keyBytes)
{
try
{
# fail, if header from rom bytes doesn't match
if (!(IsEncryptedKickstartRom $romBytes))
{
Write-Error "Rom file not encrypted"
exit 1
}
# header for encrypted roms
$header = "AMIROMTYPE1"
# strip header from rom bytes
$romBytes = $romBytes[$header.Length..$romBytes.Count]
# decrypt rom bytes using bitwise xor of key bytes
for ($i = $j = 0; $i -lt $romBytes.Count; $i++)
{
$romBytes[$i] = $romBytes[$i] -bxor $keyBytes[$j]
$j = ($j + 1) % $keyBytes.Count
}
return CalculateMd5FromBytes $romBytes
}
catch
{
throw ('Failed to calculate decrypted kickstart MD5: {1}' -f $_.ErrorDetails.Message)
}
}
# calculate md5 hash from text
function CalculateMd5FromText($text)
{
$encoding = [system.Text.Encoding]::UTF8
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
return [System.BitConverter]::ToString($md5.ComputeHash($encoding.GetBytes($text))).ToLower().Replace('-', '')
}
# get file hashes
function GetFileHashes($path)
{
$fileHashes = @()
if (!$path -or !(Test-Path -Path $path))
{
return $fileHashes
}
$files = Get-ChildItem -Path $path -Recurse | Where-Object { ! $_.PSIsContainer }
foreach ($file in $files)
{
$md5Hash = CalculateMd5FromFile $file.FullName
$fileHashes += @{ "File" = $file.FullName; "Md5Hash" = $md5Hash }
}
return $fileHashes
}
# find matching file hashes
function FindMatchingFileHashes($hashes, $path)
{
# get file hashes from path
$fileHashes = GetFileHashes $path
# index file hashes
$fileHashesIndex = @{}
$fileHashes | ForEach-Object { $fileHashesIndex.Set_Item($_.Md5Hash, $_.File) }
# find files with matching hashes
foreach($hash in $hashes)
{
$file = $null
if ($fileHashesIndex.ContainsKey($hash.Md5Hash))
{
$file = $fileHashesIndex.Get_Item($hash.Md5Hash)
}
$hash | Add-Member -MemberType NoteProperty -Name 'File' -Value $file -Force
$hash | Add-Member -MemberType NoteProperty -Name 'MatchType' -Value 'MD5' -Force
$hash | Add-Member -MemberType NoteProperty -Name 'MatchRank' -Value '1' -Force
}
}
function ReadBytes($bytes, $offset, $length)
{
$newBytes = New-Object 'byte[]' $length
[Array]::Copy($bytes, $offset, $newBytes, 0, $length)
return $newBytes
}
# read string from bytes
function ReadString($bytes, $offset, $length)
{
$stringBytes = ReadBytes $bytes $offset $length
$iso88591 = [System.Text.Encoding]::GetEncoding("ISO-8859-1");
return $iso88591.GetString($stringBytes)
}
# read adf volume name
function ReadAdfVolumeName($bytes)
{
# read volume name from offset 0x6E1B0
$volumeNameOffset = 0x6E1B0
$volumeNameLength = $bytes[$volumeNameOffset]
ReadString $bytes ($volumeNameOffset + 1) $volumeNameLength
}
# find matching amiga os adfs
function FindMatchingAmigaOsEntriesByAdfVolumeName($amigaOsEntries, $dir)
{
$adfFiles = Get-ChildItem -Path $dir -filter *.adf
$validAdfFiles = @()
foreach ($adfFile in $adfFiles)
{
# read adf bytes
$adfBytes = [System.IO.File]::ReadAllBytes($adfFile.FullName)
if ($adfBytes.Count -ne 901120)
{
continue
}
$magicBytes = ReadBytes $adfBytes 0 4
# DOS1
if ($magicBytes[0] -ne 68 -and $magicBytes[1] -ne 79 -and $magicBytes[2] -ne 83 -and $magicBytes[3] -ne 1)
{
continue
}
$volumeName = ReadAdfVolumeName $adfBytes
$validAdfFiles += @{ "VolumeName" = $volumeName; "File" = $adfFile.FullName }
}
# find matching amiga os entries by volume name, which doesn't already have a file defined
foreach($amigaOsEntry in ($amigaOsEntries | Where-Object { $_.VolumeName -ne '' -and !$_.File }))
{
$matchingAmigaOsAdfFile = $validAdfFiles | Where-Object { $_.VolumeName -eq $amigaOsEntry.VolumeName } | Select-Object -First 1
$amigaOsAdfFile = $null
if ($matchingAmigaOsAdfFile)
{
$amigaOsAdfFile = $matchingAmigaOsAdfFile.File
}
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'File' -Value $amigaOsAdfFile -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchType' -Value 'VolumeName' -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchRank' -Value '2' -Force
}
}
function FindMatchingAmigaOsEntriesByFileName($amigaOsEntries, $dir)
{
$files = Get-ChildItem -Path $dir -Recurse
# find matching amiga os entries by filename, which doesn't already have a file defined
foreach($amigaOsEntry in ($amigaOsEntries | Where-Object { $_.Filename -ne '' -and !$_.File }))
{
$matchingFile = $files | Where-Object { $_.Name -eq $amigaOsEntry.Filename } | Select-Object -First 1
if (!$matchingFile)
{
continue
}
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'File' -Value $matchingFile.FullName -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchType' -Value 'FileName' -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchRank' -Value '3' -Force
}
}
function FindMatchingKickstartFileHashes($kickstartEntries, $dir)
{
$romKeyPath = Join-Path $dir -ChildPath 'rom.key'
$romKeyPresent = Test-Path $romKeyPath
# read key bytes
$keyBytes = @()
if ($romKeyPresent)
{
$keyBytes += [System.IO.File]::ReadAllBytes($romKeyPath)
}
# get entries
$files = Get-ChildItem -Path $dir | Where-Object { !$_.PSIsContainer }
# index file hashes
$kickstartFileHashesIndex = @{}
foreach($file in $files)
{
# read rom bytes
$romBytes = @()
$romBytes += [System.IO.File]::ReadAllBytes($file.FullName)
$encrypted = 'No'
# calculate decrypted kickstart md5, if file is not encrypted kickstart rom file
if (IsEncryptedKickstartRom $romBytes)
{
if (!$romKeyPresent)
{
continue
}
$encrypted = 'Yes'
$md5Hash = CalculateDecryptedKickstartMd5FromBytes $romBytes $keyBytes
}
else
{
$md5Hash = CalculateMd5FromBytes $romBytes
}
$kickstartFile = @{
'File' = $file.FullName;
'Md5Hash' = $md5Hash;
'Encrypted' = $encrypted
}
# add kickstart file
$kickstartFileHashesIndex.Set_Item($md5Hash, $kickstartFile)
}
# return, if kickstart file hashes index is empty
if ($kickstartFileHashesIndex.Count -eq 0)
{
return
}
# find matching kickstart os entries by md5 hash
foreach($kickstartEntry in $kickstartEntries)
{
if (!$kickstartFileHashesIndex.ContainsKey($kickstartEntry.Md5Hash))
{
continue
}
$kickstartFile = $kickstartFileHashesIndex[$kickstartEntry.Md5Hash]
$kickstartEntry | Add-Member -MemberType NoteProperty -Name 'File' -Value $kickstartFile.File -Force
$kickstartEntry | Add-Member -MemberType NoteProperty -Name 'MatchType' -Value 'MD5' -Force
$kickstartEntry | Add-Member -MemberType NoteProperty -Name 'MatchRank' -Value '1' -Force
$kickstartEntry | Add-Member -MemberType NoteProperty -Name 'Encrypted' -Value $kickstartFile.Encrypted -Force
}
}
function FindMatchingFileNames($kickstartEntries, $dir)
{
# get entries
$files = Get-ChildItem -Path $dir
# find matching kickstart entries by filename, which doesn't already have a file defined
foreach($kickstartEntry in ($kickstartEntries | Where-Object { $_.Filename -ne '' -and !$_.File }))
{
$matchingFile = $files | Where-Object { $_.Name -eq $amigaOsEntry.Filename } | Select-Object -First 1
if (!$matchingFile)
{
continue
}
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'File' -Value $matchingFile.FullName -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchType' -Value 'FileName' -Force
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'MatchRank' -Value '2' -Force
}
}
# find amiga os files
function FindAmigaOsFiles($hstwb)
{
# reset amiga os dir, if it doesn't exist
if (!$hstwb.Settings.AmigaOs.AmigaOsDir -or $hstwb.Settings.AmigaOs.AmigaOsDir -match '^\s*$' -or !(Test-Path -Path $hstwb.Settings.AmigaOs.AmigaOsDir))
{
$hstwb.Settings.AmigaOs.AmigaOsDir = ''
return
}
# find files with hashes matching workbench adf hashes
FindMatchingFileHashes $hstwb.AmigaOsEntries $hstwb.Settings.AmigaOs.AmigaOsDir
# find matching amiga os entries by adf volume name
FindMatchingAmigaOsEntriesByAdfVolumeName $hstwb.AmigaOsEntries $hstwb.Settings.AmigaOs.AmigaOsDir
}
# find kickstart roms
function FindKickstartFiles($hstwb)
{
# reset kickstart rom dir, if it doesn't exist
if (!$hstwb.Settings.Kickstart.KickstartDir -or $hstwb.Settings.Kickstart.KickstartDir -match '^\s*$' -or !(Test-Path -Path $hstwb.Settings.Kickstart.KickstartDir))
{
$hstwb.Settings.Kickstart.KickstartDir = ''
return
}
# find matching kickstart files by md5 hash of encrypted and unencrypted kickstart roms
FindMatchingKickstartFileHashes $hstwb.KickstartEntries $hstwb.Settings.Kickstart.KickstartDir
}
# find best matching kickstart set
function FindBestMatchingKickstartSet($hstwb)
{
# find kickstart files
FindKickstartFiles $hstwb
# get kickstart rom sets
$kickstartRomSets = @()
$kickstartRomSets += $hstwb.KickstartEntries | Sort-Object @{expression={$_.Priority};Ascending=$false} | ForEach-Object { $_.Set } | Get-Unique
# count matching kickstart rom hashes for each set
$kickstartRomSetCount = @{}
foreach($kickstartRomSet in $kickstartRomSets)
{
$kickstartRomSetFiles = @()
$kickstartRomSetFiles += $hstwb.KickstartEntries | Where-Object { $_.Set -eq $kickstartRomSet -and $_.File }
$kickstartRomSetCount.Set_Item($kickstartRomSet, $kickstartRomSetFiles.Count)
}
# get new kickstart rom set, which has highest number of matching kickstart rom hashes
return $kickstartRomSets | Sort-Object @{expression={$kickstartRomSetCount.Get_Item($_)};Ascending=$false} | Select-Object -First 1
}
# find best matching amiga os adf set
function FindBestMatchingAmigaOsSet($hstwb)
{
# find amiga os files
FindAmigaOsFiles $hstwb
# get amiga os set names
$amigaOsSetNames = @()
$amigaOsSetNames += $hstwb.AmigaOsEntries | Where-Object { $_.Set } | ForEach-Object { $_.Set } | Get-Unique
# validate amiga os sets
$amigaOsSetResults = @()
foreach ($amigaOsSetName in $amigaOsSetNames)
{
$amigaOsSetResults += ValidateSet $hstwb.AmigaOsEntries $amigaOsSetName
}
# get best matching amiga os set, which has highest number of files that are required ordered by amiga os entries
$bestMatchingAmigaOsSetResult = $amigaOsSetResults | Where-Object { $_.FilesCountRequired -ge $_.EntriesCountRequired } | Select-Object -First 1
# return empty, if best matching amiga os set is not set
if (!$bestMatchingAmigaOsSetResult)
{
return ''
}
return $bestMatchingAmigaOsSetResult.SetName
}
# update package filtering
function UpdatePackageFiltering($hstwb)
{
$amigaOsVersion = 'All'
if ($hstwb.Settings.AmigaOs.AmigaOsSet)
{
$amigaOsEntry = $hstwb.AmigaOsEntries | Where-Object { $_.Set -eq $hstwb.Settings.AmigaOs.AmigaOsSet } | Select-Object -First 1
if ($amigaOsEntry -and $amigaOsEntry.AmigaOsVersion)
{
$amigaOsVersion = $amigaOsEntry.AmigaOsVersion
}
}
$hstwb.Settings.Packages.PackageFiltering = $amigaOsVersion
}
# validate set
function ValidateSet($entries, $setName)
{
$entriesIndex = @{}
$entries | `
Where-Object { $_.Set -eq $setName } | `
ForEach-Object {
if (!$entriesIndex.ContainsKey($_.Name.ToLower()) -or !$entriesIndex[$_.Name.ToLower()].File) {
$entriesIndex[$_.Name.ToLower()] = $_
}
}
$entriesTotal = 0
$entriesRequired = 0
$filesTotal = 0
$filesRequired = 0
$entriesTotal += $entriesIndex.Values.Count
$entriesRequired = @()
$entriesRequired += $entriesIndex.Values | Where-Object { $_.Required -eq 'True' }
$filesTotal = @()
$filesTotal += $entriesIndex.Values | Where-Object { $_.File -and $_.File -ne '' }
$filesRequired = @()
$filesRequired += $entriesIndex.Values | Where-Object { $_.Required -eq 'True' -and $_.File }
return @{
'SetName' = $setName;
'Entries' = $entriesIndex.Values;
'EntriesCount' = $entriesTotal;
'EntriesCountRequired' = $entriesRequired.Count;
'FilesCount' = $filesTotal.Count;
'FilesCountRequired' = $filesRequired.Count
}
}
function FormatAmigaOsSetInfo($result)
{
$color = $null
$errorMessage = ''
if ($result.FilesCount -gt 0)
{
$color = if ($result.FilesCountRequired -ge $result.EntriesCountRequired) { 'Green' } else { 'Red' }
$errorMessage = if ($result.FilesCountRequired -lt $result.EntriesCountRequired) { ' {0} required file(s) doesn''t exist in Amiga OS dir!' -f ($result.EntriesCountRequired - $result.FilesCountRequired) } else { '' }
}
$amigaOsEntry = $result.Entries | Select-Object -First 1
if ($amigaOsEntry -and !(IsAmigaOsVersionSupported $hstwb $result.Entries))
{
$color = 'Red'
$errorMessage = ' Kickstart rom {0} in Kickstart is required to install!' -f $amigaOsEntry.KickstartVersionRequired
}
return @{
'Text' = ("'{0}' ({1}/{2}){3}" -f $result.SetName, $result.FilesCount, $result.EntriesCount, $errorMessage);
'Color' = $color
}
}
function IsAmigaOsVersionSupported($hstwb, $amigaOsEntries)
{
if ($hstwb.Settings.Installer.Mode -notmatch "^(Install)$")
{
return $true
}
$amigaOsEntry = $amigaOsEntries | Select-Object -First 1
if (!$amigaOsEntry)
{
return $true
}
foreach ($model in $hstwb.Models)
{
$kickstartEntry = $hstwb.KickstartEntries | Where-Object { $_.RunSupported -match 'true' -and $_.Model -match $model -and $_.File -and ($_.AmigaOsVersionsSupported -split ',') -contains $amigaOsEntry.AmigaOsVersion } | Select-Object -First 1
if ($kickstartEntry)
{
return $true
}
}
return $false
}
function FormatKickstartSetInfo($result)
{
$color = 'Red'
if ($result.FilesCount -gt 0)
{
$color = if ($result.FilesCountRequired -ge $result.EntriesCountRequired) { 'Green' } else { 'Yellow' }
}
return @{
'Text' = ("'{0}' ({1}/{2})" -f $result.SetName, $result.FilesCount, $result.EntriesCount);
'Color' = $color
}
}
function UiAmigaOsSetInfo($hstwb, $amigaOsSetName)
{
$result = ValidateSet $hstwb.AmigaOsEntries $amigaOsSetName
$hstwb.UI.AmigaOs.AmigaOsSetInfo = FormatAmigaOsSetInfo $result
}
function UiKickstartSetInfo($hstwb, $kickstartSetName)
{
$result = ValidateSet $hstwb.KickstartEntries $kickstartSetName
$hstwb.UI.Kickstart.KickstartSetInfo = FormatKickstartSetInfo $result
}
# update amiga os entries
function UpdateAmigaOsEntries($hstwb)
{
# set empty amiga os entries
$hstwb.AmigaOsEntries = @()
# return, if installer mode is set to install or build self install
if ($hstwb.Settings.Installer.Mode -notmatch "^(Install|BuildSelfInstall)$")
{
return
}
# fail
if (!(Test-Path -Path $hstwb.Paths.AmigaOsEntriesFile))
{
throw ("Amiga OS entries file '{0}' doesn't exist" -f $hstwb.Paths.AmigaOsEntriesFile)
}
# read amiga os entries
$amigaOsEntries = @()
$amigaOsEntries += Import-Csv -Delimiter ';' $hstwb.Paths.AmigaOsEntriesFile | Where-Object { $_.Name -and $_.Name -ne '' }
# add priority to sets based on their order
$set = ''
$priority = 0
foreach ($amigaOsEntry in $amigaOsEntries)
{
if ($set -ne $amigaOsEntry.Set)
{
$priority++
$set = $amigaOsEntry.Set
}
$amigaOsEntry | Add-Member -MemberType NoteProperty -Name 'Priority' -Value $priority
}
# set amiga os entries
$hstwb.AmigaOsEntries = $amigaOsEntries
}
# update kickstart entries
function UpdateKickstartEntries($hstwb)
{
# set empty kickstart entries
$hstwb.KickstartEntries = @()
# return, if installer mode is set to test, install or build self install
if ($hstwb.Settings.Installer.Mode -notmatch "^(Test|Install|BuildSelfInstall)$")
{
return
}
# fail, if kickstart entries file doesn't exist
if (!(Test-Path -Path $hstwb.Paths.KickstartEntriesFile))
{
throw ("Kickstart entries file '{0}' doesn't exist" -f $hstwb.Paths.KickstartEntriesFile)
}
# read kickstart entries
$kickstartEntries = @()
$kickstartEntries += Import-Csv -Delimiter ';' $hstwb.Paths.KickstartEntriesFile | Where-Object { $_.Name -and $_.Name -ne '' }
# add priority to sets based on their order
$set = ''
$priority = 0
foreach ($kickstartEntry in $kickstartEntries)
{
if ($set -ne $kickstartEntry.Set)
{
$priority++
$set = $kickstartEntry.Set
}
$kickstartEntry | Add-Member -MemberType NoteProperty -Name 'Priority' -Value $priority
}
# set kickstart entries
$hstwb.KickstartEntries = $kickstartEntries
}
# sort packages to install
function SortPackageNames($hstwb)
{
$packageIndex = 0
$packageNodes = @()
foreach ($package in ($hstwb.Packages.Values | Sort-Object @{expression={$_.Name};Ascending=$true}))
{
# get priority, if it exists. otherwise use default priority 9999
$priority = if ($package.Priority) { [Int32]$package.Priority } else { 9999 }
$packageIndex++
$packageNodes += @{ 'Name'= $package.Name; 'Index' = $packageIndex; 'Dependencies' = $package.Dependencies.Name; 'Priority' = $priority }
}
$packageNamesSorted = @()
# topologically sort packages, if any packages are present
if ($packageNodes.Count -gt 0)
{
# sort packages by priority and name
$packagesSorted = @()
$packagesSorted += $packageNodes | Sort-Object @{expression={$_.Priority};Ascending=$true}, @{expression={$_.Index};Ascending=$true}
# topologically sort packages and add package names sorted
TopologicalSort $packagesSorted | ForEach-Object { $packageNamesSorted += $_ }
}
return $packageNamesSorted
}
# get all package dependencies
function GetDependencyPackageNames($hstwb, $package)
{
$dependencyPackageNames = @()
if (!$package.Dependencies)
{
return $dependencyPackageNames
}
foreach($dependencyPackageName in $package.Dependencies.Name)
{
$dependencyPackage = $hstwb.Packages[$dependencyPackageName.ToLower()]
if (!$dependencyPackage)
{
continue
}
$dependencyPackageNames += GetDependencyPackageNames $hstwb $dependencyPackage
$dependencyPackageNames += $dependencyPackage.Name
}
return $dependencyPackageNames
}
function BuildInstallLog($hstwb)
{
$osVersion = Get-CimInstance Win32_OperatingSystem | Select-Object Caption | ForEach-Object { $_.Caption }
$osArchitecture = Get-CimInstance Win32_OperatingSystem | Select-Object OSArchitecture | ForEach-Object { $_.OSArchitecture }
$buildNumber = Get-CimInstance Win32_OperatingSystem | Select-Object BuildNumber | ForEach-Object { $_.BuildNumber }
$powershellVersion = Get-Host | Select-Object Version | ForEach-Object { $_.Version }
$installLogLines = New-Object System.Collections.Generic.List[System.Object]
$installLogLines.Add('HstWB Installer')
$installLogLines.Add('---------------')
$installLogLines.Add('Author: Henrik Noerfjand Stengaard')
$installLogLines.Add('Date: {0}' -f (Get-Date -format "yyyy-MM-dd HH:mm:ss"))
$installLogLines.Add('')
$installLogLines.Add('System')
$installLogLines.Add(("- OS: '{0} {1} ({2})'" -f $osVersion, $osArchitecture, $buildNumber))
$installLogLines.Add("- Powershell: '{0}'" -f $powershellVersion)
$installLogLines.Add("- HstWB Installer: 'v{0}'" -f $hstwb.Version)
$installLogLines.Add('')
$installLogLines.Add('Settings')
$installLogLines.Add("- Settings File: '{0}'" -f $hstwb.Paths.SettingsFile)
$installLogLines.Add("- Assigns File: '{0}'" -f $hstwb.Paths.AssignsFile)
$installLogLines.Add('Image')
$installLogLines.Add("- Image Dir: '{0}'" -f $hstwb.Settings.Image.ImageDir)
$installLogLines.Add('Amiga OS')
$installLogLines.Add("- Install Amiga OS: '{0}'" -f $hstwb.Settings.AmigaOs.InstallAmigaOs)
$installLogLines.Add("- Amiga OS dir: '{0}'" -f $hstwb.Settings.AmigaOs.AmigaOsDir)
$amigaOsSet = @()
$amigaOsSetFiles = @()
if ($hstwb.Settings.AmigaOs.AmigaOsSet -notmatch '^$')
{
$amigaOsSet += $hstwb.AmigaOsEntries | Where-Object { $_.Set -eq $hstwb.Settings.AmigaOs.AmigaOsSet }
$amigaOsSetFiles += $amigaOsSet | Where-Object { $_.File }
}
$installLogLines.Add(("- Amiga OS set: '{0}' ({1}/{2})" -f $hstwb.Settings.AmigaOs.AmigaOsSet, $amigaOsSetFiles.Count, $workbenchAdfSetHashes.Count))
for ($i = 0; $i -lt $amigaOsSetFiles.Count; $i++)
{
$installLogLines.Add(("- Amiga OS set file {0}/{1}: '{2}' = '{3}'" -f ($i + 1), $amigaOsSetFiles.Count, $amigaOsSetFiles[$i].Filename, $amigaOsSetFiles[$i].File))
}
$installLogLines.Add('Kickstart')
$installLogLines.Add("- Install Kickstart: '{0}'" -f $hstwb.Settings.Kickstart.InstallKickstart)
$installLogLines.Add("- Kickstart dir: '{0}'" -f $hstwb.Settings.Kickstart.KickstartDir)
$kickstartRomSetHashes = @()
$kickstartRomSetFiles = @()
if ($hstwb.Settings.Kickstart.KickstartSet -notmatch '^$')
{
$kickstartRomSetHashes += $hstwb.KickstartEntries | Where-Object { $_.Set -eq $hstwb.Settings.Kickstart.KickstartSet }
$kickstartRomSetFiles += $kickstartRomSetHashes | Where-Object { $_.File }
}
$installLogLines.Add(("- Kickstart set: '{0}' ({1}/{2})" -f $hstwb.Settings.Kickstart.KickstartSet, $kickstartRomSetFiles.Count, $kickstartRomSetHashes.Count))
for ($i = 0; $i -lt $kickstartRomSetFiles.Count; $i++)
{
$installLogLines.Add(("- Kickstart set file {0}/{1}: '{2}' = '{3}'" -f ($i + 1), $kickstartRomSetFiles.Count, $kickstartRomSetFiles[$i].Filename, $kickstartRomSetFiles[$i].File))
}
$installLogLines.Add('Packages')
# get install packages
$installPackageIndex = @{}
foreach($installPackageKey in ($hstwb.Settings.Packages.Keys | Where-Object { $_ -match 'InstallPackage\d+' }))
{
$installPackageIndex.Set_Item($hstwb.Settings.Packages[$installPackageKey].ToLower(), $true)
}
$packageNames = @()
$packageNames += SortPackageNames $hstwb | ForEach-Object { $_.ToLower() }
$installPackageNames = @()
$installPackageNames += $packageNames | Where-Object { $installPackageIndex.ContainsKey($_) }
for ($i = 0; $i -lt $installPackageNames.Count; $i++)
{
$installLogLines.Add(("- Install Package {0}/{1}: '{2}'" -f ($i + 1), $installPackageNames.Count, $installPackageNames[$i]))
}
$installLogLines.Add('User Packages')
if ($hstwb.Settings.UserPackages.UserPackagesDir -and (Test-Path -Path $hstwb.Settings.UserPackages.UserPackagesDir))
{
$installLogLines.Add("- User Packages Dir: '{0}'" -f $hstwb.Settings.UserPackages.UserPackagesDir)
}
else
{
$installLogLines.Add("- User Packages Dir: ''")
}
# get install user packages
$installUserPackageNames = @()
foreach($installUserPackageKey in ($hstwb.Settings.UserPackages.Keys | Where-Object { $_ -match 'InstallUserPackage\d+' }))
{
$userPackageName = $hstwb.Settings.UserPackages.Get_Item($installUserPackageKey.ToLower())
$userPackage = $hstwb.UserPackages.Get_Item($userPackageName)
$installUserPackageNames += $userPackage.Name
}
for ($i = 0; $i -lt $installUserPackageNames.Count; $i++)
{
$installLogLines.Add(("- Install User Package {0}/{1}: '{2}'" -f ($i + 1), $installUserPackageNames.Count, $installUserPackageNames[$i]))
}
$installLogLines.Add("Emulator")
$emulatorFile = ''
if ($hstwb.Settings.Emulator.EmulatorFile -and (Test-Path -Path $hstwb.Settings.Emulator.EmulatorFile))
{
$emulatorName = DetectEmulatorName $hstwb.Settings.Emulator.EmulatorFile
if ($emulatorName)
{
$emulatorFile = "{0} ({1})" -f $emulatorName, $hstwb.Settings.Emulator.EmulatorFile
}
else
{
$emulatorFile = $hstwb.Settings.Emulator.EmulatorFile
}
}
$installLogLines.Add("- Emulator File: '{0}'" -f $emulatorFile)
$installLogLines.Add("Installer")
$installerMode = ''
switch ($hstwb.Settings.Installer.Mode)
{
"Test" { $installerMode = "Test" }
"Install" { $installerMode = "Install" }
"BuildSelfInstall" { $installerMode = "Build Self Install" }
"BuildPackageInstallation" { $installerMode = "Build Package Installation" }
"BuildUserPackageInstallation" { $installerMode = "Build User Package Installation" }
}
$installLogLines.Add("- Mode: '{0}'" -f $installerMode)
return $installLogLines.ToArray()
} | {'content_hash': '2f88beef25f7d3e0b2211324ba1e3fac', 'timestamp': '', 'source': 'github', 'line_count': 1097, 'max_line_length': 249, 'avg_line_length': 32.715587967183225, 'alnum_prop': 0.6134191535010728, 'repo_name': 'henrikstengaard/hstwb-installer', 'id': '285087b6b9d7e14c9caec3164d86632a42052543', 'size': '36081', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/data.psm1', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '110722'}, {'name': 'Batchfile', 'bytes': '1138'}, {'name': 'C', 'bytes': '33330'}, {'name': 'C#', 'bytes': '542490'}, {'name': 'CSS', 'bytes': '16926'}, {'name': 'HTML', 'bytes': '2667'}, {'name': 'JavaScript', 'bytes': '148645'}, {'name': 'PowerShell', 'bytes': '536291'}, {'name': 'Python', 'bytes': '139726'}, {'name': 'Roff', 'bytes': '331079'}, {'name': 'Shell', 'bytes': '157610'}]} |
"""Test the ibeacon init."""
import pytest
from homeassistant.components.ibeacon.const import DOMAIN
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from . import BLUECHARM_BEACON_SERVICE_INFO
from tests.common import MockConfigEntry
from tests.components.bluetooth import inject_bluetooth_service_info
@pytest.fixture(autouse=True)
def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth."""
async def remove_device(ws_client, device_id, config_entry_id):
"""Remove config entry from a device."""
await ws_client.send_json(
{
"id": 5,
"type": "config/device_registry/remove_config_entry",
"config_entry_id": config_entry_id,
"device_id": device_id,
}
)
response = await ws_client.receive_json()
return response["success"]
async def test_device_remove_devices(hass, hass_ws_client):
"""Test we can only remove a device that no longer exists."""
entry = MockConfigEntry(
domain=DOMAIN,
)
entry.add_to_hass(hass)
assert await async_setup_component(hass, "config", {})
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
inject_bluetooth_service_info(hass, BLUECHARM_BEACON_SERVICE_INFO)
await hass.async_block_till_done()
device_registry = dr.async_get(hass)
device_entry = device_registry.async_get_device(
{
(
DOMAIN,
"426c7565-4368-6172-6d42-6561636f6e73_3838_4949_61DE521B-F0BF-9F44-64D4-75BBE1738105",
)
},
{},
)
assert (
await remove_device(await hass_ws_client(hass), device_entry.id, entry.entry_id)
is False
)
dead_device_entry = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, "not_seen")},
)
assert (
await remove_device(
await hass_ws_client(hass), dead_device_entry.id, entry.entry_id
)
is True
)
| {'content_hash': '563559de77bdeec643a2b961409acb83', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 102, 'avg_line_length': 29.857142857142858, 'alnum_prop': 0.6468899521531101, 'repo_name': 'mezz64/home-assistant', 'id': 'a04799e3cd4d1e732ba55dbe15402eb945906830', 'size': '2090', 'binary': False, 'copies': '3', 'ref': 'refs/heads/dev', 'path': 'tests/components/ibeacon/test_init.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2963'}, {'name': 'PLSQL', 'bytes': '840'}, {'name': 'Python', 'bytes': '52481895'}, {'name': 'Shell', 'bytes': '6252'}]} |
namespace Go {
class Board;
}
namespace AI {
class HistoryHeuristics {
public:
enum WEIGHT_TYPE {
HISTOGRAM, SQUARE_DEPTH, TWO_POWER_DEPTH
};
public:
explicit HistoryHeuristics(size_t historySize, WEIGHT_TYPE type = HISTOGRAM, int maxDepthFromRoot = 10, int initialValue = 0);
~HistoryHeuristics();
void setHistogramAddValue(double value) {m_histogramAddValue = value;};
void recordHistory(Common::Point move, Common::Color color, int depthFromRoot);
void clearHistory(Common::Color player, double clearValue = 0);
inline size_t getTableSize() const {return m_historyMovesSize;}
inline double getHistoryValue(Common::Point move, Common::Color player) const {
assert(move>=0 && move<(signed)m_historyMovesSize);
assert(player>=0 && player < (signed)Common::COLOR_NUM);
return m_historyMoves[player][move];
}
void showTable(Common::Color color, Go::Board *board) const;
private:
private:
double **m_historyMoves;
size_t m_historyMovesSize;
WEIGHT_TYPE m_type;
int m_depthThresholdFromRoot;
double m_histogramAddValue;
};
}
| {'content_hash': 'ab4b8ff608494b387f297a12248b3df2', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 130, 'avg_line_length': 27.926829268292682, 'alnum_prop': 0.6899563318777293, 'repo_name': 'omochi64/ComputerGO_MCTS', 'id': '0d16287ba4bb6d162cbc9fa2980123b6aeb306d4', 'size': '1160', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AI/HistoryHeuristics.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '631394'}, {'name': 'Makefile', 'bytes': '15419'}, {'name': 'Shell', 'bytes': '3935'}]} |
package eu.inloop.knight.sample.presenter;
import android.app.Application;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Singleton;
import de.greenrobot.event.EventBus;
import eu.inloop.knight.As;
import eu.inloop.knight.BasePresenter;
import eu.inloop.knight.ScreenProvided;
import eu.inloop.knight.sample.R;
import eu.inloop.knight.sample.bus.ContactListEvent;
import eu.inloop.knight.sample.bus.NewContactEvent;
import eu.inloop.knight.sample.model.Contact;
import eu.inloop.knight.sample.model.Items;
import eu.inloop.knight.sample.model.api.ApiCallback;
import eu.inloop.knight.sample.model.api.ApiError;
import eu.inloop.knight.sample.model.api.IApi;
import eu.inloop.knight.sample.util.NetUtils;
import eu.inloop.knight.sample.view.IContactListView;
import eu.inloop.knight.sample.view.activity.ContactListActivity;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Class {@link ContactListPresenter}.
*
* @author f3rog
* @version 2015-07-09
*/
public class ContactListPresenter
extends BasePresenter<IContactListView>
implements IContactListPresenter {
private final Application mApp;
private final NetUtils mNetUtils;
private final IApi mApi;
private final EventBus mEventBus;
private List<Contact> mContacts;
private boolean mLoading;
/**
* Constructor
*/
@ScreenProvided(ContactListActivity.class)
@Singleton
@As(IContactListPresenter.class)
public ContactListPresenter(Application app, NetUtils utils, IApi api, EventBus eventBus) {
mApp = app;
mNetUtils = utils;
mApi = api;
mEventBus = eventBus;
mContacts = new ArrayList<>();
mEventBus.registerSticky(this);
}
@Override
public void onRemove() {
super.onRemove();
mEventBus.unregister(this);
}
@Override
public void onAddClicked() {
if (getView() != null) getView().gotoAddContactView();
}
@Override
public void onContactClicked(int position) {
// just to make sure
if (position < 0 || position >= mContacts.size()) {
if (getView() != null) getView().refreshContacts();
return;
}
if (getView() != null) getView().gotoContactDetailView(mContacts.get(position));
}
@Override
public void onCreate(@Nullable Bundle savedState) {
super.onCreate(savedState);
downloadContacts();
}
@Override
public void onBindView(@NonNull IContactListView view) {
super.onBindView(view);
view.initContacts(mContacts);
view.showLoading(mLoading);
if (!mNetUtils.isNetworkAvailable()) {
view.show(mApp.getString(R.string.err_no_connection));
}
}
private void setLoading(boolean loading) {
mLoading = loading;
if (getView() != null) getView().showLoading(mLoading);
}
/**
* Gets contact list form API. (If offline then from Cache)
*/
private void downloadContacts() {
setLoading(true);
mApi.getContacts(new ApiCallback<Items<Contact>>() {
@Override
public void onSuccess(Items<Contact> contactItems, Response response) {
mContacts.clear();
mContacts.addAll(contactItems.getItems());
Collections.sort(mContacts);
if (getView() != null) {
setLoading(false);
getView().refreshContacts();
}
}
@Override
public void onFailure(ApiError apiError, RetrofitError error) {
if (getView() != null) {
setLoading(false);
if (apiError != null) {
getView().show(apiError.getError().getMessage());
}
}
}
});
}
//region EventBus Events
public void onEventBackgroundThread(NewContactEvent event) {
mContacts.add(event.getContact());
Collections.sort(mContacts);
mEventBus.post(ContactListEvent.REFRESH);
mEventBus.removeStickyEvent(NewContactEvent.class);
}
public void onEventMainThread(ContactListEvent event) {
if (event == ContactListEvent.REFRESH && getView() != null) {
getView().refreshContacts();
}
}
//endregion
@Override
public String getId() {
return null;
}
}
| {'content_hash': '12c3cd5b5bf53278d35cef0af8d30bb0', 'timestamp': '', 'source': 'github', 'line_count': 161, 'max_line_length': 95, 'avg_line_length': 28.70807453416149, 'alnum_prop': 0.6395499783643445, 'repo_name': 'inloop/Knight', 'id': '058708273011458eb40f13aa49242b10704d05a1', 'size': '4622', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'knight-sample/src/main/java/eu/inloop/knight/sample/presenter/ContactListPresenter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '6763'}, {'name': 'Java', 'bytes': '210373'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Grav\Common\File | Grav API</title>
<link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="../../css/sami.css">
<script src="../../js/jquery-1.11.1.min.js"></script>
<script src="../../js/bootstrap.min.js"></script>
<script src="../../js/typeahead.min.js"></script>
<script src="../../sami.js"></script>
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
</head>
<body id="namespace" data-name="namespace:Grav_Common_File" data-root-path="../../">
<div id="content">
<div id="left-column">
<div id="control-panel">
<form id="search-form" action="../../search.html" method="GET">
<span class="glyphicon glyphicon-search"></span>
<input name="search"
class="typeahead form-control"
type="search"
placeholder="Search">
</form>
</div>
<div id="api-tree"></div>
</div>
<div id="right-column">
<nav id="site-nav" class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../index.html">Grav API</a>
</div>
<div class="collapse navbar-collapse" id="navbar-elements">
<ul class="nav navbar-nav">
<li><a href="../../classes.html">Classes</a></li>
<li><a href="../../namespaces.html">Namespaces</a></li>
<li><a href="../../interfaces.html">Interfaces</a></li>
<li><a href="../../traits.html">Traits</a></li>
<li><a href="../../doc-index.html">Index</a></li>
<li><a href="../../search.html">Search</a></li>
</ul>
</div>
</div>
</nav>
<div class="namespace-breadcrumbs">
<ol class="breadcrumb">
<li><span class="label label-default">Namespace</span></li>
<li><a href="../../Grav.html">Grav</a></li>
<li><a href="../../Grav/Common.html">Common</a></li>
<li><a href="../../Grav/Common/File.html">File</a></li>
</ol>
</div>
<div id="page-content">
<div class="page-header">
<h1>Grav\Common\File</h1>
</div>
<h2>Classes</h2>
<div class="container-fluid underlined">
<div class="row">
<div class="col-md-6">
<a href="../../Grav/Common/File/CompiledFile.html"><abbr title="Grav\Common\File\CompiledFile">Grav\Common\File\CompiledFile</abbr></a>
</div>
<div class="col-md-6">
Class CompiledFile
</div>
</div>
<div class="row">
<div class="col-md-6">
<a href="../../Grav/Common/File/CompiledMarkdownFile.html"><abbr title="Grav\Common\File\CompiledMarkdownFile">Grav\Common\File\CompiledMarkdownFile</abbr></a>
</div>
<div class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<a href="../../Grav/Common/File/CompiledYamlFile.html"><abbr title="Grav\Common\File\CompiledYamlFile">Grav\Common\File\CompiledYamlFile</abbr></a>
</div>
<div class="col-md-6">
</div>
</div>
</div>
</div>
<div id="footer">
Generated on December 8th at 8:01pm by <a href="http://sami.sensiolabs.org/">Sami</a>
</div>
</div>
</div>
</body>
</html>
| {'content_hash': '4a9c1f4ad4c1e6e2adedc06586f81375', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 203, 'avg_line_length': 41.554621848739494, 'alnum_prop': 0.4501516683518706, 'repo_name': 'getgrav/grav-api', 'id': 'a73f25757fece79201fbd9b48f37f0b5afd5f1cf', 'size': '4945', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'api/Grav/Common/File.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6417'}, {'name': 'HTML', 'bytes': '5595444'}, {'name': 'PHP', 'bytes': '649'}, {'name': 'Shell', 'bytes': '66'}]} |
package org.ethereum.net.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultMessageSizeEstimator;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.ethereum.net.PeerListener;
import org.ethereum.net.p2p.HelloMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.ethereum.config.SystemProperties.CONFIG;
/**
* This class establish a listener for incoming connections
* @see <a href="http://netty.io">http://netty.io</a>
*
* www.etherj.com
*
* @author: Roman Mandeleil
* Created on: 01/11/2014 10:11
*/
public class PeerServer {
private static final Logger logger = LoggerFactory.getLogger("net");
private PeerListener peerListener;
Timer inactivesCollector = new Timer("inactivesCollector");
private boolean peerDiscoveryMode = false;
List<Channel> channels = Collections.synchronizedList(new ArrayList<Channel>());
public PeerServer() {
}
public PeerServer(PeerListener peerListener) {
this();
this.peerListener = peerListener;
}
public void start(int port) {
inactivesCollector.scheduleAtFixedRate(new TimerTask() {
public void run() {
Iterator<Channel> iter = channels.iterator();
while(iter.hasNext()){
Channel channel = iter.next();
if(!channel.p2pHandler.isActive()){
iter.remove();
logger.info("Channel removed: {}", channel.p2pHandler.getHandshakeHelloMessage());
}
}
}
}, 2000, 5000);
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
if (peerListener != null)
peerListener.console("Listening on port " + port);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout());
b.handler(new LoggingHandler());
b.childHandler(new EthereumChannelInitializer(this));
// Start the client.
logger.info("Listening for incoming connections, port: [{}] ", port);
ChannelFuture f = b.bind(port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
logger.debug("Connection is closed");
} catch (Exception e) {
logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
throw new Error("Server Disconnnected");
} finally {
workerGroup.shutdownGracefully();
}
}
public void setPeerListener(PeerListener peerListener) {
this.peerListener = peerListener;
}
synchronized public void addChannel(Channel channel){
channels.add(channel);
}
}
| {'content_hash': '24d99480f2f3911b61a2e9db804b7e39', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 106, 'avg_line_length': 29.973684210526315, 'alnum_prop': 0.6438396254023998, 'repo_name': 'ethereumj/ethereumj', 'id': '93411d6d6598d6b4a76a8c0aff9a2ecfc9796258', 'size': '3417', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '5419'}, {'name': 'Java', 'bytes': '1249369'}, {'name': 'Shell', 'bytes': '2463'}]} |
namespace llvm {
class GlobalValue;
class StringRef;
class SystemZSubtarget : public SystemZGenSubtargetInfo {
virtual void anchor();
protected:
bool HasDistinctOps;
bool HasLoadStoreOnCond;
bool HasHighWord;
bool HasFPExtension;
bool HasFastSerialization;
bool HasInterlockedAccess1;
private:
Triple TargetTriple;
SystemZInstrInfo InstrInfo;
SystemZTargetLowering TLInfo;
SystemZSelectionDAGInfo TSInfo;
SystemZFrameLowering FrameLowering;
SystemZSubtarget &initializeSubtargetDependencies(StringRef CPU,
StringRef FS);
public:
SystemZSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, const TargetMachine &TM);
const TargetFrameLowering *getFrameLowering() const override {
return &FrameLowering;
}
const SystemZInstrInfo *getInstrInfo() const override { return &InstrInfo; }
const SystemZRegisterInfo *getRegisterInfo() const override {
return &InstrInfo.getRegisterInfo();
}
const SystemZTargetLowering *getTargetLowering() const override {
return &TLInfo;
}
const TargetSelectionDAGInfo *getSelectionDAGInfo() const override {
return &TSInfo;
}
// This is important for reducing register pressure in vector code.
bool useAA() const override { return true; }
// Automatically generated by tblgen.
void ParseSubtargetFeatures(StringRef CPU, StringRef FS);
// Return true if the target has the distinct-operands facility.
bool hasDistinctOps() const { return HasDistinctOps; }
// Return true if the target has the load/store-on-condition facility.
bool hasLoadStoreOnCond() const { return HasLoadStoreOnCond; }
// Return true if the target has the high-word facility.
bool hasHighWord() const { return HasHighWord; }
// Return true if the target has the floating-point extension facility.
bool hasFPExtension() const { return HasFPExtension; }
// Return true if the target has the fast-serialization facility.
bool hasFastSerialization() const { return HasFastSerialization; }
// Return true if the target has interlocked-access facility 1.
bool hasInterlockedAccess1() const { return HasInterlockedAccess1; }
// Return true if GV can be accessed using LARL for reloc model RM
// and code model CM.
bool isPC32DBLSymbol(const GlobalValue *GV, Reloc::Model RM,
CodeModel::Model CM) const;
bool isTargetELF() const { return TargetTriple.isOSBinFormatELF(); }
};
} // end namespace llvm
#endif
| {'content_hash': '30891a3991d81b5ec2c4e63100aefc90', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 78, 'avg_line_length': 33.77333333333333, 'alnum_prop': 0.7358863008290565, 'repo_name': 'impedimentToProgress/Ratchet', 'id': '99cb1ad30450ced7dcb25ac15f6eb145bf0d9fac', 'size': '3506', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'llvm/lib/Target/SystemZ/SystemZSubtarget.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '7704512'}, {'name': 'Batchfile', 'bytes': '13322'}, {'name': 'C', 'bytes': '781703'}, {'name': 'C++', 'bytes': '43693178'}, {'name': 'CMake', 'bytes': '255669'}, {'name': 'CSS', 'bytes': '9266'}, {'name': 'Emacs Lisp', 'bytes': '11520'}, {'name': 'Go', 'bytes': '131716'}, {'name': 'LLVM', 'bytes': '30529312'}, {'name': 'M4', 'bytes': '97430'}, {'name': 'Makefile', 'bytes': '287076'}, {'name': 'OCaml', 'bytes': '401181'}, {'name': 'Objective-C', 'bytes': '392650'}, {'name': 'Perl', 'bytes': '27878'}, {'name': 'Python', 'bytes': '512356'}, {'name': 'Roff', 'bytes': '18799'}, {'name': 'Shell', 'bytes': '120669'}, {'name': 'SourcePawn', 'bytes': '2461'}, {'name': 'Standard ML', 'bytes': '2841'}, {'name': 'Vim script', 'bytes': '13485'}]} |
require.config({
baseUrl: "/javascripts",
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery : "lib/jquery.min",
bootstrap : "lib/bootstrap.min",
requireLib : "lib/require.min",
Handlebars : "lib/handlebars",
Backbone : "lib/backbone.min",
text : "lib/text",
underscore : "lib/underscore.min",
jStorage : "lib/jstorage",
typeahead : "lib/typeahead",
moment : "lib/moment",
"jquery.fileupload": "lib/jquery-file-upload/jquery.fileupload",
"jquery.ui.widget" : "lib/jquery-file-upload/jquery.ui.widget",
"jquery.iframe-transport" : "lib/jquery-file-upload/jquery.iframe-transport",
"jquery.fileupload-ui": "lib/jquery-file-upload/jquery.fileupload-ui",
"jquery.fileupload-image": "lib/jquery-file-upload/jquery.fileupload-image",
common : "app/modules/common/main",
accountsModel : "app/modules/accounts/models/accountsModel",
accountTokenModel: "app/modules/accounts/models/accountTokenModel",
// collections
pluginCollection : "app/modules/plugins/collections/pluginCollection",
// views
pluginsMenuView : "app/modules/common/views/pluginsMenu",
pluginsMenuItemView: "app/modules/common/views/pluginsMenuItem",
menuSearchView : "app/modules/common/views/menuSearchView",
profileView : "app/modules/accounts/profile/views/profileView",
sessionInfoHeaderItemView: "app/modules/session/views/sessionInfoHeaderItemView"
},
shim: {
bootstrap: {
deps: ['jquery']
},
Handlebars: {
exports: 'Handlebars'
},
Backbone: {
exports: 'Backbone',
deps : ['jquery', 'underscore']
},
underscore: {
exports: '_'
},
jStorage: {
deps: ['jquery']
},
profileView: {
deps: ['Backbone']
},
"jquery.fileupload": {
deps: ["jquery.iframe-transport", "jquery.ui.widget", 'jquery']
},
'jquery.fileupload-ui': {
deps: ["jquery.fileupload-image"]
}
}
});
require(["jquery", "common", "profileView"], function ($, common, profileView) {
$(function () {
new profileView();
});
});
| {'content_hash': '9f8808084e20219f89bcb346c4cba602', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 88, 'avg_line_length': 31.670886075949365, 'alnum_prop': 0.5415667466027179, 'repo_name': 'prgmrbill/guacbot-salsa', 'id': '487de170f281dbf739ddca3efbe276dbb8824f85', 'size': '2504', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'public/javascripts/app/modules/accounts/profile/main.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '212312'}, {'name': 'JavaScript', 'bytes': '590941'}]} |
package org.spongycastle.pqc.jcajce.provider.mceliece;
import java.io.IOException;
import java.security.PrivateKey;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Primitive;
import org.spongycastle.asn1.DERNull;
import org.spongycastle.asn1.pkcs.PrivateKeyInfo;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.pqc.asn1.McEliecePrivateKey;
import org.spongycastle.pqc.crypto.mceliece.McElieceKeyPairGenerator;
import org.spongycastle.pqc.crypto.mceliece.McElieceParameters;
import org.spongycastle.pqc.crypto.mceliece.McEliecePrivateKeyParameters;
import org.spongycastle.pqc.jcajce.spec.McEliecePrivateKeySpec;
import org.spongycastle.pqc.math.linearalgebra.GF2Matrix;
import org.spongycastle.pqc.math.linearalgebra.GF2mField;
import org.spongycastle.pqc.math.linearalgebra.Permutation;
import org.spongycastle.pqc.math.linearalgebra.PolynomialGF2mSmallM;
/**
* This class implements a McEliece private key and is usually instantiated by
* the {@link McElieceKeyPairGenerator} or {@link McElieceKeyFactorySpi}.
*/
public class BCMcEliecePrivateKey
implements CipherParameters, PrivateKey
{
/**
*
*/
private static final long serialVersionUID = 1L;
// the OID of the algorithm
private String oid;
// the length of the code
private int n;
// the dimension of the code, where <tt>k >= n - mt</tt>
private int k;
// the underlying finite field
private GF2mField field;
// the irreducible Goppa polynomial
private PolynomialGF2mSmallM goppaPoly;
// the matrix S^-1
private GF2Matrix sInv;
// the permutation P1 used to generate the systematic check matrix
private Permutation p1;
// the permutation P2 used to compute the public generator matrix
private Permutation p2;
// the canonical check matrix of the code
private GF2Matrix h;
// the matrix used to compute square roots in <tt>(GF(2^m))^t</tt>
private PolynomialGF2mSmallM[] qInv;
private McElieceParameters mcElieceParams;
/**
* Constructor (used by the {@link McElieceKeyPairGenerator}).
*
* @param oid
* @param n the length of the code
* @param k the dimension of the code
* @param field the field polynomial defining the finite field
* <tt>GF(2<sup>m</sup>)</tt>
* @param goppaPoly the irreducible Goppa polynomial
* @param sInv the matrix <tt>S<sup>-1</sup></tt>
* @param p1 the permutation used to generate the systematic check
* matrix
* @param p2 the permutation used to compute the public generator
* matrix
* @param h the canonical check matrix
* @param qInv the matrix used to compute square roots in
* <tt>(GF(2<sup>m</sup>))<sup>t</sup></tt>
*/
public BCMcEliecePrivateKey(String oid, int n, int k, GF2mField field,
PolynomialGF2mSmallM goppaPoly, GF2Matrix sInv, Permutation p1,
Permutation p2, GF2Matrix h, PolynomialGF2mSmallM[] qInv)
{
this.oid = oid;
this.n = n;
this.k = k;
this.field = field;
this.goppaPoly = goppaPoly;
this.sInv = sInv;
this.p1 = p1;
this.p2 = p2;
this.h = h;
this.qInv = qInv;
}
/**
* Constructor (used by the {@link McElieceKeyFactorySpi}).
*
* @param keySpec a {@link McEliecePrivateKeySpec}
*/
public BCMcEliecePrivateKey(McEliecePrivateKeySpec keySpec)
{
this(keySpec.getOIDString(), keySpec.getN(), keySpec.getK(), keySpec.getField(), keySpec
.getGoppaPoly(), keySpec.getSInv(), keySpec.getP1(), keySpec
.getP2(), keySpec.getH(), keySpec.getQInv());
}
public BCMcEliecePrivateKey(McEliecePrivateKeyParameters params)
{
this(params.getOIDString(), params.getN(), params.getK(), params.getField(), params.getGoppaPoly(),
params.getSInv(), params.getP1(), params.getP2(), params.getH(), params.getQInv());
this.mcElieceParams = params.getParameters();
}
/**
* Return the name of the algorithm.
*
* @return "McEliece"
*/
public String getAlgorithm()
{
return "McEliece";
}
/**
* @return the length of the code
*/
public int getN()
{
return n;
}
/**
* @return the dimension of the code
*/
public int getK()
{
return k;
}
/**
* @return the finite field
*/
public GF2mField getField()
{
return field;
}
/**
* @return the irreducible Goppa polynomial
*/
public PolynomialGF2mSmallM getGoppaPoly()
{
return goppaPoly;
}
/**
* @return the k x k random binary non-singular matrix S
*/
public GF2Matrix getSInv()
{
return sInv;
}
/**
* @return the permutation used to generate the systematic check matrix
*/
public Permutation getP1()
{
return p1;
}
/**
* @return the permutation used to compute the public generator matrix
*/
public Permutation getP2()
{
return p2;
}
/**
* @return the canonical check matrix
*/
public GF2Matrix getH()
{
return h;
}
/**
* @return the matrix for computing square roots in <tt>(GF(2^m))^t</tt>
*/
public PolynomialGF2mSmallM[] getQInv()
{
return qInv;
}
/**
* @return the OID of the algorithm
*/
public String getOIDString()
{
return oid;
}
/**
* @return a human readable form of the key
*/
public String toString()
{
String result = " length of the code : " + n + "\n";
result += " dimension of the code : " + k + "\n";
result += " irreducible Goppa polynomial: " + goppaPoly + "\n";
result += " (k x k)-matrix S^-1 : " + sInv + "\n";
result += " permutation P1 : " + p1 + "\n";
result += " permutation P2 : " + p2;
return result;
}
/**
* Compare this key with another object.
*
* @param other the other object
* @return the result of the comparison
*/
public boolean equals(Object other)
{
if (!(other instanceof BCMcEliecePrivateKey))
{
return false;
}
BCMcEliecePrivateKey otherKey = (BCMcEliecePrivateKey)other;
return (n == otherKey.n) && (k == otherKey.k)
&& field.equals(otherKey.field)
&& goppaPoly.equals(otherKey.goppaPoly)
&& sInv.equals(otherKey.sInv) && p1.equals(otherKey.p1)
&& p2.equals(otherKey.p2) && h.equals(otherKey.h);
}
/**
* @return the hash code of this key
*/
public int hashCode()
{
return k + n + field.hashCode() + goppaPoly.hashCode()
+ sInv.hashCode() + p1.hashCode() + p2.hashCode()
+ h.hashCode();
}
/**
* @return the OID to encode in the SubjectPublicKeyInfo structure
*/
protected ASN1ObjectIdentifier getOID()
{
return new ASN1ObjectIdentifier(McElieceKeyFactorySpi.OID);
}
/**
* @return the algorithm parameters to encode in the SubjectPublicKeyInfo
* structure
*/
protected ASN1Primitive getAlgParams()
{
return null; // FIXME: needed at all?
}
/**
* Return the key data to encode in the SubjectPublicKeyInfo structure.
* <p>
* The ASN.1 definition of the key structure is
* <p>
* <pre>
* McEliecePrivateKey ::= SEQUENCE {
* n INTEGER -- length of the code
* k INTEGER -- dimension of the code
* fieldPoly OCTET STRING -- field polynomial defining GF(2ˆm)
* goppaPoly OCTET STRING -- irreducible Goppa polynomial
* sInv OCTET STRING -- matrix Sˆ-1
* p1 OCTET STRING -- permutation P1
* p2 OCTET STRING -- permutation P2
* h OCTET STRING -- canonical check matrix
* qInv SEQUENCE OF OCTET STRING -- matrix used to compute square roots
* }
* </pre>
* </p>
*
* @return the key data to encode in the SubjectPublicKeyInfo structure
*/
public byte[] getEncoded()
{
McEliecePrivateKey privateKey = new McEliecePrivateKey(new ASN1ObjectIdentifier(oid), n, k, field, goppaPoly, sInv, p1, p2, h, qInv);
PrivateKeyInfo pki;
try
{
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(this.getOID(), DERNull.INSTANCE);
pki = new PrivateKeyInfo(algorithmIdentifier, privateKey);
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
try
{
byte[] encoded = pki.getEncoded();
return encoded;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
public String getFormat()
{
// TODO Auto-generated method stub
return null;
}
public McElieceParameters getMcElieceParameters()
{
return mcElieceParams;
}
}
| {'content_hash': 'e42eeaa78a18d18b66d69a7f432f505f', 'timestamp': '', 'source': 'github', 'line_count': 335, 'max_line_length': 141, 'avg_line_length': 28.6955223880597, 'alnum_prop': 0.5878497867471133, 'repo_name': 'lesstif/spongycastle', 'id': '06b06466b4c2ba609ab8aeea243268329e3e76af', 'size': '9613', 'binary': False, 'copies': '6', 'ref': 'refs/heads/spongy-master', 'path': 'prov/src/main/java/org/spongycastle/pqc/jcajce/provider/mceliece/BCMcEliecePrivateKey.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '54207'}, {'name': 'Java', 'bytes': '22605685'}, {'name': 'Shell', 'bytes': '74632'}]} |
package it.unitn.ing.rista.diffr.data;
import it.unitn.ing.rista.diffr.*;
import java.lang.*;
/**
* The HIPPODataFile is a class to manage Hippo datafiles.
*
*
* @version $Revision: 1.5 $, $Date: 2006/11/10 09:33:01 $
* @author Luca Lutterotti
* @since JDK1.1
*/
public class HippoDataFile extends GSASDataFile {
/**
* Creates the datafile instance.
*/
public HippoDataFile(XRDcat aobj, String alabel) {
super(aobj, alabel);
identifier = ".hda";
}
/**
* Creates a dummy datafile instance.
*/
public HippoDataFile() {
identifier = ".hda";
}
}
| {'content_hash': 'c6e0bec5a21880e68e5cbb7d36568df0', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 58, 'avg_line_length': 16.52777777777778, 'alnum_prop': 0.6403361344537815, 'repo_name': 'luttero/Maud', 'id': 'd45c93f52ca1a8c42087410eb9ee199cda97a283', 'size': '1450', 'binary': False, 'copies': '1', 'ref': 'refs/heads/version2', 'path': 'src/it/unitn/ing/rista/diffr/data/HippoDataFile.java', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'AGS Script', 'bytes': '114580'}, {'name': 'CSS', 'bytes': '1270'}, {'name': 'HTML', 'bytes': '10108'}, {'name': 'Java', 'bytes': '15463899'}, {'name': 'Objective-C', 'bytes': '103209'}, {'name': 'Roff', 'bytes': '974'}]} |
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Web Application',
// preloading 'log' component
'preload'=>array('log'),
//aliases
'aliases' => array(
// yiistrap configuration
'bootstrap' => realpath(__DIR__ . '/../extensions/bootstrap'), // change if necessary
// yiiwheels configuration
'yiiwheels' => realpath(__DIR__ . '/../extensions/yiiwheels'), // change if necessary
),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*',
'application.modules.auditTrail.models.AuditTrail',
'bootstrap.helpers.TbHtml',
),
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'generatorPaths' => array('bootstrap.gii'),
'class'=>'system.gii.GiiModule',
'password'=>'Enter Your Password Here',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
'auditTrail'=>array(),
'user'=>array(
# encrypting method (php hash function)
'hash' => 'md5',
# send activation email
'sendActivationMail' => true,
# allow access for non-activated users
'loginNotActiv' => false,
# activate user on registration (only sendActivationMail = false)
'activeAfterRegister' => false,
# automatically login from registration
'autoLogin' => true,
# registration path
'registrationUrl' => array('/user/registration'),
# recovery password path
'recoveryUrl' => array('/user/recovery'),
# login form path
'loginUrl' => array('/user/login'),
# page after login
'returnUrl' => array('/user/profile'),
# page after logout
'returnLogoutUrl' => array('/user/login'),
),
'rights'=>array(
'superuserName'=>'Admin', // Name of the role with super user privileges.
'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
'userIdColumn'=>'id', // Name of the user id column in the database.
'userNameColumn'=>'username', // Name of the user name column in the database.
'enableBizRule'=>true, // Whether to enable authorization item business rules.
'enableBizRuleData'=>false, // Whether to enable data for business rules.
'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout'=>'application.views.layouts.main', // Application layout.
'cssFile'=>'rights.css', // Style sheet file to use for Rights.
'install'=>false, // Whether to enable installer.
'debug'=>false, // Whether to enable debug mode.
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'class' => 'RWebUser',
'allowAutoLogin'=>true,
'loginUrl' => array('/user/login'),
),
'authManager'=>array('class' => 'RDbAuthManager',),
// uncomment the following to enable URLs in path-format
// yiistrap configuration
'bootstrap' => array(
'class' => 'bootstrap.components.TbApi',
),
// yiiwheels configuration
'yiiwheels' => array(
'class' => 'yiiwheels.YiiWheels',
),
//file extension
'file'=>array(
'class'=>'application.extensions.file.CFile',
),
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=yii',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => 'tbl_',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'[email protected]',
),
); | {'content_hash': 'e0715abf2b79bcef1c71af635d81d429', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 93, 'avg_line_length': 30.683615819209038, 'alnum_prop': 0.6131467501380962, 'repo_name': 'MahabalixOpen/yii-unchained', 'id': 'fbf47ff26d85beb8eb7758fe818ccc91f01c91bd', 'size': '5431', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'yii-unchained/testdrive/protected/config/main.php', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '634017'}, {'name': 'JavaScript', 'bytes': '10652804'}, {'name': 'PHP', 'bytes': '18388219'}, {'name': 'Shell', 'bytes': '1728'}]} |
using ::testing::_;
using ::testing::Args;
using ::testing::Expectation;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::MakeMatcher;
using ::testing::Matcher;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
using ::testing::Mock;
using ::testing::Return;
namespace media {
namespace {
const std::string kBaselineFrame0 = "bear-320x192-baseline-frame-0.h264";
const std::string kBaselineFrame1 = "bear-320x192-baseline-frame-1.h264";
const std::string kBaselineFrame2 = "bear-320x192-baseline-frame-2.h264";
const std::string kBaselineFrame3 = "bear-320x192-baseline-frame-3.h264";
const std::string kHighFrame0 = "bear-320x192-high-frame-0.h264";
const std::string kHighFrame1 = "bear-320x192-high-frame-1.h264";
const std::string kHighFrame2 = "bear-320x192-high-frame-2.h264";
const std::string kHighFrame3 = "bear-320x192-high-frame-3.h264";
const std::string k10BitFrame0 = "bear-320x180-10bit-frame-0.h264";
const std::string k10BitFrame1 = "bear-320x180-10bit-frame-1.h264";
const std::string k10BitFrame2 = "bear-320x180-10bit-frame-2.h264";
const std::string k10BitFrame3 = "bear-320x180-10bit-frame-3.h264";
const std::string kYUV444Frame = "blackwhite_yuv444p-frame.h264";
// Checks whether the decrypt config in the picture matches the decrypt config
// passed to this matcher.
MATCHER_P(DecryptConfigMatches, decrypt_config, "") {
return arg->decrypt_config()->Matches(*decrypt_config);
}
MATCHER(SubsampleSizeMatches, "Verify subsample sizes match buffer size") {
const size_t buffer_size = ::testing::get<0>(arg);
const std::vector<SubsampleEntry>& subsamples = ::testing::get<1>(arg);
size_t subsample_total_size = 0;
for (const auto& sample : subsamples) {
subsample_total_size += sample.cypher_bytes;
subsample_total_size += sample.clear_bytes;
}
return subsample_total_size == buffer_size;
}
// Emulates encrypted slice header parsing. We don't actually encrypt the data
// so we can easily do this by just parsing it.
H264Decoder::H264Accelerator::Status ParseSliceHeader(
const std::vector<base::span<const uint8_t>>& data,
const std::vector<SubsampleEntry>& subsamples,
const std::vector<uint8_t>& sps_nalu_data,
const std::vector<uint8_t>& pps_nalu_data,
H264SliceHeader* slice_hdr_out) {
EXPECT_TRUE(!sps_nalu_data.empty());
EXPECT_TRUE(!pps_nalu_data.empty());
// Construct the bitstream for parsing.
std::vector<uint8_t> full_data;
const std::vector<uint8_t> start_code = {0u, 0u, 1u};
full_data.insert(full_data.end(), start_code.begin(), start_code.end());
full_data.insert(full_data.end(), sps_nalu_data.begin(), sps_nalu_data.end());
full_data.insert(full_data.end(), start_code.begin(), start_code.end());
full_data.insert(full_data.end(), pps_nalu_data.begin(), pps_nalu_data.end());
for (const auto& span : data) {
full_data.insert(full_data.end(), start_code.begin(), start_code.end());
full_data.insert(full_data.end(), span.begin(), span.end());
}
H264Parser parser;
parser.SetStream(full_data.data(), full_data.size());
while (true) {
H264NALU nalu;
H264Parser::Result res = parser.AdvanceToNextNALU(&nalu);
if (res == H264Parser::kEOStream)
break;
EXPECT_EQ(H264Parser::kOk, res);
switch (nalu.nal_unit_type) {
case H264NALU::kSPS:
int sps_id;
EXPECT_EQ(H264Parser::kOk, parser.ParseSPS(&sps_id));
break;
case H264NALU::kPPS:
int pps_id;
EXPECT_EQ(H264Parser::kOk, parser.ParsePPS(&pps_id));
break;
case H264NALU::kIDRSlice: // fallthrough
case H264NALU::kNonIDRSlice:
EXPECT_EQ(H264Parser::kOk,
parser.ParseSliceHeader(nalu, slice_hdr_out));
slice_hdr_out->full_sample_encryption = true;
break;
}
}
return H264Decoder::H264Accelerator::Status::kOk;
}
class MockH264Accelerator : public H264Decoder::H264Accelerator {
public:
MockH264Accelerator() = default;
MOCK_METHOD0(CreateH264Picture, scoped_refptr<H264Picture>());
MOCK_METHOD1(SubmitDecode, Status(scoped_refptr<H264Picture> pic));
MOCK_METHOD5(ParseEncryptedSliceHeader,
Status(const std::vector<base::span<const uint8_t>>& data,
const std::vector<SubsampleEntry>& subsamples,
const std::vector<uint8_t>& sps_nalu_data,
const std::vector<uint8_t>& pps_nalu_data,
H264SliceHeader* slice_hdr_out));
MOCK_METHOD7(SubmitFrameMetadata,
Status(const H264SPS* sps,
const H264PPS* pps,
const H264DPB& dpb,
const H264Picture::Vector& ref_pic_listp0,
const H264Picture::Vector& ref_pic_listb0,
const H264Picture::Vector& ref_pic_listb1,
scoped_refptr<H264Picture> pic));
MOCK_METHOD8(SubmitSlice,
Status(const H264PPS* pps,
const H264SliceHeader* slice_hdr,
const H264Picture::Vector& ref_pic_list0,
const H264Picture::Vector& ref_pic_list1,
scoped_refptr<H264Picture> pic,
const uint8_t* data,
size_t size,
const std::vector<SubsampleEntry>& subsamples));
MOCK_METHOD1(OutputPicture, bool(scoped_refptr<H264Picture> pic));
MOCK_METHOD2(SetStream,
Status(base::span<const uint8_t> stream,
const DecryptConfig* decrypt_config));
void Reset() override {}
};
// Test H264Decoder by feeding different of h264 frame sequences and make
// sure it behaves as expected.
class H264DecoderTest : public ::testing::Test {
public:
H264DecoderTest() = default;
void SetUp() override;
// Sets the bitstreams to be decoded, frame by frame. The content of each
// file is the encoded bitstream of a single video frame.
void SetInputFrameFiles(const std::vector<std::string>& frame_files);
// Keeps decoding the input bitstream set at |SetInputFrameFiles| until the
// decoder has consumed all bitstreams or returned from
// |H264Decoder::Decode|. If |full_sample_encryption| is true, then it sets
// a DecryptConfig for the the DecoderBuffer that indicates all but the first
// byte are encrypted. Returns the same result as |H264Decoder::Decode|.
AcceleratedVideoDecoder::DecodeResult Decode(
bool full_sample_encryption = false);
protected:
std::unique_ptr<H264Decoder> decoder_;
raw_ptr<MockH264Accelerator> accelerator_;
private:
base::queue<std::string> input_frame_files_;
std::string bitstream_;
scoped_refptr<DecoderBuffer> decoder_buffer_;
};
void H264DecoderTest::SetUp() {
auto mock_accelerator = std::make_unique<MockH264Accelerator>();
accelerator_ = mock_accelerator.get();
decoder_ = std::make_unique<H264Decoder>(std::move(mock_accelerator),
VIDEO_CODEC_PROFILE_UNKNOWN);
// Sets default behaviors for mock methods for convenience.
ON_CALL(*accelerator_, CreateH264Picture()).WillByDefault(Invoke([]() {
return new H264Picture();
}));
ON_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _))
.WillByDefault(Return(H264Decoder::H264Accelerator::Status::kOk));
ON_CALL(*accelerator_, SubmitDecode(_))
.WillByDefault(Return(H264Decoder::H264Accelerator::Status::kOk));
ON_CALL(*accelerator_, OutputPicture(_)).WillByDefault(Return(true));
ON_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _))
.With(Args<6, 7>(SubsampleSizeMatches()))
.WillByDefault(Return(H264Decoder::H264Accelerator::Status::kOk));
ON_CALL(*accelerator_, SetStream(_, _))
.WillByDefault(
Return(H264Decoder::H264Accelerator::Status::kNotSupported));
}
void H264DecoderTest::SetInputFrameFiles(
const std::vector<std::string>& input_frame_files) {
for (auto f : input_frame_files)
input_frame_files_.push(f);
}
AcceleratedVideoDecoder::DecodeResult H264DecoderTest::Decode(
bool full_sample_encryption) {
while (true) {
auto result = decoder_->Decode();
int32_t bitstream_id = 0;
if (result != AcceleratedVideoDecoder::kRanOutOfStreamData ||
input_frame_files_.empty())
return result;
auto input_file = GetTestDataFilePath(input_frame_files_.front());
input_frame_files_.pop();
CHECK(base::ReadFileToString(input_file, &bitstream_));
decoder_buffer_ = DecoderBuffer::CopyFrom(
reinterpret_cast<const uint8_t*>(bitstream_.data()), bitstream_.size());
if (full_sample_encryption) {
// We only use this in 2 tests, each use the same data where the offset to
// the byte after the NALU type for the slice header is 669.
constexpr int kOffsetToSliceHeader = 669;
decoder_buffer_->set_decrypt_config(DecryptConfig::CreateCencConfig(
"kFakeKeyId", std::string(DecryptConfig::kDecryptionKeySize, 'x'),
{SubsampleEntry(kOffsetToSliceHeader,
bitstream_.size() - kOffsetToSliceHeader)}));
}
EXPECT_NE(decoder_buffer_.get(), nullptr);
decoder_->SetStream(bitstream_id++, *decoder_buffer_);
}
}
// To have better description on mismatch.
class WithPocMatcher : public MatcherInterface<scoped_refptr<H264Picture>> {
public:
explicit WithPocMatcher(int expected_poc) : expected_poc_(expected_poc) {}
bool MatchAndExplain(scoped_refptr<H264Picture> p,
MatchResultListener* listener) const override {
if (p->pic_order_cnt == expected_poc_)
return true;
*listener << "with poc: " << p->pic_order_cnt;
return false;
}
void DescribeTo(std::ostream* os) const override {
*os << "with poc " << expected_poc_;
}
private:
int expected_poc_;
};
inline Matcher<scoped_refptr<H264Picture>> WithPoc(int expected_poc) {
return MakeMatcher(new WithPocMatcher(expected_poc));
}
// Test Cases
TEST_F(H264DecoderTest, DecodeSingleFrame) {
SetInputFrameFiles({kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
EXPECT_CALL(*accelerator_, CreateH264Picture()).WillOnce(Return(nullptr));
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfSurfaces, Decode());
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&*accelerator_));
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(_));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
// This is for CENCv1 full sample encryption.
TEST_F(H264DecoderTest, DecodeSingleEncryptedFrame) {
SetInputFrameFiles({kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode(true));
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, ParseEncryptedSliceHeader(_, _, _, _, _))
.WillOnce(Invoke(&ParseSliceHeader));
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(_));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SkipNonIDRFrames) {
SetInputFrameFiles({kBaselineFrame1, kBaselineFrame2, kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, DecodeProfileBaseline) {
SetInputFrameFiles({
kBaselineFrame0, kBaselineFrame1, kBaselineFrame2, kBaselineFrame3,
});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(4);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(4);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(4);
Expectation decode_poc0, decode_poc2, decode_poc4, decode_poc6;
{
InSequence decode_order;
decode_poc0 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
decode_poc2 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
decode_poc4 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(4)));
decode_poc6 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(6)));
}
{
InSequence display_order;
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0))).After(decode_poc0);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2))).After(decode_poc2);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(4))).After(decode_poc4);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(6))).After(decode_poc6);
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, Decode10BitStream) {
SetInputFrameFiles({k10BitFrame0, k10BitFrame1, k10BitFrame2, k10BitFrame3});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(gfx::Rect(320, 180), decoder_->GetVisibleRect());
EXPECT_EQ(H264PROFILE_HIGH10PROFILE, decoder_->GetProfile());
EXPECT_EQ(10u, decoder_->GetBitDepth());
EXPECT_LE(14u, decoder_->GetRequiredNumOfPictures());
// One picture will be kept in the DPB for reordering. The second picture
// should be outputted after feeding the third and fourth frames.
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(4);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(4);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(4);
Expectation decode_poc0, decode_poc2, decode_poc4, decode_poc6;
{
InSequence decode_order;
decode_poc0 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
decode_poc6 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(6)));
decode_poc2 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
decode_poc4 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(4)));
}
{
InSequence display_order;
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0))).After(decode_poc0);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2))).After(decode_poc2);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(4))).After(decode_poc4);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(6))).After(decode_poc6);
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, OutputPictureFailureCausesDecodeToFail) {
// Provide enough data that Decode() will try to output a frame.
SetInputFrameFiles({
kBaselineFrame0,
kBaselineFrame1,
});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_CALL(*accelerator_, OutputPicture(_)).WillRepeatedly(Return(false));
ASSERT_EQ(AcceleratedVideoDecoder::kDecodeError, Decode());
}
TEST_F(H264DecoderTest, DecodeProfileHigh) {
SetInputFrameFiles({kHighFrame0, kHighFrame1, kHighFrame2, kHighFrame3});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_HIGH, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(16u, decoder_->GetRequiredNumOfPictures());
// Two pictures will be kept in the DPB for reordering. The first picture
// should be outputted after feeding the third frame.
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(4);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(4);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(4);
Expectation decode_poc0, decode_poc2, decode_poc4, decode_poc6;
{
InSequence decode_order;
decode_poc0 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
decode_poc4 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(4)));
decode_poc2 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
decode_poc6 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(6)));
}
{
InSequence display_order;
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0))).After(decode_poc0);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2))).After(decode_poc2);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(4))).After(decode_poc4);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(6))).After(decode_poc6);
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, DenyDecodeNonYUV420) {
// YUV444 frame causes kDecodeError.
SetInputFrameFiles({kYUV444Frame});
ASSERT_EQ(AcceleratedVideoDecoder::kDecodeError, Decode());
}
TEST_F(H264DecoderTest, SwitchBaselineToHigh) {
SetInputFrameFiles({
kBaselineFrame0, kHighFrame0, kHighFrame1, kHighFrame2, kHighFrame3,
});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_HIGH, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(16u, decoder_->GetRequiredNumOfPictures());
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&*accelerator_));
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(4);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(4);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(4);
Expectation decode_poc0, decode_poc2, decode_poc4, decode_poc6;
{
InSequence decode_order;
decode_poc0 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
decode_poc4 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(4)));
decode_poc2 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
decode_poc6 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(6)));
}
{
InSequence display_order;
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0))).After(decode_poc0);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2))).After(decode_poc2);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(4))).After(decode_poc4);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(6))).After(decode_poc6);
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SwitchHighToBaseline) {
SetInputFrameFiles({
kHighFrame0, kBaselineFrame0, kBaselineFrame1, kBaselineFrame2,
kBaselineFrame3,
});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_HIGH, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(16u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&*accelerator_));
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(4);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(4);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(4);
Expectation decode_poc0, decode_poc2, decode_poc4, decode_poc6;
{
InSequence decode_order;
decode_poc0 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
decode_poc2 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
decode_poc4 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(4)));
decode_poc6 = EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(6)));
}
{
InSequence display_order;
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0))).After(decode_poc0);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2))).After(decode_poc2);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(4))).After(decode_poc4);
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(6))).After(decode_poc6);
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SwitchYUV420ToNonYUV420) {
SetInputFrameFiles({kBaselineFrame0, kYUV444Frame});
// The first frame, YUV420, is decoded with no error.
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
// The second frame, YUV444, causes kDecodeError.
ASSERT_EQ(AcceleratedVideoDecoder::kDecodeError, Decode());
}
// Verify that the decryption config is passed to the accelerator.
TEST_F(H264DecoderTest, SetEncryptedStream) {
std::string bitstream;
auto input_file = GetTestDataFilePath(kBaselineFrame0);
CHECK(base::ReadFileToString(input_file, &bitstream));
const char kAnyKeyId[] = "any_16byte_keyid";
const char kAnyIv[] = "any_16byte_iv___";
const std::vector<SubsampleEntry> subsamples = {
// No encrypted bytes. This test only checks whether the data is passed
// thru to the acclerator so making this completely clear.
{static_cast<uint32_t>(bitstream.size()), 0},
};
std::unique_ptr<DecryptConfig> decrypt_config =
DecryptConfig::CreateCencConfig(kAnyKeyId, kAnyIv, subsamples);
EXPECT_CALL(*accelerator_,
SubmitFrameMetadata(_, _, _, _, _, _,
DecryptConfigMatches(decrypt_config.get())))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kOk));
EXPECT_CALL(*accelerator_,
SubmitDecode(DecryptConfigMatches(decrypt_config.get())))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kOk));
auto buffer = DecoderBuffer::CopyFrom(
reinterpret_cast<const uint8_t*>(bitstream.data()), bitstream.size());
ASSERT_NE(buffer.get(), nullptr);
buffer->set_decrypt_config(std::move(decrypt_config));
decoder_->SetStream(0, *buffer);
EXPECT_EQ(AcceleratedVideoDecoder::kConfigChange, decoder_->Decode());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, decoder_->Decode());
EXPECT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, ParseEncryptedSliceHeaderRetry) {
SetInputFrameFiles({kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode(true));
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
EXPECT_CALL(*accelerator_, ParseEncryptedSliceHeader(_, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode(true));
// Try again, assuming key still not set. Only ParseEncryptedSliceHeader()
// should be called again.
EXPECT_CALL(*accelerator_, ParseEncryptedSliceHeader(_, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode(true));
// Assume key has been provided now, next call to Decode() should proceed.
{
InSequence sequence;
EXPECT_CALL(*accelerator_, ParseEncryptedSliceHeader(_, _, _, _, _))
.WillOnce(Invoke(&ParseSliceHeader));
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode(true));
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SubmitFrameMetadataRetry) {
SetInputFrameFiles({kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
}
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Try again, assuming key still not set. Only SubmitFrameMetadata()
// should be called again.
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(0);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Assume key has been provided now, next call to Decode() should proceed.
{
InSequence sequence;
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SubmitSliceRetry) {
SetInputFrameFiles({kBaselineFrame0});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
}
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Try again, assuming key still not set. Only SubmitSlice() should be
// called again.
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(0);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(0);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Assume key has been provided now, next call to Decode() should proceed.
{
InSequence sequence;
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SubmitDecodeRetry) {
SetInputFrameFiles({kBaselineFrame0, kBaselineFrame1});
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(_))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
}
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Try again, assuming key still not set. Only SubmitDecode() should be
// called again.
EXPECT_CALL(*accelerator_, CreateH264Picture()).Times(0);
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _)).Times(0);
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _)).Times(0);
EXPECT_CALL(*accelerator_, SubmitDecode(_))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
// Assume key has been provided now, next call to Decode() should output
// the first frame.
{
InSequence sequence;
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(2)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(2)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
TEST_F(H264DecoderTest, SetStreamRetry) {
SetInputFrameFiles({kBaselineFrame0});
EXPECT_CALL(*accelerator_, SetStream(_, _))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kTryAgain))
.WillOnce(Return(H264Decoder::H264Accelerator::Status::kOk));
ASSERT_EQ(AcceleratedVideoDecoder::kTryAgain, Decode());
ASSERT_EQ(AcceleratedVideoDecoder::kConfigChange, Decode());
EXPECT_EQ(gfx::Size(320, 192), decoder_->GetPicSize());
EXPECT_EQ(H264PROFILE_BASELINE, decoder_->GetProfile());
EXPECT_EQ(8u, decoder_->GetBitDepth());
EXPECT_LE(9u, decoder_->GetRequiredNumOfPictures());
{
InSequence sequence;
EXPECT_CALL(*accelerator_, CreateH264Picture());
EXPECT_CALL(*accelerator_, SubmitFrameMetadata(_, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitSlice(_, _, _, _, _, _, _, _));
EXPECT_CALL(*accelerator_, SubmitDecode(WithPoc(0)));
EXPECT_CALL(*accelerator_, OutputPicture(WithPoc(0)));
}
ASSERT_EQ(AcceleratedVideoDecoder::kRanOutOfStreamData, Decode());
ASSERT_TRUE(decoder_->Flush());
}
} // namespace
} // namespace media
| {'content_hash': '112ff7523f0562404070fb3c549012ad', 'timestamp': '', 'source': 'github', 'line_count': 758, 'max_line_length': 80, 'avg_line_length': 43.03825857519789, 'alnum_prop': 0.6884100174723354, 'repo_name': 'ric2b/Vivaldi-browser', 'id': '18a2fad58c597e136fd043fc1e02f1965fd87ae6', 'size': '33247', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'chromium/media/gpu/h264_decoder_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="ws_navigation_drawer_content_description" msgid="7216697245762194759">"لائحة التنقل"</string>
<string name="ws_action_drawer_content_description" msgid="1837365417701148489">"دُرج الإجراءات"</string>
</resources>
| {'content_hash': 'c9d76187c350140b1f999c9d072910a6', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 111, 'avg_line_length': 49.285714285714285, 'alnum_prop': 0.7304347826086957, 'repo_name': 'aosp-mirror/platform_frameworks_support', 'id': '89f8f104ea30f2e57349ffaea9a38aa058e26cf2', 'size': '1059', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wear/res/values-ar/strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '20090'}, {'name': 'HTML', 'bytes': '514'}, {'name': 'IDL', 'bytes': '308'}, {'name': 'Java', 'bytes': '30647232'}, {'name': 'Kotlin', 'bytes': '2665731'}, {'name': 'Python', 'bytes': '43821'}, {'name': 'Shell', 'bytes': '18933'}]} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Helper files
| 4. Custom config files
| 5. Language files
| 6. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
$autoload['libraries'] = array('database','session');
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('url','common_helper','user_helper','transaction_helper');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('model1', 'model2');
|
*/
$autoload['model'] = array();
/* End of file autoload.php */
/* Location: ./application/config/autoload.php */ | {'content_hash': 'e6674b04f0991bf56ceef5c356ba4768', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 86, 'avg_line_length': 27.504347826086956, 'alnum_prop': 0.4394562124565286, 'repo_name': 'seegan/Myproj', 'id': 'e8261d0bcb268c3cc403237bcf558523424a7215', 'size': '3163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/config/autoload.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '154'}, {'name': 'CSS', 'bytes': '348130'}, {'name': 'HTML', 'bytes': '29153'}, {'name': 'JavaScript', 'bytes': '3688'}, {'name': 'PHP', 'bytes': '1391362'}]} |
select.form-control + .chosen-container.chosen-container-single .chosen-single {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
-webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
background-image:none;
}
select.form-control + .chosen-container.chosen-container-single .chosen-single div {
top:4px;
color:#000;
}
select.form-control + .chosen-container .chosen-drop {
background-color: #FFF;
border: 1px solid #CCC;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
margin: 2px 0 0;
}
select.form-control + .chosen-container .chosen-search input[type=text] {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .chosen-container .chosen-results {
margin: 2px 0 0;
padding: 5px 0;
font-size: 14px;
list-style: none;
background-color: #fff;
margin-bottom: 5px;
}
select.form-control + .chosen-container .chosen-results li ,
select.form-control + .chosen-container .chosen-results li.active-result {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.428571429;
color: #333;
white-space: nowrap;
background-image:none;
}
select.form-control + .chosen-container .chosen-results li:hover,
select.form-control + .chosen-container .chosen-results li.active-result:hover,
select.form-control + .chosen-container .chosen-results li.highlighted
{
color: #FFF;
text-decoration: none;
background-color: #428BCA;
background-image:none;
}
select.form-control + .chosen-container-multi .chosen-choices {
display: block;
width: 100%;
min-height: 34px;
padding: 6px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-field input[type="text"] {
height:auto;
padding:5px 0;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-choice {
background-image: none;
padding: 3px 24px 3px 5px;
margin: 0 6px 0 0;
font-size: 14px;
font-weight: normal;
line-height: 1.428571429;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 4px;
color: #333;
background-color: #FFF;
border-color: #CCC;
}
select.form-control + .chosen-container-multi .chosen-choices li.search-choice .search-choice-close {
top:8px;
right:6px;
}
select.form-control + .chosen-container-multi.chosen-container-active .chosen-choices,
select.form-control + .chosen-container.chosen-container-single.chosen-container-active .chosen-single,
select.form-control + .chosen-container .chosen-search input[type=text]:focus{
border-color: #66AFE9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
}
select.form-control + .chosen-container-multi .chosen-results li.result-selected{
display: list-item;
color: #ccc;
cursor: default;
background-color: white;
} | {'content_hash': '52777d042555c76b25fb0b9cc2f80a4d', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 103, 'avg_line_length': 32.12837837837838, 'alnum_prop': 0.6504731861198738, 'repo_name': 'achluky/Quotation', 'id': 'f8360cd6519b2d83e7fb8cee066bca31bb57b7e2', 'size': '4755', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/assets/chosen/chosen-bootstrap.css', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '207'}, {'name': 'Batchfile', 'bytes': '1070'}, {'name': 'CSS', 'bytes': '735711'}, {'name': 'HTML', 'bytes': '209115'}, {'name': 'JavaScript', 'bytes': '1535220'}, {'name': 'PHP', 'bytes': '192779'}]} |
/** TODO: license boiler plate here
*
* By Victor Lu ([email protected])
*/
#ifndef __ACCUMULATOR_H__
#define __ACCUMULATOR_H__
#include <type_traits>
namespace pointkd {
// specify how element types are converted to floating point number
template <typename T, bool is_int = std::is_integral<T>::value>
struct Accumulator {};
template <typename T>
struct Accumulator<T, true> {
typedef float Type;
};
template <>
struct Accumulator<float, false> {
typedef float Type;
};
template <>
struct Accumulator<double, false> {
typedef double Type;
};
} // namespace pointkd
#endif //__ACCUMULATOR_H__
| {'content_hash': '21b2e1ffb92f9f36b464476021183e0c', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 67, 'avg_line_length': 20.433333333333334, 'alnum_prop': 0.7014681892332789, 'repo_name': 'heremaps/pptk', 'id': '3905a55c2d8f22f9dcb7495e1c8c1f7de646a46c', 'size': '613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pptk/kdtree/src/accumulator.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1170'}, {'name': 'C++', 'bytes': '327139'}, {'name': 'CMake', 'bytes': '16817'}, {'name': 'Python', 'bytes': '84666'}]} |
package Google::Ads::GoogleAds::V10::Services::FeedService::MutateFeedResult;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
feed => $args->{feed},
resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| {'content_hash': 'e4a1a848fd36f2ec0f7739f559b476c2', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 79, 'avg_line_length': 23.09090909090909, 'alnum_prop': 0.6732283464566929, 'repo_name': 'googleads/google-ads-perl', 'id': '09d3f1f719ceec1dd0f2933e6445d433d5ffad92', 'size': '1084', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'lib/Google/Ads/GoogleAds/V10/Services/FeedService/MutateFeedResult.pm', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '73'}, {'name': 'Perl', 'bytes': '5866064'}]} |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Tags")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard")]
[assembly: AssemblyCopyright("Copyright © Outercurve Foundation 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f9fe09de-83a1-4963-a134-f99bd712542f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.7.2")]
[assembly: AssemblyFileVersion("1.7.2")]
| {'content_hash': 'b89b867d1334489ed7b964a4e92b90b6', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 84, 'avg_line_length': 37.77142857142857, 'alnum_prop': 0.7488653555219364, 'repo_name': 'Imant/Tournament', 'id': '41cfe0aa4fb9e02b858e53d50765e04883c15e2c', 'size': '1325', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'src/Orchard.Web/Modules/Orchard.Tags/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '2330'}, {'name': 'C', 'bytes': '4755'}, {'name': 'C#', 'bytes': '7514034'}, {'name': 'CSS', 'bytes': '350061'}, {'name': 'JavaScript', 'bytes': '966429'}, {'name': 'Shell', 'bytes': '4601'}, {'name': 'XSLT', 'bytes': '119918'}]} |
The MIT License (MIT)
Copyright (c) 2016 Nap Joseph N. Calub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| {'content_hash': 'b344a0545dcf70fcf56035c87d26bdf3', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 78, 'avg_line_length': 51.714285714285715, 'alnum_prop': 0.8020257826887661, 'repo_name': 'njncalub/resume', 'id': 'e388d7868232bd9609b0dabc16f4e0a1f723d57b', 'size': '1086', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LICENSE.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3177'}, {'name': 'HTML', 'bytes': '10504'}, {'name': 'JavaScript', 'bytes': '178575'}]} |
package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
"github.com/spf13/cobra"
)
// SubscribersPutBundlesCmdImsi holds value of 'imsi' option
var SubscribersPutBundlesCmdImsi string
// SubscribersPutBundlesCmdBody holds contents of request body to be sent
var SubscribersPutBundlesCmdBody string
func init() {
SubscribersPutBundlesCmd.Flags().StringVar(&SubscribersPutBundlesCmdImsi, "imsi", "", TRAPI("IMSI of the target subscriber."))
SubscribersPutBundlesCmd.Flags().StringVar(&SubscribersPutBundlesCmdBody, "body", "", TRCLI("cli.common_params.body.short_help"))
SubscribersCmd.AddCommand(SubscribersPutBundlesCmd)
}
// SubscribersPutBundlesCmd defines 'put-bundles' subcommand
var SubscribersPutBundlesCmd = &cobra.Command{
Use: "put-bundles",
Short: TRAPI("/subscribers/{imsi}/bundles:put:summary"),
Long: TRAPI(`/subscribers/{imsi}/bundles:put:description`) + "\n\n" + createLinkToAPIReference("Subscriber", "putBundles"),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("unexpected arguments passed => %v", args)
}
opt := &apiClientOptions{
BasePath: "/v1",
Language: getSelectedLanguage(),
}
ac := newAPIClient(opt)
if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
ac.SetVerbose(true)
}
err := authHelper(ac, cmd, args)
if err != nil {
cmd.SilenceUsage = true
return err
}
param, err := collectSubscribersPutBundlesCmdParams(ac)
if err != nil {
return err
}
body, err := ac.callAPI(param)
if err != nil {
cmd.SilenceUsage = true
return err
}
if body == "" {
return nil
}
if rawOutput {
_, err = os.Stdout.Write([]byte(body))
} else {
return prettyPrintStringAsJSON(body)
}
return err
},
}
func collectSubscribersPutBundlesCmdParams(ac *apiClient) (*apiParams, error) {
var body string
var parsedBody interface{}
var err error
body, err = buildBodyForSubscribersPutBundlesCmd()
if err != nil {
return nil, err
}
contentType := "application/json"
if contentType == "application/json" {
err = json.Unmarshal([]byte(body), &parsedBody)
if err != nil {
return nil, fmt.Errorf("invalid json format specified for `--body` parameter: %s", err)
}
}
err = checkIfRequiredStringParameterIsSupplied("imsi", "imsi", "path", parsedBody, SubscribersPutBundlesCmdImsi)
if err != nil {
return nil, err
}
return &apiParams{
method: "PUT",
path: buildPathForSubscribersPutBundlesCmd("/subscribers/{imsi}/bundles"),
query: buildQueryForSubscribersPutBundlesCmd(),
contentType: contentType,
body: body,
noRetryOnError: noRetryOnError,
}, nil
}
func buildPathForSubscribersPutBundlesCmd(path string) string {
escapedImsi := url.PathEscape(SubscribersPutBundlesCmdImsi)
path = strReplace(path, "{"+"imsi"+"}", escapedImsi, -1)
return path
}
func buildQueryForSubscribersPutBundlesCmd() url.Values {
result := url.Values{}
return result
}
func buildBodyForSubscribersPutBundlesCmd() (string, error) {
var b []byte
var err error
if SubscribersPutBundlesCmdBody != "" {
if strings.HasPrefix(SubscribersPutBundlesCmdBody, "@") {
fname := strings.TrimPrefix(SubscribersPutBundlesCmdBody, "@")
// #nosec
b, err = ioutil.ReadFile(fname)
} else if SubscribersPutBundlesCmdBody == "-" {
b, err = ioutil.ReadAll(os.Stdin)
} else {
b = []byte(SubscribersPutBundlesCmdBody)
}
if err != nil {
return "", err
}
}
if b == nil {
b = []byte{}
}
return string(b), nil
}
| {'content_hash': 'dbcb9b05d088dabe61cb0e014e40f9a5', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 130, 'avg_line_length': 23.4635761589404, 'alnum_prop': 0.6960203217612193, 'repo_name': 'soracom/soracom-cli', 'id': '1ace3e6310a9cedb7c808af6dae8dc9665c6ff3f', 'size': '3603', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'soracom/generated/cmd/subscribers_put_bundles.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '222'}, {'name': 'Go', 'bytes': '193285'}, {'name': 'Makefile', 'bytes': '2605'}, {'name': 'Shell', 'bytes': '29223'}]} |
package com.castlemock.service.mock.soap.project.converter;
import com.castlemock.model.mock.soap.domain.SoapOperationIdentifier;
import com.castlemock.service.mock.soap.project.converter.types.MessagePart;
import com.castlemock.service.mock.soap.project.converter.types.Namespace;
import java.util.Set;
public final class MessagePartConverter {
private MessagePartConverter(){
}
public static SoapOperationIdentifier toSoapOperationIdentifier(final MessagePart messagePart,
final Set<Namespace> namespaces){
return messagePart.getElement()
.map(attribute -> AttributeConverter.toSoapOperationIdentifier(attribute, namespaces))
.orElseGet(() -> SoapOperationIdentifier.builder()
.name(messagePart.getName())
.namespace(null)
.build());
}
}
| {'content_hash': '300545f16a7e2ebb94efb7e6e13eb436', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 102, 'avg_line_length': 35.0, 'alnum_prop': 0.6518518518518519, 'repo_name': 'castlemock/castlemock', 'id': '9839dc6b07f9b7fbb3c4191b60012f7509a396ab', 'size': '1539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'service/service-mock/service-mock-soap/src/main/java/com/castlemock/service/mock/soap/project/converter/MessagePartConverter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1004'}, {'name': 'CSS', 'bytes': '8750'}, {'name': 'HTML', 'bytes': '798'}, {'name': 'Java', 'bytes': '2612368'}, {'name': 'JavaScript', 'bytes': '527130'}, {'name': 'Procfile', 'bytes': '84'}]} |
""" Tests the random forest functionality """
import unittest
from sparktkregtests.lib import sparktk_test
class RandomForest(sparktk_test.SparkTKTestCase):
def setUp(self):
"""Build the required frame"""
super(RandomForest, self).setUp()
schema = [("feat1", int), ("feat2", int), ("class", int)]
filename = self.get_file("rand_forest_class.csv")
self.frame = self.context.frame.import_csv(filename, schema=schema)
def test_classifier_train(self):
""" Test train method """
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", seed=0)
self.assertItemsEqual(model.observation_columns, ["feat1", "feat2"])
self.assertEqual(model.label_column, "class")
self.assertEqual(model.max_bins, 100)
self.assertEqual(model.max_depth, 4)
self.assertEqual(model.num_classes, 2)
self.assertEqual(model.num_trees, 1)
self.assertEqual(model.impurity, "gini")
self.assertEqual(model.min_instances_per_node, 1)
self.assertEqual(model.feature_subset_category, "auto")
self.assertEqual(model.seed, 0)
self.assertAlmostEqual(model.sub_sampling_rate, 1.0)
self.assertIsNone(model.categorical_features_info)
def test_classifier_predict(self):
"""Test binomial classification of random forest model"""
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", seed=0)
result_frame = model.predict(self.frame)
preddf = result_frame.to_pandas(self.frame.count())
for index, row in preddf.iterrows():
self.assertEqual(row['class'], row['predicted_class'])
def test_classifier_test(self):
"""Test test() method"""
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", seed=0)
test_res = model.test(self.frame)
self.assertEqual(test_res.precision, 1.0)
self.assertEqual(test_res.recall, 1.0)
self.assertEqual(test_res.accuracy, 1.0)
self.assertEqual(test_res.f_measure, 1.0)
self.assertEqual(
test_res.confusion_matrix['Predicted_Pos']['Actual_Pos'], 413)
self.assertEqual(
test_res.confusion_matrix['Predicted_Pos']['Actual_Neg'], 0)
self.assertEqual(
test_res.confusion_matrix['Predicted_Neg']['Actual_Pos'], 0)
self.assertEqual(
test_res.confusion_matrix['Predicted_Neg']['Actual_Neg'], 587)
def test_negative_seed(self):
"""Test training with negative seed does not throw exception"""
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", seed=-10)
def test_bad_class_col_name(self):
"""Negative test to check behavior for bad class column"""
with self.assertRaisesRegexp(
Exception, "Invalid column name ERR provided"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "ERR")
def test_bad_feature_col_name(self):
"""Negative test to check behavior for feature class column"""
with self.assertRaisesRegexp(
Exception, ".*Invalid column name ERR provided"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["ERR", "feat2"], "class")
def test_invalid_impurity(self):
"""Negative test for invalid impurity value"""
with self.assertRaisesRegexp(
Exception, "Supported values for impurity are gini or entropy"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", impurity="variance")
def test_negative_max_bins(self):
"""Negative test for max_bins < 0"""
with self.assertRaisesRegexp(
Exception, "Found max_bins = -1. Expected non-negative integer."):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", max_bins=-1)
def test_max_bins_0(self):
"""Test for max_bins = 0; should throw exception"""
with self.assertRaisesRegexp(
Exception,
"maxBins must be greater than 0"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", max_bins=0)
def test_negative_max_depth(self):
"""Negative test for max_depth < 0"""
with self.assertRaisesRegexp(
Exception, "Found max_depth = -2. Expected non-negative integer."):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", max_depth=-2)
def test_max_depth_0(self):
"""Negative test for max_depth=0"""
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", max_depth=0)
#check predicted values for depth 0
result_frame = model.predict(self.frame)
preddf = result_frame.to_pandas(self.frame.count())
expected_pred_labels = [0]*self.frame.count()
actual_pred_labels = preddf['predicted_class'].tolist()
self.assertItemsEqual(actual_pred_labels, expected_pred_labels)
def test_negative_num_trees(self):
"""Negative test for num_trees<0"""
with self.assertRaisesRegexp(
Exception, "Found num_trees = -10. Expected non-negative integer."):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", num_trees=-10)
def test_num_trees_0(self):
"""Negative test for num_trees=0"""
with self.assertRaisesRegexp(
Exception, "numTrees must be greater than 0"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", num_trees=0)
def test_invalid_feature_subset_category(self):
"""Negative test for feature subset category"""
with self.assertRaisesRegexp(
Exception, "feature subset category"):
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class",
feature_subset_category="any")
def test_rand_forest_save(self):
"""Tests save plugin"""
model = self.context.models.classification.random_forest_classifier.train(
self.frame, ["feat1", "feat2"], "class", seed=0)
path = self.get_name("test")
model.save(path + "/randomforestclassifier")
restored = self.context.load(path +"/randomforestclassifier")
self.assertItemsEqual(restored.observation_columns, ["feat1", "feat2"])
self.assertEqual(restored.label_column, "class")
self.assertEqual(restored.max_bins, 100)
self.assertEqual(restored.max_depth, 4)
self.assertEqual(restored.num_classes, 2)
self.assertEqual(restored.num_trees, 1)
self.assertEqual(restored.impurity, "gini")
self.assertEqual(restored.min_instances_per_node, 1)
self.assertEqual(restored.feature_subset_category, "auto")
self.assertEqual(restored.seed, 0)
self.assertAlmostEqual(restored.sub_sampling_rate, 1.0)
self.assertIsNone(restored.categorical_features_info)
if __name__ == '__main__':
unittest.main()
| {'content_hash': '93cb5d6a6a61c9c2bf62bc3ccdbf8529', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 97, 'avg_line_length': 46.59171597633136, 'alnum_prop': 0.6309372618745237, 'repo_name': 'anjalisood/spark-tk', 'id': '4aa9a73fd5f7d3abaf906ca81564c77f49c79f8b', 'size': '8579', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'regression-tests/sparktkregtests/testcases/models/random_forest_classifier_test.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '31130'}, {'name': 'Python', 'bytes': '1729929'}, {'name': 'R', 'bytes': '2242'}, {'name': 'Scala', 'bytes': '2240766'}, {'name': 'Shell', 'bytes': '28677'}]} |
Show area in open street maps
# Installation
Clone the repository to your local machine.
$ git clone https://github.com/tuxonice/size-my-area
# Demo
http://size-my-area.tlab.pt/
| {'content_hash': '33c3870bf9db12d68682519d053b2f41', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 56, 'avg_line_length': 17.0, 'alnum_prop': 0.7272727272727273, 'repo_name': 'tuxonice/size-my-area', 'id': '7e6548f505adfe440e0497ccd32b49f807d4b798', 'size': '202', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2493'}, {'name': 'HTML', 'bytes': '917'}, {'name': 'JavaScript', 'bytes': '3572'}, {'name': 'PHP', 'bytes': '884'}]} |
/*global ko, jQuery*/
// Github repository: https://github.com/One-com/knockout-dragdrop
// License: standard 3-clause BSD license https://raw.github.com/One-com/knockout-dragdrop/master/LICENSE
(function (factory) {
if (typeof define === "function" && define.amd) {
// AMD anonymous module with hard-coded dependency on "knockout"
define(["knockout", "jquery"], factory);
} else {
// <script> tag: use the global `ko` and `jQuery`
factory(ko, jQuery);
}
})(function (ko, $) {
var dropZones = {};
var eventZones = {};
var forEach = ko.utils.arrayForEach;
var first = ko.utils.arrayFirst;
var filter = ko.utils.arrayFilter;
function Zone(args) {
this.init(args);
}
Zone.prototype.init = function (args) {
this.element = args.element;
this.$element = $(args.element);
this.data = args.data;
this.dragEnter = args.dragEnter;
this.dragOver = args.dragOver;
this.dragLeave = args.dragLeave;
this.active = false;
this.inside = false;
this.dirty = false;
};
Zone.prototype.refreshDomInfo = function () {
var $element = this.$element;
this.hidden = $element.css('display') === 'none';
if (!this.hidden) {
var offset = $element.offset();
this.top = offset.top;
this.left = offset.left;
this.width = $element.outerWidth();
this.height = $element.outerHeight();
}
};
Zone.prototype.isInside = function (x, y) {
if (this.hidden) {
return false;
}
if (x < this.left || y < this.top) {
return false;
}
if (this.left + this.width < x) {
return false;
}
if (this.top + this.height < y) {
return false;
}
return true;
};
Zone.prototype.update = function (event, data) {
if (this.isInside(event.pageX, event.pageY)) {
if (!this.inside) {
this.enter(event, data);
}
if (this.dragOver) {
this.dragOver(event, data, this.data);
}
} else {
this.leave(event);
}
};
Zone.prototype.enter = function (event, data) {
this.inside = true;
if (this.dragEnter) {
this.active = this.dragEnter(event, data, this.data) !== false;
} else {
this.active = true;
}
this.dirty = true;
};
Zone.prototype.leave = function (event) {
if (event) {
event.target = this.element;
}
if (this.inside && this.dragLeave) {
this.dragLeave(event, this.data);
}
this.active = false;
this.inside = false;
this.dirty = true;
};
function DropZone(args) {
this.init(args);
this.drop = function (data) {
args.drop(data, args.data);
};
}
DropZone.prototype = Zone.prototype;
DropZone.prototype.updateStyling = function () {
if (this.dirty) {
this.$element.toggleClass('drag-over', this.active);
this.$element.toggleClass('drop-rejected', this.inside && !this.active);
}
this.dirty = false;
};
function DragElement($element) {
this.$element = $element;
this.$element.addClass('drag-element').css({
'position': 'fixed',
'z-index': 9998
});
this.$element.on('selectstart', false);
}
DragElement.prototype.updatePosition = function (event) {
this.$element.offset({
'top': event.pageY,
'left': event.pageX
});
};
DragElement.prototype.remove = function () {
this.$element.remove();
};
function Draggable(args) {
this.element = args.element;
this.name = args.name;
this.dragStart = args.dragStart;
this.dragEnd = args.dragEnd;
this.data = args.data;
}
Draggable.prototype.startDrag = function (event) {
if (this.dragStart && this.dragStart(this.data, event) === false) {
return false;
}
};
Draggable.prototype.drag = function (event) {
var that = this;
var name = this.name;
var zones = dropZones[name].concat(eventZones[name]);
forEach(zones, function (zone) {
zone.refreshDomInfo();
});
forEach(zones, function (zone) {
event.target = zone.element;
zone.update(event, that.data);
});
forEach(dropZones[name], function (zone) {
zone.updateStyling();
});
};
Draggable.prototype.dropRejected = function () {
var name = this.name;
var insideAZone = first(dropZones[name], function (zone) {
return zone.inside;
});
if (!insideAZone) {
return true;
}
var noActiveZone = !first(dropZones[name], function (zone) {
return zone.active;
});
return noActiveZone;
};
Draggable.prototype.cancelDrag = function (event) {
if (this.dragEnd) {
this.dragEnd(this.data, event);
}
};
Draggable.prototype.drop = function (event) {
var name = this.name;
var dropZoneElement = $(event.target).closest('.drop-zone');
var activeZones = filter(dropZones[name], function (zone) {
return zone.active;
});
var winningDropZone = filter(activeZones, function (zone) {
return zone.$element.is(dropZoneElement);
})[0];
forEach(dropZones[name].concat(eventZones[name]), function (zone) {
zone.leave(event);
});
forEach(dropZones[name], function (zone) {
zone.updateStyling();
});
if (winningDropZone && winningDropZone.drop) {
winningDropZone.drop(this.data);
}
if (this.dragEnd) {
this.dragEnd(this.data, event);
}
};
function ScrollArea(element, delay) {
this.element = element;
this.$element = $(element);
this.scrollMargin = Math.floor(this.$element.innerHeight() / 10);
this.offset = this.$element.offset();
this.innerHeight = this.$element.innerHeight();
this.scrollDeltaMin = 5;
this.scrollDeltaMax = 30;
this.delay = delay || 0;
this.inZone = 'center';
this.scrolling = false;
}
ScrollArea.prototype.scroll = function (x, y) {
var that = this;
this.x = x;
this.y = y;
this.topLimit = this.scrollMargin + this.offset.top;
this.bottomLimit = this.offset.top + this.innerHeight - this.scrollMargin;
if (y < this.topLimit) {
this.updateZone('top');
} else if (y > this.bottomLimit) {
this.updateZone('bottom');
} else {
this.updateZone('center');
}
};
ScrollArea.prototype.enter = function (zone) {
var that = this;
this.delayTimer = setTimeout(function () {
that.scrolling = true;
}, this.delay);
};
ScrollArea.prototype.leave = function (zone) {
this.scrolling = false;
clearTimeout(this.delayTimer);
};
ScrollArea.prototype.over = function (zone) {
var speed, scrollDelta;
if (this.scrolling) {
if (zone === 'top') {
speed = (this.topLimit - this.y) / this.scrollMargin;
scrollDelta = speed * (this.scrollDeltaMax - this.scrollDeltaMin) + this.scrollDeltaMin;
this.element.scrollTop -= scrollDelta;
} else if (zone === 'bottom') {
speed = (this.y - this.bottomLimit) / this.scrollMargin;
scrollDelta = speed * (this.scrollDeltaMax - this.scrollDeltaMin) + this.scrollDeltaMin;
this.element.scrollTop += scrollDelta;
}
}
};
ScrollArea.prototype.updateZone = function (zone) {
if (this.zone !== zone) {
this.leave(this.zone);
this.enter(zone);
}
this.zone = zone;
this.over(zone);
};
ko.utils.extend(ko.bindingHandlers, {
dropZone: {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor());
var accepts = [];
if (options.accepts) {
accepts = [].concat(options.accepts);
} else {
// options.name is deprecated
accepts.push(options.name);
}
$(element).addClass('drop-zone');
var data = options.data ||
(bindingContext && bindingContext.$data);
var zone = new DropZone({
element: element,
data: data,
drop: options.drop,
dragEnter: options.dragEnter,
dragOver: options.dragOver,
dragLeave: options.dragLeave
});
accepts.forEach(function (zoneName) {
dropZones[zoneName] = dropZones[zoneName] || [];
dropZones[zoneName].push(zone);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
zone.leave();
accepts.forEach(function (zoneName) {
dropZones[zoneName].splice(dropZones[zoneName].indexOf(zone), 1);
});
});
}
},
dragEvents: {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor());
var name = options.name;
eventZones[name] = eventZones[name] || [];
var data = options.data ||
(bindingContext && bindingContext.$data);
var zone = new Zone({
element: element,
data: data,
dragEnter: options.dragEnter,
dragOver: options.dragOver,
dragLeave: options.dragLeave
});
eventZones[name].push(zone);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
zone.leave();
eventZones[name].splice(eventZones[name].indexOf(zone), 1);
});
}
},
dragZone: {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor());
var name = options.name;
var dragDistance = options.dragDistance || 10;
dropZones[name] = dropZones[name] || [];
eventZones[name] = eventZones[name] || [];
var data = options.data ||
(bindingContext && bindingContext.$data);
var draggable = new Draggable({
element: element,
name: name,
data: data,
dragStart: options.dragStart,
dragEnd: options.dragEnd
});
function createCloneProxyElement() {
var dragProxy = $(element).clone().appendTo($(element).parent());
dragProxy.css({
height: $(element).height(),
width: $(element).width(),
opacity: 70 / 100,
filter: "alpha(opacity=70"
});
return dragProxy;
}
function createTemplateProxyElement() {
var dragProxy = $('<div>').appendTo('body');
var innerBindingContext = ('data' in options) ?
bindingContext.createChildContext(options.data) :
bindingContext;
ko.renderTemplate(options.element, innerBindingContext, {}, dragProxy[0]);
return dragProxy;
}
$(element).on('selectstart', function (e) {
if (!$(e.target).is(':input')) {
return false;
}
});
$(element).addClass('draggable');
$(element).on('mousedown', function (downEvent) {
if (downEvent.which !== 1) {
return true;
}
downEvent.preventDefault();
$(document).on('selectstart.drag', false);
function startDragging(startEvent) {
$(element).off('mouseup.startdrag click.startdrag mouseleave.startdrag mousemove.startdrag');
if (draggable.startDrag(downEvent) === false) {
return false;
}
var dragElement = null;
if (typeof options.element === 'undefined') {
dragElement = new DragElement(createCloneProxyElement());
}
var $overlay = $('<div class="drag-overlay" unselectable="on">');
$overlay.css({
'z-index': 9999,
'position': 'fixed',
'top': 0,
'left': 0,
'right': 0,
'bottom': 0,
'cursor': 'move',
'background-color': 'white',
'opacity': 0,
'filter': "alpha(opacity=0)",
'-webkit-user-select': 'none',
'-moz-user-select': '-moz-none',
'-ms-user-select': 'none',
'-o-user-select': 'none',
'user-select': 'none'
});
$overlay.on('selectstart', false);
$overlay.appendTo('body');
if (options.element) {
dragElement = new DragElement(createTemplateProxyElement());
}
if (dragElement) {
dragElement.updatePosition(downEvent);
}
var dragTimer = null;
var dropRejected = false;
function drag(event) {
draggable.drag(event);
if (draggable.dropRejected() !== dropRejected) {
$overlay.toggleClass('drop-rejected', draggable.dropRejected());
$overlay.css('cursor', draggable.dropRejected() ? 'no-drop' : 'move');
dropRejected = draggable.dropRejected();
}
dragTimer = setTimeout(function () {
drag(event);
}, 100);
}
function cancelDrag(e) {
$(element).off('mouseup.drag selectstart.drag');
clearTimeout(dragTimer);
if (dragElement) {
dragElement.remove();
}
$overlay.remove();
draggable.cancelDrag(e);
return true;
}
$overlay.on('mousemove.drag', function (moveEvent) {
if (moveEvent.which !== 1) {
return cancelDrag(moveEvent);
}
clearTimeout(dragTimer);
if (dragElement) {
dragElement.updatePosition(moveEvent);
}
drag(moveEvent);
return false;
});
$overlay.on('mouseup.drag', function (upEvent) {
clearTimeout(dragTimer);
if (dragElement) {
dragElement.remove();
}
$overlay.remove();
upEvent.target = document.elementFromPoint(upEvent.clientX, upEvent.clientY);
draggable.drop(upEvent);
$(document).off('selectstart.drag');
return false;
});
}
$(element).one('mouseup.startdrag click.startdrag mouseleave.startdrag', function (event) {
$(element).off('mousemove.startdrag');
$(document).off('selectstart.drag');
return true;
});
$(element).on('mousemove.startdrag', function (event) {
if ($(event.target).is(':input')) {
return;
}
var distance = Math.sqrt(Math.pow(downEvent.pageX - event.pageX, 2) +
Math.pow(downEvent.pageY - event.pageY, 2));
if (distance > dragDistance) {
startDragging(event);
}
});
return true;
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(document).off('selectstart.drag');
});
}
},
scrollableOnDragOver: {
// TODO make this binding scroll on the x-axis as well
init: function (element, valueAccessor, allBindingAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor());
if (typeof options === 'string') {
options = { name: options };
}
options.delay = options.delay || 0;
var scrollArea = null;
var x, y;
var scrollInterval;
function scroll() {
scrollArea.scroll(x, y);
}
function dragEnter(e) {
scrollArea = new ScrollArea(element, options.delay);
scrollInterval = setInterval(scroll, 100);
}
function dragOver(e) {
x = e.pageX;
y = e.pageY;
}
function dragLeave(e) {
clearInterval(scrollInterval);
}
ko.bindingHandlers.dragEvents.init(element, function () {
return {
name: options.name,
dragEnter: dragEnter,
dragOver: dragOver,
dragLeave: dragLeave
};
});
}
}
});
});
| {'content_hash': 'c697586e5f59086ad2c001d8f512305e', 'timestamp': '', 'source': 'github', 'line_count': 571, 'max_line_length': 117, 'avg_line_length': 34.56392294220665, 'alnum_prop': 0.45870490474260234, 'repo_name': 'jonobr1/cdnjs', 'id': 'e6cb22fcf15c6b7333b3f89f9fcb48a2cef9019d', 'size': '19736', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'ajax/libs/knockout-dragdrop/1.6.0/knockout.dragdrop.js', 'mode': '33188', 'license': 'mit', 'language': []} |
MovableObject::MovableObject() : m_MovementVelocityFactor{4.0}, m_LocalVelocity{0}
{
}
MovableObject::~MovableObject()
{
}
void MovableObject::startMoveForward()
{
m_LocalVelocity += m_MovementVelocityFactor * m_ForwardVector;
}
void MovableObject::startMoveLeft()
{
m_LocalVelocity += m_MovementVelocityFactor * m_LeftVector;
}
void MovableObject::startMoveRight()
{
m_LocalVelocity += m_MovementVelocityFactor * m_RightVector;
}
void MovableObject::startMoveBack()
{
m_LocalVelocity += m_MovementVelocityFactor * m_BackwardVector;
}
void MovableObject::stopMoveForward()
{
m_LocalVelocity -= m_MovementVelocityFactor * m_ForwardVector;
}
void MovableObject::stopMoveLeft()
{
m_LocalVelocity -= m_MovementVelocityFactor * m_LeftVector;
}
void MovableObject::stopMoveRight()
{
m_LocalVelocity -= m_MovementVelocityFactor * m_RightVector;
}
void MovableObject::stopMoveBack()
{
m_LocalVelocity -= m_MovementVelocityFactor * m_BackwardVector;
}
void MovableObject::step(double secondsPassed)
{
updatePosition(secondsPassed);
}
void MovableObject::addLocalVelocity(const glm::dvec3 & velocity)
{
m_LocalVelocity += velocity;
}
void MovableObject::updatePosition(double secondsPassed)
{
glm::dvec3 globalVelocity = glm::dvec3(m_RotationTransform*glm::vec4(m_LocalVelocity, 1.0));
glm::dvec3 translationDelta = globalVelocity*secondsPassed;
translate(translationDelta);
}
| {'content_hash': '0efaf34321821730fa38a22aeadbbd5e', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 93, 'avg_line_length': 21.12121212121212, 'alnum_prop': 0.7718794835007173, 'repo_name': 'citron0xa9/FluidSim', 'id': 'fe2c3b5fb9b5f597317a3800bfc3af9b4ac39ce2', 'size': '1423', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/MovableObject.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '329'}, {'name': 'C++', 'bytes': '208716'}, {'name': 'CMake', 'bytes': '10540'}, {'name': 'GLSL', 'bytes': '2818'}]} |
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/pnp.h>
#include "base.h"
static void quirk_awe32_resources(struct pnp_dev *dev)
{
struct pnp_port *port, *port2, *port3;
struct pnp_option *res = dev->dependent;
/*
* Unfortunately the isapnp_add_port_resource is too tightly bound
* into the PnP discovery sequence, and cannot be used. Link in the
* two extra ports (at offset 0x400 and 0x800 from the one given) by
* hand.
*/
for ( ; res ; res = res->next ) {
port2 = pnp_alloc(sizeof(struct pnp_port));
if (!port2)
return;
port3 = pnp_alloc(sizeof(struct pnp_port));
if (!port3) {
kfree(port2);
return;
}
port = res->port;
memcpy(port2, port, sizeof(struct pnp_port));
memcpy(port3, port, sizeof(struct pnp_port));
port->next = port2;
port2->next = port3;
port2->min += 0x400;
port2->max += 0x400;
port3->min += 0x800;
port3->max += 0x800;
}
printk(KERN_INFO "pnp: AWE32 quirk - adding two ports\n");
}
static void quirk_cmi8330_resources(struct pnp_dev *dev)
{
struct pnp_option *res = dev->dependent;
unsigned long tmp;
for ( ; res ; res = res->next ) {
struct pnp_irq *irq;
struct pnp_dma *dma;
for( irq = res->irq; irq; irq = irq->next ) { // Valid irqs are 5, 7, 10
tmp = 0x04A0;
bitmap_copy(irq->map, &tmp, 16); // 0000 0100 1010 0000
}
for( dma = res->dma; dma; dma = dma->next ) // Valid 8bit dma channels are 1,3
if( ( dma->flags & IORESOURCE_DMA_TYPE_MASK ) == IORESOURCE_DMA_8BIT )
dma->map = 0x000A;
}
printk(KERN_INFO "pnp: CMI8330 quirk - fixing interrupts and dma\n");
}
static void quirk_sb16audio_resources(struct pnp_dev *dev)
{
struct pnp_port *port;
struct pnp_option *res = dev->dependent;
int changed = 0;
/*
* The default range on the mpu port for these devices is 0x388-0x388.
* Here we increase that range so that two such cards can be
* auto-configured.
*/
for( ; res ; res = res->next ) {
port = res->port;
if(!port)
continue;
port = port->next;
if(!port)
continue;
port = port->next;
if(!port)
continue;
if(port->min != port->max)
continue;
port->max += 0x70;
changed = 1;
}
if(changed)
printk(KERN_INFO "pnp: SB audio device quirk - increasing port range\n");
return;
}
/*
* PnP Quirks
* Cards or devices that need some tweaking due to incomplete resource info
*/
static struct pnp_fixup pnp_fixups[] = {
/* Soundblaster awe io port quirk */
{ "CTL0021", quirk_awe32_resources },
{ "CTL0022", quirk_awe32_resources },
{ "CTL0023", quirk_awe32_resources },
/* CMI 8330 interrupt and dma fix */
{ "@X@0001", quirk_cmi8330_resources },
/* Soundblaster audio device io port range quirk */
{ "CTL0001", quirk_sb16audio_resources },
{ "CTL0031", quirk_sb16audio_resources },
{ "CTL0041", quirk_sb16audio_resources },
{ "CTL0042", quirk_sb16audio_resources },
{ "CTL0043", quirk_sb16audio_resources },
{ "CTL0044", quirk_sb16audio_resources },
{ "CTL0045", quirk_sb16audio_resources },
{ "" }
};
void pnp_fixup_device(struct pnp_dev *dev)
{
int i = 0;
while (*pnp_fixups[i].id) {
if (compare_pnp_id(dev->id,pnp_fixups[i].id)) {
pnp_dbg("Calling quirk for %s",
dev->dev.bus_id);
pnp_fixups[i].quirk_function(dev);
}
i++;
}
}
| {'content_hash': '1e22f9d2c4896024df5cafd48cf8bcff', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 80, 'avg_line_length': 24.954887218045112, 'alnum_prop': 0.6444712262729738, 'repo_name': 'impedimentToProgress/UCI-BlueChip', 'id': 'e97ecefe85841c966be495f27588ea128684bc25', 'size': '3772', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'snapgear_linux/linux-2.6.21.1/drivers/pnp/quirks.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AGS Script', 'bytes': '25338'}, {'name': 'ASP', 'bytes': '4526'}, {'name': 'Ada', 'bytes': '1075367'}, {'name': 'Assembly', 'bytes': '2137017'}, {'name': 'Awk', 'bytes': '133306'}, {'name': 'Bison', 'bytes': '399484'}, {'name': 'BlitzBasic', 'bytes': '101509'}, {'name': 'C', 'bytes': '288543995'}, {'name': 'C++', 'bytes': '7495614'}, {'name': 'CSS', 'bytes': '2128'}, {'name': 'Clojure', 'bytes': '3747'}, {'name': 'Common Lisp', 'bytes': '239683'}, {'name': 'Elixir', 'bytes': '790'}, {'name': 'Emacs Lisp', 'bytes': '45827'}, {'name': 'Erlang', 'bytes': '171340'}, {'name': 'GAP', 'bytes': '3002'}, {'name': 'Groff', 'bytes': '4517911'}, {'name': 'Groovy', 'bytes': '26513'}, {'name': 'HTML', 'bytes': '8141161'}, {'name': 'Java', 'bytes': '481441'}, {'name': 'JavaScript', 'bytes': '339345'}, {'name': 'Logos', 'bytes': '16160'}, {'name': 'M', 'bytes': '2443'}, {'name': 'Makefile', 'bytes': '1309237'}, {'name': 'Max', 'bytes': '3812'}, {'name': 'Nemerle', 'bytes': '966202'}, {'name': 'Objective-C', 'bytes': '376270'}, {'name': 'OpenEdge ABL', 'bytes': '69290'}, {'name': 'PHP', 'bytes': '11533'}, {'name': 'PLSQL', 'bytes': '8464'}, {'name': 'Pascal', 'bytes': '54420'}, {'name': 'Perl', 'bytes': '6498220'}, {'name': 'Perl6', 'bytes': '4155'}, {'name': 'Prolog', 'bytes': '62574'}, {'name': 'Python', 'bytes': '24287'}, {'name': 'QMake', 'bytes': '8619'}, {'name': 'R', 'bytes': '25999'}, {'name': 'Ruby', 'bytes': '31311'}, {'name': 'SAS', 'bytes': '15573'}, {'name': 'Scala', 'bytes': '1506'}, {'name': 'Scilab', 'bytes': '23534'}, {'name': 'Shell', 'bytes': '6951414'}, {'name': 'Smalltalk', 'bytes': '2661'}, {'name': 'Stata', 'bytes': '7930'}, {'name': 'Tcl', 'bytes': '1518344'}, {'name': 'TeX', 'bytes': '1574651'}, {'name': 'UnrealScript', 'bytes': '20822'}, {'name': 'VHDL', 'bytes': '37384578'}, {'name': 'Verilog', 'bytes': '376626'}, {'name': 'Visual Basic', 'bytes': '180'}, {'name': 'XS', 'bytes': '24500'}, {'name': 'XSLT', 'bytes': '5872'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other contributors as indicated by the @author tags.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>keycloak-integration-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>999-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-admin-client</artifactId>
<name>Keycloak Admin REST Client</name>
<description/>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-common</artifactId>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
</dependencies>
</project>
| {'content_hash': '03ae7c74d318384fefe7b53ddea73e3b', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 108, 'avg_line_length': 37.078947368421055, 'alnum_prop': 0.6036195883605394, 'repo_name': 'keycloak/keycloak', 'id': 'fd53370256aa03be3c3eb147bd300b90d9c06fff', 'size': '2818', 'binary': False, 'copies': '9', 'ref': 'refs/heads/main', 'path': 'integration/admin-client/pom.xml', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '1552'}, {'name': 'Batchfile', 'bytes': '1605'}, {'name': 'CSS', 'bytes': '33151'}, {'name': 'Dockerfile', 'bytes': '5560'}, {'name': 'Fluent', 'bytes': '217'}, {'name': 'FreeMarker', 'bytes': '225274'}, {'name': 'Gnuplot', 'bytes': '2173'}, {'name': 'Groovy', 'bytes': '4915'}, {'name': 'HTML', 'bytes': '1067837'}, {'name': 'Java', 'bytes': '34572191'}, {'name': 'JavaScript', 'bytes': '1139293'}, {'name': 'Scala', 'bytes': '67371'}, {'name': 'Shell', 'bytes': '71627'}, {'name': 'TypeScript', 'bytes': '206123'}, {'name': 'XSLT', 'bytes': '39257'}]} |
import warnings
from abc import abstractmethod
from typing import TYPE_CHECKING, Optional
from pyflink.common.serialization import BulkWriterFactory, RowDataBulkWriterFactory
if TYPE_CHECKING:
from pyflink.table.types import RowType
from pyflink.common import Duration, Encoder
from pyflink.datastream.connectors import Source, Sink
from pyflink.datastream.connectors.base import SupportsPreprocessing, StreamTransformer
from pyflink.datastream.functions import SinkFunction
from pyflink.common.utils import JavaObjectWrapper
from pyflink.java_gateway import get_gateway
from pyflink.util.java_utils import to_jarray, is_instance_of
__all__ = [
'FileCompactor',
'FileCompactStrategy',
'OutputFileConfig',
'FileSource',
'FileSourceBuilder',
'FileSink',
'StreamingFileSink',
'StreamFormat',
'BulkFormat',
'FileEnumeratorProvider',
'FileSplitAssignerProvider',
'RollingPolicy',
'BucketAssigner'
]
# ---- FileSource ----
class FileEnumeratorProvider(object):
"""
Factory for FileEnumerator which task is to discover all files to be read and to split them
into a set of file source splits. This includes possibly, path traversals, file filtering
(by name or other patterns) and deciding whether to split files into multiple splits, and
how to split them.
"""
def __init__(self, j_file_enumerator_provider):
self._j_file_enumerator_provider = j_file_enumerator_provider
@staticmethod
def default_splittable_file_enumerator() -> 'FileEnumeratorProvider':
"""
The default file enumerator used for splittable formats. The enumerator recursively
enumerates files, split files that consist of multiple distributed storage blocks into
multiple splits, and filters hidden files (files starting with '.' or '_'). Files with
suffixes of common compression formats (for example '.gzip', '.bz2', '.xy', '.zip', ...)
will not be split.
"""
JFileSource = get_gateway().jvm.org.apache.flink.connector.file.src.FileSource
return FileEnumeratorProvider(JFileSource.DEFAULT_SPLITTABLE_FILE_ENUMERATOR)
@staticmethod
def default_non_splittable_file_enumerator() -> 'FileEnumeratorProvider':
"""
The default file enumerator used for non-splittable formats. The enumerator recursively
enumerates files, creates one split for the file, and filters hidden files
(files starting with '.' or '_').
"""
JFileSource = get_gateway().jvm.org.apache.flink.connector.file.src.FileSource
return FileEnumeratorProvider(JFileSource.DEFAULT_NON_SPLITTABLE_FILE_ENUMERATOR)
class FileSplitAssignerProvider(object):
"""
Factory for FileSplitAssigner which is responsible for deciding what split should be
processed next by which node. It determines split processing order and locality.
"""
def __init__(self, j_file_split_assigner):
self._j_file_split_assigner = j_file_split_assigner
@staticmethod
def locality_aware_split_assigner() -> 'FileSplitAssignerProvider':
"""
A FileSplitAssigner that assigns to each host preferably splits that are local, before
assigning splits that are not local.
"""
JFileSource = get_gateway().jvm.org.apache.flink.connector.file.src.FileSource
return FileSplitAssignerProvider(JFileSource.DEFAULT_SPLIT_ASSIGNER)
class StreamFormat(object):
"""
A reader format that reads individual records from a stream.
Compared to the :class:`~BulkFormat`, the stream format handles a few things out-of-the-box,
like deciding how to batch records or dealing with compression.
Internally in the file source, the readers pass batches of records from the reading threads
(that perform the typically blocking I/O operations) to the async mailbox threads that do
the streaming and batch data processing. Passing records in batches
(rather than one-at-a-time) much reduces the thread-to-thread handover overhead.
This batching is by default based on I/O fetch size for the StreamFormat, meaning the
set of records derived from one I/O buffer will be handed over as one. See config option
`source.file.stream.io-fetch-size` to configure that fetch size.
"""
def __init__(self, j_stream_format):
self._j_stream_format = j_stream_format
@staticmethod
def text_line_format(charset_name: str = "UTF-8") -> 'StreamFormat':
"""
Creates a reader format that text lines from a file.
The reader uses Java's built-in java.io.InputStreamReader to decode the byte stream
using various supported charset encodings.
This format does not support optimized recovery from checkpoints. On recovery, it will
re-read and discard the number of lined that were processed before the last checkpoint.
That is due to the fact that the offsets of lines in the file cannot be tracked through
the charset decoders with their internal buffering of stream input and charset decoder
state.
:param charset_name: The charset to decode the byte stream.
"""
j_stream_format = get_gateway().jvm.org.apache.flink.connector.file.src.reader. \
TextLineInputFormat(charset_name)
return StreamFormat(j_stream_format)
class BulkFormat(object):
"""
The BulkFormat reads and decodes batches of records at a time. Examples of bulk formats are
formats like ORC or Parquet.
Internally in the file source, the readers pass batches of records from the reading threads
(that perform the typically blocking I/O operations) to the async mailbox threads that do the
streaming and batch data processing. Passing records in batches (rather than one-at-a-time) much
reduce the thread-to-thread handover overhead.
For the BulkFormat, one batch is handed over as one.
.. versionadded:: 1.16.0
"""
def __init__(self, j_bulk_format):
self._j_bulk_format = j_bulk_format
class FileSourceBuilder(object):
"""
The builder for the :class:`~FileSource`, to configure the various behaviors.
Start building the source via one of the following methods:
- :func:`~FileSource.for_record_stream_format`
"""
def __init__(self, j_file_source_builder):
self._j_file_source_builder = j_file_source_builder
def monitor_continuously(
self,
discovery_interval: Duration) -> 'FileSourceBuilder':
"""
Sets this source to streaming ("continuous monitoring") mode.
This makes the source a "continuous streaming" source that keeps running, monitoring
for new files, and reads these files when they appear and are discovered by the
monitoring.
The interval in which the source checks for new files is the discovery_interval. Shorter
intervals mean that files are discovered more quickly, but also imply more frequent
listing or directory traversal of the file system / object store.
"""
self._j_file_source_builder.monitorContinuously(discovery_interval._j_duration)
return self
def process_static_file_set(self) -> 'FileSourceBuilder':
"""
Sets this source to bounded (batch) mode.
In this mode, the source processes the files that are under the given paths when the
application is started. Once all files are processed, the source will finish.
This setting is also the default behavior. This method is mainly here to "switch back"
to bounded (batch) mode, or to make it explicit in the source construction.
"""
self._j_file_source_builder.processStaticFileSet()
return self
def set_file_enumerator(
self,
file_enumerator: 'FileEnumeratorProvider') -> 'FileSourceBuilder':
"""
Configures the FileEnumerator for the source. The File Enumerator is responsible
for selecting from the input path the set of files that should be processed (and which
to filter out). Furthermore, the File Enumerator may split the files further into
sub-regions, to enable parallelization beyond the number of files.
"""
self._j_file_source_builder.setFileEnumerator(
file_enumerator._j_file_enumerator_provider)
return self
def set_split_assigner(
self,
split_assigner: 'FileSplitAssignerProvider') -> 'FileSourceBuilder':
"""
Configures the FileSplitAssigner for the source. The File Split Assigner
determines which parallel reader instance gets which {@link FileSourceSplit}, and in
which order these splits are assigned.
"""
self._j_file_source_builder.setSplitAssigner(split_assigner._j_file_split_assigner)
return self
def build(self) -> 'FileSource':
"""
Creates the file source with the settings applied to this builder.
"""
return FileSource(self._j_file_source_builder.build())
class FileSource(Source):
"""
A unified data source that reads files - both in batch and in streaming mode.
This source supports all (distributed) file systems and object stores that can be accessed via
the Flink's FileSystem class.
Start building a file source via one of the following calls:
- :func:`~FileSource.for_record_stream_format`
This creates a :class:`~FileSource.FileSourceBuilder` on which you can configure all the
properties of the file source.
<h2>Batch and Streaming</h2>
This source supports both bounded/batch and continuous/streaming data inputs. For the
bounded/batch case, the file source processes all files under the given path(s). In the
continuous/streaming case, the source periodically checks the paths for new files and will start
reading those.
When you start creating a file source (via the
:class:`~FileSource.FileSourceBuilder` created through one of the above-mentioned methods)
the source is by default in bounded/batch mode. Call
:func:`~FileSource.FileSourceBuilder.monitor_continuously` to put the source into continuous
streaming mode.
<h2>Format Types</h2>
The reading of each file happens through file readers defined by <i>file formats</i>. These
define the parsing logic for the contents of the file. There are multiple classes that the
source supports. Their interfaces trade of simplicity of implementation and
flexibility/efficiency.
- A :class:`~FileSource.StreamFormat` reads the contents of a file from a file stream.
It is the simplest format to implement, and provides many features out-of-the-box
(like checkpointing logic) but is limited in the optimizations it
can apply (such as object reuse, batching, etc.).
<h2>Discovering / Enumerating Files</h2>
The way that the source lists the files to be processes is defined by the
:class:`~FileSource.FileEnumeratorProvider`. The FileEnumeratorProvider is responsible to
select the relevant files (for example filter out hidden files) and to optionally splits files
into multiple regions (= file source splits) that can be read in parallel).
"""
def __init__(self, j_file_source):
super(FileSource, self).__init__(source=j_file_source)
@staticmethod
def for_record_stream_format(stream_format: StreamFormat, *paths: str) -> FileSourceBuilder:
"""
Builds a new FileSource using a :class:`~FileSource.StreamFormat` to read record-by-record
from a file stream.
When possible, stream-based formats are generally easier (preferable) to file-based
formats, because they support better default behavior around I/O batching or progress
tracking (checkpoints).
Stream formats also automatically de-compress files based on the file extension. This
supports files ending in ".deflate" (Deflate), ".xz" (XZ), ".bz2" (BZip2), ".gz", ".gzip"
(GZip).
"""
JPath = get_gateway().jvm.org.apache.flink.core.fs.Path
JFileSource = get_gateway().jvm.org.apache.flink.connector.file.src.FileSource
j_paths = to_jarray(JPath, [JPath(p) for p in paths])
return FileSourceBuilder(
JFileSource.forRecordStreamFormat(stream_format._j_stream_format, j_paths))
@staticmethod
def for_bulk_file_format(bulk_format: BulkFormat, *paths: str) -> FileSourceBuilder:
JPath = get_gateway().jvm.org.apache.flink.core.fs.Path
JFileSource = get_gateway().jvm.org.apache.flink.connector.file.src.FileSource
j_paths = to_jarray(JPath, [JPath(p) for p in paths])
return FileSourceBuilder(
JFileSource.forBulkFileFormat(bulk_format._j_bulk_format, j_paths))
# ---- FileSink ----
class BucketAssigner(JavaObjectWrapper):
"""
A BucketAssigner is used with a file sink to determine the bucket each incoming element should
be put into.
The StreamingFileSink can be writing to many buckets at a time, and it is responsible
for managing a set of active buckets. Whenever a new element arrives it will ask the
BucketAssigner for the bucket the element should fall in. The BucketAssigner can, for
example, determine buckets based on system time.
"""
def __init__(self, j_bucket_assigner):
super().__init__(j_bucket_assigner)
@staticmethod
def base_path_bucket_assigner() -> 'BucketAssigner':
"""
Creates a BucketAssigner that does not perform any bucketing of files. All files are
written to the base path.
"""
return BucketAssigner(get_gateway().jvm.org.apache.flink.streaming.api.functions.sink.
filesystem.bucketassigners.BasePathBucketAssigner())
@staticmethod
def date_time_bucket_assigner(format_str: str = "yyyy-MM-dd--HH", timezone_id: str = None):
"""
Creates a BucketAssigner that assigns to buckets based on current system time.
It will create directories of the following form: /{basePath}/{dateTimePath}/}.
The basePath is the path that was specified as a base path when creating the new bucket.
The dateTimePath is determined based on the current system time and the user provided format
string.
The Java DateTimeFormatter is used to derive a date string from the current system time and
the date format string. The default format string is "yyyy-MM-dd--HH" so the rolling files
will have a granularity of hours.
:param format_str: The format string used to determine the bucket id.
:param timezone_id: The timezone id, either an abbreviation such as "PST", a full name
such as "America/Los_Angeles", or a custom timezone_id such as
"GMT-08:00". Th e default time zone will b used if it's None.
"""
if timezone_id is not None and isinstance(timezone_id, str):
j_timezone = get_gateway().jvm.java.time.ZoneId.of(timezone_id)
else:
j_timezone = get_gateway().jvm.java.time.ZoneId.systemDefault()
return BucketAssigner(
get_gateway().jvm.org.apache.flink.streaming.api.functions.sink.
filesystem.bucketassigners.DateTimeBucketAssigner(format_str, j_timezone))
class RollingPolicy(JavaObjectWrapper):
"""
The policy based on which a Bucket in the FileSink rolls its currently
open part file and opens a new one.
"""
def __init__(self, j_rolling_policy):
super().__init__(j_rolling_policy)
@staticmethod
def default_rolling_policy(
part_size: int = 1024 * 1024 * 128,
rollover_interval: int = 60 * 1000,
inactivity_interval: int = 60 * 1000) -> 'DefaultRollingPolicy':
"""
Returns the default implementation of the RollingPolicy.
This policy rolls a part file if:
- there is no open part file,
- the current file has reached the maximum bucket size (by default 128MB),
- the current file is older than the roll over interval (by default 60 sec), or
- the current file has not been written to for more than the allowed inactivityTime (by
default 60 sec).
:param part_size: The maximum part file size before rolling.
:param rollover_interval: The maximum time duration a part file can stay open before
rolling.
:param inactivity_interval: The time duration of allowed inactivity after which a part file
will have to roll.
"""
JDefaultRollingPolicy = get_gateway().jvm.org.apache.flink.streaming.api.functions.\
sink.filesystem.rollingpolicies.DefaultRollingPolicy
j_rolling_policy = JDefaultRollingPolicy.builder()\
.withMaxPartSize(part_size) \
.withRolloverInterval(rollover_interval) \
.withInactivityInterval(inactivity_interval) \
.build()
return DefaultRollingPolicy(j_rolling_policy)
@staticmethod
def on_checkpoint_rolling_policy() -> 'OnCheckpointRollingPolicy':
"""
Returns a RollingPolicy which rolls (ONLY) on every checkpoint.
"""
JOnCheckpointRollingPolicy = get_gateway().jvm.org.apache.flink.streaming.api.functions. \
sink.filesystem.rollingpolicies.OnCheckpointRollingPolicy
return OnCheckpointRollingPolicy(JOnCheckpointRollingPolicy.build())
class DefaultRollingPolicy(RollingPolicy):
"""
The default implementation of the RollingPolicy.
This policy rolls a part file if:
- there is no open part file,
- the current file has reached the maximum bucket size (by default 128MB),
- the current file is older than the roll over interval (by default 60 sec), or
- the current file has not been written to for more than the allowed inactivityTime (by
default 60 sec).
"""
def __init__(self, j_rolling_policy):
super().__init__(j_rolling_policy)
class OnCheckpointRollingPolicy(RollingPolicy):
"""
A RollingPolicy which rolls (ONLY) on every checkpoint.
"""
def __init__(self, j_rolling_policy):
super().__init__(j_rolling_policy)
class OutputFileConfig(JavaObjectWrapper):
"""
Part file name configuration.
This allow to define a prefix and a suffix to the part file name.
"""
@staticmethod
def builder():
return OutputFileConfig.OutputFileConfigBuilder()
def __init__(self, part_prefix: str, part_suffix: str):
filesystem = get_gateway().jvm.org.apache.flink.streaming.api.functions.sink.filesystem
self._j_output_file_config = filesystem.OutputFileConfig(part_prefix, part_suffix)
super().__init__(self._j_output_file_config)
def get_part_prefix(self) -> str:
"""
The prefix for the part name.
"""
return self._j_output_file_config.getPartPrefix()
def get_part_suffix(self) -> str:
"""
The suffix for the part name.
"""
return self._j_output_file_config.getPartSuffix()
class OutputFileConfigBuilder(object):
"""
A builder to create the part file configuration.
"""
def __init__(self):
self.part_prefix = "part"
self.part_suffix = ""
def with_part_prefix(self, prefix) -> 'OutputFileConfig.OutputFileConfigBuilder':
self.part_prefix = prefix
return self
def with_part_suffix(self, suffix) -> 'OutputFileConfig.OutputFileConfigBuilder':
self.part_suffix = suffix
return self
def build(self) -> 'OutputFileConfig':
return OutputFileConfig(self.part_prefix, self.part_suffix)
class FileCompactStrategy(JavaObjectWrapper):
"""
Strategy for compacting the files written in {@link FileSink} before committing.
.. versionadded:: 1.16.0
"""
def __init__(self, j_file_compact_strategy):
super().__init__(j_file_compact_strategy)
@staticmethod
def builder() -> 'FileCompactStrategy.Builder':
return FileCompactStrategy.Builder()
class Builder(object):
def __init__(self):
JFileCompactStrategy = get_gateway().jvm.org.apache.flink.connector.file.sink.\
compactor.FileCompactStrategy
self._j_builder = JFileCompactStrategy.Builder.newBuilder()
def build(self) -> 'FileCompactStrategy':
return FileCompactStrategy(self._j_builder.build())
def enable_compaction_on_checkpoint(self, num_checkpoints_before_compaction: int) \
-> 'FileCompactStrategy.Builder':
"""
Optional, compaction will be triggered when N checkpoints passed since the last
triggering, -1 by default indicating no compaction on checkpoint.
"""
self._j_builder.enableCompactionOnCheckpoint(num_checkpoints_before_compaction)
return self
def set_size_threshold(self, size_threshold: int) -> 'FileCompactStrategy.Builder':
"""
Optional, compaction will be triggered when the total size of compacting files reaches
the threshold. -1 by default, indicating the size is unlimited.
"""
self._j_builder.setSizeThreshold(size_threshold)
return self
def set_num_compact_threads(self, num_compact_threads: int) \
-> 'FileCompactStrategy.Builder':
"""
Optional, the count of compacting threads in a compactor operator, 1 by default.
"""
self._j_builder.setNumCompactThreads(num_compact_threads)
return self
class FileCompactor(JavaObjectWrapper):
"""
The FileCompactor is responsible for compacting files into one file.
.. versionadded:: 1.16.0
"""
def __init__(self, j_file_compactor):
super().__init__(j_file_compactor)
@staticmethod
def concat_file_compactor(file_delimiter: bytes = None):
"""
Returns a file compactor that simply concat the compacting files. The file_delimiter will be
added between neighbouring files if provided.
"""
JConcatFileCompactor = get_gateway().jvm.org.apache.flink.connector.file.sink.compactor.\
ConcatFileCompactor
if file_delimiter:
return FileCompactor(JConcatFileCompactor(file_delimiter))
else:
return FileCompactor(JConcatFileCompactor())
@staticmethod
def identical_file_compactor():
"""
Returns a file compactor that directly copy the content of the only input file to the
output.
"""
JIdenticalFileCompactor = get_gateway().jvm.org.apache.flink.connector.file.sink.compactor.\
IdenticalFileCompactor
return FileCompactor(JIdenticalFileCompactor())
class FileSink(Sink, SupportsPreprocessing):
"""
A unified sink that emits its input elements to FileSystem files within buckets. This
sink achieves exactly-once semantics for both BATCH and STREAMING.
When creating the sink a basePath must be specified. The base directory contains one
directory for every bucket. The bucket directories themselves contain several part files, with
at least one for each parallel subtask of the sink which is writing data to that bucket.
These part files contain the actual output data.
The sink uses a BucketAssigner to determine in which bucket directory each element
should be written to inside the base directory. The BucketAssigner can, for example, roll
on every checkpoint or use time or a property of the element to determine the bucket directory.
The default BucketAssigner is a DateTimeBucketAssigner which will create one new
bucket every hour. You can specify a custom BucketAssigner using the
:func:`~FileSink.RowFormatBuilder.with_bucket_assigner`, after calling
:class:`~FileSink.for_row_format`.
The names of the part files could be defined using OutputFileConfig. This
configuration contains a part prefix and a part suffix that will be used with a random uid
assigned to each subtask of the sink and a rolling counter to determine the file names. For
example with a prefix "prefix" and a suffix ".ext", a file named {@code
"prefix-81fc4980-a6af-41c8-9937-9939408a734b-17.ext"} contains the data from subtask with uid
{@code 81fc4980-a6af-41c8-9937-9939408a734b} of the sink and is the {@code 17th} part-file
created by that subtask.
Part files roll based on the user-specified RollingPolicy. By default, a DefaultRollingPolicy
is used for row-encoded sink output; a OnCheckpointRollingPolicy is
used for bulk-encoded sink output.
In some scenarios, the open buckets are required to change based on time. In these cases, the
user can specify a bucket_check_interval (by default 1m) and the sink will check
periodically and roll the part file if the specified rolling policy says so.
Part files can be in one of three states: in-progress, pending or finished. The reason for this
is how the sink works to provide exactly-once semantics and fault-tolerance. The part file that
is currently being written to is in-progress. Once a part file is closed for writing it becomes
pending. When a checkpoint is successful (for STREAMING) or at the end of the job (for BATCH)
the currently pending files will be moved to finished.
For STREAMING in order to guarantee exactly-once semantics in case of a failure, the
sink should roll back to the state it had when that last successful checkpoint occurred. To this
end, when restoring, the restored files in pending state are transferred into the finished state
while any in-progress files are rolled back, so that they do not contain data that arrived after
the checkpoint from which we restore.
"""
def __init__(self, j_file_sink, transformer: Optional[StreamTransformer] = None):
super(FileSink, self).__init__(sink=j_file_sink)
self._transformer = transformer
def get_transformer(self) -> Optional[StreamTransformer]:
return self._transformer
class BaseBuilder(object):
def __init__(self, j_builder):
self._j_builder = j_builder
def with_bucket_check_interval(self, interval: int):
"""
:param interval: The check interval in milliseconds.
"""
self._j_builder.withBucketCheckInterval(interval)
return self
def with_bucket_assigner(self, bucket_assigner: BucketAssigner):
self._j_builder.withBucketAssigner(bucket_assigner.get_java_object())
return self
def with_output_file_config(self, output_file_config: OutputFileConfig):
self._j_builder.withOutputFileConfig(output_file_config.get_java_object())
return self
def enable_compact(self, strategy: FileCompactStrategy, compactor: FileCompactor):
self._j_builder.enableCompact(strategy.get_java_object(), compactor.get_java_object())
return self
def disable_compact(self):
self._j_builder.disableCompact()
return self
@abstractmethod
def with_rolling_policy(self, rolling_policy):
pass
def build(self):
return FileSink(self._j_builder.build())
class RowFormatBuilder(BaseBuilder):
"""
Builder for the vanilla FileSink using a row format.
.. versionchanged:: 1.16.0
Support compaction.
"""
def __init__(self, j_row_format_builder):
super().__init__(j_row_format_builder)
def with_rolling_policy(self, rolling_policy: RollingPolicy):
self._j_builder.withRollingPolicy(rolling_policy.get_java_object())
return self
@staticmethod
def for_row_format(base_path: str, encoder: Encoder) -> 'FileSink.RowFormatBuilder':
JPath = get_gateway().jvm.org.apache.flink.core.fs.Path
JFileSink = get_gateway().jvm.org.apache.flink.connector.file.sink.FileSink
return FileSink.RowFormatBuilder(
JFileSink.forRowFormat(JPath(base_path), encoder._j_encoder))
class BulkFormatBuilder(BaseBuilder):
"""
Builder for the vanilla FileSink using a bulk format.
.. versionadded:: 1.16.0
"""
def __init__(self, j_bulk_format_builder):
super().__init__(j_bulk_format_builder)
self._transformer = None
def with_rolling_policy(self, rolling_policy: OnCheckpointRollingPolicy):
if not isinstance(rolling_policy, OnCheckpointRollingPolicy):
raise ValueError('rolling_policy must be OnCheckpointRollingPolicy for bulk format')
return self
def _with_row_type(self, row_type: 'RowType') -> 'FileSink.BulkFormatBuilder':
from pyflink.datastream.data_stream import DataStream
from pyflink.table.types import _to_java_data_type
def _check_if_row_data_type(ds) -> bool:
j_type_info = ds._j_data_stream.getType()
if not is_instance_of(
j_type_info,
'org.apache.flink.table.runtime.typeutils.InternalTypeInfo'
):
return False
return is_instance_of(
j_type_info.toLogicalType(),
'org.apache.flink.table.types.logical.RowType'
)
class RowRowTransformer(StreamTransformer):
def apply(self, ds):
jvm = get_gateway().jvm
if _check_if_row_data_type(ds):
return ds
j_map_function = jvm.org.apache.flink.python.util.PythonConnectorUtils \
.RowRowMapper(_to_java_data_type(row_type))
return DataStream(ds._j_data_stream.process(j_map_function))
self._transformer = RowRowTransformer()
return self
def build(self) -> 'FileSink':
return FileSink(self._j_builder.build(), self._transformer)
@staticmethod
def for_bulk_format(base_path: str, writer_factory: BulkWriterFactory) \
-> 'FileSink.BulkFormatBuilder':
jvm = get_gateway().jvm
j_path = jvm.org.apache.flink.core.fs.Path(base_path)
JFileSink = jvm.org.apache.flink.connector.file.sink.FileSink
builder = FileSink.BulkFormatBuilder(
JFileSink.forBulkFormat(j_path, writer_factory.get_java_object())
)
if isinstance(writer_factory, RowDataBulkWriterFactory):
return builder._with_row_type(writer_factory.get_row_type())
else:
return builder
# ---- StreamingFileSink ----
class StreamingFileSink(SinkFunction):
"""
Sink that emits its input elements to `FileSystem` files within buckets. This is
integrated with the checkpointing mechanism to provide exactly once semantics.
When creating the sink a `basePath` must be specified. The base directory contains
one directory for every bucket. The bucket directories themselves contain several part files,
with at least one for each parallel subtask of the sink which is writing data to that bucket.
These part files contain the actual output data.
"""
def __init__(self, j_obj):
warnings.warn("Deprecated in 1.15. Use FileSink instead.", DeprecationWarning)
super(StreamingFileSink, self).__init__(j_obj)
class BaseBuilder(object):
def __init__(self, j_builder):
self._j_builder = j_builder
def with_bucket_check_interval(self, interval: int):
self._j_builder.withBucketCheckInterval(interval)
return self
def with_bucket_assigner(self, bucket_assigner: BucketAssigner):
self._j_builder.withBucketAssigner(bucket_assigner.get_java_object())
return self
@abstractmethod
def with_rolling_policy(self, policy):
pass
def with_output_file_config(self, output_file_config: OutputFileConfig):
self._j_builder.withOutputFileConfig(output_file_config.get_java_object())
return self
def build(self) -> 'StreamingFileSink':
j_stream_file_sink = self._j_builder.build()
return StreamingFileSink(j_stream_file_sink)
class DefaultRowFormatBuilder(BaseBuilder):
"""
Builder for the vanilla `StreamingFileSink` using a row format.
"""
def __init__(self, j_default_row_format_builder):
super().__init__(j_default_row_format_builder)
def with_rolling_policy(self, policy: RollingPolicy):
self._j_builder.withRollingPolicy(policy.get_java_object())
return self
@staticmethod
def for_row_format(base_path: str, encoder: Encoder) -> 'DefaultRowFormatBuilder':
j_path = get_gateway().jvm.org.apache.flink.core.fs.Path(base_path)
j_default_row_format_builder = get_gateway().jvm.org.apache.flink.streaming.api.\
functions.sink.filesystem.StreamingFileSink.forRowFormat(j_path, encoder._j_encoder)
return StreamingFileSink.DefaultRowFormatBuilder(j_default_row_format_builder)
class DefaultBulkFormatBuilder(BaseBuilder):
def __init__(self, j_default_bulk_format_builder):
super().__init__(j_default_bulk_format_builder)
def with_rolling_policy(self, policy: OnCheckpointRollingPolicy):
self._j_builder.withRollingPolicy(policy.get_java_object())
return self
@staticmethod
def for_bulk_format(base_path: str, writer_factory: BulkWriterFactory):
jvm = get_gateway().jvm
j_path = jvm.org.apache.flink.core.fs.Path(base_path)
j_default_bulk_format_builder = jvm.org.apache.flink.streaming.api.functions.sink \
.filesystem.StreamingFileSink.forBulkFormat(j_path, writer_factory.get_java_object())
return StreamingFileSink.DefaultBulkFormatBuilder(j_default_bulk_format_builder)
| {'content_hash': '2c0bfa83b7d9e25487f2b146e463b0fc', 'timestamp': '', 'source': 'github', 'line_count': 821, 'max_line_length': 100, 'avg_line_length': 41.95736906211937, 'alnum_prop': 0.6744564112985165, 'repo_name': 'xccui/flink', 'id': '11ad3918ef3a5ab43e1c388a74cf4b4a4d3766d2', 'size': '35405', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'flink-python/pyflink/datastream/connectors/file_system.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '20596'}, {'name': 'Batchfile', 'bytes': '1863'}, {'name': 'C', 'bytes': '847'}, {'name': 'Cython', 'bytes': '138311'}, {'name': 'Dockerfile', 'bytes': '5579'}, {'name': 'FreeMarker', 'bytes': '100031'}, {'name': 'GAP', 'bytes': '139536'}, {'name': 'HTML', 'bytes': '188041'}, {'name': 'HiveQL', 'bytes': '213569'}, {'name': 'Java', 'bytes': '98600106'}, {'name': 'JavaScript', 'bytes': '7038'}, {'name': 'Less', 'bytes': '84321'}, {'name': 'Makefile', 'bytes': '5134'}, {'name': 'Python', 'bytes': '3206355'}, {'name': 'Scala', 'bytes': '10942352'}, {'name': 'Shell', 'bytes': '528784'}, {'name': 'TypeScript', 'bytes': '391270'}, {'name': 'q', 'bytes': '16671'}]} |
layout: "journal_by_tag"
tag: "light painting"
title: "Fisiogramas"
description: "Etiquetas"
permalink: "/blog/tag/light-painting/"
header-img: "img/archive-bg.jpg"
---
| {'content_hash': '709bb8ade639294919c962fce686ed4f', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 38, 'avg_line_length': 24.142857142857142, 'alnum_prop': 0.727810650887574, 'repo_name': 'davidhdz/davidhdz.github.io', 'id': 'f2cb5f8db7281d3ae62cc1713771378cfc5fbfdf', 'size': '173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'blog/tag/light-painting.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '45252'}, {'name': 'HTML', 'bytes': '282357'}, {'name': 'JavaScript', 'bytes': '72763'}, {'name': 'Ruby', 'bytes': '261'}]} |
<ul>
<li><p>This is a list item with two paragraphs.</p>
<p>This is the second paragraph in the list item. You're
only required to indent the first line. Lorem ipsum dolor
sit amet, consectetuer adipiscing elit.</p></li>
<li><p>Another item in the same list.</p></li>
</ul> | {'content_hash': '1c82eb953c0795df81a1dea74040ea20', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 60, 'avg_line_length': 31.88888888888889, 'alnum_prop': 0.6829268292682927, 'repo_name': 'taskworld/upndown', 'id': '6fa59a7c16b667a872bd1c07c5006eef99279c10', 'size': '287', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'test/fixtures/lists/ulist-p-inside.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2999'}, {'name': 'JavaScript', 'bytes': '302372'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '9676dd44b72e3d000a733f42463d0087', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '4a224349f145d235568dca30d835029d9337d3ac', 'size': '174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Gypsocallis/Gypsocallis pilosa/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
#import <Foundation/Foundation.h>
// Note: This file is included by Objective-C and Swift code,
// so it must not contain any C++ declarations.
@class Interpreter;
typedef unsigned char Char;
typedef int Number;
typedef NS_ENUM(NSInteger, InputResultKind)
{
InputResultKindValue,
InputResultKindEndOfStream,
InputResultKindWaiting
};
typedef struct
{
InputResultKind kind;
Char value; // only used when kind == InputResultKindValue
} InputCharResult;
// Functions for creating an InputCharResult with the appropriate kind
__BEGIN_DECLS
InputCharResult InputCharResult_Value(Char c);
InputCharResult InputCharResult_EndOfStream();
InputCharResult InputCharResult_Waiting();
__END_DECLS
/// Protocol implemented by object that provides I/O operations for an
/// Interpreter
@protocol InterpreterIO <NSObject>
/// Return next input character, or nil if at end-of-file or an error occurs
- (InputCharResult)getInputCharForInterpreter:(Interpreter *)interpreter;
/// Write specified output character
- (void)putOutputChar:(Char)c forInterpreter:(Interpreter *)interpreter;
/// Display a prompt to the user for entering an immediate command or line of
/// code
- (void)showCommandPromptForInterpreter:(Interpreter *)interpreter;
/// Display a prompt to the user for entering data for an INPUT statement
- (void)showInputPromptForInterpreter:(Interpreter *)interpreter;
/// Display error message to user
- (void)showErrorMessage:(NSString *)message
forInterpreter:(Interpreter *)interpreter;
/// Display a debug trace message
- (void)showDebugTraceMessage:(NSString *)message
forInterpreter:(Interpreter *)interpreter;
/// Called when BYE is executed
- (void)byeForInterpreter:(Interpreter *)interpreter;
@end
/// State of the interpreter
///
/// The interpreter begins in the `.Idle` state, which
/// causes it to immediately display a statement prompt
/// and then enter the `.ReadingStatement` state, where it
/// will process numbered and unnumbered statements.
///
/// A `RUN` statement will put it into `.Running` state, and it
/// will execute the stored program. If an `INPUT` statement
/// is executed, the interpreter will go into .ReadingInput
/// state until valid input is received, and it will return
/// to `.Running` state.
///
/// The state returns to `.ReadingStatement` on an `END`
/// statement or if `RUN` has to abort due to an error.
typedef NS_ENUM(NSInteger, InterpreterState)
{
/// Interpreter is not "doing anything".
///
/// When in this state, interpreter will display
/// statement prompt and then enter the
/// `ReadingStatement` state.
InterpreterStateIdle,
/// Interpreter is trying to read a statement/command
InterpreterStateReadingStatement,
/// Interpreter is running a program
InterpreterStateRunning,
/// Interpreter is processing an `INPUT` statement
InterpreterStateReadingInput
};
@interface Interpreter : NSObject <NSCoding>
@property id<InterpreterIO> io;
/// Initializer
- (instancetype)initWithInterpreterIO:(id<InterpreterIO>)interpreterIO;
/// Return the state of the interpreter as a property-list dictionary.
///
/// This property list can be used to restore interpreter state
/// with restoreStateFromPropertyList()
- (NSDictionary *)stateAsPropertyList;
/// Set interpreter's properties using archived state produced by stateAsPropertyList()'
- (void)restoreStateFromPropertyList:(NSDictionary *)propertyList;
/// Display prompt and read input lines and interpret them until end of input.
///
/// This method should only be used when `InterpreterIO.getInputChar()`
/// will never return `InputCharResult.Waiting`.
/// Otherwise, host should call `next()` in a loop.
- (void)runUntilEndOfInput;
/// Perform next operation.
///
/// The host can drive the interpreter by calling `next()`
/// in a loop.
- (void)next;
/// Return interpreter state
- (InterpreterState)state;
/// Halt running machine
- (void)breakExecution;
@end
| {'content_hash': 'b5ef6882daa68a8f4e19efc3c70590e6', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 88, 'avg_line_length': 30.265151515151516, 'alnum_prop': 0.7459324155193993, 'repo_name': 'kristopherjohnson/bitsybasic', 'id': '3cf06ab3f3bcd52b677813a3b353db2ab84a4523', 'size': '5062', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'finchlib_cpp/Interpreter.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '54067'}, {'name': 'Objective-C', 'bytes': '5194'}, {'name': 'Objective-C++', 'bytes': '85815'}, {'name': 'Swift', 'bytes': '153171'}]} |
DayZ-based loot-eating sim.
#### Clarification
This is "Squarenarus" not Chernarus+. This is not based on actual gameplay. The simulation assumes players are dumb drones that make a bee-line for their goal destination. Also, there's no where where loot collects, like towns with lots of buildings. Loot spawns randomly across the entire square.
# Description
Light green circles are "goal" areas where the blue "players" randomly choose to head towards when they spawn on the coast (bottom and right edges of the image.
Brown dots are "food" that the players need to live longer. Otherwise the player starved to death and a black dot is left behind.
The map is a flat square where loot can spawn anywhere randomly.
In this simulation, I have tried my best to replicate all the loot spawning rules of the 0.55 persistence system as described here: http://forums.dayzgame.com/index.php?/topic/223307-central-economy/
# Simulations
### http://www.gfycat.com/BogusFreshAsianporcupine
Less sped-up version here (also a shorter loot lifetime): http://www.gfycat.com/AmazingIncredibleHarrierhawk
# Lessons
* There's definately more food where player's havent been.
* A lower loot lifetime keeps loot from being too rare in high-traffic areas.
* Too low of a lifetime makes loot more likely to despawn when players are in the vicinity.
* The balance between calories food gives you, calories burned, loot lifetime, loot distribution, and starting hunger is difficult to achieve.
* There does exist a "barrier of death." Players either don't get enough food and die in it, or they pass it and thrive beyond it.
| {'content_hash': '30b7a932ac59c07d5392d4cc0b7ca1be', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 297, 'avg_line_length': 57.607142857142854, 'alnum_prop': 0.7848729076255425, 'repo_name': 'C222/Squarenarus', 'id': 'b368aee98c813dba03fbfc549cd464cf933561ee', 'size': '1627', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '6764'}]} |
package schema
import (
"expvar"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/mysql"
"github.com/youtube/vitess/go/mysql/fakesqldb"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/vt/sqlparser"
"github.com/youtube/vitess/go/vt/vttablet/tabletserver/schema/schematest"
"github.com/youtube/vitess/go/vt/vttablet/tabletserver/tabletenv"
querypb "github.com/youtube/vitess/go/vt/proto/query"
)
func TestOpenFailedDueToMissMySQLTime(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
db.AddQuery("select unix_timestamp()", &sqltypes.Result{
// Make this query fail by returning 2 values.
Fields: []*querypb.Field{
{Type: sqltypes.Uint64},
},
Rows: [][]sqltypes.Value{
{sqltypes.NewVarBinary("1427325875")},
{sqltypes.NewVarBinary("1427325875")},
},
})
se := newEngine(10, 1*time.Second, 1*time.Second, false)
err := se.Open(db.ConnParams())
want := "could not get MySQL time"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("se.Open: %v, want %s", err, want)
}
}
func TestOpenFailedDueToIncorrectMysqlRowNum(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
db.AddQuery("select unix_timestamp()", &sqltypes.Result{
Fields: []*querypb.Field{{
Type: sqltypes.Uint64,
}},
Rows: [][]sqltypes.Value{
// make this query fail by returning NULL
{sqltypes.NULL},
},
})
se := newEngine(10, 1*time.Second, 1*time.Second, false)
err := se.Open(db.ConnParams())
want := "unexpected result for MySQL time"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("se.Open: %v, want %s", err, want)
}
}
func TestOpenFailedDueToInvalidTimeFormat(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
db.AddQuery("select unix_timestamp()", &sqltypes.Result{
Fields: []*querypb.Field{{
Type: sqltypes.VarChar,
}},
Rows: [][]sqltypes.Value{
// make safety check fail, invalid time format
{sqltypes.NewVarBinary("invalid_time")},
},
})
se := newEngine(10, 1*time.Second, 1*time.Second, false)
err := se.Open(db.ConnParams())
want := "could not parse time"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("se.Open: %v, want %s", err, want)
}
}
func TestOpenFailedDueToExecErr(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
db.AddRejectedQuery(mysql.BaseShowTables, fmt.Errorf("injected error"))
se := newEngine(10, 1*time.Second, 1*time.Second, false)
err := se.Open(db.ConnParams())
want := "could not get table list"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("se.Open: %v, want %s", err, want)
}
}
func TestOpenFailedDueToTableErr(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
db.AddQuery(mysql.BaseShowTables, &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow("test_table", false, ""),
},
})
db.AddQuery("select * from test_table where 1 != 1", &sqltypes.Result{
// this will cause NewTable error, as it expects zero rows.
Fields: []*querypb.Field{
{
Type: querypb.Type_VARCHAR,
},
},
Rows: [][]sqltypes.Value{
{sqltypes.NewVarBinary("")},
},
})
se := newEngine(10, 1*time.Second, 1*time.Second, false)
err := se.Open(db.ConnParams())
want := "could not get schema for any tables"
if err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("se.Open: %v, want %s", err, want)
}
}
func TestReload(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
ctx := context.Background()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
idleTimeout := 10 * time.Second
se := newEngine(10, 10*time.Second, idleTimeout, true)
se.Open(db.ConnParams())
defer se.Close()
// this new table does not exist
newTable := sqlparser.NewTableIdent("test_table_04")
table := se.GetTable(newTable)
if table != nil {
t.Fatalf("table: %s exists; expecting nil", newTable)
}
se.Reload(ctx)
table = se.GetTable(newTable)
if table != nil {
t.Fatalf("table: %s exists; expecting nil", newTable)
}
db.AddQuery(mysql.BaseShowTables, &sqltypes.Result{
// make this query return nothing during reload
Fields: mysql.BaseShowTablesFields,
})
db.AddQuery(mysql.BaseShowTablesForTable(newTable.String()), &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow(newTable.String(), false, ""),
},
})
db.AddQuery("select * from test_table_04 where 1 != 1", &sqltypes.Result{
Fields: []*querypb.Field{{
Name: "pk",
Type: sqltypes.Int32,
}},
})
db.AddQuery("describe test_table_04", &sqltypes.Result{
Fields: mysql.DescribeTableFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.DescribeTableRow("pk", "int(11)", false, "PRI", "0"),
},
})
db.AddQuery("show index from test_table_04", &sqltypes.Result{
Fields: mysql.ShowIndexFromTableFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.ShowIndexFromTableRow("test_table_04", true, "PRIMARY", 1, "pk", false),
},
})
se.Reload(ctx)
table = se.GetTable(newTable)
if table != nil {
t.Fatalf("table: %s exists; expecting nil", newTable)
}
// test reload with new table: test_table_04
db.AddQuery(mysql.BaseShowTables, &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow(newTable.String(), false, ""),
},
})
table = se.GetTable(newTable)
if table != nil {
t.Fatalf("table: %s exists; expecting nil", newTable)
}
if err := se.Reload(ctx); err != nil {
t.Fatalf("se.Reload() error: %v", err)
}
table = se.GetTable(newTable)
if table == nil {
t.Fatalf("table: %s should exist", newTable)
}
}
func TestCreateOrUpdateTableFailedDuetoExecErr(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
db.AddRejectedQuery(mysql.BaseShowTablesForTable("test_table"), fmt.Errorf("forced fail"))
se := newEngine(10, 1*time.Second, 1*time.Second, false)
se.Open(db.ConnParams())
defer se.Close()
originalSchemaErrorCount := tabletenv.InternalErrors.Counts()["Schema"]
// should silently fail: no errors returned, but increment a counter
se.TableWasCreatedOrAltered(context.Background(), "test_table")
newSchemaErrorCount := tabletenv.InternalErrors.Counts()["Schema"]
schemaErrorDiff := newSchemaErrorCount - originalSchemaErrorCount
if schemaErrorDiff != 1 {
t.Errorf("InternalErrors.Schema counter should have increased by 1, instead got %v", schemaErrorDiff)
}
}
func TestCreateOrUpdateTable(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
se := newEngine(10, 1*time.Second, 1*time.Second, false)
se.Open(db.ConnParams())
defer se.Close()
existingTable := "test_table_01"
db.AddQuery(mysql.BaseShowTablesForTable(existingTable), &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow(existingTable, false, ""),
},
})
i := 0
se.RegisterNotifier("test", func(schema map[string]*Table, created, altered, dropped []string) {
switch i {
case 0:
if len(created) != 5 {
t.Errorf("callback 0: %v, want len of 5\n", created)
}
case 1:
want := []string{"test_table_01"}
if !reflect.DeepEqual(altered, want) {
t.Errorf("callback 0: %v, want %v\n", created, want)
}
default:
t.Fatal("unexpected")
}
i++
})
defer se.UnregisterNotifier("test")
if err := se.TableWasCreatedOrAltered(context.Background(), "test_table_01"); err != nil {
t.Fatal(err)
}
if i < 2 {
t.Error("Notifier did not get called")
}
}
func TestExportVars(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
se := newEngine(10, 1*time.Second, 1*time.Second, true)
se.Open(db.ConnParams())
defer se.Close()
expvar.Do(func(kv expvar.KeyValue) {
_ = kv.Value.String()
})
}
func TestUpdatedMysqlStats(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
ctx := context.Background()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
idleTimeout := 10 * time.Second
se := newEngine(10, 10*time.Second, idleTimeout, true)
se.Open(db.ConnParams())
defer se.Close()
// Add new table
tableName := sqlparser.NewTableIdent("mysql_stats_test_table")
db.AddQuery(mysql.BaseShowTables, &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow(tableName.String(), false, ""),
},
})
// Add queries necessary for TableWasCreatedOrAltered() and NewTable()
db.AddQuery(mysql.BaseShowTablesForTable(tableName.String()), &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow(tableName.String(), false, ""),
},
})
q := fmt.Sprintf("select * from %s where 1 != 1", tableName)
db.AddQuery(q, &sqltypes.Result{
Fields: []*querypb.Field{{
Name: "pk",
Type: sqltypes.Int32,
}},
})
q = fmt.Sprintf("describe %s", tableName)
db.AddQuery(q, &sqltypes.Result{
Fields: mysql.DescribeTableFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.DescribeTableRow("pk", "int(11)", false, "PRI", "0"),
},
})
q = fmt.Sprintf("show index from %s", tableName)
db.AddQuery(q, &sqltypes.Result{
Fields: mysql.ShowIndexFromTableFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
mysql.ShowIndexFromTableRow(tableName.String(), true, "PRIMARY", 1, "pk", false),
},
})
if err := se.Reload(ctx); err != nil {
t.Fatalf("se.Reload() error: %v", err)
}
table := se.GetTable(tableName)
if table == nil {
t.Fatalf("table: %s should exist", tableName)
}
tr1 := table.TableRows
dl1 := table.DataLength
il1 := table.IndexLength
df1 := table.DataFree
mdl1 := table.MaxDataLength
// Update existing table with new stats.
row := mysql.BaseShowTablesRow(tableName.String(), false, "")
row[2] = sqltypes.NewUint64(0) // smaller timestamp
row[4] = sqltypes.NewUint64(2) // table_rows
row[5] = sqltypes.NewUint64(3) // data_length
row[6] = sqltypes.NewUint64(4) // index_length
row[7] = sqltypes.NewUint64(5) // data_free
row[8] = sqltypes.NewUint64(6) // max_data_length
db.AddQuery(mysql.BaseShowTables, &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
RowsAffected: 1,
Rows: [][]sqltypes.Value{
row,
},
})
if err := se.Reload(ctx); err != nil {
t.Fatalf("se.Reload() error: %v", err)
}
table = se.GetTable(tableName)
tr2 := table.TableRows
dl2 := table.DataLength
il2 := table.IndexLength
df2 := table.DataFree
mdl2 := table.MaxDataLength
if tr1 == tr2 || dl1 == dl2 || il1 == il2 || df1 == df2 || mdl1 == mdl2 {
t.Logf("%v==%v %v==%v %v==%v %v==%v %v==%v", tr1, tr2, dl1, dl2, il1, il2, df1, df2, mdl1, mdl2)
t.Fatalf("MysqlStats() results failed to change between queries. ")
}
}
func TestStatsURL(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
for query, result := range schematest.Queries() {
db.AddQuery(query, result)
}
se := newEngine(10, 1*time.Second, 1*time.Second, true)
se.Open(db.ConnParams())
defer se.Close()
request, _ := http.NewRequest("GET", "/debug/schema", nil)
response := httptest.NewRecorder()
se.ServeHTTP(response, request)
}
type dummyChecker struct {
}
func (dummyChecker) CheckMySQL() {}
var DummyChecker = dummyChecker{}
func newEngine(queryCacheSize int, reloadTime time.Duration, idleTimeout time.Duration, strict bool) *Engine {
config := tabletenv.DefaultQsConfig
config.QueryCacheSize = queryCacheSize
config.SchemaReloadTime = float64(reloadTime) / 1e9
config.IdleTimeout = float64(idleTimeout) / 1e9
return NewEngine(DummyChecker, config)
}
| {'content_hash': '5b5838726ab3c871261761c4def9c004', 'timestamp': '', 'source': 'github', 'line_count': 417, 'max_line_length': 110, 'avg_line_length': 29.203836930455637, 'alnum_prop': 0.6796682542289374, 'repo_name': 'rnavarro/vitess', 'id': 'b676a91ce25966a05bd3315b8e846d5555b476b1', 'size': '12735', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'go/vt/vttablet/tabletserver/schema/engine_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '213877'}, {'name': 'Go', 'bytes': '7674685'}, {'name': 'HTML', 'bytes': '58963'}, {'name': 'Java', 'bytes': '1169274'}, {'name': 'JavaScript', 'bytes': '43452'}, {'name': 'Liquid', 'bytes': '7287'}, {'name': 'Makefile', 'bytes': '9760'}, {'name': 'PHP', 'bytes': '1244834'}, {'name': 'Protocol Buffer', 'bytes': '142384'}, {'name': 'Python', 'bytes': '1103625'}, {'name': 'Ruby', 'bytes': '466'}, {'name': 'Shell', 'bytes': '62996'}, {'name': 'Smarty', 'bytes': '24438'}, {'name': 'TypeScript', 'bytes': '152739'}, {'name': 'Yacc', 'bytes': '46376'}]} |
FOUNDATION_EXPORT double Pods_Neuron_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Neuron_TestsVersionString[];
| {'content_hash': '3f4d609d20245c74308e27ae03efed35', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 71, 'avg_line_length': 43.333333333333336, 'alnum_prop': 0.8538461538461538, 'repo_name': 'Draveness/Neuron', 'id': '296055f50a237bc3e972ff71113a44db248af1b7', 'size': '156', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Example/Pods/Target Support Files/Pods-Neuron_Tests/Pods-Neuron_Tests-umbrella.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '846'}, {'name': 'Ruby', 'bytes': '1745'}, {'name': 'Shell', 'bytes': '14370'}, {'name': 'Swift', 'bytes': '6018'}]} |
require 'spec_helper'
describe Projects::AutocompleteService do
describe '#issues' do
describe 'confidential issues' do
let(:author) { create(:user) }
let(:assignee) { create(:user) }
let(:non_member) { create(:user) }
let(:member) { create(:user) }
let(:admin) { create(:admin) }
let(:project) { create(:project, :public) }
let!(:issue) { create(:issue, project: project, title: 'Issue 1') }
let!(:security_issue_1) { create(:issue, :confidential, project: project, title: 'Security issue 1', author: author) }
let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignees: [assignee]) }
it 'does not list project confidential issues for guests' do
autocomplete = described_class.new(project, nil)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).not_to include security_issue_1.iid
expect(issues).not_to include security_issue_2.iid
expect(issues.count).to eq 1
end
it 'does not list project confidential issues for non project members' do
autocomplete = described_class.new(project, non_member)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).not_to include security_issue_1.iid
expect(issues).not_to include security_issue_2.iid
expect(issues.count).to eq 1
end
it 'does not list project confidential issues for project members with guest role' do
project.add_guest(member)
autocomplete = described_class.new(project, non_member)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).not_to include security_issue_1.iid
expect(issues).not_to include security_issue_2.iid
expect(issues.count).to eq 1
end
it 'lists project confidential issues for author' do
autocomplete = described_class.new(project, author)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).to include security_issue_1.iid
expect(issues).not_to include security_issue_2.iid
expect(issues.count).to eq 2
end
it 'lists project confidential issues for assignee' do
autocomplete = described_class.new(project, assignee)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).not_to include security_issue_1.iid
expect(issues).to include security_issue_2.iid
expect(issues.count).to eq 2
end
it 'lists project confidential issues for project members' do
project.add_developer(member)
autocomplete = described_class.new(project, member)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).to include security_issue_1.iid
expect(issues).to include security_issue_2.iid
expect(issues.count).to eq 3
end
it 'lists all project issues for admin' do
autocomplete = described_class.new(project, admin)
issues = autocomplete.issues.map(&:iid)
expect(issues).to include issue.iid
expect(issues).to include security_issue_1.iid
expect(issues).to include security_issue_2.iid
expect(issues.count).to eq 3
end
end
end
describe '#milestones' do
let(:user) { create(:user) }
let(:group) { create(:group) }
let(:project) { create(:project, group: group) }
let!(:group_milestone1) { create(:milestone, group: group, due_date: '2017-01-01', title: 'Second Title') }
let!(:group_milestone2) { create(:milestone, group: group, due_date: '2017-01-01', title: 'First Title') }
let!(:project_milestone) { create(:milestone, project: project, due_date: '2016-01-01') }
let(:milestone_titles) { described_class.new(project, user).milestones.map(&:title) }
it 'includes project and group milestones and sorts them correctly' do
expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title, group_milestone1.title])
end
it 'does not include closed milestones' do
group_milestone1.close
expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title])
end
it 'does not include milestones from other projects in the group' do
other_project = create(:project, group: group)
project_milestone.update!(project: other_project)
expect(milestone_titles).to eq([group_milestone2.title, group_milestone1.title])
end
context 'with nested groups', :nested_groups do
let(:subgroup) { create(:group, :public, parent: group) }
let!(:subgroup_milestone) { create(:milestone, group: subgroup) }
before do
project.update(namespace: subgroup)
end
it 'includes project milestones and all acestors milestones' do
expect(milestone_titles).to match_array(
[project_milestone.title, group_milestone2.title, group_milestone1.title, subgroup_milestone.title]
)
end
end
end
describe '#labels_as_hash' do
def expect_labels_to_equal(labels, expected_labels)
expect(labels.size).to eq(expected_labels.size)
extract_title = lambda { |label| label['title'] }
expect(labels.map(&extract_title)).to eq(expected_labels.map(&extract_title))
end
let(:user) { create(:user) }
let(:group) { create(:group, :nested) }
let!(:sub_group) { create(:group, parent: group) }
let(:project) { create(:project, :public, group: group) }
let(:issue) { create(:issue, project: project) }
let!(:label1) { create(:label, project: project) }
let!(:label2) { create(:label, project: project) }
let!(:sub_group_label) { create(:group_label, group: sub_group) }
let!(:parent_group_label) { create(:group_label, group: group.parent, group_id: group.id) }
before do
create(:group_member, group: group, user: user)
end
it 'returns labels from project and ancestor groups' do
service = described_class.new(project, user)
results = service.labels_as_hash(nil)
expected_labels = [label1, label2, parent_group_label]
expect_labels_to_equal(results, expected_labels)
end
context 'some labels are already assigned' do
before do
issue.labels << label1
end
it 'marks already assigned as set' do
service = described_class.new(project, user)
results = service.labels_as_hash(issue)
expected_labels = [label1, label2, parent_group_label]
expect_labels_to_equal(results, expected_labels)
assigned_label_titles = issue.labels.map(&:title)
results.each do |hash|
if assigned_label_titles.include?(hash['title'])
expect(hash[:set]).to eq(true)
else
expect(hash.key?(:set)).to eq(false)
end
end
end
end
end
end
| {'content_hash': '33f1573942dd138d67f41c445266eaf3', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 131, 'avg_line_length': 37.59574468085106, 'alnum_prop': 0.6552065647990946, 'repo_name': 'iiet/iiet-git', 'id': '2f70c8ea94d74bf7c4749ef21509caf300fe4e96', 'size': '7099', 'binary': False, 'copies': '1', 'ref': 'refs/heads/release', 'path': 'spec/services/projects/autocomplete_service_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '694819'}, {'name': 'Clojure', 'bytes': '79'}, {'name': 'Dockerfile', 'bytes': '1907'}, {'name': 'HTML', 'bytes': '1386003'}, {'name': 'JavaScript', 'bytes': '4784137'}, {'name': 'Ruby', 'bytes': '21288676'}, {'name': 'Shell', 'bytes': '47962'}, {'name': 'Vue', 'bytes': '1163492'}]} |
body {
font-size: 62.5%;
}
table {
font-size: 1em;
}
/* Site
-------------------------------- */
body {
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
}
/* Layout
-------------------------------- */
.layout-grid {
width: 960px;
}
.layout-grid td {
vertical-align: top;
}
.layout-grid td.left-nav {
width: 140px;
}
.layout-grid td.normal {
border-left: 1px solid #eee;
padding: 20px 24px;
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
}
.layout-grid td.demos {
background: url('/images/demos_bg.jpg') no-repeat;
height: 337px;
overflow: hidden;
}
/* Normal
-------------------------------- */
.normal h3,
.normal h4 {
margin: 0;
font-weight: normal;
}
.normal h3 {
padding: 0 0 9px;
font-size: 1.8em;
}
.normal h4 {
padding-bottom: 21px;
border-bottom: 1px dashed #999;
font-size: 1.2em;
font-weight: bold;
}
.normal p {
font-size: 1.2em;
}
/* Demos */
.demos-nav, .demos-nav dt, .demos-nav dd, .demos-nav ul, .demos-nav li {
margin: 0;
padding: 0
}
.demos-nav {
float: left;
width: 170px;
font-size: 1.3em;
}
.demos-nav dt,
.demos-nav h4 {
margin: 0;
padding: 0;
font: normal 1.1em "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
color: #e87b10;
}
.demos-nav dt,
.demos-nav h4 {
margin-top: 1.5em;
margin-bottom: 0;
padding-left: 8px;
padding-bottom:5px;
line-height: 1.2em;
border-bottom: 1px solid #F4F4F4;
}
.demos-nav dd a,
.demos-nav li a {
border-bottom: 1px solid #F4F4F4;
display:block;
padding: 4px 3px 4px 8px;
font-size: 90%;
text-decoration: none;
color: #555 ;
margin:2px 0;
height:13px;
}
.demos-nav dd a:hover,
.demos-nav dd a:focus,
.demos-nav dd a:hover,
.demos-nav dd a:focus {
background: #f3f3f3;
color:#000;
-moz-border-radius: 5px; -webkit-border-radius: 5px;
}
.demos-nav dd a.selected {
background: #555;
color:#ffffff;
-moz-border-radius: 5px; -webkit-border-radius: 5px;
}
/* new styles for demo pages, added by Filament 12.29.08
eventually we should convert the font sizes to ems -- using px for now to minimize style conflicts
*/
.normal h3.demo-header { font-size:32px; padding:0 0 5px; border-bottom:1px solid #eee; text-transform: capitalize; }
.normal h4.demo-subheader { font-size:10px; text-transform: uppercase; color:#999; padding:8px 0 3px; border:0; margin:0; }
.normal a:link,
.normal a:visited { color:#1b75bb; text-decoration:none; }
.normal a:hover,
.normal a:active { color:#0b559b; }
#demo-config { padding:20px 0 0; }
#demo-frame { float:left; width:540px; height:380px; border:1px solid #ddd; overflow: auto; position: relative; }
#demo-frame h3, #demo-frame h4 { padding: 0; font-weight: bold; font-size: 1em; }
#demo-config-menu { float:right; width:180px; }
#demo-config-menu h4 { font-size:13px; color:#666; font-weight:normal; border:0; padding-left:18px; }
#demo-config-menu ul { list-style: none; padding: 0; margin: 0; }
#demo-config-menu li { font-size:12px; padding:0 0 0 10px; margin:3px 0; zoom: 1; }
#demo-config-menu li a:link,
#demo-config-menu li a:visited { display:block; padding:1px 8px 4px; border-bottom:1px dotted #b3b3b3; }
* html #demo-config-menu li a:link,
* html #demo-config-menu li a:visited { padding:1px 8px 2px; }
#demo-config-menu li a:hover,
#demo-config-menu li a:active { background-color:#f6f6f6; }
#demo-config-menu li.demo-config-on { background: url(../../../jQuery-UI/themes/base/images/demo-config-on-tile.gif) repeat-x left center; }
#demo-config-menu li.demo-config-on a:link,
#demo-config-menu li.demo-config-on a:visited,
#demo-config-menu li.demo-config-on a:hover,
#demo-config-menu li.demo-config-on a:active { background: url(../../../jQuery-UI/themes/base/images/demo-config-on.gif) no-repeat left; padding-left:18px; color:#fff; border:0; margin-left:-10px; margin-top: 0px; margin-bottom: 0px; }
#demo-source, #demo-notes {
clear: both;
padding: 20px 0 0;
font-size: 1.3em;
}
#demo-notes { width:520px; color:#333; font-size: 1em; }
#demo-notes p code, .demo-description p code { padding: 0; font-weight: bold; }
#demo-source pre, #demo-source code { padding: 0; }
code, pre { padding:8px 0 8px 20px ; font-size: 1.2em; line-height:130%; }
#demo-source a:link,
#demo-source a:visited,
#demo-source a:hover,
#demo-source a:active { font-size:12px; padding-left:13px; background-position: left center; background-repeat: no-repeat; }
#demo-source a.source-open:link,
#demo-source a.source-open:visited,
#demo-source a.source-open:hover,
#demo-source a.source-open:active { background-image: url(../../../jQuery-UI/themes/base/images/demo-spindown-open.gif); }
#demo-source a.source-closed:link,
#demo-source a.source-closed:visited,
#demo-source a.source-closed:hover,
#demo-source a.source-closed:active { background-image: url(../../../jQuery-UI/themes/base/images/demo-spindown-closed.gif); }
div.demo {
padding:12px;
font-family: "Trebuchet MS", "Arial", "Helvetica", "Verdana", "sans-serif";
}
div.demo h3.docs { clear:left; font-size:12px; font-weight:normal; padding:0 0 1em; margin:0; }
div.demo-description {
clear:both;
padding:12px;
font-family: "Trebuchet MS", "Arial", "Helvetica", "Verdana", "sans-serif";
font-size: 1.3em;
line-height: 1.4em;
}
.ui-draggable, .ui-droppable {
background-position: top left;
}
.left-nav .demos-nav {
padding-right: 10px;
}
#demo-link { font-size:11px; padding-top: 6px; clear: both; overflow: hidden; }
#demo-link a span.ui-icon { float:left; margin-right:3px; }
/* Component containers
----------------------------------*/
#widget-docs .ui-widget { font-family: Trebuchet MS,Verdana,Arial,sans-serif; font-size: 1em; }
#widget-docs .ui-widget input, #widget-docs .ui-widget select, #widget-docs .ui-widget textarea, #widget-docs .ui-widget button { font-family: Trebuchet MS,Verdana,Arial,sans-serif; font-size: 1em; }
#widget-docs .ui-widget-header { border: 1px solid #ffffff; background: #464646 url(../../../jQuery-UI/themes/base/images/464646_40x100_textures_01_flat_100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; }
#widget-docs .ui-widget-header a { color: #ffffff; }
#widget-docs .ui-widget-content { border: 1px solid #ffffff; background: #ffffff url(../../../jQuery-UI/themes/base/images/ffffff_40x100_textures_01_flat_75.png) 50% 50% repeat-x; color: #222222; }
#widget-docs .ui-widget-content a { color: #222222; }
/* Interaction states
----------------------------------*/
#widget-docs .ui-state-default, #widget-docs .ui-widget-content #widget-docs .ui-state-default { border: 1px solid #666666; background: #555555 url(../../../jQuery-UI/themes/base/images/555555_40x100_textures_03_highlight_soft_75.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; outline: none; }
#widget-docs .ui-state-default a { color: #ffffff; text-decoration: none; outline: none; }
#widget-docs .ui-state-hover, #widget-docs .ui-widget-content #widget-docs .ui-state-hover, #widget-docs .ui-state-focus, #widget-docs .ui-widget-content #widget-docs .ui-state-focus { border: 1px solid #666666; background: #444444 url(../../../jQuery-UI/themes/base/images/444444_40x100_textures_03_highlight_soft_60.png) 50% 50% repeat-x; font-weight: normal; color: #ffffff; outline: none; }
#widget-docs .ui-state-hover a { color: #ffffff; text-decoration: none; outline: none; }
#widget-docs .ui-state-active, #widget-docs .ui-widget-content #widget-docs .ui-state-active { border: 1px solid #666666; background: #ffffff url(../../../jQuery-UI/themes/base/images/ffffff_40x100_textures_01_flat_65.png) 50% 50% repeat-x; font-weight: normal; color: #F6921E; outline: none; }
#widget-docs .ui-state-active a { color: #F6921E; outline: none; text-decoration: none; }
/* Interaction Cues
----------------------------------*/
#widget-docs .ui-state-highlight, #widget-docs .ui-widget-content #widget-docs .ui-state-highlight {border: 1px solid #fcefa1; background: #fbf9ee url(../../../jQuery-UI/themes/base/images/fbf9ee_40x100_textures_02_glass_55.png) 50% 50% repeat-x; color: #363636; }
#widget-docs .ui-state-error, #widget-docs .ui-widget-content #widget-docs .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(../../../jQuery-UI/themes/base/images/fef1ec_40x100_textures_05_inset_soft_95.png) 50% bottom repeat-x; color: #cd0a0a; }
#widget-docs .ui-state-error-text, #widget-docs .ui-widget-content #widget-docs .ui-state-error-text { color: #cd0a0a; }
#widget-docs .ui-state-disabled, #widget-docs .ui-widget-content #widget-docs .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
#widget-docs .ui-priority-primary, #widget-docs .ui-widget-content #widget-docs .ui-priority-primary { font-weight: bold; }
#widget-docs .ui-priority-secondary, #widget-docs .ui-widget-content #widget-docs .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
/* Icons
----------------------------------*/
/* states and images */
#demo-frame-wrapper .ui-icon, #widget-docs .ui-icon { width: 16px; height: 16px; background-image: url(../../../jQuery-UI/themes/base/images/222222_256x240_icons_icons.png); }
#widget-docs .ui-widget-content .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/222222_256x240_icons_icons.png); }
#widget-docs .ui-widget-header .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/222222_256x240_icons_icons.png); }
#widget-docs .ui-state-default .ui-icon { background-image: url(../../../jQuery-UI/themes/base/images/888888_256x240_icons_icons.png); }
#widget-docs .ui-state-hover .ui-icon, #widget-docs .ui-state-focus .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/454545_256x240_icons_icons.png); }
#widget-docs .ui-state-active .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/454545_256x240_icons_icons.png); }
#widget-docs .ui-state-highlight .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/2e83ff_256x240_icons_icons.png); }
#widget-docs .ui-state-error .ui-icon, #widget-docs .ui-state-error-text .ui-icon {background-image: url(../../../jQuery-UI/themes/base/images/cd0a0a_256x240_icons_icons.png); }
/* Misc visuals
----------------------------------*/
/* Corner radius */
#widget-docs .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; }
#widget-docs .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
#widget-docs .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
#widget-docs .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
#widget-docs .ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
#widget-docs .ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
#widget-docs .ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
#widget-docs .ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
#widget-docs .ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; }
/* Overlays */
#widget-docs .ui-widget-overlay { background: #aaaaaa url(../../../jQuery-UI/themes/base/images/aaaaaa_40x100_textures_01_flat_0.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
#widget-docs .ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(../../../jQuery-UI/themes/base/images/aaaaaa_40x100_textures_01_flat_0.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -webkit-border-radius: 8px; }
/*
----------------------------------*/
#widget-docs { margin:20px 0 0; border: none; }
#widget-docs h2, #widget-docs h3, #widget-docs h4, #widget-docs p, #widget-docs ul, #widget-docs code { margin:0; padding:0; }
#widget-docs code { display:block; color:#444; font-size:.9em; margin:0 0 1em; }
#widget-docs code strong { color:#000; }
#widget-docs p { margin:0 3em 1.2em 0; }
#widget-docs p.intro { font-size:13px; color:#666; line-height:1.3; }
#widget-docs ul { list-style-type: none; }
#widget-docs h2 { font-size:16px; margin:1.2em 0 .5em; }
#widget-docs h3 { font-size:14px; color:#e6820E; margin:1.5em 0 .5em; }
.normal #widget-docs h4 { font-size:12px; color:#000; border:0; margin:0 0 .5em; }
#docs-overview-main { width:400px; }
#docs-overview-sidebar { float:right; width:200px; }
#docs-overview-sidebar a span { color:#666; }
#widget-docs #docs-overview-main p { margin-right:0; }
#widget-docs #docs-overview-sidebar h4 { padding-left:0; }
.docs-list-header { float:left; width:100%; margin:10px 0 0; border-bottom:1px solid #eee; }
#widget-docs .docs-list-header h2 { float:left; margin:0; }
#widget-docs .docs-list-header p { float:right; margin:5px 0; font-size:11px; }
.docs-list { float:left; width:100%; padding:0 0 10px; }
.docs-list .param-header { float:left; clear:left; width:100%; padding:8px 0; border-top:1px solid #eee; }
#widget-docs .param-header h3, #widget-docs .param-header p { margin:0; float:left; }
#widget-docs .param-header h3 { width:50%; }
#widget-docs .param-header h3 span { background: url(../../../jQuery-UI/themes/base/images/demo-spindown-closed.gif) no-repeat left; padding-left:13px; }
#widget-docs .param-open .param-header h3 span { background: url(../../../jQuery-UI/themes/base/images/demo-spindown-open.gif) no-repeat left; }
#widget-docs .param-header p { width:24%; }
#widget-docs .param-header p.param-type span { background: url(../../../jQuery-UI/themes/base/images/icon-docs-info.gif) no-repeat left; cursor:pointer; border-bottom:1px dashed #ccc; padding-left:15px; }
.param-details { padding-left:13px; }
.param-args { margin:0 0 1.5em; border-top:1px dotted #ccc;}
.param-args td { padding:3px 30px 3px 5px; border-bottom:1px dotted #ccc; }
/* overrides for ui-tab styles */
#widget-docs ul.ui-tabs-nav { padding:0 0 0 8px; }
#widget-docs .ui-tabs-nav li { margin:5px 5px 0 0; }
#widget-docs .ui-tabs-nav li a:link,
#widget-docs .ui-tabs-nav li a:visited,
#widget-docs .ui-tabs-nav li a:hover,
#widget-docs .ui-tabs-nav li a:active { font-size:14px; padding:4px 1.2em 3px; color:#fff; }
#widget-docs .ui-tabs-nav li.ui-tabs-selected a:link,
#widget-docs .ui-tabs-nav li.ui-tabs-selected a:visited,
#widget-docs .ui-tabs-nav li.ui-tabs-selected a:hover,
#widget-docs .ui-tabs-nav li.ui-tabs-selected a:active { color:#e6820E; }
#widget-docs .ui-tabs-panel { padding:20px 9px; font-size:12px; line-height:1.4; color:#000; }
#widget-docs .ui-widget-content a:link,
#widget-docs .ui-widget-content a:visited { color:#1b75bb; text-decoration:none; }
#widget-docs .ui-widget-content a:hover,
#widget-docs .ui-widget-content a:active { color:#0b559b; }
| {'content_hash': '759bac6da0eaa3fc6d915bc85103f4a9', 'timestamp': '', 'source': 'github', 'line_count': 334, 'max_line_length': 394, 'avg_line_length': 45.15568862275449, 'alnum_prop': 0.6920169738761437, 'repo_name': 'maxis1314/phputils', 'id': 'a2eae087bd4693f9b96b85bbbfd36789493caac4', 'size': '15082', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mysql_crud/skin/themes/base/pages.css', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '67155'}, {'name': 'ApacheConf', 'bytes': '128'}, {'name': 'Batchfile', 'bytes': '178'}, {'name': 'CSS', 'bytes': '194892'}, {'name': 'HTML', 'bytes': '544586'}, {'name': 'JavaScript', 'bytes': '474502'}, {'name': 'PHP', 'bytes': '2719776'}, {'name': 'Perl', 'bytes': '3659'}, {'name': 'Smarty', 'bytes': '357371'}]} |
'use strict';
var blockiesDrtv = function() {
return function(scope, element, attrs){
var watchVar = attrs.watchVar;
scope.$watch(watchVar, function() {
var address = attrs.blockieAddress;
var content = ethFuncs.validateEtherAddress(address) ? globalFuncs.getBlockie(address):'';
element.css({
'background-image': 'url(' + content +')'
});
});
};
};
module.exports = blockiesDrtv; | {'content_hash': '9e8a594a03dcea29d196c0f4e31e464a', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 102, 'avg_line_length': 33.5, 'alnum_prop': 0.5863539445628998, 'repo_name': 'avatar-lavventura/eBlocWallet', 'id': 'd2973fffe8f8375cf9f7b4a432285edeb999c2c6', 'size': '469', 'binary': False, 'copies': '5', 'ref': 'refs/heads/ebloc', 'path': 'app/scripts/directives/blockiesDrtv.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '42624'}, {'name': 'HTML', 'bytes': '140131'}, {'name': 'JavaScript', 'bytes': '4817557'}, {'name': 'PHP', 'bytes': '10366'}, {'name': 'Python', 'bytes': '4031'}, {'name': 'Smarty', 'bytes': '154123'}]} |
namespace Microsoft.Azure.Management.ResourceManager.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using System.Linq;
public partial class ResourceManagementPrivateLink : IResource
{
/// <summary>
/// Initializes a new instance of the ResourceManagementPrivateLink
/// class.
/// </summary>
public ResourceManagementPrivateLink()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ResourceManagementPrivateLink
/// class.
/// </summary>
/// <param name="id">The rmplResourceID.</param>
/// <param name="name">The rmpl Name.</param>
/// <param name="type">The operation type.</param>
/// <param name="location">the region of the rmpl</param>
public ResourceManagementPrivateLink(ResourceManagementPrivateLinkEndpointConnections properties = default(ResourceManagementPrivateLinkEndpointConnections), string id = default(string), string name = default(string), string type = default(string), string location = default(string))
{
Properties = properties;
Id = id;
Name = name;
Type = type;
Location = location;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties")]
public ResourceManagementPrivateLinkEndpointConnections Properties { get; set; }
/// <summary>
/// Gets the rmplResourceID.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
/// <summary>
/// Gets the rmpl Name.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets the operation type.
/// </summary>
[JsonProperty(PropertyName = "type")]
public string Type { get; private set; }
/// <summary>
/// Gets or sets the region of the rmpl
/// </summary>
[JsonProperty(PropertyName = "location")]
public string Location { get; set; }
}
}
| {'content_hash': '1995d3d6bc097678b0237716286fc2e0', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 291, 'avg_line_length': 33.541666666666664, 'alnum_prop': 0.5850931677018634, 'repo_name': 'Azure/azure-sdk-for-net', 'id': '3521762755b90145a8380ded45bef6adbcbc7649', 'size': '2768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/resources/Microsoft.Azure.Management.Resource/src/Generated/Models/ResourceManagementPrivateLink.cs', 'mode': '33188', 'license': 'mit', 'language': []} |
package java.util.regex;
/**
* Holds the results of a successful match of a regular expression against a
* given string. Only used internally, thus sparsely documented (though the
* defining public interface has full documentation).
*
* @see java.util.regex.MatchResult
*/
class MatchResultImpl implements MatchResult {
/**
* Holds the original input text.
*/
private String text;
/**
* Holds the offsets of the groups in the input text. The first two elements
* specifiy start and end of the zero group, the next two specify group 1,
* and so on.
*/
private int[] offsets;
MatchResultImpl(String text, int[] offsets) {
this.text = text;
this.offsets = offsets.clone();
}
public int end() {
return end(0);
}
public int end(int group) {
return offsets[2 * group + 1];
}
public String group() {
return text.substring(start(), end());
}
public String group(int group) {
int from = offsets[group * 2];
int to = offsets[(group * 2) + 1];
if (from == -1 || to == -1) {
return null;
} else {
return text.substring(from, to);
}
}
public int groupCount() {
return (offsets.length / 2) - 1;
}
public int start() {
return start(0);
}
public int start(int group) {
return offsets[2 * group];
}
}
| {'content_hash': 'f390bc7162410c070f24d236808175cb', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 77, 'avg_line_length': 19.523076923076925, 'alnum_prop': 0.653270291568164, 'repo_name': 'webos21/xi', 'id': 'f90a7e6be4bf02143565c1c373ab89be22653c62', 'size': '1888', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/jcl/src/java/java/util/regex/MatchResultImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '122940'}, {'name': 'C', 'bytes': '24974111'}, {'name': 'C++', 'bytes': '9533209'}, {'name': 'Java', 'bytes': '11074296'}, {'name': 'Objective-C', 'bytes': '71993'}, {'name': 'Shell', 'bytes': '1678'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.flex.examples</groupId>
<artifactId>parent</artifactId>
<version>1</version>
</parent>
<artifactId>simple-maven</artifactId>
<version>0.1</version>
<name>A scanner for a toy programming language.</name>
<description>It is the example from the JLex website with some small
modifications, to make it a bit more readable.
It does nothing really useful, because there is no parser for
the toy programming language. It's just a demonstration how a
small simple scanner looks like.</description>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {'content_hash': 'ca3e96859f4c6f6c0ae4a3be4296f24c', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 201, 'avg_line_length': 38.38461538461539, 'alnum_prop': 0.7104208416833667, 'repo_name': 'bjorndm/prebake', 'id': '0c90bb5e83f630dea292cf4c458c72e923a1cf42', 'size': '998', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'code/third_party/jflex/examples/simple-maven/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4237'}, {'name': 'HTML', 'bytes': '1251138'}, {'name': 'Java', 'bytes': '1262459'}, {'name': 'JavaScript', 'bytes': '91498'}, {'name': 'Perl', 'bytes': '5698'}, {'name': 'Python', 'bytes': '3178'}, {'name': 'Shell', 'bytes': '58950'}, {'name': 'XSLT', 'bytes': '129565'}]} |
var Aria = require("../Aria");
var robotClasspath = require("./$RobotSelection").getRobotClasspath();
/**
* This class is still experimental, its interface may change without notice. This class gives access to a robot
* implementation, allowing to send low-level mouse and keyboard events to a web page.
* @private
*/
module.exports = Aria.classDefinition({
$classpath : 'aria.jsunit.Robot',
$singleton : true,
$statics : {
ROBOT_UNAVAILABLE : "There is no usable implementation of the robot.",
BUTTON1_MASK : 16,
BUTTON2_MASK : 8,
BUTTON3_MASK : 4
},
$constructor : function () {
/**
* Robot implementation.
* @type aria.jsunit.IRobot
*/
this.robot = null;
},
$prototype : {
/**
* Returns the classpath of the robot implementation to use.
* @return {String}
*/
getRobotClasspath : function () {
return robotClasspath;
},
/**
* Returns true if the robot is most likely usable (the PhantomJS robot is available or Java is enabled).
* @return {Boolean} true if an implementation of the robot is most likely usable.
*/
isUsable : function () {
return !!this.getRobotClasspath();
},
/**
* Initializes the robot.
* @param {aria.core.CfgBeans:Callback} callback callback to be called when the robot is ready to be used.
*/
initRobot : function (cb) {
if (this.robot) {
this.robot.initRobot(cb);
} else {
if (!robotClasspath) {
this.$logError(this.ROBOT_UNAVAILABLE);
return;
}
Aria.load({
classes : [robotClasspath],
oncomplete : {
fn : this._robotLoaded,
scope : this,
args : {
cb : cb
}
}
});
}
},
/**
* Called when the robot implementation has been loaded with Aria.load.
* @param {Object} args contains the robotClasspath and cb properties.
*/
_robotLoaded : function (args) {
if (!this.robot) {
this.robot = Aria.getClassRef(robotClasspath).$interface("aria.jsunit.IRobot");
}
this.robot.initRobot(args.cb);
}
}
});
| {'content_hash': '5e6c478f9f0803a7dffa061e25a79e30', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 114, 'avg_line_length': 31.51851851851852, 'alnum_prop': 0.5068546807677242, 'repo_name': 'ymeine/ariatemplates', 'id': 'de4ecd920079f65e5fdf108c8cbb0ee4cba7d83a', 'size': '3146', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'src/aria/jsunit/Robot.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '216069'}, {'name': 'HTML', 'bytes': '25071'}, {'name': 'JavaScript', 'bytes': '10491832'}, {'name': 'Shell', 'bytes': '2112'}, {'name': 'Smarty', 'bytes': '1093700'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Omphalia peri Berk. & Broome
### Remarks
null | {'content_hash': '306065935a657cd7b0716420ac0ca836', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 28, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '656376c82ac55f1369211e3953220310fe876e05', 'size': '195', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Clitopilus/Clitopilus peri/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
include_recipe "bcpc::default"
package "ufw"
template "/etc/default/ufw" do
source "ufw.erb"
mode 00644
notifies :restart, "service[ufw]", :delayed
end
template "/etc/ufw/sysctl.conf" do
source "ufw.sysctl.conf.erb"
mode 00644
notifies :restart, "service[ufw]", :delayed
end
template "/etc/ufw/before.rules" do
source "ufw.before.rules.erb"
mode 00640
notifies :restart, "service[ufw]", :delayed
end
bash "setup-allow-rules-ufw" do
user "root"
code <<-EOH
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 4000/tcp
ufw allow 4040/tcp
ufw allow in on #{node['bcpc']['bootstrap']['pxe_interface']} from any port 68 to any port 67 proto udp
ufw allow in on #{node['bcpc']['bootstrap']['pxe_interface']} from any to #{node['bcpc']['bootstrap']['server']} port tftp
ufw allow 10050/tcp
ufw --force enable
EOH
end
service "ufw" do
action [:enable, :start]
end
| {'content_hash': 'ff212b68996ddd8eff061fb4773de3a5', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 130, 'avg_line_length': 24.9, 'alnum_prop': 0.6325301204819277, 'repo_name': 'semenovroman/chef-bcpc', 'id': 'd21c2d92541c82e0eedf05e55c597240926ec4a5', 'size': '1624', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'cookbooks/bcpc/recipes/ufw.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '416367'}, {'name': 'Perl', 'bytes': '5763'}, {'name': 'Python', 'bytes': '86694'}, {'name': 'Ruby', 'bytes': '413689'}, {'name': 'SQLPL', 'bytes': '9464'}, {'name': 'Shell', 'bytes': '193731'}]} |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit95ff7e0d66f077f72d39bd5647ccecc6::getLoader();
| {'content_hash': '6969eb1c3bbd6b07207a266f7e005505', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 75, 'avg_line_length': 26.142857142857142, 'alnum_prop': 0.7595628415300546, 'repo_name': 'startupftw/startupftw-php', 'id': '6f4f49d0503174c32eca58afceb640f6d6ae3834', 'size': '183', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/autoload.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '517'}, {'name': 'CSS', 'bytes': '33226'}, {'name': 'HTML', 'bytes': '4156'}, {'name': 'JavaScript', 'bytes': '32557'}, {'name': 'PHP', 'bytes': '1758058'}, {'name': 'Python', 'bytes': '494'}, {'name': 'Shell', 'bytes': '1670'}]} |
/**
* A set of four arrows around the edges of the canvas that show off screen Blocks
* @constructor
*/
function OverflowArrows() {
this.group = GuiElements.create.group(0, 0);
this.triTop = this.makeTriangle();
this.triLeft = this.makeTriangle();
this.triRight = this.makeTriangle();
this.triBottom = this.makeTriangle();
this.setArrowPos();
this.visible = false;
}
OverflowArrows.setConstants = function() {
const OA = OverflowArrows;
OA.triangleW = 25;
OA.triangleH = 15;
OA.margin = 15;
OA.opacity = 0.5;
};
/**
* Creates an SVG path element of the correct color. The actual path information will be added later.
* @return {Element} - The SVG path element
*/
OverflowArrows.prototype.makeTriangle = function() {
const OA = OverflowArrows;
const tri = GuiElements.create.path();
GuiElements.update.color(tri, Colors.white);
GuiElements.update.opacity(tri, OA.opacity);
GuiElements.update.makeClickThrough(tri);
return tri;
};
/**
* Updates the visibility of the arrows given the active region of the canvas. If the canvas extends beyond an arrow
* in one direction, then that arrow becomes visible to indicate off screen blocks
* @param {number} left - The left boundary of the canvas
* @param {number} right - The right boundary of the canvas
* @param {number} top - The top boundary of the canvas
* @param {number} bottom - The bottom boundary of the canvas
*/
OverflowArrows.prototype.setArrows = function(left, right, top, bottom) {
if (left === right) {
// If the width of the canvas is 0, there are no Blocks, so the arrows should be hidden.
this.showIfTrue(this.triLeft, false);
this.showIfTrue(this.triRight, false);
} else {
this.showIfTrue(this.triLeft, left < this.left);
this.showIfTrue(this.triRight, right > this.right);
}
if (top === bottom) {
// If the height of the canvas is 0, there are no Blocks, so the arrows should be hidden.
this.showIfTrue(this.triTop, false);
this.showIfTrue(this.triBottom, false);
} else {
this.showIfTrue(this.triTop, top < this.top);
this.showIfTrue(this.triBottom, bottom > this.bottom);
}
};
/**
* Sets the visibility of the triangle according to the boolean parameter
* @param {Element} tri - The path to set the visibility of
* @param {boolean} shouldShow - Whether the path should be visible of not.
*/
OverflowArrows.prototype.showIfTrue = function(tri, shouldShow) {
if (shouldShow) {
this.group.appendChild(tri);
} else {
tri.remove();
}
};
/**
* Makes all overflow arrows visible
*/
OverflowArrows.prototype.show = function() {
if (!this.visible) {
this.visible = true;
GuiElements.layers.overflowArr.appendChild(this.group);
}
};
/**
* Makes all overflow arrows hidden
*/
OverflowArrows.prototype.hide = function() {
if (this.visible) {
this.visible = false;
this.group.remove();
}
};
/**
* Recomputes the positions of the overflow arrows
*/
OverflowArrows.prototype.updateZoom = function() {
this.setArrowPos();
};
/**
* Moves overflowArrows to the correct positions and stores the boundary of the portion of the screen for the canvas
*/
OverflowArrows.prototype.setArrowPos = function() {
const OA = OverflowArrows;
this.left = BlockPalette.width;
if (!GuiElements.paletteLayersVisible) {
this.left = 0;
}
this.top = TitleBar.height;
this.right = GuiElements.width;
this.bottom = GuiElements.height;
const midX = (this.left + this.right) / 2;
const midY = (this.top + this.bottom) / 2;
const topY = this.top + OA.margin;
const bottomY = this.bottom - OA.margin;
const leftX = this.left + OA.margin;
const rightX = this.right - OA.margin;
GuiElements.update.triangleFromPoint(this.triTop, midX, topY, OA.triangleW, OA.triangleH, true);
GuiElements.update.triangleFromPoint(this.triLeft, leftX, midY, OA.triangleW, OA.triangleH, false);
GuiElements.update.triangleFromPoint(this.triRight, rightX, midY, OA.triangleW, -OA.triangleH, false);
GuiElements.update.triangleFromPoint(this.triBottom, midX, bottomY, OA.triangleW, -OA.triangleH, true);
}; | {'content_hash': '40ac3abafb912d0d06dd51c40845dafe', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 116, 'avg_line_length': 31.69291338582677, 'alnum_prop': 0.7217391304347827, 'repo_name': 'BirdBrainTechnologies/HummingbirdDragAndDrop-', 'id': 'a324b711046a60314f10a5df3b9a51f7406d0c7d', 'size': '4025', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UIParts/TabManager/OverflowArrows.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3089'}, {'name': 'HTML', 'bytes': '25811'}, {'name': 'JavaScript', 'bytes': '3155678'}, {'name': 'Python', 'bytes': '4528'}, {'name': 'TeX', 'bytes': '58660'}]} |
"""Test RangeDataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.contrib.data.python.ops import dataset_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_dataset_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
class RangeDatasetTest(test.TestCase):
def tearDown(self):
# Remove all checkpoint files.
prefix = self._iterator_checkpoint_prefix()
pattern = prefix + "*"
files = gfile.Glob(pattern)
map(gfile.Remove, files)
def testStop(self):
stop = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(stop).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={stop: 5})
for i in range(5):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testStartStop(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start,
stop).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 2, stop: 5})
for i in range(2, 5):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testStartStopStep(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
step = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start, stop,
step).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 2, stop: 10, step: 2})
for i in range(2, 10, 2):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testZeroStep(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
step = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start, stop,
step).make_initializable_iterator()
init_op = iterator.initializer
with self.test_session() as sess:
with self.assertRaises(errors.InvalidArgumentError):
sess.run(init_op, feed_dict={start: 2, stop: 10, step: 0})
def testNegativeStep(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
step = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start, stop,
step).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 2, stop: 10, step: -1})
# This for loop is a no-op but will ensure that the implementation is
# consistent with range if it ever changes.
for i in range(2, 10, -1):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testStopLessThanStart(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start,
stop).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 10, stop: 2})
# This for loop is a no-op but will ensure that the implementation is
# consistent with range if it ever changes.
for i in range(10, 2):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testStopLessThanStartWithPositiveStep(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
step = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start, stop,
step).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 10, stop: 2, step: 2})
# This for loop is a no-op but will ensure that the implementation is
# consistent with range if it ever changes.
for i in range(10, 2, 2):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testStopLessThanStartWithNegativeStep(self):
start = array_ops.placeholder(dtypes.int64, shape=[])
stop = array_ops.placeholder(dtypes.int64, shape=[])
step = array_ops.placeholder(dtypes.int64, shape=[])
iterator = dataset_ops.Dataset.range(start, stop,
step).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
with self.test_session() as sess:
sess.run(init_op, feed_dict={start: 10, stop: 2, step: -1})
for i in range(10, 2, -1):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testEnumerateDataset(self):
components = (["a", "b"], [1, 2], [37.0, 38])
start = constant_op.constant(20, dtype=dtypes.int64)
iterator = (dataset_ops.Dataset.from_tensor_slices(components).enumerate(
start=start).make_initializable_iterator())
init_op = iterator.initializer
get_next = iterator.get_next()
self.assertEqual(dtypes.int64, get_next[0].dtype)
self.assertEqual((), get_next[0].shape)
self.assertEqual([tensor_shape.TensorShape([])] * 3,
[t.shape for t in get_next[1]])
with self.test_session() as sess:
sess.run(init_op)
self.assertEqual((20, (b"a", 1, 37.0)), sess.run(get_next))
self.assertEqual((21, (b"b", 2, 38.0)), sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def _iterator_checkpoint_prefix(self):
return os.path.join(self.get_temp_dir(), "iterator")
def testSaveRestore(self):
def _build_graph(start, stop):
iterator = dataset_ops.Dataset.range(start,
stop).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
path = self._iterator_checkpoint_prefix()
save_op = gen_dataset_ops.save_iterator(iterator._iterator_resource, path)
restore_op = gen_dataset_ops.restore_iterator(iterator._iterator_resource,
path)
return init_op, get_next, save_op, restore_op
# Saving and restoring in different sessions.
start = 2
stop = 10
break_point = 5
with ops.Graph().as_default() as g:
init_op, get_next, save_op, _ = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(init_op)
for i in range(start, break_point):
self.assertEqual(i, sess.run(get_next))
sess.run(save_op)
with ops.Graph().as_default() as g:
init_op, get_next, _, restore_op = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(init_op)
sess.run(restore_op)
for i in range(break_point, stop):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
# Saving and restoring in same session.
with ops.Graph().as_default() as g:
init_op, get_next, save_op, restore_op = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(init_op)
for i in range(start, break_point):
self.assertEqual(i, sess.run(get_next))
sess.run(save_op)
sess.run(restore_op)
for i in range(break_point, stop):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testMultipleSaves(self):
def _build_graph(start, stop):
iterator = dataset_ops.Dataset.range(start,
stop).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
path = self._iterator_checkpoint_prefix()
save_op = gen_dataset_ops.save_iterator(iterator._iterator_resource, path)
restore_op = gen_dataset_ops.restore_iterator(iterator._iterator_resource,
path)
return init_op, get_next, save_op, restore_op
start = 2
stop = 10
break_point1 = 5
break_point2 = 7
with ops.Graph().as_default() as g:
init_op, get_next, save_op, _ = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(init_op)
for i in range(start, break_point1):
self.assertEqual(i, sess.run(get_next))
sess.run(save_op)
with ops.Graph().as_default() as g:
init_op, get_next, save_op, restore_op = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(init_op)
sess.run(restore_op)
for i in range(break_point1, break_point2):
self.assertEqual(i, sess.run(get_next))
sess.run(save_op)
break_point2 = 7
with ops.Graph().as_default() as g:
init_op, get_next, save_op, restore_op = _build_graph(start, stop)
with self.test_session(graph=g) as sess:
sess.run(init_op)
sess.run(restore_op)
for i in range(break_point2, stop):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testSaveRestoreWithRepeat(self):
def _build_graph(start, stop, num_epochs):
iterator = dataset_ops.Dataset.range(
start, stop).repeat(num_epochs).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
path = self._iterator_checkpoint_prefix()
save_op = gen_dataset_ops.save_iterator(iterator._iterator_resource, path)
restore_op = gen_dataset_ops.restore_iterator(iterator._iterator_resource,
path)
return init_op, get_next, save_op, restore_op
start = 2
stop = 10
num_epochs = 5
break_range = 5
break_epoch = 3
with ops.Graph().as_default() as g:
init_op, get_next, save_op, restore_op = _build_graph(
start, stop, num_epochs)
with self.test_session(graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(init_op)
# Note: There is no checkpoint saved currently so a NotFoundError is
# raised.
with self.assertRaises(errors.NotFoundError):
sess.run(restore_op)
for _ in range(break_epoch - 1):
for i in range(start, stop):
self.assertEqual(i, sess.run(get_next))
for i in range(start, break_range):
self.assertEqual(i, sess.run(get_next))
sess.run(save_op)
with ops.Graph().as_default() as g:
init_op, get_next, _, restore_op = _build_graph(start, stop, num_epochs)
with self.test_session(graph=g) as sess:
sess.run(init_op)
sess.run(restore_op)
for i in range(break_range, stop):
self.assertEqual(i, sess.run(get_next))
for _ in range(break_epoch, num_epochs):
for i in range(start, stop):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testSaveRestoreExhaustedIterator(self):
def _build_graph(start, stop, num_epochs):
iterator = dataset_ops.Dataset.range(
start, stop).repeat(num_epochs).make_initializable_iterator()
init_op = iterator.initializer
get_next = iterator.get_next()
path = self._iterator_checkpoint_prefix()
save_op = gen_dataset_ops.save_iterator(iterator._iterator_resource, path)
restore_op = gen_dataset_ops.restore_iterator(iterator._iterator_resource,
path)
return init_op, get_next, save_op, restore_op
start = 2
stop = 10
num_epochs = 5
with ops.Graph().as_default() as g:
init_op, get_next, save_op, restore_op = _build_graph(
start, stop, num_epochs)
with self.test_session(graph=g) as sess:
sess.run(variables.global_variables_initializer())
sess.run(init_op)
# Note: There is no checkpoint saved currently so a NotFoundError is
# raised.
with self.assertRaises(errors.NotFoundError):
sess.run(restore_op)
for _ in range(num_epochs):
for i in range(start, stop):
self.assertEqual(i, sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
sess.run(save_op)
with ops.Graph().as_default() as g:
init_op, get_next, _, restore_op = _build_graph(start, stop, num_epochs)
with self.test_session(graph=g) as sess:
sess.run(init_op)
sess.run(restore_op)
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
if __name__ == "__main__":
test.main()
| {'content_hash': '7bba745e87bc58ea70f2ff97daf07f5f', 'timestamp': '', 'source': 'github', 'line_count': 368, 'max_line_length': 80, 'avg_line_length': 39.578804347826086, 'alnum_prop': 0.6306213525575008, 'repo_name': 'alivecor/tensorflow', 'id': '87bab43ccf508241702807897b4326c105ed8651', 'size': '15254', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'tensorflow/contrib/data/python/kernel_tests/range_dataset_op_test.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '7666'}, {'name': 'C', 'bytes': '198380'}, {'name': 'C++', 'bytes': '29214526'}, {'name': 'CMake', 'bytes': '640979'}, {'name': 'Go', 'bytes': '971217'}, {'name': 'Java', 'bytes': '407618'}, {'name': 'Jupyter Notebook', 'bytes': '1833674'}, {'name': 'LLVM', 'bytes': '6536'}, {'name': 'Makefile', 'bytes': '38189'}, {'name': 'Objective-C', 'bytes': '7056'}, {'name': 'Objective-C++', 'bytes': '63210'}, {'name': 'Perl', 'bytes': '6715'}, {'name': 'Protocol Buffer', 'bytes': '268983'}, {'name': 'PureBasic', 'bytes': '24932'}, {'name': 'Python', 'bytes': '25693552'}, {'name': 'Ruby', 'bytes': '327'}, {'name': 'Shell', 'bytes': '374053'}]} |
#import <Foundation/NSObject.h>
#import "SZGameController.h"
/**
* Controller that reads the state of the Pad singleton in order to determine
* what the human player is doing.
*/
@interface SZPlayerOneController : NSObject <SZGameController> {
}
/**
* Is left held?
*/
- (BOOL)isLeftHeld;
/**
* Is right held?
*/
- (BOOL)isRightHeld;
/**
* Is up held?
*/
- (BOOL)isUpHeld;
/**
* Is down held?
*/
- (BOOL)isDownHeld;
/**
* Is the rotate clockwise button held?
*/
- (BOOL)isRotateClockwiseHeld;
/**
* Is the rotate anticlockwise button held?
*/
- (BOOL)isRotateAntiClockwiseHeld;
@end
| {'content_hash': 'e0553db0cc080f29f3f27cfa3ebda9de', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 77, 'avg_line_length': 14.452380952380953, 'alnum_prop': 0.6655683690280065, 'repo_name': 'ant512/SuperFoulEggiOS', 'id': '687aa0a9432dece57a8281d32e8bdfb3769e1e59', 'size': '607', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SuperFoulEggiOS/Engine/SZPlayerOneController.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '300697'}, {'name': 'C++', 'bytes': '18958'}, {'name': 'M', 'bytes': '333590'}, {'name': 'Matlab', 'bytes': '1875'}, {'name': 'Objective-C', 'bytes': '1806863'}]} |
#include <cstdio>
#include <ctime>
#include <iostream>
#include "..\cryptopp562\des.h"
#include "..\cryptopp562\aes.h"
#include "..\cryptopp562\modes.h"
#include "..\cryptopp562\randpool.h"
#include "..\cryptopp562\\osrng.h"
#include "..\cryptopp562\rsa.h"
#include "..\cryptopp562\hex.h"
using namespace std;
using namespace CryptoPP;
void DES_test()
{
byte key[DES::KEYLENGTH] = "1234567";
byte input[DES::BLOCKSIZE] = "123457";
byte output[DES::BLOCKSIZE] = "";
byte txt[DES::BLOCKSIZE] = "";
DESEncryption desEn;
desEn.SetKey(key, DES::KEYLENGTH);
desEn.ProcessBlock(input, output);
DESDecryption desDe;
desDe.SetKey(key, DES::KEYLENGTH);
desDe.ProcessBlock(output, txt);
printf("key = %s, input = %s, output = %s, txt = %s\n", key, input, output, txt);
}
void DES_EDE2_test()
{
byte key[DES_EDE2::KEYLENGTH] = "1234567890abcde";
byte input[DES_EDE2::BLOCKSIZE] = "123457";
byte output[DES_EDE2::BLOCKSIZE] = "";
byte txt[DES_EDE2::BLOCKSIZE] = "";
DES_EDE2_Encryption desEn;
desEn.SetKey(key, DES_EDE2::KEYLENGTH);
desEn.ProcessBlock(input, output);
DES_EDE2_Decryption desDe;
desDe.SetKey(key, DES_EDE2::KEYLENGTH);
desDe.ProcessBlock(output, txt);
printf("key = %s, input = %s, output = %s, txt = %s\n", key, input, output, txt);
}
void DES_EDE3_test()
{
byte key[DES_EDE3::KEYLENGTH] = "1234567890abcdefghijlmn";
byte input[DES_EDE3::BLOCKSIZE] = "123457";
byte output[DES_EDE3::BLOCKSIZE] = "";
byte txt[DES_EDE3::BLOCKSIZE] = "";
DES_EDE3_Encryption desEn;
desEn.SetKey(key, DES_EDE3::KEYLENGTH);
desEn.ProcessBlock(input, output);
DES_EDE3_Decryption desDe;
desDe.SetKey(key, DES_EDE3::KEYLENGTH);
desDe.ProcessBlock(output, txt);
printf("key = %s, input = %s, output = %s, txt = %s\n", key, input, output, txt);
}
void DES_XEX3_test()
{
byte key[DES_XEX3::KEYLENGTH] = "1234567890abcdefghijlmn";
byte input[DES_XEX3::BLOCKSIZE] = "123457";
byte output[DES_XEX3::BLOCKSIZE] = "";
byte txt[DES_XEX3::BLOCKSIZE] = "";
DES_XEX3_Encryption desEn;
desEn.SetKey(key, DES_EDE3::KEYLENGTH);
desEn.ProcessBlock(input, output);
DES_XEX3_Decryption desDe;
desDe.SetKey(key, DES_EDE3::KEYLENGTH);
desDe.ProcessBlock(output, txt);
printf("key = %s, input = %s, output = %s, txt = %s\n", key, input, output, txt);
}
void AES_test()
{
byte aesKey[AES::DEFAULT_KEYLENGTH] = "abcdefg"; //ÃÜÔ¿
byte inBlock[AES::BLOCKSIZE] = "1234567"; //Òª¼ÓÃܵÄÊý¾Ý¿é
byte outBlock[AES::BLOCKSIZE]; //¼ÓÃܺóµÄÃÜÎÄ¿é
byte xorBlock[AES::BLOCKSIZE]; //±ØÐëÉ趨ΪȫÁã
byte plainText[AES::BLOCKSIZE]; //½âÃÜ
memset(xorBlock, 0, AES::BLOCKSIZE ); //ÖÃÁã
AESEncryption aesEncryptor; //¼ÓÃÜÆ÷
aesEncryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH ); //É趨¼ÓÃÜÃÜÔ¿
aesEncryptor.ProcessAndXorBlock( inBlock, xorBlock, outBlock ); //¼ÓÃÜ
AESDecryption aesDecryptor;
aesDecryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH );
aesDecryptor.ProcessAndXorBlock( outBlock, xorBlock, plainText );
printf("output = %s size = %d\n", outBlock, strlen((char *)outBlock));
AutoSeededRandomPool prng;
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock( key, key.size() );
byte iv[ AES::BLOCKSIZE ];
prng.GenerateBlock( iv, sizeof(iv) );
string plain = "CBC Mode Test";
string cipher, encoded, recovered;
/*********************************\
\*********************************/
try
{
cout << "plain text: " << plain << endl;
CBC_Mode< AES >::Encryption e;
e.SetKeyWithIV( key, key.size(), iv );
// The StreamTransformationFilter adds padding
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
StringSource ss( plain, true,
new StreamTransformationFilter( e,
new StringSink( cipher )
) // StreamTransformationFilter
); // StringSource
}
catch( const CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
// Pretty print cipher text
StringSource ss( cipher, true,
new HexEncoder(
new StringSink( encoded )
) // HexEncoder
); // StringSource
cout << "cipher text: " << encoded << endl;
/*********************************\
\*********************************/
try
{
CBC_Mode< AES >::Decryption d;
d.SetKeyWithIV( key, key.size(), iv );
// The StreamTransformationFilter removes
// padding as required.
StringSource ss( cipher, true,
new StreamTransformationFilter( d,
new StringSink( recovered )
) // StreamTransformationFilter
); // StringSource
cout << "recovered text: " << recovered << endl;
}
catch( const CryptoPP::Exception& e )
{
cerr << e.what() << endl;
exit(1);
}
}
void RSA_Test()
{
//´ý¼ÓÃܵÄ×Ö·û´®
string message = "http://my.oschina.net/xlplbo/blog";
printf("message = %s, length = %d\n", message.c_str(), strlen(message.c_str()));
/*
//×Ô¶¯Éú³ÉËæ»úÊý¾Ý
byte seed[600] = "";
AutoSeededRandomPool rnd;
rnd.GenerateBlock(seed, sizeof(seed));
printf("seed = %s\n", (char *)seed, strlen((char *)seed));
//Éú³É¼ÓÃܵĸßÖÊÁ¿Î±Ëæ»ú×Ö½Ú²¥ÖÖ³ØÒ»Ì廯ºóµÄìØ
RandomPool randPool;
randPool.Put(seed, sizeof(seed));
*/
AutoSeededRandomPool rnd;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize(rnd, 1024);
RSA::PrivateKey privateKey(params);
RSA::PublicKey publicKey(params);
//ʹÓÃOAEPģʽ
//RSAES_OAEP_SHA_Decryptor pri(randPool, sizeof(seed));
//RSAES_OAEP_SHA_Encryptor pub(pri);
RSAES_OAEP_SHA_Decryptor pri(privateKey);
RSAES_OAEP_SHA_Encryptor pub(publicKey);
printf("max plaintext Length = %d,%d\n", pri.FixedMaxPlaintextLength(), pub.FixedMaxPlaintextLength());
if (pub.FixedMaxPlaintextLength() > message.length())
{//´ý¼ÓÃÜÎı¾²»ÄÜ´óÓÚ×î´ó¼ÓÃܳ¤¶È
string chilper;
StringSource(message, true, new PK_EncryptorFilter(rnd, pub, new StringSink(chilper)));
printf("chilper = %s, length = %d\n", chilper.c_str(), strlen(chilper.c_str()));
string txt;
StringSource(chilper, true, new PK_DecryptorFilter(rnd, pri, new StringSink(txt)));
printf("txt = %s, length = %d\n", txt.c_str(), strlen(txt.c_str()));
}
//ʹÓÃPKCS1v15ģʽ
//RSAES_PKCS1v15_Decryptor pri1(randPool, sizeof(seed));
//RSAES_PKCS1v15_Encryptor pub1(pri1);
RSAES_PKCS1v15_Decryptor pri1(privateKey);
RSAES_PKCS1v15_Encryptor pub1(publicKey);
printf("max plaintext Length = %d,%d\n", pri1.FixedMaxPlaintextLength(), pub1.FixedMaxPlaintextLength());
if (pub1.FixedMaxPlaintextLength() > message.length())
{//´ý¼ÓÃÜÎı¾²»ÄÜ´óÓÚ×î´ó¼ÓÃܳ¤¶È
string chilper;
StringSource(message, true, new PK_EncryptorFilter(rnd, pub1, new StringSink(chilper)));
printf("chilper = %s, length = %d\n", chilper.c_str(), strlen(chilper.c_str()));
string txt;
StringSource(chilper, true, new PK_DecryptorFilter(rnd, pri1, new StringSink(txt)));
printf("txt = %s, length = %d\n", txt.c_str(), strlen(txt.c_str()));
}
}
void test()
{
////////////////////////////////////////////////
// Generate keys
AutoSeededRandomPool rng;
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize( rng, 1536 );
RSA::PrivateKey privateKey( params );
RSA::PublicKey publicKey( params );
string plain="RSA Encryption", cipher, recovered;
////////////////////////////////////////////////
// Encryption
RSAES_OAEP_SHA_Encryptor e( publicKey );
StringSource ss1( plain, true,
new PK_EncryptorFilter( rng, e,
new StringSink( cipher )
) // PK_EncryptorFilter
); // StringSource
////////////////////////////////////////////////
// Decryption
RSAES_OAEP_SHA_Decryptor d( privateKey );
StringSource ss2( cipher, true,
new PK_DecryptorFilter( rng, d,
new StringSink( recovered )
) // PK_DecryptorFilter
); // StringSource
assert( plain == recovered );
}
int main()
{
//DES_test();
//DES_EDE2_test();
//DES_EDE3_test();
//DES_XEX3_test();
AES_test();
//RSA_Test();
test();
} | {'content_hash': '859eb129748325cc07236aab5f2d3ab3', 'timestamp': '', 'source': 'github', 'line_count': 283, 'max_line_length': 106, 'avg_line_length': 27.575971731448764, 'alnum_prop': 0.6541517170681702, 'repo_name': 'xlplbo/cryptopp', 'id': 'c927f7d735f519132ab979f5e70414db55945197', 'size': '7804', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/main.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '82096'}, {'name': 'C', 'bytes': '27212'}, {'name': 'C++', 'bytes': '2183296'}, {'name': 'Makefile', 'bytes': '6823'}, {'name': 'Protocol Buffer', 'bytes': '300'}]} |
package com.mollyshove.psu.cs300;
import javax.swing.*;
import java.awt.event.*;
/**
* Created by pixie on 6/6/2017 for CS202.
*/
public class ChatScreen {
private JList userList;
private JTextField boxToRead;
public JTextArea boxForText;
private JPanel ChatScreen;
public JFrame frame;
public ChatScreen() {
boxToRead.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
if (e.getKeyChar() == KeyEvent.VK_ENTER) {//if they hit enter key stroke works
if(boxToRead.getText().equals("/history")) {
HistoryScreen historyScreen = new HistoryScreen();
}
else{
try {
ChatClient.sendMessage(boxToRead.getText(), ChatClientController.user);
boxForText.append(ChatClientController.user + ": " + boxToRead.getText() + "\n");//displays!
ChatClientController.write(ChatClientController.user + ": " + boxToRead.getText() + "\n");//writes it to history
} catch (Exception e1) {
e1.printStackTrace();
}
boxToRead.setText("");//clears text
}
}
}
});
frame = new JFrame("ChatScreen");
frame.setContentPane(ChatScreen);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}
| {'content_hash': '2a61b139f8eb66532e17d38cec41525a', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 140, 'avg_line_length': 30.942307692307693, 'alnum_prop': 0.5201988812927284, 'repo_name': 'pixieofhugs/ChatterboxX', 'id': '2f1bb8505cdf5867ba32cb606d78435d50021ae0', 'size': '1609', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Client/src/com/mollyshove/psu/cs300/ChatScreen.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '106'}, {'name': 'Java', 'bytes': '26743'}, {'name': 'Protocol Buffer', 'bytes': '688'}]} |
###############################################################################
# Name: syntax.py #
# Purpose: Manage and dynamically load/provide syntax on request from editor. #
# Also manages the mappings of file extensions to lexers. #
# Author: Cody Precord <[email protected]> #
# Copyright: (c) 2007 Cody Precord <[email protected]> #
# Licence: wxWindows Licence #
###############################################################################
"""
FILE: syntax.py
AUTHOR: Cody Precord
SUMMARY:
Toolkit for managing the importing of syntax modules and providing the data
to the requesting text control. It is meant to be the main access point to the
resources and api provided by this package.
DETAIL:
The main item of this module is the L{SyntaxMgr} it is a singleton object that
manages the dynamic importing of syntax data and configurations for all of the
editors supported languages. It allows only the needed data to be loaded into
memory when requested. The loading is only done once per session and all
subsequent requests share the same object.
In addition to the L{SyntaxMgr} there are also a number of other utility and
convienience functions in this module for accessing data from other related
objects such as the Extension Register.
@summary: Main api access point for the syntax package.
"""
__author__ = "Cody Precord <[email protected]>"
__svnid__ = "$Id: syntax.py 71711 2012-06-09 18:59:03Z CJP $"
__revision__ = "$Revision: 71711 $"
#-----------------------------------------------------------------------------#
# Dependencies
import wx
import os
#-----------------------------------------------------------------------------#
# Data Objects / Constants
# Used to index the tuple returned by getting data from EXT_REG
LANG_ID = 0
MODULE = 1
_ = wx.GetTranslation
#-----------------------------------------------------------------------------#
# Imports
import synglob
import syndata
import synxml
# Needed by other modules that use this api
from synextreg import ExtensionRegister, GetFileExtensions, RegisterNewLangId
#-----------------------------------------------------------------------------#
class SyntaxMgr(object):
"""Class Object for managing loaded syntax data. The manager
is only created once as a singleton and shared amongst all
editor windows
"""
instance = None
first = True
def __init__(self, config=None):
"""Initialize a syntax manager. If the optional
value config is set the mapping of extensions to
lexers will be loaded from a config file.
@keyword config: path of config file to load file extension config from
"""
if SyntaxMgr.first:
object.__init__(self)
SyntaxMgr.first = False
self._extreg = ExtensionRegister()
self._config = config
self._loaded = dict()
# Syntax mode extensions
self._extensions = dict() # loaded extensions "py" : PythonMode()
self.InitConfig()
def __new__(cls, config=None):
"""Ensure only a single instance is shared amongst
all objects.
@return: class instance
"""
if cls.instance is None:
cls.instance = object.__new__(cls)
return cls.instance
def _ExtToMod(self, ext):
"""Gets the name of the module that is is associated
with the given extension or None in the event that there
is no association or that the association is plain text.
@param ext: extension string to lookup module for
"""
ftype = self._extreg.FileTypeFromExt(ext)
lexdat = synglob.LANG_MAP.get(ftype)
mod = None
if lexdat:
mod = lexdat[MODULE]
return mod
def GetLangId(self, ext):
"""Gets the language Id that is associated with the file
extension.
@param ext: extension to get lang id for
"""
ftype = self._extreg.FileTypeFromExt(ext)
return synglob.LANG_MAP[ftype][LANG_ID]
def InitConfig(self):
"""Initialize the SyntaxMgr's configuration state"""
if self._config:
self._extreg.LoadFromConfig(self._config)
else:
self._extreg.LoadDefault()
if self._config:
self.LoadExtensions(self._config)
def IsModLoaded(self, modname):
"""Checks if a module has already been loaded
@param modname: name of module to lookup
"""
if modname in self._loaded:
return True
else:
return False
def LoadModule(self, modname):
"""Dynamically loads a module by name. The loading is only
done if the modules data set is not already being managed
@param modname: name of syntax module to load
"""
if modname == None:
return False
if not self.IsModLoaded(modname):
try:
self._loaded[modname] = __import__(modname, globals(),
locals(), [''])
except ImportError, msg:
return False
return True
def SaveState(self):
"""Saves the current configuration state of the manager to
disk for use in other sessions.
@return: whether save was successful or not
"""
if not self._config or not os.path.exists(self._config):
return False
path = os.path.join(self._config, self._extreg.config)
try:
file_h = open(path, "wb")
file_h.write(str(self._extreg))
file_h.close()
except IOError:
return False
return True
def GetSyntaxData(self, ext):
"""Fetches the language data based on a file extension string. The file
extension is used to look up the default lexer actions from the EXT_REG
dictionary.
@see: L{synglob}
@param ext: a string representing the file extension
@return: SyntaxData object
"""
# The Return Value
lang = self._extreg.FileTypeFromExt(ext)
if lang in self._extensions:
syn_data = self._extensions[lang]
return syn_data
# Check for extensions that may have been removed
if lang not in synglob.LANG_MAP:
self._extreg.Remove(lang)
lex_cfg = synglob.LANG_MAP.get(lang, synglob.LANG_MAP[synglob.LANG_TXT])
# Check if module is loaded and load if necessary
if not self.LoadModule(lex_cfg[MODULE]):
# Bail out and return a default plaintext config as
# nothing else can be done at this point
return syndata.SyntaxDataBase()
# This little bit of code fetches the keyword/syntax
# spec set(s) from the specified module
mod = self._loaded[lex_cfg[MODULE]]
syn_data = mod.SyntaxData(lex_cfg[LANG_ID])
return syn_data
def LoadExtensions(self, path):
"""Load all extensions found at the extension path
@param path: path to look for extension on
"""
for fname in os.listdir(path):
if fname.endswith(u".edxml"):
fpath = os.path.join(path, fname)
modeh = synxml.LoadHandler(fpath)
if modeh.IsOk():
sdata = SynExtensionDelegate(modeh)
self._extensions[sdata.GetXmlObject().GetLanguage()] = sdata
else:
pass
#TODO: report error
def SetConfigDir(self, path):
"""Set the path to locate config information at. The SyntaxMgr will
look for file type associations in a file called synmap and will load
syntax extensions from .edxml files found at this path.
@param path: string
"""
self._config = path
#-----------------------------------------------------------------------------#
class SynExtensionDelegate(syndata.SyntaxDataBase):
"""Delegate SyntaxData class for SynXml Extension class instances"""
def __init__(self, xml_obj):
"""Initialize the data class
@param xml_obj: SynXml
"""
langId = _RegisterExtensionHandler(xml_obj)
syndata.SyntaxDataBase.__init__(self, langId)
# Attributes
self._xml = xml_obj
# Setup
self.SetLexer(self._xml.GetLexer())
#TODO: Load and register features specified by the xml object
#---- Syntax Data Implementation ----#
def GetCommentPattern(self):
"""Get the comment pattern
@return: list of strings ['/*', '*/']
"""
return self._xml.GetCommentPattern()
def GetKeywords(self):
"""Get the Keyword List(s)
@return: list of tuples [(1, ['kw1', kw2']),]
"""
keywords = self._xml.GetKeywords()
rwords = list()
for sid, words in keywords:
rwords.append((sid, u" ".join(words)))
return rwords
def GetProperties(self):
"""Get the Properties List
@return: list of tuples [('fold', '1'),]
"""
return self._xml.GetProperties()
def GetSyntaxSpec(self):
"""Get the the syntax specification list
@return: list of tuples [(int, 'style_tag'),]
"""
return self._xml.GetSyntaxSpec()
#---- End Syntax Data Implementation ----#
def GetXmlObject(self):
"""Get the xml object
@return: EditraXml instance
"""
return self._xml
#-----------------------------------------------------------------------------#
def GenLexerMenu():
"""Generates a menu of available syntax configurations
@return: wx.Menu
"""
lex_menu = wx.Menu()
f_types = dict()
for key in synglob.LANG_MAP:
f_types[key] = synglob.LANG_MAP[key][LANG_ID]
f_order = list(f_types)
f_order.sort(key=unicode.lower)
for lang in f_order:
lex_menu.Append(f_types[lang], lang,
_("Switch Lexer to %s") % lang, wx.ITEM_CHECK)
return lex_menu
def GenFileFilters():
"""Generates a list of file filters
@return: list of all file filters based on extension associations
"""
extreg = ExtensionRegister()
# Convert extension list into a formatted string
f_dict = dict()
for key, val in extreg.iteritems():
val.sort()
if key.lower() == 'makefile':
continue
f_dict[key] = u";*." + u";*.".join(val)
# Build the final list of properly formatted strings
filters = list()
for key in f_dict:
tmp = u" (%s)|%s|" % (f_dict[key][1:], f_dict[key][1:])
filters.append(key + tmp)
filters.sort(key=unicode.lower)
filters.insert(0, u"All Files (*)|*|")
filters[-1] = filters[-1][:-1] # IMPORTANT trim last '|' from item in list
return filters
def GetLexerList():
"""Gets the list of all supported file types
@return: list of strings
"""
f_types = synglob.LANG_MAP.keys()
f_types.sort(key=unicode.lower)
return f_types
#---- Syntax id set ----#
SYNTAX_IDS = None
def SyntaxIds():
"""Gets a list of all Syntax Ids and returns it
@return: list of all syntax language ids
"""
# Use the cached list if its available
if SYNTAX_IDS is not None:
return SYNTAX_IDS
syn_ids = list()
for item in dir(synglob):
if item.startswith("ID_LANG"):
syn_ids.append(getattr(synglob, item))
return syn_ids
SYNTAX_IDS = SyntaxIds()
def SyntaxNames():
"""Gets a list of all Syntax Labels
@return: list of strings
"""
syn_list = list()
for item in dir(synglob):
if item.startswith("LANG_"):
val = getattr(synglob, item)
if isinstance(val, basestring):
syn_list.append(val)
return syn_list
#---- End Syntax ids ----#
def GetExtFromId(ext_id):
"""Takes a language ID and fetches an appropriate file extension string
@param ext_id: language id to get extension for
@return: file extension
"""
extreg = ExtensionRegister()
ftype = synglob.GetDescriptionFromId(ext_id)
rval = u''
if len(extreg[ftype]):
rval = extreg[ftype][0]
return rval
def GetIdFromExt(ext):
"""Get the language id from the given file extension
@param ext: file extension (no dot)
@return: language identifier id from extension register
"""
ftype = ExtensionRegister().FileTypeFromExt(ext)
if ftype in synglob.LANG_MAP:
return synglob.LANG_MAP[ftype][LANG_ID]
else:
return synglob.ID_LANG_TXT
def GetTypeFromExt(ext):
"""Get the filetype description string from the given extension.
The return value defaults to synglob.LANG_TXT if nothing is found.
@param ext: file extension string (no dot)
@return: String
"""
return ExtensionRegister().FileTypeFromExt(ext)
def _RegisterExtensionHandler(xml_obj):
"""Register an ExtensionHandler with this module.
@todo: this is a temporary hack till what to do with the language id's
is decided.
"""
# Create an ID value for the lang id string
langId = xml_obj.GetLangId()
rid = RegisterNewLangId(langId, xml_obj.GetLanguage())
setattr(synglob, langId, rid)
setattr(synglob, langId[3:], xml_obj.GetLanguage())
# Register file extensions with extension register
ExtensionRegister().Associate(xml_obj.GetLanguage(),
u" ".join(xml_obj.FileExtensions))
# Update static syntax id list
if rid not in SYNTAX_IDS:
SYNTAX_IDS.append(rid)
return rid
| {'content_hash': '6d211b2b3b7fe1d579e1c2747f05d2e8', 'timestamp': '', 'source': 'github', 'line_count': 441, 'max_line_length': 80, 'avg_line_length': 32.42403628117914, 'alnum_prop': 0.5608783831037135, 'repo_name': 'ktan2020/legacy-automation', 'id': '7688dcd5572964e3e23a7b20c7ddab4405258ac6', 'size': '14299', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'win/Lib/site-packages/wx-3.0-msw/wx/tools/Editra/src/syntax/syntax.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '913'}, {'name': 'Ada', 'bytes': '289'}, {'name': 'Assembly', 'bytes': '687'}, {'name': 'Boo', 'bytes': '540'}, {'name': 'C', 'bytes': '40116'}, {'name': 'C#', 'bytes': '474'}, {'name': 'C++', 'bytes': '393'}, {'name': 'CSS', 'bytes': '70883'}, {'name': 'ColdFusion', 'bytes': '1012'}, {'name': 'Common Lisp', 'bytes': '1034'}, {'name': 'D', 'bytes': '1858'}, {'name': 'Eiffel', 'bytes': '426'}, {'name': 'Erlang', 'bytes': '9243'}, {'name': 'FORTRAN', 'bytes': '1810'}, {'name': 'Forth', 'bytes': '182'}, {'name': 'Groovy', 'bytes': '2366'}, {'name': 'Haskell', 'bytes': '816'}, {'name': 'Haxe', 'bytes': '455'}, {'name': 'Java', 'bytes': '1155'}, {'name': 'JavaScript', 'bytes': '69444'}, {'name': 'Lua', 'bytes': '795'}, {'name': 'Matlab', 'bytes': '1278'}, {'name': 'OCaml', 'bytes': '350'}, {'name': 'Objective-C++', 'bytes': '885'}, {'name': 'PHP', 'bytes': '1411'}, {'name': 'Pascal', 'bytes': '388'}, {'name': 'Perl', 'bytes': '252651'}, {'name': 'Pike', 'bytes': '589'}, {'name': 'Python', 'bytes': '42085780'}, {'name': 'R', 'bytes': '1156'}, {'name': 'Ruby', 'bytes': '480'}, {'name': 'Scheme', 'bytes': '282'}, {'name': 'Shell', 'bytes': '30518'}, {'name': 'Smalltalk', 'bytes': '926'}, {'name': 'Squirrel', 'bytes': '697'}, {'name': 'Stata', 'bytes': '302'}, {'name': 'SystemVerilog', 'bytes': '3145'}, {'name': 'Tcl', 'bytes': '1039'}, {'name': 'TeX', 'bytes': '1746'}, {'name': 'VHDL', 'bytes': '985'}, {'name': 'Vala', 'bytes': '664'}, {'name': 'Verilog', 'bytes': '439'}, {'name': 'Visual Basic', 'bytes': '2142'}, {'name': 'XSLT', 'bytes': '152770'}, {'name': 'ooc', 'bytes': '890'}, {'name': 'xBase', 'bytes': '769'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>lambek: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.0 / lambek - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
lambek
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-12 10:52:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-12 10:52:21 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.0 Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler
ocamlfind 1.9.1 A library manager for OCaml
ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/lambek"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Lambek"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: Computational linguistic" "keyword: categorial grammar" "keyword: Lambek calculus..." "category: Computer Science/Formal Languages Theory and Automata" "date: March-July 2003" ]
authors: [ "Houda Anoun <[email protected]>" "Pierre Castéran <[email protected]>" ]
bug-reports: "https://github.com/coq-contribs/lambek/issues"
dev-repo: "git+https://github.com/coq-contribs/lambek.git"
synopsis: "A Coq Toolkit for Lambek Calculus"
description: """
This library contains some definitions concerning Lambek calculus.
Three formalisations of this calculus are proposed, and also some certified
functions which translate derivations from one formalism to another.
Several derived properties are proved and also some meta-theorems.
Users can define their own lexicons and use the defined tactics to prove the
derivation of sentences in a particular system (L, NL, LP, NLP ...)"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/lambek/archive/v8.6.0.tar.gz"
checksum: "md5=cc0f6b594eed76d3a1173da03efa542b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-lambek.8.6.0 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0).
The following dependencies couldn't be met:
- coq-lambek -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-lambek.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '89b626894a6d4ee8349938912eb39440', 'timestamp': '', 'source': 'github', 'line_count': 172, 'max_line_length': 245, 'avg_line_length': 44.43023255813954, 'alnum_prop': 0.5582308296257524, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '6bf08f82d974b7ce6f87d6c22a9f25195101f556', 'size': '7668', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.05.0-2.0.1/released/8.14.0/lambek/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.php.project</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/php-project/1">
<name>SAA</name>
</data>
</configuration>
</project>
| {'content_hash': '6c4ee2831b2aee6015050702c2874f4e', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 63, 'avg_line_length': 34.888888888888886, 'alnum_prop': 0.5987261146496815, 'repo_name': 'AnasMhaish/SAA', 'id': 'f6048573ff93f13ab329bedf288635bff716c35f', 'size': '314', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'nbproject/project.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '2728'}, {'name': 'PHP', 'bytes': '119175'}, {'name': 'Shell', 'bytes': '1552'}]} |
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "Pods-BondSample/Bond.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "Pods-BondSample/Bond.framework"
fi
| {'content_hash': '4e8724efcd1d51f7e04bc04335aadb51', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 209, 'avg_line_length': 39.13333333333333, 'alnum_prop': 0.6342986939239069, 'repo_name': 'taktamur/BondSample', 'id': 'f5abbec9729b9a0332c7e52df580f2060a853d8c', 'size': '3532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Pods/Target Support Files/Pods-BondSample/Pods-BondSample-frameworks.sh', 'mode': '33261', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '272'}, {'name': 'Swift', 'bytes': '15464'}]} |
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
])
SimpleCov.start do
add_filter '/spec/'
end
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
# config.order = 'random'
config.before(:each) do
clear_db
end
config.after :suite do
RailsSettingsMigration.migrate(:down)
end
end
require 'active_record'
require 'protected_attributes' if ENV['PROTECTED_ATTRIBUTES'] == 'true'
require 'rails-settings'
if I18n.respond_to?(:enforce_available_locales=)
I18n.enforce_available_locales = false
end
class User < ActiveRecord::Base
has_settings do |s|
s.key :dashboard, :defaults => { :theme => 'blue', :view => 'monthly', :a => 'b', :filter => true, owner_name: -> (target) { target.name } }
s.key :calendar, :defaults => { :scope => 'company', :events => [], :profile => {} }
end
end
class GuestUser < User
has_settings do |s|
s.key :dashboard, :defaults => { :theme => 'red', :view => 'monthly', :filter => true }
end
end
class Account < ActiveRecord::Base
has_settings :portal
end
class Project < ActiveRecord::Base
has_settings :info, :class_name => 'ProjectSettingObject'
end
class ProjectSettingObject < RailsSettings::SettingObject
validate do
unless self.owner_name.present? && self.owner_name.is_a?(String)
errors.add(:base, "Owner name is missing")
end
end
end
def setup_db
ActiveRecord::Base.configurations = YAML.load_file(File.dirname(__FILE__) + '/database.yml')
ActiveRecord::Base.establish_connection(:sqlite)
ActiveRecord::Migration.verbose = false
print "Testing with ActiveRecord #{ActiveRecord::VERSION::STRING}"
if ActiveRecord::VERSION::MAJOR == 4
print " #{defined?(ProtectedAttributes) ? 'with' : 'without'} gem `protected_attributes`"
end
puts
require File.expand_path('../../lib/generators/rails_settings/migration/templates/migration.rb', __FILE__)
RailsSettingsMigration.migrate(:up)
ActiveRecord::Schema.define(:version => 1) do
create_table :users do |t|
t.string :type
t.string :name
end
create_table :accounts do |t|
t.string :subdomain
end
create_table :projects do |t|
t.string :name
end
end
end
def clear_db
User.delete_all
Account.delete_all
RailsSettings::SettingObject.delete_all
end
setup_db
| {'content_hash': '4420fe29a491999ef7f1741b528e74e5', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 144, 'avg_line_length': 28.324324324324323, 'alnum_prop': 0.6981552162849872, 'repo_name': 'DFrenkel/rails-settings', 'id': '5d262bd064bad6fbb627258b6d9ecf2f352c8a9f', 'size': '3144', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/spec_helper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '36897'}]} |
<?php
namespace yii\filters;
use Yii;
use yii\base\ActionFilter;
use yii\base\Action;
use yii\caching\Cache;
use yii\caching\Dependency;
use yii\di\Instance;
use yii\web\Response;
/**
* PageCache implements server-side caching of whole pages.
*
* It is an action filter that can be added to a controller and handles the `beforeAction` event.
*
* To use PageCache, declare it in the `behaviors()` method of your controller class.
* In the following example the filter will be applied to the `index` action and
* cache the whole page for maximum 60 seconds or until the count of entries in the post table changes.
* It also stores different versions of the page depending on the application language.
*
* ```php
* public function behaviors()
* {
* return [
* 'pageCache' => [
* 'class' => 'yii\filters\PageCache',
* 'only' => ['index'],
* 'duration' => 60,
* 'dependency' => [
* 'class' => 'yii\caching\DbDependency',
* 'sql' => 'SELECT COUNT(*) FROM post',
* ],
* 'variations' => [
* \Yii::$app->language,
* ]
* ],
* ];
* }
* ```
*
* @author Qiang Xue <[email protected]>
* @since 2.0
*/
class PageCache extends ActionFilter
{
/**
* @var bool whether the content being cached should be differentiated according to the route.
* A route consists of the requested controller ID and action ID. Defaults to true.
*/
public $varyByRoute = true;
/**
* @var Cache|array|string the cache object or the application component ID of the cache object.
* After the PageCache object is created, if you want to change this property,
* you should only assign it with a cache object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $cache = 'cache';
/**
* @var int number of seconds that the data can remain valid in cache.
* Use 0 to indicate that the cached data will never expire.
*/
public $duration = 60;
/**
* @var array|Dependency the dependency that the cached content depends on.
* This can be either a [[Dependency]] object or a configuration array for creating the dependency object.
* For example,
*
* ```php
* [
* 'class' => 'yii\caching\DbDependency',
* 'sql' => 'SELECT MAX(updated_at) FROM post',
* ]
* ```
*
* would make the output cache depend on the last modified time of all posts.
* If any post has its modification time changed, the cached content would be invalidated.
*
* If [[cacheCookies]] or [[cacheHeaders]] is enabled, then [[\yii\caching\Dependency::reusable]] should be enabled as well to save performance.
* This is because the cookies and headers are currently stored separately from the actual page content, causing the dependency to be evaluated twice.
*/
public $dependency;
/**
* @var array list of factors that would cause the variation of the content being cached.
* Each factor is a string representing a variation (e.g. the language, a GET parameter).
* The following variation setting will cause the content to be cached in different versions
* according to the current application language:
*
* ```php
* [
* Yii::$app->language,
* ]
* ```
*/
public $variations;
/**
* @var bool whether to enable the page cache. You may use this property to turn on and off
* the page cache according to specific setting (e.g. enable page cache only for GET requests).
*/
public $enabled = true;
/**
* @var \yii\base\View the view component to use for caching. If not set, the default application view component
* [[\yii\web\Application::view]] will be used.
*/
public $view;
/**
* @var bool|array a boolean value indicating whether to cache all cookies, or an array of
* cookie names indicating which cookies can be cached. Be very careful with caching cookies, because
* it may leak sensitive or private data stored in cookies to unwanted users.
* @since 2.0.4
*/
public $cacheCookies = false;
/**
* @var bool|array a boolean value indicating whether to cache all HTTP headers, or an array of
* HTTP header names (case-insensitive) indicating which HTTP headers can be cached.
* Note if your HTTP headers contain sensitive information, you should white-list which headers can be cached.
* @since 2.0.4
*/
public $cacheHeaders = true;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->view === null) {
$this->view = Yii::$app->getView();
}
}
/**
* This method is invoked right before an action is to be executed (after all possible filters.)
* You may override this method to do last-minute preparation for the action.
* @param Action $action the action to be executed.
* @return bool whether the action should continue to be executed.
*/
public function beforeAction($action)
{
if (!$this->enabled) {
return true;
}
$this->cache = Instance::ensure($this->cache, Cache::className());
if (is_array($this->dependency)) {
$this->dependency = Yii::createObject($this->dependency);
}
$properties = [];
foreach (['cache', 'duration', 'dependency', 'variations'] as $name) {
$properties[$name] = $this->$name;
}
$id = $this->varyByRoute ? $action->getUniqueId() : __CLASS__;
$response = Yii::$app->getResponse();
ob_start();
ob_implicit_flush(false);
if ($this->view->beginCache($id, $properties)) {
$response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
Yii::trace('Valid page content is not found in the cache.', __METHOD__);
return true;
} else {
$data = $this->cache->get($this->calculateCacheKey());
if (is_array($data)) {
$this->restoreResponse($response, $data);
}
$response->content = ob_get_clean();
Yii::trace('Valid page content is found in the cache.', __METHOD__);
return false;
}
}
/**
* Restores response properties from the given data
* @param Response $response the response to be restored
* @param array $data the response property data
* @since 2.0.3
*/
protected function restoreResponse($response, $data)
{
if (isset($data['format'])) {
$response->format = $data['format'];
}
if (isset($data['version'])) {
$response->version = $data['version'];
}
if (isset($data['statusCode'])) {
$response->statusCode = $data['statusCode'];
}
if (isset($data['statusText'])) {
$response->statusText = $data['statusText'];
}
if (isset($data['headers']) && is_array($data['headers'])) {
$headers = $response->getHeaders()->toArray();
$response->getHeaders()->fromArray(array_merge($data['headers'], $headers));
}
if (isset($data['cookies']) && is_array($data['cookies'])) {
$cookies = $response->getCookies()->toArray();
$response->getCookies()->fromArray(array_merge($data['cookies'], $cookies));
}
}
/**
* Caches response properties.
* @since 2.0.3
*/
public function cacheResponse()
{
$this->view->endCache();
$response = Yii::$app->getResponse();
$data = [
'format' => $response->format,
'version' => $response->version,
'statusCode' => $response->statusCode,
'statusText' => $response->statusText,
];
if (!empty($this->cacheHeaders)) {
$headers = $response->getHeaders()->toArray();
if (is_array($this->cacheHeaders)) {
$filtered = [];
foreach ($this->cacheHeaders as $name) {
$name = strtolower($name);
if (isset($headers[$name])) {
$filtered[$name] = $headers[$name];
}
}
$headers = $filtered;
}
$data['headers'] = $headers;
}
if (!empty($this->cacheCookies)) {
$cookies = $response->getCookies()->toArray();
if (is_array($this->cacheCookies)) {
$filtered = [];
foreach ($this->cacheCookies as $name) {
if (isset($cookies[$name])) {
$filtered[$name] = $cookies[$name];
}
}
$cookies = $filtered;
}
$data['cookies'] = $cookies;
}
$this->cache->set($this->calculateCacheKey(), $data, $this->duration, $this->dependency);
echo ob_get_clean();
}
/**
* @return array the key used to cache response properties.
* @since 2.0.3
*/
protected function calculateCacheKey()
{
$key = [__CLASS__];
if ($this->varyByRoute) {
$key[] = Yii::$app->requestedRoute;
}
if (is_array($this->variations)) {
foreach ($this->variations as $value) {
$key[] = $value;
}
}
return $key;
}
}
| {'content_hash': '8b78096f8b67abf46de965d3f6cb7e59', 'timestamp': '', 'source': 'github', 'line_count': 268, 'max_line_length': 154, 'avg_line_length': 35.84701492537314, 'alnum_prop': 0.5646924117830748, 'repo_name': 'delgado161/extranet', 'id': '9b9495e2859a068bbb77bc14ac248a51abf37478', 'size': '9751', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'vendor/yiisoft/yii2/filters/PageCache.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '245'}, {'name': 'Batchfile', 'bytes': '1030'}, {'name': 'CSS', 'bytes': '520275'}, {'name': 'JavaScript', 'bytes': '158988'}, {'name': 'PHP', 'bytes': '436184'}]} |
int main()
{
BookHandle book = xlCreateBook();
if(book)
{
FontHandle font;
FormatHandle format;
SheetHandle sheet;
font = xlBookAddFont(book, 0);
xlFontSetName(font, "Impact");
xlFontSetSize(font, 36);
format = xlBookAddFormat(book, NULL);
xlFormatSetAlignH(format, ALIGNH_CENTER);
xlFormatSetBorder(format, BORDERSTYLE_MEDIUMDASHDOTDOT);
xlFormatSetBorderColor(format, COLOR_RED);
xlFormatSetFont(format, font);
sheet = xlBookAddSheet(book, "Custom", 0);
if(sheet)
{
xlSheetWriteStr(sheet, 2, 1, "Format", format);
xlSheetSetCol(sheet, 1, 1, 25, 0, 0);
}
if(xlBookSave(book, "format.xls")) printf("\nFile format.xls has been created.\n");
}
printf("\nPress any key to exit...");
_getch();
return 0;
}
| {'content_hash': '80aa4abacf8bbf53b379c386b17bbcf0', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 91, 'avg_line_length': 26.41176470588235, 'alnum_prop': 0.5757238307349666, 'repo_name': 'mikhaelmurmur/PseudoRandomGenerators', 'id': '5bef528225648acb0244c467dcbdc3bcb92f5201', 'size': '956', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'extern/libxl-3.7.0.1/examples/c/mingw/format.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '113799'}, {'name': 'C++', 'bytes': '2697605'}, {'name': 'HTML', 'bytes': '1673272'}, {'name': 'Objective-C', 'bytes': '17483'}]} |
function ii::text::reset() {
if [ -t 1 ]; then
tput sgr0
fi
}
# ii::text::bold sets the terminal output to bold text if it is called in a TTY
function ii::text::bold() {
if [ -t 1 ]; then
tput bold
fi
}
# ii::text::red sets the terminal output to red text if it is called in a TTY
function ii::text::red() {
if [ -t 1 ]; then
tput setaf 1
fi
}
# ii::text::green sets the terminal output to green text if it is called in a TTY
function ii::text::green() {
if [ -t 1 ]; then
tput setaf 2
fi
}
# ii::text::blue sets the terminal output to blue text if it is called in a TTY
function ii::text::blue() {
if [ -t 1 ]; then
tput setaf 4
fi
}
# ii::text::yellow sets the terminal output to yellow text if it is called in a TTY
function ii::text::yellow() {
if [ -t 1 ]; then
tput setaf 11
fi
}
# ii::text::clear_last_line clears the text from the last line of output to the
# terminal and leaves the cursor on that line to allow for overwriting that text
# if it is called in a TTY
function ii::text::clear_last_line() {
if [ -t 1 ]; then
tput cuu 1
tput el
fi
}
# ii::text::print_bold prints all input in bold text
function ii::text::print_bold() {
ii::text::bold
echo "${*}"
ii::text::reset
}
# ii::text::print_red prints all input in red text
function ii::text::print_red() {
ii::text::red
echo "${*}"
ii::text::reset
}
# ii::text::print_red_bold prints all input in bold red text
function ii::text::print_red_bold() {
ii::text::red
ii::text::bold
echo "${*}"
ii::text::reset
}
# ii::text::print_green prints all input in green text
function ii::text::print_green() {
ii::text::green
echo "${*}"
ii::text::reset
}
# ii::text::print_green_bold prints all input in bold green text
function ii::text::print_green_bold() {
ii::text::green
ii::text::bold
echo "${*}"
ii::text::reset
}
# ii::text::print_blue prints all input in blue text
function ii::text::print_blue() {
ii::text::blue
echo "${*}"
ii::text::reset
}
# ii::text::print_blue_bold prints all input in bold blue text
function ii::text::print_blue_bold() {
ii::text::blue
ii::text::bold
echo "${*}"
ii::text::reset
}
# ii::text::print_yellow prints all input in yellow text
function ii::text::print_yellow() {
ii::text::yellow
echo "${*}"
ii::text::reset
}
# ii::text::print_yellow_bold prints all input in bold yellow text
function ii::text::print_yellow_bold() {
ii::text::yellow
ii::text::bold
echo "${*}"
ii::text::reset
}
| {'content_hash': '7bb0861055e1a711192acc04e15c4670', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 83, 'avg_line_length': 20.99145299145299, 'alnum_prop': 0.6547231270358306, 'repo_name': 'ilackarms/image-inspector', 'id': 'cfa30cddac3271ecd4c3cb6aaf5ce13360de534c', 'size': '2764', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'hack/text.sh', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '83610'}, {'name': 'Makefile', 'bytes': '1108'}, {'name': 'Shell', 'bytes': '48894'}]} |
trackr-frontend
==============
This is the trackr-page frontend. Though named trackr it's actually an app containing trackr. But trackr is most of it, code and featurewise.
Building
--------
You need node, npm installed. From npm you need grunt-cli, bower and karma.
In the main directory run
grunt test
grunt dist
grunt karma:cover
Test will run all tests. dist will create the production package. karma:cover will run some coverage. The coverage report will be placed in reports/coverage.
Running
-------
The best way to run the frontend against a backend locally is to have a HTTP server like nginx running that serves the static files and proxies the requests to the backend.
Here is my nginx config:
server {
listen 80;
server_name localhost;
root /Users/moritz/workspace/techdev/trackr-frontend/;
location /trackr/api/ {
proxy_pass http://localhost:8080/;
}
location /trackr/ {
alias /Users/moritz/workspace/techdev/trackr-frontend/dist/;
try_files $uri $uri/ index.html =404;
}
location /portal/ {
proxy_pass http://localhost:8081/;
proxy_redirect http://localhost:8081/ http://localhost/portal/;
}
}
Of course you have to change the root path to your location. If you want to test the dist/ just add it to the root path.
Put this in /etc/nginx/sites-available/trackr.conf, then make a symbolic link
ln -s /etc/nginx/sites-avialable/trackr.conf /etc/nginx/sites-enabled/
And be sure that the sites-enabled are loaded in the nginx.conf. If you start nginx you can find trackr under http://localhost:9090/.
A similar Apache config is
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
LoadModule substitute_module /usr/lib/apache2/modules/mod_substitute.so
<VirtualHost *:80>
DocumentRoot /var/www/
Alias /trackr /var/www/trackr-frontend
<Location /trackr/api>
ProxyPreserveHost On
ProxyPass http://localhost:8080
</Location>
<Location /portal/>
ProxyPreserveHost Off
ProxyPass http://localhost:8081/
ProxyPassReverse http://localhost:8081/
</Location>
</VirtualHost>
| {'content_hash': '5d4c1cb4091cb00a0818d865949da6af', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 172, 'avg_line_length': 33.183098591549296, 'alnum_prop': 0.6752971137521222, 'repo_name': 'agilemobiledev/trackr-frontend', 'id': '5312c64fc5e67c04f0a138818bda721edfc85631', 'size': '2356', 'binary': False, 'copies': '3', 'ref': 'refs/heads/development', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '92310'}, {'name': 'JavaScript', 'bytes': '356700'}]} |
internal unsafe struct C4ListenerConfig
{
public ushort port;
public FLSlice networkInterface;
public C4ListenerAPIs apis;
public C4TLSConfig* tlsConfig;
public IntPtr httpAuthCallback;
public void* callbackContext;
public FLSlice directory;
private byte _allowCreateDBs;
private byte _allowDeleteDBs;
private byte _allowPush;
private byte _allowPull;
private byte _enableDeltaSync;
public bool allowCreateDBs
{
get {
return Convert.ToBoolean(_allowCreateDBs);
}
set {
_allowCreateDBs = Convert.ToByte(value);
}
}
public bool allowDeleteDBs
{
get {
return Convert.ToBoolean(_allowDeleteDBs);
}
set {
_allowDeleteDBs = Convert.ToByte(value);
}
}
public bool allowPush
{
get {
return Convert.ToBoolean(_allowPush);
}
set {
_allowPush = Convert.ToByte(value);
}
}
public bool allowPull
{
get {
return Convert.ToBoolean(_allowPull);
}
set {
_allowPull = Convert.ToByte(value);
}
}
public bool enableDeltaSync
{
get {
return Convert.ToBoolean(_enableDeltaSync);
}
set {
_enableDeltaSync = Convert.ToByte(value);
}
}
}
| {'content_hash': '8565259e114189a63e111b329e9286b0', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 59, 'avg_line_length': 25.323076923076922, 'alnum_prop': 0.47691373025516404, 'repo_name': 'couchbase/couchbase-lite-net', 'id': '6aa14b691b9cd4aa174b64011b2d6a8bce6bd228', 'size': '1646', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/LiteCore/parse/templates_c4/C4ListenerConfig.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2853'}, {'name': 'C#', 'bytes': '2694002'}, {'name': 'PowerShell', 'bytes': '17354'}, {'name': 'Python', 'bytes': '26527'}, {'name': 'Shell', 'bytes': '2708'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.