text stringlengths 2 1.04M | meta dict |
|---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/participant.proto
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* The top-level message returned from the `StreamingAnalyzeContent` method.
* Multiple response messages can be returned in order:
* 1. If the input was set to streaming audio, the first one or more messages
* contain `recognition_result`. Each `recognition_result` represents a more
* complete transcript of what the user said. The last `recognition_result`
* has `is_final` set to `true`.
* 2. In virtual agent stage: if `enable_partial_automated_agent_reply` is
* true, the following N (currently 1 <= N <= 4) messages
* contain `automated_agent_reply` and optionally `reply_audio`
* returned by the virtual agent. The first (N-1)
* `automated_agent_reply`s will have `automated_agent_reply_type` set to
* `PARTIAL`. The last `automated_agent_reply` has
* `automated_agent_reply_type` set to `FINAL`.
* If `enable_partial_automated_agent_reply` is not enabled, response stream
* only contains the final reply.
* In human assist stage: the following N (N >= 1) messages contain
* `human_agent_suggestion_results`, `end_user_suggestion_results` or
* `message`.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse}
*/
public final class StreamingAnalyzeContentResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse)
StreamingAnalyzeContentResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use StreamingAnalyzeContentResponse.newBuilder() to construct.
private StreamingAnalyzeContentResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StreamingAnalyzeContentResponse() {
replyText_ = "";
humanAgentSuggestionResults_ = java.util.Collections.emptyList();
endUserSuggestionResults_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new StreamingAnalyzeContentResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.ParticipantProto
.internal_static_google_cloud_dialogflow_v2_StreamingAnalyzeContentResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.ParticipantProto
.internal_static_google_cloud_dialogflow_v2_StreamingAnalyzeContentResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.class,
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.Builder.class);
}
public static final int RECOGNITION_RESULT_FIELD_NUMBER = 1;
private com.google.cloud.dialogflow.v2.StreamingRecognitionResult recognitionResult_;
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*
* @return Whether the recognitionResult field is set.
*/
@java.lang.Override
public boolean hasRecognitionResult() {
return recognitionResult_ != null;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*
* @return The recognitionResult.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingRecognitionResult getRecognitionResult() {
return recognitionResult_ == null
? com.google.cloud.dialogflow.v2.StreamingRecognitionResult.getDefaultInstance()
: recognitionResult_;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingRecognitionResultOrBuilder
getRecognitionResultOrBuilder() {
return getRecognitionResult();
}
public static final int REPLY_TEXT_FIELD_NUMBER = 2;
private volatile java.lang.Object replyText_;
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @return The replyText.
*/
@java.lang.Override
public java.lang.String getReplyText() {
java.lang.Object ref = replyText_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
replyText_ = s;
return s;
}
}
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @return The bytes for replyText.
*/
@java.lang.Override
public com.google.protobuf.ByteString getReplyTextBytes() {
java.lang.Object ref = replyText_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
replyText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REPLY_AUDIO_FIELD_NUMBER = 3;
private com.google.cloud.dialogflow.v2.OutputAudio replyAudio_;
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*
* @return Whether the replyAudio field is set.
*/
@java.lang.Override
public boolean hasReplyAudio() {
return replyAudio_ != null;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*
* @return The replyAudio.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.OutputAudio getReplyAudio() {
return replyAudio_ == null
? com.google.cloud.dialogflow.v2.OutputAudio.getDefaultInstance()
: replyAudio_;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.OutputAudioOrBuilder getReplyAudioOrBuilder() {
return getReplyAudio();
}
public static final int AUTOMATED_AGENT_REPLY_FIELD_NUMBER = 4;
private com.google.cloud.dialogflow.v2.AutomatedAgentReply automatedAgentReply_;
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*
* @return Whether the automatedAgentReply field is set.
*/
@java.lang.Override
public boolean hasAutomatedAgentReply() {
return automatedAgentReply_ != null;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*
* @return The automatedAgentReply.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.AutomatedAgentReply getAutomatedAgentReply() {
return automatedAgentReply_ == null
? com.google.cloud.dialogflow.v2.AutomatedAgentReply.getDefaultInstance()
: automatedAgentReply_;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.AutomatedAgentReplyOrBuilder
getAutomatedAgentReplyOrBuilder() {
return getAutomatedAgentReply();
}
public static final int MESSAGE_FIELD_NUMBER = 6;
private com.google.cloud.dialogflow.v2.Message message_;
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*
* @return Whether the message field is set.
*/
@java.lang.Override
public boolean hasMessage() {
return message_ != null;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*
* @return The message.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.Message getMessage() {
return message_ == null
? com.google.cloud.dialogflow.v2.Message.getDefaultInstance()
: message_;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.MessageOrBuilder getMessageOrBuilder() {
return getMessage();
}
public static final int HUMAN_AGENT_SUGGESTION_RESULTS_FIELD_NUMBER = 7;
private java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
humanAgentSuggestionResults_;
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
getHumanAgentSuggestionResultsList() {
return humanAgentSuggestionResults_;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getHumanAgentSuggestionResultsOrBuilderList() {
return humanAgentSuggestionResults_;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
@java.lang.Override
public int getHumanAgentSuggestionResultsCount() {
return humanAgentSuggestionResults_.size();
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SuggestionResult getHumanAgentSuggestionResults(int index) {
return humanAgentSuggestionResults_.get(index);
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder
getHumanAgentSuggestionResultsOrBuilder(int index) {
return humanAgentSuggestionResults_.get(index);
}
public static final int END_USER_SUGGESTION_RESULTS_FIELD_NUMBER = 8;
private java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult> endUserSuggestionResults_;
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
getEndUserSuggestionResultsList() {
return endUserSuggestionResults_;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getEndUserSuggestionResultsOrBuilderList() {
return endUserSuggestionResults_;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
@java.lang.Override
public int getEndUserSuggestionResultsCount() {
return endUserSuggestionResults_.size();
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SuggestionResult getEndUserSuggestionResults(int index) {
return endUserSuggestionResults_.get(index);
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder
getEndUserSuggestionResultsOrBuilder(int index) {
return endUserSuggestionResults_.get(index);
}
public static final int DTMF_PARAMETERS_FIELD_NUMBER = 10;
private com.google.cloud.dialogflow.v2.DtmfParameters dtmfParameters_;
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*
* @return Whether the dtmfParameters field is set.
*/
@java.lang.Override
public boolean hasDtmfParameters() {
return dtmfParameters_ != null;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*
* @return The dtmfParameters.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.DtmfParameters getDtmfParameters() {
return dtmfParameters_ == null
? com.google.cloud.dialogflow.v2.DtmfParameters.getDefaultInstance()
: dtmfParameters_;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.DtmfParametersOrBuilder getDtmfParametersOrBuilder() {
return getDtmfParameters();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (recognitionResult_ != null) {
output.writeMessage(1, getRecognitionResult());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(replyText_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, replyText_);
}
if (replyAudio_ != null) {
output.writeMessage(3, getReplyAudio());
}
if (automatedAgentReply_ != null) {
output.writeMessage(4, getAutomatedAgentReply());
}
if (message_ != null) {
output.writeMessage(6, getMessage());
}
for (int i = 0; i < humanAgentSuggestionResults_.size(); i++) {
output.writeMessage(7, humanAgentSuggestionResults_.get(i));
}
for (int i = 0; i < endUserSuggestionResults_.size(); i++) {
output.writeMessage(8, endUserSuggestionResults_.get(i));
}
if (dtmfParameters_ != null) {
output.writeMessage(10, getDtmfParameters());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (recognitionResult_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getRecognitionResult());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(replyText_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, replyText_);
}
if (replyAudio_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getReplyAudio());
}
if (automatedAgentReply_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getAutomatedAgentReply());
}
if (message_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, getMessage());
}
for (int i = 0; i < humanAgentSuggestionResults_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
7, humanAgentSuggestionResults_.get(i));
}
for (int i = 0; i < endUserSuggestionResults_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
8, endUserSuggestionResults_.get(i));
}
if (dtmfParameters_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(10, getDtmfParameters());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse other =
(com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse) obj;
if (hasRecognitionResult() != other.hasRecognitionResult()) return false;
if (hasRecognitionResult()) {
if (!getRecognitionResult().equals(other.getRecognitionResult())) return false;
}
if (!getReplyText().equals(other.getReplyText())) return false;
if (hasReplyAudio() != other.hasReplyAudio()) return false;
if (hasReplyAudio()) {
if (!getReplyAudio().equals(other.getReplyAudio())) return false;
}
if (hasAutomatedAgentReply() != other.hasAutomatedAgentReply()) return false;
if (hasAutomatedAgentReply()) {
if (!getAutomatedAgentReply().equals(other.getAutomatedAgentReply())) return false;
}
if (hasMessage() != other.hasMessage()) return false;
if (hasMessage()) {
if (!getMessage().equals(other.getMessage())) return false;
}
if (!getHumanAgentSuggestionResultsList().equals(other.getHumanAgentSuggestionResultsList()))
return false;
if (!getEndUserSuggestionResultsList().equals(other.getEndUserSuggestionResultsList()))
return false;
if (hasDtmfParameters() != other.hasDtmfParameters()) return false;
if (hasDtmfParameters()) {
if (!getDtmfParameters().equals(other.getDtmfParameters())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasRecognitionResult()) {
hash = (37 * hash) + RECOGNITION_RESULT_FIELD_NUMBER;
hash = (53 * hash) + getRecognitionResult().hashCode();
}
hash = (37 * hash) + REPLY_TEXT_FIELD_NUMBER;
hash = (53 * hash) + getReplyText().hashCode();
if (hasReplyAudio()) {
hash = (37 * hash) + REPLY_AUDIO_FIELD_NUMBER;
hash = (53 * hash) + getReplyAudio().hashCode();
}
if (hasAutomatedAgentReply()) {
hash = (37 * hash) + AUTOMATED_AGENT_REPLY_FIELD_NUMBER;
hash = (53 * hash) + getAutomatedAgentReply().hashCode();
}
if (hasMessage()) {
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
}
if (getHumanAgentSuggestionResultsCount() > 0) {
hash = (37 * hash) + HUMAN_AGENT_SUGGESTION_RESULTS_FIELD_NUMBER;
hash = (53 * hash) + getHumanAgentSuggestionResultsList().hashCode();
}
if (getEndUserSuggestionResultsCount() > 0) {
hash = (37 * hash) + END_USER_SUGGESTION_RESULTS_FIELD_NUMBER;
hash = (53 * hash) + getEndUserSuggestionResultsList().hashCode();
}
if (hasDtmfParameters()) {
hash = (37 * hash) + DTMF_PARAMETERS_FIELD_NUMBER;
hash = (53 * hash) + getDtmfParameters().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The top-level message returned from the `StreamingAnalyzeContent` method.
* Multiple response messages can be returned in order:
* 1. If the input was set to streaming audio, the first one or more messages
* contain `recognition_result`. Each `recognition_result` represents a more
* complete transcript of what the user said. The last `recognition_result`
* has `is_final` set to `true`.
* 2. In virtual agent stage: if `enable_partial_automated_agent_reply` is
* true, the following N (currently 1 <= N <= 4) messages
* contain `automated_agent_reply` and optionally `reply_audio`
* returned by the virtual agent. The first (N-1)
* `automated_agent_reply`s will have `automated_agent_reply_type` set to
* `PARTIAL`. The last `automated_agent_reply` has
* `automated_agent_reply_type` set to `FINAL`.
* If `enable_partial_automated_agent_reply` is not enabled, response stream
* only contains the final reply.
* In human assist stage: the following N (N >= 1) messages contain
* `human_agent_suggestion_results`, `end_user_suggestion_results` or
* `message`.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse)
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.ParticipantProto
.internal_static_google_cloud_dialogflow_v2_StreamingAnalyzeContentResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.ParticipantProto
.internal_static_google_cloud_dialogflow_v2_StreamingAnalyzeContentResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.class,
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
if (recognitionResultBuilder_ == null) {
recognitionResult_ = null;
} else {
recognitionResult_ = null;
recognitionResultBuilder_ = null;
}
replyText_ = "";
if (replyAudioBuilder_ == null) {
replyAudio_ = null;
} else {
replyAudio_ = null;
replyAudioBuilder_ = null;
}
if (automatedAgentReplyBuilder_ == null) {
automatedAgentReply_ = null;
} else {
automatedAgentReply_ = null;
automatedAgentReplyBuilder_ = null;
}
if (messageBuilder_ == null) {
message_ = null;
} else {
message_ = null;
messageBuilder_ = null;
}
if (humanAgentSuggestionResultsBuilder_ == null) {
humanAgentSuggestionResults_ = java.util.Collections.emptyList();
} else {
humanAgentSuggestionResults_ = null;
humanAgentSuggestionResultsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
if (endUserSuggestionResultsBuilder_ == null) {
endUserSuggestionResults_ = java.util.Collections.emptyList();
} else {
endUserSuggestionResults_ = null;
endUserSuggestionResultsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
if (dtmfParametersBuilder_ == null) {
dtmfParameters_ = null;
} else {
dtmfParameters_ = null;
dtmfParametersBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.ParticipantProto
.internal_static_google_cloud_dialogflow_v2_StreamingAnalyzeContentResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse build() {
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse buildPartial() {
com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse result =
new com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse(this);
int from_bitField0_ = bitField0_;
if (recognitionResultBuilder_ == null) {
result.recognitionResult_ = recognitionResult_;
} else {
result.recognitionResult_ = recognitionResultBuilder_.build();
}
result.replyText_ = replyText_;
if (replyAudioBuilder_ == null) {
result.replyAudio_ = replyAudio_;
} else {
result.replyAudio_ = replyAudioBuilder_.build();
}
if (automatedAgentReplyBuilder_ == null) {
result.automatedAgentReply_ = automatedAgentReply_;
} else {
result.automatedAgentReply_ = automatedAgentReplyBuilder_.build();
}
if (messageBuilder_ == null) {
result.message_ = message_;
} else {
result.message_ = messageBuilder_.build();
}
if (humanAgentSuggestionResultsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
humanAgentSuggestionResults_ =
java.util.Collections.unmodifiableList(humanAgentSuggestionResults_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.humanAgentSuggestionResults_ = humanAgentSuggestionResults_;
} else {
result.humanAgentSuggestionResults_ = humanAgentSuggestionResultsBuilder_.build();
}
if (endUserSuggestionResultsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
endUserSuggestionResults_ =
java.util.Collections.unmodifiableList(endUserSuggestionResults_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.endUserSuggestionResults_ = endUserSuggestionResults_;
} else {
result.endUserSuggestionResults_ = endUserSuggestionResultsBuilder_.build();
}
if (dtmfParametersBuilder_ == null) {
result.dtmfParameters_ = dtmfParameters_;
} else {
result.dtmfParameters_ = dtmfParametersBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse) {
return mergeFrom((com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse other) {
if (other
== com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.getDefaultInstance())
return this;
if (other.hasRecognitionResult()) {
mergeRecognitionResult(other.getRecognitionResult());
}
if (!other.getReplyText().isEmpty()) {
replyText_ = other.replyText_;
onChanged();
}
if (other.hasReplyAudio()) {
mergeReplyAudio(other.getReplyAudio());
}
if (other.hasAutomatedAgentReply()) {
mergeAutomatedAgentReply(other.getAutomatedAgentReply());
}
if (other.hasMessage()) {
mergeMessage(other.getMessage());
}
if (humanAgentSuggestionResultsBuilder_ == null) {
if (!other.humanAgentSuggestionResults_.isEmpty()) {
if (humanAgentSuggestionResults_.isEmpty()) {
humanAgentSuggestionResults_ = other.humanAgentSuggestionResults_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.addAll(other.humanAgentSuggestionResults_);
}
onChanged();
}
} else {
if (!other.humanAgentSuggestionResults_.isEmpty()) {
if (humanAgentSuggestionResultsBuilder_.isEmpty()) {
humanAgentSuggestionResultsBuilder_.dispose();
humanAgentSuggestionResultsBuilder_ = null;
humanAgentSuggestionResults_ = other.humanAgentSuggestionResults_;
bitField0_ = (bitField0_ & ~0x00000001);
humanAgentSuggestionResultsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getHumanAgentSuggestionResultsFieldBuilder()
: null;
} else {
humanAgentSuggestionResultsBuilder_.addAllMessages(other.humanAgentSuggestionResults_);
}
}
}
if (endUserSuggestionResultsBuilder_ == null) {
if (!other.endUserSuggestionResults_.isEmpty()) {
if (endUserSuggestionResults_.isEmpty()) {
endUserSuggestionResults_ = other.endUserSuggestionResults_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.addAll(other.endUserSuggestionResults_);
}
onChanged();
}
} else {
if (!other.endUserSuggestionResults_.isEmpty()) {
if (endUserSuggestionResultsBuilder_.isEmpty()) {
endUserSuggestionResultsBuilder_.dispose();
endUserSuggestionResultsBuilder_ = null;
endUserSuggestionResults_ = other.endUserSuggestionResults_;
bitField0_ = (bitField0_ & ~0x00000002);
endUserSuggestionResultsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getEndUserSuggestionResultsFieldBuilder()
: null;
} else {
endUserSuggestionResultsBuilder_.addAllMessages(other.endUserSuggestionResults_);
}
}
}
if (other.hasDtmfParameters()) {
mergeDtmfParameters(other.getDtmfParameters());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getRecognitionResultFieldBuilder().getBuilder(), extensionRegistry);
break;
} // case 10
case 18:
{
replyText_ = input.readStringRequireUtf8();
break;
} // case 18
case 26:
{
input.readMessage(getReplyAudioFieldBuilder().getBuilder(), extensionRegistry);
break;
} // case 26
case 34:
{
input.readMessage(
getAutomatedAgentReplyFieldBuilder().getBuilder(), extensionRegistry);
break;
} // case 34
case 50:
{
input.readMessage(getMessageFieldBuilder().getBuilder(), extensionRegistry);
break;
} // case 50
case 58:
{
com.google.cloud.dialogflow.v2.SuggestionResult m =
input.readMessage(
com.google.cloud.dialogflow.v2.SuggestionResult.parser(),
extensionRegistry);
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.add(m);
} else {
humanAgentSuggestionResultsBuilder_.addMessage(m);
}
break;
} // case 58
case 66:
{
com.google.cloud.dialogflow.v2.SuggestionResult m =
input.readMessage(
com.google.cloud.dialogflow.v2.SuggestionResult.parser(),
extensionRegistry);
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.add(m);
} else {
endUserSuggestionResultsBuilder_.addMessage(m);
}
break;
} // case 66
case 82:
{
input.readMessage(getDtmfParametersFieldBuilder().getBuilder(), extensionRegistry);
break;
} // case 82
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.dialogflow.v2.StreamingRecognitionResult recognitionResult_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.StreamingRecognitionResult,
com.google.cloud.dialogflow.v2.StreamingRecognitionResult.Builder,
com.google.cloud.dialogflow.v2.StreamingRecognitionResultOrBuilder>
recognitionResultBuilder_;
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*
* @return Whether the recognitionResult field is set.
*/
public boolean hasRecognitionResult() {
return recognitionResultBuilder_ != null || recognitionResult_ != null;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*
* @return The recognitionResult.
*/
public com.google.cloud.dialogflow.v2.StreamingRecognitionResult getRecognitionResult() {
if (recognitionResultBuilder_ == null) {
return recognitionResult_ == null
? com.google.cloud.dialogflow.v2.StreamingRecognitionResult.getDefaultInstance()
: recognitionResult_;
} else {
return recognitionResultBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public Builder setRecognitionResult(
com.google.cloud.dialogflow.v2.StreamingRecognitionResult value) {
if (recognitionResultBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
recognitionResult_ = value;
onChanged();
} else {
recognitionResultBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public Builder setRecognitionResult(
com.google.cloud.dialogflow.v2.StreamingRecognitionResult.Builder builderForValue) {
if (recognitionResultBuilder_ == null) {
recognitionResult_ = builderForValue.build();
onChanged();
} else {
recognitionResultBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public Builder mergeRecognitionResult(
com.google.cloud.dialogflow.v2.StreamingRecognitionResult value) {
if (recognitionResultBuilder_ == null) {
if (recognitionResult_ != null) {
recognitionResult_ =
com.google.cloud.dialogflow.v2.StreamingRecognitionResult.newBuilder(
recognitionResult_)
.mergeFrom(value)
.buildPartial();
} else {
recognitionResult_ = value;
}
onChanged();
} else {
recognitionResultBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public Builder clearRecognitionResult() {
if (recognitionResultBuilder_ == null) {
recognitionResult_ = null;
onChanged();
} else {
recognitionResult_ = null;
recognitionResultBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public com.google.cloud.dialogflow.v2.StreamingRecognitionResult.Builder
getRecognitionResultBuilder() {
onChanged();
return getRecognitionResultFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
public com.google.cloud.dialogflow.v2.StreamingRecognitionResultOrBuilder
getRecognitionResultOrBuilder() {
if (recognitionResultBuilder_ != null) {
return recognitionResultBuilder_.getMessageOrBuilder();
} else {
return recognitionResult_ == null
? com.google.cloud.dialogflow.v2.StreamingRecognitionResult.getDefaultInstance()
: recognitionResult_;
}
}
/**
*
*
* <pre>
* The result of speech recognition.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.StreamingRecognitionResult recognition_result = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.StreamingRecognitionResult,
com.google.cloud.dialogflow.v2.StreamingRecognitionResult.Builder,
com.google.cloud.dialogflow.v2.StreamingRecognitionResultOrBuilder>
getRecognitionResultFieldBuilder() {
if (recognitionResultBuilder_ == null) {
recognitionResultBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.StreamingRecognitionResult,
com.google.cloud.dialogflow.v2.StreamingRecognitionResult.Builder,
com.google.cloud.dialogflow.v2.StreamingRecognitionResultOrBuilder>(
getRecognitionResult(), getParentForChildren(), isClean());
recognitionResult_ = null;
}
return recognitionResultBuilder_;
}
private java.lang.Object replyText_ = "";
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @return The replyText.
*/
public java.lang.String getReplyText() {
java.lang.Object ref = replyText_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
replyText_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @return The bytes for replyText.
*/
public com.google.protobuf.ByteString getReplyTextBytes() {
java.lang.Object ref = replyText_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
replyText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @param value The replyText to set.
* @return This builder for chaining.
*/
public Builder setReplyText(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
replyText_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearReplyText() {
replyText_ = getDefaultInstance().getReplyText();
onChanged();
return this;
}
/**
*
*
* <pre>
* The output text content.
* This field is set if an automated agent responded with a text for the user.
* </pre>
*
* <code>string reply_text = 2;</code>
*
* @param value The bytes for replyText to set.
* @return This builder for chaining.
*/
public Builder setReplyTextBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
replyText_ = value;
onChanged();
return this;
}
private com.google.cloud.dialogflow.v2.OutputAudio replyAudio_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.OutputAudio,
com.google.cloud.dialogflow.v2.OutputAudio.Builder,
com.google.cloud.dialogflow.v2.OutputAudioOrBuilder>
replyAudioBuilder_;
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*
* @return Whether the replyAudio field is set.
*/
public boolean hasReplyAudio() {
return replyAudioBuilder_ != null || replyAudio_ != null;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*
* @return The replyAudio.
*/
public com.google.cloud.dialogflow.v2.OutputAudio getReplyAudio() {
if (replyAudioBuilder_ == null) {
return replyAudio_ == null
? com.google.cloud.dialogflow.v2.OutputAudio.getDefaultInstance()
: replyAudio_;
} else {
return replyAudioBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public Builder setReplyAudio(com.google.cloud.dialogflow.v2.OutputAudio value) {
if (replyAudioBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
replyAudio_ = value;
onChanged();
} else {
replyAudioBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public Builder setReplyAudio(
com.google.cloud.dialogflow.v2.OutputAudio.Builder builderForValue) {
if (replyAudioBuilder_ == null) {
replyAudio_ = builderForValue.build();
onChanged();
} else {
replyAudioBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public Builder mergeReplyAudio(com.google.cloud.dialogflow.v2.OutputAudio value) {
if (replyAudioBuilder_ == null) {
if (replyAudio_ != null) {
replyAudio_ =
com.google.cloud.dialogflow.v2.OutputAudio.newBuilder(replyAudio_)
.mergeFrom(value)
.buildPartial();
} else {
replyAudio_ = value;
}
onChanged();
} else {
replyAudioBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public Builder clearReplyAudio() {
if (replyAudioBuilder_ == null) {
replyAudio_ = null;
onChanged();
} else {
replyAudio_ = null;
replyAudioBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public com.google.cloud.dialogflow.v2.OutputAudio.Builder getReplyAudioBuilder() {
onChanged();
return getReplyAudioFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
public com.google.cloud.dialogflow.v2.OutputAudioOrBuilder getReplyAudioOrBuilder() {
if (replyAudioBuilder_ != null) {
return replyAudioBuilder_.getMessageOrBuilder();
} else {
return replyAudio_ == null
? com.google.cloud.dialogflow.v2.OutputAudio.getDefaultInstance()
: replyAudio_;
}
}
/**
*
*
* <pre>
* The audio data bytes encoded as specified in the request.
* This field is set if:
* - The `reply_audio_config` field is specified in the request.
* - The automated agent, which this output comes from, responded with audio.
* In such case, the `reply_audio.config` field contains settings used to
* synthesize the speech.
* In some scenarios, multiple output audio fields may be present in the
* response structure. In these cases, only the top-most-level audio output
* has content.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.OutputAudio reply_audio = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.OutputAudio,
com.google.cloud.dialogflow.v2.OutputAudio.Builder,
com.google.cloud.dialogflow.v2.OutputAudioOrBuilder>
getReplyAudioFieldBuilder() {
if (replyAudioBuilder_ == null) {
replyAudioBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.OutputAudio,
com.google.cloud.dialogflow.v2.OutputAudio.Builder,
com.google.cloud.dialogflow.v2.OutputAudioOrBuilder>(
getReplyAudio(), getParentForChildren(), isClean());
replyAudio_ = null;
}
return replyAudioBuilder_;
}
private com.google.cloud.dialogflow.v2.AutomatedAgentReply automatedAgentReply_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.AutomatedAgentReply,
com.google.cloud.dialogflow.v2.AutomatedAgentReply.Builder,
com.google.cloud.dialogflow.v2.AutomatedAgentReplyOrBuilder>
automatedAgentReplyBuilder_;
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*
* @return Whether the automatedAgentReply field is set.
*/
public boolean hasAutomatedAgentReply() {
return automatedAgentReplyBuilder_ != null || automatedAgentReply_ != null;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*
* @return The automatedAgentReply.
*/
public com.google.cloud.dialogflow.v2.AutomatedAgentReply getAutomatedAgentReply() {
if (automatedAgentReplyBuilder_ == null) {
return automatedAgentReply_ == null
? com.google.cloud.dialogflow.v2.AutomatedAgentReply.getDefaultInstance()
: automatedAgentReply_;
} else {
return automatedAgentReplyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public Builder setAutomatedAgentReply(
com.google.cloud.dialogflow.v2.AutomatedAgentReply value) {
if (automatedAgentReplyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
automatedAgentReply_ = value;
onChanged();
} else {
automatedAgentReplyBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public Builder setAutomatedAgentReply(
com.google.cloud.dialogflow.v2.AutomatedAgentReply.Builder builderForValue) {
if (automatedAgentReplyBuilder_ == null) {
automatedAgentReply_ = builderForValue.build();
onChanged();
} else {
automatedAgentReplyBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public Builder mergeAutomatedAgentReply(
com.google.cloud.dialogflow.v2.AutomatedAgentReply value) {
if (automatedAgentReplyBuilder_ == null) {
if (automatedAgentReply_ != null) {
automatedAgentReply_ =
com.google.cloud.dialogflow.v2.AutomatedAgentReply.newBuilder(automatedAgentReply_)
.mergeFrom(value)
.buildPartial();
} else {
automatedAgentReply_ = value;
}
onChanged();
} else {
automatedAgentReplyBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public Builder clearAutomatedAgentReply() {
if (automatedAgentReplyBuilder_ == null) {
automatedAgentReply_ = null;
onChanged();
} else {
automatedAgentReply_ = null;
automatedAgentReplyBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public com.google.cloud.dialogflow.v2.AutomatedAgentReply.Builder
getAutomatedAgentReplyBuilder() {
onChanged();
return getAutomatedAgentReplyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
public com.google.cloud.dialogflow.v2.AutomatedAgentReplyOrBuilder
getAutomatedAgentReplyOrBuilder() {
if (automatedAgentReplyBuilder_ != null) {
return automatedAgentReplyBuilder_.getMessageOrBuilder();
} else {
return automatedAgentReply_ == null
? com.google.cloud.dialogflow.v2.AutomatedAgentReply.getDefaultInstance()
: automatedAgentReply_;
}
}
/**
*
*
* <pre>
* Only set if a Dialogflow automated agent has responded.
* Note that: [AutomatedAgentReply.detect_intent_response.output_audio][]
* and [AutomatedAgentReply.detect_intent_response.output_audio_config][]
* are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.AutomatedAgentReply automated_agent_reply = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.AutomatedAgentReply,
com.google.cloud.dialogflow.v2.AutomatedAgentReply.Builder,
com.google.cloud.dialogflow.v2.AutomatedAgentReplyOrBuilder>
getAutomatedAgentReplyFieldBuilder() {
if (automatedAgentReplyBuilder_ == null) {
automatedAgentReplyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.AutomatedAgentReply,
com.google.cloud.dialogflow.v2.AutomatedAgentReply.Builder,
com.google.cloud.dialogflow.v2.AutomatedAgentReplyOrBuilder>(
getAutomatedAgentReply(), getParentForChildren(), isClean());
automatedAgentReply_ = null;
}
return automatedAgentReplyBuilder_;
}
private com.google.cloud.dialogflow.v2.Message message_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.Message,
com.google.cloud.dialogflow.v2.Message.Builder,
com.google.cloud.dialogflow.v2.MessageOrBuilder>
messageBuilder_;
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*
* @return Whether the message field is set.
*/
public boolean hasMessage() {
return messageBuilder_ != null || message_ != null;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*
* @return The message.
*/
public com.google.cloud.dialogflow.v2.Message getMessage() {
if (messageBuilder_ == null) {
return message_ == null
? com.google.cloud.dialogflow.v2.Message.getDefaultInstance()
: message_;
} else {
return messageBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public Builder setMessage(com.google.cloud.dialogflow.v2.Message value) {
if (messageBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
message_ = value;
onChanged();
} else {
messageBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public Builder setMessage(com.google.cloud.dialogflow.v2.Message.Builder builderForValue) {
if (messageBuilder_ == null) {
message_ = builderForValue.build();
onChanged();
} else {
messageBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public Builder mergeMessage(com.google.cloud.dialogflow.v2.Message value) {
if (messageBuilder_ == null) {
if (message_ != null) {
message_ =
com.google.cloud.dialogflow.v2.Message.newBuilder(message_)
.mergeFrom(value)
.buildPartial();
} else {
message_ = value;
}
onChanged();
} else {
messageBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public Builder clearMessage() {
if (messageBuilder_ == null) {
message_ = null;
onChanged();
} else {
message_ = null;
messageBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public com.google.cloud.dialogflow.v2.Message.Builder getMessageBuilder() {
onChanged();
return getMessageFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
public com.google.cloud.dialogflow.v2.MessageOrBuilder getMessageOrBuilder() {
if (messageBuilder_ != null) {
return messageBuilder_.getMessageOrBuilder();
} else {
return message_ == null
? com.google.cloud.dialogflow.v2.Message.getDefaultInstance()
: message_;
}
}
/**
*
*
* <pre>
* Message analyzed by CCAI.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.Message message = 6;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.Message,
com.google.cloud.dialogflow.v2.Message.Builder,
com.google.cloud.dialogflow.v2.MessageOrBuilder>
getMessageFieldBuilder() {
if (messageBuilder_ == null) {
messageBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.Message,
com.google.cloud.dialogflow.v2.Message.Builder,
com.google.cloud.dialogflow.v2.MessageOrBuilder>(
getMessage(), getParentForChildren(), isClean());
message_ = null;
}
return messageBuilder_;
}
private java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
humanAgentSuggestionResults_ = java.util.Collections.emptyList();
private void ensureHumanAgentSuggestionResultsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
humanAgentSuggestionResults_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2.SuggestionResult>(
humanAgentSuggestionResults_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
humanAgentSuggestionResultsBuilder_;
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
getHumanAgentSuggestionResultsList() {
if (humanAgentSuggestionResultsBuilder_ == null) {
return java.util.Collections.unmodifiableList(humanAgentSuggestionResults_);
} else {
return humanAgentSuggestionResultsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public int getHumanAgentSuggestionResultsCount() {
if (humanAgentSuggestionResultsBuilder_ == null) {
return humanAgentSuggestionResults_.size();
} else {
return humanAgentSuggestionResultsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult getHumanAgentSuggestionResults(
int index) {
if (humanAgentSuggestionResultsBuilder_ == null) {
return humanAgentSuggestionResults_.get(index);
} else {
return humanAgentSuggestionResultsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder setHumanAgentSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (humanAgentSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.set(index, value);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder setHumanAgentSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.set(index, builderForValue.build());
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder addHumanAgentSuggestionResults(
com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (humanAgentSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.add(value);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder addHumanAgentSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (humanAgentSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.add(index, value);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder addHumanAgentSuggestionResults(
com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.add(builderForValue.build());
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder addHumanAgentSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.add(index, builderForValue.build());
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder addAllHumanAgentSuggestionResults(
java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.SuggestionResult> values) {
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, humanAgentSuggestionResults_);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder clearHumanAgentSuggestionResults() {
if (humanAgentSuggestionResultsBuilder_ == null) {
humanAgentSuggestionResults_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public Builder removeHumanAgentSuggestionResults(int index) {
if (humanAgentSuggestionResultsBuilder_ == null) {
ensureHumanAgentSuggestionResultsIsMutable();
humanAgentSuggestionResults_.remove(index);
onChanged();
} else {
humanAgentSuggestionResultsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
getHumanAgentSuggestionResultsBuilder(int index) {
return getHumanAgentSuggestionResultsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder
getHumanAgentSuggestionResultsOrBuilder(int index) {
if (humanAgentSuggestionResultsBuilder_ == null) {
return humanAgentSuggestionResults_.get(index);
} else {
return humanAgentSuggestionResultsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getHumanAgentSuggestionResultsOrBuilderList() {
if (humanAgentSuggestionResultsBuilder_ != null) {
return humanAgentSuggestionResultsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(humanAgentSuggestionResults_);
}
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
addHumanAgentSuggestionResultsBuilder() {
return getHumanAgentSuggestionResultsFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.v2.SuggestionResult.getDefaultInstance());
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
addHumanAgentSuggestionResultsBuilder(int index) {
return getHumanAgentSuggestionResultsFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.v2.SuggestionResult.getDefaultInstance());
}
/**
*
*
* <pre>
* The suggestions for most recent human agent. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config].
* </pre>
*
* <code>
* repeated .google.cloud.dialogflow.v2.SuggestionResult human_agent_suggestion_results = 7;
* </code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult.Builder>
getHumanAgentSuggestionResultsBuilderList() {
return getHumanAgentSuggestionResultsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getHumanAgentSuggestionResultsFieldBuilder() {
if (humanAgentSuggestionResultsBuilder_ == null) {
humanAgentSuggestionResultsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>(
humanAgentSuggestionResults_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
humanAgentSuggestionResults_ = null;
}
return humanAgentSuggestionResultsBuilder_;
}
private java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
endUserSuggestionResults_ = java.util.Collections.emptyList();
private void ensureEndUserSuggestionResultsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
endUserSuggestionResults_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2.SuggestionResult>(
endUserSuggestionResults_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
endUserSuggestionResultsBuilder_;
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult>
getEndUserSuggestionResultsList() {
if (endUserSuggestionResultsBuilder_ == null) {
return java.util.Collections.unmodifiableList(endUserSuggestionResults_);
} else {
return endUserSuggestionResultsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public int getEndUserSuggestionResultsCount() {
if (endUserSuggestionResultsBuilder_ == null) {
return endUserSuggestionResults_.size();
} else {
return endUserSuggestionResultsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult getEndUserSuggestionResults(int index) {
if (endUserSuggestionResultsBuilder_ == null) {
return endUserSuggestionResults_.get(index);
} else {
return endUserSuggestionResultsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder setEndUserSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (endUserSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.set(index, value);
onChanged();
} else {
endUserSuggestionResultsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder setEndUserSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.set(index, builderForValue.build());
onChanged();
} else {
endUserSuggestionResultsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder addEndUserSuggestionResults(
com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (endUserSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.add(value);
onChanged();
} else {
endUserSuggestionResultsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder addEndUserSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult value) {
if (endUserSuggestionResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.add(index, value);
onChanged();
} else {
endUserSuggestionResultsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder addEndUserSuggestionResults(
com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.add(builderForValue.build());
onChanged();
} else {
endUserSuggestionResultsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder addEndUserSuggestionResults(
int index, com.google.cloud.dialogflow.v2.SuggestionResult.Builder builderForValue) {
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.add(index, builderForValue.build());
onChanged();
} else {
endUserSuggestionResultsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder addAllEndUserSuggestionResults(
java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.SuggestionResult> values) {
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, endUserSuggestionResults_);
onChanged();
} else {
endUserSuggestionResultsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder clearEndUserSuggestionResults() {
if (endUserSuggestionResultsBuilder_ == null) {
endUserSuggestionResults_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
endUserSuggestionResultsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public Builder removeEndUserSuggestionResults(int index) {
if (endUserSuggestionResultsBuilder_ == null) {
ensureEndUserSuggestionResultsIsMutable();
endUserSuggestionResults_.remove(index);
onChanged();
} else {
endUserSuggestionResultsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
getEndUserSuggestionResultsBuilder(int index) {
return getEndUserSuggestionResultsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder
getEndUserSuggestionResultsOrBuilder(int index) {
if (endUserSuggestionResultsBuilder_ == null) {
return endUserSuggestionResults_.get(index);
} else {
return endUserSuggestionResultsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getEndUserSuggestionResultsOrBuilderList() {
if (endUserSuggestionResultsBuilder_ != null) {
return endUserSuggestionResultsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(endUserSuggestionResults_);
}
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
addEndUserSuggestionResultsBuilder() {
return getEndUserSuggestionResultsFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.v2.SuggestionResult.getDefaultInstance());
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public com.google.cloud.dialogflow.v2.SuggestionResult.Builder
addEndUserSuggestionResultsBuilder(int index) {
return getEndUserSuggestionResultsFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.v2.SuggestionResult.getDefaultInstance());
}
/**
*
*
* <pre>
* The suggestions for end user. The order is the same as
* [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of
* [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config].
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2.SuggestionResult end_user_suggestion_results = 8;
* </code>
*/
public java.util.List<com.google.cloud.dialogflow.v2.SuggestionResult.Builder>
getEndUserSuggestionResultsBuilderList() {
return getEndUserSuggestionResultsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>
getEndUserSuggestionResultsFieldBuilder() {
if (endUserSuggestionResultsBuilder_ == null) {
endUserSuggestionResultsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2.SuggestionResult,
com.google.cloud.dialogflow.v2.SuggestionResult.Builder,
com.google.cloud.dialogflow.v2.SuggestionResultOrBuilder>(
endUserSuggestionResults_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
endUserSuggestionResults_ = null;
}
return endUserSuggestionResultsBuilder_;
}
private com.google.cloud.dialogflow.v2.DtmfParameters dtmfParameters_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.DtmfParameters,
com.google.cloud.dialogflow.v2.DtmfParameters.Builder,
com.google.cloud.dialogflow.v2.DtmfParametersOrBuilder>
dtmfParametersBuilder_;
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*
* @return Whether the dtmfParameters field is set.
*/
public boolean hasDtmfParameters() {
return dtmfParametersBuilder_ != null || dtmfParameters_ != null;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*
* @return The dtmfParameters.
*/
public com.google.cloud.dialogflow.v2.DtmfParameters getDtmfParameters() {
if (dtmfParametersBuilder_ == null) {
return dtmfParameters_ == null
? com.google.cloud.dialogflow.v2.DtmfParameters.getDefaultInstance()
: dtmfParameters_;
} else {
return dtmfParametersBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public Builder setDtmfParameters(com.google.cloud.dialogflow.v2.DtmfParameters value) {
if (dtmfParametersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
dtmfParameters_ = value;
onChanged();
} else {
dtmfParametersBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public Builder setDtmfParameters(
com.google.cloud.dialogflow.v2.DtmfParameters.Builder builderForValue) {
if (dtmfParametersBuilder_ == null) {
dtmfParameters_ = builderForValue.build();
onChanged();
} else {
dtmfParametersBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public Builder mergeDtmfParameters(com.google.cloud.dialogflow.v2.DtmfParameters value) {
if (dtmfParametersBuilder_ == null) {
if (dtmfParameters_ != null) {
dtmfParameters_ =
com.google.cloud.dialogflow.v2.DtmfParameters.newBuilder(dtmfParameters_)
.mergeFrom(value)
.buildPartial();
} else {
dtmfParameters_ = value;
}
onChanged();
} else {
dtmfParametersBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public Builder clearDtmfParameters() {
if (dtmfParametersBuilder_ == null) {
dtmfParameters_ = null;
onChanged();
} else {
dtmfParameters_ = null;
dtmfParametersBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public com.google.cloud.dialogflow.v2.DtmfParameters.Builder getDtmfParametersBuilder() {
onChanged();
return getDtmfParametersFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
public com.google.cloud.dialogflow.v2.DtmfParametersOrBuilder getDtmfParametersOrBuilder() {
if (dtmfParametersBuilder_ != null) {
return dtmfParametersBuilder_.getMessageOrBuilder();
} else {
return dtmfParameters_ == null
? com.google.cloud.dialogflow.v2.DtmfParameters.getDefaultInstance()
: dtmfParameters_;
}
}
/**
*
*
* <pre>
* Indicates the parameters of DTMF.
* </pre>
*
* <code>.google.cloud.dialogflow.v2.DtmfParameters dtmf_parameters = 10;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.DtmfParameters,
com.google.cloud.dialogflow.v2.DtmfParameters.Builder,
com.google.cloud.dialogflow.v2.DtmfParametersOrBuilder>
getDtmfParametersFieldBuilder() {
if (dtmfParametersBuilder_ == null) {
dtmfParametersBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.DtmfParameters,
com.google.cloud.dialogflow.v2.DtmfParameters.Builder,
com.google.cloud.dialogflow.v2.DtmfParametersOrBuilder>(
getDtmfParameters(), getParentForChildren(), isClean());
dtmfParameters_ = null;
}
return dtmfParametersBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse)
private static final com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse();
}
public static com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<StreamingAnalyzeContentResponse> PARSER =
new com.google.protobuf.AbstractParser<StreamingAnalyzeContentResponse>() {
@java.lang.Override
public StreamingAnalyzeContentResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<StreamingAnalyzeContentResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StreamingAnalyzeContentResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| {
"content_hash": "5ec004f679e8ffcfbfa00a48d38b549c",
"timestamp": "",
"source": "github",
"line_count": 3309,
"max_line_length": 157,
"avg_line_length": 37.3756421879722,
"alnum_prop": 0.6670898153239109,
"repo_name": "googleapis/google-cloud-java",
"id": "ae03fa48090a12b201157482ebf87875bde1b031",
"size": "124270",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/StreamingAnalyzeContentResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2614"
},
{
"name": "HCL",
"bytes": "28592"
},
{
"name": "Java",
"bytes": "826434232"
},
{
"name": "Jinja",
"bytes": "2292"
},
{
"name": "Python",
"bytes": "200408"
},
{
"name": "Shell",
"bytes": "97954"
}
],
"symlink_target": ""
} |
import struct
import socket
import binascii
import time
import hashlib
from bitcoin.serialize import *
from bitcoin.coredefs import *
from bitcoin.script import CScript
class CAddress(object):
def __init__(self, protover=PROTO_VERSION):
self.protover = protover
self.nTime = 0
self.nServices = 1
self.pchReserved = "\x00" * 10 + "\xff" * 2
self.ip = "0.0.0.0"
self.port = 0
def deserialize(self, f):
if self.protover >= CADDR_TIME_VERSION:
self.nTime = struct.unpack("<I", f.read(4))[0]
self.nServices = struct.unpack("<Q", f.read(8))[0]
self.pchReserved = f.read(12)
self.ip = socket.inet_ntoa(f.read(4))
self.port = struct.unpack(">H", f.read(2))[0]
def serialize(self):
r = ""
if self.protover >= CADDR_TIME_VERSION:
r += struct.pack("<I", self.nTime)
r += struct.pack("<Q", self.nServices)
r += self.pchReserved
r += socket.inet_aton(self.ip)
r += struct.pack(">H", self.port)
return r
def __repr__(self):
return "CAddress(nTime=%d nServices=%i ip=%s port=%i)" % (self.nTime, self.nServices, self.ip, self.port)
class CInv(object):
typemap = {
0: "Error",
1: "TX",
2: "Block"}
def __init__(self):
self.type = 0
self.hash = 0L
def deserialize(self, f):
self.type = struct.unpack("<i", f.read(4))[0]
self.hash = deser_uint256(f)
def serialize(self):
r = ""
r += struct.pack("<i", self.type)
r += ser_uint256(self.hash)
return r
def __repr__(self):
return "CInv(type=%s hash=%064x)" % (self.typemap[self.type], self.hash)
class CBlockLocator(object):
def __init__(self):
self.nVersion = PROTO_VERSION
self.vHave = []
def deserialize(self, f):
self.nVersion = struct.unpack("<i", f.read(4))[0]
self.vHave = deser_uint256_vector(f)
def serialize(self):
r = ""
r += struct.pack("<i", self.nVersion)
r += ser_uint256_vector(self.vHave)
return r
def __repr__(self):
return "CBlockLocator(nVersion=%i vHave=%s)" % (self.nVersion, repr(self.vHave))
class COutPoint(object):
def __init__(self):
self.hash = 0
self.n = 0
def deserialize(self, f):
self.hash = deser_uint256(f)
self.n = struct.unpack("<I", f.read(4))[0]
def serialize(self):
r = ""
r += ser_uint256(self.hash)
r += struct.pack("<I", self.n)
return r
def set_null(self):
self.hash = 0
self.n = 0xffffffff
def is_null(self):
return ((self.hash == 0) and (self.n == 0xffffffff))
def copy(self, old_outpt):
self.hash = old_outpt.hash
self.n = old_outpt.n
def __repr__(self):
return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n)
class CTxIn(object):
def __init__(self):
self.prevout = COutPoint()
self.scriptSig = ""
self.nSequence = 0xffffffff
def deserialize(self, f):
self.prevout = COutPoint()
self.prevout.deserialize(f)
self.scriptSig = deser_string(f)
self.nSequence = struct.unpack("<I", f.read(4))[0]
def serialize(self):
r = ""
r += self.prevout.serialize()
r += ser_string(self.scriptSig)
r += struct.pack("<I", self.nSequence)
return r
def is_final(self):
return (self.nSequence == 0xffffffff)
def is_valid(self):
script = CScript()
if not script.tokenize(self.scriptSig):
return False
return True
def copy(self, old_txin):
self.prevout = COutPoint()
self.prevout.copy(old_txin.prevout)
self.scriptSig = old_txin.scriptSig
self.nSequence = old_txin.nSequence
def __repr__(self):
return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" % (repr(self.prevout), binascii.hexlify(self.scriptSig), self.nSequence)
class CTxOut(object):
def __init__(self):
self.nValue = -1
self.scriptPubKey = ""
def deserialize(self, f):
self.nValue = struct.unpack("<q", f.read(8))[0]
self.scriptPubKey = deser_string(f)
def serialize(self):
r = ""
r += struct.pack("<q", self.nValue)
r += ser_string(self.scriptPubKey)
return r
def is_valid(self):
if not MoneyRange(self.nValue):
return False
script = CScript()
if not script.tokenize(self.scriptPubKey):
return False
return True
def copy(self, old_txout):
self.nValue = old_txout.nValue
self.scriptPubKey = old_txout.scriptPubKey
def __repr__(self):
return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" % (self.nValue // 100000000, self.nValue % 100000000, binascii.hexlify(self.scriptPubKey))
class CTransaction(object):
def __init__(self):
# serialized
self.nVersion = 1
self.vin = []
self.vout = []
self.nLockTime = 0
# used at runtime
self.sha256 = None
self.nFeesPaid = 0
self.dFeePerKB = None
self.dPriority = None
self.ser_size = 0
def deserialize(self, f):
self.nVersion = struct.unpack("<i", f.read(4))[0]
self.vin = deser_vector(f, CTxIn)
self.vout = deser_vector(f, CTxOut)
self.nLockTime = struct.unpack("<I", f.read(4))[0]
def serialize(self):
r = ""
r += struct.pack("<i", self.nVersion)
r += ser_vector(self.vin)
r += ser_vector(self.vout)
r += struct.pack("<I", self.nLockTime)
return r
def calc_sha256(self):
if self.sha256 is None:
self.sha256 = Hash(self.serialize())
def is_valid(self):
self.calc_sha256()
if not self.is_coinbase():
for tin in self.vin:
if not tin.is_valid():
return False
for tout in self.vout:
if not tout.is_valid():
return False
return True
def is_final(self):
for tin in self.vin:
if not tin.is_final():
return False
return True
def is_coinbase(self):
return len(self.vin) == 1 and self.vin[0].prevout.is_null()
def copy(self, old_tx):
self.nVersion = old_tx.nVersion
self.vin = []
self.vout = []
self.nLockTime = old_tx.nLockTime
self.sha256 = None
for old_txin in old_tx.vin:
txin = CTxIn()
txin.copy(old_txin)
self.vin.append(txin)
for old_txout in old_tx.vout:
txout = CTxOut()
txout.copy(old_txout)
self.vout.append(txout)
def __repr__(self):
return "CTransaction(nVersion=%i vin=%s vout=%s nLockTime=%i)" % (self.nVersion, repr(self.vin), repr(self.vout), self.nLockTime)
class CBlock(object):
def __init__(self):
self.nVersion = 1
self.hashPrevBlock = 0
self.hashMerkleRoot = 0
self.nTime = 0
self.nBits = 0
self.nNonce = 0
self.vtx = []
self.sha256 = None
def deserialize(self, f):
self.nVersion = struct.unpack("<i", f.read(4))[0]
self.hashPrevBlock = deser_uint256(f)
self.hashMerkleRoot = deser_uint256(f)
self.nTime = struct.unpack("<I", f.read(4))[0]
self.nBits = struct.unpack("<I", f.read(4))[0]
self.nNonce = struct.unpack("<I", f.read(4))[0]
self.vtx = deser_vector(f, CTransaction)
def serialize_hdr(self):
r = ""
r += struct.pack("<i", self.nVersion)
r += ser_uint256(self.hashPrevBlock)
r += ser_uint256(self.hashMerkleRoot)
r += struct.pack("<I", self.nTime)
r += struct.pack("<I", self.nBits)
r += struct.pack("<I", self.nNonce)
return r
def serialize(self):
r = self.serialize_hdr()
r += ser_vector(self.vtx)
return r
def calc_sha256(self):
if self.sha256 is None:
self.sha256 = Hash(self.serialize_hdr())
def calc_merkle(self):
hashes = []
for tx in self.vtx:
if not tx.is_valid():
return None
tx.calc_sha256()
hashes.append(ser_uint256(tx.sha256))
while len(hashes) > 1:
newhashes = []
for i in xrange(0, len(hashes), 2):
i2 = min(i+1, len(hashes)-1)
newhashes.append(hashlib.sha256(hashlib.sha256(hashes[i] + hashes[i2]).digest()).digest())
hashes = newhashes
return uint256_from_str(hashes[0])
def is_valid(self):
self.calc_sha256()
target = uint256_from_compact(self.nBits)
if self.sha256 > target:
return False
if self.calc_merkle() != self.hashMerkleRoot:
return False
return True
def __repr__(self):
return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
class CUnsignedAlert(object):
def __init__(self):
self.nVersion = 1
self.nRelayUntil = 0
self.nExpiration = 0
self.nID = 0
self.nCancel = 0
self.setCancel = []
self.nMinVer = 0
self.nMaxVer = 0
self.setSubVer = []
self.nPriority = 0
self.strComment = ""
self.strStatusBar = ""
self.strReserved = ""
def deserialize(self, f):
self.nVersion = struct.unpack("<i", f.read(4))[0]
self.nRelayUntil = struct.unpack("<q", f.read(8))[0]
self.nExpiration = struct.unpack("<q", f.read(8))[0]
self.nID = struct.unpack("<i", f.read(4))[0]
self.nCancel = struct.unpack("<i", f.read(4))[0]
self.setCancel = deser_int_vector(f)
self.nMinVer = struct.unpack("<i", f.read(4))[0]
self.nMaxVer = struct.unpack("<i", f.read(4))[0]
self.setSubVer = deser_string_vector(f)
self.nPriority = struct.unpack("<i", f.read(4))[0]
self.strComment = deser_string(f)
self.strStatusBar = deser_string(f)
self.strReserved = deser_string(f)
def serialize(self):
r = ""
r += struct.pack("<i", self.nVersion)
r += struct.pack("<q", self.nRelayUntil)
r += struct.pack("<q", self.nExpiration)
r += struct.pack("<i", self.nID)
r += struct.pack("<i", self.nCancel)
r += ser_int_vector(self.setCancel)
r += struct.pack("<i", self.nMinVer)
r += struct.pack("<i", self.nMaxVer)
r += ser_string_vector(self.setSubVer)
r += struct.pack("<i", self.nPriority)
r += ser_string(self.strComment)
r += ser_string(self.strStatusBar)
r += ser_string(self.strReserved)
return r
def __repr__(self):
return "CUnsignedAlert(nVersion %d, nRelayUntil %d, nExpiration %d, nID %d, nCancel %d, nMinVer %d, nMaxVer %d, nPriority %d, strComment %s, strStatusBar %s, strReserved %s)" % (self.nVersion, self.nRelayUntil, self.nExpiration, self.nID, self.nCancel, self.nMinVer, self.nMaxVer, self.nPriority, self.strComment, self.strStatusBar, self.strReserved)
class CAlert(object):
def __init__(self):
self.vchMsg = ""
self.vchSig = ""
def deserialize(self, f):
self.vchMsg = deser_string(f)
self.vchSig = deser_string(f)
def serialize(self):
r = ""
r += ser_string(self.vchMsg)
r += ser_string(self.vchSig)
return r
def __repr__(self):
return "CAlert(vchMsg.sz %d, vchSig.sz %d)" % (len(self.vchMsg), len(self.vchSig))
| {
"content_hash": "6dce915e0ec5b1f1ffcbbbe497534dd5",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 358,
"avg_line_length": 34.98224852071006,
"alnum_prop": 0.559117050067659,
"repo_name": "0dayZh/python-bitcoinlib",
"id": "230b5ae50a107da855513cbf41d13a56ef3bf1ba",
"size": "11983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bitcoin/core.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/llCustomTitleContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_marginBottom="3dp"
android:orientation="horizontal"
android:padding="3dp"
android:background="@color/gray"
android:visibility="gone"
>
<TextView
android:id="@+id/txtCustomTitle"
android:text="[Custom Title]"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textColor="@color/gray_foreground"
>
</TextView>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:cacheColorHint="#00000000"
>
</ListView>
</LinearLayout>
| {
"content_hash": "d2d31d7520441958d4cc34ab194130d0",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 59,
"avg_line_length": 27.89189189189189,
"alnum_prop": 0.7296511627906976,
"repo_name": "hanguyenhuu/DTUI_201105_Android",
"id": "e4b4d4767ebf857a7f291fb6cbe8cb71f8b26eba",
"size": "1032",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/activity_list.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "208920"
}
],
"symlink_target": ""
} |
module AwsCli
module CLI
module EC2
module VPC
require 'awscli/cli/ec2/vpc'
class Dhcp < Thor
desc "list", "List Dhcp Options"
def list
create_ec2_object
@ec2.list
end
desc "create", "Creates a set of DHCP options for your VPC"
method_option :dhcp_configuration_options, :aliases => "-o", :type => :hash, :required => true, :desc => "hash of key value dhcp options(domain-name, domain-name-servers, ntp-servers, netbios-name-servers, netbios-node-type) to assign"
def create
create_ec2_object
@ec2.create options[:dhcp_configuration_options]
end
desc "delete", "Deletes a set of DHCP options that you specify"
method_option :dhcp_options_id, :aliases => "-d", :type => :string, :required => true, :desc => "The ID of the DHCP options set you want to delete"
def delete
create_ec2_object
@ec2.delete options[:dhcp_options_id]
end
desc "associate", "Associates a set of DHCP options (that you've previously created) with the specified VPC. Or, associates no DHCP options with the VPC"
method_option :dhcp_options_id, :aliases => "-d", :type => :string, :required => true, :desc => "The ID of the DHCP options you want to associate with the VPC"
method_option :vpc_id, :aliases => "-v", :type => :string, :required => true, :desc => "The ID of the VPC you want to associate the DHCP options with"
def associate
create_ec2_object
@ec2.associate options[:dhcp_options_id], options[:vpc_id]
end
private
def create_ec2_object
puts "ec2 Establishing Connetion..."
$ec2_conn = if parent_options[:region]
Awscli::Connection.new.request_ec2(parent_options[:region])
else
Awscli::Connection.new.request_ec2
end
puts "ec2 Establishing Connetion... OK"
@ec2 = Awscli::EC2::Dhcp.new($ec2_conn)
end
AwsCli::CLI::EC2::Vpc.register AwsCli::CLI::EC2::VPC::Dhcp, :dhcp, 'dhcp [COMMAND]', 'VPC DHCP Management'
end
end
end
end
end | {
"content_hash": "edd981c8e7724ac253230910072296af",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 245,
"avg_line_length": 41.981818181818184,
"alnum_prop": 0.5751407535729753,
"repo_name": "ashrithr/awscli",
"id": "7d4153e244944178d5dd48bfbbcddc9cbc8bc695",
"size": "2309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/awscli/cli/ec2/vpc/dhcp.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "274956"
}
],
"symlink_target": ""
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package kg.apc.jmeter.reporters;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleResult;
import org.junit.*;
public class ConsoleStatusLoggerTest {
public ConsoleStatusLoggerTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of sampleOccurred method, of class ConsoleStatusLogger.
*/
@Test
public void testSampleOccurred() throws InterruptedException {
System.out.println("sampleOccurred");
SampleResult res = new SampleResult();
res.setResponseCode("200");
SampleEvent se = new SampleEvent(res, "testTG");
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.testStarted();
instance.sampleOccurred(se);
instance.sampleOccurred(se);
Thread.sleep(1020);
instance.sampleOccurred(se);
instance.sampleOccurred(se);
Thread.sleep(1020);
instance.sampleOccurred(se);
instance.sampleOccurred(se);
}
/**
* Test of sampleStarted method, of class ConsoleStatusLogger.
*/
@Test
public void testSampleStarted() {
System.out.println("sampleStarted");
SampleEvent se = null;
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.sampleStarted(se);
}
/**
* Test of sampleStopped method, of class ConsoleStatusLogger.
*/
@Test
public void testSampleStopped() {
System.out.println("sampleStopped");
SampleEvent se = null;
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.sampleStopped(se);
}
/**
* Test of testStarted method, of class ConsoleStatusLogger.
*/
@Test
public void testTestStarted_0args() {
System.out.println("testStarted");
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.testStarted();
}
/**
* Test of testStarted method, of class ConsoleStatusLogger.
*/
@Test
public void testTestStarted_String() {
System.out.println("testStarted");
String string = "";
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.testStarted(string);
}
/**
* Test of testEnded method, of class ConsoleStatusLogger.
*/
@Test
public void testTestEnded_0args() {
System.out.println("testEnded");
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.testEnded();
}
/**
* Test of testEnded method, of class ConsoleStatusLogger.
*/
@Test
public void testTestEnded_String() {
System.out.println("testEnded");
String string = "";
ConsoleStatusLogger instance = new ConsoleStatusLogger();
instance.testEnded(string);
}
}
| {
"content_hash": "9e71630eaf940ab5e0092ddc01116d95",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 67,
"avg_line_length": 26.752136752136753,
"alnum_prop": 0.6412140575079872,
"repo_name": "Sausageo/jmeter-plugins",
"id": "93a6baad717f4b247cb64c80065223e228a643f5",
"size": "3130",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/csl/src/test/java/kg/apc/jmeter/reporters/ConsoleStatusLoggerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4700"
},
{
"name": "HTML",
"bytes": "21374"
},
{
"name": "Java",
"bytes": "2299614"
},
{
"name": "PHP",
"bytes": "2007"
},
{
"name": "Python",
"bytes": "3690"
},
{
"name": "Shell",
"bytes": "1131"
},
{
"name": "Smarty",
"bytes": "7429"
}
],
"symlink_target": ""
} |
// (C) Copyright 2015 Moodle Pty Ltd.
//
// 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.
import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavParams } from 'ionic-angular';
import { AddonModSurveyIndexComponent } from '../../components/index/index';
/**
* Page that displays a survey.
*/
@IonicPage({ segment: 'addon-mod-survey-index' })
@Component({
selector: 'page-addon-mod-survey-index',
templateUrl: 'index.html',
})
export class AddonModSurveyIndexPage {
@ViewChild(AddonModSurveyIndexComponent) surveyComponent: AddonModSurveyIndexComponent;
title: string;
module: any;
courseId: number;
constructor(navParams: NavParams) {
this.module = navParams.get('module') || {};
this.courseId = navParams.get('courseId');
this.title = this.module.name;
}
/**
* Update some data based on the survey instance.
*
* @param survey Survey instance.
*/
updateData(survey: any): void {
this.title = survey.name || this.title;
}
}
| {
"content_hash": "4b35d3a18b3d170c251388395dbf7a09",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 91,
"avg_line_length": 32.354166666666664,
"alnum_prop": 0.6896329684481648,
"repo_name": "moodlehq/moodlemobile2",
"id": "f5cda2208695a6d194c11a14f9267585e9f192e8",
"size": "1553",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/addon/mod/survey/pages/index/index.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "215100"
},
{
"name": "Dockerfile",
"bytes": "619"
},
{
"name": "HTML",
"bytes": "698205"
},
{
"name": "Java",
"bytes": "1782"
},
{
"name": "JavaScript",
"bytes": "240820"
},
{
"name": "PHP",
"bytes": "31462"
},
{
"name": "Shell",
"bytes": "14375"
},
{
"name": "TypeScript",
"bytes": "8373893"
}
],
"symlink_target": ""
} |
var DEFAULT_CHANNEL = "default-channel";
var last_time = {};
var count_timeout = {};
var globalHandler = function handler(channel, notify_interval, scope, newValue, oldValue) {
last_time[channel] = last_time[channel] || 0;
count_timeout[channel] = count_timeout[channel] || null;
var now_time = new Date().getTime();
var delta_time = now_time - last_time[channel];
if (delta_time > notify_interval) {
last_time[channel] = now_time;
scope.$broadcast(channel, newValue, oldValue);
} else {
if (count_timeout[channel] == null) {
count_timeout[channel] = setTimeout(function() {
globalHandler(channel, notify_interval, scope, newValue, oldValue);
count_timeout[channel] = null;
}, notify_interval - delta_time + 10); //adding more 10s for ensuring delta_time > notify_interval
}
}
};
function bindChannelSimple(parse, scope, expression, attr, callback) {
var update_channel = parse(attr.owsChannel)(scope) || DEFAULT_CHANNEL;
console.log("RegisterChannel:" + attr.owsChannel + " -> " + update_channel, scope);
function onUpdate(event, args) {
//console.log("Channel updated");
callback();
}
scope.$on(update_channel, onUpdate);
onUpdate();
}
function bindChannel(parse, scope, expression, attr, callback) {
var update_channel = parse(attr.owsChannel)(scope) || DEFAULT_CHANNEL;
console.log("RegisterChannel:" + attr.owsChannel + " -> " + update_channel, scope);
function onUpdate(event, args) {
// console.log("Channel updated");
var new_value = parse(expression)(scope);
callback(new_value);
}
scope.$on(update_channel, onUpdate);
onUpdate();
}
function bindChannelFlex(parse, scope, expression, attr, callback) {
var update_channel = parse(attr.owsChannel)(scope) || DEFAULT_CHANNEL;
var old_value;
console.log("RegisterChannel:" + attr.owsChannel + " -> " + update_channel, scope);
function onUpdate(event, args) {
// console.log("Channel updated");
var new_value = parse(expression)(scope);
callback(new_value, old_value);
old_value = new_value;
}
scope.$on(update_channel, onUpdate);
onUpdate();
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1,
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
},
removeEventListenerFn = function(element, type, fn) {
element.removeEventListener(type, fn, false);
};
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:-]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteHasData(node) {
for (var key in jqCache[node.ng339]) {
return true;
}
return false;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = tmp || fragment.appendChild(context.createElement("div"));
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = "";
}
// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants) jqLiteRemoveData(element);
if (element.querySelectorAll) {
var descendants = element.querySelectorAll('*');
for (var i = 0, l = descendants.length; i < l; i++) {
jqLiteRemoveData(descendants[i]);
}
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
removeEventListenerFn(element, type, handle);
}
delete events[type];
}
} else {
forEach(type.split(' '), function(type) {
if (isDefined(fn)) {
var listenerFns = events[type];
arrayRemove(listenerFns || [], fn);
if (listenerFns && listenerFns.length > 0) {
return;
}
}
removeEventListenerFn(element, type, handle);
delete events[type];
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
return;
}
if (expandoStore.handle) {
if (expandoStore.events.$destroy) {
expandoStore.handle({}, '$destroy');
}
jqLiteOff(element);
}
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[key] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[key];
} else { // mass-setter: data({key1: val1, key2: val2})
extend(data, key);
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf(" " + selector + " ") > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType == NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if (isDefined(value = jqLite.data(element, names[i]))) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behaviour
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document is already loaded
if (document.readyState === 'complete') {
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
jqLite = JQLite;
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var SKIP_INDEXES = 2;
var templateArgs = arguments,
code = templateArgs[0],
message = '[' + (module ? module + ':' : '') + code + '] ',
template = templateArgs[1],
paramPrefix, i;
message += template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1),
shiftedIndex = index + SKIP_INDEXES;
if (shiftedIndex < templateArgs.length) {
return toDebugString(templateArgs[shiftedIndex]);
}
return match;
});
message += '\nhttp://errors.angularjs.org/1.4.7/' +
(module ? module + '/' : '') + code;
for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
encodeURIComponent(toDebugString(templateArgs[i]));
}
return new ErrorConstructor(message);
};
}
function serializeObject(obj) {
var seen = [];
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '...';
seen.push(val);
}
return val;
});
}
function toDebugString(obj) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (isUndefined(obj)) {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj);
}
return obj;
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType == 'function' || (objType == 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array, isolatedUid) {
if (isolatedUid) {
var uid = 0;
this.nextUid = function() {
return ++uid;
};
}
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key, this.nextUid)] = value;
},
/**
* @param key
* @returns {Object} the value for the key
*/
get: function(key) {
return this[hashKey(key, this.nextUid)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key, this.nextUid)];
delete this[key];
return value;
}
};
var $$HashMapProvider = [function() {
this.$get = [function() {
return HashMap;
}];
}];
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @description
*
* # ng (core module)
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
* <div doc-module-components="ng"></div>
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
/**
* @ngdoc function
* @name angular.lowercase
* @module ng
* @kind function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @ngdoc function
* @name angular.uppercase
* @module ng
* @kind function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
// Support: iOS 8.2 (not reproducible in simulator)
// "length" in obj used to prevent JIT error (gh-11508)
var length = "length" in Object(obj) && obj.length;
if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
}
return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
var isArray = Array.isArray;
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
function isTypedArray(value) {
return TYPED_ARRAY_REGEXP.test(toString.call(value));
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08');
};
/**
* @ngdoc function
* @name angular.isElement
* @module ng
* @kind function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str) {
var obj = {}, items = str.split(","), i;
for (i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
// Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
// Slow path for objects which do not have a method `hasOwnProperty`
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function nodeName_(element) {
return lowercase(element.nodeName || (element[0] && element[0].nodeName));
}
function includes(array, obj) {
return Array.prototype.indexOf.call(array, obj) != -1;
}
function arrayRemove(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
<example module="copyExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}]);
</script>
</file>
</example>
*/
function copy(source, destination, stackSource, stackDest) {
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
"Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (isTypedArray(destination)) {
throw ngMinErr('cpta',
"Can't copy! TypedArray destination cannot be mutated.");
}
if (!destination) {
destination = source;
if (isObject(source)) {
var index;
if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
return stackDest[index];
}
// TypedArray, Date and RegExp have specific copy functionality and must be
// pushed onto the stack before returning.
// Array and other objects create the base object and recurse to copy child
// objects. The array/object will be pushed onto the stack when recursed.
if (isArray(source)) {
return copy(source, [], stackSource, stackDest);
} else if (isTypedArray(source)) {
destination = new source.constructor(source);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else if (isFunction(source.cloneNode)) {
destination = source.cloneNode(true);
} else {
var emptyObject = Object.create(getPrototypeOf(source));
return copy(source, emptyObject, stackSource, stackDest);
}
if (stackDest) {
stackSource.push(source);
stackDest.push(destination);
}
}
} else {
if (source === destination) throw ngMinErr('cpi',
"Can't copy! Source and destination are identical.");
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
stackSource.push(source);
stackDest.push(destination);
}
var result, key;
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
destination.push(copy(source[i], null, stackSource, stackDest));
}
} else {
var h = destination.$$hashKey;
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
delete destination[key];
});
}
if (isBlankObject(source)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in source) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
} else if (source && typeof source.hasOwnProperty === 'function') {
// Slow path, which must rely on hasOwnProperty
for (key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
} else {
// Slowest path --- hasOwnProperty can't be called as a method
for (key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return equals(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
return isRegExp(o2) ? o1.toString() == o2.toString() : false;
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
isDefined(o2[key]) &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
var csp = function() {
if (!isDefined(csp.rules)) {
var ngCspElement = (document.querySelector('[ng-csp]') ||
document.querySelector('[data-ng-csp]'));
if (ngCspElement) {
var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
ngCspElement.getAttribute('data-ng-csp');
csp.rules = {
noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
};
} else {
csp.rules = {
noUnsafeEval: noUnsafeEval(),
noInlineStyle: false
};
}
}
return csp.rules;
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
};
/**
* @ngdoc directive
* @module ng
* @name ngJq
*
* @element ANY
* @param {string=} ngJq the name of the library available under `window`
* to be used for angular.element
* @description
* Use this directive to force the angular.element library. This should be
* used to force either jqLite by leaving ng-jq blank or setting the name of
* the jquery variable under window (eg. jQuery).
*
* Since angular looks for this directive when it is loaded (doesn't wait for the
* DOMContentLoaded event), it must be placed on an element that comes before the script
* which loads angular. Also, only the first instance of `ng-jq` will be used and all
* others ignored.
*
* @example
* This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-jq>
...
...
</html>
```
* @example
* This example shows how to use a jQuery based library of a different name.
* The library name must be available at the top most 'window'.
```html
<!doctype html>
<html ng-app ng-jq="jQueryLib">
...
...
</html>
```
*/
var jq = function() {
if (isDefined(jq.name_)) return jq.name_;
var el;
var i, ii = ngAttrPrefixes.length, prefix, name;
for (i = 0; i < ii; ++i) {
prefix = ngAttrPrefixes[i];
if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
name = el.getAttribute(prefix + 'jq');
break;
}
}
return (jq.name_ = name);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {Array} the inputted object or a jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): update `nodes` instead of creating a new object?
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes;
for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
if (blockNodes || nodes[i] !== node) {
if (!blockNodes) {
blockNodes = jqLite(slice.call(nodes, 0, i));
}
blockNodes.push(node);
}
}
return blockNodes || nodes;
}
/**
* @ngdoc directive
* @name owsNgRepeat
* @multiElement
*
* @description
* The `owsNgRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
* <div class="alert alert-info">
* Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
* This may be useful when, for instance, nesting owsNgRepeats.
* </div>
*
*
* # Iterating over object properties
*
* It is possible to get `owsNgRepeat` to iterate over the properties of an object using the following
* syntax:
*
* ```js
* <div ng-repeat="(key, value) in myObj"> ... </div>
* ```
*
* You need to be aware that the JavaScript specification does not define the order of keys
* returned for an object. (To mitigate this in Angular 1.3 the `owsNgRepeat` directive
* used to sort the keys alphabetically.)
*
* Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
* when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
* keys in the order in which they were defined, although there are exceptions when keys are deleted
* and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
*
* If this is not desired, the recommended workaround is to convert your object into an array
* that is sorted into the order that you prefer before providing it to `owsNgRepeat`. You could
* do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
* or implement a `$watch` on the object yourself.
*
*
* # Tracking and Duplicates
*
* When the contents of the collection change, `owsNgRepeat` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* By default, `owsNgRepeat` does not allow duplicate items in arrays. This is because when
* there are duplicates, it is not possible to maintain a one-to-one mapping between collection
* items and DOM elements.
*
* If you do need to repeat duplicate items, you can substitute the default tracking behavior
* with your own using the `track by` expression.
*
* For example, you may track items by the index of each item in the collection, using the
* special scope property `$index`:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by $index">
* {{n}}
* </div>
* ```
*
* You may use arbitrary expressions in `track by`, including references to custom functions
* on the scope:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
* {{n}}
* </div>
* ```
*
* If you are working with objects that have an identifier property, you can track
* by the identifier instead of the whole object. Should you reload your data later, `owsNgRepeat`
* will not have to rebuild the DOM elements for items it has already rendered, even if the
* JavaScript objects in the collection have been substituted for new ones:
* ```html
* <div ng-repeat="model in collection track by model.id">
* {{model.name}}
* </div>
* ```
*
* When no `track by` expression is provided, it is equivalent to tracking by the built-in
* `$id` function, which tracks items by their identity:
* ```html
* <div ng-repeat="obj in collection track by $id(obj)">
* {{obj.prop}}
* </div>
* ```
*
* <div class="alert alert-warning">
* **Note:** `track by` must always be the last expression:
* </div>
* ```
* <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
* {{model.name}}
* </div>
* ```
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, owsNgRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* ```html
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* ```
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
* ```html
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* ```
*
* The custom start and end points for owsNgRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* **.enter** - when a new item is added to the list or when an item is revealed after a filter
*
* **.leave** - when an item is removed from the list or when an item is filtered out
*
* **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} owsNgRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
* which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
* is specified, ng-repeat associates elements by identity. It is an error to have
* more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.)
*
* Note that the tracking expression must come last, after any filters, and the alias expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way in the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
* intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
* when a filter is active on the repeater, but the filtered result set is empty.
*
* For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
* the items have been processed through the filter.
*
* Please note that `as [variable name] is not an operator but rather a part of owsNgRepeat micro-syntax so it can be used only at the end
* (and not as operator, inside an expression).
*
* For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
*
* @example
* This example initializes the scope to a list of names and
* then uses `owsNgRepeat` to display every person:
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0 10px;
}
.animate-repeat {
line-height:40px;
list-style:none;
box-sizing:border-box;
}
.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
transition:all linear 0.5s;
}
.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
opacity:0;
max-height:0;
}
.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
opacity:1;
max-height:40px;
}
</file>
<file name="protractor.js" type="protractor">
var friends = element.all(by.repeater('friend in friends'));
it('should render initial data set', function() {
expect(friends.count()).toBe(10);
expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
expect(element(by.binding('friends.length')).getText())
.toMatch("I have 10 friends. They are:");
});
it('should update repeater when filter predicate changes', function() {
expect(friends.count()).toBe(10);
element(by.model('q')).sendKeys('ma');
expect(friends.count()).toBe(2);
expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
});
</file>
</example>
*/
var owsNgRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var owsNgRepeatMinErr = minErr('owsNgRepeat');
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
// TODO(perf): generate setters to shave off ~40ms or 1-1.5%
scope[valueIdentifier] = value;
if (keyIdentifier) scope[keyIdentifier] = key;
scope.$index = index;
scope.$first = (index === 0);
scope.$last = (index === (arrayLength - 1));
scope.$middle = !(scope.$first || scope.$last);
// jshint bitwise: false
scope.$odd = !(scope.$even = (index&1) === 0);
// jshint bitwise: true
};
var getBlockStart = function(block) {
return block.clone[0];
};
var getBlockEnd = function(block) {
return block.clone[block.clone.length - 1];
};
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function owsNgRepeatCompile($element, $attr) {
var expression = $attr.owsNgRepeat;
var owsNgRepeatEndComment = document.createComment(' end owsNgRepeat: ' + expression + ' ');
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw owsNgRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1];
var rhs = match[2];
var aliasAs = match[3];
var trackByExp = match[4];
match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if (!match) {
throw owsNgRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
throw owsNgRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
aliasAs);
}
var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
var hashFnLocals = {$id: hashKey};
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
return function owsNgRepeatLink($scope, $element, $attr, ctrl, $transclude) {
if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
}
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
//
// We are using no-proto object so that we don't need to guard against inherited props via
// hasOwnProperty.
var lastBlockMap = createMap();
//watch props
bindChannelSimple($parse, $scope, '', $attr, function owsNgRepeatAction() {
var collection = $parse(rhs)($scope);
var index, length,
previousNode = $element[0], // node that cloned nodes should be inserted after
// initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = createMap(),
collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder,
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, in enumeration order, unsorted
collectionKeys = [];
for (var itemKey in collection) {
if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
collectionKeys.push(itemKey);
}
}
}
collectionLength = collectionKeys.length;
nextBlockOrder = new Array(collectionLength);
// locate existing items
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
if (lastBlockMap[trackById]) {
// found previously seen block
block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap[trackById]) {
// if collision detected. restore lastBlockMap and throw an error
forEach(nextBlockOrder, function(block) {
if (block && block.scope) lastBlockMap[block.id] = block;
});
throw owsNgRepeatMinErr('dupes',
"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
expression, trackById, value);
} else {
// new never before seen block
nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
nextBlockMap[trackById] = true;
}
}
// remove leftover items
for (var blockKey in lastBlockMap) {
block = lastBlockMap[blockKey];
elementsToRemove = getBlockNodes(block.clone);
$animate.leave(elementsToRemove);
if (elementsToRemove[0].parentNode) {
// if the element was not removed yet because of pending animation, mark it as deleted
// so that we can ignore it later
for (index = 0, length = elementsToRemove.length; index < length; index++) {
elementsToRemove[index][NG_REMOVED] = true;
}
}
block.scope.$destroy();
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
nextNode = previousNode;
// skip nodes that are already pending removal via leave animation
do {
nextNode = nextNode.nextSibling;
} while (nextNode && nextNode[NG_REMOVED]);
if (getBlockStart(block) != nextNode) {
// existing item which got moved
$animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
}
previousNode = getBlockEnd(block);
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
} else {
// new item which we don't know about
$transclude(function owsNgRepeatTransclude(clone, scope) {
block.scope = scope;
// http://jsperf.com/clone-vs-createcomment
var endNode = owsNgRepeatEndComment.cloneNode(false);
clone[clone.length++] = endNode;
// TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block.clone = clone;
nextBlockMap[block.id] = block;
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
var owsNgRepeatOnlyPushDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var owsNgRepeatMinErr = minErr('owsNgRepeatOnlyPush');
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
// TODO(perf): generate setters to shave off ~40ms or 1-1.5%
scope[valueIdentifier] = value;
if (keyIdentifier) scope[keyIdentifier] = key;
scope.$index = index;
scope.$first = (index === 0);
scope.$last = (index === (arrayLength - 1));
scope.$middle = !(scope.$first || scope.$last);
// jshint bitwise: false
scope.$odd = !(scope.$even = (index&1) === 0);
// jshint bitwise: true
};
var getBlockStart = function(block) {
return block.clone[0];
};
var getBlockEnd = function(block) {
return block.clone[block.clone.length - 1];
};
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function owsNgRepeatCompile($element, $attr) {
var expression = $attr.owsNgRepeatOnlyPush;
var owsNgRepeatEndComment = document.createComment(' end owsNgRepeat: ' + expression + ' ');
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw owsNgRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1];
var rhs = match[2];
var aliasAs = match[3];
var trackByExp = match[4];
match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if (!match) {
throw owsNgRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
throw owsNgRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
aliasAs);
}
var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
var hashFnLocals = {$id: hashKey};
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
return function owsNgRepeatLink($scope, $element, $attr, ctrl, $transclude) {
if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
}
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
//
// We are using no-proto object so that we don't need to guard against inherited props via
// hasOwnProperty.
var lastBlockMap = createMap();
var previousNode = $element[0];
var preLength = 0;
//watch props
bindChannelSimple($parse, $scope, '', $attr, function owsNgRepeatAction() {
var collection = $parse(rhs)($scope);
var index, length, // node that cloned nodes should be inserted after
// initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = createMap(),
collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
console.log($element);
//only support array
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
collectionLength = collectionKeys.length;
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = preLength; index < collectionLength; index++) {
value = collection[index];
// new item which we don't know about
$transclude(function owsNgRepeatTransclude(clone, scope) {
// http://jsperf.com/clone-vs-createcomment
var endNode = owsNgRepeatEndComment.cloneNode(false);
clone[clone.length++] = endNode;
// TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
updateScope(scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
preLength = collectionLength;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBind
* @restrict AC
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var nameInput = element(by.model('name'));
expect(element(by.binding('name')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('name')).getText()).toBe('world');
});
</file>
</example>
*/
var owsNgBindDirective = ['$compile', '$rootScope', '$parse',
function($compile, $rootScope, $parse) {
return {
restrict: 'AC',
compile: function ngBindCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.owsNgBind);
element = element[0];
bindChannel($parse, scope, attr.owsNgBind, attr, function ngBindWatchAction(value) {
element.textContent = isUndefined(value) ? '' : value;
});
};
}
};
}
];
function valueFn(value) {return function() {return value;};}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
};
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name ngBindHtml
*
* @description
* Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
* the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
* To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
* ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
* in your module's dependencies, you need to include "angular-sanitize.js" in your application.
*
* You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
<example module="bindHtmlExample" deps="angular-sanitize.js">
<file name="index.html">
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</file>
<file name="script.js">
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind-html', function() {
expect(element(by.binding('myHTML')).getText()).toBe(
'I am an HTMLstring with links! and other stuff');
});
</file>
</example>
*/
var owsNgBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function owsNgBindHtmlCompile(tElement, tAttrs) {
var owsNgBindHtmlGetter = $parse(tAttrs.owsNgBindHtml);
var owsNgBindHtmlWatch = $parse(tAttrs.owsNgBindHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function owsNgBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.owsNgBindHtml);
bindChannelSimple($parse, scope, owsNgBindHtmlWatch, attr, function ngBindWatchAction(value) {
// we re-evaluate the expr because we want a TrustedValueHolderType
// for $sce, not a string
element.html($sce.getTrustedHtml(owsNgBindHtmlGetter(scope)) || '');
});
};
}
};
}];
function classDirective(name, selector) {
name = 'owsNgClass' + name;
return ['$animate', '$parse', function($animate, $parse) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal;
bindChannel($parse, scope, attr[name], attr, owsNgClassWatchAction);
attr.$observe('class', function(value) {
owsNgClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'owsNgClass') {
scope.$watch('$index', function($index, old$index) {
// jshint bitwise: false
var mod = $index & 1;
if (mod !== (old$index & 1)) {
var classes = arrayClasses(scope.$eval(attr[name]));
mod === selector ?
addClasses(classes) :
removeClasses(classes);
}
});
}
function addClasses(classes) {
var newClasses = digestClassCounts(classes, 1);
attr.$addClass(newClasses);
}
function removeClasses(classes) {
var newClasses = digestClassCounts(classes, -1);
attr.$removeClass(newClasses);
}
function digestClassCounts(classes, count) {
// Use createMap() to prevent class assumptions involving property
// names in Object.prototype
var classCounts = element.data('$classCounts') || createMap();
var classesToUpdate = [];
forEach(classes, function(className) {
if (count > 0 || classCounts[className]) {
classCounts[className] = (classCounts[className] || 0) + count;
if (classCounts[className] === +(count > 0)) {
classesToUpdate.push(className);
}
}
});
element.data('$classCounts', classCounts);
return classesToUpdate.join(' ');
}
function updateClasses(oldClasses, newClasses) {
var toAdd = arrayDifference(newClasses, oldClasses);
var toRemove = arrayDifference(oldClasses, newClasses);
toAdd = digestClassCounts(toAdd, 1);
toRemove = digestClassCounts(toRemove, -1);
if (toAdd && toAdd.length) {
$animate.addClass(element, toAdd);
}
if (toRemove && toRemove.length) {
$animate.removeClass(element, toRemove);
}
}
function owsNgClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
var newClasses = arrayClasses(newVal || []);
if (!oldVal) {
addClasses(newClasses);
} else if (!equals(newVal,oldVal)) {
var oldClasses = arrayClasses(oldVal);
updateClasses(oldClasses, newClasses);
}
}
oldVal = shallowCopy(newVal);
}
}
};
function arrayDifference(tokens1, tokens2) {
var values = [];
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
}
function arrayClasses(classVal) {
var classes = [];
if (isArray(classVal)) {
forEach(classVal, function(v) {
classes = classes.concat(arrayClasses(v));
});
return classes;
} else if (isString(classVal)) {
return classVal.split(' ');
} else if (isObject(classVal)) {
forEach(classVal, function(v, k) {
if (v) {
classes = classes.concat(k.split(' '));
}
});
return classes;
}
return classVal;
}
}];
}
/**
* @ngdoc directive
* @name owsNgClass
* @restrict AC
*
* @description
* The `owsNgClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
* an expression that represents all classes to be added.
*
* The directive operates in three different ways, depending on which of three types the expression
* evaluates to:
*
* 1. If the expression evaluates to a string, the string should be one or more space-delimited class
* names.
*
* 2. If the expression evaluates to an object, then for each key-value pair of the
* object with a truthy value the corresponding key is used as a class name.
*
* 3. If the expression evaluates to an array, each element of the array should either be a string as in
* type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
* to give you more control over what CSS classes appear. See the code below for an example of this.
*
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then are the
* new classes added.
*
* @animations
* **add** - happens just before the class is applied to the elements
*
* **remove** - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} owsNgClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demonstrates basic bindings via owsNgClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
<label>
<input type="checkbox" ng-model="deleted">
deleted (apply "strike" class)
</label><br>
<label>
<input type="checkbox" ng-model="important">
important (apply "bold" class)
</label><br>
<label>
<input type="checkbox" ng-model="error">
error (apply "has-error" class)
</label>
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style"
placeholder="Type: bold strike red" aria-label="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
<input ng-model="style2"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
<input ng-model="style3"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
<hr>
<p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
<input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
<label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
.has-error {
color: red;
background-color: yellow;
}
.orange {
color: orange;
}
</file>
<file name="protractor.js" type="protractor">
var ps = element.all(by.css('p'));
it('should let you toggle the class', function() {
expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
element(by.model('important')).click();
expect(ps.first().getAttribute('class')).toMatch(/bold/);
element(by.model('error')).click();
expect(ps.first().getAttribute('class')).toMatch(/has-error/);
});
it('should let you toggle string example', function() {
expect(ps.get(1).getAttribute('class')).toBe('');
element(by.model('style')).clear();
element(by.model('style')).sendKeys('red');
expect(ps.get(1).getAttribute('class')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(ps.get(2).getAttribute('class')).toBe('');
element(by.model('style1')).sendKeys('bold');
element(by.model('style2')).sendKeys('strike');
element(by.model('style3')).sendKeys('red');
expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
});
it('array with map example should have 2 classes', function() {
expect(ps.last().getAttribute('class')).toBe('');
element(by.model('style4')).sendKeys('bold');
element(by.model('warning')).click();
expect(ps.last().getAttribute('class')).toBe('bold orange');
});
</file>
</example>
## Animations
The example below demonstrates how to perform animations using owsNgClass.
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.base-class {
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.base-class.my-class {
color: red;
font-size:3em;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class', function() {
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
element(by.id('setbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).
toMatch(/my-class/);
element(by.id('clearbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
});
</file>
</example>
## owsNgClass and pre-existing CSS3 Transitions/Animations
The owsNgClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
to view the step by step details of {@link $animate#addClass $animate.addClass} and
{@link $animate#removeClass $animate.removeClass}.
*/
var owsNgClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name owsNgClassOdd
* @restrict AC
*
* @description
* The `owsNgClassOdd` and `owsNgClassEven` directives work exactly as
* {@link ng.directive:owsNgClass owsNgClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} owsNgClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var owsNgClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name owsNgClassEven
* @restrict AC
*
* @description
* The `owsNgClassOdd` and `owsNgClassEven` directives work exactly as
* {@link ng.directive:owsNgClass owsNgClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} owsNgClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var owsNgClassEvenDirective = classDirective('Even', 1);
var NG_HIDE_CLASS = 'ng-hide';
var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
/**
* @ngdoc directive
* @name owsNgShow
* @multiElement
*
* @description
* The `owsNgShow` directive shows or hides the given HTML element based on the expression
* provided to the `owsNgShow` attribute. The element is shown or hidden by removing or adding
* the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* ```
*
* When the `owsNgShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with owsNgShow/owsNgHide then this can be achieved by restating the styles for the `.ng-hide`
* class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
* with extra animation classes that can be added.
*
* ```css
* .ng-hide:not(.ng-hide-animate) {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `owsNgShow`
*
* Animations in owsNgShow/owsNgHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
* you must also include the !important flag to override the display property
* so that you can perform an animation when the element is hidden during the time of the animation.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* /* this is required as of 1.3x to properly
* apply all styling in a show/hide animation */
* transition: 0s linear all;
* }
*
* .my-element.ng-hide-add-active,
* .my-element.ng-hide-remove-active {
* /* the transition is defined in the active class */
* transition: 1s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* addClass: `.ng-hide` - happens after the `owsNgShow` expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: `.ng-hide` - happens after the `owsNgShow` expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} owsNgShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle owsNgHide"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-show {
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-show.ng-hide-add, .animate-show.ng-hide-remove {
transition: all linear 0.5s;
}
.animate-show.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var owsNgShowDirective = ['$animate', '$parse', function($animate, $parse) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
bindChannel($parse, scope, attr.owsNgShow, attr, function owsNgShowWatchAction(value) {
// we're adding a temporary, animation-specific class for ng-hide since this way
// we can control when the element is actually displayed on screen without having
// to have a global/greedy CSS selector that breaks when other animations are run.
// Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
$animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name owsNgHide
* @multiElement
*
* @description
* The `owsNgHide` directive shows or hides the given HTML element based on the expression
* provided to the `owsNgHide` attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue" class="ng-hide"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue"></div>
* ```
*
* When the `owsNgHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with owsNgShow/owsNgHide then this can be achieved by restating the styles for the `.ng-hide`
* class in CSS:
*
* ```css
* .ng-hide {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `owsNgHide`
*
* Animations in owsNgShow/owsNgHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
* CSS class is added and removed for you instead of your own CSS class.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition: 0.5s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* removeClass: `.ng-hide` - happens after the `owsNgHide` expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: `.ng-hide` - happens after the `owsNgHide` expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} owsNgHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle owsNgShow"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-hide {
transition: all linear 0.5s;
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-hide.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var owsNgHideDirective = ['$animate', '$parse', function($animate, $parse) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
bindChannel($parse, scope, attr.owsNgHide, attr, function owsNgHideWatchAction(value) {
// The comment inside of the owsNgShowDirective explains why we add and
// remove a temporary class for the show/hide animation
$animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name owsNgStyle
* @restrict AC
*
* @description
* The `owsNgStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} owsNgStyle
*
* {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* Since some CSS style names are not valid keys for an object, they must be quoted.
* See the 'background-color' style in the example below.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="protractor.js" type="protractor">
var colorSpan = element(by.css('span'));
it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
element(by.css('input[value=\'set color\']')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
element(by.css('input[value=clear]')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
});
</file>
</example>
*/
var owsNgStyleDirective = ['$animate', '$parse', function($animate, $parse) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
bindChannelFlex($parse, scope, attr.owsNgStyle, attr, function owsNgStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
});
}
};
}];
/**
* @ngdoc directive
* @name owsNgSwitch
* @restrict EA
*
* @description
* The `owsNgSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within `owsNgSwitch` but without `owsNgSwitchWhen` or `owsNgSwitchDefault` directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), `owsNgSwitch` simply chooses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`on="..."` attribute**
* (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform owsNgSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* <div class="alert alert-info">
* Be aware that the attribute values to match against cannot be expressions. They are interpreted
* as literal string values to match against.
* For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
* value of the expression `$scope.someVal`.
* </div>
* @animations
* enter - happens after the owsNgSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the owsNgSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
*
* ```
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
* ```
*
*
* @scope
* @priority 1200
* @param {*} owsNgSwitch|on expression to match against <code>ng-switch-when</code>.
* On child elements add:
*
* * `owsNgSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `owsNgSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example module="switchExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="selection" ng-options="item for item in items">
</select>
<code>selection={{selection}}</code>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
angular.module('switchExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}]);
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top:-50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top:0;
}
</file>
<file name="protractor.js" type="protractor">
var switchElem = element(by.css('[ng-switch]'));
var select = element(by.model('selection'));
it('should start in settings', function() {
expect(switchElem.getText()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select.all(by.css('option')).get(1).click();
expect(switchElem.getText()).toMatch(/Home Span/);
});
it('should select default', function() {
select.all(by.css('option')).get(2).click();
expect(switchElem.getText()).toMatch(/default/);
});
</file>
</example>
*/
var owsNgSwitchDirective = ['$animate', '$parse', function($animate, $parse) {
return {
require: 'owsNgSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function owsNgSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, owsNgSwitchController) {
var watchExpr = attr.owsNgSwitch || attr.on,
selectedTranscludes = [],
selectedElements = [],
previousLeaveAnimations = [],
selectedScopes = [];
var spliceFactory = function(array, index) {
return function() { array.splice(index, 1); };
};
bindChannel($parse, scope, watchExpr, attr, function owsNgSwitchWatchAction(value) {
var i, ii;
for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
$animate.cancel(previousLeaveAnimations[i]);
}
previousLeaveAnimations.length = 0;
for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
var selected = getBlockNodes(selectedElements[i].clone);
selectedScopes[i].$destroy();
var promise = previousLeaveAnimations[i] = $animate.leave(selected);
promise.then(spliceFactory(previousLeaveAnimations, i));
}
selectedElements.length = 0;
selectedScopes.length = 0;
if ((selectedTranscludes = owsNgSwitchController.cases['!' + value] || owsNgSwitchController.cases['?'])) {
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
var anchor = selectedTransclude.element;
caseElement[caseElement.length++] = document.createComment(' end owsNgSwitchWhen: ');
var block = { clone: caseElement };
selectedElements.push(block);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
};
}];
var owsNgSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^owsNgSwitch',
multiElement: true,
link: function(scope, element, attrs, ctrl, $transclude) {
ctrl.cases['!' + attrs.owsNgSwitchWhen] = (ctrl.cases['!' + attrs.owsNgSwitchWhen] || []);
ctrl.cases['!' + attrs.owsNgSwitchWhen].push({ transclude: $transclude, element: element });
}
});
var owsNgSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^owsNgSwitch',
multiElement: true,
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
});
/**
* @ngdoc directive
* @name owsNgIf
* @restrict A
* @multiElement
*
* @description
* The `owsNgIf` directive removes or recreates a portion of the DOM tree based on an
* {expression}. If the expression assigned to `owsNgIf` evaluates to a false
* value then the element is removed from the DOM, otherwise a clone of the
* element is reinserted into the DOM.
*
* `owsNgIf` differs from `ngShow` and `ngHide` in that `owsNgIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that when an element is removed using `owsNgIf` its scope is destroyed and a new scope
* is created when the element is restored. The scope created within `owsNgIf` inherits from
* its parent scope using
* [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
* An important implication of this is if `ngModel` is used within `owsNgIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `owsNgIf` recreates elements using their compiled state. An example of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `owsNgIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
* and `leave` effects.
*
* @animations
* enter - happens just after the `owsNgIf` contents change and a new DOM element is created and injected into the `owsNgIf` container
* leave - happens just before the `owsNgIf` contents are removed from the DOM
*
* @element ANY
* @scope
* @priority 600
* @param {expression} owsNgIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree. If it is truthy a copy of the compiled
* element is added to the DOM tree.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-leave,
.animate-if.ng-enter.ng-enter-active {
opacity:1;
}
</file>
</example>
*/
var owsNgIfDirective = ['$animate', '$parse', function($animate, $parse) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
bindChannel($parse, $scope, $attr.owsNgIf, $attr, function owsNgIfWatchAction(value) {
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end owsNgIf: ' + $attr.owsNgIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
});
}
};
}];
var owsNotifier = ['$rootScope', '$timeout', '$parse', function($rootScope, $timeout, $parse) {
var Mode = {
SHALLOW: 'shallow',
DEEP: 'deep',
COLLECtION: 'collection'
};
var DEFAULT_MODE = Mode.SHALLOW;
return {
restrict: 'AC',
link: function($scope, $element, $attr, ctrl, $transclude) {
var update_channel = $parse($attr.owsChannel)($scope);
var broadcast_interval = $parse($attr.owsBroadcastInterval)($scope) || 500;
console.log("RegisterBroadcaster:" + $attr.owsChannel + " -> " + update_channel + " with " + broadcast_interval + " ms");
$scope.$watch($attr.owsNotifier, function ngIfWatchAction(value) {
window.OwsFbUpdate(update_channel, broadcast_interval);//default 500ms
});
}
};
}];
var owsBroadcaster = ['$rootScope', '$timeout', '$parse', function($rootScope, $timeout, $parse) {
var Mode = {
SHALLOW: 'shallow',
DEEP: 'deep',
COLLECtION: 'collection'
};
var DEFAULT_MODE = Mode.SHALLOW;
return {
restrict: 'AC',
link: function($scope, $element, $attr, ctrl, $transclude) {
var update_channel = $parse($attr.owsChannel)($scope) || null;
var monitor_mode = $parse($attr.owsMode)($scope) || DEFAULT_MODE;
var broadcast_interval = $parse($attr.owsBroadcastInterval)($scope) || 500;
//check condition
if(update_channel == null){
throw Error('ows-broadcaster: missing ows-channel value');
}
console.log("RegisterBroadcaster:" + $attr.owsChannel + " -> " + update_channel + ":" + monitor_mode + " with " + broadcast_interval + " ms");
var handler = function handler(newValue, oldValue, scope) {
globalHandler(update_channel, broadcast_interval, $rootScope, newValue, oldValue);
};
switch (monitor_mode) {
case Mode.SHALLOW:
case Mode.DEEP:
$scope.$watch($attr.owsBroadcaster, handler, monitor_mode === Mode.DEEP);
break;
case Mode.COLLECTION:
scope.$watchCollection($attr.owsBroadcaster, handler);
break;
default:
throw Error('fast-bind-notifier: Invalid ows-mode "' + monitor_mode + '"');
}
}
};
}];
var owsNotifier = ['$rootScope', '$timeout', '$parse', function($rootScope, $timeout, $parse) {
var Mode = {
SHALLOW: 'shallow',
DEEP: 'deep',
COLLECtION: 'collection'
};
var DEFAULT_MODE = Mode.SHALLOW;
return {
restrict: 'AC',
link: function($scope, $element, $attr, ctrl, $transclude) {
var update_channel = $parse($attr.owsChannel)($scope) || DEFAULT_CHANNEL;
var monitor_mode = $parse($attr.owsMode)($scope) || DEFAULT_MODE;
var notify_interval = $parse($attr.owsNotifyInterval)($scope) || 500;
//check condition
if(update_channel == null){
throw Error('ows-broadcaster: missing ows-channel value');
}
console.log("RegisterBroadcaster:" + update_channel + ":" + monitor_mode);
var last_time = 0;
var count_timeout = null;
var handler = function handler(newValue, oldValue, scope) {
var now_time = new Date().getTime();
var delta_time = now_time - last_time;
if(delta_time > notify_interval){
last_time = now_time;
scope.$broadcast(update_channel, newValue, oldValue);
}else{
if(count_timeout == null){
count_timeout = $timeout(function(){
handler(newValue, oldValue, scope);
count_timeout = null;
}, notify_interval - delta_time + 10); //adding more 10s for ensuring delta_time > notify_interval
}
}
};
switch (monitor_mode) {
case Mode.SHALLOW:
case Mode.DEEP:
$scope.$watch($attr.owsNotifier, handler, monitor_mode === Mode.DEEP);
break;
case Mode.COLLECTION:
scope.$watchCollection($attr.owsNotifier, handler);
break;
default:
throw Error('fast-bind-notifier: Invalid ows-mode "' + monitor_mode + '"');
}
}
};
}];
var owsFastBindGlobalInit = ['$rootScope', '$timeout', function($rootScope, $timeout) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
window.OwsFbUpdate = function(channel, interval){
globalHandler(channel, interval, $rootScope, 1, 1);
}
}
};
}];
/* global myModule */
myModule
.directive('owsFastBindGlobalInit', owsFastBindGlobalInit)
.directive('owsNotifier', owsNotifier)
.directive('owsBroadcaster', owsBroadcaster)
.directive('owsNgBind', owsNgBindDirective)
.directive('owsNgBindHtml', owsNgBindHtmlDirective)
.directive('owsNgClass', owsNgClassDirective)
.directive('owsNgClassOdd', owsNgClassOddDirective)
.directive('owsNgClassEven', owsNgClassEvenDirective)
.directive('owsNgShow', owsNgShowDirective)
.directive('owsNgHide', owsNgHideDirective)
.directive('owsNgStyle', owsNgStyleDirective)
.directive('owsNgSwitch', owsNgSwitchDirective)
.directive('owsNgSwitchWhen', owsNgSwitchWhenDirective)
.directive('owsNgSwitchDefault', owsNgSwitchDefaultDirective)
.directive('owsNgIf', owsNgIfDirective)
.directive('owsNgRepeat', owsNgRepeatDirective)
.directive('owsNgRepeatOnlyPush', owsNgRepeatOnlyPushDirective)
| {
"content_hash": "614dc6dcc5a2c206d1b33bb2ed3dc25e",
"timestamp": "",
"source": "github",
"line_count": 3725,
"max_line_length": 175,
"avg_line_length": 34.98604026845638,
"alnum_prop": 0.6227373525778258,
"repo_name": "spidercpsf/ows-fast-bind",
"id": "dff8a4c6a3893fde1f500525176e99806a81c5d3",
"size": "130331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/directive.directive.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "374"
},
{
"name": "HTML",
"bytes": "3662"
},
{
"name": "JavaScript",
"bytes": "275849"
}
],
"symlink_target": ""
} |
#ifndef _I386_PAGE_H
#define _I386_PAGE_H
/* PAGE_SHIFT determines the page size */
#define PAGE_SHIFT 12
#define PAGE_SIZE (1UL << PAGE_SHIFT)
#define PAGE_MASK (~(PAGE_SIZE-1))
#define LARGE_PAGE_MASK (~(LARGE_PAGE_SIZE-1))
#define LARGE_PAGE_SIZE (1UL << PMD_SHIFT)
#ifdef __KERNEL__
#ifndef __ASSEMBLY__
#ifdef CONFIG_X86_USE_3DNOW
#include <asm/mmx.h>
#define clear_page(page) mmx_clear_page((void *)(page))
#define copy_page(to,from) mmx_copy_page(to,from)
#else
/*
* On older X86 processors it's not a win to use MMX here it seems.
* Maybe the K6-III ?
*/
#define clear_page(page) memset((void *)(page), 0, PAGE_SIZE)
#define copy_page(to,from) memcpy((void *)(to), (void *)(from), PAGE_SIZE)
#endif
#define clear_user_page(page, vaddr, pg) clear_page(page)
#define copy_user_page(to, from, vaddr, pg) copy_page(to, from)
#define alloc_zeroed_user_highpage(vma, vaddr) alloc_page_vma(GFP_HIGHUSER | __GFP_ZERO, vma, vaddr)
#define __HAVE_ARCH_ALLOC_ZEROED_USER_HIGHPAGE
/*
* These are used to make use of C type-checking..
*/
extern int nx_enabled;
#ifdef CONFIG_X86_PAE
extern unsigned long long __supported_pte_mask;
typedef struct { unsigned long pte_low, pte_high; } pte_t;
typedef struct { unsigned long long pmd; } pmd_t;
typedef struct { unsigned long long pgd; } pgd_t;
typedef struct { unsigned long long pgprot; } pgprot_t;
#define pmd_val(x) ((x).pmd)
#define pte_val(x) ((x).pte_low | ((unsigned long long)(x).pte_high << 32))
#define __pmd(x) ((pmd_t) { (x) } )
#define HPAGE_SHIFT 21
#include <asm-generic/pgtable-nopud.h>
#else
typedef struct { unsigned long pte_low; } pte_t;
typedef struct { unsigned long pgd; } pgd_t;
typedef struct { unsigned long pgprot; } pgprot_t;
#define boot_pte_t pte_t /* or would you rather have a typedef */
#define pte_val(x) ((x).pte_low)
#define HPAGE_SHIFT 22
#include <asm-generic/pgtable-nopmd.h>
#endif
#define PTE_MASK PAGE_MASK
#ifdef CONFIG_HUGETLB_PAGE
#define HPAGE_SIZE ((1UL) << HPAGE_SHIFT)
#define HPAGE_MASK (~(HPAGE_SIZE - 1))
#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
#define HAVE_ARCH_HUGETLB_UNMAPPED_AREA
#endif
#define pgd_val(x) ((x).pgd)
#define pgprot_val(x) ((x).pgprot)
#define __pte(x) ((pte_t) { (x) } )
#define __pgd(x) ((pgd_t) { (x) } )
#define __pgprot(x) ((pgprot_t) { (x) } )
#endif /* !__ASSEMBLY__ */
/* to align the pointer to the (next) page boundary */
#define PAGE_ALIGN(addr) (((addr)+PAGE_SIZE-1)&PAGE_MASK)
/*
* This handles the memory map.. We could make this a config
* option, but too many people screw it up, and too few need
* it.
*
* A __PAGE_OFFSET of 0xC0000000 means that the kernel has
* a virtual address space of one gigabyte, which limits the
* amount of physical memory you can use to about 950MB.
*
* If you want more physical memory than this then see the CONFIG_HIGHMEM4G
* and CONFIG_HIGHMEM64G options in the kernel configuration.
*/
#ifndef __ASSEMBLY__
struct vm_area_struct;
/*
* This much address space is reserved for vmalloc() and iomap()
* as well as fixmap mappings.
*/
extern unsigned int __VMALLOC_RESERVE;
extern int sysctl_legacy_va_layout;
extern int page_is_ram(unsigned long pagenr);
#endif /* __ASSEMBLY__ */
#ifdef __ASSEMBLY__
#define __PAGE_OFFSET CONFIG_PAGE_OFFSET
#else
#define __PAGE_OFFSET ((unsigned long)CONFIG_PAGE_OFFSET)
#endif
#define PAGE_OFFSET ((unsigned long)__PAGE_OFFSET)
#define VMALLOC_RESERVE ((unsigned long)__VMALLOC_RESERVE)
#define MAXMEM (-__PAGE_OFFSET-__VMALLOC_RESERVE)
#define __pa(x) ((unsigned long)(x)-PAGE_OFFSET)
/* __pa_symbol should be used for C visible symbols.
This seems to be the official gcc blessed way to do such arithmetic. */
#define __pa_symbol(x) __pa(RELOC_HIDE((unsigned long)(x),0))
#define __va(x) ((void *)((unsigned long)(x)+PAGE_OFFSET))
#define pfn_to_kaddr(pfn) __va((pfn) << PAGE_SHIFT)
#ifdef CONFIG_FLATMEM
#define pfn_valid(pfn) ((pfn) < max_mapnr)
#endif /* CONFIG_FLATMEM */
#define virt_to_page(kaddr) pfn_to_page(__pa(kaddr) >> PAGE_SHIFT)
#define virt_addr_valid(kaddr) pfn_valid(__pa(kaddr) >> PAGE_SHIFT)
#define VM_DATA_DEFAULT_FLAGS \
(VM_READ | VM_WRITE | \
((current->personality & READ_IMPLIES_EXEC) ? VM_EXEC : 0 ) | \
VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC)
#include <asm-generic/memory_model.h>
#include <asm-generic/page.h>
#ifndef CONFIG_COMPAT_VDSO
#define __HAVE_ARCH_GATE_AREA 1
#endif
#endif /* __KERNEL__ */
#endif /* _I386_PAGE_H */
| {
"content_hash": "aceea41d80d56c7767c3303669d781cf",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 100,
"avg_line_length": 29.483443708609272,
"alnum_prop": 0.6850853548966757,
"repo_name": "impedimentToProgress/UCI-BlueChip",
"id": "7b19f454761de838acb513e2f14f00215581d31a",
"size": "4452",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "snapgear_linux/linux-2.6.21.1/include/asm-i386/page.h",
"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"
}
],
"symlink_target": ""
} |
package org.ovirt.engine.core.bll.validator.gluster;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.gluster.GlusterFeatureSupported;
import org.ovirt.engine.core.compat.Version;
public class GlusterVolumeValidator {
public ValidationResult isForceCreateVolumeAllowed(Version clusterVersion, boolean isForce) {
if (isForce && !GlusterFeatureSupported.glusterForceCreateVolumeSupported(clusterVersion)) {
return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_ADD_BRICK_FORCE_NOT_SUPPORTED);
}
return ValidationResult.VALID;
}
}
| {
"content_hash": "88e0961ea03fd842a43b7805668b4567",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 120,
"avg_line_length": 43.4375,
"alnum_prop": 0.7899280575539568,
"repo_name": "halober/ovirt-engine",
"id": "5f9ed17a8aa903fd8906764de10d66de81e024f2",
"size": "695",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/validator/gluster/GlusterVolumeValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "251848"
},
{
"name": "Java",
"bytes": "26541598"
},
{
"name": "JavaScript",
"bytes": "890"
},
{
"name": "Python",
"bytes": "698283"
},
{
"name": "Shell",
"bytes": "105362"
},
{
"name": "XSLT",
"bytes": "54683"
}
],
"symlink_target": ""
} |
package com.amebame.triton.config;
import java.util.HashMap;
import java.util.Map;
/**
* Memcached configuration
*/
public class TritonMemcachedConfiguration {
private Map<String, TritonMemcachedClusterConfiguration> clusters;
public TritonMemcachedConfiguration() {
clusters = new HashMap<>();
}
/**
* Get cluster map
* @return
*/
public Map<String, TritonMemcachedClusterConfiguration> getClusters() {
return clusters;
}
/**
* Set cluster map
* @param clusters
*/
public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) {
this.clusters = clusters;
}
}
| {
"content_hash": "e3fd8c490f98289f3c46b77612dd35e3",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 85,
"avg_line_length": 18.78787878787879,
"alnum_prop": 0.7290322580645161,
"repo_name": "ameba-proteus/triton-server",
"id": "8d0cdb33513b3f7b2c083066c736254c5f7d175c",
"size": "620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "159977"
},
{
"name": "Shell",
"bytes": "1476"
}
],
"symlink_target": ""
} |
package org.springside.examples.quickstart.service;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.examples.oadata.repository.BuyerViewDao;
import org.springside.examples.quickstart.entity.BuyerData;
import org.springside.examples.quickstart.entity.ProjectData;
import org.springside.examples.quickstart.entity.xmlnode.BuyerXml;
import org.springside.examples.quickstart.repository.BuyerDataDao;
import org.springside.examples.quickstart.repository.ProjectDataDao;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.utils.PropertiesLoader;
// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class BuyerDataService {
private static Logger logger = LoggerFactory.getLogger(BuyerDataService.class);
static Marshaller marshaller ;
static CloseableHttpClient httpClient;
@Autowired
PropertiesLoader propertiesLoader;
static {
//发送
try {
JAXBContext context = JAXBContext.newInstance(BuyerXml.class);
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// 创建包含connection pool与超时设置的client
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000).setConnectTimeout(20 * 1000).build();
httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20).setDefaultRequestConfig(requestConfig).build();
} catch (JAXBException e) {
logger.error("初始化{}类错误:"+ BuyerDataService.class.getName() + e.getStackTrace());
}
}
@Autowired
private BuyerDataDao buyerDataDao;
@Autowired
private BuyerViewDao buyerViewDao;
@Autowired
private ProjectDataDao projectDataDao;
public Page<BuyerData> getBuyerData( Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) {
PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
Specification<BuyerData> spec = buildSpecification( searchParams);
return buyerDataDao.findAll(spec, pageRequest);
}
/**创建分页请求*/
private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
Sort sort = null;
if ("auto".equals(sortType)) {
sort = new Sort(Direction.DESC, "id");
} else if ("title".equals(sortType)) {
sort = new Sort(Direction.ASC, "title");
} else {
sort = new Sort(Direction.ASC, "customerId");
}
return new PageRequest(pageNumber - 1, pagzSize, sort);
}
/**
* 创建动态查询条件组合.
*/
private Specification<BuyerData> buildSpecification(Map<String, Object> searchParams) {
Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
//filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId));
Specification<BuyerData> spec = DynamicSpecifications.bySearchFilter(filters.values(), BuyerData.class);
return spec;
}
// /**
// * 向阳光易购发送采购人数据
// * @param ids
// */
// public boolean synBuyer(Long[] ids) {
// //方法执行结果
// boolean result = false;
// List<Long> idls = new ArrayList<Long>();
// CollectionUtils.addAll(idls, ids);
// Iterable<BuyerData> buyerDatas = buyerDataDao.findAll(idls);
// for (BuyerData buyerData: buyerDatas){
// //发送
// StringWriter writer = new StringWriter();
//
// BodyXml<BuyerData> bodyXml = new BodyXml<BuyerData>();
// bodyXml.setBuyerInfo(buyerData);
// BuyerXml buyerXml = new BuyerXml();
// buyerXml.setBody(bodyXml);
//
// try {
// marshaller.marshal(buyerXml, writer);
// } catch (JAXBException e) {
// logger.error("采购人{}|{}XML对象转换错误:"+e.getStackTrace(), buyerData.getId() , buyerData.getCustomerName() );
// }
// try {
//
// HttpPost httpPost = new HttpPost( propertiesLoader.getProperty("syn.synBuyerUrl") );
// // 创建名/值组列表
// List<NameValuePair> parameters = new ArrayList<NameValuePair>();
//
// parameters.add(new BasicNameValuePair( "xmlContent", writer.toString() ));
// // 创建UrlEncodedFormEntity对象
// UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity( parameters , "UTF-8");
// httpPost.setEntity(formEntiry);
//
// // 创建包含connection pool与超时设置的client
// CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
// closeableHttpResponse.getEntity().getContent();
// String xmlContentresp = IOUtils.toString(closeableHttpResponse.getEntity().getContent());
// if(xmlContentresp.contains("operTag")){
// String operTag = StringUtils.substringBetween(xmlContentresp, "<operTag>", "</operTag>");
// if("Y".equals(operTag)){//成功
// //更新同步状态
// buyerData.setSynStatus( BuyerData.SYNSTATUS_SUCCESS );
// buyerDataDao.save( buyerData );
// result = true;
// }else{
//
// logger.error("采购人【{}|{}】同步失败!", buyerData.getId() , buyerData.getCustomerName());
// }
// }
// //httpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// logger.error("采购人【{}|{}】同步接口连接错误:"+e.getStackTrace(),buyerData.getId() , buyerData.getCustomerName());
// }
// }
// return result;
// }
public boolean synBuyerProccess( ProjectData projectData){
//方法执行结果
boolean result = false;
// //采购人的代码不能为空
// if( projectData.getDelegateCompany() == null ){
// return result;
// }
//
// BuyerView buyerView = buyerViewDao.findOne( Integer.parseInt( projectData.getDelegateCompany() ) );
//
// //List<BuyerData> buyerDatas = buyerDataDao.findBuyerData( Integer.parseInt( projectData.getDelegateCompany() ) );
//
// //if(buyerDatas!=null && buyerDatas.size() > 0 ){
// //BuyerData buyerData = buyerDatas.get(0);
// //发送
// StringWriter writer = new StringWriter();
//
// BodyXml<BuyerView> bodyXml = new BodyXml<BuyerView>();
// bodyXml.setBuyerInfo(buyerView);
// BuyerXml buyerXml = new BuyerXml();
// buyerXml.setBody(bodyXml);
//
// try {
// marshaller.marshal(buyerXml, writer);
// } catch (JAXBException e) {
// logger.error("采购人{}|{}XML对象转换错误:"+e.getStackTrace(), buyerView.getCustomerId() , buyerView.getCustomerName() );
// }
// try {
//
// HttpPost httpPost = new HttpPost( propertiesLoader.getProperty("syn.synBuyerUrl") );
// // 创建名/值组列表
// List<NameValuePair> parameters = new ArrayList<NameValuePair>();
//
// parameters.add(new BasicNameValuePair( "xmlContent", writer.toString() ));
// // 创建UrlEncodedFormEntity对象
// UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity( parameters , "UTF-8");
// httpPost.setEntity(formEntiry);
//
// // 创建包含connection pool与超时设置的client
// CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
// closeableHttpResponse.getEntity().getContent();
// String xmlContentresp = IOUtils.toString(closeableHttpResponse.getEntity().getContent());
// if(xmlContentresp.contains("operTag")){
// String operTag = StringUtils.substringBetween(xmlContentresp, "<operTag>", "</operTag>");
// if("Y".equals(operTag)){//成功
// //更新同步状态
//// buyerData.setSynStatus( BuyerData.SYNSTATUS_SUCCESS );
//// buyerDataDao.save( buyerData );
// //更新项目中的采购人信息成功状态
// projectData.setSynStatus(ProjectData.SYNSTATUS_BUYERINFO_SUCCESS );
// projectDataDao.save(projectData);
// result = true;
// }else{
// logger.error("采购人【{}|{}】同步失败!", buyerView.getCustomerId() , buyerView.getCustomerName());
// }
// }
// closeableHttpResponse.close();
// //httpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// logger.error("采购人【{}|{}】同步接口连接错误:"+e.getStackTrace(),buyerView.getCustomerId() , buyerView.getCustomerName());
// }
// //}
projectData.setSynStatus(ProjectData.SYNSTATUS_BUYERINFO_SUCCESS );
projectDataDao.save(projectData);
result = true;
return result;
}
public String getBuyerDataName(String delegateCompany) {
BuyerData buyerData = buyerDataDao.findOne(Long.parseLong(delegateCompany));
return buyerData!=null ?buyerData.getCustomerName():null;
}
}
| {
"content_hash": "6309e7d4dc0ce9f90b4dd1b5d4d7a270",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 133,
"avg_line_length": 37.2625,
"alnum_prop": 0.7037906742703791,
"repo_name": "yuchengyang/springside4",
"id": "05b949a2a18f8baf1550d27d1f2aad23d866e4b4",
"size": "9680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/quickstart/src/main/java/org/springside/examples/quickstart/service/BuyerDataService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2927"
},
{
"name": "CSS",
"bytes": "509"
},
{
"name": "FreeMarker",
"bytes": "17"
},
{
"name": "Java",
"bytes": "433874"
},
{
"name": "JavaScript",
"bytes": "2597"
},
{
"name": "Lua",
"bytes": "2132"
},
{
"name": "Shell",
"bytes": "2370"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">07_05_监听APP状态</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
| {
"content_hash": "83ce6e49a6535ba415b51e9c0f33c8a6",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 52,
"avg_line_length": 27.875,
"alnum_prop": 0.672645739910314,
"repo_name": "dragonflyor/AndroidDemo_Base",
"id": "5f13ae7d5a2315836e4ec1d50c3e26c2087b95f7",
"size": "231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "07_05_监听APP状态/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6204"
},
{
"name": "C++",
"bytes": "251"
},
{
"name": "Java",
"bytes": "17332475"
},
{
"name": "Makefile",
"bytes": "38646"
}
],
"symlink_target": ""
} |
package org.picocontainer.behaviors;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.references.ThreadLocalReference;
/**
* <p>
* This behavior supports caches values per thread.
* </p>
*
* @author Paul Hammant
*/
@SuppressWarnings("serial")
public final class ThreadCached<T> extends Stored<T>{
public ThreadCached(ComponentAdapter<T> delegate) {
super(delegate, new ThreadLocalReference<Instance<T>>());
}
public String getDescriptor() {
return "ThreadCached" + getLifecycleDescriptor();
}
} | {
"content_hash": "5eb62587d4f8c10ac09a4da59b8fb9f9",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 65,
"avg_line_length": 22.28,
"alnum_prop": 0.718132854578097,
"repo_name": "tmyroadctfig/picocontainer-android",
"id": "d1ad9e194b953ca14b26ad64bbd0f8e9c0d20252",
"size": "1268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/picocontainer/behaviors/ThreadCached.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "664452"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
namespace Trivadis.AzureBootcamp.WebApi.Models
{
internal class ChatUserContext
{
private readonly HashSet<string> _signalrConnections = new HashSet<string>();
public ChatUser User { get; set; }
public void AddConnection(string connectionId)
{
_signalrConnections.Add(connectionId);
}
public void RemoveConnection(string connectionId)
{
_signalrConnections.Remove(connectionId);
}
public bool HasConnections { get { return _signalrConnections.Any(); } }
}
} | {
"content_hash": "8e5d0bb09dc2599316d95e32bd77797b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 85,
"avg_line_length": 28.043478260869566,
"alnum_prop": 0.6325581395348837,
"repo_name": "Trivadis/AzureDeveloperBootcamp",
"id": "ce2af3f23a646ec7da12a02aa065bae497e18a4b",
"size": "647",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Trivadis.AzureBootcamp.WebApi/Models/ChatUserContext.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "474"
},
{
"name": "Batchfile",
"bytes": "4104"
},
{
"name": "C#",
"bytes": "270665"
},
{
"name": "CSS",
"bytes": "942064"
},
{
"name": "HTML",
"bytes": "16753"
},
{
"name": "JavaScript",
"bytes": "674173"
},
{
"name": "PowerShell",
"bytes": "5721"
},
{
"name": "TypeScript",
"bytes": "11786"
}
],
"symlink_target": ""
} |
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
namespace CSharpMath.Rendering.Text {
using CSharpMath.Structures;
public class TextAtomListBuilder : IReadOnlyList<TextAtom> {
readonly List<TextAtom> _list = new List<TextAtom>();
private void Add(TextAtom atom) => _list.Add(atom);
public void ControlSpace() => Add(new TextAtom.ControlSpace());
public void Accent(TextAtom atom, string accent) => Add(new TextAtom.Accent(atom, accent));
public void Text(string text) {
if (char.IsPunctuation(text, 0))
switch (Last) {
case TextAtom.Text { Content: var prevText }:
Last = new TextAtom.Text(prevText + text);
return;
case TextAtom.Math { DisplayStyle: false, Content: var mathList }:
mathList.Add(new Atom.Atoms.Punctuation(text));
return;
}
Add(new TextAtom.Text(text));
}
public void Space(Space space) => Add(new TextAtom.Space(space));
public void Style(TextAtom atom, Atom.FontStyle style) => Add(new TextAtom.Style(atom, style));
public void Size(TextAtom atom, float fontSize) => Add(new TextAtom.Size(atom, fontSize));
public void Color(TextAtom atom, Color color) => Add(new TextAtom.Colored(atom, color));
public Result Math(string mathLaTeX, bool displayStyle, int startAt, ref int endAt) {
var builder = new Atom.LaTeXParser(mathLaTeX);
var (mathList, error) = builder.Build();
if (error != null) {
endAt = startAt - mathLaTeX.Length + builder.NextChar - 1;
return Result.Err("[Math] " + error);
} else {
Add(new TextAtom.Math(mathList, displayStyle));
return Result.Ok();
}
}
public void List(IReadOnlyList<TextAtom> textAtoms) => Add(new TextAtom.List(textAtoms));
public void Break() => Add(new TextAtom.Newline());
public void Comment(string comment) => Add(new TextAtom.Comment(comment));
public TextAtom Build() => _list.Count == 1 ? _list[0] : new TextAtom.List(this);
public int TextLength { get; set; } = 0;
[System.Diagnostics.CodeAnalysis.DisallowNull] // setter value cannot be null
public TextAtom? Last { get => Count == 0 ? null : _list[Count - 1]; set => _list[Count - 1] = value; }
public TextAtom this[int index] => _list[index];
public int Count => _list.Count;
public List<TextAtom>.Enumerator GetEnumerator() => _list.GetEnumerator();
IEnumerator<TextAtom> IEnumerable<TextAtom>.GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
}
}
| {
"content_hash": "e50136e66d448d3fb0289fdf8ed3231a",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 107,
"avg_line_length": 50.34615384615385,
"alnum_prop": 0.6665393430099312,
"repo_name": "verybadcat/CSharpMath",
"id": "25032677d05e016a13524e87d964d4c774d63bc5",
"size": "2618",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharpMath.Rendering/Text/TextAtomListBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "839425"
},
{
"name": "F#",
"bytes": "2142"
},
{
"name": "PowerShell",
"bytes": "3303"
}
],
"symlink_target": ""
} |
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/** @addtogroup STM32F4xx_StdPeriph_Templates
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#if defined (USE_STM324xG_EVAL)
#define MESSAGE1 " STM32F40xx "
#define MESSAGE2 " Device running on "
#define MESSAGE3 " STM324xG-EVAL "
#else /* USE_STM324x7I_EVAL */
#define MESSAGE1 " STM32F427x "
#define MESSAGE2 " Device running on "
#define MESSAGE3 " STM324x7I-EVAL "
#endif
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static __IO uint32_t uwTimingDelay;
RCC_ClocksTypeDef RCC_Clocks;
/* Private function prototypes -----------------------------------------------*/
static void Delay(__IO uint32_t nTime);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
/*!< At this stage the microcontroller clock setting is already configured,
this is done through SystemInit() function which is called from startup
files (startup_stm32f40xx.s/startup_stm32f427x.s) before to branch to
application main.
To reconfigure the default setting of SystemInit() function, refer to
system_stm32f4xx.c file
*/
/* SysTick end of count event each 10ms */
RCC_GetClocksFreq(&RCC_Clocks);
SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
/* Initialize LEDs and LCD available on EVAL board **************************/
STM_EVAL_LEDInit(LED1);
STM_EVAL_LEDInit(LED2);
STM_EVAL_LEDInit(LED3);
STM_EVAL_LEDInit(LED4);
/* Initialize the LCD */
LCD_Init();
/* Display message on LCD ***************************************************/
/* Clear the Foreground Layer */
LCD_Clear(LCD_COLOR_WHITE);
/* Set the LCD Back Color */
LCD_SetBackColor(LCD_COLOR_WHITE);
/* Set the LCD Text Color */
LCD_SetTextColor(LCD_COLOR_BLUE);
/* Display LCD messages */
LCD_DisplayStringLine(LCD_LINE_3, (uint8_t *)MESSAGE1);
LCD_DisplayStringLine(LCD_LINE_4, (uint8_t *)MESSAGE2);
LCD_DisplayStringLine(LCD_LINE_5, (uint8_t *)MESSAGE3);
/* Turn on LEDs *************************************************************/
STM_EVAL_LEDOn(LED1);
STM_EVAL_LEDOn(LED2);
STM_EVAL_LEDOn(LED3);
STM_EVAL_LEDOn(LED4);
/* Add your application code here */
/* Infinite loop */
while (1)
{
/* Toggle LD1 */
STM_EVAL_LEDToggle(LED1);
/* Insert 50 ms delay */
Delay(5);
/* Toggle LD2 */
STM_EVAL_LEDToggle(LED2);
/* Insert 50 ms delay */
Delay(5);
/* Toggle LD3 */
STM_EVAL_LEDToggle(LED3);
/* Insert 50 ms delay */
Delay(5);
/* Toggle LD4 */
STM_EVAL_LEDToggle(LED4);
/* Insert 50 ms delay */
Delay(5);
}
}
/**
* @brief Inserts a delay time.
* @param nTime: specifies the delay time length, in milliseconds.
* @retval None
*/
void Delay(__IO uint32_t nTime)
{
uwTimingDelay = nTime;
while(uwTimingDelay != 0);
}
/**
* @brief Decrements the TimingDelay variable.
* @param None
* @retval None
*/
void TimingDelay_Decrement(void)
{
if (uwTimingDelay != 0x00)
{
uwTimingDelay--;
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"content_hash": "762c9b1521ab62de68792ecb4e7fa419",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 81,
"avg_line_length": 25.9,
"alnum_prop": 0.5463320463320464,
"repo_name": "jys0305/highspeedlogger",
"id": "80dc4af9fcf9af26be230cb839773e44fc6939d0",
"size": "5259",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sw/libs/STM32F4xx_DSP_StdPeriph_Lib_V1.1.0/Project/STM32F4xx_StdPeriph_Templates/main.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "280928"
},
{
"name": "C",
"bytes": "21114329"
},
{
"name": "C++",
"bytes": "100991"
},
{
"name": "HTML",
"bytes": "455966"
},
{
"name": "LSL",
"bytes": "47664"
},
{
"name": "Makefile",
"bytes": "4331"
},
{
"name": "Objective-C",
"bytes": "1718"
}
],
"symlink_target": ""
} |
#include "tkInt.h"
#include "xbytes.h"
/*
*----------------------------------------------------------------------
*
* TkAlignImageData --
*
* This function takes an image and copies the data into an aligned
* buffer, performing any necessary bit swapping.
*
* Results:
* Returns a newly allocated buffer that should be freed by the caller.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
char *
TkAlignImageData(
XImage *image, /* Image to be aligned. */
int alignment, /* Number of bytes to which the data should be
* aligned (e.g. 2 or 4) */
int bitOrder) /* Desired bit order: LSBFirst or MSBFirst. */
{
long dataWidth;
char *data, *srcPtr, *destPtr;
int i, j;
if (image->bits_per_pixel != 1) {
Tcl_Panic(
"TkAlignImageData: Can't handle image depths greater than 1.");
}
/*
* Compute line width for output data buffer.
*/
dataWidth = image->bytes_per_line;
if (dataWidth % alignment) {
dataWidth += (alignment - (dataWidth % alignment));
}
data = ckalloc(dataWidth * image->height);
destPtr = data;
for (i = 0; i < image->height; i++) {
srcPtr = &image->data[i * image->bytes_per_line];
for (j = 0; j < dataWidth; j++) {
if (j >= image->bytes_per_line) {
*destPtr = 0;
} else if (image->bitmap_bit_order != bitOrder) {
*destPtr = xBitReverseTable[(unsigned char)(*(srcPtr++))];
} else {
*destPtr = *(srcPtr++);
}
destPtr++;
}
}
return data;
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* fill-column: 78
* End:
*/
| {
"content_hash": "82e218fdd40d0004d2d258fe270f5dea",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 72,
"avg_line_length": 21.57894736842105,
"alnum_prop": 0.5420731707317074,
"repo_name": "bitkeeper-scm/bitkeeper",
"id": "548716563d0460e6d1a11c24eca1b768a2699235",
"size": "1906",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/gui/tcltk/tk/generic/tkImgUtil.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "138638"
},
{
"name": "Awk",
"bytes": "537"
},
{
"name": "Batchfile",
"bytes": "17857"
},
{
"name": "BlitzBasic",
"bytes": "194161"
},
{
"name": "C",
"bytes": "28873391"
},
{
"name": "C#",
"bytes": "54012"
},
{
"name": "C++",
"bytes": "863164"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "28687"
},
{
"name": "CSS",
"bytes": "2606"
},
{
"name": "Common Lisp",
"bytes": "1386"
},
{
"name": "DIGITAL Command Language",
"bytes": "31087"
},
{
"name": "DTrace",
"bytes": "7347"
},
{
"name": "Emacs Lisp",
"bytes": "205568"
},
{
"name": "HTML",
"bytes": "1374203"
},
{
"name": "JavaScript",
"bytes": "6682"
},
{
"name": "Jolie",
"bytes": "3956"
},
{
"name": "Lex",
"bytes": "189720"
},
{
"name": "Logos",
"bytes": "168703"
},
{
"name": "M4",
"bytes": "744535"
},
{
"name": "Makefile",
"bytes": "506590"
},
{
"name": "Module Management System",
"bytes": "3093"
},
{
"name": "Objective-C",
"bytes": "220655"
},
{
"name": "Pascal",
"bytes": "94171"
},
{
"name": "Perl",
"bytes": "125543"
},
{
"name": "Perl 6",
"bytes": "1129"
},
{
"name": "PostScript",
"bytes": "130437"
},
{
"name": "Python",
"bytes": "48455"
},
{
"name": "R",
"bytes": "1390"
},
{
"name": "Roff",
"bytes": "4316683"
},
{
"name": "Ruby",
"bytes": "4837"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "742546"
},
{
"name": "Tcl",
"bytes": "4829953"
},
{
"name": "TeX",
"bytes": "677682"
},
{
"name": "Vim script",
"bytes": "385"
},
{
"name": "Yacc",
"bytes": "64491"
},
{
"name": "sed",
"bytes": "2377"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.mail;
import javax.mail.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.jvnet.mock_javamail.Mailbox;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MailToMultipleEndpointsTest extends CamelTestSupport {
@Test
public void testMultipleEndpoints() throws Exception {
Mailbox.clearAll();
template.sendBodyAndHeader("direct:a", "Hello World", "Subject", "Hello a");
template.sendBodyAndHeader("direct:b", "Bye World", "Subject", "Hello b");
template.sendBodyAndHeader("direct:c", "Hi World", "Subject", "Hello c");
Mailbox boxA = Mailbox.get("a@a.com");
assertEquals(1, boxA.size());
assertEquals("Hello a", boxA.get(0).getSubject());
assertEquals("Hello World", boxA.get(0).getContent());
assertEquals("me@me.com", boxA.get(0).getFrom()[0].toString());
Mailbox boxB = Mailbox.get("b@b.com");
assertEquals(1, boxB.size());
assertEquals("Hello b", boxB.get(0).getSubject());
assertEquals("Bye World", boxB.get(0).getContent());
assertEquals("you@you.com", boxB.get(0).getFrom()[0].toString());
Mailbox boxC = Mailbox.get("c@c.com");
assertEquals(1, boxC.size());
assertEquals("Hello c", boxC.get(0).getSubject());
assertEquals("Hi World", boxC.get(0).getContent());
assertEquals("me@me.com", boxC.get(0).getFrom()[0].toString());
assertEquals("you@you.com", boxC.get(0).getRecipients(Message.RecipientType.CC)[0].toString());
assertEquals("them@them.com", boxC.get(0).getRecipients(Message.RecipientType.CC)[1].toString());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:a").to("smtp://localhost?username=james2&password=secret&to=a@a.com&from=me@me.com");
from("direct:b").to("smtp://localhost?username=james&password=secret&to=b@b.com&from=you@you.com");
from("direct:c").to(
"smtp://localhost?username=admin&password=secret&to=c@c.com&from=me@me.com&cc=you@you.com,them@them.com");
}
};
}
}
| {
"content_hash": "68dd962c6268524a63c247902c6c7dbf",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 130,
"avg_line_length": 40.93103448275862,
"alnum_prop": 0.6385846672283066,
"repo_name": "adessaigne/camel",
"id": "dd7a8c23d8ba893fa1867cce7be67dff2db5b9de",
"size": "3176",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "components/camel-mail/src/test/java/org/apache/camel/component/mail/MailToMultipleEndpointsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "16123"
},
{
"name": "Groovy",
"bytes": "383919"
},
{
"name": "HTML",
"bytes": "209156"
},
{
"name": "Java",
"bytes": "109812609"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "19367"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
'use strict'
const pushJenkinsUpdate = require('../lib/push-jenkins-update')
function handleJenkinsStart (event) {
const { repo, owner } = event
pushJenkinsUpdate.pushStarted({
owner,
repo,
logger: event.logger
}, event, (err) => {
if (err) {
event.logger.error(err, 'Error while handling Jenkins start event')
}
})
}
function handleJenkinsStop (event) {
const { repo, owner } = event
pushJenkinsUpdate.pushEnded({
owner,
repo,
logger: event.logger
}, event, (err) => {
if (err) {
event.logger.error(err, 'Error while handling Jenkins end event')
}
})
}
module.exports = function (_, event) {
event.on('jenkins.start', handleJenkinsStart)
event.on('jenkins.end', handleJenkinsStop)
}
| {
"content_hash": "05a1365742c2c440751a1216a2d7e140",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 73,
"avg_line_length": 21.166666666666668,
"alnum_prop": 0.6456692913385826,
"repo_name": "nodejs/github-bot",
"id": "f9feaf0a6b89645ae442c6cc9d2648979998a737",
"size": "762",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "scripts/jenkins-status.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "41093"
},
{
"name": "Procfile",
"bytes": "17"
}
],
"symlink_target": ""
} |
---
order: 8
layout: default
title: "Pratiques de base"
subtitle: "Le petit bassin"
permalink: /8-base/
---
Toute théorie reste infondée sans une pratique intensive. Ou l'inverse...
Les propriétés sont connues, la plupart de leurs valeurs associées aussi. Mais qu'en faire ? Que souhaitez-vous faire ?
Mettre cet objet à droite. Décaler cet élément. Agrandir ce texte. Espacer ces titres. Décorer ce bloc.
Du mouvement, de la fluidité, de l'entrain !
### Centrer un élément
C'est une obsession très répandue que de vouloir centrer un site web. Moins répandue : celle de centrer du texte.
La distinction n'est pas anodine, que ce soit visuellement ou syntaxiquement.
#### Centrer un élément inline
Et par inline, je parle surtout et avant tout de **texte**. Une seule propriété : text-align.
{% highlight html %}
<p>On se croit naturellement bien plus capable d'arriver au centre des choses que d'embrasser leur circonférence.</p>
{% endhighlight %}
{% highlight css %}
p{ text-align: center;}
{% endhighlight %}
Notez bien que le text-align s'applique à un **bloc**, mais que c'est le contenu inline de ce dernier qui sera centré.
#### Centrer un bloc
C'est un désir primaire que de vouloir centrer un bloc, voire _le_ bloc principal, le site lui-même !
Par défaut, un bloc prend toute la largeur possible. Le centrer (horizontalement) correspond visuellement à avoir une marge _identique_ de part et d'autre de ce bloc.
Encore faut-il savoir si ce dernier possède une largeur fixe ou non.
* **bloc à largeur variable**
{% highlight html %}
<p>On se croit naturellement bien plus capable d'arriver au centre des choses que d'embrasser leur circonférence.</p>
{% endhighlight %}
{% highlight css %}
p{ margin: 0 100px;}
{% endhighlight %}
La largeur reste variable mais le bloc s'écarte des bords.
* **bloc à largeur fixe**
Ou bien la véritable définition du centrage d'un bloc. Une largeur fixe. Comment centrer alors ? Si l'on regarde l'exemple précédent, les marges sont fixes mais la largeur variable. Cette dernière s'ajuste _automatiquement_.
Si ici la largeur est fixe, alors ce sont les marges qui doivent s'adapter _automatiquement_. La solution est dans le mot même :
{% highlight html %}
<p>On se croit naturellement bien plus capable d'arriver au centre des choses que d'embrasser leur circonférence.</p>
{% endhighlight %}
{% highlight css %}
p{ margin: 0 auto; width: 400px;}
{% endhighlight %}
Puisque le conteneur principal (le body) a une largeur variable (selon la résolution de l'écran généralement) et le `<p>` une fixe, ce sont les marges qui vont arbitrer le positionnement central du bloc. Avec la valeur "auto" appliquées aux **deux** côtés, les margin-left et margin-right seront toujours **égaux** et s'ajusteront simultanément.
### Deux colonnes côte à côte
C'est une configuration très répandue et très désirée (car désirable), surtout depuis l'avènement des blogs en tout genre. En général, la largeur des deux colonnes n'est pas identique, l'une d'elle servant avant de subordonnée de l'autre.
{% highlight html %}
<div class="main">
<div class="lead">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt tincidunt elit, ac imperdiet risus accumsan eget. Praesent et sapien arcu, at lobortis purus. Donec eu velit eget elit fringilla fermentum id sit amet eros. Curabitur sit amet diam a sem vulputate lobortis eu at felis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In sem ligula, tempor sed dignissim non, hendrerit ut erat. Pellentesque congue euismod arcu, non tempor turpis volutpat eu. Donec sagittis auctor arcu, quis lobortis elit euismod non.
</p>
<p>
Duis dolor augue, ornare et accumsan quis, faucibus sit amet risus. Fusce egestas adipiscing turpis non lobortis. Donec eleifend sollicitudin aliquet. Integer eget enim mauris. Phasellus lorem felis, suscipit id porta vitae, suscipit quis ante. Praesent et metus massa, et blandit urna. Nullam ultricies rhoncus leo at blandit. Morbi egestas, enim in sagittis rutrum, est nibh pulvinar mauris, nec suscipit dolor lectus et lacus. Ut vel justo sit amet arcu ullamcorper ultricies a a diam. In ultricies, risus laoreet convallis consectetur, mauris libero consectetur lacus, eget sagittis lacus orci quis dui. Donec sed tortor nibh.
</p>
<p>
Integer sed odio dui. Vivamus quam neque, ultrices at suscipit non, tristique fermentum sapien. Nullam diam lectus, luctus sed semper vel, elementum et massa. Morbi venenatis tortor eu mauris sagittis tincidunt. Proin non urna at enim venenatis feugiat eu ut felis. Etiam auctor posuere lorem iaculis dictum. Duis venenatis urna non lectus accumsan mollis. Integer gravida dapibus enim, et porttitor eros vulputate quis. Praesent eget leo neque. Praesent pharetra velit sit amet purus tempor semper. Sed odio sem, faucibus quis ullamcorper ac, varius in quam. Donec quis ante non metus egestas consectetur. Aenean rhoncus pretium rhoncus. Nam sollicitudin sem quis risus placerat aliquam.
</p>
</div>
<div class="side">
<p>
La modestie doit être la réaction naturelle de l'homme qui reçoit les acclamations que lui ont valu le sang versé par ses subordonnés et le sacrifice de ses amis.
</p>
</div>
<div style="clear:both;"></div>
</div>
{% endhighlight %}
{% highlight css %}
.main {
margin: 0 auto;
width: 980px;
}
.lead,
.side {
padding: 20px;
}
.lead {
background: #e2e9ec;
float: left;
width: 680px;
}
.side {
background: #b7c9d1;
float: right;
width: 220px;
}
{% endhighlight %}
<figure class="image">
<img src="/images/2-colonnes-css.png" alt="2 colonnes en CSS">
<figcaption>Résultat : deux colonnes en CSS</figcaption>
</figure>
Tout d'abord un mot sur le **nom des classes**.
Pourquoi "main", "lead" et "side" ?
Pourquoi pas "main", "left" et "right" ?
Quelle horreur !
Imaginez que vous vouliez échanger l'emplacement des deux colonnes, soit les échanger, soit les mettre à la suite. Il faudra dans ce cas aussi modifier le nom des classes dans le HTML qui ne seront plus du tout pertinentes !
C'est pourquoi il faut généralement donner à une classe le nom de la **fonction de la balise à laquelle elle s'applique**.
Le "lead" est le contenu principal. Le "side" est le contenu _bis_. Libre à vous d'en modifier les noms, tant qu'il ne s'agit pas d'un nom lié au style qui lui est appliqué.
<p>Deuxième chose : dominus domini domino.<br>Du latin en guise de contenu principal ? Ce latin là, qui ne veut absolument rien dire, est bien connu des éditeurs. Il s'agit de <a href="http://fr.wikipedia.org/wiki/Faux-texte" title="Faux-Texte">faux-texte</a>. Des lignes de mots variés mais incompréhensibles, qui sont là pour leur <em>forme</em> et non pour leur <em>fond</em> (qui est d'ailleurs inexistant).<br>Bien plus intéressant qu'un mot unique répété répété répété répété répété répété répété répété une infinité de fois.<br>Bien plus efficace que du français pur jus car le <span style="text-decoration:line-through">lecteur</span> spectateur oublie le contenu pour ne se concentrer uniquement sur la mise en page.</p>
<aside>
<p>
Un rappel des dimensions.
</p>
<ul>
<li>La <code><div class="main"></code> fait 980px de large.
</li>
<li>La <code><div class="lead"></code> fait 720px de large (680 en width, 40 en padding).
</li>
<li>La <code><div class="side"></code> fait 260px de large (220 en width, 40 en padding).
</li>
</ul>
<p>
Le compte y est.
</p>
</aside>
Troisième chose : pourquoi le side est à droite alors qu'un `float: left` lui est appliqué ?
A vrai dire, le "lead" étant calé à gauche, le "side" (qui est second dans le code) se cale à gauche autant que possible, dans l'espace que le "lead" lui laisse.
Essayez par exemple de réduire la largeur du "lead" et vous verrez le "side" se déplacer vers la gauche, toujours **collé** au "lead".
Pourquoi ne pas appliquer un `float: right` au "side" alors ?
A vrai dire, c'est même **mieux** si vous souhaitez coller le "side" à droite en toutes circonstances. De ce fait, une réduction de la largeur du "lead" résultera en un espace blanc entre les deux colonnes (et non plus à droite du "side").
Autre avantage : avec un `float: right`, le "side" ne sera plus dépendant de sa position dans le code HTML. Il peut être placé _avant_ le "lead" sans pour autant modifier la mise en page.
### Trois colonnes côte à côte
Pourquoi s'arrêter en si bon chemin ?
{% highlight html %}
<div class="main">
<div class="lead">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt tincidunt elit, ac imperdiet risus accumsan eget. Praesent et sapien arcu, at lobortis purus. Donec eu velit eget elit fringilla fermentum id sit amet eros. Curabitur sit amet diam a sem vulputate lobortis eu at felis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In sem ligula, tempor sed dignissim non, hendrerit ut erat. Pellentesque congue euismod arcu, non tempor turpis volutpat eu. Donec sagittis auctor arcu, quis lobortis elit euismod non.
</p>
<p>
Duis dolor augue, ornare et accumsan quis, faucibus sit amet risus. Fusce egestas adipiscing turpis non lobortis. Donec eleifend sollicitudin aliquet. Integer eget enim mauris. Phasellus lorem felis, suscipit id porta vitae, suscipit quis ante. Praesent et metus massa, et blandit urna. Nullam ultricies rhoncus leo at blandit. Morbi egestas, enim in sagittis rutrum, est nibh pulvinar mauris, nec suscipit dolor lectus et lacus. Ut vel justo sit amet arcu ullamcorper ultricies a a diam. In ultricies, risus laoreet convallis consectetur, mauris libero consectetur lacus, eget sagittis lacus orci quis dui. Donec sed tortor nibh.
</p>
<p>
Integer sed odio dui. Vivamus quam neque, ultrices at suscipit non, tristique fermentum sapien. Nullam diam lectus, luctus sed semper vel, elementum et massa. Morbi venenatis tortor eu mauris sagittis tincidunt. Proin non urna at enim venenatis feugiat eu ut felis. Etiam auctor posuere lorem iaculis dictum. Duis venenatis urna non lectus accumsan mollis. Integer gravida dapibus enim, et porttitor eros vulputate quis. Praesent eget leo neque. Praesent pharetra velit sit amet purus tempor semper. Sed odio sem, faucibus quis ullamcorper ac, varius in quam. Donec quis ante non metus egestas consectetur. Aenean rhoncus pretium rhoncus. Nam sollicitudin sem quis risus placerat aliquam.
</p>
</div>
<div class="bis">
<p>
Tout homme est le centre d'un cercle dont il ne peut franchir la circonférence.
</p>
</div>
<div class="ter">
<p>
La modestie doit être la réaction naturelle de l'homme qui reçoit les acclamations que lui ont valu le sang versé par ses subordonnés et le sacrifice de ses amis.
</p>
</div>
<div style="clear:both;"></div>
</div>
{% endhighlight %}
{% highlight css %}
.main {
margin: 0 auto;
width: 980px;
}
.lead {
background: #e2e9ec;
float: left;
padding: 30px;
width: 500px;
}
.bis,
.ter {
float: left;
font-size: 14px;
line-height: 20px;
padding: 20px;
width: 170px;
}
.bis {
background: #b7c9d1;
}
.ter {
background: #8ba9b6;
}
{% endhighlight %}
<figure class="image">
<img src="/images/3-colonnes-css.png" alt="3 colonnes en CSS">
<figcaption>Résultat : trois colonnes en CSS</figcaption>
</figure>
Premier constat : les 3 colonnes étant en `float:left`, leur ordre dans le HTML est primordial. "De haut en bas" dans le code HTML équivaut à "de gauche à droite" à l'affichage.
Aussi, pour intervertir les colonnes "bis" et "ter", rien de plus simple. Il suffit de leur appliquer un `float:right`.
Comment ça marche ? Le `float:right` place le 1er élément dans le code ("bis") à droite, puis le 2ème ("ter") à sa gauche.
### Un tableau HTML
Décriés à tord par certains intégrateurs peu scrupuleux (et peu clairvoyants, n'est-ce pas), les tableaux sont un passage obligé car très utiles pour ceux qu'ils sont sensés mettre en forme : des données tabulaires. Un croisement d'informations absolument pratique.
Un des soucis du code HTML d'un tableau est que ce code est extrêmement **bavard**. Enormément de balises pour un affichage minimal. Jugez vous-même :
{% highlight html %}
<table>
<tr>
<td>
La peur de la mort est l'unique source des religions.
</td>
</tr>
</table>
{% endhighlight %}
Le code HTML ci-dessus est le code minimum nécessaire pour construire un tableau valide :
* `<table>`
Elle entoure l'ensemble du tableau.
* `<tr>`
Une ligne (tr = **t**able **r**ow).
* `<td>`
Une cellule d'un tableau. (td = **t**able cell **d**elimiter).
Elle doit forcément être directement enfant d'une balise `<tr>`
* `<th>`
Identique au `<td>` mise à part qu'il s'agit d'un **titre** dans un tableau. (th = **t**able **h**eader cell ).
Quel est le lien entre l'**ordre** des balises dans le code HTML et l'affichage du tableau ?
D'abord de de gauche à droite _puis_ de haut en bas.
Cela vient du fait que le `<td>` est imbriqué dans le `<tr>`, et non pas l'inverse.
{% highlight html %}
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
{% endhighlight %}
{% highlight css %}
td{ background:#fafafa; border:1px solid #eee; color:#777; padding:2px 10px;}
{% endhighlight %}
<figure class="image">
<img src="/images/ordre-cellules-tableau.png" alt="Ordre des cellules d'un tableau HTML">
<figcaption>Ordre des cellules d'un tableau HTML</figcaption>
</figure>
Si votre résultat est différent, c'est que vous n'utilisez pas le [Reset CSS](/2-pinceau.html#reset-css). Ce dernier applique un style de base très utile aux tableaux :
{% highlight css %}
table {
border-collapse: collapse;
border-spacing: 0;
}
{% endhighlight %}
Le `border-collapse` permet aux bordures des cellules d'être **confondues**. Ainsi, entre deux cellules adjacentes, la bordure a une épaisseur de 1 pixel. Le résultat est beaucoup plus sobre et pratique.
En ce qui concerne le `border-spacing`, il s'agit de l'espacement _entre_ les cellules. Une sorte de `margin` particulier.
#### tbody, thead, tfoot : un tableau de la tête aux pieds
Déjà très morcelé, le tableau peut se dôter d'un corps en 3 parties :
{% highlight html %}
<table>
<thead>
<tr>
<th>Titre</th>
<th>Année</th>
<th>Minutes</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Titre</th>
<th>Année</th>
<th>Minutes</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Day of the Fight</td>
<td>1951</td>
<td>16</td>
</tr>
<tr>
<td>Flying Padre</td>
<td>1951</td>
<td>9</td>
</tr>
<tr>
<td>The Seafarers</td>
<td>1953</td>
<td>30</td>
</tr>
</tbody>
</table>
{% endhighlight %}
<figure class="image">
<img src="/images/tableau-html-thead-tfoot-tbody.png" alt="Tableau HTML en 3 parties">
<figcaption>Un tableau HTML en 3 parties</figcaption>
</figure>
Tout ceci n'est qu'une question de **sémantique**.
Vous noterez que le `<tfoot>`, malgré qu'il soit avant le `<tbody>` dans le code HTML, se retrouve _à la fin_ à l'affichage.
Cette particularité est une obligation. Le W3C le justifie par le fait que le `<tfoot>` doit être généré avant que les données (parfois très nombreuses) du `<tbody>` arrivent.
### Styler un formulaire
L'interactivité avec le serveur. Je demande, tu renvoies.
Les formulaires sont omniprésents sur la toile, mais bien trop souvent pourvus d'un graphisme douteux. Pour cause : les formulaires sont difficiles à styler. Ils répondent différemment aux styles qu'on leur appliquent. Par exemple, le line-height est partiellement, voire totalement, inefficace sur les champs de texte.
De plus, chaque navigateur possède à la base sa propre flopée de styles pour les éléments des formulaires. Alors quand il s'agit de réappliquer un style par-dessus, commun à tous, l'exercice s'avère tendu.
En même temps, les formulaires sont là pour être utilisés avant d'être observés. Ils ont un rôle bien défini.
Malgré tout, un formulaire a le droit et la possibilité de se voir embelli par nos soins. Il suffit de bien apréhender les contraintes posées pour mieux les embrasser. Il y en a même qui écrivent des articles plutôt intéressants sur [comment réaliser un bon formulaire HTML](http://bbxdesign.com/2009/04/21/comment-realiser-un-bon-formulaire-html). C'est dire.
#### form
La balise `<form>` est celle qui englobe tous les éléments d'un formulaire.
Ce formulaire a un rôle **unique**. Comprenez : tous les éléments inclus (champ texte, boutons radio, checkbox, menu select...) sont **associés**. C'est leur **combinaison** qui va définir ce que le formulaire va nous renvoyer par la suite.
{% highlight html %}
<form action="resultat.php"><!-- Eléments du formulaire --></form>
{% endhighlight %}
L'attribut "action" est obligatoire. Il définit où se trouve le fichier qui renverra le résultat de la soumission du formulaire.
#### input
Derrière cette balise, un grand nombre de possibilités selon la valeur de l'attribut "type" :
<table>
<tbody>
<tr>
<th>
Type
</th>
<th>
Apparence
</th>
<th>
Stylable ?
</th>
</tr>
<tr>
<td>
<code><input type="text"></code>
</td>
<td>
<input type="text" value="Un champ texte">
</td>
<td>
Oui
</td>
</tr>
<tr>
<td>
<code><input type="password"></code>
</td>
<td>
<input type="password" value="123456789">
</td>
<td>
Oui
</td>
</tr>
<tr>
<td>
<code><input type="checkbox"></code>
</td>
<td>
<input type="checkbox">
</td>
<td>
Non
</td>
</tr>
<tr>
<td>
<code><input type="radio"></code>
</td>
<td>
<input type="radio">
</td>
<td>
Non
</td>
</tr>
<tr>
<td>
<code><input type="file"></code>
</td>
<td>
<input type="file">
</td>
<td>
Non (pas du tout même)
</td>
</tr>
<tr>
<td>
<code><input type="submit"></code> ou <code><input type="button"></code>
</td>
<td>
<input type="button" value="Soumettre le formulaire">
</td>
<td>
Oui mais...
</td>
</tr>
<tr>
<td>
<code><input type="reset"></code>
</td>
<td>
<input type="reset">
</td>
<td>
Oui mais...
</td>
</tr>
<tr>
<td>
<code><input type="image" alt="Description"></code>
</td>
<td>
<input type="image" src="input-type-image.png" alt="Une image pour soumission">
</td>
<td>
Non
</td>
</tr>
<tr>
<td>
<code><input type="hidden"></code>
</td>
<td>
<input type="hidden" value="Une donnée utile">Invisible mais utilisé pour transmettre des données sans les afficher
</td>
<td>
...
</td>
</tr>
</tbody>
</table>
#### textarea
Lorsqu'une seule ligne ne suffit plus...
<textarea style="height:140px; line-height:20px; max-width:550px; padding:10px; width:550px;" cols="100" rows="8">Le train, maintenant, roulait à toute vitesse, sur le plateau qui va de Bolbec à Sotteville. Il devait filer d'un trait à Paris, sans arrêt aucun, sauf aux points marqués pour prendre de l'eau. L'énorme masse, les dix-huit wagons, chargés, bondés de bétail humain, traversaient la campagne noire, dans un grondement continu. Et ces hommes qu'on charriait au massacre, chantaient, chantaient à tue-tête, d'une clameur si haute, qu'elle dominait le bruit des roues.</textarea>
Les attributs "cols" et "rows" ne sont plus obligatoires mais il est préférable de les garder pour d'antiques navigateurs.
Le textarea répond aux indications de dimensions :
{% highlight css %}
textarea{ height:140px; line-height:20px; padding:10px; width:550px;}
{% endhighlight %}
Cependant, la réaction selon les navigateurs peut varier, notamment en ce qui concerne l'apparence de la scrollbar lorsque celle-ci apparaît.
Aussi, il faut désormais tenir compte de la tendance des navigateurs à offrir la possibilité à l'internaute de redimensionner à souhait les textarea, ce qui, en soit, est un net avantage pour l'internaute mais parfois un souci pour l'intégrité du design.
Même si cette feature est contournable grâce à la propriété `textarea{ resize:none;}` (qui empêche le **redimensionnement du textarea**), je ne la conseille pas.
Dans ce cas, il est préférable de bloquer uniquement le redimensionnement horizontal qui est souvent celui qui pose souci.
{% highlight css %}
textarea{ max-width:550px;}
{% endhighlight %}
<aside>Firefox 4 permet, comme Chrome, de redimensionner les textarea. Cependant, Firefox le fait bien mal. Alors que Chrome utilise les valeurs "height" et "width" aussi comme valeurs <em>minmales</em> du textarea, Firefox laisse la possibilité de redimensionner jusqu'à 0x0 pixel, ce qui est une bêtise totale. C'est pourquoi il faut doubler les valeurs height/width avec leurs compères min-height/min-width.</aside>
#### label
Le label ne fait rien en soi. Il est surtout là pour décrire les input auxquels il est associé.
{% highlight html %}
<label for="nom">Nom</label><br><input id="nom" type="text">
{% endhighlight %}
<figure class="image">
<img src="/images/label-et-input-text.png" alt="Label et Input text">
<figcaption>Un label et un input text, what else?</figcaption>
</figure>
L'attribut "for" est plutôt pratique : en cliquant sur le label "Nom", le focus est réalisé sur l'input text à l'id "nom".
Vous me direz "Pourquoi ne pas cliquer directement dans l'input text ?". En l'occurence, oui. Le champ de texte est assez vaste pour être facilement cliquable.
<p>L'intérêt de la balise <code><label></code> se trouve lorsqu'elle est associée à des boutons radio <input type="radio"> ou des checkbox <input type="checkbox">. Comme vous pouvez le constater, la zone cliquable de ces boutons est plutôt restreinte. Voici comment y remédier :</p>
{% highlight html %}
<input id="oui" type="radio" name="question" value="oui">
<label for="oui">Oui</label>
<br>
<input id="non" type="radio" name="question" value="non">
<label for="non">Non</label>
{% endhighlight %}
<p class="image">
<img src="img/boutons-et-label.png" alt="Boutons radio et label">
<span>Les mots "Oui" et "Non" sont cliquables</span>
</p>
L'attribut "for" associe à nouveau chaque label à un bouton radio.
L'attribut "name" quant à lui associe les boutons radio entre eux : cliquez sur l'un, ça désactive tous les autres. Logique : le choix est exclusif au sein des boutons radio. La zone cliquable s'est bien agrandie.
Mais oubliez cette syntaxe lorsqu'il en existe une plus légère et tout aussi efficace :
{% highlight html %}
<label>
<input type="radio" name="question" value="oui"> Oui
</label>
<br>
<label>
<input type="radio" name="question" value="non"> Non
</label>
{% endhighlight %}
Les input radio (et checkbox) peuvent être **imbriqués** dans un `<label>`. Résultat : on s'affranchit de l'utilisation des attributs for (pour le label) et id (pour les input). Une notation bien plus simple pour une zone cliquable tout aussi, voire légèrement plus grande.
#### Un formulaire CSS simple, valide et flexible
Avec un minimum de classes et de classe, on peut déjà arriver à un résultat intéressant.
{% highlight html %}
<div class="form">
<form action="/">
<p>
<label>Name</label><br>
<input type="text">
</p>
<p>
<label>Email</label><br>
<input type="text">
</p>
<p>
<label>You've got to ask yourself one question: 'Do I feel lucky?' Well, do ya, punk?</label><br>
<label class="radio"><input name="punk" type="radio"> Yes</label><br>
<label class="radio"><input name="punk" type="radio"> No</label>
</p>
<p>
<label>Why's that?</label><br>
<textarea></textarea>
</p>
<p>
<input type="submit" value="Go ahead, make my day">
</p>
</form>
</div>
{% endhighlight %}
<div class="form">
<form action="/">
<p>
<label>Name</label><br>
<input type="text">
</p>
<p>
<label>Email</label><br>
<input type="text">
</p>
<p>
<label>You've got to ask yourself one question: 'Do I feel lucky?' Well, do ya, punk?</label><br>
<label class="radio"><input name="punk" type="radio"> Yes</label><br>
<label class="radio"><input name="punk" type="radio"> No</label>
</p>
<p>
<label>Why's that?</label><br>
<textarea></textarea>
</p>
<p>
<input type="submit" value="Go ahead, make my day">
</p>
</form>
</div>
{% highlight css %}
.form {
background: #fafafa;
border: 1px solid #eee;
border-radius: 4px;
margin-bottom: 24px;
padding: 20px;
width: 600px;
}
.form input[type=text],
.form textarea {
border: 2px solid #ddd;
}
.form input[type=text] {
padding: 4px;
width: 260px;
}
.form input[type=text]:focus,
.form textarea:focus {
border-color: #e64135;
}
.form textarea {
height: 120px;
max-width: 578px;
padding: 10px;
width: 578px;
}
.form label {
font-weight: bold;
}
.form .radio {
cursor: pointer;
font-weight: normal;
}
{% endhighlight %}
{% highlight css %}
/* Le bouton submit */
.form input[type=submit] {
background: #f3f3f3;
background: -webkit-gradient(linear, 0% 40%, 0% 70%, from(#F5F5F5), to(#F1F1F1));
border: 1px solid #dcdcdc;
border-radius: 2px;
color: #6e6e6e;
cursor: pointer;
display: inline-block;
margin-right: 10px;
padding: 7px 12px;
position: relative;
text-shadow: 0 1px 0 #fff;
transition: border-color .218s;
}
.form input[type=submit]:hover {
border-color: #999;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
color: #333;
}
.form input[type=submit]:active {
border-color: #444;
color: #000;
}
{% endhighlight %}
Les `<input type="text">` comprennent très mal, voire pas du tout, le `line-height`. Pour centrer le texte verticalement, il faut uniquement s'appuyer sur les `padding` : ici, 4px en haut et en bas.
Pratique cette page. En voilà des [bonnes](/9-bonnes-pratiques), d'ailleurs.
| {
"content_hash": "596d4f84a7358eb39fe9566d037c85b5",
"timestamp": "",
"source": "github",
"line_count": 686,
"max_line_length": 729,
"avg_line_length": 38.731778425655975,
"alnum_prop": 0.6899134362062477,
"repo_name": "jgthms/css-art-science",
"id": "c73093da731e17c19ac7afd01f649bb418107b09",
"size": "26877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "8-base.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13770"
},
{
"name": "HTML",
"bytes": "4733"
},
{
"name": "JavaScript",
"bytes": "247"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "83e797fe8f189a012f159f8cb191afde",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 8.384615384615385,
"alnum_prop": 0.6788990825688074,
"repo_name": "mdoering/backbone",
"id": "b9fa429da011a526f9bc45a4c83ae4792d5a1df9",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Clavularia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.nifi.web.api;
import com.sun.jersey.api.core.ResourceContext;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import com.wordnik.swagger.annotations.Authorization;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.authorization.AuthorizeControllerServiceReference;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.authorization.ComponentAuthorizable;
import org.apache.nifi.authorization.RequestAction;
import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.user.NiFiUserUtils;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.web.IllegalClusterResourceRequestException;
import org.apache.nifi.web.NiFiServiceFacade;
import org.apache.nifi.web.Revision;
import org.apache.nifi.web.api.dto.BulletinDTO;
import org.apache.nifi.web.api.dto.ClusterDTO;
import org.apache.nifi.web.api.dto.ControllerServiceDTO;
import org.apache.nifi.web.api.dto.NodeDTO;
import org.apache.nifi.web.api.dto.ReportingTaskDTO;
import org.apache.nifi.web.api.entity.BulletinEntity;
import org.apache.nifi.web.api.entity.ClusterEntity;
import org.apache.nifi.web.api.entity.ControllerConfigurationEntity;
import org.apache.nifi.web.api.entity.ControllerServiceEntity;
import org.apache.nifi.web.api.entity.Entity;
import org.apache.nifi.web.api.entity.HistoryEntity;
import org.apache.nifi.web.api.entity.NodeEntity;
import org.apache.nifi.web.api.entity.ReportingTaskEntity;
import org.apache.nifi.web.api.request.DateTimeParameter;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.Date;
/**
* RESTful endpoint for managing a Flow Controller.
*/
@Path("/controller")
@Api(
value = "/controller",
description = "Provides realtime command and control of this NiFi instance"
)
public class ControllerResource extends ApplicationResource {
private NiFiServiceFacade serviceFacade;
private Authorizer authorizer;
private ReportingTaskResource reportingTaskResource;
private ControllerServiceResource controllerServiceResource;
@Context
private ResourceContext resourceContext;
/**
* Authorizes access to the flow.
*/
private void authorizeController(final RequestAction action) {
serviceFacade.authorizeAccess(lookup -> {
final Authorizable controller = lookup.getController();
controller.authorize(authorizer, action, NiFiUserUtils.getNiFiUser());
});
}
/**
* Retrieves the configuration for this NiFi.
*
* @return A controllerConfigurationEntity.
*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("config")
@ApiOperation(
value = "Retrieves the configuration for this NiFi Controller",
response = ControllerConfigurationEntity.class,
authorizations = {
@Authorization(value = "Read - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response getControllerConfig() {
authorizeController(RequestAction.READ);
if (isReplicateRequest()) {
return replicate(HttpMethod.GET);
}
final ControllerConfigurationEntity entity = serviceFacade.getControllerConfiguration();
return generateOkResponse(entity).build();
}
/**
* Update the configuration for this NiFi.
*
* @param httpServletRequest request
* @param requestConfigEntity A controllerConfigurationEntity.
* @return A controllerConfigurationEntity.
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("config")
@ApiOperation(
value = "Retrieves the configuration for this NiFi",
response = ControllerConfigurationEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response updateControllerConfig(
@Context final HttpServletRequest httpServletRequest,
@ApiParam(
value = "The controller configuration.",
required = true
) final ControllerConfigurationEntity requestConfigEntity) {
if (requestConfigEntity == null || requestConfigEntity.getComponent() == null) {
throw new IllegalArgumentException("Controller configuration must be specified");
}
if (requestConfigEntity.getRevision() == null) {
throw new IllegalArgumentException("Revision must be specified.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.PUT, requestConfigEntity);
}
final Revision requestRevision = getRevision(requestConfigEntity.getRevision(), FlowController.class.getSimpleName());
return withWriteLock(
serviceFacade,
requestConfigEntity,
requestRevision,
lookup -> {
authorizeController(RequestAction.WRITE);
},
null,
(revision, configEntity) -> {
final ControllerConfigurationEntity entity = serviceFacade.updateControllerConfiguration(revision, configEntity.getComponent());
return generateOkResponse(entity).build();
}
);
}
// ---------------
// reporting tasks
// ---------------
/**
* Creates a new Reporting Task.
*
* @param httpServletRequest request
* @param requestReportingTaskEntity A reportingTaskEntity.
* @return A reportingTaskEntity.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("reporting-tasks")
@ApiOperation(
value = "Creates a new reporting task",
response = ReportingTaskEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = ""),
@Authorization(value = "Read - any referenced Controller Services - /controller-services/{uuid}", type = ""),
@Authorization(value = "Write - if the Reporting Task is restricted - /restricted-components", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response createReportingTask(
@Context final HttpServletRequest httpServletRequest,
@ApiParam(
value = "The reporting task configuration details.",
required = true
) final ReportingTaskEntity requestReportingTaskEntity) {
if (requestReportingTaskEntity == null || requestReportingTaskEntity.getComponent() == null) {
throw new IllegalArgumentException("Reporting task details must be specified.");
}
if (requestReportingTaskEntity.getRevision() == null || (requestReportingTaskEntity.getRevision().getVersion() == null || requestReportingTaskEntity.getRevision().getVersion() != 0)) {
throw new IllegalArgumentException("A revision of 0 must be specified when creating a new Reporting task.");
}
final ReportingTaskDTO requestReportingTask = requestReportingTaskEntity.getComponent();
if (requestReportingTask.getId() != null) {
throw new IllegalArgumentException("Reporting task ID cannot be specified.");
}
if (StringUtils.isBlank(requestReportingTask.getType())) {
throw new IllegalArgumentException("The type of reporting task to create must be specified.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.POST, requestReportingTaskEntity);
}
return withWriteLock(
serviceFacade,
requestReportingTaskEntity,
lookup -> {
authorizeController(RequestAction.WRITE);
ComponentAuthorizable authorizable = null;
try {
authorizable = lookup.getConfigurableComponent(requestReportingTask.getType(), requestReportingTask.getBundle());
if (authorizable.isRestricted()) {
lookup.getRestrictedComponents().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
}
if (requestReportingTask.getProperties() != null) {
AuthorizeControllerServiceReference.authorizeControllerServiceReferences(requestReportingTask.getProperties(), authorizable, authorizer, lookup);
}
} finally {
if (authorizable != null) {
authorizable.cleanUpResources();
}
}
},
() -> serviceFacade.verifyCreateReportingTask(requestReportingTask),
(reportingTaskEntity) -> {
final ReportingTaskDTO reportingTask = reportingTaskEntity.getComponent();
// set the processor id as appropriate
reportingTask.setId(generateUuid());
// create the reporting task and generate the json
final Revision revision = getRevision(reportingTaskEntity, reportingTask.getId());
final ReportingTaskEntity entity = serviceFacade.createReportingTask(revision, reportingTask);
reportingTaskResource.populateRemainingReportingTaskEntityContent(entity);
// build the response
return generateCreatedResponse(URI.create(entity.getUri()), entity).build();
}
);
}
/**
* Creates a Bulletin.
*
* @param httpServletRequest request
* @param requestBulletinEntity A bulletinEntity.
* @return A bulletinEntity.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("bulletin")
@ApiOperation(
value = "Creates a new bulletin",
response = BulletinEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response createBulletin(
@Context final HttpServletRequest httpServletRequest,
@ApiParam(
value = "The reporting task configuration details.",
required = true
) final BulletinEntity requestBulletinEntity) {
if (requestBulletinEntity == null || requestBulletinEntity.getBulletin() == null) {
throw new IllegalArgumentException("Bulletin details must be specified.");
}
final BulletinDTO requestBulletin = requestBulletinEntity.getBulletin();
if (requestBulletin.getId() != null) {
throw new IllegalArgumentException("A bulletin ID cannot be specified.");
}
if (StringUtils.isBlank(requestBulletin.getMessage())) {
throw new IllegalArgumentException("The bulletin message must be specified.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.POST, requestBulletinEntity);
}
return withWriteLock(
serviceFacade,
requestBulletinEntity,
lookup -> {
authorizeController(RequestAction.WRITE);
},
null,
(bulletinEntity) -> {
final BulletinDTO bulletin = bulletinEntity.getBulletin();
final BulletinEntity entity = serviceFacade.createBulletin(bulletin,true);
return generateOkResponse(entity).build();
}
);
}
// -------------------
// controller services
// -------------------
/**
* Creates a new Controller Service.
*
* @param httpServletRequest request
* @param requestControllerServiceEntity A controllerServiceEntity.
* @return A controllerServiceEntity.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("controller-services")
@ApiOperation(
value = "Creates a new controller service",
response = ControllerServiceEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = ""),
@Authorization(value = "Read - any referenced Controller Services - /controller-services/{uuid}", type = ""),
@Authorization(value = "Write - if the Controller Service is restricted - /restricted-components", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response createControllerService(
@Context final HttpServletRequest httpServletRequest,
@ApiParam(
value = "The controller service configuration details.",
required = true
) final ControllerServiceEntity requestControllerServiceEntity) {
if (requestControllerServiceEntity == null || requestControllerServiceEntity.getComponent() == null) {
throw new IllegalArgumentException("Controller service details must be specified.");
}
if (requestControllerServiceEntity.getRevision() == null
|| (requestControllerServiceEntity.getRevision().getVersion() == null || requestControllerServiceEntity.getRevision().getVersion() != 0)) {
throw new IllegalArgumentException("A revision of 0 must be specified when creating a new Controller service.");
}
final ControllerServiceDTO requestControllerService = requestControllerServiceEntity.getComponent();
if (requestControllerService.getId() != null) {
throw new IllegalArgumentException("Controller service ID cannot be specified.");
}
if (requestControllerService.getParentGroupId() != null) {
throw new IllegalArgumentException("Parent process group ID cannot be specified.");
}
if (StringUtils.isBlank(requestControllerService.getType())) {
throw new IllegalArgumentException("The type of controller service to create must be specified.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.POST, requestControllerServiceEntity);
}
return withWriteLock(
serviceFacade,
requestControllerServiceEntity,
lookup -> {
authorizeController(RequestAction.WRITE);
ComponentAuthorizable authorizable = null;
try {
authorizable = lookup.getConfigurableComponent(requestControllerService.getType(), requestControllerService.getBundle());
if (authorizable.isRestricted()) {
lookup.getRestrictedComponents().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
}
if (requestControllerService.getProperties() != null) {
AuthorizeControllerServiceReference.authorizeControllerServiceReferences(requestControllerService.getProperties(), authorizable, authorizer, lookup);
}
} finally {
if (authorizable != null) {
authorizable.cleanUpResources();
}
}
},
() -> serviceFacade.verifyCreateControllerService(requestControllerService),
(controllerServiceEntity) -> {
final ControllerServiceDTO controllerService = controllerServiceEntity.getComponent();
// set the processor id as appropriate
controllerService.setId(generateUuid());
// create the controller service and generate the json
final Revision revision = getRevision(controllerServiceEntity, controllerService.getId());
final ControllerServiceEntity entity = serviceFacade.createControllerService(revision, null, controllerService);
controllerServiceResource.populateRemainingControllerServiceEntityContent(entity);
// build the response
return generateCreatedResponse(URI.create(entity.getUri()), entity).build();
}
);
}
// -------
// cluster
// -------
/**
* Gets the contents of this NiFi cluster. This includes all nodes and their status.
*
* @return A clusterEntity
*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("cluster")
@ApiOperation(
value = "Gets the contents of the cluster",
notes = "Returns the contents of the cluster including all nodes and their status.",
response = ClusterEntity.class,
authorizations = {
@Authorization(value = "Read - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response getCluster() {
authorizeController(RequestAction.READ);
// ensure connected to the cluster
if (!isConnectedToCluster()) {
throw new IllegalClusterResourceRequestException("Only a node connected to a cluster can process the request.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.GET, getClusterCoordinatorNode());
}
final ClusterDTO dto = serviceFacade.getCluster();
// create entity
final ClusterEntity entity = new ClusterEntity();
entity.setCluster(dto);
// generate the response
return generateOkResponse(entity).build();
}
/**
* Gets the contents of the specified node in this NiFi cluster.
*
* @param id The node id.
* @return A nodeEntity.
*/
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("cluster/nodes/{id}")
@ApiOperation(
value = "Gets a node in the cluster",
response = NodeEntity.class,
authorizations = {
@Authorization(value = "Read - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 404, message = "The specified resource could not be found."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response getNode(
@ApiParam(
value = "The node id.",
required = true
)
@PathParam("id") String id) {
authorizeController(RequestAction.READ);
// ensure connected to the cluster
if (!isConnectedToCluster()) {
throw new IllegalClusterResourceRequestException("Only a node connected to a cluster can process the request.");
}
if (isReplicateRequest()) {
return replicate(HttpMethod.GET, getClusterCoordinatorNode());
}
// get the specified relationship
final NodeDTO dto = serviceFacade.getNode(id);
// create the response entity
final NodeEntity entity = new NodeEntity();
entity.setNode(dto);
// generate the response
return generateOkResponse(entity).build();
}
/**
* Updates the contents of the specified node in this NiFi cluster.
*
* @param id The id of the node
* @param nodeEntity A nodeEntity
* @return A nodeEntity
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("cluster/nodes/{id}")
@ApiOperation(
value = "Updates a node in the cluster",
response = NodeEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 404, message = "The specified resource could not be found."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response updateNode(
@ApiParam(
value = "The node id.",
required = true
)
@PathParam("id") String id,
@ApiParam(
value = "The node configuration. The only configuration that will be honored at this endpoint is the status.",
required = true
) NodeEntity nodeEntity) {
authorizeController(RequestAction.WRITE);
// ensure connected to the cluster
if (!isConnectedToCluster()) {
throw new IllegalClusterResourceRequestException("Only a node connected to a cluster can process the request.");
}
if (nodeEntity == null || nodeEntity.getNode() == null) {
throw new IllegalArgumentException("Node details must be specified.");
}
// get the request node
final NodeDTO requestNodeDTO = nodeEntity.getNode();
if (!id.equals(requestNodeDTO.getNodeId())) {
throw new IllegalArgumentException(String.format("The node id (%s) in the request body does "
+ "not equal the node id of the requested resource (%s).", requestNodeDTO.getNodeId(), id));
}
if (isReplicateRequest()) {
return replicateToCoordinator(HttpMethod.PUT, nodeEntity);
}
// update the node
final NodeDTO node = serviceFacade.updateNode(requestNodeDTO);
// create the response entity
NodeEntity entity = new NodeEntity();
entity.setNode(node);
// generate the response
return generateOkResponse(entity).build();
}
/**
* Removes the specified from this NiFi cluster.
*
* @param id The id of the node
* @return A nodeEntity
*/
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("cluster/nodes/{id}")
@ApiOperation(
value = "Removes a node from the cluster",
response = NodeEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 404, message = "The specified resource could not be found."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response deleteNode(
@ApiParam(
value = "The node id.",
required = true
)
@PathParam("id") String id) {
authorizeController(RequestAction.WRITE);
// ensure connected to the cluster
if (!isConnectedToCluster()) {
throw new IllegalClusterResourceRequestException("Only a node connected to a cluster can process the request.");
}
if (isReplicateRequest()) {
return replicateToCoordinator(HttpMethod.DELETE, getRequestParameters());
}
serviceFacade.deleteNode(id);
// create the response entity
final NodeEntity entity = new NodeEntity();
// generate the response
return generateOkResponse(entity).build();
}
// -------
// history
// -------
/**
* Deletes flow history from the specified end date.
*
* @param endDate The end date for the purge action.
* @return A historyEntity
*/
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("history")
@ApiOperation(
value = "Purges history",
response = HistoryEntity.class,
authorizations = {
@Authorization(value = "Write - /controller", type = "")
}
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
@ApiResponse(code = 401, message = "Client could not be authenticated."),
@ApiResponse(code = 403, message = "Client is not authorized to make this request."),
@ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.")
}
)
public Response deleteHistory(
@Context final HttpServletRequest httpServletRequest,
@ApiParam(
value = "Purge actions before this date/time.",
required = true
)
@QueryParam("endDate") DateTimeParameter endDate) {
// ensure the end date is specified
if (endDate == null) {
throw new IllegalArgumentException("The end date must be specified.");
}
// Note: History requests are not replicated throughout the cluster and are instead handled by the nodes independently
return withWriteLock(
serviceFacade,
new EndDateEntity(endDate.getDateTime()),
lookup -> {
authorizeController(RequestAction.WRITE);
},
null,
(endDateEntity) -> {
// purge the actions
serviceFacade.deleteActions(endDateEntity.getEndDate());
// generate the response
return generateOkResponse(new HistoryEntity()).build();
}
);
}
private class EndDateEntity extends Entity {
final Date endDate;
public EndDateEntity(Date endDate) {
this.endDate = endDate;
}
public Date getEndDate() {
return endDate;
}
}
// setters
public void setServiceFacade(final NiFiServiceFacade serviceFacade) {
this.serviceFacade = serviceFacade;
}
public void setReportingTaskResource(final ReportingTaskResource reportingTaskResource) {
this.reportingTaskResource = reportingTaskResource;
}
public void setControllerServiceResource(final ControllerServiceResource controllerServiceResource) {
this.controllerServiceResource = controllerServiceResource;
}
public void setAuthorizer(final Authorizer authorizer) {
this.authorizer = authorizer;
}
}
| {
"content_hash": "dc417af962bdcd0dae6c862ef3fdb383",
"timestamp": "",
"source": "github",
"line_count": 774,
"max_line_length": 192,
"avg_line_length": 42.03488372093023,
"alnum_prop": 0.6158598432457354,
"repo_name": "jjmeyer0/nifi",
"id": "97cb4c954e05a5411e4cac0823480b9bead8df66",
"size": "33336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ControllerResource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18455"
},
{
"name": "CSS",
"bytes": "219356"
},
{
"name": "Clojure",
"bytes": "3993"
},
{
"name": "GAP",
"bytes": "30012"
},
{
"name": "Groovy",
"bytes": "1239078"
},
{
"name": "HTML",
"bytes": "324337"
},
{
"name": "Java",
"bytes": "26404436"
},
{
"name": "JavaScript",
"bytes": "2568964"
},
{
"name": "Lua",
"bytes": "983"
},
{
"name": "Protocol Buffer",
"bytes": "2154"
},
{
"name": "Python",
"bytes": "17954"
},
{
"name": "Ruby",
"bytes": "8028"
},
{
"name": "Shell",
"bytes": "42505"
},
{
"name": "XSLT",
"bytes": "5681"
}
],
"symlink_target": ""
} |
import {
configureStore,
getDefaultMiddleware,
isPlain,
ThunkAction,
ThunkDispatch,
Action,
SerializableStateInvariantMiddlewareOptions
} from '@reduxjs/toolkit'
import type { CryptoStore } from 'hoodie-plugin-store-crypto'
import rootReducer from '../bundles'
import configureReactors from './configureReactors'
import { createLocalDB, createCryptoStore, createRemoteDB } from './db'
import { proxyFetch, fetchLLSD } from './llsdFetch'
import type Circuit from '../network/circuit'
export type RootState = ReturnType<typeof rootReducer>
export type AppDispatch = ThunkDispatch<RootState, ExtraArguments, Action<string>>
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
ExtraArguments,
Action<string>
>
export interface LLSDResponse extends Response {
llsd: <T = any>() => Promise<T>
}
export interface ExtraArguments {
cryptoStore: CryptoStore,
db: PouchDB.Database,
remoteDB: PouchDB.Database | null,
/**
* Create the local and/or remote databases.
*/
createDatabases: (args: CreateDatabasesArgs) => CreateDatabasesResult,
/**
* Fetch for grids.
*/
proxyFetch: (url: string | URL, options?: RequestInit) => Promise<Response>,
/**
* Fetch for grids, but data is encoded in LLSD and a llsd decode function exists on return.
*/
fetchLLSD: (url: string | URL, options?: RequestInit) => Promise<LLSDResponse>,
/**
* Functions which are called when an avatar logs out.
*/
onAvatarLogout: (() => void)[],
/**
* null if no avatar is logged in.
*/
circuit: Circuit | null
}
export interface CreateDatabasesArgs {
local?: boolean,
remote?: string,
skipSetup?: boolean
}
export interface CreateDatabasesResult {
local: PouchDB.Database | null,
remote: PouchDB.Database | null
}
/**
* Create Redux-Store with local db, remote db and more.
*/
export default function createStore (preloadedState?: RootState) {
const extraArgument = createExtraArgument(({ local, remote, skipSetup }) => {
const result: CreateDatabasesResult = { local: null, remote: null }
if (local) {
result.local = createLocalDB()
}
if (remote) {
result.remote = createRemoteDB(remote, skipSetup)
}
return result
})
const store = createStoreCore(preloadedState, extraArgument)
extraArgument.proxyFetch = (url: string | URL, options?: RequestInit) => proxyFetch(
store.getState,
url,
options
)
extraArgument.fetchLLSD = (url: string | URL, options?: RequestInit) => {
const result = fetchLLSD(store.getState, url.toString(), options)
return (result as any) as Promise<LLSDResponse>
}
configureReactors(store)
if (process.env.NODE_ENV !== 'production') {
;(window as any)['devStore'] = store
;(window as any)['localDB'] = extraArgument.db
;(window as any)['remoteDB'] = extraArgument.remoteDB
;(window as any)['cryptoStore'] = extraArgument.cryptoStore
if ((module as any).hot) {
// Enable Webpack hot module replacement for reducers
(module as any).hot.accept('../bundles', () => {
store.replaceReducer(rootReducer)
})
}
}
return store
}
/**
* Create the thunk extraArgument.
* It adds the localDB and remoteDB to it, but does not setup proxyFetch or fetchLLSD.
*/
export function createExtraArgument (
createDatabases: (args: CreateDatabasesArgs) => CreateDatabasesResult
): ExtraArguments {
const { local, remote } = createDatabases({ local: true, remote: '_users', skipSetup: true })
const placeholder = () => Promise.reject(new Error('unimplemented'))
const extraArgument = {
cryptoStore: createCryptoStore(local),
db: local!,
remoteDB: remote!,
createDatabases,
// Must be added after the store was created
proxyFetch: placeholder,
// Must be added after the store was created
fetchLLSD: placeholder,
onAvatarLogout: [],
circuit: null // will be set on login
}
return extraArgument
}
/**
* Core of the store creation.
*/
export function createStoreCore (
preloadedState: RootState | undefined,
extraArgument: ExtraArguments
) {
const serializableCheck: SerializableStateInvariantMiddlewareOptions = {
isSerializable: value => isPlain(value) || value instanceof Uint8Array
}
const middleware = getDefaultMiddleware({
thunk: {
extraArgument
},
// Allow Uint8Array (Buffer) and AvatarName to be in actions and the state.
serializableCheck
})
const store = configureStore({
reducer: rootReducer,
middleware,
// enable devTools in development. Please use the Redux DevTools Extension
// http://extension.remotedev.io/
devTools: process.env.NODE_ENV !== 'production',
preloadedState
})
return store
}
| {
"content_hash": "499e185f1ad8f09663f7ae00fd3bbfce",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 95,
"avg_line_length": 28.76969696969697,
"alnum_prop": 0.6989677691173373,
"repo_name": "Terreii/andromeda-viewer",
"id": "679c3794ffcfb92ab531d5c6c13b3df8702e6298",
"size": "4747",
"binary": false,
"copies": "1",
"ref": "refs/heads/latest",
"path": "src/store/configureStore.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1865"
},
{
"name": "HTML",
"bytes": "1597"
},
{
"name": "JavaScript",
"bytes": "629814"
},
{
"name": "TypeScript",
"bytes": "138244"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: ferdi
* Date: 06.11.15
* Time: 17:06
*/
namespace Jimtonic\RedisLockHandler;
class MyBlamedLockable extends MyLockable implements BlamedLockableInterface
{
/** @var string */
private $username;
/**
* MyBlamedLockable constructor.
* @param string $lockname
* @param string $username
*/
public function __construct($lockname, $username)
{
parent::__construct($lockname);
$this->username = $username;
}
/**
* @return string
*/
public function getUsername()
{
return $this->username;
}
} | {
"content_hash": "88822d8ed25a2e5126be4e4f6220cb05",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 76,
"avg_line_length": 17.47222222222222,
"alnum_prop": 0.5993640699523053,
"repo_name": "jimtonic/redis-lock-handler",
"id": "c3dccf292d761ac54311dcd6cace121463d7018f",
"size": "629",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/_files/MyBlamedLockable.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "15601"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
F. B. Forbes & W. B. Hemsley, J. Linn. Soc. , Bot. 26:178. 1890
#### Original name
null
### Remarks
null | {
"content_hash": "b02590ff3158c655b190af8b456da586",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 63,
"avg_line_length": 14.23076923076923,
"alnum_prop": 0.6594594594594595,
"repo_name": "mdoering/backbone",
"id": "6e65aea4011f2fa007aa066f1521b46b16cf5e3c",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Scrophularia/Scrophularia ningpoensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ES5Harness.registerTest( {
id: "13.1-3-6-s",
path: "TestCases/chapter13/13.1/13.1-3-6-s.js",
description: "SyntaxError if eval used as function identifier in function expression in strict code",
test: function testcase()
{
try
{
eval("'use strict' ;(function eval(){});");
return false
}
catch (e) { e instanceof SyntaxError }
},
precondition: function prereq() {
return fnSupportsStrict();
}
});
| {
"content_hash": "b1c99325e6bb681734b0c5c064903cef",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 101,
"avg_line_length": 19.318181818181817,
"alnum_prop": 0.6635294117647059,
"repo_name": "techdragon/Js2Py",
"id": "a6d9087c0f4a09b17c2dc149535024fac6daf7f1",
"size": "1986",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/TestCases/chapter13/13.1/13.1-3-6-s.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2603881"
},
{
"name": "Python",
"bytes": "567425"
}
],
"symlink_target": ""
} |
using System.Windows.Controls;
using Accelerider.Windows.Infrastructure.Mvvm;
using Accelerider.Windows.Views.Authentication;
using MaterialDesignThemes.Wpf;
using Unity;
namespace Accelerider.Windows.ViewModels.Authentication
{
public class AuthenticationWindowViewModel : ViewModelBase, IViewLoadedAndUnloadedAware<AuthenticationWindow>, INotificable
{
private bool _isLoading;
private TabItem _signInTabItem;
public AuthenticationWindowViewModel(IUnityContainer container) : base(container)
{
EventAggregator.GetEvent<MainWindowLoadingEvent>().Subscribe(e => IsLoading = e);
EventAggregator.GetEvent<SignUpSuccessEvent>().Subscribe(signUpInfo => _signInTabItem.IsSelected = true); // It cannot be done by binding the IsSelected property, it will cause an animation error.
/*
* There are some puzzle here:
* 1. If SignInTabItem.IsSelected is not directly set to "True" (e.g. Set value by Binding), a style error will occur in AuthenticationWindow UI;
* 2. If SignInTabItem.IsSelected is first set to "True" in Xaml, then binding to a property, (e.g. SetBinding(TabItem.IsSelectedProperty, XXX) in OnLoaded or code behind)
* which can avoid the error in 1. But an animation error will occur when loading SignInView every time.
*/
}
public bool IsLoading
{
get => _isLoading;
set => SetProperty(ref _isLoading, value);
}
public void OnLoaded(AuthenticationWindow view)
{
_signInTabItem = view.SignInTabItem;
}
public void OnUnloaded(AuthenticationWindow view) { }
public ISnackbarMessageQueue GlobalMessageQueue { get; set; }
}
}
| {
"content_hash": "bf44d83ff81e3f169becf04c234ed906",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 208,
"avg_line_length": 41.74418604651163,
"alnum_prop": 0.6841225626740947,
"repo_name": "ResourceHunter/BaiduPanDownloadWpf",
"id": "ade36e5b2d7c00f4f82c4ec9fe123f0b60c5b6fe",
"size": "1797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Accelerider.Windows/ViewModels/Authentication/AuthenticationWindow.vm.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "224794"
}
],
"symlink_target": ""
} |
<?php
class SearchTest extends PHPUnit_Framework_Testcase
{
public function testCommand()
{
$command = new SearchCommand();
$this->markTestIncomplete();
}
}
| {
"content_hash": "5c0972ec9f372e31a3a5a809ce30987c",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 51,
"avg_line_length": 18.6,
"alnum_prop": 0.6397849462365591,
"repo_name": "sinergia/project-console",
"id": "8b0806399dcdc93450e0627572a9234a32c74b22",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/SearchTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2907"
},
{
"name": "Ruby",
"bytes": "226"
},
{
"name": "Shell",
"bytes": "328"
}
],
"symlink_target": ""
} |
package org.scalarules.dsl.nl.datum
import org.scalarules.finance.nl.{Bedrag, Percentage}
import org.scalarules.engine.{Context, FactEngine}
import org.scalatest.{FlatSpec, Matchers}
import org.scalarules.dsl.nl.grammar._
import org.scalarules.facts.SingularFact
class DatumImplicitsTest extends FlatSpec with Matchers {
val sutDatumA = new SingularFact[Datum]("sutDatumA")
val sutDatumB = new SingularFact[Datum]("sutDatumB")
val result = new SingularFact[Boolean]("result")
val expected = new SingularFact[Boolean]("expected")
it should "compile" in {
Gegeven(sutDatumA < sutDatumB)
Gegeven(sutDatumA <= sutDatumB)
Gegeven(sutDatumA > sutDatumB)
Gegeven(sutDatumA >= sutDatumB)
Gegeven(sutDatumA is sutDatumB)
}
it should "compare dates" in {
check( Gegeven(sutDatumA < sutDatumB), true, false, false )
}
def check(gegeven: GegevenWord, expectSmaller: Boolean, expectEqual: Boolean, expectGreater: Boolean): Unit = {
val accumulator: BerekeningAccumulator = gegeven Bereken( result ) is( expected )
val resultContext: Context = FactEngine.runNormalDerivations(Map(sutDatumA -> "01-01-2015".datum, sutDatumB -> "02-01-2015".datum), accumulator.derivations)
val evaluatedResult: Boolean = result.toEval(resultContext).getOrElse(false)
}
}
| {
"content_hash": "e1ef0b347986a4ef4e2c26ebabaff476",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 160,
"avg_line_length": 36.22222222222222,
"alnum_prop": 0.7484662576687117,
"repo_name": "scala-rules/rule-engine",
"id": "5a66fbf5cfad162a019542c048a7610a84273961",
"size": "1304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/src/test/scala/org/scalarules/dsl/nl/datum/DatumImplicitsTest.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "257566"
}
],
"symlink_target": ""
} |
class Matterhorn::Endpoint::Ingest < Matterhorn::Endpoint
# -------------------------------------------------------------------------- endpoint methodes ---
def addAttachment(file, flavor)
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
@media_pkg_local.add_attachment(file, flavor) if @media_pkg_local
begin
spit_response http_endpoint_client.post(
"ingest/addAttachment",
{ 'flavor' => flavor,
'mediaPackage' => @media_pkg_xml_remote,
'BODY' => file
}
)
@media_pkg_xml_remote = response_body
rescue => ex
exception_handler('addAttachment', ex, {
400 => "Media package not valid! / media package:\n#{@media_pkg_xml_remote}"
}
)
raise ex
end
@media_pkg_xml_remote
end
def addCatalog(file, flavor)
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
@media_pkg_local.add_catalog(file, flavor) if @media_pkg_local
begin
split_response http_endpoint_client.post(
"ingest/addCatalog",
{ 'flavor' => flavor,
'mediaPackage' => @media_pkg_xml_remote,
'BODY' => file
}
)
@media_pkg_xml_remote = response_body
rescue => ex
exception_handler('addCatalog', ex, {
400 => "Media package not valid! / media package:\n#{@media_pkg_xml_remote}"
}
)
raise ex
end
@media_pkg_xml_remote
end
def addDCCatalog(dublin_core)
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
@media_pkg_local.add_dc_catalog(dublin_core) if @media_pkg_local
begin
split_response http_endpoint_client.post(
"ingest/addDCCatalog",
{ 'flavor' => 'dublincore/episode',
'mediaPackage' => @media_pkg_xml_remote,
'dublinCore' => dublin_core
}
)
@media_pkg_xml_remote = response_body
rescue => ex
exception_handler('create', ex, {
400 => "Media package not valid! / media package:\n#{@media_pkg_xml_remote}"
}
)
raise ex
end
@media_pkg_xml_remote
end
HTTP_PROTOCOL_RE = /^https?:/
def addTrack(file_or_url, flavor)
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
@media_pkg_local.add_track(file_or_url, flavor) if @media_pkg_local
begin
if HTTP_PROTOCOL_RE =~ file_or_url
split_response http_endpoint_client.post(
"ingest/addTrack",
{ 'flavor' => flavor,
'mediaPackage' => @media_pkg_xml_remote,
'url' => file_or_url
}
)
else
split_response http_endpoint_client.post(
"ingest/addTrack",
{ 'flavor' => flavor,
'mediaPackage' => @media_pkg_xml_remote,
'BODY' => file_or_url
}
)
end
@media_pkg_xml_remote = response_body
rescue => ex
exception_handler('addTrack', ex, {
400 => "Media package not valid! / media package:\n#{@media_pkg_xml_remote}"
}
)
raise ex
end
@media_pkg_xml_remote
end
# Create a media package on the matterhorn server.
# If the source_path to the source folder of uploaded items for that media package is given,
# then a local media description file 'manifest.xml' will be automaticaly saved in that folder.
#
def createMediaPackage(source_path = nil)
if @media_pkg_xml_remote then raise(Matterhorn::Error, "A media package is allready created!"); end
@media_pkg_local = if source_path
Matterhorn::MediaPackage.new(nil, {:path => source_path})
else
nil
end
begin
split_response http_endpoint_client.get(
"ingest/createMediaPackage"
)
@media_pkg_xml_remote = response_body
rescue => ex
exception_handler('createMediaPackage', ex, {})
raise ex
end
@media_pkg_xml_remote
end
def ingest(wdID = 'full', options = {})
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
@media_pkg_local.save if @media_pkg_local
options['mediaPackage'] = @media_pkg_xml_remote
begin
split_response http_endpoint_client.post(
"ingest/ingest/#{wdID}",
options
)
@workflow_inst = response_body
rescue => ex
exception_handler('create', ex, {
400 => "Media package not valid! / media package:\n#{@media_pkg_xml_remote}"
}
)
raise ex
end
workflow_instance
end
def media_package_identifier
return nil unless @media_pkg_xml_remote
Matterhorn::MediaPackage.new(@media_pkg_xml_remote).identifier
end
# ---------------------------------------------------------------------------- helper methodes ---
def media_package(kind = 'local')
unless @media_pkg_xml_remote then raise(Matterhorn::Error, "No media package is available!"); end
if kind == 'local' && @media_pkg_local
return @media_pkg_local
elsif @media_pkg_xml_remote
Matterhorn::MediaPackage.new(@media_pkg_xml_remote)
else
nil
end
end
def setTitle(title)
dublin_core = <<DUBLIN_CORE
<?xml version="1.0" encoding="UTF-8"?>
<dublincore xmlns="http://www.opencastproject.org/xsd/1.0/dublincore/" xmlns:dcterms="http://purl.org/dc/terms/">
<dcterms:title>#{title.encode(:xml => :text)}</dcterms:title>
</dublincore>
DUBLIN_CORE
addDCCatalog(dublin_core)
end
def workflow_instance
@workflow_inst ? Matterhorn::WorkflowInstance.new(@workflow_inst) : nil
end
end # --------------------------------------------------------- end Matterhorn::Endpoint::Ingest ---
| {
"content_hash": "8fb8f6556f50db0f6f89cbe95b8cda42",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 113,
"avg_line_length": 30.96842105263158,
"alnum_prop": 0.5863358259687288,
"repo_name": "Manfred/matterhorn_whymper",
"id": "725f622c6df86e91f5906f5f718470a311475b90",
"size": "5986",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/matterhorn/endpoint/ingest.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "61840"
},
{
"name": "Shell",
"bytes": "2528"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.EnterpriseServices;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Codebase;
public partial class AdminPannel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (SessionManager.Instance.UserRights == UserRights.Guest)
FormsAuthentication.RedirectToLoginPage();
if (!IsPostBack)
{
string command = Request.QueryString["command"];
string type = Request.QueryString["type"];
int id = !string.IsNullOrEmpty(Request.QueryString["id"]) ? Convert.ToInt32(Request.QueryString["id"]) : -1;
if (id <= 0 || string.IsNullOrEmpty(command))
Response.Redirect("Default.aspx");
lblCommand.Text = command;
lblID.Text = id.ToString();
lbltype.Text = type;
if (command == "edit")
{
var user = dbContext.Instance.Users.FirstOrDefault(x => x.UserID == id);
if (user != null)
{
txtFirstName.Text = user.FirstName;
txtLastName.Text = user.LastName;
txtUserName.Text = user.Username;
txtAddress.Text = user.Address;
txtPhone.Text = user.Phone;
txtEmail.Text = user.Email;
ddlAccessLevel.SelectedIndex = user.AccessLevel - 1;
type = user.IsSubUser ? "user" : "client";
lbltype.Text = type;
}
}
ResolveControls(type, command);
}
}
private void ResolveControls(string type, string command)
{
if (type.Equals("user") && command.Equals("edit"))
{
lblTitle.Text = "Edit user info";
btnEdit.Text = "Save user info";
btnAdd.Visible = false;
}
else if (type.Equals("client") && command.Equals("edit"))
{
lblTitle.Text = "Edit client info";
btnEdit.Text = "Save client info";
btnAdd.Visible = false;
}
else if (type.Equals("user") && command.Equals("add"))
{
lblTitle.Text = "Add new user";
btnAdd.Text = "Add user";
btnEdit.Visible = false;
}
else if (type.Equals("client") && command.Equals("add"))
{
lblTitle.Text = "Add new client";
btnAdd.Text = "Add client";
btnEdit.Visible = false;
}
if (SessionManager.Instance.UserRights == UserRights.MonoUser
|| SessionManager.Instance.UserRights == UserRights.User)
{
pAccessLevel.Visible = false;
pMultiUser.Visible = false;
}
else if (SessionManager.Instance.UserRights == UserRights.MultiUser)
{
if (command.Equals("add"))
pMultiUser.Visible = false;
else
{
pMultiUser.Visible = false;
if (type.Equals("client"))
pAccessLevel.Visible = false;
}
}
}
protected void AddButtonClick(object sender, EventArgs e)
{
try
{
User user = new User();
if (user != null)
{
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Username = txtUserName.Text;
user.Password = PasswordHash.CreateHash(txtPassword.Text);
user.Email = txtEmail.Text;
user.Phone = txtPhone.Text;
user.Address = txtAddress.Text;
user.AccessLevel = Convert.ToInt32(ddlAccessLevel.SelectedItem.Value);
if (lbltype.Text == "user")
{
user.IsMultiUser = false;
user.IsSubUser = true;
}
else if (lbltype.Text == "client")
{
user.IsMultiUser = cbMultiUser.Checked;
user.IsSubUser = false;
}
user.IsAdmin = false;
user.OwnerID = Convert.ToInt32(lblID.Text);
dbContext.Instance.Users.InsertOnSubmit(user);
dbContext.Instance.SubmitChanges();
lblError.Text = "Info successfully changed!";
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
protected void EditButtonClick(object sender, EventArgs e)
{
//if (!SessionManager.Instance.IsAdmin.HasValue || !SessionManager.Instance.IsAdmin.Value)
// FormsAuthentication.RedirectToLoginPage();
try
{
User user =
dbContext.Instance.Users.FirstOrDefault(
x => x.UserID == Convert.ToInt32(lblID.Text));
if (user != null)
{
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Username = txtUserName.Text;
user.Password = PasswordHash.CreateHash(txtPassword.Text);
user.Email = txtEmail.Text;
user.Phone = txtPhone.Text;
user.Address = txtAddress.Text;
if (SessionManager.Instance.UserRights == UserRights.Admin ||
SessionManager.Instance.UserRights == UserRights.MultiUser)
user.AccessLevel = Convert.ToInt32(ddlAccessLevel.SelectedItem.Value);
if (!user.IsSubUser)
user.IsMultiUser = cbMultiUser.Checked;
dbContext.Instance.SubmitChanges();
lblError.Text = "Info successfully changed!";
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
protected void BackButtonClick(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
} | {
"content_hash": "3fba2704f0d6c85bc9b40760304eb496",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 120,
"avg_line_length": 33.17297297297297,
"alnum_prop": 0.5230568681766335,
"repo_name": "misha-bilous/SecurityWebSite",
"id": "81116dddac1b39ade71772a7b481b294062fbc51",
"size": "6139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecurityWebSite/AdminPannel.aspx.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "19870"
},
{
"name": "C#",
"bytes": "70791"
},
{
"name": "CSS",
"bytes": "2117"
},
{
"name": "HTML",
"bytes": "5127"
},
{
"name": "JavaScript",
"bytes": "146843"
}
],
"symlink_target": ""
} |
import {Widget} from 'app/types';
import {getChartDataByDay, getChartDataForWidget} from 'app/views/discover/result/utils';
import {WIDGET_DISPLAY} from '../constants';
import {isTimeSeries} from './isTimeSeries';
/**
* Get data function based on widget properties
*/
export function getChartDataFunc({
queries,
type,
fieldLabelMap,
}: Widget): [Function, object[]] {
if (queries.discover.some(isTimeSeries)) {
return [
getChartDataByDay,
[
{
allSeries: true,
fieldLabelMap,
},
],
];
}
return [
getChartDataForWidget,
[
{
includePercentages: type === WIDGET_DISPLAY.TABLE,
},
],
];
}
| {
"content_hash": "64d8c290e542195c63f4c77fc61128c6",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 89,
"avg_line_length": 19.38888888888889,
"alnum_prop": 0.6103151862464183,
"repo_name": "beeftornado/sentry",
"id": "d097ea711190a196ba520ec02190b36ec5332fab",
"size": "698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sentry/static/sentry/app/views/dashboards/utils/getChartDataFunc.tsx",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "157195"
},
{
"name": "HTML",
"bytes": "197026"
},
{
"name": "JavaScript",
"bytes": "380379"
},
{
"name": "Makefile",
"bytes": "2832"
},
{
"name": "Python",
"bytes": "6473603"
}
],
"symlink_target": ""
} |
namespace content {
class WebContents;
} // namespace content
// aura::WindowTreeHost implementation used to present web content inside
// web.Frame.
class FrameWindowTreeHost : public aura::WindowTreeHostPlatform {
public:
// |web_contents| must to outlive |FrameWindowTreeHost|.
FrameWindowTreeHost(fuchsia::ui::views::ViewToken view_token,
content::WebContents* web_contents);
~FrameWindowTreeHost() final;
FrameWindowTreeHost(const FrameWindowTreeHost&) = delete;
FrameWindowTreeHost& operator=(const FrameWindowTreeHost&) = delete;
// Creates and returns a ViewRef for the window.
fuchsia::ui::views::ViewRef CreateViewRef();
private:
class WindowParentingClientImpl;
// aura::WindowTreeHostPlatform overrides.
void OnActivationChanged(bool active) final;
void OnWindowStateChanged(ui::PlatformWindowState new_state) final;
fuchsia::ui::views::ViewRef view_ref_;
std::unique_ptr<WindowParentingClientImpl> window_parenting_client_;
content::WebContents* web_contents_;
};
#endif // FUCHSIA_ENGINE_BROWSER_FRAME_WINDOW_TREE_HOST_H_
| {
"content_hash": "fcda31d268c05167ce279f523267ec87",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 73,
"avg_line_length": 34.28125,
"alnum_prop": 0.7575205104831358,
"repo_name": "endlessm/chromium-browser",
"id": "17fe15f5c5ab5c6999093bda80b51acbfd1b4992",
"size": "1472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fuchsia/engine/browser/frame_window_tree_host.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/**
* Routes for express app
*/
import passport from 'passport';
import unsupportedMessage from '../db/unsupportedMessage';
import { passport as passportConfig } from '../db';
export default (app) => {
// user routes
if (passportConfig && passportConfig.google) {
// google auth
// Redirect the user to Google for authentication. When complete, Google
// will redirect the user back to the application at
// /auth/google/return
// Authentication with google requires an additional scope param, for more info go
// here https://developers.google.com/identity/protocols/OpenIDConnect#scope-param
app.get('/auth/google', passport.authenticate('google', {
scope: [
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
]
}));
// Google will redirect the user to this URL after authentication. Finish the
// process by verifying the assertion. If valid, the user will be logged in.
// Otherwise, the authentication has failed.
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/user',
failureRedirect: '/'
})
);
app.get('/user/user-info', checkAuthentication, (req, res) => {
res.json(req.user);
});
app.get('/logout', (req, res) => {
req.session.destroy();
req.logout();
res.redirect("/");
});
app.post('/save-presentation', (req, res) => {
});
function checkAuthentication(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}
}
}
};
| {
"content_hash": "3829166990b89d4150a46f3155050012",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 86,
"avg_line_length": 27.683333333333334,
"alnum_prop": 0.621312462372065,
"repo_name": "gajananpp/DS",
"id": "b4be4e9145da73ec9c0c86806b9994b51af0c749",
"size": "1661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/init/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9506"
},
{
"name": "JavaScript",
"bytes": "125884"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>topology: 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.7.1 / topology - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
topology
<small>
8.9.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-09 15:43:56 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-09 15:43:56 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.7.1 Formal proof management system.
num 0 The Num library for arbitrary-precision integer and rational arithmetic
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
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/topology"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Topology"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
"coq-zorns-lemma" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: topology"
"keyword: filters"
"keyword: nets"
"keyword: metric spaces"
"keyword: real analysis"
"keyword: Urysohn's lemma"
"keyword: Tietze extension theorem"
"category: Mathematics/Real Calculus and Topology"
]
authors: [
"Daniel Schepler <dschepler@gmail.com>"
]
bug-reports: "https://github.com/coq-contribs/topology/issues"
dev-repo: "git+https://github.com/coq-contribs/topology.git"
synopsis: "General Topology"
description: """
This library develops some of the basic concepts and results of general topology."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/topology/archive/v8.9.0.tar.gz"
checksum: "md5=c8b3a305d79561f5c28d7a76d50418ca"
}
</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-topology.8.9.0 coq.8.7.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1).
The following dependencies couldn't be met:
- coq-topology -> coq >= 8.9
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-topology.8.9.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">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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": "847b7ebf2f6b5733623095a8cd574e3c",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 157,
"avg_line_length": 40.367231638418076,
"alnum_prop": 0.5456962911126662,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "6d7fa26a940bf99be80278f51133da95210c6366",
"size": "7147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.7.1/topology/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.antlr.v4.tool.interp;
import org.antlr.v4.Tool;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNState;
import org.antlr.v4.runtime.atn.DecisionState;
import org.antlr.v4.runtime.atn.ParserATNSimulator;
import org.antlr.v4.runtime.atn.PredictionContextCache;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.Nullable;
import org.antlr.v4.tool.Grammar;
public class ParserInterpreter {
public static class DummyParser extends Parser {
public final ATN atn;
public final DFA[] decisionToDFA; // not shared for interp
public final PredictionContextCache sharedContextCache =
new PredictionContextCache();
public Grammar g;
public DummyParser(Grammar g, ATN atn, TokenStream input) {
super(input);
this.g = g;
this.atn = atn;
this.decisionToDFA = new DFA[atn.getNumberOfDecisions()];
for (int i = 0; i < decisionToDFA.length; i++) {
decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);
}
}
@Override
public String getGrammarFileName() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public String[] getRuleNames() {
return g.rules.keySet().toArray(new String[g.rules.size()]);
}
@Override
public String[] getTokenNames() {
return g.getTokenNames();
}
@Override
public ATN getATN() {
return atn;
}
}
protected Grammar g;
public DummyParser parser;
protected ParserATNSimulator atnSimulator;
protected TokenStream input;
public ParserInterpreter(@NotNull Grammar g) {
this.g = g;
}
public ParserInterpreter(@NotNull Grammar g, @NotNull TokenStream input) {
Tool antlr = new Tool();
antlr.process(g,false);
parser = new DummyParser(g, g.atn, input);
atnSimulator =
new ParserATNSimulator(parser, g.atn, parser.decisionToDFA,
parser.sharedContextCache);
}
public int adaptivePredict(@NotNull TokenStream input, int decision,
@Nullable ParserRuleContext outerContext)
{
return atnSimulator.adaptivePredict(input, decision, outerContext);
}
public int matchATN(@NotNull TokenStream input,
@NotNull ATNState startState)
{
if (startState.getNumberOfTransitions() == 1) {
return 1;
}
else if (startState instanceof DecisionState) {
return atnSimulator.adaptivePredict(input, ((DecisionState)startState).decision, null);
}
else if (startState.getNumberOfTransitions() > 0) {
return 1;
}
else {
return -1;
}
}
public ParserATNSimulator getATNSimulator() {
return atnSimulator;
}
}
| {
"content_hash": "3d48e762f6c629ecbbe7621a8a0c4995",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 90,
"avg_line_length": 26.184466019417474,
"alnum_prop": 0.731924360400445,
"repo_name": "deveshg/antlr4",
"id": "ecf1a78c5a91d30db9e0a830668c30948d0d96a1",
"size": "4247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tool/src/org/antlr/v4/tool/interp/ParserInterpreter.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ANTLR",
"bytes": "64300"
},
{
"name": "GAP",
"bytes": "108293"
},
{
"name": "Java",
"bytes": "2186597"
}
],
"symlink_target": ""
} |
<!--###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################-->
<?xml version="1.0"?>
<package>
<name>px2_camera_image</name>
<version>0.0.0</version>
<description>The px2_camera_image package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
<maintainer email="zhengchao04@baidu.com">zhengchao04</maintainer>
<!-- One license tag required, multiple allowed, one license per tag -->
<!-- Commonly used license strings: -->
<!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
<license>BSD</license>
<!-- Url tags are optional, but multiple are allowed, one per tag -->
<!-- Optional attribute type can be: website, bugtracker, or repository -->
<!-- Example: -->
<!-- <url type="website">http://wiki.ros.org/px2_camera_image</url> -->
<!-- Author tags are optional, multiple are allowed, one per tag -->
<!-- Authors do not have to be maintainers, but could be -->
<!-- Example: -->
<!-- <author email="jane.doe@example.com">Jane Doe</author> -->
<!-- The *_depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
<!-- Use run_depend for packages you need at runtime: -->
<!-- <run_depend>message_runtime</run_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_depend> -->
<buildtool_depend>catkin</buildtool_depend>
<build_depend>cv_bridge</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>rospy</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<run_depend>cv_bridge</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>rospy</run_depend>
<run_depend>sensor_msgs</run_depend>
<run_depend>std_msgs</run_depend>
<!-- The export tag contains other, unspecified, tags -->
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>
| {
"content_hash": "e8b86fbc91da06f75ddd80dbb388817a",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 83,
"avg_line_length": 40.39473684210526,
"alnum_prop": 0.6469055374592834,
"repo_name": "fy2462/apollo",
"id": "76bdf20984824f997bb2cc04732a3407e8a3f1ca",
"size": "3070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/e2e/online_system/px2_camera_image/package.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3386"
},
{
"name": "C++",
"bytes": "4761775"
},
{
"name": "CMake",
"bytes": "58901"
},
{
"name": "CSS",
"bytes": "20492"
},
{
"name": "HTML",
"bytes": "236"
},
{
"name": "JavaScript",
"bytes": "147786"
},
{
"name": "Python",
"bytes": "640744"
},
{
"name": "Shell",
"bytes": "103381"
},
{
"name": "Smarty",
"bytes": "54938"
}
],
"symlink_target": ""
} |
package io.motown.utils.rest.jax_rs;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public final class GenericExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
}
}
| {
"content_hash": "56df378214c14dec256916cb45ef8524",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 128,
"avg_line_length": 29.5,
"alnum_prop": 0.7669491525423728,
"repo_name": "motown-io/motown",
"id": "d72bde3c48eb7784ea8ce24392ea50c2699c2b94",
"size": "1090",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "utils/rest/src/main/java/io/motown/utils/rest/jax_rs/GenericExceptionMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2759906"
}
],
"symlink_target": ""
} |
<?php
namespace Insider\OrderBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="delivery")
* @ORM\HasLifecycleCallbacks()
*/
class Delivery
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", nullable=false)
*/
protected $title;
/**
* @ORM\Column(type="string", nullable=true)
*/
protected $description;
/**
* @ORM\ManyToOne(targetEntity="Insider\CurrencyBundle\Entity\Currency")
*/
protected $priceCurrency;
/**
* @ORM\OneToMany(targetEntity="Insider\OrderBundle\Entity\DeliveryWeightPrice", mappedBy="delivery", indexBy="delivery", cascade={"persist", "remove"})
*/
protected $weights;
public function __construct()
{
$this->weights = new ArrayCollection();
}
public function getPriceByWeight($orderWeight)
{
/** @var DeliveryWeightPrice $deliveryWeightPrice */
foreach ($this->weights as $deliveryWeightPrice) {
$weight = $deliveryWeightPrice->getWeight();
// For custom weights cannot decide price by order weight
if ($weight->isCustom()) {
continue;
}
if (
($weight->getMinless()
|| (!$weight->getMinless() && $weight->getMinWeight() <= $orderWeight)
)
&& ($weight->getMaxless()
|| (!$weight->getMaxless() && $weight->getMaxWeight() > $orderWeight)
)
) {
return $deliveryWeightPrice->getPrice();
}
}
return null;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getPriceCurrency()
{
return $this->priceCurrency;
}
/**
* @param mixed $priceCurrency
*/
public function setPriceCurrency($priceCurrency)
{
$this->priceCurrency = $priceCurrency;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return ArrayCollection
*/
public function getWeights()
{
return $this->weights;
}
/**
* @param ArrayCollection $weights
*/
public function setWeights(ArrayCollection $weights)
{
$this->weights = $weights;
}
/**
* @param Weight $weight
*/
public function addWeights(DeliveryWeightPrice $weight)
{
$this->weights->add($weight);
}
public function __toString()
{
return $this->title
? $this->title
: 'Новая доставка'
;
}
}
| {
"content_hash": "e180fb0ce358e13fe6c3e9a9fd9b679b",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 156,
"avg_line_length": 20.57396449704142,
"alnum_prop": 0.5355191256830601,
"repo_name": "varloc2000/order",
"id": "308564e71f633b63b632a94192639d34ea99cc95",
"size": "3490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Insider/OrderBundle/Entity/Delivery.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2754"
},
{
"name": "CSS",
"bytes": "226"
},
{
"name": "HTML",
"bytes": "259620"
},
{
"name": "JavaScript",
"bytes": "20517"
},
{
"name": "PHP",
"bytes": "219669"
},
{
"name": "Ruby",
"bytes": "1278"
}
],
"symlink_target": ""
} |
import numpy as np
import os
from os.path import join as pjoin
from numpy.testing import assert_raises, assert_array_equal
from tempfile import mktemp
import nibabel as nib
from surfer import Brain
from surfer import io, utils
from surfer.utils import requires_fsaverage
from mayavi import mlab
subj_dir = utils._get_subjects_dir()
subject_id = 'fsaverage'
std_args = [subject_id, 'lh', 'inflated']
data_dir = pjoin(os.path.split(__file__)[0], '..', '..',
'examples', 'example_data')
small_brain = dict(size=100)
def has_freesurfer():
if 'FREESURFER_HOME' not in os.environ:
return False
else:
return True
requires_fs = np.testing.dec.skipif(not has_freesurfer(),
'Requires FreeSurfer command line tools')
@requires_fsaverage
def test_offscreen():
"""Test offscreen rendering
"""
mlab.options.backend = 'auto'
brain = Brain(*std_args, offscreen=True)
shot = brain.screenshot()
assert_array_equal(shot.shape, (800, 800, 3))
@requires_fsaverage
def test_image():
"""Test image saving
"""
mlab.options.backend = 'auto'
brain = Brain(*std_args, config_opts=small_brain)
tmp_name = mktemp() + '.png'
brain.save_image(tmp_name)
brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
brain.screenshot()
brain.close()
@requires_fsaverage
def test_brains():
"""Test plotting of Brain with different arguments
"""
# testing backend breaks when passing in a figure, so we use 'auto' here
# (shouldn't affect usability, but it makes testing more annoying)
mlab.options.backend = 'auto'
surfs = ['inflated', 'sphere']
hemis = ['lh', 'rh']
curvs = [True, False]
titles = [None, 'Hello']
config_opts = [{}, dict(size=(800, 800))]
figs = [None, mlab.figure()]
subj_dirs = [None, subj_dir]
for surf, hemi, curv, title, co, fig, sd \
in zip(surfs, hemis, curvs, titles, config_opts, figs, subj_dirs):
brain = Brain(subject_id, hemi, surf, curv, title, co, fig, sd)
brain.close()
assert_raises(ValueError, Brain, subject_id, 'lh', 'inflated',
subjects_dir='')
@requires_fsaverage
def test_annot():
"""Test plotting of annot
"""
mlab.options.backend = 'test'
annots = ['aparc', 'aparc.a2005s']
borders = [True, False]
alphas = [1, 0.5]
brain = Brain(*std_args)
for a, b, p in zip(annots, borders, alphas):
brain.add_annotation(a, b, p)
brain.close()
@requires_fsaverage
def test_contour():
"""Test plotting of contour overlay
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
brain.add_contour_overlay(overlay_file)
brain.add_contour_overlay(overlay_file, max=20, n_contours=9,
line_width=2)
brain.contour['surface'].actor.property.line_width = 1
brain.contour['surface'].contour.number_of_contours = 10
brain.close()
@requires_fsaverage
@requires_fs
def test_data():
"""Test plotting of data
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
reg_file = pjoin(data_dir, 'register.dat')
surf_data = io.project_volume_data(mri_file, "lh", reg_file)
brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
brain.close()
@requires_fsaverage
def test_foci():
"""Test plotting of foci
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
coords = [[-36, 18, -3],
[-43, 25, 24],
[-48, 26, -2]]
brain.add_foci(coords, map_surface="white", color="gold")
annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
ids, ctab, names = nib.freesurfer.read_annot(annot_path)
verts = np.arange(0, len(ids))
coords = np.random.permutation(verts[ids == 74])[:10]
scale_factor = 0.7
brain.add_foci(coords, coords_as_verts=True,
scale_factor=scale_factor, color="#A52A2A")
brain.close()
@requires_fsaverage
def test_label():
"""Test plotting of label
"""
mlab.options.backend = 'test'
subject_id = "fsaverage"
hemi = "lh"
surf = "smoothwm"
brain = Brain(subject_id, hemi, surf)
brain.add_label("BA1")
brain.add_label("BA1", color="blue", scalar_thresh=.5)
label_file = pjoin(subj_dir, subject_id,
"label", "%s.MT.label" % hemi)
brain.add_label(label_file)
brain.add_label("BA44", borders=True)
brain.add_label("BA6", alpha=.7)
brain.show_view("medial")
brain.add_label("V1", color="steelblue", alpha=.6)
brain.add_label("V2", color="#FF6347", alpha=.6)
brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
brain.close()
@requires_fsaverage
def test_meg_inverse():
"""Test plotting of MEG inverse solution
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
stc_fname = os.path.join(data_dir, 'meg_source_estimate-lh.stc')
stc = io.read_stc(stc_fname)
data = stc['data']
vertices = stc['vertices']
time = 1e3 * np.linspace(stc['tmin'],
stc['tmin'] + data.shape[1] * stc['tstep'],
data.shape[1])
colormap = 'hot'
time_label = 'time=%0.2f ms'
brain.add_data(data, colormap=colormap, vertices=vertices,
smoothing_steps=10, time=time, time_label=time_label)
brain.set_data_time_index(2)
brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True)
# viewer = TimeViewer(brain)
brain.close()
@requires_fsaverage
def test_morphometry():
"""Test plotting of morphometry
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
brain.add_morphometry("curv")
brain.add_morphometry("sulc", grayscale=True)
brain.add_morphometry("thickness")
brain.close()
@requires_fsaverage
def test_overlay():
"""Test plotting of overlay
"""
mlab.options.backend = 'test'
# basic overlay support
overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
brain = Brain(*std_args)
brain.add_overlay(overlay_file)
brain.overlays["sig"].remove()
brain.add_overlay(overlay_file, min=5, max=20, sign="pos")
sig1 = io.read_scalar_data(pjoin(data_dir, "lh.sig.nii.gz"))
sig2 = io.read_scalar_data(pjoin(data_dir, "lh.alt_sig.nii.gz"))
thresh = 4
sig1[sig1 < thresh] = 0
sig2[sig2 < thresh] = 0
conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
brain.add_overlay(sig1, 4, 30, name="sig1")
brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
brain.overlays["sig1"].pos_bar.visible = False
brain.add_overlay(sig2, 4, 30, name="sig2")
brain.overlays["sig2"].pos_bar.lut_mode = "Blues"
brain.overlays["sig2"].pos_bar.visible = False
brain.add_overlay(conjunct, 4, 30, name="conjunct")
brain.overlays["conjunct"].pos_bar.lut_mode = "Purples"
brain.overlays["conjunct"].pos_bar.visible = False
brain.close()
@requires_fsaverage
def test_probabilistic_labels():
"""Test plotting of probabilistic labels
"""
mlab.options.backend = 'test'
brain = Brain("fsaverage", "lh", "inflated",
config_opts=dict(cortex="low_contrast"))
brain.add_label("BA1", color="darkblue")
brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5)
brain.add_label("BA45", color="firebrick", borders=True)
brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5)
label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label")
prob_field = np.zeros_like(brain._geo.x)
ids, probs = io.read_label(label_file, read_scalars=True)
prob_field[ids] = probs
brain.add_data(prob_field, thresh=1e-5)
brain.data["colorbar"].number_of_colors = 10
brain.data["colorbar"].number_of_labels = 11
brain.close()
@requires_fsaverage
def test_text():
"""Test plotting of text
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
brain.add_text(0.1, 0.1, 'Hello', 'blah')
brain.close()
@requires_fsaverage
def test_animate():
"""Test animation
"""
mlab.options.backend = 'auto'
brain = Brain(*std_args, config_opts=small_brain)
brain.add_morphometry('curv')
tmp_name = mktemp() + '.avi'
brain.animate(["m"] * 3, n_steps=2)
brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
# can't rotate in axial plane
assert_raises(ValueError, brain.animate, ['l', 'd'])
brain.close()
@requires_fsaverage
def test_views():
"""Test showing different views
"""
mlab.options.backend = 'test'
brain = Brain(*std_args)
brain.show_view('lateral')
brain.show_view('m')
brain.show_view('rostral')
brain.show_view('caudal')
brain.show_view('ve')
brain.show_view('frontal')
brain.show_view('par')
brain.show_view('dor')
brain.show_view({'distance': 432})
brain.show_view({'azimuth': 135, 'elevation': 79}, roll=107)
brain.close()
| {
"content_hash": "e67f93de77390d510325da77e7858737",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 78,
"avg_line_length": 30.535117056856187,
"alnum_prop": 0.6225629791894852,
"repo_name": "aestrivex/PySurfer",
"id": "b04443d699428b6eec3cb118283a30e2aeb6de2e",
"size": "9130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "surfer/tests/test_viz.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.camunda.spin.json.tree;
import static org.assertj.core.api.Assertions.assertThat;
import static org.camunda.spin.json.JsonTestConstants.EXAMPLE_JSON_FILE_NAME;
import org.camunda.spin.impl.test.Script;
import org.camunda.spin.impl.test.ScriptTest;
import org.camunda.spin.impl.test.ScriptVariable;
import org.camunda.spin.json.SpinJsonPropertyException;
import org.junit.Test;
/**
* @author Thorben Lindhauer
*
*/
public abstract class JsonTreeRemovePropertyScriptTest extends ScriptTest {
@Test
@Script
@ScriptVariable(name = "input", file = EXAMPLE_JSON_FILE_NAME)
public void shouldRemovePropertyByName() {
Boolean value = script.getVariable("value");
assertThat(value).isFalse();
}
@Test
@Script
@ScriptVariable(name = "input", file = EXAMPLE_JSON_FILE_NAME)
public void shouldRemovePropertyByList() {
Boolean value1 = script.getVariable("value1");
Boolean value2 = script.getVariable("value2");
assertThat(value1).isFalse();
assertThat(value2).isFalse();
}
@Test(expected = SpinJsonPropertyException.class)
@Script(execute = false)
@ScriptVariable(name = "input", file = EXAMPLE_JSON_FILE_NAME)
public void shouldFailWhileRemovingPropertyByName() throws Throwable{
failingWithException();
}
@Test(expected = SpinJsonPropertyException.class)
@Script(execute = false)
@ScriptVariable(name = "input", file = EXAMPLE_JSON_FILE_NAME)
public void shouldFailWhileRemovingPropertyByList() throws Throwable{
failingWithException();
}
}
| {
"content_hash": "879119514a25165c780fde6b34d686bd",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 77,
"avg_line_length": 28.35185185185185,
"alnum_prop": 0.7504898758981058,
"repo_name": "camunda/camunda-spin",
"id": "024a3fa13ff54ed505155e7f38427a25ea6b4efc",
"size": "2338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dataformat-json-jackson/src/test/java/org/camunda/spin/json/tree/JsonTreeRemovePropertyScriptTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "24425"
},
{
"name": "Java",
"bytes": "714834"
},
{
"name": "JavaScript",
"bytes": "41714"
},
{
"name": "Python",
"bytes": "20444"
},
{
"name": "Ruby",
"bytes": "20491"
},
{
"name": "XSLT",
"bytes": "299"
}
],
"symlink_target": ""
} |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createFilterOptions = createFilterOptions;
exports.default = useAutocomplete;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _utils = require("../utils");
/* eslint-disable no-constant-condition */
// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
// Give up on IE11 support for this feature
function stripDiacritics(string) {
return typeof string.normalize !== 'undefined' ? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : string;
}
function createFilterOptions(config = {}) {
const {
ignoreAccents = true,
ignoreCase = true,
limit,
matchFrom = 'any',
stringify,
trim = false
} = config;
return (options, {
inputValue,
getOptionLabel
}) => {
let input = trim ? inputValue.trim() : inputValue;
if (ignoreCase) {
input = input.toLowerCase();
}
if (ignoreAccents) {
input = stripDiacritics(input);
}
const filteredOptions = options.filter(option => {
let candidate = (stringify || getOptionLabel)(option);
if (ignoreCase) {
candidate = candidate.toLowerCase();
}
if (ignoreAccents) {
candidate = stripDiacritics(candidate);
}
return matchFrom === 'start' ? candidate.indexOf(input) === 0 : candidate.indexOf(input) > -1;
});
return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;
};
} // To replace with .findIndex() once we stop IE11 support.
function findIndex(array, comp) {
for (let i = 0; i < array.length; i += 1) {
if (comp(array[i])) {
return i;
}
}
return -1;
}
const defaultFilterOptions = createFilterOptions(); // Number of options to jump in list box when pageup and pagedown keys are used.
const pageSize = 5;
function useAutocomplete(props) {
const {
autoComplete = false,
autoHighlight = false,
autoSelect = false,
blurOnSelect = false,
clearOnBlur = !props.freeSolo,
clearOnEscape = false,
componentName = 'useAutocomplete',
debug = false,
defaultValue = props.multiple ? [] : null,
disableClearable = false,
disableCloseOnSelect = false,
disabledItemsFocusable = false,
disableListWrap = false,
filterOptions = defaultFilterOptions,
filterSelectedOptions = false,
freeSolo = false,
getOptionDisabled,
getOptionLabel: getOptionLabelProp = option => {
var _option$label;
return (_option$label = option.label) !== null && _option$label !== void 0 ? _option$label : option;
},
getOptionSelected = (option, value) => option === value,
groupBy,
handleHomeEndKeys = !props.freeSolo,
id: idProp,
includeInputInList = false,
inputValue: inputValueProp,
multiple = false,
onChange,
onClose,
onHighlightChange,
onInputChange,
onOpen,
open: openProp,
openOnFocus = false,
options,
selectOnFocus = !props.freeSolo,
value: valueProp
} = props;
const id = (0, _utils.unstable_useId)(idProp);
let getOptionLabel = getOptionLabelProp;
if (process.env.NODE_ENV !== 'production') {
getOptionLabel = option => {
const optionLabel = getOptionLabelProp(option);
if (typeof optionLabel !== 'string') {
const erroneousReturn = optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;
console.error(`Material-UI: The \`getOptionLabel\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(option)}.`);
}
return optionLabel;
};
}
const ignoreFocus = React.useRef(false);
const firstFocus = React.useRef(true);
const inputRef = React.useRef(null);
const listboxRef = React.useRef(null);
const [anchorEl, setAnchorEl] = React.useState(null);
const [focusedTag, setFocusedTag] = React.useState(-1);
const defaultHighlighted = autoHighlight ? 0 : -1;
const highlightedIndexRef = React.useRef(defaultHighlighted);
const [value, setValueState] = (0, _utils.useControlled)({
controlled: valueProp,
default: defaultValue,
name: componentName
});
const [inputValue, setInputValueState] = (0, _utils.useControlled)({
controlled: inputValueProp,
default: '',
name: componentName,
state: 'inputValue'
});
const [focused, setFocused] = React.useState(false);
const resetInputValue = (0, _utils.useEventCallback)((event, newValue) => {
let newInputValue;
if (multiple) {
newInputValue = '';
} else if (newValue == null) {
newInputValue = '';
} else {
const optionLabel = getOptionLabel(newValue);
newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
}
if (inputValue === newInputValue) {
return;
}
setInputValueState(newInputValue);
if (onInputChange) {
onInputChange(event, newInputValue, 'reset');
}
});
React.useEffect(() => {
resetInputValue(null, value);
}, [value, resetInputValue]);
const [open, setOpenState] = (0, _utils.useControlled)({
controlled: openProp,
default: false,
name: componentName,
state: 'open'
});
const [inputPristine, setInputPristine] = React.useState(true);
const inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);
const popupOpen = open;
const filteredOptions = popupOpen ? filterOptions(options.filter(option => {
if (filterSelectedOptions && (multiple ? value : [value]).some(value2 => value2 !== null && getOptionSelected(option, value2))) {
return false;
}
return true;
}), // we use the empty string to manipulate `filterOptions` to not filter any options
// i.e. the filter predicate always returns true
{
inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
getOptionLabel
}) : [];
const listboxAvailable = open && filteredOptions.length > 0;
if (process.env.NODE_ENV !== 'production') {
if (value !== null && !freeSolo && options.length > 0) {
const missingValue = (multiple ? value : [value]).filter(value2 => !options.some(option => getOptionSelected(option, value2)));
if (missingValue.length > 0) {
console.warn([`Material-UI: The value provided to ${componentName} is invalid.`, `None of the options match with \`${missingValue.length > 1 ? JSON.stringify(missingValue) : JSON.stringify(missingValue[0])}\`.`, 'You can use the `getOptionSelected` prop to customize the equality test.'].join('\n'));
}
}
}
const focusTag = (0, _utils.useEventCallback)(tagToFocus => {
if (tagToFocus === -1) {
inputRef.current.focus();
} else {
anchorEl.querySelector(`[data-tag-index="${tagToFocus}"]`).focus();
}
}); // Ensure the focusedTag is never inconsistent
React.useEffect(() => {
if (multiple && focusedTag > value.length - 1) {
setFocusedTag(-1);
focusTag(-1);
}
}, [value, multiple, focusedTag, focusTag]);
function validOptionIndex(index, direction) {
if (!listboxRef.current || index === -1) {
return -1;
}
let nextFocus = index;
while (true) {
// Out of range
if (direction === 'next' && nextFocus === filteredOptions.length || direction === 'previous' && nextFocus === -1) {
return -1;
}
const option = listboxRef.current.querySelector(`[data-option-index="${nextFocus}"]`); // Same logic as MenuList.js
const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
if (option && !option.hasAttribute('tabindex') || nextFocusDisabled) {
// Move to the next element.
nextFocus += direction === 'next' ? 1 : -1;
} else {
return nextFocus;
}
}
}
const setHighlightedIndex = (0, _utils.useEventCallback)(({
event,
index,
reason = 'auto'
}) => {
highlightedIndexRef.current = index; // does the index exist?
if (index === -1) {
inputRef.current.removeAttribute('aria-activedescendant');
} else {
inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);
}
if (onHighlightChange) {
onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
}
if (!listboxRef.current) {
return;
}
const prev = listboxRef.current.querySelector('[data-focus]');
if (prev) {
prev.removeAttribute('data-focus');
prev.classList.remove('Mui-focusVisible');
}
const listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]'); // "No results"
if (!listboxNode) {
return;
}
if (index === -1) {
listboxNode.scrollTop = 0;
return;
}
const option = listboxRef.current.querySelector(`[data-option-index="${index}"]`);
if (!option) {
return;
}
option.setAttribute('data-focus', 'true');
if (reason === 'keyboard') {
option.classList.add('Mui-focusVisible');
} // Scroll active descendant into view.
// Logic copied from https://www.w3.org/TR/wai-aria-practices/examples/listbox/js/listbox.js
//
// Consider this API instead once it has a better browser support:
// .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse') {
const element = option;
const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
const elementBottom = element.offsetTop + element.offsetHeight;
if (elementBottom > scrollBottom) {
listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
} else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {
listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
}
}
});
const changeHighlightedIndex = (0, _utils.useEventCallback)(({
event,
diff,
direction = 'next',
reason = 'auto'
}) => {
if (!popupOpen) {
return;
}
const getNextIndex = () => {
const maxIndex = filteredOptions.length - 1;
if (diff === 'reset') {
return defaultHighlighted;
}
if (diff === 'start') {
return 0;
}
if (diff === 'end') {
return maxIndex;
}
const newIndex = highlightedIndexRef.current + diff;
if (newIndex < 0) {
if (newIndex === -1 && includeInputInList) {
return -1;
}
if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {
return 0;
}
return maxIndex;
}
if (newIndex > maxIndex) {
if (newIndex === maxIndex + 1 && includeInputInList) {
return -1;
}
if (disableListWrap || Math.abs(diff) > 1) {
return maxIndex;
}
return 0;
}
return newIndex;
};
const nextIndex = validOptionIndex(getNextIndex(), direction);
setHighlightedIndex({
index: nextIndex,
reason,
event
}); // Sync the content of the input with the highlighted option.
if (autoComplete && diff !== 'reset') {
if (nextIndex === -1) {
inputRef.current.value = inputValue;
} else {
const option = getOptionLabel(filteredOptions[nextIndex]);
inputRef.current.value = option; // The portion of the selected suggestion that has not been typed by the user,
// a completion string, appears inline after the input cursor in the textbox.
const index = option.toLowerCase().indexOf(inputValue.toLowerCase());
if (index === 0 && inputValue.length > 0) {
inputRef.current.setSelectionRange(inputValue.length, option.length);
}
}
}
});
const syncHighlightedIndex = React.useCallback(() => {
if (!popupOpen) {
return;
}
const valueItem = multiple ? value[0] : value; // The popup is empty, reset
if (filteredOptions.length === 0 || valueItem == null) {
changeHighlightedIndex({
diff: 'reset'
});
return;
}
if (!listboxRef.current) {
return;
} // Synchronize the value with the highlighted index
if (valueItem != null) {
const currentOption = filteredOptions[highlightedIndexRef.current]; // Keep the current highlighted index if possible
if (multiple && currentOption && findIndex(value, val => getOptionSelected(currentOption, val)) !== -1) {
return;
}
const itemIndex = findIndex(filteredOptions, optionItem => getOptionSelected(optionItem, valueItem));
if (itemIndex === -1) {
changeHighlightedIndex({
diff: 'reset'
});
} else {
setHighlightedIndex({
index: itemIndex
});
}
return;
} // Prevent the highlighted index to leak outside the boundaries.
if (highlightedIndexRef.current >= filteredOptions.length - 1) {
setHighlightedIndex({
index: filteredOptions.length - 1
});
return;
} // Restore the focus to the previous index.
setHighlightedIndex({
index: highlightedIndexRef.current
}); // Ignore filteredOptions (and options, getOptionSelected, getOptionLabel) not to break the scroll position
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [// Only sync the highlighted index when the option switch between empty and not
// eslint-disable-next-line react-hooks/exhaustive-deps
filteredOptions.length === 0, // Don't sync the highlighted index with the value when multiple
// eslint-disable-next-line react-hooks/exhaustive-deps
multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);
const handleListboxRef = (0, _utils.useEventCallback)(node => {
(0, _utils.setRef)(listboxRef, node);
if (!node) {
return;
}
syncHighlightedIndex();
});
React.useEffect(() => {
syncHighlightedIndex();
}, [syncHighlightedIndex]);
const handleOpen = event => {
if (open) {
return;
}
setOpenState(true);
setInputPristine(true);
if (onOpen) {
onOpen(event);
}
};
const handleClose = (event, reason) => {
if (!open) {
return;
}
setOpenState(false);
if (onClose) {
onClose(event, reason);
}
};
const handleValue = (event, newValue, reason, details) => {
if (value === newValue) {
return;
}
if (onChange) {
onChange(event, newValue, reason, details);
}
setValueState(newValue);
};
const isTouch = React.useRef(false);
const selectNewValue = (event, option, reasonProp = 'select-option', origin = 'options') => {
let reason = reasonProp;
let newValue = option;
if (multiple) {
newValue = Array.isArray(value) ? value.slice() : [];
if (process.env.NODE_ENV !== 'production') {
const matches = newValue.filter(val => getOptionSelected(option, val));
if (matches.length > 1) {
console.error([`Material-UI: The \`getOptionSelected\` method of ${componentName} do not handle the arguments correctly.`, `The component expects a single value to match a given option but found ${matches.length} matches.`].join('\n'));
}
}
const itemIndex = findIndex(newValue, valueItem => getOptionSelected(option, valueItem));
if (itemIndex === -1) {
newValue.push(option);
} else if (origin !== 'freeSolo') {
newValue.splice(itemIndex, 1);
reason = 'remove-option';
}
}
resetInputValue(event, newValue);
handleValue(event, newValue, reason, {
option
});
if (!disableCloseOnSelect && !event.ctrlKey && !event.metaKey) {
handleClose(event, reason);
}
if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {
inputRef.current.blur();
}
};
function validTagIndex(index, direction) {
if (index === -1) {
return -1;
}
let nextFocus = index;
while (true) {
// Out of range
if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {
return -1;
}
const option = anchorEl.querySelector(`[data-tag-index="${nextFocus}"]`); // Same logic as MenuList.js
if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {
nextFocus += direction === 'next' ? 1 : -1;
} else {
return nextFocus;
}
}
}
const handleFocusTag = (event, direction) => {
if (!multiple) {
return;
}
handleClose(event, 'toggleInput');
let nextTag = focusedTag;
if (focusedTag === -1) {
if (inputValue === '' && direction === 'previous') {
nextTag = value.length - 1;
}
} else {
nextTag += direction === 'next' ? 1 : -1;
if (nextTag < 0) {
nextTag = 0;
}
if (nextTag === value.length) {
nextTag = -1;
}
}
nextTag = validTagIndex(nextTag, direction);
setFocusedTag(nextTag);
focusTag(nextTag);
};
const handleClear = event => {
ignoreFocus.current = true;
setInputValueState('');
if (onInputChange) {
onInputChange(event, '', 'clear');
}
handleValue(event, multiple ? [] : null, 'clear');
};
const handleKeyDown = other => event => {
if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
setFocusedTag(-1);
focusTag(-1);
} // Wait until IME is settled.
if (event.which !== 229) {
switch (event.key) {
case 'Home':
if (popupOpen && handleHomeEndKeys) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: 'start',
direction: 'next',
reason: 'keyboard',
event
});
}
break;
case 'End':
if (popupOpen && handleHomeEndKeys) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: 'end',
direction: 'previous',
reason: 'keyboard',
event
});
}
break;
case 'PageUp':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: -pageSize,
direction: 'previous',
reason: 'keyboard',
event
});
handleOpen(event);
break;
case 'PageDown':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: pageSize,
direction: 'next',
reason: 'keyboard',
event
});
handleOpen(event);
break;
case 'ArrowDown':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex({
diff: 1,
direction: 'next',
reason: 'keyboard',
event
});
handleOpen(event);
break;
case 'ArrowUp':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex({
diff: -1,
direction: 'previous',
reason: 'keyboard',
event
});
handleOpen(event);
break;
case 'ArrowLeft':
handleFocusTag(event, 'previous');
break;
case 'ArrowRight':
handleFocusTag(event, 'next');
break;
case 'Enter':
if (highlightedIndexRef.current !== -1 && popupOpen) {
const option = filteredOptions[highlightedIndexRef.current];
const disabled = getOptionDisabled ? getOptionDisabled(option) : false; // We don't want to validate the form.
event.preventDefault();
if (disabled) {
return;
}
selectNewValue(event, option, 'select-option'); // Move the selection to the end.
if (autoComplete) {
inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
}
} else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
if (multiple) {
// Allow people to add new values before they submit the form.
event.preventDefault();
}
selectNewValue(event, inputValue, 'create-option', 'freeSolo');
}
break;
case 'Escape':
if (popupOpen) {
// Avoid Opera to exit fullscreen mode.
event.preventDefault(); // Avoid the Modal to handle the event.
event.stopPropagation();
handleClose(event, 'escape');
} else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
// Avoid Opera to exit fullscreen mode.
event.preventDefault(); // Avoid the Modal to handle the event.
event.stopPropagation();
handleClear(event);
}
break;
case 'Backspace':
if (multiple && inputValue === '' && value.length > 0) {
const index = focusedTag === -1 ? value.length - 1 : focusedTag;
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'remove-option', {
option: value[index]
});
}
break;
default:
}
}
if (other.onKeyDown) {
other.onKeyDown(event);
}
};
const handleFocus = event => {
setFocused(true);
if (openOnFocus && !ignoreFocus.current) {
handleOpen(event);
}
};
const handleBlur = event => {
// Ignore the event when using the scrollbar with IE11
if (listboxRef.current !== null && listboxRef.current.parentElement.contains(document.activeElement)) {
inputRef.current.focus();
return;
}
setFocused(false);
firstFocus.current = true;
ignoreFocus.current = false;
if (debug && inputValue !== '') {
return;
}
if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
} else if (autoSelect && freeSolo && inputValue !== '') {
selectNewValue(event, inputValue, 'blur', 'freeSolo');
} else if (clearOnBlur) {
resetInputValue(event, value);
}
handleClose(event, 'blur');
};
const handleInputChange = event => {
const newValue = event.target.value;
if (inputValue !== newValue) {
setInputValueState(newValue);
setInputPristine(false);
if (onInputChange) {
onInputChange(event, newValue, 'input');
}
}
if (newValue === '') {
if (!disableClearable && !multiple) {
handleValue(event, null, 'clear');
}
} else {
handleOpen(event);
}
};
const handleOptionMouseOver = event => {
setHighlightedIndex({
event,
index: Number(event.currentTarget.getAttribute('data-option-index')),
reason: 'mouse'
});
};
const handleOptionTouchStart = () => {
isTouch.current = true;
};
const handleOptionClick = event => {
const index = Number(event.currentTarget.getAttribute('data-option-index'));
selectNewValue(event, filteredOptions[index], 'select-option');
isTouch.current = false;
};
const handleTagDelete = index => event => {
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'remove-option', {
option: value[index]
});
};
const handlePopupIndicator = event => {
if (open) {
handleClose(event, 'toggleInput');
} else {
handleOpen(event);
}
}; // Prevent input blur when interacting with the combobox
const handleMouseDown = event => {
if (event.target.getAttribute('id') !== id) {
event.preventDefault();
}
}; // Focus the input when interacting with the combobox
const handleClick = () => {
inputRef.current.focus();
if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
inputRef.current.select();
}
firstFocus.current = false;
};
const handleInputMouseDown = event => {
if (inputValue === '' || !open) {
handlePopupIndicator(event);
}
};
let dirty = freeSolo && inputValue.length > 0;
dirty = dirty || (multiple ? value.length > 0 : value !== null);
let groupedOptions = filteredOptions;
if (groupBy) {
// used to keep track of key and indexes in the result array
const indexBy = new Map();
let warn = false;
groupedOptions = filteredOptions.reduce((acc, option, index) => {
const group = groupBy(option);
if (acc.length > 0 && acc[acc.length - 1].group === group) {
acc[acc.length - 1].options.push(option);
} else {
if (process.env.NODE_ENV !== 'production') {
if (indexBy.get(group) && !warn) {
console.warn(`Material-UI: The options provided combined with the \`groupBy\` method of ${componentName} returns duplicated headers.`, 'You can solve the issue by sorting the options with the output of `groupBy`.');
warn = true;
}
indexBy.set(group, true);
}
acc.push({
key: index,
index,
group,
options: [option]
});
}
return acc;
}, []);
}
return {
getRootProps: (other = {}) => (0, _extends2.default)({
'aria-owns': listboxAvailable ? `${id}-listbox` : null,
role: 'combobox',
'aria-expanded': listboxAvailable
}, other, {
onKeyDown: handleKeyDown(other),
onMouseDown: handleMouseDown,
onClick: handleClick
}),
getInputLabelProps: () => ({
id: `${id}-label`,
htmlFor: id
}),
getInputProps: () => ({
id,
value: inputValue,
onBlur: handleBlur,
onFocus: handleFocus,
onChange: handleInputChange,
onMouseDown: handleInputMouseDown,
// if open then this is handled imperativeley so don't let react override
// only have an opinion about this when closed
'aria-activedescendant': popupOpen ? '' : null,
'aria-autocomplete': autoComplete ? 'both' : 'list',
'aria-controls': listboxAvailable ? `${id}-listbox` : null,
// Disable browser's suggestion that might overlap with the popup.
// Handle autocomplete but not autofill.
autoComplete: 'off',
ref: inputRef,
autoCapitalize: 'none',
spellCheck: 'false'
}),
getClearProps: () => ({
tabIndex: -1,
onClick: handleClear
}),
getPopupIndicatorProps: () => ({
tabIndex: -1,
onClick: handlePopupIndicator
}),
getTagProps: ({
index
}) => ({
key: index,
'data-tag-index': index,
tabIndex: -1,
onDelete: handleTagDelete(index)
}),
getListboxProps: () => ({
role: 'listbox',
id: `${id}-listbox`,
'aria-labelledby': `${id}-label`,
ref: handleListboxRef,
onMouseDown: event => {
// Prevent blur
event.preventDefault();
}
}),
getOptionProps: ({
index,
option
}) => {
const selected = (multiple ? value : [value]).some(value2 => value2 != null && getOptionSelected(option, value2));
const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
return {
key: index,
tabIndex: -1,
role: 'option',
id: `${id}-option-${index}`,
onMouseOver: handleOptionMouseOver,
onClick: handleOptionClick,
onTouchStart: handleOptionTouchStart,
'data-option-index': index,
'aria-disabled': disabled,
'aria-selected': selected
};
},
id,
inputValue,
value,
dirty,
popupOpen,
focused: focused || focusedTag !== -1,
anchorEl,
setAnchorEl,
focusedTag,
groupedOptions
};
} | {
"content_hash": "60a71ef7811881238f3d8b5611945a55",
"timestamp": "",
"source": "github",
"line_count": 1011,
"max_line_length": 308,
"avg_line_length": 28.469831849653808,
"alnum_prop": 0.5965674182677275,
"repo_name": "cdnjs/cdnjs",
"id": "fa86192f9607f2868f2ad20cf1ca78e80e482366",
"size": "28783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/material-ui/5.0.0-alpha.15/node/useAutocomplete/useAutocomplete.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
layout: post
title: Animation
date: 2016-10-30
---
This tutorial will try to explain in a simplified manner how to implement 2D animation in the Web.
I'm going to use the [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) API to
keep things simple. However you can use any rendering API. So open up your favorite [Text Editor](https://en.wikipedia.org/wiki/Text_editor),
prepare your coffee and get ready for this adventure.
# Computer Animation:
### Abstract:
 computer animation is the process used to create animated images, as opposed to static images
that stay the same all the time, like your favorite game's background.
Computer animation is essentially the digital successor to the stop motion techniques that attempts to
trick your brains into thinking that they are seeing a smoothly moving object when they are in fact
seeing different states of motion of that object. This is possible thanks to a phenomenon called the
[Persistence of Vision](https://en.wikipedia.org/wiki/Persistence_of_vision).
The pictures should be draw at around 12 frames per seconds and usually faster, otherwise most people
will detect some sort of jerkiness associated with the drawing of new images that detracts from the illusion
of realistic movement. Lots of conventions are used when it comes to this, For example hand-drawn cartoon animation
often use 15 frame/s whereas films seen in theaters run at 24 frame/s.
There are different techniques used to achieve computer animations such as [Keyframing](https://en.wikipedia.org/wiki/Key_frame#Animation_by_means_of_computer_graphics),
[Blocking](https://en.wikipedia.org/wiki/Blocking_(animation)), [Morphing](https://en.wikipedia.org/wiki/Morphing), etc... .
### Basic Animation Steps:
 Implementing 2D computer animation is fairly simple and straightforward, these are the minimal steps you
should take to draw every frame.
- Clear the canvas:
Each frame a completely different frame from the last one at the pixel level, so you'll have to clear all previously
drawn object and prepare for drawing the next frame. the easiest way to this is the use the `clearRect` method.
- Save the canvas state:
To draw anthing on the screen you might will often need to change the canvas state. For example, you need translate the canvas a bit to make
your character seem to move and them go back to the original state. You can do this using the `save` method in canvas to save the current transformations associated
with the rendering context.
- Do all your rendering logic here:
This is where you will do all your image processing and rendering here.
- Restore your canvas state:
If you have saved your last canvas state, you can restore it but calling the `restore` method, which will pop off the last state frame and
set it as the current one.
# Code:
### Setting up our rendering context:
 Let's try to make a simple moving character. I used a free spritesheet for animation, [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame)
method for animation which tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. this
will improve your application's performance and make your animation smoothier. I will be using ES6 for scripting, so your browser might not support any of this code, but this will only be a problem
for those who use older browser.
Let's start off by setting up a view layer where we will draw all of our graphics.
```html
<canvas id="view">
</canvas>
```
```javascript
let canvas = document.getElementById('view'); //get a reference to our canvas DOM element
let ctx = canvas.getContext('2d'); //create a 2D context for drawing.
canvas.width = 640;
canvas.height = 480; //640x480 resolution
let loader = {
cache: {}, //mapping from image url to their promises
loadImage(url) {
let img = this.cache[url];
if ( img )
return img;
img = this.cache[url] = new Promise((resolve, reject) => {
let image = new Image();
image.src = url;
image.onload = () => resolve(image);
image.onerror = (err) => reject(err);
});
return img;
},
await() {
let promises = [];
for ( let url in this.cache )
promises.push(this.cache[url]);
return Promise.all(promises);
}
};
```
Up until now, we're not doing anything interesting, just getting a reference to a 2D content for drawing
on the canvas and setting its resolution to 640x480 pixel.
Then creating a loader object that will help us load all of our images and await for them asynchronously
before starting the game. At this point, if you try this, you will see nothing and this is expected.
### Loading our first image:
This will be pretty simple because we have all we need to start rendering our first image on the screen.
It's as simple as calling `putImage(image, x, y, width, height)`.
```javascript
let Sprite = function(x, y, width, height, url) {
this.position = {x, y};
this.width = width; //the width we want to show
this.height = height; //the height we want to show
this.texture = null;
loader.loadImage(url).then(image => {
this.texture = image;
});
};
Sprite.prototype.draw = function() {
ctx.drawImage(this.texture, this.position.x, this.position.y, this.width, this.height);
};
let sheet = new Sprite(0, 0, 640, 480, './run.png'); //our sprite sheet, image located at './run.png'
function animate() {
window.requestAnimationFrame(animate); //request for the next frame of this animation
ctx.clearRect(0, 0, 640, 480); //clear the canvas
sheet.draw(); //draw out sprite sheet
};
loader.await().then(all => {
window.requestAnimationFrame(animate); //start the animation when everything is loaded
});
```
We are making a nice `Sprite` class which will hold all the information we need to show our spritesheet on the screen,
spritesheet has a `draw` method which will draw the image on the screen and save us a lot of writing.
If you run this, you are supposed to get<br/>
<img src="/img/first.png" style="display: block; margin: 0 auto;"/>
Very nice, is it not ?
### Animating the sprite:
In order to bring this [Ninja](https://en.wikipedia.org/wiki/Ninja) back to life, we'll have to animate it, luckily our spritesheet
contains all the frames needed to do this, so we'll have to tune our code a little bit to get this right.
To do this, we need to cut our image to little chunk and display each at a time.
To do this, we need to call `drawImage(image, clipX, clipY, clipWidth, clipHeight, x, y, width, height)`.
The arguments names are self explanatory. If this is still hard to image, I hope this picture will explain it all.
<img src="/img/drawImage.jpg" style="display: block; margin: 0 auto;"/>
```javascript
let TextureFrame = function(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}; //Define where and how much we should clip the image
let Sprite = function(x, y, width, height, url) {
//All the old stuff
this.frame = null;
loader.loadImage(url).then(image => {
this.texture = image;
this.frame = new TextureFrame(0, 0, image.width, image.height); //show the whole image, no clipping
});
};
Sprite.prototype.draw = function() {
ctx.drawImage(this.texture, this.frame.x, this.frame.y, this.frame.width, this.frame.height, this.position.x, this.position.y, this.width, this.height);
};
```
And as expected, if you run this you will see no difference.
Let's get onto the fun part and define our `Animation` class.
```javascript
let Animation = function(frames, ticks) {
this.frames = frames;
this.index = 0; //the current frame index
this.ticksPerSec = ticks; //how many ticks before the next frame
this.ticks = 0; //how many ticks the frames ticked so far
this.playing = false; //is this playing ?
};
Animation.prototype.play = function() {
this.playing = true; //play the animation
};
Animation.prototype.stop = function() {
this.playing = false;
};
Animation.prototype.tick = function() { //method that will be called each frame
if ( ! this.playing )
return; //if this is not playing, do nothing.
this.ticks++;
if ( this.ticks >= this.ticksPerSec ) {
this.ticks = 0;
this.index = (++this.index) % this.frames.length; //allow the animation to loop back
}
};
//Change the draw procedure to be animation aware, simple checks aren't performance critical
Sprite.prototype.draw = function() {
if ( ! this.animation )
return ctx.drawImage(this.texture, this.frame.x, this.frame.y, this.frame.width, this.frame.height, this.position.x, this.position.y, this.width, this.height);
let frame = this.animation.frames[this.animation.index];
ctx.drawImage(this.texture, frame.x, frame.y, frame.width, frame.height, this.position.x, this.position.y, this.width, this.height);
this.animation.tick();
};
let ninja = new Sprite(0, 0, 280, 385, './run.png'); //each frame is of size 280, 385
let frames = [
new TextureFrame(0, 0, 280, 385),
new TextureFrame(280, 0, 280, 385),
new TextureFrame(560, 0, 280, 385),
new TextureFrame(840, 0, 280, 385),
new TextureFrame(1120, 0, 280, 385),
new TextureFrame(0, 385, 280, 385),
new TextureFrame(280, 385, 280, 385),
new TextureFrame(560, 385, 280, 385),
new TextureFrame(840, 385, 280, 385),
new TextureFrame(1120, 385, 280, 385),
]; //All clippings
ninja.animation = new Animation(frames, 5); //5 ticks per frame, 12 frame per sec
ninja.animation.play();
function animate() {
window.requestAnimationFrame(animate); //request for the next frame of this animation
ctx.clearRect(0, 0, 640, 480); //clear the canvas
ninja.draw(); //draw our sprite
};
```
And that's all there is to it. Congrats, you have now learnt how to animate your spritesheets. This approach
is very nice and easy to extend.
Here's a demo.
<canvas id="view" style="display: block; margin: 0 auto;">
</canvas>
<script type="text/javascript">
let canvas = document.getElementById('view'); //get a reference to our canvas DOM element
let ctx = canvas.getContext('2d'); //create a 2D context for drawing.
canvas.width = 640;
canvas.height = 480; //640x480 resolution
let loader = {
cache: {}, //mapping from image url to their promises
loadImage(url) {
let img = this.cache[url];
if ( img )
return img;
img = this.cache[url] = new Promise((resolve, reject) => {
let image = new Image();
image.src = url;
image.onload = () => resolve(image);
image.onerror = (err) => reject(err);
});
return img;
},
await() {
let promises = [];
for ( let url in this.cache )
promises.push(this.cache[url]);
return Promise.all(promises);
}
};
let TextureFrame = function(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}; //Define were and how much we should clip the image
let Sprite = function(x, y, width, height, url) {
this.position = {x, y};
this.width = width; //the width we want to show
this.height = height; //the height we want to show
this.texture = null;
this.frame = null;
loader.loadImage(url).then(image => {
this.texture = image;
this.frame = new TextureFrame(0, 0, image.width, image.height); //show the whole image, no clipping
});
};
Sprite.prototype.draw = function() {
if ( ! this.animation )
return ctx.drawImage(this.texture, this.frame.x, this.frame.y, this.frame.width, this.frame.height, this.position.x, this.position.y, this.width, this.height);
let frame = this.animation.frames[this.animation.index];
ctx.drawImage(this.texture, frame.x, frame.y, frame.width, frame.height, this.position.x, this.position.y, this.width, this.height);
this.animation.tick();
};
let Animation = function(frames, ticks) {
this.frames = frames;
this.index = 0; //the current frame index
this.ticksPerSec = ticks; //how many ticks before the next frame
this.ticks = 0; //how many ticks the frames ticked so far
this.playing = false; //is this playing ?
};
Animation.prototype.play = function() {
this.playing = true; //play the animation
};
Animation.prototype.stop = function() {
this.playing = false;
};
Animation.prototype.tick = function() { //method that will be called each frame
if ( ! this.playing )
return; //if this is not playing stop
this.ticks++;
if ( this.ticks >= this.ticksPerSec ) {
this.ticks = 0;
this.index = (++this.index) % this.frames.length; //allow the animation to loop back
}
};
let ninja = new Sprite(0, 0, 280, 385, '/img/run.png'); //each frame is of size 280, 385
let frames = [
new TextureFrame(0, 0, 280, 385),
new TextureFrame(280, 0, 280, 385),
new TextureFrame(560, 0, 280, 385),
new TextureFrame(840, 0, 280, 385),
new TextureFrame(1120, 0, 280, 385),
new TextureFrame(0, 385, 280, 385),
new TextureFrame(280, 385, 280, 385),
new TextureFrame(560, 385, 280, 385),
new TextureFrame(840, 385, 280, 385),
new TextureFrame(1120, 385, 280, 385),
]; //All clippings
ninja.animation = new Animation(frames, 5); //5 ticks per frame, 12 frame per sec
ninja.animation.play();
function animate() {
window.requestAnimationFrame(animate); //request for the next frame of this animation
ctx.clearRect(0, 0, 640, 480); //clear the canvas
ninja.draw();
};
loader.await().then(all => {
window.requestAnimationFrame(animate); //start the animation when everything is loaded
});
</script>
### Full Code:
```html
<canvas id="view">
</canvas>
<script type="text/javascript">
let canvas = document.getElementById('view'); //get a reference to our canvas DOM element
let ctx = canvas.getContext('2d'); //create a 2D context for drawing.
canvas.width = 640;
canvas.height = 480; //640x480 resolution
let loader = {
cache: {}, //mapping from image url to their promises
loadImage(url) {
let img = this.cache[url];
if ( img )
return img;
img = this.cache[url] = new Promise((resolve, reject) => {
let image = new Image();
image.src = url;
image.onload = () => resolve(image);
image.onerror = (err) => reject(err);
});
return img;
},
await() {
let promises = [];
for ( let url in this.cache )
promises.push(this.cache[url]);
return Promise.all(promises);
}
};
let TextureFrame = function(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}; //Define were and how much we should clip the image
let Sprite = function(x, y, width, height, url) {
this.position = {x, y};
this.width = width; //the width we want to show
this.height = height; //the height we want to show
this.texture = null;
this.frame = null;
loader.loadImage(url).then(image => {
this.texture = image;
this.frame = new TextureFrame(0, 0, image.width, image.height); //show the whole image, no clipping
});
};
Sprite.prototype.draw = function() {
if ( ! this.animation )
return ctx.drawImage(this.texture, this.frame.x, this.frame.y, this.frame.width, this.frame.height, this.position.x, this.position.y, this.width, this.height);
let frame = this.animation.frames[this.animation.index];
ctx.drawImage(this.texture, frame.x, frame.y, frame.width, frame.height, this.position.x, this.position.y, this.width, this.height);
this.animation.tick();
};
let Animation = function(frames, ticks) {
this.frames = frames;
this.index = 0; //the current frame index
this.ticksPerSec = ticks; //how many ticks before the next frame
this.ticks = 0; //how many ticks the frames ticked so far
this.playing = false; //is this playing ?
};
Animation.prototype.play = function() {
this.playing = true; //play the animation
};
Animation.prototype.stop = function() {
this.playing = false;
};
Animation.prototype.tick = function() { //method that will be called each frame
if ( ! this.playing )
return; //if this is not playing stop
this.ticks++;
if ( this.ticks >= this.ticksPerSec ) {
this.ticks = 0;
this.index = (++this.index) % this.frames.length; //allow the animation to loop back
}
};
let ninja = new Sprite(0, 0, 280, 385, './run.png'); //each frame is of size 280, 385
let frames = [
new TextureFrame(0, 0, 280, 385),
new TextureFrame(280, 0, 280, 385),
new TextureFrame(560, 0, 280, 385),
new TextureFrame(840, 0, 280, 385),
new TextureFrame(1120, 0, 280, 385),
new TextureFrame(0, 385, 280, 385),
new TextureFrame(280, 385, 280, 385),
new TextureFrame(560, 385, 280, 385),
new TextureFrame(840, 385, 280, 385),
new TextureFrame(1120, 385, 280, 385),
]; //All clippings
ninja.animation = new Animation(frames, 5); //5 ticks per frame, 12 frame per sec
ninja.animation.play();
function animate() {
window.requestAnimationFrame(animate); //request for the next frame of this animation
ctx.clearRect(0, 0, 640, 480); //clear the canvas
ninja.draw();
};
loader.await().then(all => {
window.requestAnimationFrame(animate); //start the animation when everything is loaded
});
</script>
```
I hope everything is clear enough, the code can be found here. It's free to use for any purpose and doesn't come with any restrictive license.
# So what ?:
Actually that's all there is to it. Animation spritesheets in canvas is very easy and can get a bit more challenging if you try this in OpenGL or DirectX.
The approach is the same and very easy to understand. If you have any question, don't hesitate to post a comment below and I will try to answer it as
fast as I can. If you liked this post, **please** leave a comment below, and thanks for existing.
<img src="/img/byebye.gif-c200" style="display: block; margin: 0 auto;"/> | {
"content_hash": "b6922bd7f7f983ab320084ad95ca5ed4",
"timestamp": "",
"source": "github",
"line_count": 506,
"max_line_length": 197,
"avg_line_length": 34.94268774703557,
"alnum_prop": 0.7066907980317856,
"repo_name": "Noctisdark/noctisdark.github.io",
"id": "60251cb298e0dbb4c7fb61e6ce7ff674936072cc",
"size": "17685",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-10-30-Animation.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7432"
},
{
"name": "HTML",
"bytes": "11935"
},
{
"name": "JavaScript",
"bytes": "739"
}
],
"symlink_target": ""
} |
package io.fabric8.openshift.api.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.ListMeta;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import io.sundr.transform.annotations.TemplateTransformation;
import io.sundr.transform.annotations.TemplateTransformations;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"apiVersion",
"kind",
"metadata",
"items"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
"_",
""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
@BuildableReference(ObjectMeta.class),
@BuildableReference(LabelSelector.class),
@BuildableReference(Container.class),
@BuildableReference(PodTemplateSpec.class),
@BuildableReference(ResourceRequirements.class),
@BuildableReference(IntOrString.class),
@BuildableReference(ObjectReference.class),
@BuildableReference(LocalObjectReference.class),
@BuildableReference(PersistentVolumeClaim.class)
})
@TemplateTransformations({
@TemplateTransformation(value = "/manifest.vm", outputPath = "META-INF/services/io.fabric8.kubernetes.api.model.KubernetesResource", gather = true)
})
@Version("v1")
@Group("template.openshift.io")
public class TemplateList implements KubernetesResource, KubernetesResourceList<io.fabric8.openshift.api.model.Template>
{
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
private String apiVersion = "template.openshift.io/v1";
@JsonProperty("items")
private List<io.fabric8.openshift.api.model.Template> items = new ArrayList<io.fabric8.openshift.api.model.Template>();
/**
*
* (Required)
*
*/
@JsonProperty("kind")
private String kind = "TemplateList";
@JsonProperty("metadata")
private ListMeta metadata;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public TemplateList() {
}
/**
*
* @param metadata
* @param apiVersion
* @param kind
* @param items
*/
public TemplateList(String apiVersion, List<io.fabric8.openshift.api.model.Template> items, String kind, ListMeta metadata) {
super();
this.apiVersion = apiVersion;
this.items = items;
this.kind = kind;
this.metadata = metadata;
}
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
public String getApiVersion() {
return apiVersion;
}
/**
*
* (Required)
*
*/
@JsonProperty("apiVersion")
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
@JsonProperty("items")
public List<io.fabric8.openshift.api.model.Template> getItems() {
return items;
}
@JsonProperty("items")
public void setItems(List<io.fabric8.openshift.api.model.Template> items) {
this.items = items;
}
/**
*
* (Required)
*
*/
@JsonProperty("kind")
public String getKind() {
return kind;
}
/**
*
* (Required)
*
*/
@JsonProperty("kind")
public void setKind(String kind) {
this.kind = kind;
}
@JsonProperty("metadata")
public ListMeta getMetadata() {
return metadata;
}
@JsonProperty("metadata")
public void setMetadata(ListMeta metadata) {
this.metadata = metadata;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| {
"content_hash": "44c76829e9d867866ae262598b8be9f3",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 192,
"avg_line_length": 29.075675675675676,
"alnum_prop": 0.7090537274586355,
"repo_name": "fabric8io/kubernetes-client",
"id": "67f0aa2ae44d1b1b0960c998f7081254f37261de",
"size": "5379",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kubernetes-model-generator/openshift-model/src/generated/java/io/fabric8/openshift/api/model/TemplateList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1037"
},
{
"name": "Go",
"bytes": "368451"
},
{
"name": "Groovy",
"bytes": "1016"
},
{
"name": "Java",
"bytes": "24470630"
},
{
"name": "Makefile",
"bytes": "55512"
},
{
"name": "Shell",
"bytes": "15791"
}
],
"symlink_target": ""
} |
<TS language="cs" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Pravým tlačítkem myši začneš upravovat označení adresy</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Vytvoř novou adresu</translation>
</message>
<message>
<source>&New</source>
<translation>&Nová</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Zkopíruj aktuálně vybranou adresu do systémové schránky</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Kopíruj</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Zavřít</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Kopíruj adresu</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Smaž zvolenou adresu ze seznamu</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportuj data z tohoto panelu do souboru</translation>
</message>
<message>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<source>&Delete</source>
<translation>S&maž</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Zvol adresu, na kterou pošleš mince</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Zvol adres na příjem mincí</translation>
</message>
<message>
<source>C&hoose</source>
<translation>&Zvol</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Odesílací adresy</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Přijímací adresy</translation>
</message>
<message>
<source>These are your Dotcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Tohle jsou tvé Dotcoinové adresy pro posílání plateb. Před odesláním mincí si vždy zkontroluj částku a cílovou adresu.</translation>
</message>
<message>
<source>These are your Dotcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Tohle jsou tvé Dotcoinové adresy pro příjem plateb. Je doporučené používat pokaždé novou adresu pro každou transakci.</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Kopíruj &označení</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Uprav</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Exportuj seznam adres</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>CSV formát (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Exportování selhalo</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Při ukládání seznamu adres do %1 se přihodila nějaká chyba. Zkus to prosím znovu.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Označení</translation>
</message>
<message>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<source>(no label)</source>
<translation>(bez označení)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Změna hesla</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Zadej platné heslo</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Zadej nové heslo</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Totéž heslo ještě jednou</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Zašifruj peněženku</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla odemknout.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Odemkni peněženku</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla dešifrovat.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Dešifruj peněženku</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Změň heslo</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Zadej staré a nové heslo k peněžence.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Potvrď zašifrování peněženky</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR DotcoinS</b>!</source>
<translation>Upozornění: Pokud si zašifruješ peněženku a ztratíš či zapomeneš heslo, <b>PŘIJDEŠ O VŠECHNY DotcoinY</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Jsi si jistý, že chceš peněženku zašifrovat?</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>DŮLEŽITÉ: Všechny předchozí zálohy peněženky by měly být nahrazeny nově vygenerovanou, zašifrovanou peněženkou. Z bezpečnostních důvodů budou předchozí zálohy nešifrované peněženky nepoužitelné, jakmile začneš používat novou zašifrovanou peněženku.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Upozornění: Caps Lock je zapnutý!</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Peněženka je zašifrována</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Zadej nové heslo k peněžence.<br/>Použij <b>alespoň deset náhodných znaků</b> nebo <b>alespoň osm slov</b>.</translation>
</message>
<message>
<source>Dotcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Dotcoins from being stolen by malware infecting your computer.</source>
<translation>Dotcoin se teď ukončí, aby dokončil zašifrování. Pamatuj však, že pouhé zašifrování peněženky úplně nezabraňuje krádeži tvých Dotcoinů malwarem, kterým se může počítač nakazit.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Zašifrování peněženky selhalo</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Zašifrování peněženky selhalo kvůli vnitřní chybě. Tvá peněženka tedy nebyla zašifrována.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Zadaná hesla nejsou shodná.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Nepodařilo se odemknout peněženku</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Nezadal jsi správné heslo pro dešifrování peněženky.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Nepodařilo se dešifrovat peněženku</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Heslo k peněžence bylo v pořádku změněno.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Po&depiš zprávu...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Synchronizuji se se sítí...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Přehled</translation>
</message>
<message>
<source>Node</source>
<translation>Uzel</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Zobraz celkový přehled peněženky</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transakce</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Procházej historii transakcí</translation>
</message>
<message>
<source>E&xit</source>
<translation>&Konec</translation>
</message>
<message>
<source>Quit application</source>
<translation>Ukonči aplikaci</translation>
</message>
<message>
<source>About &Qt</source>
<translation>O &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Zobraz informace o Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Možnosti...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>Zaši&fruj peněženku...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Zazálohuj peněženku...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>Změň &heslo...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>Od&esílací adresy...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>Př&ijímací adresy...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Načíst &URI...</translation>
</message>
<message>
<source>Dotcoin Core client</source>
<translation>Dotcoin Core klient</translation>
</message>
<message>
<source>Importing blocks from disk...</source>
<translation>Importuji bloky z disku...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Vytvářím nový index bloků na disku...</translation>
</message>
<message>
<source>Send coins to a Dotcoin address</source>
<translation>Pošli mince na Dotcoinovou adresu</translation>
</message>
<message>
<source>Modify configuration options for Dotcoin</source>
<translation>Uprav nastavení Dotcoinu</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Zazálohuj peněženku na jiné místo</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Změň heslo k šifrování peněženky</translation>
</message>
<message>
<source>&Debug window</source>
<translation>&Ladicí okno</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Otevři ladicí a diagnostickou konzoli</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Ověř zprávu...</translation>
</message>
<message>
<source>Dotcoin</source>
<translation>Dotcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Peněženka</translation>
</message>
<message>
<source>&Send</source>
<translation>&Pošli</translation>
</message>
<message>
<source>&Receive</source>
<translation>Při&jmi</translation>
</message>
<message>
<source>Show information about Dotcoin Core</source>
<translation>Zobraz informace o Dotcoin Core</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Zobraz/Skryj</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Zobraz nebo skryj hlavní okno</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Zašifruj soukromé klíče ve své peněžence</translation>
</message>
<message>
<source>Sign messages with your Dotcoin addresses to prove you own them</source>
<translation>Podepiš zprávy svými Dotcoinovými adresami, čímž prokážeš, že jsi jejich vlastníkem</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Dotcoin addresses</source>
<translation>Ověř zprávy, aby ses ujistil, že byly podepsány danými Dotcoinovými adresami</translation>
</message>
<message>
<source>&File</source>
<translation>&Soubor</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Nastavení</translation>
</message>
<message>
<source>&Help</source>
<translation>Ná&pověda</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Panel s listy</translation>
</message>
<message>
<source>Dotcoin Core</source>
<translation>Dotcoin Core</translation>
</message>
<message>
<source>Request payments (generates QR codes and Dotcoin: URIs)</source>
<translation>Požaduj platby (generuje QR kódy a Dotcoin: URI)</translation>
</message>
<message>
<source>&About Dotcoin Core</source>
<translation>O &Dotcoin Core</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Ukaž seznam použitých odesílacích adres a jejich označení</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Ukaž seznam použitých přijímacích adres a jejich označení</translation>
</message>
<message>
<source>Open a Dotcoin: URI or payment request</source>
<translation>Načti Dotcoin: URI nebo platební požadavek</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Ar&gumenty z příkazové řádky</translation>
</message>
<message>
<source>Show the Dotcoin Core help message to get a list with possible Dotcoin command-line options</source>
<translation>Seznam argumentů Dotcoinu pro příkazovou řádku získáš v nápovědě Dotcoinu Core</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Dotcoin network</source>
<translation><numerusform>%n aktivní spojení do Dotcoinové sítě</numerusform><numerusform>%n aktivní spojení do Dotcoinové sítě</numerusform><numerusform>%n aktivních spojení do Dotcoinové sítě</numerusform></translation>
</message>
<message>
<source>No block source available...</source>
<translation>Není dostupný žádný zdroj bloků...</translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n hodinu</numerusform><numerusform>%n hodiny</numerusform><numerusform>%n hodin</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n den</numerusform><numerusform>%n dny</numerusform><numerusform>%n dnů</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n týden</numerusform><numerusform>%n týdny</numerusform><numerusform>%n týdnů</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 a %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n rok</numerusform><numerusform>%n roky</numerusform><numerusform>%n roků</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>Stahuji ještě bloky transakcí za poslední %1</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Poslední stažený blok byl vygenerován %1 zpátky.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Následné transakce ještě nebudou vidět.</translation>
</message>
<message>
<source>Error</source>
<translation>Chyba</translation>
</message>
<message>
<source>Warning</source>
<translation>Upozornění</translation>
</message>
<message>
<source>Information</source>
<translation>Informace</translation>
</message>
<message>
<source>Up to date</source>
<translation>Aktuální</translation>
</message>
<message numerus="yes">
<source>Processed %n blocks of transaction history.</source>
<translation><numerusform>Zpracován %n blok transakční historie.</numerusform><numerusform>Zpracovány %n bloky transakční historie.</numerusform><numerusform>Zpracováno %n bloků transakční historie.</numerusform></translation>
</message>
<message>
<source>Catching up...</source>
<translation>Stahuji...</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Odeslané transakce</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Příchozí transakce</translation>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Částka: %2
Typ: %3
Adresa: %4
</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Peněženka je <b>zašifrovaná</b> a momentálně <b>odemčená</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Peněženka je <b>zašifrovaná</b> a momentálně <b>zamčená</b></translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation>Upozornění sítě</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Výběr mincí</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Počet:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bajtů:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Částka:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Priorita:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Poplatek:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Prach:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Čistá částka:</translation>
</message>
<message>
<source>Change:</source>
<translation>Drobné:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(od)označit všechny</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Zobrazit jako strom</translation>
</message>
<message>
<source>List mode</source>
<translation>Vypsat jako seznam</translation>
</message>
<message>
<source>Amount</source>
<translation>Částka</translation>
</message>
<message>
<source>Received with label</source>
<translation>Příjem na označení</translation>
</message>
<message>
<source>Received with address</source>
<translation>Příjem na adrese</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Potvrzení</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Potvrzeno</translation>
</message>
<message>
<source>Priority</source>
<translation>Priorita</translation>
</message>
<message>
<source>Copy address</source>
<translation>Kopíruj adresu</translation>
</message>
<message>
<source>Copy label</source>
<translation>Kopíruj její označení</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopíruj částku</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Kopíruj ID transakce</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Zamkni neutracené</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Odemkni k utracení</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Kopíruj počet</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Kopíruj poplatek</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Kopíruj čistou částku</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Kopíruj bajty</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Kopíruj prioritu</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Kopíruj prach</translation>
</message>
<message>
<source>Copy change</source>
<translation>Kopíruj drobné</translation>
</message>
<message>
<source>highest</source>
<translation>nejvyšší</translation>
</message>
<message>
<source>higher</source>
<translation>vyšší</translation>
</message>
<message>
<source>high</source>
<translation>vysoká</translation>
</message>
<message>
<source>medium-high</source>
<translation>vyšší střední</translation>
</message>
<message>
<source>medium</source>
<translation>střední</translation>
</message>
<message>
<source>low-medium</source>
<translation>nižší střední</translation>
</message>
<message>
<source>low</source>
<translation>nízká</translation>
</message>
<message>
<source>lower</source>
<translation>nižší</translation>
</message>
<message>
<source>lowest</source>
<translation>nejnižší</translation>
</message>
<message>
<source>(%1 locked)</source>
<translation>(%1 zamčeno)</translation>
</message>
<message>
<source>none</source>
<translation>žádná</translation>
</message>
<message>
<source>Can vary +/- %1 satoshi(s) per input.</source>
<translation>Může se lišit o +/– %1 satoshi na každý vstup.</translation>
</message>
<message>
<source>yes</source>
<translation>ano</translation>
</message>
<message>
<source>no</source>
<translation>ne</translation>
</message>
<message>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation>Popisek zčervená, pokud je velikost transakce větší než 1000 bajtů.</translation>
</message>
<message>
<source>This means a fee of at least %1 per kB is required.</source>
<translation>To znamená, že je vyžadován poplatek alespoň %1 za kB.</translation>
</message>
<message>
<source>Can vary +/- 1 byte per input.</source>
<translation>Může se lišit o +/– 1 bajt na každý vstup.</translation>
</message>
<message>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation>Transakce s vyšší prioritou mají větší šanci na zařazení do bloku.</translation>
</message>
<message>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation>Popisek zčervená, pokud je priorita menší než „střední“.</translation>
</message>
<message>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation>Popisek zčervená, pokud má některý příjemce obdržet částku menší než %1.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(bez označení)</translation>
</message>
<message>
<source>change from %1 (%2)</source>
<translation>drobné z %1 (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(drobné)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Uprav adresu</translation>
</message>
<message>
<source>&Label</source>
<translation>&Označení</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>Označení spojené s tímto záznamem v seznamu adres</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>Adresa spojená s tímto záznamem v seznamu adres. Lze upravovat jen pro odesílací adresy.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adresa</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Nová přijímací adresa</translation>
</message>
<message>
<source>New sending address</source>
<translation>Nová odesílací adresa</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Uprav přijímací adresu</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Uprav odesílací adresu</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>Zadaná adresa "%1" už v adresáři je.</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Dotcoin address.</source>
<translation>Zadaná adresa "%1" není platná Dotcoinová adresa.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Nemohu odemknout peněženku.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Nepodařilo se mi vygenerovat nový klíč.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Vytvoří se nový adresář pro data.</translation>
</message>
<message>
<source>name</source>
<translation>název</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Adresář už existuje. Přidej %1, pokud tady chceš vytvořit nový adresář.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Taková cesta už existuje, ale není adresářem.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Tady nemůžu vytvořit adresář pro data.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Dotcoin Core</source>
<translation>Dotcoin Core</translation>
</message>
<message>
<source>version</source>
<translation>verze</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About Dotcoin Core</source>
<translation>O Dotcoin Core</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Argumenty z příkazové řádky</translation>
</message>
<message>
<source>Usage:</source>
<translation>Užití:</translation>
</message>
<message>
<source>command-line options</source>
<translation>možnosti příkazové řádky</translation>
</message>
<message>
<source>UI options</source>
<translation>Možnosti UI</translation>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nastavit jazyk, například "de_DE" (výchozí: systémové nastavení)</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Nastartovat minimalizovaně</translation>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation>Nastavit kořenové SSL certifikáty pro platební požadavky (výchozí: -system-)</translation>
</message>
<message>
<source>Show splash screen on startup (default: 1)</source>
<translation>Zobrazit startovací obrazovku (výchozí: 1)</translation>
</message>
<message>
<source>Choose data directory on startup (default: 0)</source>
<translation>Zvolit adresář pro data při startu (výchozí: 0)</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Vítej</translation>
</message>
<message>
<source>Welcome to Dotcoin Core.</source>
<translation>Vítej v Dotcoin Core.</translation>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where Dotcoin Core will store its data.</source>
<translation>Tohle je poprvé, co spouštíš Dotcoin Core, takže si můžeš zvolit, kam bude ukládat svá data.</translation>
</message>
<message>
<source>Dotcoin Core will download and store a copy of the Dotcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation>Dotcoin Core bude stahovat kopii řetězce bloků. Proto bude potřeba do tohoto adresáře uložit nejméně %1 GB dat – toto číslo bude navíc v průběhu času pomalu růst. Tvá peněženka bude rovněž uložena v tomto adresáři.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Použij výchozí adresář pro data</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Použij tento adresář pro data:</translation>
</message>
<message>
<source>Dotcoin Core</source>
<translation>Dotcoin Core</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Chyba: Nejde vytvořit požadovaný adresář pro data „%1“.</translation>
</message>
<message>
<source>Error</source>
<translation>Chyba</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n GB volného místa</numerusform><numerusform>%n GB volného místa</numerusform><numerusform>%n GB volného místa</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(z potřebného %n GB)</numerusform><numerusform>(z potřebných %n GB)</numerusform><numerusform>(z potřebných %n GB)</numerusform></translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Načíst URI</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Načíst platební požadavek z URI nebo ze souboru</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Vyber soubor platebního požadavku</translation>
</message>
<message>
<source>Select payment request file to open</source>
<translation>Vyber soubor platebního požadavku k načtení</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Možnosti</translation>
</message>
<message>
<source>&Main</source>
<translation>&Hlavní</translation>
</message>
<message>
<source>Automatically start Dotcoin after logging in to the system.</source>
<translation>Automaticky spustí Dotcoin po přihlášení do systému.</translation>
</message>
<message>
<source>&Start Dotcoin on system login</source>
<translation>S&pustit Dotcoin po přihlášení do systému</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Velikost &databázové cache</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Počet vláken pro &verifikaci skriptů</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Přijímat spojení zvenčí</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Přijímat příchozí spojení</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>IP adresa proxy (např. IPv4: 127.0.0.1/IPv6: ::1)</translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>URL třetích stran (např. block exploreru), které se zobrazí v kontextovém menu v záložce Transakce. %s v URL se nahradí hashem transakce. Více URL odděl svislítkem |.</translation>
</message>
<message>
<source>Third party transaction URLs</source>
<translation>URL transakcí třetích stran</translation>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation>Aktivní argumenty z příkazové řádky, které přetloukly tato nastavení:</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Vrátí všechny volby na výchozí hodnoty.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Obnovit nastavení</translation>
</message>
<message>
<source>&Network</source>
<translation>&Síť</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = automaticky, <0 = nechat daný počet jader volný, výchozí: 0)</translation>
</message>
<message>
<source>W&allet</source>
<translation>P&eněženka</translation>
</message>
<message>
<source>Expert</source>
<translation>Odborník</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Povolit ruční správu &mincí</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>Pokud zakážeš utrácení ještě nepotvrzených drobných, nepůjde použít drobné z transakce, dokud nebude mít alespoň jedno potvrzení. Ovlivní to také výpočet stavu účtu.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>&Utrácet i ještě nepotvrzené drobné</translation>
</message>
<message>
<source>Automatically open the Dotcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automaticky otevře potřebný port na routeru. Tohle funguje jen za předpokladu, že tvůj router podporuje UPnP a že je UPnP povolené.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Namapovat port přes &UPnP</translation>
</message>
<message>
<source>Connect to the Dotcoin network through a SOCKS5 proxy.</source>
<translation>Připojí se do Dotcoinové sítě přes SOCKS5 proxy.</translation>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>&Připojit přes SOCKS5 proxy (výchozí proxy):</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>&IP adresa proxy:</translation>
</message>
<message>
<source>&Port:</source>
<translation>Por&t:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port proxy (např. 9050)</translation>
</message>
<message>
<source>&Window</source>
<translation>O&kno</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Po minimalizaci okna zobrazí pouze ikonu v panelu.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimalizovávat do ikony v panelu</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Zavřením se aplikace minimalizuje. Pokud je tato volba zaškrtnuta, tak se aplikace ukončí pouze zvolením Konec v menu.</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>Za&vřením minimalizovat</translation>
</message>
<message>
<source>&Display</source>
<translation>Zobr&azení</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>&Jazyk uživatelského rozhraní:</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting Dotcoin.</source>
<translation>Tady lze nastavit jazyk uživatelského rozhraní. Nastavení se projeví až po restartování Dotcoinu.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>J&ednotka pro částky:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Zvol výchozí podjednotku, která se bude zobrazovat v programu a při posílání mincí.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Zda ukazovat možnosti pro ruční správu mincí nebo ne.</translation>
</message>
<message>
<source>&OK</source>
<translation>&Budiž</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Zrušit</translation>
</message>
<message>
<source>default</source>
<translation>výchozí</translation>
</message>
<message>
<source>none</source>
<translation>žádné</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Potvrzení obnovení nastavení</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>K aktivaci změn je potřeba restartovat klienta.</translation>
</message>
<message>
<source>Client will be shutdown, do you want to proceed?</source>
<translation>Klient se vypne, chceš pokračovat?</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Tahle změna bude chtít restartovat klienta.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Zadaná adresa proxy je neplatná.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Formulář</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Dotcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Zobrazené informace nemusí být aktuální. Tvá peněženka se automaticky sesynchronizuje s Dotcoinovou sítí, jakmile se s ní spojí. Zatím ale ještě není synchronizace dokončena.</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>Sledované:</translation>
</message>
<message>
<source>Available:</source>
<translation>K dispozici:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Aktuální disponibilní stav tvého účtu</translation>
</message>
<message>
<source>Pending:</source>
<translation>Očekáváno:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Souhrn transakcí, které ještě nejsou potvrzené a které se ještě nezapočítávají do celkového disponibilního stavu účtu</translation>
</message>
<message>
<source>Immature:</source>
<translation>Nedozráno:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Vytěžené mince, které ještě nejsou zralé</translation>
</message>
<message>
<source>Balances</source>
<translation>Stavy účtů</translation>
</message>
<message>
<source>Total:</source>
<translation>Celkem:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Celkový stav tvého účtu</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>Aktuální stav účtu sledovaných adres</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Běžné:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Poslední transakce</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Nepotvrzené transakce sledovaných adres</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Vytěžené mince na sledovaných adresách, které ještě nejsou zralé</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Aktuální stav účtu sledovaných adres</translation>
</message>
<message>
<source>out of sync</source>
<translation>nesynchronizováno</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>URI handling</source>
<translation>Zpracování URI</translation>
</message>
<message>
<source>Invalid payment address %1</source>
<translation>Neplatná platební adresa %1</translation>
</message>
<message>
<source>Payment request rejected</source>
<translation>Platební požadavek byl odmítnut</translation>
</message>
<message>
<source>Payment request network doesn't match client network.</source>
<translation>Síť platebního požadavku neodpovídá síti klienta.</translation>
</message>
<message>
<source>Payment request has expired.</source>
<translation>Platební požadavek vypršel.</translation>
</message>
<message>
<source>Payment request is not initialized.</source>
<translation>Platební požadavek není zahájený.</translation>
</message>
<message>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation>Požadovaná platební částka %1 je příliš malá (je považována za prach).</translation>
</message>
<message>
<source>Payment request error</source>
<translation>Chyba platebního požadavku</translation>
</message>
<message>
<source>Cannot start Dotcoin: click-to-pay handler</source>
<translation>Nemůžu spustit Dotcoin: obsluha click-to-pay</translation>
</message>
<message>
<source>Payment request fetch URL is invalid: %1</source>
<translation>Zdrojová URL platebního požadavku není platná: %1</translation>
</message>
<message>
<source>URI cannot be parsed! This can be caused by an invalid Dotcoin address or malformed URI parameters.</source>
<translation>Nepodařilo se analyzovat URI! Důvodem může být neplatná Dotcoinová adresa nebo poškozené parametry URI.</translation>
</message>
<message>
<source>Payment request file handling</source>
<translation>Zpracování souboru platebního požadavku</translation>
</message>
<message>
<source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source>
<translation>Soubor platebního požadavku nejde přečíst nebo zpracovat! Příčinou může být špatný soubor platebního požadavku.</translation>
</message>
<message>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation>Neověřené platební požadavky k uživatelským platebním skriptům nejsou podporované.</translation>
</message>
<message>
<source>Refund from %1</source>
<translation>Vrácení peněz od %1</translation>
</message>
<message>
<source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source>
<translation>Platební požadavek %1 je moc velký (%2 bajtů, povoleno %3 bajtů).</translation>
</message>
<message>
<source>Payment request DoS protection</source>
<translation>DoS ochrana platebního požadavku</translation>
</message>
<message>
<source>Error communicating with %1: %2</source>
<translation>Chyba při komunikaci s %1: %2</translation>
</message>
<message>
<source>Payment request cannot be parsed!</source>
<translation>Platební požadavek je nečitelný!</translation>
</message>
<message>
<source>Bad response from server %1</source>
<translation>Chybná odpověď ze serveru %1</translation>
</message>
<message>
<source>Payment acknowledged</source>
<translation>Platba potvrzena</translation>
</message>
<message>
<source>Network request error</source>
<translation>Chyba síťového požadavku</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Typ klienta</translation>
</message>
<message>
<source>Address/Hostname</source>
<translation>Adresa/Název hostitele</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Odezva</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Částka</translation>
</message>
<message>
<source>Enter a Dotcoin address (e.g. %1)</source>
<translation>Zadej Dotcoinovou adresu (např. %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 d</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>NETWORK</source>
<translation>SÍŤ</translation>
</message>
<message>
<source>UNKNOWN</source>
<translation>NEZNÁMÁ</translation>
</message>
<message>
<source>None</source>
<translation>Žádné</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Ulož obrázek...</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Kopíruj obrázek</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>Ulož QR kód</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>PNG obrázek (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation>Název klienta</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>Client version</source>
<translation>Verze klienta</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informace</translation>
</message>
<message>
<source>Debug window</source>
<translation>Ladicí okno</translation>
</message>
<message>
<source>General</source>
<translation>Obecné</translation>
</message>
<message>
<source>Using OpenSSL version</source>
<translation>Používaná verze OpenSSL</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Používaná verze BerkeleyDB</translation>
</message>
<message>
<source>Startup time</source>
<translation>Čas spuštění</translation>
</message>
<message>
<source>Network</source>
<translation>Síť</translation>
</message>
<message>
<source>Name</source>
<translation>Název</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Počet spojení</translation>
</message>
<message>
<source>Block chain</source>
<translation>Řetězec bloků</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Aktuální počet bloků</translation>
</message>
<message>
<source>Received</source>
<translation>Přijato</translation>
</message>
<message>
<source>Sent</source>
<translation>Odesláno</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Protějšky</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Vyber protějšek a uvidíš jeho detailní informace.</translation>
</message>
<message>
<source>Direction</source>
<translation>Směr</translation>
</message>
<message>
<source>Version</source>
<translation>Verze</translation>
</message>
<message>
<source>User Agent</source>
<translation>Typ klienta</translation>
</message>
<message>
<source>Services</source>
<translation>Služby</translation>
</message>
<message>
<source>Starting Height</source>
<translation>Prvotní výška</translation>
</message>
<message>
<source>Sync Height</source>
<translation>Aktuální výška</translation>
</message>
<message>
<source>Ban Score</source>
<translation>Skóre pro klatbu</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Doba spojení</translation>
</message>
<message>
<source>Last Send</source>
<translation>Poslední odeslání</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Poslední příjem</translation>
</message>
<message>
<source>Bytes Sent</source>
<translation>Bajtů odesláno</translation>
</message>
<message>
<source>Bytes Received</source>
<translation>Bajtů přijato</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Odezva</translation>
</message>
<message>
<source>Last block time</source>
<translation>Čas posledního bloku</translation>
</message>
<message>
<source>&Open</source>
<translation>&Otevřít</translation>
</message>
<message>
<source>&Console</source>
<translation>&Konzole</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>&Síťový provoz</translation>
</message>
<message>
<source>&Clear</source>
<translation>&Vyčistit</translation>
</message>
<message>
<source>Totals</source>
<translation>Součty</translation>
</message>
<message>
<source>In:</source>
<translation>Sem:</translation>
</message>
<message>
<source>Out:</source>
<translation>Ven:</translation>
</message>
<message>
<source>Build date</source>
<translation>Datum kompilace</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Soubor s ladicími záznamy</translation>
</message>
<message>
<source>Open the Dotcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Otevři soubor s ladicími záznamy Dotcoinu z aktuálního datového adresáře. U velkých logů to může pár vteřin zabrat.</translation>
</message>
<message>
<source>Clear console</source>
<translation>Vyčistit konzoli</translation>
</message>
<message>
<source>Welcome to the Dotcoin RPC console.</source>
<translation>Vítej v Dotcoinové RPC konzoli.</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>V historii se pohybuješ šipkami nahoru a dolů a pomocí <b>Ctrl-L</b> čistíš obrazovku.</translation>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Napsáním <b>help</b> si vypíšeš přehled dostupných příkazů.</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 kB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>via %1</source>
<translation>via %1</translation>
</message>
<message>
<source>never</source>
<translation>nikdy</translation>
</message>
<message>
<source>Inbound</source>
<translation>Sem</translation>
</message>
<message>
<source>Outbound</source>
<translation>Ven</translation>
</message>
<message>
<source>Unknown</source>
<translation>Neznámá</translation>
</message>
<message>
<source>Fetching...</source>
<translation>Stahuji...</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Čás&tka:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Označení:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Zpráva:</translation>
</message>
<message>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation>Recyklovat již dříve použité adresy. Recyklace adres má bezpečnostní rizika a narušuje soukromí. Nezaškrtávejte to, pokud znovu nevytváříte již dříve vytvořený platební požadavek.</translation>
</message>
<message>
<source>R&euse an existing receiving address (not recommended)</source>
<translation>&Recyklovat již existující adresy (nedoporučeno)</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Dotcoin network.</source>
<translation>Volitelná zpráva, která se připojí k platebnímu požadavku a která se zobrazí, když se požadavek otevře. Poznámka: Tahle zpráva se neposílá s platbou po Dotcoinové síti.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>Volitelné označení, které se má přiřadit k nové adrese.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Tímto formulář můžeš požadovat platby. Všechna pole jsou <b>volitelná</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>Volitelná částka, kterou požaduješ. Nech prázdné nebo nulové, pokud nepožaduješ konkrétní částku.</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Promaž obsah ze všech formulářových políček.</translation>
</message>
<message>
<source>Clear</source>
<translation>Vyčistit</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Historie vyžádaných plateb</translation>
</message>
<message>
<source>&Request payment</source>
<translation>&Vyžádat platbu</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Zobraz zvolený požadavek (stejně tak můžeš přímo na něj dvakrát poklepat)</translation>
</message>
<message>
<source>Show</source>
<translation>Zobrazit</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Smaž zvolené požadavky ze seznamu</translation>
</message>
<message>
<source>Remove</source>
<translation>Smazat</translation>
</message>
<message>
<source>Copy label</source>
<translation>Kopíruj její označení</translation>
</message>
<message>
<source>Copy message</source>
<translation>Kopíruj zprávu</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopíruj částku</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>QR kód</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>&Kopíruj URI</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Kopíruj &adresu</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Ulož obrázek...</translation>
</message>
<message>
<source>Request payment to %1</source>
<translation>Platební požadavek: %1</translation>
</message>
<message>
<source>Payment information</source>
<translation>Informace o platbě</translation>
</message>
<message>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<source>Amount</source>
<translation>Částka</translation>
</message>
<message>
<source>Label</source>
<translation>Označení</translation>
</message>
<message>
<source>Message</source>
<translation>Zpráva</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Výsledná URI je příliš dlouhá, zkus zkrátit text označení/zprávy.</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Chyba při kódování URI do QR kódu.</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Označení</translation>
</message>
<message>
<source>Message</source>
<translation>Zpráva</translation>
</message>
<message>
<source>Amount</source>
<translation>Částka</translation>
</message>
<message>
<source>(no label)</source>
<translation>(bez označení)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(bez zprávy)</translation>
</message>
<message>
<source>(no amount)</source>
<translation>(bez částky)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Pošli mince</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Možnosti ruční správy mincí</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Vstupy...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>automaticky vybrané</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Nedostatek prostředků!</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Počet:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bajtů:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Částka:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Priorita:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Poplatek:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Čistá částka:</translation>
</message>
<message>
<source>Change:</source>
<translation>Drobné:</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Pokud aktivováno, ale adresa pro drobné je prázdná nebo neplatná, tak se drobné pošlou na nově vygenerovanou adresu.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Vlastní adresa pro drobné</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Transakční poplatek:</translation>
</message>
<message>
<source>Choose...</source>
<translation>Zvol...</translation>
</message>
<message>
<source>collapse fee-settings</source>
<translation>sbal nastavení poplatků</translation>
</message>
<message>
<source>Minimize</source>
<translation>Skryj</translation>
</message>
<message>
<source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source>
<translation>Pokud je vlastní poplatek nastavený na 1000 satoshi a transakce má pouze 250 bajtů, tak „za kilobajt“ zaplatí poplatek jen 250 satoshi, zatímco „přinejmenším“ zaplatí 1000 satoshi. Pro transakce větší než kilobajt obě možnosti platí za kilobajt.</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>za kilobajt</translation>
</message>
<message>
<source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source>
<translation>Pokud je vlastní poplatek nastavený na 1000 satoshi a transakce má pouze 250 bajtů, tak „za kilobajt“ zaplatí poplatek jen 250 satoshi, zatímco „přinejmenším“ zaplatí 1000 satoshi. Pro transakce větší než kilobajt obě možnosti platí za kilobajt.</translation>
</message>
<message>
<source>total at least</source>
<translation>přinejmenším</translation>
</message>
<message>
<source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for Dotcoin transactions than the network can process.</source>
<translation>Platit jen minimální poplatek je v pořádku, pokud je zrovna méně transakcí než místa v blocích. Ale počítej s tím, že to také může skončit transakcí, která nikdy nebude potvrzena, pokud je větší poptávka po Dotcoinových transakcích, než síť zvládne zpracovat.</translation>
</message>
<message>
<source>(read the tooltip)</source>
<translation>(viz bublina)</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Doporučený:</translation>
</message>
<message>
<source>Custom:</source>
<translation>Vlastní:</translation>
</message>
<message>
<source>(Smart fee not initialized yet. This usually takes a few blocks...)</source>
<translation>(Inteligentní poplatek ještě není inicializovaný. Obvykle mu to tak pár bloků trvá...)</translation>
</message>
<message>
<source>Confirmation time:</source>
<translation>Rychlost potvrzení:</translation>
</message>
<message>
<source>normal</source>
<translation>normální</translation>
</message>
<message>
<source>fast</source>
<translation>rychlá</translation>
</message>
<message>
<source>Send as zero-fee transaction if possible</source>
<translation>Pošli transakci pokud možno bez poplatku</translation>
</message>
<message>
<source>(confirmation may take longer)</source>
<translation>(potvrzení může trvat déle)</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Pošli více příjemcům naráz</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Při&dej příjemce</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Promaž obsah ze všech formulářových políček.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Prach:</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Všechno s&maž</translation>
</message>
<message>
<source>Balance:</source>
<translation>Stav účtu:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Potvrď odeslání</translation>
</message>
<message>
<source>S&end</source>
<translation>P&ošli</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Potvrď odeslání mincí</translation>
</message>
<message>
<source>%1 to %2</source>
<translation>%1 pro %2</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Kopíruj počet</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopíruj částku</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Kopíruj poplatek</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Kopíruj čistou částku</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Kopíruj bajty</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Kopíruj prioritu</translation>
</message>
<message>
<source>Copy change</source>
<translation>Kopíruj drobné</translation>
</message>
<message>
<source>Total Amount %1 (= %2)</source>
<translation>Celková částka %1 (= %2)</translation>
</message>
<message>
<source>or</source>
<translation>nebo</translation>
</message>
<message>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresa příjemce je neplatná, překontroluj ji prosím.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Odesílaná částka musí být větší než 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Částka překračuje stav účtu.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Celková částka při připočítání poplatku %1 překročí stav účtu.</translation>
</message>
<message>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Zaznamenána duplikovaná adresa; každá adresa může být v odesílané platbě pouze jednou.</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>Vytvoření transakce selhalo!</translation>
</message>
<message>
<source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Transakce byla odmítnuta! Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation>
</message>
<message>
<source>Warning: Invalid Dotcoin address</source>
<translation>Upozornění: Neplatná Dotcoinová adresa</translation>
</message>
<message>
<source>(no label)</source>
<translation>(bez označení)</translation>
</message>
<message>
<source>Warning: Unknown change address</source>
<translation>Upozornění: Neznámá adresa pro drobné</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Kopíruj prach</translation>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation>Jsi si jistý, že to chceš poslat?</translation>
</message>
<message>
<source>added as transaction fee</source>
<translation>přidán jako transakční poplatek</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Čás&tka:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>&Komu:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation>
</message>
<message>
<source>&Label:</source>
<translation>O&značení:</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Vyber již použitou adresu</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Tohle je normální platba.</translation>
</message>
<message>
<source>The Dotcoin address to send the payment to</source>
<translation>Dotcoinová adresa příjemce</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Vlož adresu ze schránky</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Smaž tento záznam</translation>
</message>
<message>
<source>Message:</source>
<translation>Zpráva:</translation>
</message>
<message>
<source>This is a verified payment request.</source>
<translation>Tohle je ověřený platební požadavek.</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation>
</message>
<message>
<source>A message that was attached to the Dotcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Dotcoin network.</source>
<translation>Zpráva, která byla připojena k Dotcoin: URI a která se ti pro přehled uloží k transakci. Poznámka: Tahle zpráva se neposílá s platbou po Dotcoinové síti.</translation>
</message>
<message>
<source>This is an unverified payment request.</source>
<translation>Tohle je neověřený platební požadavek.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Komu:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Poznámka:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>Dotcoin Core is shutting down...</source>
<translation>Dotcoin Core se ukončuje...</translation>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Nevypínej počítač, dokud toto okno nezmizí.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Podpisy - podepsat/ověřit zprávu</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Podepiš zprávu</translation>
</message>
<message>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Podepsáním zprávy svými adresami můžeš prokázat, že je skutečně vlastníš. Buď opatrný a nepodepisuj nic vágního; například při phishingových útocích můžeš být lákán, abys něco takového podepsal. Podepisuj pouze zcela úplná a detailní prohlášení, se kterými souhlasíš.</translation>
</message>
<message>
<source>The Dotcoin address to sign the message with</source>
<translation>Dotcoinová adresa, kterou se zpráva podepíše</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Vyber již použitou adresu</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Vlož adresu ze schránky</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Sem vepiš zprávu, kterou chceš podepsat</translation>
</message>
<message>
<source>Signature</source>
<translation>Podpis</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Zkopíruj aktuálně vybraný podpis do systémové schránky</translation>
</message>
<message>
<source>Sign the message to prove you own this Dotcoin address</source>
<translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této Dotcoinové adresy</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Po&depiš zprávu</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Vymaž všechna pole formuláře pro podepsání zrávy</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Všechno &smaž</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Ověř zprávu</translation>
</message>
<message>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>K ověření podpisu zprávy zadej podepisující adresu, zprávu (ověř si, že správně kopíruješ zalomení řádků, mezery, tabulátory apod.) a podpis. Dávej pozor na to, abys nezkopíroval do podpisu víc, než co je v samotné podepsané zprávě, abys nebyl napálen man-in-the-middle útokem.</translation>
</message>
<message>
<source>The Dotcoin address the message was signed with</source>
<translation>Dotcoinová adresa, kterou je zpráva podepsána</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Dotcoin address</source>
<translation>Ověř zprávu, aby ses ujistil, že byla podepsána danou Dotcoinovou adresou</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>O&věř zprávu</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Vymaž všechna pole formuláře pro ověření zrávy</translation>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation>Kliknutím na "Podepiš zprávu" vygeneruješ podpis</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>Zadaná adresa je neplatná.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Zkontroluj ji prosím a zkus to pak znovu.</translation>
</message>
<message>
<source>The entered address does not refer to a key.</source>
<translation>Zadaná adresa nepasuje ke klíči.</translation>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation>Odemčení peněženky bylo zrušeno.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>Soukromý klíč pro zadanou adresu není dostupný.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Nepodařilo se podepsat zprávu.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Zpráv podepsána.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>Podpis nejde dekódovat.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Zkontroluj ho prosím a zkus to pak znovu.</translation>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation>Podpis se neshoduje s hašem zprávy.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Nepodařilo se ověřit zprávu.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Zpráva ověřena.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>Dotcoin Core</source>
<translation>Dotcoin Core</translation>
</message>
<message>
<source>The Bitcoin Core developers</source>
<translation>Vývojáři Bitcoin Core</translation>
</message>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>kB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>Otřevřeno dokud %1</translation>
</message>
<message>
<source>conflicted</source>
<translation>kolidující</translation>
</message>
<message>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/nepotvrzeno</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 potvrzení</translation>
</message>
<message>
<source>Status</source>
<translation>Stav</translation>
</message>
<message numerus="yes">
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, rozesláno přes %n uzel</numerusform><numerusform>, rozesláno přes %n uzly</numerusform><numerusform>, rozesláno přes %n uzlů</numerusform></translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Source</source>
<translation>Zdroj</translation>
</message>
<message>
<source>Generated</source>
<translation>Vygenerováno</translation>
</message>
<message>
<source>From</source>
<translation>Od</translation>
</message>
<message>
<source>To</source>
<translation>Pro</translation>
</message>
<message>
<source>own address</source>
<translation>vlastní adresa</translation>
</message>
<message>
<source>watch-only</source>
<translation>sledovaná</translation>
</message>
<message>
<source>label</source>
<translation>označení</translation>
</message>
<message>
<source>Credit</source>
<translation>Příjem</translation>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation><numerusform>dozraje po %n bloku</numerusform><numerusform>dozraje po %n blocích</numerusform><numerusform>dozraje po %n blocích</numerusform></translation>
</message>
<message>
<source>not accepted</source>
<translation>neakceptováno</translation>
</message>
<message>
<source>Debit</source>
<translation>Výdaj</translation>
</message>
<message>
<source>Total debit</source>
<translation>Celkové výdaje</translation>
</message>
<message>
<source>Total credit</source>
<translation>Celkové příjmy</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Transakční poplatek</translation>
</message>
<message>
<source>Net amount</source>
<translation>Čistá částka</translation>
</message>
<message>
<source>Message</source>
<translation>Zpráva</translation>
</message>
<message>
<source>Comment</source>
<translation>Komentář</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID transakce</translation>
</message>
<message>
<source>Merchant</source>
<translation>Obchodník</translation>
</message>
<message>
<source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Vygenerované mince musí čekat %1 bloků, než mohou být utraceny. Když jsi vygeneroval tenhle blok, tak byl rozposlán do sítě, aby byl přidán do řetězce bloků. Pokud se mu nepodaří dostat se do řetězce, změní se na "neakceptovaný" a nepůjde utratit. To se občas může stát, pokud jiný uzel vygeneruje blok zhruba ve stejném okamžiku jako ty.</translation>
</message>
<message>
<source>Debug information</source>
<translation>Ladicí informace</translation>
</message>
<message>
<source>Transaction</source>
<translation>Transakce</translation>
</message>
<message>
<source>Inputs</source>
<translation>Vstupy</translation>
</message>
<message>
<source>Amount</source>
<translation>Částka</translation>
</message>
<message>
<source>true</source>
<translation>true</translation>
</message>
<message>
<source>false</source>
<translation>false</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, ještě nebylo rozesláno</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Otevřeno pro %n další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation>
</message>
<message>
<source>unknown</source>
<translation>neznámo</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>Detaily transakce</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Toto okno zobrazuje detailní popis transakce</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Nedozráno (%1 potvrzení, bude k dispozici za %2)</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Otevřeno pro %n další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Otřevřeno dokud %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Potvrzeno (%1 potvrzení)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Tento blok nedostal žádný jiný uzel a pravděpodobně nebude akceptován!</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Vygenerováno, ale neakceptováno</translation>
</message>
<message>
<source>Offline</source>
<translation>Offline</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Nepotvrzeno</translation>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Potvrzuje se (%1 z %2 doporučených potvrzení)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>V kolizi</translation>
</message>
<message>
<source>Received with</source>
<translation>Přijato do</translation>
</message>
<message>
<source>Received from</source>
<translation>Přijato od</translation>
</message>
<message>
<source>Sent to</source>
<translation>Posláno na</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Platba sama sobě</translation>
</message>
<message>
<source>Mined</source>
<translation>Vytěženo</translation>
</message>
<message>
<source>watch-only</source>
<translation>sledovací</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Stav transakce. Najetím myši na toto políčko si zobrazíš počet potvrzení.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Datum a čas přijetí transakce.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Druh transakce.</translation>
</message>
<message>
<source>Whether or not a watch-only address is involved in this transaction.</source>
<translation>Zda tato transakce zahrnuje i některou sledovanou adresu.</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>Cílová adresa transakce.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Částka odečtená z nebo přičtená k účtu.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Vše</translation>
</message>
<message>
<source>Today</source>
<translation>Dnes</translation>
</message>
<message>
<source>This week</source>
<translation>Tento týden</translation>
</message>
<message>
<source>This month</source>
<translation>Tento měsíc</translation>
</message>
<message>
<source>Last month</source>
<translation>Minulý měsíc</translation>
</message>
<message>
<source>This year</source>
<translation>Letos</translation>
</message>
<message>
<source>Range...</source>
<translation>Rozsah...</translation>
</message>
<message>
<source>Received with</source>
<translation>Přijato</translation>
</message>
<message>
<source>Sent to</source>
<translation>Posláno</translation>
</message>
<message>
<source>To yourself</source>
<translation>Sám sobě</translation>
</message>
<message>
<source>Mined</source>
<translation>Vytěženo</translation>
</message>
<message>
<source>Other</source>
<translation>Ostatní</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Zadej adresu nebo označení pro její vyhledání</translation>
</message>
<message>
<source>Min amount</source>
<translation>Minimální částka</translation>
</message>
<message>
<source>Copy address</source>
<translation>Kopíruj adresu</translation>
</message>
<message>
<source>Copy label</source>
<translation>Kopíruj její označení</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopíruj částku</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Kopíruj ID transakce</translation>
</message>
<message>
<source>Edit label</source>
<translation>Uprav označení</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Zobraz detaily transakce</translation>
</message>
<message>
<source>Export Transaction History</source>
<translation>Exportuj transakční historii</translation>
</message>
<message>
<source>Watch-only</source>
<translation>Sledovaná</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Exportování selhalo</translation>
</message>
<message>
<source>There was an error trying to save the transaction history to %1.</source>
<translation>Při ukládání transakční historie do %1 se přihodila nějaká chyba.</translation>
</message>
<message>
<source>Exporting Successful</source>
<translation>Úspěšně vyexportováno</translation>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation>Transakční historie byla v pořádku uložena do %1.</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>CSV formát (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Potvrzeno</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<source>Label</source>
<translation>Označení</translation>
</message>
<message>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>Rozsah:</translation>
</message>
<message>
<source>to</source>
<translation>až</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Jednotka pro částky. Klikni pro výběr nějaké jiné.</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>Žádná peněženka se nenačetla.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Pošli mince</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportuj data z tohoto panelu do souboru</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Záloha peněženky</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>Data peněženky (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>Zálohování selhalo</translation>
</message>
<message>
<source>There was an error trying to save the wallet data to %1.</source>
<translation>Při ukládání peněženky do %1 se přihodila nějaká chyba.</translation>
</message>
<message>
<source>The wallet data was successfully saved to %1.</source>
<translation>Data z peněženky byla v pořádku uložena do %1.</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>Úspěšně zazálohováno</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Možnosti:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Adresář pro data</translation>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Připojit se k uzlu, získat adresy jeho protějšků a odpojit se</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Specifikuj svou veřejnou adresu</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Akceptovat příkazy z příkazové řádky a přes JSON-RPC</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Běžet na pozadí jako démon a akceptovat příkazy</translation>
</message>
<message>
<source>Use the test network</source>
<translation>Použít testovací síť (testnet)</translation>
</message>
<message>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Přijímat spojení zvenčí (výchozí: 1, pokud není zadáno -proxy nebo -connect)</translation>
</message>
<message>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Poslouchat na zadané adrese. Pro zápis IPv6 adresy použij notaci [adresa]:port</translation>
</message>
<message>
<source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source>
<translation>Smazat všechny transakce peněženky a při startu obnovit pouze relevantní části řetězce bloků pomocí -rescan</translation>
</message>
<message>
<source>Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.</source>
<translation>Šířen pod softwarovou licencí MIT, viz přiložený soubor COPYING nebo <http://www.opensource.org/licenses/mit-license.php>.</translation>
</message>
<message>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source>
<translation>Přepnout do módu testování regresí, který používá speciální řetězec, ve kterém mohou být bloky okamžitě vyřešeny.</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Spustit příkaz, když se objeví transakce týkající se peněženky (%s se v příkazu nahradí za TxID)</translation>
</message>
<message>
<source>In this mode -genproclimit controls how many blocks are generated immediately.</source>
<translation>V tomto módu -genproclimit určuje, kolik bloků je vygenerováno okamžitě.</translation>
</message>
<message>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation>Nastavení počtu vláken pro verifikaci skriptů (%u až %d, 0 = automaticky, <0 = nechat daný počet jader volný, výchozí: %d)</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Tohle je testovací verze – používej ji jen na vlastní riziko, ale rozhodně ji nepoužívej k těžbě nebo pro obchodní aplikace</translation>
</message>
<message>
<source>Unable to bind to %s on this computer. Dotcoin Core is probably already running.</source>
<translation>Nedaří se mi připojit na %s na tomhle počítači. Dotcoin Core už pravděpodobně jednou běží.</translation>
</message>
<message>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Upozornění: -paytxfee je nastaveno velmi vysoko! Toto je transakční poplatek, který zaplatíš za každou poslanou transakci.</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Upozornění: Síť podle všeho není v konzistentním stavu. Někteří těžaři jsou zřejmě v potížích.</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Upozornění: Nesouhlasím zcela se svými protějšky! Možná potřebuji aktualizovat nebo ostatní uzly potřebují aktualizovat.</translation>
</message>
<message>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Upozornění: nastala chyba při čtení souboru wallet.dat! Všechny klíče se přečetly správně, ale data o transakcích nebo záznamy v adresáři mohou chybět či být nesprávné.</translation>
</message>
<message>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Upozornění: soubor wallet.dat je poškozený, data jsou však zachráněna! Původní soubor wallet.dat je uložený jako wallet.{timestamp}.bak v %s. Pokud je stav tvého účtu nebo transakce nesprávné, zřejmě bys měl obnovit zálohu.</translation>
</message>
<message>
<source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source>
<translation>Umístit na bílou listinu protějšky připojující se z dané podsítě či IP adresy. Lze zadat i vícekrát.</translation>
</message>
<message>
<source>(default: 1)</source>
<translation>(výchozí: 1)</translation>
</message>
<message>
<source><category> can be:</source>
<translation><category> může být:</translation>
</message>
<message>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Pokusit se zachránit soukromé klíče z poškozeného souboru wallet.dat</translation>
</message>
<message>
<source>Block creation options:</source>
<translation>Možnosti vytvoření bloku:</translation>
</message>
<message>
<source>Connect only to the specified node(s)</source>
<translation>Připojit se pouze k zadanému uzlu (příp. zadaným uzlům)</translation>
</message>
<message>
<source>Connection options:</source>
<translation>Možnosti připojení:</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Bylo zjištěno poškození databáze bloků</translation>
</message>
<message>
<source>Debugging/Testing options:</source>
<translation>Možnosti ladění/testování:</translation>
</message>
<message>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Zjistit vlastní IP adresu (výchozí: 1, pokud naslouchá a není zadáno -externalip)</translation>
</message>
<message>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation>Nenačítat peněženku a vypnout její RPC volání</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Chceš přestavět databázi bloků hned teď?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Chyba při zakládání databáze bloků</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Chyba při vytváření databázového prostředí %s pro peněženku!</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Chyba při načítání databáze bloků</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Chyba při otevírání databáze bloků</translation>
</message>
<message>
<source>Error: A fatal internal error occured, see debug.log for details</source>
<translation>Chyba: Stala se fatální vnitřní chyba. detaily viz v debug.log</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Problém: Na disku je málo místa!</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Nepodařilo se naslouchat na žádném portu. Použij -listen=0, pokud to byl tvůj záměr.</translation>
</message>
<message>
<source>If <category> is not supplied, output all debugging information.</source>
<translation>Pokud není <category> zadána, bude tisknout veškeré ladicí informace.</translation>
</message>
<message>
<source>Importing...</source>
<translation>Importuji...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Nemám žádný nebo jen špatný genesis blok. Není špatně nastavený datadir?</translation>
</message>
<message>
<source>Invalid -onion address: '%s'</source>
<translation>Neplatná -onion adresa: '%s'</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Je nedostatek deskriptorů souborů.</translation>
</message>
<message>
<source>Only connect to nodes in network <net> (ipv4, ipv6 or onion)</source>
<translation>Připojovat se pouze k uzlům v <net> síti (ipv4, ipv6 nebo onion)</translation>
</message>
<message>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Znovu vytvořit index řetězce bloků z aktuálních blk000??.dat souborů</translation>
</message>
<message>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation>Nastavit velikost databázové vyrovnávací paměti v megabajtech (%d až %d, výchozí: %d)</translation>
</message>
<message>
<source>Set maximum block size in bytes (default: %d)</source>
<translation>Nastavit maximální velikost bloku v bajtech (výchozí: %d)</translation>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation>Udej název souboru s peněženkou (v rámci datového adresáře)</translation>
</message>
<message>
<source>This is intended for regression testing tools and app development.</source>
<translation>Tohle je určeno pro nástroje na regresní testování a vyvíjení aplikací.</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: %u)</source>
<translation>Použít UPnP k namapování naslouchacího portu (výchozí: %u)</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Ověřuji bloky... </translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Kontroluji peněženku...</translation>
</message>
<message>
<source>Wallet %s resides outside data directory %s</source>
<translation>Peněženka %s se nachází mimo datový adresář %s</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Možnosti peněženky:</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation>Je třeba přestavět databázi použitím -reindex, aby bylo možné změnit -txindex</translation>
</message>
<message>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importovat bloky z externího souboru blk000??.dat</translation>
</message>
<message>
<source>Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source>
<translation>Povolit JSON-RPC spojení ze specifikovaného zdroje. Platnou hodnotou <ip> je jednotlivá IP adresa (např. 1.2.3.4), síť/maska (např. 1.2.3.4/255.255.255.0) nebo síť/CIDR (např. 1.2.3.4/24). Tuto volbu lze použít i vícekrát</translation>
</message>
<message>
<source>An error occurred while setting up the RPC address %s port %u for listening: %s</source>
<translation>Při nastavování naslouchací RPC adresy %s a portu %u nastala chyba: %s</translation>
</message>
<message>
<source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source>
<translation>Obsadit zadanou adresu a protějšky, které se na ní připojí, umístit na bílou listinu. Pro zápis IPv6 adresy použij notaci [adresa]:port</translation>
</message>
<message>
<source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source>
<translation>Čekat na zadané adrese na JSON-RPC spojení. Pro zápis IPv6 adresy použij notaci [adresa]:port. Tuto volbu lze použít i vícekrát (výchozí: poslouchat na všech rozhraních)</translation>
</message>
<message>
<source>Cannot obtain a lock on data directory %s. Dotcoin Core is probably already running.</source>
<translation>Nedaří se mi získat zámek na datový adresář %s. Dotcoin Core pravděpodobně už jednou běží.</translation>
</message>
<message>
<source>Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:%u)</source>
<translation>Kontinuálně omezovat bezpoplatkové transakce na <n>*1000 bajtů za minutu (výchozí: %u)</translation>
</message>
<message>
<source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source>
<translation>Vytvářet nové soubory s výchozími systémovými právy namísto umask 077 (uplatní se, pouze pokud je vypnutá funkce peněženky)</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>Chyba: Nelze naslouchat příchozí spojení (listen vrátil chybu %s)</translation>
</message>
<message>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation>Chyba: Byl použit nepodporovaný argument -socks. Nastavení verze SOCKS už není možné, podporovány jsou pouze SOCKS5 proxy.</translation>
</message>
<message>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation>Spustit příkaz, když přijde relevantní upozornění nebo když dojde k opravdu dlouhému rozštěpení řetezce bloků (%s se v příkazu nahradí zprávou)</translation>
</message>
<message>
<source>Fees (in DOT/Kb) smaller than this are considered zero fee for relaying (default: %s)</source>
<translation>Poplatky (v DOT/Kb) menší než tato hodnota jsou považovány za nulové pro účely přeposílání transakcí (výchozí: %s)</translation>
</message>
<message>
<source>Fees (in DOT/Kb) smaller than this are considered zero fee for transaction creation (default: %s)</source>
<translation>Poplatky (v DOT/Kb) menší než tato hodnota jsou považovány za nulové pro účely vytváření transakcí (výchozí: %s)</translation>
</message>
<message>
<source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source>
<translation>Pokud paytxfee není nastaveno, platit dostatečný poplatek na to, aby byly transakce potvrzeny v průměru během n bloků (výchozí: %u)</translation>
</message>
<message>
<source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source>
<translation>Maximální velikost dat v transakcích nesoucích data, se kterou jsme ochotni je ještě přeposílat a těžit (výchozí: %u)</translation>
</message>
<message>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation>Při nedostatku adres získat další protějšky z DNS (výchozí: 1, pokud není použito -connect)</translation>
</message>
<message>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation>Nastavit maximální velikost prioritních/nízkopoplatkových transakcí v bajtech (výchozí: %d)</translation>
</message>
<message>
<source>Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)</source>
<translation>Nastavení počtu vláken pro těžení, je-li zapnuté (-1 = všechna jádra, výchozí: %d)</translation>
</message>
<message>
<source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source>
<translation>Tento produkt zahrnuje programy vyvinuté OpenSSL Projektem pro použití v OpenSSL Toolkitu <https://www.openssl.org/> a kryptografický program od Erika Younga a program UPnP od Thomase Bernarda.</translation>
</message>
<message>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Dotcoin Core will not work properly.</source>
<translation>Upozornění: Zkontroluj, že máš v počítači správně nastavený datum a čas! Pokud jsou nastaveny špatně, Dotcoin Core nebude fungovat správně.</translation>
</message>
<message>
<source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source>
<translation>Na protějšky na bílé listině se nevztahuje DoS klatba a jejich transakce jsou vždy přeposílány, i když už třeba jsou v mempoolu, což je užitečné např. pro bránu</translation>
</message>
<message>
<source>Cannot resolve -whitebind address: '%s'</source>
<translation>Nemohu přeložit -whitebind adresu: '%s'</translation>
</message>
<message>
<source>Connect through SOCKS5 proxy</source>
<translation>Připojit se přes SOCKS5 proxy</translation>
</message>
<message>
<source>Copyright (C) 2009-%i The Bitcoin Core Developers</source>
<translation>Copyright (C) 2009-%i Vývojáři Bitcoin Core</translation>
</message>
<message>
<source>Could not parse -rpcbind value %s as network address</source>
<translation>Nejde mi přečíst hodnotu -rpcbind %s jako síťovou adresu</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet requires newer version of Dotcoin Core</source>
<translation>Chyba při načítání wallet.dat: peněženka vyžaduje novější verzi Dotcoin Core</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Chyba při čtení z databáze, ukončuji se.</translation>
</message>
<message>
<source>Error: Unsupported argument -tor found, use -onion.</source>
<translation>Chyba: Argument -tor již není podporovaný, použij -onion.</translation>
</message>
<message>
<source>Fee (in DOT/kB) to add to transactions you send (default: %s)</source>
<translation>Poplatek (v DOT/kB), který se přidá ke každé odeslané transakci (výchozí: %s)</translation>
</message>
<message>
<source>Information</source>
<translation>Informace</translation>
</message>
<message>
<source>Initialization sanity check failed. Dotcoin Core is shutting down.</source>
<translation>Selhala úvodní zevrubná prověrka. Dotcoin Core se ukončuje.</translation>
</message>
<message>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Neplatná částka pro -minrelaytxfee=<částka>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Neplatná částka pro -mintxfee=<částka>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Neplatná částka pro -paytxfee=<částka>: '%s' (musí být alespoň %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>Ve -whitelist byla zadána neplatná podsíť: '%s'</translation>
</message>
<message>
<source>Keep at most <n> unconnectable transactions in memory (default: %u)</source>
<translation>Držet v paměti nejvýše <n> nespojitelných transakcí (výchozí: %u)</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>V rámci -whitebind je třeba specifikovat i port: '%s'</translation>
</message>
<message>
<source>Node relay options:</source>
<translation>Možnosti přeposílání:</translation>
</message>
<message>
<source>RPC SSL options: (see the Dotcoin Wiki for SSL setup instructions)</source>
<translation>Možnosti SSL pro RPC: (viz instrukce nastavení SSL na Dotcoin Wiki)</translation>
</message>
<message>
<source>RPC server options:</source>
<translation>Možnosti RPC serveru:</translation>
</message>
<message>
<source>Randomly drop 1 of every <n> network messages</source>
<translation>Náhodně zahazovat jednu z každých <n> síťových zpráv</translation>
</message>
<message>
<source>Randomly fuzz 1 of every <n> network messages</source>
<translation>Náhodně pozměňovat jednu z každých <n> síťových zpráv</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Posílat stopovací/ladicí informace do konzole místo do souboru debug.log</translation>
</message>
<message>
<source>Send transactions as zero-fee transactions if possible (default: %u)</source>
<translation>Posílat transakce pokud možno bez poplatků (výchozí: %u)</translation>
</message>
<message>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation>Zobrazit všechny možnosti ladění (užití: --help -help-debug)</translation>
</message>
<message>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Při spuštění klienta zmenšit soubor debug.log (výchozí: 1, pokud není zadáno -debug)</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Nepodařilo se podepsat transakci</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Tohle je experimentální program.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Částka v transakci je příliš malá</translation>
</message>
<message>
<source>Transaction amounts must be positive</source>
<translation>Částky v transakci musí být kladné</translation>
</message>
<message>
<source>Transaction too large for fee policy</source>
<translation>Transakce je na poplatkovou politiku příliš velká</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Transakce je příliš velká</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>Nedaří se mi připojit na %s na tomhle počítači (operace bind vrátila chybu %s)</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Použít UPnP k namapování naslouchacího portu (výchozí: 1, pokud naslouchá)</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Uživatelské jméno pro JSON-RPC spojení</translation>
</message>
<message>
<source>Wallet needed to be rewritten: restart Dotcoin Core to complete</source>
<translation>Soubor s peněženkou potřeboval přepsat: restartuj Dotcoin Core, aby se operace dokončila</translation>
</message>
<message>
<source>Warning</source>
<translation>Upozornění</translation>
</message>
<message>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Upozornění: tahle verze je zastaralá, měl bys ji aktualizovat!</translation>
</message>
<message>
<source>Warning: Unsupported argument -benchmark ignored, use -debug=bench.</source>
<translation>Upozornění: Nepodporovaný argument -benchmark se ignoruje, použij -debug=bench.</translation>
</message>
<message>
<source>Warning: Unsupported argument -debugnet ignored, use -debug=net.</source>
<translation>Upozornění: Nepodporovaný argument -debugnet se ignoruje, použij -debug=net.</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Vymazat všechny transakce z peněženky...</translation>
</message>
<message>
<source>on startup</source>
<translation>při startu</translation>
</message>
<message>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Soubor wallet.dat je poškozen, jeho záchrana se nezdařila</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Heslo pro JSON-RPC spojení</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Spustit příkaz, když se změní nejlepší blok (%s se v příkazu nahradí hashem bloku)</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>Převést peněženku na nejnovější formát</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Přeskenovat řetězec bloků na chybějící transakce tvé pěněženky</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Použít OpenSSL (https) pro JSON-RPC spojení</translation>
</message>
<message>
<source>This help message</source>
<translation>Tato nápověda</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Povolit DNS dotazy pro -addnode (přidání uzlu), -seednode a -connect (připojení)</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Načítám adresy...</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Chyba při načítání wallet.dat: peněženka je poškozená</translation>
</message>
<message>
<source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source>
<translation>(1 = ukládat transakční metadata, např. majitele účtu a informace o platebním požadavku, 2 = mazat transakční metadata)</translation>
</message>
<message>
<source>Flush database activity from memory pool to disk log every <n> megabytes (default: %u)</source>
<translation>Promítnout databázovou aktivitu z paměťového prostoru do záznamu na disku každých <n> megabajtů (výchozí: %u)</translation>
</message>
<message>
<source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source>
<translation>Jak moc důkladná má být verifikace bloků -checkblocks (0-4, výchozí: %u)</translation>
</message>
<message>
<source>Log transaction priority and fee per kB when mining blocks (default: %u)</source>
<translation>Zaznamenávat během těžení bloků prioritu transakce a poplatek za kB (výchozí: %u)</translation>
</message>
<message>
<source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source>
<translation>Spravovat úplný index transakcí, který je využíván rpc voláním getrawtransaction (výchozí: %u)</translation>
</message>
<message>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source>
<translation>Doba ve vteřinách, po kterou se nebudou moci zlobivé protějšky znovu připojit (výchozí: %u)</translation>
</message>
<message>
<source>Output debugging information (default: %u, supplying <category> is optional)</source>
<translation>Tisknout ladicí informace (výchozí: %u, zadání <category> je volitelné)</translation>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source>
<translation>Použít samostatnou SOCKS5 proxy ke spojení s protějšky přes skryté služby v Toru (výchozí: %s)</translation>
</message>
<message>
<source>(default: %s)</source>
<translation>(výchozí: %s)</translation>
</message>
<message>
<source>Acceptable ciphers (default: %s)</source>
<translation>Akceptovatelné šifry (výchozí: %s)</translation>
</message>
<message>
<source>Always query for peer addresses via DNS lookup (default: %u)</source>
<translation>Vždy získávat adresy dalších protějšků přes DNS (výchozí: %u)</translation>
</message>
<message>
<source>Disable safemode, override a real safe mode event (default: %u)</source>
<translation>Vypnout bezpečný režim (safemode), překrýt skutečnou událost bezpečného režimu (výchozí: %u)</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>Chyba při načítání wallet.dat</translation>
</message>
<message>
<source>Force safe mode (default: %u)</source>
<translation>Vynutit bezpečný mód (výchozí: %u)</translation>
</message>
<message>
<source>Generate coins (default: %u)</source>
<translation>Těžit (výchozí: %u)</translation>
</message>
<message>
<source>How many blocks to check at startup (default: %u, 0 = all)</source>
<translation>Kolik bloků při startu zkontrolovat (výchozí: %u, 0 = všechny)</translation>
</message>
<message>
<source>Include IP addresses in debug output (default: %u)</source>
<translation>Zaznamenávat do ladicích výstupů i IP adresy (výchozí: %u)</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Neplatná -proxy adresa: '%s'</translation>
</message>
<message>
<source>Limit size of signature cache to <n> entries (default: %u)</source>
<translation>Omezit velikost vyrovnávací paměti pro podpisy na <n> položek (výchozí: %u)</translation>
</message>
<message>
<source>Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)</source>
<translation>Čekat na JSON-RPC spojení na <portu> (výchozí: %u nebo testnet: %u)</translation>
</message>
<message>
<source>Listen for connections on <port> (default: %u or testnet: %u)</source>
<translation>Čekat na spojení na <portu> (výchozí: %u nebo testnet: %u)</translation>
</message>
<message>
<source>Maintain at most <n> connections to peers (default: %u)</source>
<translation>Povolit nejvýše <n> protějšků (výchozí: %u)</translation>
</message>
<message>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)</source>
<translation>Maximální velikost přijímacího bufferu pro každé spojení, <n>*1000 bajtů (výchozí: %u)</translation>
</message>
<message>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: %u)</source>
<translation>Maximální velikost odesílacího bufferu pro každé spojení, <n>*1000 bajtů (výchozí: %u)</translation>
</message>
<message>
<source>Only accept block chain matching built-in checkpoints (default: %u)</source>
<translation>Uznávat pouze řetězec bloků, který odpovídá vnitřním kontrolním bodům (výchozí: %u)</translation>
</message>
<message>
<source>Prepend debug output with timestamp (default: %u)</source>
<translation>Připojit před ladicí výstup časové razítko (výchozí: %u)</translation>
</message>
<message>
<source>Relay and mine data carrier transactions (default: %u)</source>
<translation>Přeposílat a těžit transakce nesoucí data (výchozí: %u)</translation>
</message>
<message>
<source>Relay non-P2SH multisig (default: %u)</source>
<translation>Přeposílat ne-P2SH multisig (výchozí: %u)</translation>
</message>
<message>
<source>Run a thread to flush wallet periodically (default: %u)</source>
<translation>Spustit vlákno pročišťující periodicky peněženku (výchozí: %u)</translation>
</message>
<message>
<source>Server certificate file (default: %s)</source>
<translation>Soubor se serverovým certifikátem (výchozí: %s)</translation>
</message>
<message>
<source>Server private key (default: %s)</source>
<translation>Soubor se serverovým soukromým klíčem (výchozí: %s)</translation>
</message>
<message>
<source>Set key pool size to <n> (default: %u)</source>
<translation>Nastavit zásobník klíčů na velikost <n> (výchozí: %u)</translation>
</message>
<message>
<source>Set minimum block size in bytes (default: %u)</source>
<translation>Nastavit minimální velikost bloku v bajtech (výchozí: %u)</translation>
</message>
<message>
<source>Set the number of threads to service RPC calls (default: %d)</source>
<translation>Nastavení počtu vláken pro servisní RPC volání (výchozí: %d)</translation>
</message>
<message>
<source>Sets the DB_PRIVATE flag in the wallet db environment (default: %u)</source>
<translation>Nastavit příznak DB_PRIVATE v databázovém prostředí peněženky (výchozí: %u)</translation>
</message>
<message>
<source>Specify configuration file (default: %s)</source>
<translation>Konfigurační soubor (výchozí: %s)</translation>
</message>
<message>
<source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source>
<translation>Zadej časový limit spojení v milivteřinách (minimum: 1, výchozí: %d)</translation>
</message>
<message>
<source>Spend unconfirmed change when sending transactions (default: %u)</source>
<translation>Utrácet i ještě nepotvrzené drobné při posílání transakcí (výchozí: %u)</translation>
</message>
<message>
<source>Stop running after importing blocks from disk (default: %u)</source>
<translation>Ukončit se po importu bloků z disku (výchozí: %u)</translation>
</message>
<message>
<source>Threshold for disconnecting misbehaving peers (default: %u)</source>
<translation>Práh pro odpojování zlobivých protějšků (výchozí: %u)</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>V -onlynet byla uvedena neznámá síť: '%s'</translation>
</message>
<message>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Nemohu přeložit -bind adresu: '%s'</translation>
</message>
<message>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Nemohu přeložit -externalip adresu: '%s'</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Neplatná částka pro -paytxfee=<částka>: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Nedostatek prostředků</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Načítám index bloků...</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Přidat uzel, ke kterému se připojit a snažit se spojení udržet</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Načítám peněženku...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Nemohu převést peněženku do staršího formátu</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>Nemohu napsat výchozí adresu</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Přeskenovávám...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Načítání dokončeno</translation>
</message>
<message>
<source>Error</source>
<translation>Chyba</translation>
</message>
</context>
</TS>
| {
"content_hash": "45b3e46530454f0b245da4707fc4a334",
"timestamp": "",
"source": "github",
"line_count": 3506,
"max_line_length": 379,
"avg_line_length": 40.45065601825442,
"alnum_prop": 0.6603652517275419,
"repo_name": "wargo32/DOTCoin",
"id": "70de713982549c8f1b1214cb60c6757fc26a5698",
"size": "145189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_cs.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7639"
},
{
"name": "C",
"bytes": "342282"
},
{
"name": "C++",
"bytes": "3536519"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "18050"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "Makefile",
"bytes": "61686"
},
{
"name": "Objective-C",
"bytes": "2023"
},
{
"name": "Objective-C++",
"bytes": "7246"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "211877"
},
{
"name": "QMake",
"bytes": "2019"
},
{
"name": "Shell",
"bytes": "40505"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<!--<link rel = "stylesheet" href = "http://localhost/sense/asset/css/bootstrap.min.css"> -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="<?php echo base_url()?>asset/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<title>Category group management</title>
</head>
<body>
<div class="container">
<h2 class="text-primary">Edit Category Group</h2><br>
<table class="table table-striped table-bordered table-hover table-condensed">
<tr>
<th class="text-info">ID</th>
<th class="text-info">NAME</th>
<th class="text-info">TITLE</th>
<th class="text-info">STATUS</th>
</tr>
<?php $options = array(
'active' => 'Active',
'inactive' => 'Inactive'
)?>
<?php foreach ( $aCategory_group as $key => $data ):?>
<form action="<?php echo base_url()?>category/edit_category_group" method="post">
<tr>
<td> <?php echo ++$key ?> </td>
<td> <?php echo '<input type = "text" name ="group_name" value = "'.$data->name.'">'; ?> </td>
<td> <?php echo '<input type = "text" name ="group_title" value = "'.$data->title.'">';?> </td>
<td><?php foreach ( $aStatus as $status ):?>
<?php if( $data->status == $status->id ):?>
<?php $group_status = $status->title ?>
<?php echo form_dropdown('category_group_status', $options, $group_status);?>
<?php endif;?>
<?php endforeach;?>
</td>
<td><button type="submit" class="btn btn-default" data-category ="<?php echo $data->id ?>">Update</button></td>
<?php endforeach;?>
</form>
</table>
</div>
</body>
</body>
</html>
| {
"content_hash": "379601f53a7055e2d5849a5b3fe79643",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 215,
"avg_line_length": 45.78846153846154,
"alnum_prop": 0.5472490550188996,
"repo_name": "kirandamac/sense",
"id": "40d3760221732389860958d47b67851a61b52ffc",
"size": "2381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/category/edit_category_group1.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "365"
},
{
"name": "CSS",
"bytes": "14838"
},
{
"name": "HTML",
"bytes": "8516350"
},
{
"name": "JavaScript",
"bytes": "57540"
},
{
"name": "PHP",
"bytes": "1793891"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Fri Jun 16 09:55:13 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.jaxrs.btm.zipkin Class Hierarchy (Public javadocs 2017.6.1 API)</title>
<meta name="date" content="2017-06-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.wildfly.swarm.jaxrs.btm.zipkin Class Hierarchy (Public javadocs 2017.6.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/jaxrs/btm/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/wildfly/swarm/jaxrs/detect/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/jaxrs/btm/zipkin/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.wildfly.swarm.jaxrs.btm.zipkin</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.wildfly.swarm.jaxrs.btm.zipkin.<a href="../../../../../../org/wildfly/swarm/jaxrs/btm/zipkin/BraveFactory.html" title="class in org.wildfly.swarm.jaxrs.btm.zipkin"><span class="typeNameLink">BraveFactory</span></a></li>
<li type="circle">org.wildfly.swarm.jaxrs.btm.zipkin.<a href="../../../../../../org/wildfly/swarm/jaxrs/btm/zipkin/ClientRequestInterceptor.html" title="class in org.wildfly.swarm.jaxrs.btm.zipkin"><span class="typeNameLink">ClientRequestInterceptor</span></a></li>
<li type="circle">org.wildfly.swarm.jaxrs.btm.zipkin.<a href="../../../../../../org/wildfly/swarm/jaxrs/btm/zipkin/ClientResponseInterceptor.html" title="class in org.wildfly.swarm.jaxrs.btm.zipkin"><span class="typeNameLink">ClientResponseInterceptor</span></a></li>
<li type="circle">org.wildfly.swarm.jaxrs.btm.zipkin.<a href="../../../../../../org/wildfly/swarm/jaxrs/btm/zipkin/ServerRequestInterceptor.html" title="class in org.wildfly.swarm.jaxrs.btm.zipkin"><span class="typeNameLink">ServerRequestInterceptor</span></a></li>
<li type="circle">org.wildfly.swarm.jaxrs.btm.zipkin.<a href="../../../../../../org/wildfly/swarm/jaxrs/btm/zipkin/ServerResponseInterceptor.html" title="class in org.wildfly.swarm.jaxrs.btm.zipkin"><span class="typeNameLink">ServerResponseInterceptor</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/wildfly/swarm/jaxrs/btm/package-tree.html">Prev</a></li>
<li><a href="../../../../../../org/wildfly/swarm/jaxrs/detect/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/jaxrs/btm/zipkin/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "0ddc24663989237a41c1b93b31ea8ce5",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 267,
"avg_line_length": 44.55172413793103,
"alnum_prop": 0.6348297213622291,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "fd979c2fa11886b8e4ea3e4fdcde28617cef0ed6",
"size": "6460",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2017.6.1/apidocs/org/wildfly/swarm/jaxrs/btm/zipkin/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package hu.scelight.gui.setting;
import hu.scelight.service.env.Env;
import hu.scelight.service.extmod.ModEnv;
import hu.scelightapibase.bean.settings.ISettingsBean;
import hu.scelightapibase.bean.settings.type.INodeSetting;
import hu.sllauncher.gui.setting.LSettingsDialog;
import hu.sllauncher.gui.setting.LSettingsNodePage;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.List;
/**
* A dialog to view/edit settings of the application.
*
* @author Andras Belicza
*/
@SuppressWarnings( "serial" )
public class SettingsDialog extends LSettingsDialog {
/**
* Returns an array of all settings beans. These include the settings beans of loaded external modules.
*
* @return an array of all settings beans
*/
private static ISettingsBean[] getAllSettingss() {
final List< ISettingsBean > settingsList = new ArrayList<>();
settingsList.add( Env.BOOT_SETTINGS );
settingsList.add( Env.LAUNCHER_SETTINGS );
settingsList.add( Env.APP_SETTINGS );
for ( final ModEnv modEnv : Env.EXT_MOD_MANAGER.getStartedExtModEnvList() )
settingsList.addAll( modEnv.getSettingsBeanList() );
return settingsList.toArray( new ISettingsBean[ settingsList.size() ] );
}
/**
* Creates a new {@link SettingsDialog}.
*
* <p>
* <b>Does not make the dialog visible!</b>
* </p>
*
* @param owner reference to the owner frame
* @param defaultNodeSetting optional node setting to select by default
*/
public SettingsDialog( final Frame owner, final INodeSetting defaultNodeSetting ) {
super( owner, defaultNodeSetting, getAllSettingss() );
}
/**
* Overridden to return a new instance of {@link SettingsNodePage}.
*/
@Override
protected LSettingsNodePage createNewSettingsNodePage( final INodeSetting nodeSetting ) {
return new SettingsNodePage( nodeSetting );
}
}
| {
"content_hash": "de4d40582286423415056b590910e6b2",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 104,
"avg_line_length": 30.548387096774192,
"alnum_prop": 0.7180570221752904,
"repo_name": "icza/scelight",
"id": "d3a166ae720e3f159436a688e14e7423fdab2fa3",
"size": "2164",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src-app/hu/scelight/gui/setting/SettingsDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2394"
},
{
"name": "Dockerfile",
"bytes": "390"
},
{
"name": "HTML",
"bytes": "212964"
},
{
"name": "Java",
"bytes": "3431340"
},
{
"name": "Shell",
"bytes": "1946"
}
],
"symlink_target": ""
} |
{-|
Description: response utilities
utilities and defaults for sending responses.
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Web.Respond.DefaultHandlers where
import Control.Applicative ((<$>))
import Network.Wai
import qualified Data.ByteString as BS
import Network.HTTP.Types.Status
--import Network.HTTP.Types.Header
import Network.HTTP.Types.Method
--import Control.Lens (view)
import Web.Respond.Types
import Web.Respond.Monad
import Web.Respond.Response
-- | default failure handlers. uses the defaultXHandler for each field
defaultHandlers :: FailureHandlers
defaultHandlers = FailureHandlers {
_unsupportedMethod = defaultUnsupportedMethodHandler,
_unmatchedPath = defaultUnmatchedPathHandler,
_bodyParseFailed = defaultBodyParseFailureHandler,
_authFailed = defaultAuthFailedHandler,
_accessDenied = defaultAccessDeniedHandler,
_caughtException = defaultCaughtExceptionHandler,
_unacceptableResponse = defaultUnacceptableResponseHandler
}
-- | default unsupported method handler sends back an EmptyBody with status
-- 405 and an Allowed header listing the allowed methods in the first path
defaultUnsupportedMethodHandler :: MonadRespond m => [StdMethod] -> Method -> m ResponseReceived
defaultUnsupportedMethodHandler allowed = const $ respondEmptyBody methodNotAllowed405 [("Allowed", allowedStr allowed)]
where allowedStr mths = BS.intercalate ", " (renderStdMethod <$> mths)
-- | respond with status404 and nothing else
defaultUnmatchedPathHandler :: MonadRespond m => m ResponseReceived
defaultUnmatchedPathHandler = respondEmptyBody notFound404 []
-- | respond with status 400 and a message about the body parse failure
defaultBodyParseFailureHandler :: (MonadRespond m, ReportableError e) => e -> m ResponseReceived
defaultBodyParseFailureHandler = respondReportError badRequest400 []
-- | respond with 401
defaultAuthFailedHandler :: (MonadRespond m, ReportableError e) => e -> m ResponseReceived
defaultAuthFailedHandler = respondReportError unauthorized401 []
-- | respond with 403
defaultAccessDeniedHandler :: (MonadRespond m, ReportableError e) => e -> m ResponseReceived
defaultAccessDeniedHandler = respondReportError forbidden403 []
-- | respond with 500
defaultCaughtExceptionHandler :: (MonadRespond m, ReportableError e) => e -> m ResponseReceived
defaultCaughtExceptionHandler = respondReportError internalServerError500 []
-- | respond with 406
defaultUnacceptableResponseHandler :: MonadRespond m => m ResponseReceived
defaultUnacceptableResponseHandler = respondEmptyBody notAcceptable406 []
| {
"content_hash": "c72515116076a964f491008e502c291e",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 120,
"avg_line_length": 41.935483870967744,
"alnum_prop": 0.8026923076923077,
"repo_name": "raptros/respond",
"id": "817e1c8655e23de6cb6917e0f0671bdeab529b0f",
"size": "2600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Web/Respond/DefaultHandlers.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "62751"
}
],
"symlink_target": ""
} |
/* Most of this hacked by Steve Chamberlain <sac@cygnus.com>.
PE/PEI rearrangement (and code added): Donn Terry
Softway Systems, Inc. */
/* Hey look, some documentation [and in a place you expect to find it]!
The main reference for the pei format is "Microsoft Portable Executable
and Common Object File Format Specification 4.1". Get it if you need to
do some serious hacking on this code.
Another reference:
"Peering Inside the PE: A Tour of the Win32 Portable Executable
File Format", MSJ 1994, Volume 9.
The *sole* difference between the pe format and the pei format is that the
latter has an MSDOS 2.0 .exe header on the front that prints the message
"This app must be run under Windows." (or some such).
(FIXME: Whether that statement is *really* true or not is unknown.
Are there more subtle differences between pe and pei formats?
For now assume there aren't. If you find one, then for God sakes
document it here!)
The Microsoft docs use the word "image" instead of "executable" because
the former can also refer to a DLL (shared library). Confusion can arise
because the `i' in `pei' also refers to "image". The `pe' format can
also create images (i.e. executables), it's just that to run on a win32
system you need to use the pei format.
FIXME: Please add more docs here so the next poor fool that has to hack
on this code has a chance of getting something accomplished without
wasting too much time. */
/* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64
depending on whether we're compiling for straight PE or PE+. */
#define COFF_WITH_XX
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "coff/internal.h"
#include "bfdver.h"
#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif
/* NOTE: it's strange to be including an architecture specific header
in what's supposed to be general (to PE/PEI) code. However, that's
where the definitions are, and they don't vary per architecture
within PE/PEI, so we get them from there. FIXME: The lack of
variance is an assumption which may prove to be incorrect if new
PE/PEI targets are created. */
#if defined COFF_WITH_pex64
# include "coff/x86_64.h"
#elif defined COFF_WITH_pep
# include "coff/ia64.h"
#else
# include "coff/i386.h"
#endif
#include "coff/pe.h"
#include "libcoff.h"
#include "libpei.h"
#include "safe-ctype.h"
#if defined COFF_WITH_pep || defined COFF_WITH_pex64
# undef AOUTSZ
# define AOUTSZ PEPAOUTSZ
# define PEAOUTHDR PEPAOUTHDR
#endif
#define HighBitSet(val) ((val) & 0x80000000)
#define SetHighBit(val) ((val) | 0x80000000)
#define WithoutHighBit(val) ((val) & 0x7fffffff)
/* FIXME: This file has various tests of POWERPC_LE_PE. Those tests
worked when the code was in peicode.h, but no longer work now that
the code is in peigen.c. PowerPC NT is said to be dead. If
anybody wants to revive the code, you will have to figure out how
to handle those issues. */
void
_bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
{
SYMENT *ext = (SYMENT *) ext1;
struct internal_syment *in = (struct internal_syment *) in1;
if (ext->e.e_name[0] == 0)
{
in->_n._n_n._n_zeroes = 0;
in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
}
else
memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
in->n_value = H_GET_32 (abfd, ext->e_value);
in->n_scnum = H_GET_16 (abfd, ext->e_scnum);
if (sizeof (ext->e_type) == 2)
in->n_type = H_GET_16 (abfd, ext->e_type);
else
in->n_type = H_GET_32 (abfd, ext->e_type);
in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
#ifndef STRICT_PE_FORMAT
/* This is for Gnu-created DLLs. */
/* The section symbols for the .idata$ sections have class 0x68
(C_SECTION), which MS documentation indicates is a section
symbol. Unfortunately, the value field in the symbol is simply a
copy of the .idata section's flags rather than something useful.
When these symbols are encountered, change the value to 0 so that
they will be handled somewhat correctly in the bfd code. */
if (in->n_sclass == C_SECTION)
{
char namebuf[SYMNMLEN + 1];
const char *name = NULL;
in->n_value = 0x0;
/* Create synthetic empty sections as needed. DJ */
if (in->n_scnum == 0)
{
asection *sec;
name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
if (name == NULL)
/* FIXME: Return error. */
abort ();
sec = bfd_get_section_by_name (abfd, name);
if (sec != NULL)
in->n_scnum = sec->target_index;
}
if (in->n_scnum == 0)
{
int unused_section_number = 0;
asection *sec;
flagword flags;
for (sec = abfd->sections; sec; sec = sec->next)
if (unused_section_number <= sec->target_index)
unused_section_number = sec->target_index + 1;
if (name == namebuf)
{
name = (const char *) bfd_alloc (abfd, strlen (namebuf) + 1);
if (name == NULL)
/* FIXME: Return error. */
abort ();
strcpy ((char *) name, namebuf);
}
flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
sec = bfd_make_section_anyway_with_flags (abfd, name, flags);
if (sec == NULL)
/* FIXME: Return error. */
abort ();
sec->vma = 0;
sec->lma = 0;
sec->size = 0;
sec->filepos = 0;
sec->rel_filepos = 0;
sec->reloc_count = 0;
sec->line_filepos = 0;
sec->lineno_count = 0;
sec->userdata = NULL;
sec->next = NULL;
sec->alignment_power = 2;
sec->target_index = unused_section_number;
in->n_scnum = unused_section_number;
}
in->n_sclass = C_STAT;
}
#endif
#ifdef coff_swap_sym_in_hook
/* This won't work in peigen.c, but since it's for PPC PE, it's not
worth fixing. */
coff_swap_sym_in_hook (abfd, ext1, in1);
#endif
}
unsigned int
_bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
{
struct internal_syment *in = (struct internal_syment *) inp;
SYMENT *ext = (SYMENT *) extp;
if (in->_n._n_name[0] == 0)
{
H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
}
else
memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
H_PUT_32 (abfd, in->n_value, ext->e_value);
H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
if (sizeof (ext->e_type) == 2)
H_PUT_16 (abfd, in->n_type, ext->e_type);
else
H_PUT_32 (abfd, in->n_type, ext->e_type);
H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
return SYMESZ;
}
void
_bfd_XXi_swap_aux_in (bfd * abfd,
void * ext1,
int type,
int in_class,
int indx ATTRIBUTE_UNUSED,
int numaux ATTRIBUTE_UNUSED,
void * in1)
{
AUXENT *ext = (AUXENT *) ext1;
union internal_auxent *in = (union internal_auxent *) in1;
switch (in_class)
{
case C_FILE:
if (ext->x_file.x_fname[0] == 0)
{
in->x_file.x_n.x_zeroes = 0;
in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
}
else
memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
return;
case C_STAT:
case C_LEAFSTAT:
case C_HIDDEN:
if (type == T_NULL)
{
in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
return;
}
break;
}
in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
|| ISTAG (in_class))
{
in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
}
else
{
in->x_sym.x_fcnary.x_ary.x_dimen[0] =
H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
in->x_sym.x_fcnary.x_ary.x_dimen[1] =
H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
in->x_sym.x_fcnary.x_ary.x_dimen[2] =
H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
in->x_sym.x_fcnary.x_ary.x_dimen[3] =
H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
}
if (ISFCN (type))
{
in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
}
else
{
in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
}
}
unsigned int
_bfd_XXi_swap_aux_out (bfd * abfd,
void * inp,
int type,
int in_class,
int indx ATTRIBUTE_UNUSED,
int numaux ATTRIBUTE_UNUSED,
void * extp)
{
union internal_auxent *in = (union internal_auxent *) inp;
AUXENT *ext = (AUXENT *) extp;
memset (ext, 0, AUXESZ);
switch (in_class)
{
case C_FILE:
if (in->x_file.x_fname[0] == 0)
{
H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
}
else
memcpy (ext->x_file.x_fname, in->x_file.x_fname, FILNMLEN);
return AUXESZ;
case C_STAT:
case C_LEAFSTAT:
case C_HIDDEN:
if (type == T_NULL)
{
PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
return AUXESZ;
}
break;
}
H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
|| ISTAG (in_class))
{
PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr, ext);
PUT_FCN_ENDNDX (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
}
else
{
H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
}
if (ISFCN (type))
H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
else
{
PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
}
return AUXESZ;
}
void
_bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
{
LINENO *ext = (LINENO *) ext1;
struct internal_lineno *in = (struct internal_lineno *) in1;
in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
in->l_lnno = GET_LINENO_LNNO (abfd, ext);
}
unsigned int
_bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
{
struct internal_lineno *in = (struct internal_lineno *) inp;
struct external_lineno *ext = (struct external_lineno *) outp;
H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
return LINESZ;
}
void
_bfd_XXi_swap_aouthdr_in (bfd * abfd,
void * aouthdr_ext1,
void * aouthdr_int1)
{
PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
struct internal_aouthdr *aouthdr_int
= (struct internal_aouthdr *) aouthdr_int1;
struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
aouthdr_int->text_start =
GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
/* PE32+ does not have data_start member! */
aouthdr_int->data_start =
GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
a->BaseOfData = aouthdr_int->data_start;
#endif
a->Magic = aouthdr_int->magic;
a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
a->SizeOfCode = aouthdr_int->tsize ;
a->SizeOfInitializedData = aouthdr_int->dsize ;
a->SizeOfUninitializedData = aouthdr_int->bsize ;
a->AddressOfEntryPoint = aouthdr_int->entry;
a->BaseOfCode = aouthdr_int->text_start;
a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
a->MajorOperatingSystemVersion =
H_GET_16 (abfd, src->MajorOperatingSystemVersion);
a->MinorOperatingSystemVersion =
H_GET_16 (abfd, src->MinorOperatingSystemVersion);
a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
a->CheckSum = H_GET_32 (abfd, src->CheckSum);
a->Subsystem = H_GET_16 (abfd, src->Subsystem);
a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
a->SizeOfStackReserve =
GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
a->SizeOfStackCommit =
GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
a->SizeOfHeapReserve =
GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
a->SizeOfHeapCommit =
GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
{
int idx;
for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++)
{
/* If data directory is empty, rva also should be 0. */
int size =
H_GET_32 (abfd, src->DataDirectory[idx][1]);
a->DataDirectory[idx].Size = size;
if (size)
a->DataDirectory[idx].VirtualAddress =
H_GET_32 (abfd, src->DataDirectory[idx][0]);
else
a->DataDirectory[idx].VirtualAddress = 0;
}
}
if (aouthdr_int->entry)
{
aouthdr_int->entry += a->ImageBase;
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
aouthdr_int->entry &= 0xffffffff;
#endif
}
if (aouthdr_int->tsize)
{
aouthdr_int->text_start += a->ImageBase;
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
aouthdr_int->text_start &= 0xffffffff;
#endif
}
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
/* PE32+ does not have data_start member! */
if (aouthdr_int->dsize)
{
aouthdr_int->data_start += a->ImageBase;
aouthdr_int->data_start &= 0xffffffff;
}
#endif
#ifdef POWERPC_LE_PE
/* These three fields are normally set up by ppc_relocate_section.
In the case of reading a file in, we can pick them up from the
DataDirectory. */
first_thunk_address = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress;
thunk_size = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size;
import_table_size = a->DataDirectory[PE_IMPORT_TABLE].Size;
#endif
}
/* A support function for below. */
static void
add_data_entry (bfd * abfd,
struct internal_extra_pe_aouthdr *aout,
int idx,
char *name,
bfd_vma base)
{
asection *sec = bfd_get_section_by_name (abfd, name);
/* Add import directory information if it exists. */
if ((sec != NULL)
&& (coff_section_data (abfd, sec) != NULL)
&& (pei_section_data (abfd, sec) != NULL))
{
/* If data directory is empty, rva also should be 0. */
int size = pei_section_data (abfd, sec)->virt_size;
aout->DataDirectory[idx].Size = size;
if (size)
{
aout->DataDirectory[idx].VirtualAddress =
(sec->vma - base) & 0xffffffff;
sec->flags |= SEC_DATA;
}
}
}
unsigned int
_bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
{
struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
pe_data_type *pe = pe_data (abfd);
struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
bfd_vma sa, fa, ib;
IMAGE_DATA_DIRECTORY idata2, idata5, tls;
sa = extra->SectionAlignment;
fa = extra->FileAlignment;
ib = extra->ImageBase;
idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
if (aouthdr_in->tsize)
{
aouthdr_in->text_start -= ib;
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
aouthdr_in->text_start &= 0xffffffff;
#endif
}
if (aouthdr_in->dsize)
{
aouthdr_in->data_start -= ib;
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
aouthdr_in->data_start &= 0xffffffff;
#endif
}
if (aouthdr_in->entry)
{
aouthdr_in->entry -= ib;
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
aouthdr_in->entry &= 0xffffffff;
#endif
}
#define FA(x) (((x) + fa -1 ) & (- fa))
#define SA(x) (((x) + sa -1 ) & (- sa))
/* We like to have the sizes aligned. */
aouthdr_in->bsize = FA (aouthdr_in->bsize);
extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
add_data_entry (abfd, extra, 0, ".edata", ib);
add_data_entry (abfd, extra, 2, ".rsrc", ib);
add_data_entry (abfd, extra, 3, ".pdata", ib);
/* In theory we do not need to call add_data_entry for .idata$2 or
.idata$5. It will be done in bfd_coff_final_link where all the
required information is available. If however, we are not going
to perform a final link, eg because we have been invoked by objcopy
or strip, then we need to make sure that these Data Directory
entries are initialised properly.
So - we copy the input values into the output values, and then, if
a final link is going to be performed, it can overwrite them. */
extra->DataDirectory[PE_IMPORT_TABLE] = idata2;
extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
extra->DataDirectory[PE_TLS_TABLE] = tls;
if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
/* Until other .idata fixes are made (pending patch), the entry for
.idata is needed for backwards compatibility. FIXME. */
add_data_entry (abfd, extra, 1, ".idata", ib);
/* For some reason, the virtual size (which is what's set by
add_data_entry) for .reloc is not the same as the size recorded
in this slot by MSVC; it doesn't seem to cause problems (so far),
but since it's the best we've got, use it. It does do the right
thing for .pdata. */
if (pe->has_reloc_section)
add_data_entry (abfd, extra, 5, ".reloc", ib);
{
asection *sec;
bfd_vma hsize = 0;
bfd_vma dsize = 0;
bfd_vma isize = 0;
bfd_vma tsize = 0;
for (sec = abfd->sections; sec; sec = sec->next)
{
int rounded = FA (sec->size);
/* The first non-zero section filepos is the header size.
Sections without contents will have a filepos of 0. */
if (hsize == 0)
hsize = sec->filepos;
if (sec->flags & SEC_DATA)
dsize += rounded;
if (sec->flags & SEC_CODE)
tsize += rounded;
/* The image size is the total VIRTUAL size (which is what is
in the virt_size field). Files have been seen (from MSVC
5.0 link.exe) where the file size of the .data segment is
quite small compared to the virtual size. Without this
fix, strip munges the file.
FIXME: We need to handle holes between sections, which may
happpen when we covert from another format. We just use
the virtual address and virtual size of the last section
for the image size. */
if (coff_section_data (abfd, sec) != NULL
&& pei_section_data (abfd, sec) != NULL)
isize = (sec->vma - extra->ImageBase
+ SA (FA (pei_section_data (abfd, sec)->virt_size)));
}
aouthdr_in->dsize = dsize;
aouthdr_in->tsize = tsize;
extra->SizeOfHeaders = hsize;
extra->SizeOfImage = isize;
}
H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
/* e.g. 219510000 is linker version 2.19 */
#define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
/* This piece of magic sets the "linker version" field to
LINKER_VERSION. */
H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
aouthdr_out->standard.vstamp);
PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
aouthdr_out->standard.text_start);
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
/* PE32+ does not have data_start member! */
PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
aouthdr_out->standard.data_start);
#endif
PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
aouthdr_out->MajorOperatingSystemVersion);
H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
aouthdr_out->MinorOperatingSystemVersion);
H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
H_PUT_16 (abfd, extra->MajorSubsystemVersion,
aouthdr_out->MajorSubsystemVersion);
H_PUT_16 (abfd, extra->MinorSubsystemVersion,
aouthdr_out->MinorSubsystemVersion);
H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
aouthdr_out->SizeOfStackReserve);
PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
aouthdr_out->SizeOfStackCommit);
PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
aouthdr_out->SizeOfHeapReserve);
PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
aouthdr_out->SizeOfHeapCommit);
H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
aouthdr_out->NumberOfRvaAndSizes);
{
int idx;
for (idx = 0; idx < 16; idx++)
{
H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
aouthdr_out->DataDirectory[idx][0]);
H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
aouthdr_out->DataDirectory[idx][1]);
}
}
return AOUTSZ;
}
unsigned int
_bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
{
int idx;
struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
if (pe_data (abfd)->has_reloc_section
|| pe_data (abfd)->dont_strip_reloc)
filehdr_in->f_flags &= ~F_RELFLG;
if (pe_data (abfd)->dll)
filehdr_in->f_flags |= F_DLL;
filehdr_in->pe.e_magic = DOSMAGIC;
filehdr_in->pe.e_cblp = 0x90;
filehdr_in->pe.e_cp = 0x3;
filehdr_in->pe.e_crlc = 0x0;
filehdr_in->pe.e_cparhdr = 0x4;
filehdr_in->pe.e_minalloc = 0x0;
filehdr_in->pe.e_maxalloc = 0xffff;
filehdr_in->pe.e_ss = 0x0;
filehdr_in->pe.e_sp = 0xb8;
filehdr_in->pe.e_csum = 0x0;
filehdr_in->pe.e_ip = 0x0;
filehdr_in->pe.e_cs = 0x0;
filehdr_in->pe.e_lfarlc = 0x40;
filehdr_in->pe.e_ovno = 0x0;
for (idx = 0; idx < 4; idx++)
filehdr_in->pe.e_res[idx] = 0x0;
filehdr_in->pe.e_oemid = 0x0;
filehdr_in->pe.e_oeminfo = 0x0;
for (idx = 0; idx < 10; idx++)
filehdr_in->pe.e_res2[idx] = 0x0;
filehdr_in->pe.e_lfanew = 0x80;
/* This next collection of data are mostly just characters. It
appears to be constant within the headers put on NT exes. */
filehdr_in->pe.dos_message[0] = 0x0eba1f0e;
filehdr_in->pe.dos_message[1] = 0xcd09b400;
filehdr_in->pe.dos_message[2] = 0x4c01b821;
filehdr_in->pe.dos_message[3] = 0x685421cd;
filehdr_in->pe.dos_message[4] = 0x70207369;
filehdr_in->pe.dos_message[5] = 0x72676f72;
filehdr_in->pe.dos_message[6] = 0x63206d61;
filehdr_in->pe.dos_message[7] = 0x6f6e6e61;
filehdr_in->pe.dos_message[8] = 0x65622074;
filehdr_in->pe.dos_message[9] = 0x6e757220;
filehdr_in->pe.dos_message[10] = 0x206e6920;
filehdr_in->pe.dos_message[11] = 0x20534f44;
filehdr_in->pe.dos_message[12] = 0x65646f6d;
filehdr_in->pe.dos_message[13] = 0x0a0d0d2e;
filehdr_in->pe.dos_message[14] = 0x24;
filehdr_in->pe.dos_message[15] = 0x0;
filehdr_in->pe.nt_signature = NT_SIGNATURE;
H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
/* Only use a real timestamp if the option was chosen. */
if ((pe_data (abfd)->insert_timestamp))
H_PUT_32 (abfd, time(0), filehdr_out->f_timdat);
PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
filehdr_out->f_symptr);
H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
/* Put in extra dos header stuff. This data remains essentially
constant, it just has to be tacked on to the beginning of all exes
for NT. */
H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
for (idx = 0; idx < 4; idx++)
H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
for (idx = 0; idx < 10; idx++)
H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
for (idx = 0; idx < 16; idx++)
H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx],
filehdr_out->dos_message[idx]);
/* Also put in the NT signature. */
H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
return FILHSZ;
}
unsigned int
_bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
{
struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
FILHDR *filehdr_out = (FILHDR *) out;
H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
return FILHSZ;
}
unsigned int
_bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
{
struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
SCNHDR *scnhdr_ext = (SCNHDR *) out;
unsigned int ret = SCNHSZ;
bfd_vma ps;
bfd_vma ss;
memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
PUT_SCNHDR_VADDR (abfd,
((scnhdr_int->s_vaddr
- pe_data (abfd)->pe_opthdr.ImageBase)
& 0xffffffff),
scnhdr_ext->s_vaddr);
/* NT wants the size data to be rounded up to the next
NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
sometimes). */
if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
{
if (bfd_pei_p (abfd))
{
ps = scnhdr_int->s_size;
ss = 0;
}
else
{
ps = 0;
ss = scnhdr_int->s_size;
}
}
else
{
if (bfd_pei_p (abfd))
ps = scnhdr_int->s_paddr;
else
ps = 0;
ss = scnhdr_int->s_size;
}
PUT_SCNHDR_SIZE (abfd, ss,
scnhdr_ext->s_size);
/* s_paddr in PE is really the virtual size. */
PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
scnhdr_ext->s_scnptr);
PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
scnhdr_ext->s_relptr);
PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
scnhdr_ext->s_lnnoptr);
{
/* Extra flags must be set when dealing with PE. All sections should also
have the IMAGE_SCN_MEM_READ (0x40000000) flag set. In addition, the
.text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
(this is especially important when dealing with the .idata section since
the addresses for routines from .dlls must be overwritten). If .reloc
section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
(0x02000000). Also, the resource data should also be read and
writable. */
/* FIXME: Alignment is also encoded in this field, at least on PPC and
ARM-WINCE. Although - how do we get the original alignment field
back ? */
typedef struct
{
const char * section_name;
unsigned long must_have;
}
pe_required_section_flags;
pe_required_section_flags known_sections [] =
{
{ ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
{ ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
{ ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
{ ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
{ ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
{ ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
{ ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
{ ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
{ ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
{ ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
{ ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
{ ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
{ NULL, 0}
};
pe_required_section_flags * p;
/* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
we know exactly what this specific section wants so we remove it
and then allow the must_have field to add it back in if necessary.
However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
by ld --enable-auto-import (if auto-import is actually needed),
by ld --omagic, or by obcopy --writable-text. */
for (p = known_sections; p->section_name; p++)
if (strcmp (scnhdr_int->s_name, p->section_name) == 0)
{
if (strcmp (scnhdr_int->s_name, ".text")
|| (bfd_get_file_flags (abfd) & WP_TEXT))
scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
scnhdr_int->s_flags |= p->must_have;
break;
}
H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
}
if (coff_data (abfd)->link_info
&& ! coff_data (abfd)->link_info->relocatable
&& ! coff_data (abfd)->link_info->shared
&& strcmp (scnhdr_int->s_name, ".text") == 0)
{
/* By inference from looking at MS output, the 32 bit field
which is the combination of the number_of_relocs and
number_of_linenos is used for the line number count in
executables. A 16-bit field won't do for cc1. The MS
document says that the number of relocs is zero for
executables, but the 17-th bit has been observed to be there.
Overflow is not an issue: a 4G-line program will overflow a
bunch of other fields long before this! */
H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
}
else
{
if (scnhdr_int->s_nlnno <= 0xffff)
H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
else
{
(*_bfd_error_handler) (_("%s: line number overflow: 0x%lx > 0xffff"),
bfd_get_filename (abfd),
scnhdr_int->s_nlnno);
bfd_set_error (bfd_error_file_truncated);
H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
ret = 0;
}
/* Although we could encode 0xffff relocs here, we do not, to be
consistent with other parts of bfd. Also it lets us warn, as
we should never see 0xffff here w/o having the overflow flag
set. */
if (scnhdr_int->s_nreloc < 0xffff)
H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
else
{
/* PE can deal with large #s of relocs, but not here. */
H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
}
}
return ret;
}
static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
{
N_("Export Directory [.edata (or where ever we found it)]"),
N_("Import Directory [parts of .idata]"),
N_("Resource Directory [.rsrc]"),
N_("Exception Directory [.pdata]"),
N_("Security Directory"),
N_("Base Relocation Directory [.reloc]"),
N_("Debug Directory"),
N_("Description Directory"),
N_("Special Directory"),
N_("Thread Storage Directory [.tls]"),
N_("Load Configuration Directory"),
N_("Bound Import Directory"),
N_("Import Address Table Directory"),
N_("Delay Import Directory"),
N_("CLR Runtime Header"),
N_("Reserved")
};
#ifdef POWERPC_LE_PE
/* The code for the PPC really falls in the "architecture dependent"
category. However, it's not clear that anyone will ever care, so
we're ignoring the issue for now; if/when PPC matters, some of this
may need to go into peicode.h, or arguments passed to enable the
PPC- specific code. */
#endif
static bfd_boolean
pe_print_idata (bfd * abfd, void * vfile)
{
FILE *file = (FILE *) vfile;
bfd_byte *data;
asection *section;
bfd_signed_vma adj;
#ifdef POWERPC_LE_PE
asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
#endif
bfd_size_type datasize = 0;
bfd_size_type dataoff;
bfd_size_type i;
int onaline = 20;
pe_data_type *pe = pe_data (abfd);
struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
bfd_vma addr;
addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
{
/* Maybe the extra header isn't there. Look for the section. */
section = bfd_get_section_by_name (abfd, ".idata");
if (section == NULL)
return TRUE;
addr = section->vma;
datasize = section->size;
if (datasize == 0)
return TRUE;
}
else
{
addr += extra->ImageBase;
for (section = abfd->sections; section != NULL; section = section->next)
{
datasize = section->size;
if (addr >= section->vma && addr < section->vma + datasize)
break;
}
if (section == NULL)
{
fprintf (file,
_("\nThere is an import table, but the section containing it could not be found\n"));
return TRUE;
}
}
fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
section->name, (unsigned long) addr);
dataoff = addr - section->vma;
#ifdef POWERPC_LE_PE
if (rel_section != 0 && rel_section->size != 0)
{
/* The toc address can be found by taking the starting address,
which on the PPC locates a function descriptor. The
descriptor consists of the function code starting address
followed by the address of the toc. The starting address we
get from the bfd, and the descriptor is supposed to be in the
.reldata section. */
bfd_vma loadable_toc_address;
bfd_vma toc_address;
bfd_vma start_address;
bfd_byte *data;
bfd_vma offset;
if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
{
if (data != NULL)
free (data);
return FALSE;
}
offset = abfd->start_address - rel_section->vma;
if (offset >= rel_section->size || offset + 8 > rel_section->size)
{
if (data != NULL)
free (data);
return FALSE;
}
start_address = bfd_get_32 (abfd, data + offset);
loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
toc_address = loadable_toc_address - 32768;
fprintf (file,
_("\nFunction descriptor located at the start address: %04lx\n"),
(unsigned long int) (abfd->start_address));
fprintf (file,
_("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
start_address, loadable_toc_address, toc_address);
if (data != NULL)
free (data);
}
else
{
fprintf (file,
_("\nNo reldata section! Function descriptor not decoded.\n"));
}
#endif
fprintf (file,
_("\nThe Import Tables (interpreted %s section contents)\n"),
section->name);
fprintf (file,
_("\
vma: Hint Time Forward DLL First\n\
Table Stamp Chain Name Thunk\n"));
/* Read the whole section. Some of the fields might be before dataoff. */
if (!bfd_malloc_and_get_section (abfd, section, &data))
{
if (data != NULL)
free (data);
return FALSE;
}
adj = section->vma - extra->ImageBase;
/* Print all image import descriptors. */
for (i = dataoff; i + onaline <= datasize; i += onaline)
{
bfd_vma hint_addr;
bfd_vma time_stamp;
bfd_vma forward_chain;
bfd_vma dll_name;
bfd_vma first_thunk;
int idx = 0;
bfd_size_type j;
char *dll;
/* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
fprintf (file, " %08lx\t", (unsigned long) (i + adj));
hint_addr = bfd_get_32 (abfd, data + i);
time_stamp = bfd_get_32 (abfd, data + i + 4);
forward_chain = bfd_get_32 (abfd, data + i + 8);
dll_name = bfd_get_32 (abfd, data + i + 12);
first_thunk = bfd_get_32 (abfd, data + i + 16);
fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
(unsigned long) hint_addr,
(unsigned long) time_stamp,
(unsigned long) forward_chain,
(unsigned long) dll_name,
(unsigned long) first_thunk);
if (hint_addr == 0 && first_thunk == 0)
break;
if (dll_name - adj >= section->size)
break;
dll = (char *) data + dll_name - adj;
fprintf (file, _("\n\tDLL Name: %s\n"), dll);
if (hint_addr != 0)
{
bfd_byte *ft_data;
asection *ft_section;
bfd_vma ft_addr;
bfd_size_type ft_datasize;
int ft_idx;
int ft_allocated;
fprintf (file, _("\tvma: Hint/Ord Member-Name Bound-To\n"));
idx = hint_addr - adj;
ft_addr = first_thunk + extra->ImageBase;
ft_idx = first_thunk - adj;
ft_data = data + ft_idx;
ft_datasize = datasize - ft_idx;
ft_allocated = 0;
if (first_thunk != hint_addr)
{
/* Find the section which contains the first thunk. */
for (ft_section = abfd->sections;
ft_section != NULL;
ft_section = ft_section->next)
{
if (ft_addr >= ft_section->vma
&& ft_addr < ft_section->vma + ft_section->size)
break;
}
if (ft_section == NULL)
{
fprintf (file,
_("\nThere is a first thunk, but the section containing it could not be found\n"));
continue;
}
/* Now check to see if this section is the same as our current
section. If it is not then we will have to load its data in. */
if (ft_section != section)
{
ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
ft_datasize = ft_section->size - ft_idx;
ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
if (ft_data == NULL)
continue;
/* Read ft_datasize bytes starting at offset ft_idx. */
if (!bfd_get_section_contents (abfd, ft_section, ft_data,
(bfd_vma) ft_idx, ft_datasize))
{
free (ft_data);
continue;
}
ft_allocated = 1;
}
}
/* Print HintName vector entries. */
#ifdef COFF_WITH_pex64
for (j = 0; idx + j + 8 <= datasize; j += 8)
{
unsigned long member = bfd_get_32 (abfd, data + idx + j);
unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
if (!member && !member_high)
break;
if (HighBitSet (member_high))
fprintf (file, "\t%lx%08lx\t %4lx%08lx <none>",
member_high, member,
WithoutHighBit (member_high), member);
else
{
int ordinal;
char *member_name;
ordinal = bfd_get_16 (abfd, data + member - adj);
member_name = (char *) data + member - adj + 2;
fprintf (file, "\t%04lx\t %4d %s",member, ordinal, member_name);
}
/* If the time stamp is not zero, the import address
table holds actual addresses. */
if (time_stamp != 0
&& first_thunk != 0
&& first_thunk != hint_addr
&& j + 4 <= ft_datasize)
fprintf (file, "\t%04lx",
(unsigned long) bfd_get_32 (abfd, ft_data + j));
fprintf (file, "\n");
}
#else
for (j = 0; idx + j + 4 <= datasize; j += 4)
{
unsigned long member = bfd_get_32 (abfd, data + idx + j);
/* Print single IMAGE_IMPORT_BY_NAME vector. */
if (member == 0)
break;
if (HighBitSet (member))
fprintf (file, "\t%04lx\t %4lu <none>",
member, WithoutHighBit (member));
else
{
int ordinal;
char *member_name;
ordinal = bfd_get_16 (abfd, data + member - adj);
member_name = (char *) data + member - adj + 2;
fprintf (file, "\t%04lx\t %4d %s",
member, ordinal, member_name);
}
/* If the time stamp is not zero, the import address
table holds actual addresses. */
if (time_stamp != 0
&& first_thunk != 0
&& first_thunk != hint_addr
&& j + 4 <= ft_datasize)
fprintf (file, "\t%04lx",
(unsigned long) bfd_get_32 (abfd, ft_data + j));
fprintf (file, "\n");
}
#endif
if (ft_allocated)
free (ft_data);
}
fprintf (file, "\n");
}
free (data);
return TRUE;
}
static bfd_boolean
pe_print_edata (bfd * abfd, void * vfile)
{
FILE *file = (FILE *) vfile;
bfd_byte *data;
asection *section;
bfd_size_type datasize = 0;
bfd_size_type dataoff;
bfd_size_type i;
bfd_signed_vma adj;
struct EDT_type
{
long export_flags; /* Reserved - should be zero. */
long time_stamp;
short major_ver;
short minor_ver;
bfd_vma name; /* RVA - relative to image base. */
long base; /* Ordinal base. */
unsigned long num_functions;/* Number in the export address table. */
unsigned long num_names; /* Number in the name pointer table. */
bfd_vma eat_addr; /* RVA to the export address table. */
bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
bfd_vma ot_addr; /* RVA to the Ordinal Table. */
} edt;
pe_data_type *pe = pe_data (abfd);
struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
bfd_vma addr;
addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
{
/* Maybe the extra header isn't there. Look for the section. */
section = bfd_get_section_by_name (abfd, ".edata");
if (section == NULL)
return TRUE;
addr = section->vma;
dataoff = 0;
datasize = section->size;
if (datasize == 0)
return TRUE;
}
else
{
addr += extra->ImageBase;
for (section = abfd->sections; section != NULL; section = section->next)
if (addr >= section->vma && addr < section->vma + section->size)
break;
if (section == NULL)
{
fprintf (file,
_("\nThere is an export table, but the section containing it could not be found\n"));
return TRUE;
}
dataoff = addr - section->vma;
datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
if (datasize > section->size - dataoff)
{
fprintf (file,
_("\nThere is an export table in %s, but it does not fit into that section\n"),
section->name);
return TRUE;
}
}
fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
section->name, (unsigned long) addr);
data = (bfd_byte *) bfd_malloc (datasize);
if (data == NULL)
return FALSE;
if (! bfd_get_section_contents (abfd, section, data,
(file_ptr) dataoff, datasize))
return FALSE;
/* Go get Export Directory Table. */
edt.export_flags = bfd_get_32 (abfd, data + 0);
edt.time_stamp = bfd_get_32 (abfd, data + 4);
edt.major_ver = bfd_get_16 (abfd, data + 8);
edt.minor_ver = bfd_get_16 (abfd, data + 10);
edt.name = bfd_get_32 (abfd, data + 12);
edt.base = bfd_get_32 (abfd, data + 16);
edt.num_functions = bfd_get_32 (abfd, data + 20);
edt.num_names = bfd_get_32 (abfd, data + 24);
edt.eat_addr = bfd_get_32 (abfd, data + 28);
edt.npt_addr = bfd_get_32 (abfd, data + 32);
edt.ot_addr = bfd_get_32 (abfd, data + 36);
adj = section->vma - extra->ImageBase + dataoff;
/* Dump the EDT first. */
fprintf (file,
_("\nThe Export Tables (interpreted %s section contents)\n\n"),
section->name);
fprintf (file,
_("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
fprintf (file,
_("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
fprintf (file,
_("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
fprintf (file,
_("Name \t\t\t\t"));
bfd_fprintf_vma (abfd, file, edt.name);
fprintf (file,
" %s\n", data + edt.name - adj);
fprintf (file,
_("Ordinal Base \t\t\t%ld\n"), edt.base);
fprintf (file,
_("Number in:\n"));
fprintf (file,
_("\tExport Address Table \t\t%08lx\n"),
edt.num_functions);
fprintf (file,
_("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
fprintf (file,
_("Table Addresses\n"));
fprintf (file,
_("\tExport Address Table \t\t"));
bfd_fprintf_vma (abfd, file, edt.eat_addr);
fprintf (file, "\n");
fprintf (file,
_("\tName Pointer Table \t\t"));
bfd_fprintf_vma (abfd, file, edt.npt_addr);
fprintf (file, "\n");
fprintf (file,
_("\tOrdinal Table \t\t\t"));
bfd_fprintf_vma (abfd, file, edt.ot_addr);
fprintf (file, "\n");
/* The next table to find is the Export Address Table. It's basically
a list of pointers that either locate a function in this dll, or
forward the call to another dll. Something like:
typedef union
{
long export_rva;
long forwarder_rva;
} export_address_table_entry; */
fprintf (file,
_("\nExport Address Table -- Ordinal Base %ld\n"),
edt.base);
for (i = 0; i < edt.num_functions; ++i)
{
bfd_vma eat_member = bfd_get_32 (abfd,
data + edt.eat_addr + (i * 4) - adj);
if (eat_member == 0)
continue;
if (eat_member - adj <= datasize)
{
/* This rva is to a name (forwarding function) in our section. */
/* Should locate a function descriptor. */
fprintf (file,
"\t[%4ld] +base[%4ld] %04lx %s -- %s\n",
(long) i,
(long) (i + edt.base),
(unsigned long) eat_member,
_("Forwarder RVA"),
data + eat_member - adj);
}
else
{
/* Should locate a function descriptor in the reldata section. */
fprintf (file,
"\t[%4ld] +base[%4ld] %04lx %s\n",
(long) i,
(long) (i + edt.base),
(unsigned long) eat_member,
_("Export RVA"));
}
}
/* The Export Name Pointer Table is paired with the Export Ordinal Table. */
/* Dump them in parallel for clarity. */
fprintf (file,
_("\n[Ordinal/Name Pointer] Table\n"));
for (i = 0; i < edt.num_names; ++i)
{
bfd_vma name_ptr = bfd_get_32 (abfd,
data +
edt.npt_addr
+ (i*4) - adj);
char *name = (char *) data + name_ptr - adj;
bfd_vma ord = bfd_get_16 (abfd,
data +
edt.ot_addr
+ (i*2) - adj);
fprintf (file,
"\t[%4ld] %s\n", (long) ord, name);
}
free (data);
return TRUE;
}
/* This really is architecture dependent. On IA-64, a .pdata entry
consists of three dwords containing relative virtual addresses that
specify the start and end address of the code range the entry
covers and the address of the corresponding unwind info data.
On ARM and SH-4, a compressed PDATA structure is used :
_IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
_IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
This is the version for uncompressed data. */
static bfd_boolean
pe_print_pdata (bfd * abfd, void * vfile)
{
#if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
# define PDATA_ROW_SIZE (3 * 8)
#else
# define PDATA_ROW_SIZE (5 * 4)
#endif
FILE *file = (FILE *) vfile;
bfd_byte *data = 0;
asection *section = bfd_get_section_by_name (abfd, ".pdata");
bfd_size_type datasize = 0;
bfd_size_type i;
bfd_size_type start, stop;
int onaline = PDATA_ROW_SIZE;
if (section == NULL
|| coff_section_data (abfd, section) == NULL
|| pei_section_data (abfd, section) == NULL)
return TRUE;
stop = pei_section_data (abfd, section)->virt_size;
if ((stop % onaline) != 0)
fprintf (file,
_("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
(long) stop, onaline);
fprintf (file,
_("\nThe Function Table (interpreted .pdata section contents)\n"));
#if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
fprintf (file,
_(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
#else
fprintf (file, _("\
vma:\t\tBegin End EH EH PrologEnd Exception\n\
\t\tAddress Address Handler Data Address Mask\n"));
#endif
datasize = section->size;
if (datasize == 0)
return TRUE;
if (! bfd_malloc_and_get_section (abfd, section, &data))
{
if (data != NULL)
free (data);
return FALSE;
}
start = 0;
for (i = start; i < stop; i += onaline)
{
bfd_vma begin_addr;
bfd_vma end_addr;
bfd_vma eh_handler;
bfd_vma eh_data;
bfd_vma prolog_end_addr;
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
int em_data;
#endif
if (i + PDATA_ROW_SIZE > stop)
break;
begin_addr = GET_PDATA_ENTRY (abfd, data + i );
end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
&& eh_data == 0 && prolog_end_addr == 0)
/* We are probably into the padding of the section now. */
break;
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
#endif
eh_handler &= ~(bfd_vma) 0x3;
prolog_end_addr &= ~(bfd_vma) 0x3;
fputc (' ', file);
bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
bfd_fprintf_vma (abfd, file, eh_handler);
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
fputc (' ', file);
bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
bfd_fprintf_vma (abfd, file, prolog_end_addr);
fprintf (file, " %x", em_data);
#endif
#ifdef POWERPC_LE_PE
if (eh_handler == 0 && eh_data != 0)
{
/* Special bits here, although the meaning may be a little
mysterious. The only one I know for sure is 0x03
Code Significance
0x00 None
0x01 Register Save Millicode
0x02 Register Restore Millicode
0x03 Glue Code Sequence. */
switch (eh_data)
{
case 0x01:
fprintf (file, _(" Register save millicode"));
break;
case 0x02:
fprintf (file, _(" Register restore millicode"));
break;
case 0x03:
fprintf (file, _(" Glue code sequence"));
break;
default:
break;
}
}
#endif
fprintf (file, "\n");
}
free (data);
return TRUE;
#undef PDATA_ROW_SIZE
}
typedef struct sym_cache
{
int symcount;
asymbol ** syms;
} sym_cache;
static asymbol **
slurp_symtab (bfd *abfd, sym_cache *psc)
{
asymbol ** sy = NULL;
long storage;
if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
{
psc->symcount = 0;
return NULL;
}
storage = bfd_get_symtab_upper_bound (abfd);
if (storage < 0)
return NULL;
if (storage)
sy = (asymbol **) bfd_malloc (storage);
psc->symcount = bfd_canonicalize_symtab (abfd, sy);
if (psc->symcount < 0)
return NULL;
return sy;
}
static const char *
my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
{
int i;
if (psc->syms == 0)
psc->syms = slurp_symtab (abfd, psc);
for (i = 0; i < psc->symcount; i++)
{
if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
return psc->syms[i]->name;
}
return NULL;
}
static void
cleanup_syms (sym_cache *psc)
{
psc->symcount = 0;
free (psc->syms);
psc->syms = NULL;
}
/* This is the version for "compressed" pdata. */
bfd_boolean
_bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
{
# define PDATA_ROW_SIZE (2 * 4)
FILE *file = (FILE *) vfile;
bfd_byte *data = NULL;
asection *section = bfd_get_section_by_name (abfd, ".pdata");
bfd_size_type datasize = 0;
bfd_size_type i;
bfd_size_type start, stop;
int onaline = PDATA_ROW_SIZE;
struct sym_cache cache = {0, 0} ;
if (section == NULL
|| coff_section_data (abfd, section) == NULL
|| pei_section_data (abfd, section) == NULL)
return TRUE;
stop = pei_section_data (abfd, section)->virt_size;
if ((stop % onaline) != 0)
fprintf (file,
_("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
(long) stop, onaline);
fprintf (file,
_("\nThe Function Table (interpreted .pdata section contents)\n"));
fprintf (file, _("\
vma:\t\tBegin Prolog Function Flags Exception EH\n\
\t\tAddress Length Length 32b exc Handler Data\n"));
datasize = section->size;
if (datasize == 0)
return TRUE;
if (! bfd_malloc_and_get_section (abfd, section, &data))
{
if (data != NULL)
free (data);
return FALSE;
}
start = 0;
for (i = start; i < stop; i += onaline)
{
bfd_vma begin_addr;
bfd_vma other_data;
bfd_vma prolog_length, function_length;
int flag32bit, exception_flag;
asection *tsection;
if (i + PDATA_ROW_SIZE > stop)
break;
begin_addr = GET_PDATA_ENTRY (abfd, data + i );
other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
if (begin_addr == 0 && other_data == 0)
/* We are probably into the padding of the section now. */
break;
prolog_length = (other_data & 0x000000FF);
function_length = (other_data & 0x3FFFFF00) >> 8;
flag32bit = (int)((other_data & 0x40000000) >> 30);
exception_flag = (int)((other_data & 0x80000000) >> 31);
fputc (' ', file);
bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
fprintf (file, "%2d %2d ", flag32bit, exception_flag);
/* Get the exception handler's address and the data passed from the
.text section. This is really the data that belongs with the .pdata
but got "compressed" out for the ARM and SH4 architectures. */
tsection = bfd_get_section_by_name (abfd, ".text");
if (tsection && coff_section_data (abfd, tsection)
&& pei_section_data (abfd, tsection))
{
bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
bfd_byte *tdata;
tdata = (bfd_byte *) bfd_malloc (8);
if (tdata)
{
if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
{
bfd_vma eh, eh_data;
eh = bfd_get_32 (abfd, tdata);
eh_data = bfd_get_32 (abfd, tdata + 4);
fprintf (file, "%08x ", (unsigned int) eh);
fprintf (file, "%08x", (unsigned int) eh_data);
if (eh != 0)
{
const char *s = my_symbol_for_address (abfd, eh, &cache);
if (s)
fprintf (file, " (%s) ", s);
}
}
free (tdata);
}
}
fprintf (file, "\n");
}
free (data);
cleanup_syms (& cache);
return TRUE;
#undef PDATA_ROW_SIZE
}
#define IMAGE_REL_BASED_HIGHADJ 4
static const char * const tbl[] =
{
"ABSOLUTE",
"HIGH",
"LOW",
"HIGHLOW",
"HIGHADJ",
"MIPS_JMPADDR",
"SECTION",
"REL32",
"RESERVED1",
"MIPS_JMPADDR16",
"DIR64",
"HIGH3ADJ",
"UNKNOWN", /* MUST be last. */
};
static bfd_boolean
pe_print_reloc (bfd * abfd, void * vfile)
{
FILE *file = (FILE *) vfile;
bfd_byte *data = 0;
asection *section = bfd_get_section_by_name (abfd, ".reloc");
bfd_size_type i;
bfd_size_type start, stop;
if (section == NULL)
return TRUE;
if (section->size == 0)
return TRUE;
fprintf (file,
_("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
if (! bfd_malloc_and_get_section (abfd, section, &data))
{
if (data != NULL)
free (data);
return FALSE;
}
start = 0;
stop = section->size;
for (i = start; i < stop;)
{
int j;
bfd_vma virtual_address;
long number, size;
/* The .reloc section is a sequence of blocks, with a header consisting
of two 32 bit quantities, followed by a number of 16 bit entries. */
virtual_address = bfd_get_32 (abfd, data+i);
size = bfd_get_32 (abfd, data+i+4);
number = (size - 8) / 2;
if (size == 0)
break;
fprintf (file,
_("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
(unsigned long) virtual_address, size, (unsigned long) size, number);
for (j = 0; j < number; ++j)
{
unsigned short e = bfd_get_16 (abfd, data + i + 8 + j * 2);
unsigned int t = (e & 0xF000) >> 12;
int off = e & 0x0FFF;
if (t >= sizeof (tbl) / sizeof (tbl[0]))
t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
fprintf (file,
_("\treloc %4d offset %4x [%4lx] %s"),
j, off, (unsigned long) (off + virtual_address), tbl[t]);
/* HIGHADJ takes an argument, - the next record *is* the
low 16 bits of addend. */
if (t == IMAGE_REL_BASED_HIGHADJ)
{
fprintf (file, " (%4x)",
((unsigned int)
bfd_get_16 (abfd, data + i + 8 + j * 2 + 2)));
j++;
}
fprintf (file, "\n");
}
i += size;
}
free (data);
return TRUE;
}
static bfd_byte *
rsrc_print_resource_directory (FILE * , bfd *, unsigned int,
bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
static bfd_byte *
rsrc_print_resource_entries (FILE * file,
bfd * abfd,
unsigned int indent,
bfd_boolean is_name,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias)
{
unsigned long entry, addr, size;
if (data + 8 >= dataend)
return dataend + 1;
fprintf (file, _("%*.s Entry: "), indent, " ");
entry = (long) bfd_get_32 (abfd, data);
if (is_name)
{
bfd_byte * name;
/* Note - the documenation says that this field is an RVA value
but windres appears to produce a section relative offset with
the top bit set. Support both styles for now. */
if (HighBitSet (entry))
name = datastart + WithoutHighBit (entry);
else
name = datastart + entry - rva_bias;
if (name + 2 < dataend)
{
unsigned int len;
len = bfd_get_16 (abfd, name);
fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
if (name + 2 + len * 2 < dataend)
{
/* This strange loop is to cope with multibyte characters. */
while (len --)
{
name += 2;
fprintf (file, "%.1s", name);
}
}
else
fprintf (file, _("<corrupt string length: %#x>"), len);
}
else
fprintf (file, _("<corrupt string offset: %#lx>"), entry);
}
else
fprintf (file, _("ID: %#08lx"), entry);
entry = (long) bfd_get_32 (abfd, data + 4);
fprintf (file, _(", Value: %#08lx\n"), entry);
if (HighBitSet (entry))
return rsrc_print_resource_directory (file, abfd, indent + 1,
datastart,
datastart + WithoutHighBit (entry),
dataend, rva_bias);
if (datastart + entry + 16 >= dataend)
return dataend + 1;
fprintf (file, _("%*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
indent, " ",
addr = (long) bfd_get_32 (abfd, datastart + entry),
size = (long) bfd_get_32 (abfd, datastart + entry + 4),
(int) bfd_get_32 (abfd, datastart + entry + 8));
/* Check that the reserved entry is 0. */
if (bfd_get_32 (abfd, datastart + entry + 12) != 0
/* And that the data address/size is valid too. */
|| (datastart + (addr - rva_bias) + size > dataend))
return dataend + 1;
return datastart + (addr - rva_bias) + size;
}
#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) < (b) ? (a) : (b))
static bfd_byte *
rsrc_print_resource_directory (FILE * file,
bfd * abfd,
unsigned int indent,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias)
{
unsigned int num_names, num_ids;
bfd_byte * highest_data = data;
if (data + 16 >= dataend)
return dataend + 1;
fprintf (file, "%*.s ", indent, " ");
switch (indent)
{
case 0: fprintf (file, "Type"); break;
case 2: fprintf (file, "Name"); break;
case 4: fprintf (file, "Language"); break;
default: fprintf (file, "<unknown>"); break;
}
fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
(int) bfd_get_32 (abfd, data),
(long) bfd_get_32 (abfd, data + 4),
(int) bfd_get_16 (abfd, data + 8),
(int) bfd_get_16 (abfd, data + 10),
num_names = (int) bfd_get_16 (abfd, data + 12),
num_ids = (int) bfd_get_16 (abfd, data + 14));
data += 16;
while (num_names --)
{
bfd_byte * entry_end;
entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, TRUE,
datastart, data, dataend, rva_bias);
data += 8;
highest_data = max (highest_data, entry_end);
if (entry_end >= dataend)
return entry_end;
}
while (num_ids --)
{
bfd_byte * entry_end;
entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, FALSE,
datastart, data, dataend,
rva_bias);
data += 8;
highest_data = max (highest_data, entry_end);
if (entry_end >= dataend)
return entry_end;
}
return max (highest_data, data);
}
/* Display the contents of a .rsrc section. We do not try to
reproduce the resources, windres does that. Instead we dump
the tables in a human readable format. */
static bfd_boolean
rsrc_print_section (bfd * abfd, void * vfile)
{
bfd_vma rva_bias;
pe_data_type * pe;
FILE * file = (FILE *) vfile;
bfd_size_type datasize;
asection * section;
bfd_byte * data;
bfd_byte * dataend;
bfd_byte * datastart;
pe = pe_data (abfd);
if (pe == NULL)
return TRUE;
section = bfd_get_section_by_name (abfd, ".rsrc");
if (section == NULL)
return TRUE;
rva_bias = section->vma - pe->pe_opthdr.ImageBase;
datasize = section->size;
if (datasize == 0)
return TRUE;
if (! bfd_malloc_and_get_section (abfd, section, & data))
{
if (data != NULL)
free (data);
return FALSE;
}
datastart = data;
dataend = data + datasize;
fflush (file);
fprintf (file, "\nThe .rsrc Resource Directory section:\n");
while (data < dataend)
{
bfd_byte * p = data;
data = rsrc_print_resource_directory (file, abfd, 0, data, data,
dataend, rva_bias);
if (data == dataend + 1)
fprintf (file, _("Corrupt .rsrc section detected!\n"));
else
{
/* Align data before continuing. */
int align = (1 << section->alignment_power) - 1;
data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
rva_bias += data - p;
/* For reasons that are unclear .rsrc sections are sometimes created
aligned to a 1^3 boundary even when their alignment is set at
1^2. Catch that case here before we issue a spurious warning
message. */
if (data == (dataend - 4))
data = dataend;
else if (data < dataend)
fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
}
}
free (datastart);
return TRUE;
}
/* Print out the program headers. */
bfd_boolean
_bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
{
FILE *file = (FILE *) vfile;
int j;
pe_data_type *pe = pe_data (abfd);
struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
const char *subsystem_name = NULL;
const char *name;
/* The MS dumpbin program reportedly ands with 0xff0f before
printing the characteristics field. Not sure why. No reason to
emulate it here. */
fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
#undef PF
#define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
PF (IMAGE_FILE_SYSTEM, "system file");
PF (IMAGE_FILE_DLL, "DLL");
PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
#undef PF
/* ctime implies '\n'. */
{
time_t t = pe->coff.timestamp;
fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
}
#ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
# define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
#endif
#ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
# define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
#endif
#ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
# define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
#endif
switch (i->Magic)
{
case IMAGE_NT_OPTIONAL_HDR_MAGIC:
name = "PE32";
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
name = "PE32+";
break;
case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
name = "ROM";
break;
default:
name = NULL;
break;
}
fprintf (file, "Magic\t\t\t%04x", i->Magic);
if (name)
fprintf (file, "\t(%s)",name);
fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
fprintf (file, "SizeOfCode\t\t%08lx\n", (unsigned long) i->SizeOfCode);
fprintf (file, "SizeOfInitializedData\t%08lx\n",
(unsigned long) i->SizeOfInitializedData);
fprintf (file, "SizeOfUninitializedData\t%08lx\n",
(unsigned long) i->SizeOfUninitializedData);
fprintf (file, "AddressOfEntryPoint\t");
bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
fprintf (file, "\nBaseOfCode\t\t");
bfd_fprintf_vma (abfd, file, i->BaseOfCode);
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
/* PE32+ does not have BaseOfData member! */
fprintf (file, "\nBaseOfData\t\t");
bfd_fprintf_vma (abfd, file, i->BaseOfData);
#endif
fprintf (file, "\nImageBase\t\t");
bfd_fprintf_vma (abfd, file, i->ImageBase);
fprintf (file, "\nSectionAlignment\t");
bfd_fprintf_vma (abfd, file, i->SectionAlignment);
fprintf (file, "\nFileAlignment\t\t");
bfd_fprintf_vma (abfd, file, i->FileAlignment);
fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
fprintf (file, "Win32Version\t\t%08lx\n", (unsigned long) i->Reserved1);
fprintf (file, "SizeOfImage\t\t%08lx\n", (unsigned long) i->SizeOfImage);
fprintf (file, "SizeOfHeaders\t\t%08lx\n", (unsigned long) i->SizeOfHeaders);
fprintf (file, "CheckSum\t\t%08lx\n", (unsigned long) i->CheckSum);
switch (i->Subsystem)
{
case IMAGE_SUBSYSTEM_UNKNOWN:
subsystem_name = "unspecified";
break;
case IMAGE_SUBSYSTEM_NATIVE:
subsystem_name = "NT native";
break;
case IMAGE_SUBSYSTEM_WINDOWS_GUI:
subsystem_name = "Windows GUI";
break;
case IMAGE_SUBSYSTEM_WINDOWS_CUI:
subsystem_name = "Windows CUI";
break;
case IMAGE_SUBSYSTEM_POSIX_CUI:
subsystem_name = "POSIX CUI";
break;
case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
subsystem_name = "Wince CUI";
break;
// These are from UEFI Platform Initialization Specification 1.1.
case IMAGE_SUBSYSTEM_EFI_APPLICATION:
subsystem_name = "EFI application";
break;
case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
subsystem_name = "EFI boot service driver";
break;
case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
subsystem_name = "EFI runtime driver";
break;
case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
subsystem_name = "SAL runtime driver";
break;
// This is from revision 8.0 of the MS PE/COFF spec
case IMAGE_SUBSYSTEM_XBOX:
subsystem_name = "XBOX";
break;
// Added default case for clarity - subsystem_name is NULL anyway.
default:
subsystem_name = NULL;
}
fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
if (subsystem_name)
fprintf (file, "\t(%s)", subsystem_name);
fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
fprintf (file, "SizeOfStackReserve\t");
bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
fprintf (file, "\nSizeOfStackCommit\t");
bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
fprintf (file, "\nSizeOfHeapReserve\t");
bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
fprintf (file, "\nSizeOfHeapCommit\t");
bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
(unsigned long) i->NumberOfRvaAndSizes);
fprintf (file, "\nThe Data Directory\n");
for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
{
fprintf (file, "Entry %1x ", j);
bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
fprintf (file, "%s\n", dir_names[j]);
}
pe_print_idata (abfd, vfile);
pe_print_edata (abfd, vfile);
if (bfd_coff_have_print_pdata (abfd))
bfd_coff_print_pdata (abfd, vfile);
else
pe_print_pdata (abfd, vfile);
pe_print_reloc (abfd, vfile);
rsrc_print_section (abfd, vfile);
return TRUE;
}
/* Copy any private info we understand from the input bfd
to the output bfd. */
bfd_boolean
_bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
{
pe_data_type *ipe, *ope;
/* One day we may try to grok other private data. */
if (ibfd->xvec->flavour != bfd_target_coff_flavour
|| obfd->xvec->flavour != bfd_target_coff_flavour)
return TRUE;
ipe = pe_data (ibfd);
ope = pe_data (obfd);
/* pe_opthdr is copied in copy_object. */
ope->dll = ipe->dll;
/* Don't copy input subsystem if output is different from input. */
if (obfd->xvec != ibfd->xvec)
ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
/* For strip: if we removed .reloc, we'll make a real mess of things
if we don't remove this entry as well. */
if (! pe_data (obfd)->has_reloc_section)
{
pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
}
/* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
won't be added. */
if (! pe_data (ibfd)->has_reloc_section
&& ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
pe_data (obfd)->dont_strip_reloc = 1;
return TRUE;
}
/* Copy private section data. */
bfd_boolean
_bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
asection *isec,
bfd *obfd,
asection *osec)
{
if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
|| bfd_get_flavour (obfd) != bfd_target_coff_flavour)
return TRUE;
if (coff_section_data (ibfd, isec) != NULL
&& pei_section_data (ibfd, isec) != NULL)
{
if (coff_section_data (obfd, osec) == NULL)
{
bfd_size_type amt = sizeof (struct coff_section_tdata);
osec->used_by_bfd = bfd_zalloc (obfd, amt);
if (osec->used_by_bfd == NULL)
return FALSE;
}
if (pei_section_data (obfd, osec) == NULL)
{
bfd_size_type amt = sizeof (struct pei_section_tdata);
coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
if (coff_section_data (obfd, osec)->tdata == NULL)
return FALSE;
}
pei_section_data (obfd, osec)->virt_size =
pei_section_data (ibfd, isec)->virt_size;
pei_section_data (obfd, osec)->pe_flags =
pei_section_data (ibfd, isec)->pe_flags;
}
return TRUE;
}
void
_bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
{
coff_get_symbol_info (abfd, symbol, ret);
}
#if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
static int
sort_x64_pdata (const void *l, const void *r)
{
const char *lp = (const char *) l;
const char *rp = (const char *) r;
bfd_vma vl, vr;
vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
if (vl != vr)
return (vl < vr ? -1 : 1);
/* We compare just begin address. */
return 0;
}
#endif
/* Functions to process a .rsrc section. */
static unsigned int sizeof_leaves;
static unsigned int sizeof_strings;
static unsigned int sizeof_tables_and_entries;
static bfd_byte *
rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
static bfd_byte *
rsrc_count_entries (bfd * abfd,
bfd_boolean is_name,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias)
{
unsigned long entry, addr, size;
if (data + 8 >= dataend)
return dataend + 1;
if (is_name)
{
bfd_byte * name;
entry = (long) bfd_get_32 (abfd, data);
if (HighBitSet (entry))
name = datastart + WithoutHighBit (entry);
else
name = datastart + entry - rva_bias;
if (name + 2 >= dataend)
return dataend + 1;
unsigned int len = bfd_get_16 (abfd, name);
if (len == 0 || len > 256)
return dataend + 1;
sizeof_strings += (len + 1) * 2;
}
entry = (long) bfd_get_32 (abfd, data + 4);
if (HighBitSet (entry))
return rsrc_count_directory (abfd,
datastart,
datastart + WithoutHighBit (entry),
dataend, rva_bias);
if (datastart + entry + 16 >= dataend)
return dataend + 1;
addr = (long) bfd_get_32 (abfd, datastart + entry);
size = (long) bfd_get_32 (abfd, datastart + entry + 4);
sizeof_leaves += 16;
return datastart + addr - rva_bias + size;
}
static bfd_byte *
rsrc_count_directory (bfd * abfd,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias)
{
unsigned int num_entries, num_ids;
bfd_byte * highest_data = data;
if (data + 16 >= dataend)
return dataend + 1;
num_entries = (int) bfd_get_16 (abfd, data + 12);
num_ids = (int) bfd_get_16 (abfd, data + 14);
num_entries += num_ids;
data += 16;
sizeof_tables_and_entries += 16;
while (num_entries --)
{
bfd_byte * entry_end;
entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
datastart, data, dataend, rva_bias);
data += 8;
sizeof_tables_and_entries += 8;
highest_data = max (highest_data, entry_end);
if (entry_end >= dataend)
break;
}
return max (highest_data, data);
}
typedef struct rsrc_dir_chain
{
unsigned int num_entries;
struct rsrc_entry * first_entry;
struct rsrc_entry * last_entry;
} rsrc_dir_chain;
typedef struct rsrc_directory
{
unsigned int characteristics;
unsigned int time;
unsigned int major;
unsigned int minor;
rsrc_dir_chain names;
rsrc_dir_chain ids;
struct rsrc_entry * entry;
} rsrc_directory;
typedef struct rsrc_string
{
unsigned int len;
bfd_byte * string;
} rsrc_string;
typedef struct rsrc_leaf
{
unsigned int size;
unsigned int codepage;
bfd_byte * data;
} rsrc_leaf;
typedef struct rsrc_entry
{
bfd_boolean is_name;
union
{
unsigned int id;
struct rsrc_string name;
} name_id;
bfd_boolean is_dir;
union
{
struct rsrc_directory * directory;
struct rsrc_leaf * leaf;
} value;
struct rsrc_entry * next_entry;
struct rsrc_directory * parent;
} rsrc_entry;
static bfd_byte *
rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
static bfd_byte *
rsrc_parse_entry (bfd * abfd,
bfd_boolean is_name,
rsrc_entry * entry,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias,
rsrc_directory * parent)
{
unsigned long val, addr, size;
val = bfd_get_32 (abfd, data);
entry->parent = parent;
entry->is_name = is_name;
if (is_name)
{
/* FIXME: Add range checking ? */
if (HighBitSet (val))
{
val = WithoutHighBit (val);
entry->name_id.name.len = bfd_get_16 (abfd, datastart + val);
entry->name_id.name.string = datastart + val + 2;
}
else
{
entry->name_id.name.len = bfd_get_16 (abfd, datastart + val
- rva_bias);
entry->name_id.name.string = datastart + val - rva_bias + 2;
}
}
else
entry->name_id.id = val;
val = bfd_get_32 (abfd, data + 4);
if (HighBitSet (val))
{
entry->is_dir = TRUE;
entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
if (entry->value.directory == NULL)
return dataend;
return rsrc_parse_directory (abfd, entry->value.directory,
datastart,
datastart + WithoutHighBit (val),
dataend, rva_bias, entry);
}
entry->is_dir = FALSE;
entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
if (entry->value.leaf == NULL)
return dataend;
addr = bfd_get_32 (abfd, datastart + val);
size = entry->value.leaf->size = bfd_get_32 (abfd, datastart + val + 4);
entry->value.leaf->codepage = bfd_get_32 (abfd, datastart + val + 8);
entry->value.leaf->data = bfd_malloc (size);
if (entry->value.leaf->data == NULL)
return dataend;
memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
return datastart + (addr - rva_bias) + size;
}
static bfd_byte *
rsrc_parse_entries (bfd * abfd,
rsrc_dir_chain * chain,
bfd_boolean is_name,
bfd_byte * highest_data,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias,
rsrc_directory * parent)
{
unsigned int i;
rsrc_entry * entry;
if (chain->num_entries == 0)
{
chain->first_entry = chain->last_entry = NULL;
return highest_data;
}
entry = bfd_malloc (sizeof * entry);
if (entry == NULL)
return dataend;
chain->first_entry = entry;
for (i = chain->num_entries; i--;)
{
bfd_byte * entry_end;
entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
data, dataend, rva_bias, parent);
data += 8;
highest_data = max (entry_end, highest_data);
if (entry_end > dataend)
return dataend;
if (i)
{
entry->next_entry = bfd_malloc (sizeof * entry);
entry = entry->next_entry;
if (entry == NULL)
return dataend;
}
else
entry->next_entry = NULL;
}
chain->last_entry = entry;
return highest_data;
}
static bfd_byte *
rsrc_parse_directory (bfd * abfd,
rsrc_directory * table,
bfd_byte * datastart,
bfd_byte * data,
bfd_byte * dataend,
bfd_vma rva_bias,
rsrc_entry * entry)
{
bfd_byte * highest_data = data;
if (table == NULL)
return dataend;
table->characteristics = bfd_get_32 (abfd, data);
table->time = bfd_get_32 (abfd, data + 4);
table->major = bfd_get_16 (abfd, data + 8);
table->minor = bfd_get_16 (abfd, data + 10);
table->names.num_entries = bfd_get_16 (abfd, data + 12);
table->ids.num_entries = bfd_get_16 (abfd, data + 14);
table->entry = entry;
data += 16;
highest_data = rsrc_parse_entries (abfd, & table->names, TRUE, data,
datastart, data, dataend, rva_bias, table);
data += table->names.num_entries * 8;
highest_data = rsrc_parse_entries (abfd, & table->ids, FALSE, highest_data,
datastart, data, dataend, rva_bias, table);
data += table->ids.num_entries * 8;
return max (highest_data, data);
}
typedef struct rsrc_write_data
{
bfd * abfd;
bfd_byte * datastart;
bfd_byte * next_table;
bfd_byte * next_leaf;
bfd_byte * next_string;
bfd_byte * next_data;
bfd_vma rva_bias;
} rsrc_write_data;
static void
rsrc_write_string (rsrc_write_data * data,
rsrc_string * string)
{
bfd_put_16 (data->abfd, string->len, data->next_string);
memcpy (data->next_string + 2, string->string, string->len * 2);
data->next_string += (string->len + 1) * 2;
}
static inline unsigned int
rsrc_compute_rva (rsrc_write_data * data,
bfd_byte * addr)
{
return (addr - data->datastart) + data->rva_bias;
}
static void
rsrc_write_leaf (rsrc_write_data * data,
rsrc_leaf * leaf)
{
bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
data->next_leaf);
bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
data->next_leaf += 16;
memcpy (data->next_data, leaf->data, leaf->size);
data->next_data += leaf->size;
}
static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
static void
rsrc_write_entry (rsrc_write_data * data,
bfd_byte * where,
rsrc_entry * entry)
{
if (entry->is_name)
{
bfd_put_32 (data->abfd,
SetHighBit (data->next_string - data->datastart),
where);
rsrc_write_string (data, & entry->name_id.name);
}
else
bfd_put_32 (data->abfd, entry->name_id.id, where);
if (entry->is_dir)
{
bfd_put_32 (data->abfd,
SetHighBit (data->next_table - data->datastart),
where + 4);
rsrc_write_directory (data, entry->value.directory);
}
else
{
bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
rsrc_write_leaf (data, entry->value.leaf);
}
}
static void
rsrc_write_directory (rsrc_write_data * data,
rsrc_directory * dir)
{
rsrc_entry * entry;
unsigned int i;
bfd_byte * next_entry;
bfd_byte * nt;
bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
/* Compute where the entries and the next table will be placed. */
next_entry = data->next_table + 16;
data->next_table = next_entry + (dir->names.num_entries * 8)
+ (dir->ids.num_entries * 8);
nt = data->next_table;
/* Write the entries. */
for (i = dir->names.num_entries, entry = dir->names.first_entry;
i > 0 && entry != NULL;
i--, entry = entry->next_entry)
{
rsrc_write_entry (data, next_entry, entry);
next_entry += 8;
}
BFD_ASSERT (i == 0);
BFD_ASSERT (entry == NULL);
for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
i > 0 && entry != NULL;
i--, entry = entry->next_entry)
{
rsrc_write_entry (data, next_entry, entry);
next_entry += 8;
}
BFD_ASSERT (i == 0);
BFD_ASSERT (entry == NULL);
BFD_ASSERT (nt == next_entry);
}
#if defined HAVE_WCHAR_H && ! defined __CYGWIN__ && ! defined __MINGW32__
/* Return the length (number of units) of the first character in S,
putting its 'ucs4_t' representation in *PUC. */
static unsigned int
u16_mbtouc (wchar_t * puc, const unsigned short * s, unsigned int n)
{
unsigned short c = * s;
if (c < 0xd800 || c >= 0xe000)
{
*puc = c;
return 1;
}
if (c < 0xdc00)
{
if (n >= 2)
{
if (s[1] >= 0xdc00 && s[1] < 0xe000)
{
*puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
return 2;
}
}
else
{
/* Incomplete multibyte character. */
*puc = 0xfffd;
return n;
}
}
/* Invalid multibyte character. */
*puc = 0xfffd;
return 1;
}
#endif /* HAVE_WCHAR_H and not Cygwin/Mingw */
/* Perform a comparison of two entries. */
static signed int
rsrc_cmp (bfd_boolean is_name, rsrc_entry * a, rsrc_entry * b)
{
signed int res;
bfd_byte * astring;
unsigned int alen;
bfd_byte * bstring;
unsigned int blen;
if (! is_name)
return a->name_id.id - b->name_id.id;
/* We have to perform a case insenstive, unicode string comparison... */
astring = a->name_id.name.string;
alen = a->name_id.name.len;
bstring = b->name_id.name.string;
blen = b->name_id.name.len;
#if defined __CYGWIN__ || defined __MINGW32__
/* Under Windows hosts (both Cygwin and Mingw types),
unicode == UTF-16 == wchar_t. The case insensitive string comparison
function however goes by different names in the two environments... */
#undef rscpcmp
#ifdef __CYGWIN__
#define rscpcmp wcsncasecmp
#endif
#ifdef __MINGW32__
#define rscpcmp wcsnicmp
#endif
res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
min (alen, blen));
#elif defined HAVE_WCHAR_H
{
unsigned int i;
res = 0;
for (i = min (alen, blen); i--; astring += 2, bstring += 2)
{
wchar_t awc;
wchar_t bwc;
/* Convert UTF-16 unicode characters into wchar_t characters so
that we can then perform a case insensitive comparison. */
int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
if (Alen != Blen)
return Alen - Blen;
res = wcsncasecmp (& awc, & bwc, 1);
if (res)
break;
}
}
#else
/* Do the best we can - a case sensitive, untranslated comparison. */
res = memcmp (astring, bstring, min (alen, blen) * 2);
#endif
if (res == 0)
res = alen - blen;
return res;
}
static void
rsrc_print_name (char * buffer, rsrc_string string)
{
unsigned int i;
bfd_byte * name = string.string;
for (i = string.len; i--; name += 2)
sprintf (buffer + strlen (buffer), "%.1s", name);
}
static const char *
rsrc_resource_name (rsrc_entry * entry, rsrc_directory * dir)
{
static char buffer [256];
bfd_boolean is_string = FALSE;
buffer[0] = 0;
if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
&& dir->entry->parent->entry != NULL)
{
strcpy (buffer, "type: ");
if (dir->entry->parent->entry->is_name)
rsrc_print_name (buffer + strlen (buffer),
dir->entry->parent->entry->name_id.name);
else
{
unsigned int id = dir->entry->parent->entry->name_id.id;
sprintf (buffer + strlen (buffer), "%x", id);
switch (id)
{
case 1: strcat (buffer, " (CURSOR)"); break;
case 2: strcat (buffer, " (BITMAP)"); break;
case 3: strcat (buffer, " (ICON)"); break;
case 4: strcat (buffer, " (MENU)"); break;
case 5: strcat (buffer, " (DIALOG)"); break;
case 6: strcat (buffer, " (STRING)"); is_string = TRUE; break;
case 7: strcat (buffer, " (FONTDIR)"); break;
case 8: strcat (buffer, " (FONT)"); break;
case 9: strcat (buffer, " (ACCELERATOR)"); break;
case 10: strcat (buffer, " (RCDATA)"); break;
case 11: strcat (buffer, " (MESSAGETABLE)"); break;
case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
case 14: strcat (buffer, " (GROUP_ICON)"); break;
case 16: strcat (buffer, " (VERSION)"); break;
case 17: strcat (buffer, " (DLGINCLUDE)"); break;
case 19: strcat (buffer, " (PLUGPLAY)"); break;
case 20: strcat (buffer, " (VXD)"); break;
case 21: strcat (buffer, " (ANICURSOR)"); break;
case 22: strcat (buffer, " (ANIICON)"); break;
case 23: strcat (buffer, " (HTML)"); break;
case 24: strcat (buffer, " (MANIFEST)"); break;
case 240: strcat (buffer, " (DLGINIT)"); break;
case 241: strcat (buffer, " (TOOLBAR)"); break;
}
}
}
if (dir != NULL && dir->entry != NULL)
{
strcat (buffer, " name: ");
if (dir->entry->is_name)
rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
else
{
unsigned int id = dir->entry->name_id.id;
sprintf (buffer + strlen (buffer), "%x", id);
if (is_string)
sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
(id - 1) << 4, (id << 4) - 1);
}
}
if (entry != NULL)
{
strcat (buffer, " lang: ");
if (entry->is_name)
rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
else
sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
}
return buffer;
}
/* *sigh* Windows resource strings are special. Only the top 28-bits of
their ID is stored in the NAME entry. The bottom four bits are used as
an index into unicode string table that makes up the data of the leaf.
So identical type-name-lang string resources may not actually be
identical at all.
This function is called when we have detected two string resources with
match top-28-bit IDs. We have to scan the string tables inside the leaves
and discover if there are any real collisions. If there are then we report
them and return FALSE. Otherwise we copy any strings from B into A and
then return TRUE. */
static bfd_boolean
rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
rsrc_entry * b ATTRIBUTE_UNUSED)
{
unsigned int copy_needed = 0;
unsigned int i;
bfd_byte * astring;
bfd_byte * bstring;
bfd_byte * new_data;
bfd_byte * nstring;
/* Step one: Find out what we have to do. */
BFD_ASSERT (! a->is_dir);
astring = a->value.leaf->data;
BFD_ASSERT (! b->is_dir);
bstring = b->value.leaf->data;
for (i = 0; i < 16; i++)
{
unsigned int alen = astring[0] + (astring[1] << 8);
unsigned int blen = bstring[0] + (bstring[1] << 8);
if (alen == 0)
{
copy_needed += blen * 2;
}
else if (blen == 0)
;
else if (alen != blen)
/* FIXME: Should we continue the loop in order to report other duplicates ? */
break;
/* alen == blen != 0. We might have two identical strings. If so we
can ignore the second one. There is no need for wchar_t vs UTF-16
theatrics here - we are only interested in (case sensitive) equality. */
else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
break;
astring += (alen + 1) * 2;
bstring += (blen + 1) * 2;
}
if (i != 16)
{
if (a->parent != NULL
&& a->parent->entry != NULL
&& a->parent->entry->is_name == FALSE)
_bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
((a->parent->entry->name_id.id - 1) << 4) + i);
return FALSE;
}
if (copy_needed == 0)
return TRUE;
/* If we reach here then A and B must both have non-colliding strings.
(We never get string resources with fully empty string tables).
We need to allocate an extra COPY_NEEDED bytes in A and then bring
in B's strings. */
new_data = bfd_malloc (a->value.leaf->size + copy_needed);
if (new_data == NULL)
return FALSE;
nstring = new_data;
astring = a->value.leaf->data;
bstring = b->value.leaf->data;
for (i = 0; i < 16; i++)
{
unsigned int alen = astring[0] + (astring[1] << 8);
unsigned int blen = bstring[0] + (bstring[1] << 8);
if (alen != 0)
{
memcpy (nstring, astring, (alen + 1) * 2);
nstring += (alen + 1) * 2;
}
else if (blen != 0)
{
memcpy (nstring, bstring, (blen + 1) * 2);
nstring += (blen + 1) * 2;
}
else
{
* nstring++ = 0;
* nstring++ = 0;
}
astring += (alen + 1) * 2;
bstring += (blen + 1) * 2;
}
BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
free (a->value.leaf->data);
a->value.leaf->data = new_data;
a->value.leaf->size += copy_needed;
return TRUE;
}
static void rsrc_merge (rsrc_entry *, rsrc_entry *);
/* Sort the entries in given part of the directory.
We use an old fashioned bubble sort because we are dealing
with lists and we want to handle matches specially. */
static void
rsrc_sort_entries (rsrc_dir_chain * chain,
bfd_boolean is_name,
rsrc_directory * dir)
{
rsrc_entry * entry;
rsrc_entry * next;
rsrc_entry ** points_to_entry;
bfd_boolean swapped;
if (chain->num_entries < 2)
return;
do
{
swapped = FALSE;
points_to_entry = & chain->first_entry;
entry = * points_to_entry;
next = entry->next_entry;
do
{
signed int cmp = rsrc_cmp (is_name, entry, next);
if (cmp > 0)
{
entry->next_entry = next->next_entry;
next->next_entry = entry;
* points_to_entry = next;
points_to_entry = & next->next_entry;
next = entry->next_entry;
swapped = TRUE;
}
else if (cmp == 0)
{
if (entry->is_dir && next->is_dir)
{
/* When we encounter identical directory entries we have to
merge them together. The exception to this rule is for
resource manifests - there can only be one of these,
even if they differ in language. Zero-language manifests
are assumed to be default manifests (provided by the
cygwin build system) and these can be silently dropped,
unless that would reduce the number of manifests to zero.
There should only ever be one non-zero lang manifest -
if there are more it is an error. A non-zero lang
manifest takes precedence over a default manifest. */
if (entry->is_name == FALSE
&& entry->name_id.id == 1
&& dir != NULL
&& dir->entry != NULL
&& dir->entry->is_name == FALSE
&& dir->entry->name_id.id == 0x18)
{
if (next->value.directory->names.num_entries == 0
&& next->value.directory->ids.num_entries == 1
&& next->value.directory->ids.first_entry->is_name == FALSE
&& next->value.directory->ids.first_entry->name_id.id == 0)
/* Fall through so that NEXT is dropped. */
;
else if (entry->value.directory->names.num_entries == 0
&& entry->value.directory->ids.num_entries == 1
&& entry->value.directory->ids.first_entry->is_name == FALSE
&& entry->value.directory->ids.first_entry->name_id.id == 0)
{
/* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
entry->next_entry = next->next_entry;
next->next_entry = entry;
* points_to_entry = next;
points_to_entry = & next->next_entry;
next = entry->next_entry;
swapped = TRUE;
}
else
{
_bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
bfd_set_error (bfd_error_file_truncated);
return;
}
/* Unhook NEXT from the chain. */
/* FIXME: memory loss here. */
entry->next_entry = next->next_entry;
chain->num_entries --;
if (chain->num_entries < 2)
return;
next = next->next_entry;
}
else
rsrc_merge (entry, next);
}
else if (entry->is_dir != next->is_dir)
{
_bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
bfd_set_error (bfd_error_file_truncated);
return;
}
else
{
/* Otherwise with identical leaves we issue an error
message - because there should never be duplicates.
The exception is Type 18/Name 1/Lang 0 which is the
defaul manifest - this can just be dropped. */
if (entry->is_name == FALSE
&& entry->name_id.id == 0
&& dir != NULL
&& dir->entry != NULL
&& dir->entry->is_name == FALSE
&& dir->entry->name_id.id == 1
&& dir->entry->parent != NULL
&& dir->entry->parent->entry != NULL
&& dir->entry->parent->entry->is_name == FALSE
&& dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
;
else if (dir != NULL
&& dir->entry != NULL
&& dir->entry->parent != NULL
&& dir->entry->parent->entry != NULL
&& dir->entry->parent->entry->is_name == FALSE
&& dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
{
/* Strings need special handling. */
if (! rsrc_merge_string_entries (entry, next))
{
/* _bfd_error_handler should have been called inside merge_strings. */
bfd_set_error (bfd_error_file_truncated);
return;
}
}
else
{
if (dir == NULL
|| dir->entry == NULL
|| dir->entry->parent == NULL
|| dir->entry->parent->entry == NULL)
_bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
else
_bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
rsrc_resource_name (entry, dir));
bfd_set_error (bfd_error_file_truncated);
return;
}
}
/* Unhook NEXT from the chain. */
entry->next_entry = next->next_entry;
chain->num_entries --;
if (chain->num_entries < 2)
return;
next = next->next_entry;
}
else
{
points_to_entry = & entry->next_entry;
entry = next;
next = next->next_entry;
}
}
while (next);
chain->last_entry = entry;
}
while (swapped);
}
/* Attach B's chain onto A. */
static void
rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
{
if (bchain->num_entries == 0)
return;
achain->num_entries += bchain->num_entries;
if (achain->first_entry == NULL)
{
achain->first_entry = bchain->first_entry;
achain->last_entry = bchain->last_entry;
}
else
{
achain->last_entry->next_entry = bchain->first_entry;
achain->last_entry = bchain->last_entry;
}
bchain->num_entries = 0;
bchain->first_entry = bchain->last_entry = NULL;
}
static void
rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
{
rsrc_directory * adir;
rsrc_directory * bdir;
BFD_ASSERT (a->is_dir);
BFD_ASSERT (b->is_dir);
adir = a->value.directory;
bdir = b->value.directory;
if (adir->characteristics != bdir->characteristics)
{
_bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics\n"));
bfd_set_error (bfd_error_file_truncated);
return;
}
if (adir->major != bdir->major || adir->minor != bdir->minor)
{
_bfd_error_handler (_(".rsrc merge failure: differing directory versions\n"));
bfd_set_error (bfd_error_file_truncated);
return;
}
/* Attach B's name chain to A. */
rsrc_attach_chain (& adir->names, & bdir->names);
/* Attach B's ID chain to A. */
rsrc_attach_chain (& adir->ids, & bdir->ids);
/* Now sort A's entries. */
rsrc_sort_entries (& adir->names, TRUE, adir);
rsrc_sort_entries (& adir->ids, FALSE, adir);
}
/* Check the .rsrc section. If it contains multiple concatenated
resources then we must merge them properly. Otherwise Windows
will ignore all but the first set. */
static void
rsrc_process_section (bfd * abfd,
struct coff_final_link_info * pfinfo)
{
rsrc_directory new_table;
bfd_size_type size;
asection * sec;
pe_data_type * pe;
bfd_vma rva_bias;
bfd_byte * data;
bfd_byte * datastart;
bfd_byte * dataend;
bfd_byte * new_data;
unsigned int num_resource_sets;
rsrc_directory * type_tables;
rsrc_write_data write_data;
unsigned int indx;
new_table.names.num_entries = 0;
new_table.ids.num_entries = 0;
sec = bfd_get_section_by_name (abfd, ".rsrc");
if (sec == NULL || (size = sec->rawsize) == 0)
return;
pe = pe_data (abfd);
if (pe == NULL)
return;
rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
data = bfd_malloc (size);
if (data == NULL)
return;
datastart = data;
if (! bfd_get_section_contents (abfd, sec, data, 0, size))
goto end;
/* Step one: Walk the section, computing the size of the tables,
leaves and data and decide if we need to do anything. */
dataend = data + size;
num_resource_sets = 0;
sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
while (data < dataend)
{
bfd_byte * p = data;
data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
if (data > dataend)
{
/* Corrupted .rsrc section - cannot merge. */
_bfd_error_handler (_("%s: .rsrc merge failure: corrupt .rsrc section"),
bfd_get_filename (abfd));
bfd_set_error (bfd_error_file_truncated);
goto end;
}
/* Align the data pointer - we assume 1^2 alignment. */
data = (bfd_byte *) (((ptrdiff_t) (data + 3)) & ~ 3);
rva_bias += data - p;
if (data == (dataend - 4))
data = dataend;
++ num_resource_sets;
}
if (num_resource_sets < 2)
/* No merging necessary. */
goto end;
/* Step two: Walk the data again, building trees of the resources. */
data = datastart;
rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
if (type_tables == NULL)
goto end;
indx = 0;
while (data < dataend)
{
bfd_byte * p = data;
data = rsrc_parse_directory (abfd, type_tables + indx, data, data,
dataend, rva_bias, NULL);
data = (bfd_byte *) (((ptrdiff_t) (data + 3)) & ~ 3);
rva_bias += data - p;
if (data == (dataend - 4))
data = dataend;
indx ++;
}
BFD_ASSERT (indx == num_resource_sets);
/* Step three: Merge the top level tables (there can be only one).
We must ensure that the merged entries are in ascending order.
We also thread the top level table entries from the old tree onto
the new table, so that they can be pulled off later. */
/* FIXME: Should we verify that all type tables are the same ? */
new_table.characteristics = type_tables[0].characteristics;
new_table.time = type_tables[0].time;
new_table.major = type_tables[0].major;
new_table.minor = type_tables[0].minor;
/* Chain the NAME entries onto the table. */
new_table.names.first_entry = NULL;
new_table.names.last_entry = NULL;
for (indx = 0; indx < num_resource_sets; indx++)
rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
rsrc_sort_entries (& new_table.names, TRUE, & new_table);
/* Chain the ID entries onto the table. */
new_table.ids.first_entry = NULL;
new_table.ids.last_entry = NULL;
for (indx = 0; indx < num_resource_sets; indx++)
rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
rsrc_sort_entries (& new_table.ids, FALSE, & new_table);
/* Step four: Create new contents for the .rsrc section. */
new_data = bfd_malloc (size);
if (new_data == NULL)
goto end;
write_data.abfd = abfd;
write_data.datastart = new_data;
write_data.next_table = new_data;
write_data.next_leaf = new_data + sizeof_tables_and_entries;
write_data.next_string = write_data.next_leaf + sizeof_leaves;
write_data.next_data = write_data.next_string + sizeof_strings;
write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
rsrc_write_directory (& write_data, & new_table);
/* Step five: Replace the old contents with the new.
We recompute the size as we may have lost entries due to mergeing. */
size = ((write_data.next_data - new_data) + 3) & ~ 3;
bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
sec->size = sec->rawsize = size;
end:
/* FIXME: Free the resource tree, if we have one. */
free (datastart);
}
/* Handle the .idata section and other things that need symbol table
access. */
bfd_boolean
_bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
{
struct coff_link_hash_entry *h1;
struct bfd_link_info *info = pfinfo->info;
bfd_boolean result = TRUE;
/* There are a few fields that need to be filled in now while we
have symbol table access.
The .idata subsections aren't directly available as sections, but
they are in the symbol table, so get them from there. */
/* The import directory. This is the address of .idata$2, with size
of .idata$2 + .idata$3. */
h1 = coff_link_hash_lookup (coff_hash_table (info),
".idata$2", FALSE, FALSE, TRUE);
if (h1 != NULL)
{
/* PR ld/2729: We cannot rely upon all the output sections having been
created properly, so check before referencing them. Issue a warning
message for any sections tht could not be found. */
if ((h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
(h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset);
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"),
abfd);
result = FALSE;
}
h1 = coff_link_hash_lookup (coff_hash_table (info),
".idata$4", FALSE, FALSE, TRUE);
if (h1 != NULL
&& (h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
((h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset)
- pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"),
abfd);
result = FALSE;
}
/* The import address table. This is the size/address of
.idata$5. */
h1 = coff_link_hash_lookup (coff_hash_table (info),
".idata$5", FALSE, FALSE, TRUE);
if (h1 != NULL
&& (h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
(h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset);
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"),
abfd);
result = FALSE;
}
h1 = coff_link_hash_lookup (coff_hash_table (info),
".idata$6", FALSE, FALSE, TRUE);
if (h1 != NULL
&& (h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
((h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset)
- pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
abfd);
result = FALSE;
}
}
else
{
h1 = coff_link_hash_lookup (coff_hash_table (info),
"__IAT_start__", FALSE, FALSE, TRUE);
if (h1 != NULL
&& (h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
{
bfd_vma iat_va;
iat_va =
(h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset);
h1 = coff_link_hash_lookup (coff_hash_table (info),
"__IAT_end__", FALSE, FALSE, TRUE);
if (h1 != NULL
&& (h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
{
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
((h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset)
- iat_va);
if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
}
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
" because .idata$6 is missing"), abfd);
result = FALSE;
}
}
}
h1 = coff_link_hash_lookup (coff_hash_table (info),
(bfd_get_symbol_leading_char(abfd) != 0
? "__tls_used" : "_tls_used"),
FALSE, FALSE, TRUE);
if (h1 != NULL)
{
if ((h1->root.type == bfd_link_hash_defined
|| h1->root.type == bfd_link_hash_defweak)
&& h1->root.u.def.section != NULL
&& h1->root.u.def.section->output_section != NULL)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
(h1->root.u.def.value
+ h1->root.u.def.section->output_section->vma
+ h1->root.u.def.section->output_offset
- pe_data (abfd)->pe_opthdr.ImageBase);
else
{
_bfd_error_handler
(_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"),
abfd);
result = FALSE;
}
/* According to PECOFF sepcifications by Microsoft version 8.2
the TLS data directory consists of 4 pointers, followed
by two 4-byte integer. This implies that the total size
is different for 32-bit and 64-bit executables. */
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
#else
pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
#endif
}
/* If there is a .pdata section and we have linked pdata finally, we
need to sort the entries ascending. */
#if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
{
asection *sec = bfd_get_section_by_name (abfd, ".pdata");
if (sec)
{
bfd_size_type x = sec->rawsize;
bfd_byte *tmp_data = NULL;
if (x)
tmp_data = bfd_malloc (x);
if (tmp_data != NULL)
{
if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
{
qsort (tmp_data,
(size_t) (x / 12),
12, sort_x64_pdata);
bfd_set_section_contents (pfinfo->output_bfd, sec,
tmp_data, 0, x);
}
free (tmp_data);
}
}
}
#endif
rsrc_process_section (abfd, pfinfo);
/* If we couldn't find idata$2, we either have an excessively
trivial program or are in DEEP trouble; we have to assume trivial
program.... */
return result;
}
| {
"content_hash": "599d4f2bb4197ff82226b5a655b48a74",
"timestamp": "",
"source": "github",
"line_count": 3837,
"max_line_length": 120,
"avg_line_length": 29.865519937451133,
"alnum_prop": 0.611018028867131,
"repo_name": "execunix/vinos",
"id": "1da5a9a9869f27e6f87f45d180fe9c2ff9530769",
"size": "115541",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "external/gpl3/gdb/dist/bfd/peXXigen.c",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XK_enopensquarebullet` constant in crate `x11_dl`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XK_enopensquarebullet">
<title>x11_dl::keysym::XK_enopensquarebullet - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a></p><script>window.sidebarCurrent = {name: 'XK_enopensquarebullet', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>x11_dl</a>::<wbr><a href='index.html'>keysym</a>::<wbr><a class='constant' href=''>XK_enopensquarebullet</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-5136' class='srclink' href='../../src/x11_dl/keysym.rs.html#911' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XK_enopensquarebullet: <a class='type' href='../../libc/types/os/arch/c95/type.c_uint.html' title='libc::types::os::arch::c95::c_uint'>c_uint</a><code> = </code><code>0xae1</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "x11_dl";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html> | {
"content_hash": "7b0f6577a47f25196aa0072f0ecf4768",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 252,
"avg_line_length": 38.2970297029703,
"alnum_prop": 0.531540847983454,
"repo_name": "mcanders/bevy",
"id": "69877a5b7b97814056d227de6d17092b3e5385ea",
"size": "3868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/x11_dl/keysym/constant.XK_enopensquarebullet.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "316751"
}
],
"symlink_target": ""
} |
import * as amqp from 'amqplib';
import { Service } from './../globals/system';
import { IActionBusAdapter, IEventBusAdapter } from '../bus/busAdapter';
import { EventData } from "./messageBus";
import { RequestData } from "../pipeline/common";
import { CryptoHelper } from '../utils/crypto';
export /**
* RabbitAdapter
*/
class RabbitAdapter implements IActionBusAdapter, IEventBusAdapter {
private eventHandlers = new Map<string, { queue, domain: string, handlers: Function[], args: string }>();
private channel: amqp.Channel;
private initialized = false;
private ignoreInputMessages = false;
constructor(private address: string) {
if (!this.address)
throw new Error("Address is required for RabbitAdapter");
if (!address.startsWith("amqp://"))
this.address = "amqp://" + address;
}
open() {
let self = this;
return new Promise<void>((resolve, reject) => {
if (self.initialized)
{
return resolve();
}
self.initialized = true;
Service.log.info(null, ()=>"Open rabbitmq connection on " + Service.removePasswordFromUrl(this.address));
amqp.connect(this.address).then((conn: amqp.Connection) => {
conn.createChannel().then((ch: amqp.Channel) => {
self.channel = ch;
resolve();
});
})
.catch(err => {
Service.log.error(null, err, ()=>`Unable to open rabbit connection.`);
reject();
});
});
}
pauseReception() {
this.ignoreInputMessages = true;
}
resumeReception() {
this.ignoreInputMessages = false;
}
stopReception() {
this.pauseReception();
this.eventHandlers.forEach(eh => { this.channel.unbindQueue(eh.queue, eh.domain, eh.args); });
this.eventHandlers.clear();
}
dispose() {
this.stopReception();
this.channel.close();
}
/**
* Send domain event (event raises by an action)
* Domain events are shared by all services of any domains
*
* @param {string} domain
* @param {EventData} event
*
* @memberOf RabbitAdapter
*/
sendEvent(domain:string, event:EventData) {
if (!this.channel)
return;
domain = this.createSourceName(domain);
this.channel.assertExchange(domain, 'fanout', { durable: false });
this.channel.publish(domain, '', new Buffer(JSON.stringify(event)));
}
private createSourceName(domain: string) {
return "vulcain_" + domain.toLowerCase() + "_events";
}
private createEventQueueName(domain: string, key?: string)
{
if (!key)
return '';
// Create an unique by service + handler queue name
// domain, service, version + hash
return ["vulcain", domain.toLowerCase(), Service.fullServiceName, CryptoHelper.hash(key)].join('_');
}
/**
* Listening for domain events
*
* @param {string} domain
* @param {Function} handler
* @param {string} queuename
*
* If queuename is set, event are take into account by only one instance and a ack is send if the process complete sucessfully
* else event is distributed to every instance with no ack
*/
consumeEvents(domain: string, handler: (event: EventData) => void, distributionKey?:string) {
if (!this.channel)
return;
let self = this;
const queueName = this.createEventQueueName(domain, distributionKey);
// Since this method can be called many times for a same domain
// all handlers are aggregated on only one binding
domain = this.createSourceName(domain);
const handlerKey = domain + queueName;
let handlerInfo = this.eventHandlers.get(handlerKey);
if (handlerInfo) {
handlerInfo.handlers.push(handler);
return;
}
// First time for this domain, create the binding
this.channel.assertExchange(domain, 'fanout', { durable: false });
// For one event delivery:
// specific queue and exclusive=false
// else
// empty queue name and exclusive=true
let options = { exclusive: !queueName, autoDelete: !!queueName };
this.channel.assertQueue(queueName, options).then(queue => {
const handlers = [handler];
this.eventHandlers.set(handlerKey, {queue: queue.queue, domain, handlers, args: ''});
self.channel.bindQueue(queue.queue, domain, '');
self.channel.consume(queue.queue, async (msg) => {
if (this.ignoreInputMessages) return;
let obj = JSON.parse(msg.content.toString());
let handlerInfo = self.eventHandlers.get(handlerKey);
try {
if (handlerInfo) {
let tasks = handlerInfo.handlers.map(h => h(obj));
if (queueName) {
await Promise.all(tasks);
self.channel.ack(msg);
}
}
}
catch (e) {
Service.log.error(null, e, () => "Event handler failed for event " + obj.metadata.eventId);
}
}, { noAck: !queueName });
});
}
/**
* Task = asynchronous action
* Shared by the current service instances
*
* @param {string} domain
* @param {string} serviceId
* @param {ActionData} command
*
* @memberOf RabbitAdapter
*/
publishTask(domain:string, serviceId:string, command:RequestData) {
if (!this.channel)
return;
domain = domain.toLowerCase();
this.channel.assertExchange(domain, 'direct', { durable: false });
this.channel.publish(domain, serviceId, new Buffer(JSON.stringify(command)), {persistent:true});
}
/**
* Listening for asynchronous task
*
* @param {string} domain
* @param {string} serviceId
* @param {Function} handler
*
* @memberOf RabbitAdapter
*/
consumeTask(domain: string, serviceId: string, handler: (event: RequestData) => void) {
if (!this.channel)
return;
let self = this;
domain = domain.toLowerCase();
this.channel.assertExchange(domain, 'direct', { durable: false });
this.channel.assertQueue(domain, { durable: true }).then(queue => {
this.eventHandlers.set("Async:" + domain, {queue: queue.queue, domain, handlers: [handler], args: serviceId});
// Channel name = serviceId
self.channel.bindQueue(queue.queue, domain, serviceId);
self.channel.prefetch(1);
self.channel.consume(queue.queue, async (msg) => {
if (this.ignoreInputMessages) return;
await handler(JSON.parse(msg.content.toString()));
self.channel.ack(msg);
}, { noAck: false });
});
}
} | {
"content_hash": "b36e3825e36b6f577b373af97b88971f",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 130,
"avg_line_length": 33.91943127962085,
"alnum_prop": 0.5690931954729636,
"repo_name": "vulcainjs/vulcain-corejs",
"id": "8167d80fd80f5eae7e54707a352e1c47ff61cb7a",
"size": "7157",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/bus/rabbitAdapter.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "TypeScript",
"bytes": "585816"
}
],
"symlink_target": ""
} |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BootLoader. ;;
;; Copyright (C) 2007 Diolan ( http://www.diolan.com ) ;;
;; ;;
;; This program is free software: you can redistribute it and/or modify ;;
;; it under the terms of the GNU General Public License as published by ;;
;; the Free Software Foundation, either version 3 of the License, or ;;
;; (at your option) any later version. ;;
;; ;;
;; This program is distributed in the hope that it will be useful, ;;
;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;
;; GNU General Public License for more details. ;;
;; ;;
;; You should have received a copy of the GNU General Public License ;;
;; along with this program. If not, see <http://www.gnu.org/licenses/> ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Copyright (c) 2015 Kustaa Nyholm / SpareTimeLabs
; - modified NOT to use Extended Instruction Set (for compatibility with SDCC)
; - ported to PIC18F4550
; - ported to PIC18F45K50
; - extensively optimized to still fit in the 2 kB boot block
;
;-----------------------------------------------------------------------------
; Device Reset Vectors
;-----------------------------------------------------------------------------
#include "mpasmx.inc"
#include "boot.inc"
#include "io_cfg.inc"
;-----------------------------------------------------------------------------
; Externals
;-----------------------------------------------------------------------------
extern main
extern bootloader_soft_reset
;-----------------------------------------------------------------------------
; START
;-----------------------------------------------------------------------------
VECTORS CODE 0x0000
;--- RESET Vector
org 0x0000
clrf TBLPTRU
clrf TBLPTRH
bra pre_main
;-----------------------------------------------------------------------------
;--- HIGH Interrupt Vector
org 0x0008
goto APP_HIGH_INTERRUPT_VECTOR
;-----------------------------------------------------------------------------
pre_main
; JP_BOOTLOADER_PIN to digital mode
;
; Here is four words free if processors is ot 18F45K50
;
#ifdef __18F45K50
movlw 0x80 ; 3X PLL ratio mode
movwf OSCTUNE
;
movlw 0x70 ; Switch to 16MHz HFINTOSC
movwf OSCCON
#endif
;
bra main
;-----------------------------------------------------------------------------
;--- BOOTLOADER External Entry Point
org 0x0016
if USE_EEPROM_MARK
bra bootloader_soft_reset
endif
;--- HIGH Interrupt Vector
org 0x0018
goto APP_LOW_INTERRUPT_VECTOR
;-----------------------------------------------------------------------------
; APPLICATION STUB
;-----------------------------------------------------------------------------
APPSTRT CODE APP_RESET_VECTOR
bra $
;-----------------------------------------------------------------------------
END
| {
"content_hash": "3507a0e3f70709836a828b68f43b330b",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 78,
"avg_line_length": 42.8125,
"alnum_prop": 0.3821897810218978,
"repo_name": "nyholku/TOAD4",
"id": "e226a3bab4d8a233fde3e84915645ac33d8a599e",
"size": "3425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "diolan-plus2-toad5/fw/vectors.asm",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "99534"
},
{
"name": "Java",
"bytes": "17072"
},
{
"name": "Makefile",
"bytes": "5283"
}
],
"symlink_target": ""
} |
.. _backend-api:
*************************************
:mod:`mopidy.backend` --- Backend API
*************************************
.. module:: mopidy.backend
:synopsis: The API implemented by backends
The backend API is the interface that must be implemented when you create a
backend. If you are working on a frontend and need to access the backends, see
the :ref:`core-api` instead.
URIs and routing of requests to the backend
===========================================
When Mopidy's core layer is processing a client request, it routes the request
to one or more appropriate backends based on the URIs of the objects the
request touches on. The objects' URIs are compared with the backends'
:attr:`~mopidy.backend.Backend.uri_schemes` to select the relevant backends.
An often used pattern when implementing Mopidy backends is to create your own
URI scheme which you use for all tracks, playlists, etc. related to your
backend. In most cases the Mopidy URI is translated to an actual URI that
GStreamer knows how to play right before playback. For example:
- Spotify already has its own URI scheme (``spotify:track:...``,
``spotify:playlist:...``, etc.) used throughout their applications, and thus
Mopidy-Spotify simply uses the same URI scheme. Playback is handled by
pushing raw audio data into a GStreamer ``appsrc`` element.
- Mopidy-SoundCloud created it's own URI scheme, after the model of Spotify,
and uses URIs of the following forms: ``soundcloud:search``,
``soundcloud:user-...``, ``soundcloud:exp-...``, and ``soundcloud:set-...``.
Playback is handled by converting the custom ``soundcloud:..`` URIs to
``http://`` URIs immediately before they are passed on to GStreamer for
playback.
- Mopidy differentiates between ``file://...`` URIs handled by
:ref:`ext-stream` and ``local:...`` URIs handled by Mopidy-Local.
:ref:`ext-stream` can play ``file://...`` URIs pointing to tracks and
playlists located anywhere on your system, but it doesn't know a thing about
the object before you play it. On the other hand, Mopidy-Local scans a
predefined :confval:`local/media_dir` to build a meta data library of all
known tracks. It is thus limited to playing tracks residing in the media
library, but can provide additional features like directory browsing and
search. In other words, we have two different ways of playing local music,
handled by two different backends, and have thus created two different URI
schemes to separate their handling. The ``local:...`` URIs are converted to
``file://...`` URIs immediately before they are passed on to GStreamer for
playback.
If there isn't an existing URI scheme that fits for your backend's purpose,
you should create your own, and name it after your extension's
:attr:`~mopidy.ext.Extension.ext_name`. Care should be taken not to conflict
with already in use URI schemes. It is also recommended to design the format
such that tracks, playlists and other entities can be distinguished easily.
However, it's important to note that outside of the backend that created them,
URIs are opaque values that neither Mopidy's core layer or Mopidy frontends
should attempt to derive any meaning from. The only valid exception to this is
checking the scheme.
Backend class
=============
.. autoclass:: mopidy.backend.Backend
:members:
Playback provider
=================
.. autoclass:: mopidy.backend.PlaybackProvider
:members:
Playlists provider
==================
.. autoclass:: mopidy.backend.PlaylistsProvider
:members:
Library provider
================
.. autoclass:: mopidy.backend.LibraryProvider
:members:
Backend listener
================
.. autoclass:: mopidy.backend.BackendListener
:members:
Backend implementations
=======================
See the `extension registry <https://mopidy.com/ext/>`_.
| {
"content_hash": "282a828979d92a31be066c26d4232548",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 78,
"avg_line_length": 37,
"alnum_prop": 0.7104989604989606,
"repo_name": "kingosticks/mopidy",
"id": "4f8e7096284a6807673b8a2626f740373e9fc5b5",
"size": "3848",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "docs/api/backend.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "610"
},
{
"name": "HTML",
"bytes": "805"
},
{
"name": "Python",
"bytes": "743402"
},
{
"name": "Roff",
"bytes": "573"
},
{
"name": "Shell",
"bytes": "741"
}
],
"symlink_target": ""
} |
<ion-modal-view>
<ion-header-bar align-title="center">
<button class="button button-dark button-clear" ng-click="close()" translate>
Close
</button>
<div class="title" translate>
Search Transactions ({{wallet.coin}})
</div>
</ion-header-bar>
<ion-content ng-controller="searchController" ng-init="search = ''">
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios-search placeholder-icon"></i>
<input type="search" ng-model="search" ng-init="search = ''" ng-change="updateSearchInput(search)"
placeholder="{{'Search transactions' | translate}}">
</label>
</div>
<div class="list">
<div class="wallet-details__list" ng-show="filteredTxHistory.length === 0 && search != ''">
<div class="text-gray text-center p10t">
{{'No results found'|translate}}
</div>
<div class="p10t text-center">
<button class="button button-small button-primary" ng-click="searchOnBlockchain(search)" translate>
<span ng-if="searchTermIsTxId">{{'Show Transaction on Blockchain'|translate}}</span>
<span ng-if="searchTermIsAddress">{{'Show Address on Blockchain'|translate}}</span>
<span ng-if="!searchTermIsAddress && !searchTermIsTxId">{{'Search on Blockchain'|translate}}</span>
</button>
</div>
</div>
<div class="wallet-details__list" ng-show="txHistory[0]">
<div ng-repeat="btx in txHistorySearchResults track by $index" ng-click="openTx(btx)">
<span ng-include="'views/includes/walletHistory.html'"></span>
</div>
</div>
<div class="text-gray text-center size-12 p10t" ng-if="txHistoryShowMore">
<span class="size-12">{{filteredTxHistory.length - txHistorySearchResults.length}} more</span>
<i class="icon-arrow-down4"></i>
</div>
<ion-infinite-scroll
ng-if="txHistoryShowMore"
on-infinite="moreSearchResults()"
distance="1%">
</ion-infinite-scroll>
</div>
</ion-content>
</ion-modal-view>
| {
"content_hash": "62ae0a3b05f6fa91c51c8b3b551b1c3e",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 111,
"avg_line_length": 42.74,
"alnum_prop": 0.6176883481516144,
"repo_name": "Bitcoin-com/Wallet",
"id": "66eb5c6aafc70b949067cf1a9ca915398f4bab65",
"size": "2137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/views/modals/search.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "678073"
},
{
"name": "HTML",
"bytes": "397373"
},
{
"name": "Inno Setup",
"bytes": "2753"
},
{
"name": "JavaScript",
"bytes": "1620971"
},
{
"name": "Makefile",
"bytes": "642"
},
{
"name": "Python",
"bytes": "9739"
},
{
"name": "Shell",
"bytes": "11875"
}
],
"symlink_target": ""
} |
<com.tle.beans.mime.MimeEntry>
<id>769528</id>
<institution>
<id>769423</id>
<uniqueId>0</uniqueId>
<enabled>true</enabled>
</institution>
<extensions class="list">
<string>jif</string>
<string>jfif</string>
<string>jpe</string>
<string>jpg</string>
<string>jpeg</string>
</extensions>
<type>image/jpeg</type>
<description>Image</description>
<attributes>
<entry>
<string>enabledViewers</string>
<string>["fancy","livNavTreeViewer"]</string>
</entry>
<entry>
<string>PluginIconPath</string>
<string>icons/image.png</string>
</entry>
<entry>
<string>defaultViewerId</string>
<string>fancy</string>
</entry>
</attributes>
</com.tle.beans.mime.MimeEntry> | {
"content_hash": "96940ea9ecb1bd6c392a3f5142201bec",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 71,
"avg_line_length": 25.193548387096776,
"alnum_prop": 0.6338028169014085,
"repo_name": "equella/Equella",
"id": "590345374ef9c28c1b1b2b80473160053bf458f6",
"size": "781",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "autotest/Tests/tests/ldapad/institution/mimetypes/image_jpeg.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "402"
},
{
"name": "Batchfile",
"bytes": "38432"
},
{
"name": "CSS",
"bytes": "648823"
},
{
"name": "Dockerfile",
"bytes": "2055"
},
{
"name": "FreeMarker",
"bytes": "370046"
},
{
"name": "HTML",
"bytes": "865667"
},
{
"name": "Java",
"bytes": "27081020"
},
{
"name": "JavaScript",
"bytes": "1673995"
},
{
"name": "PHP",
"bytes": "821"
},
{
"name": "PLpgSQL",
"bytes": "1363"
},
{
"name": "PureScript",
"bytes": "307610"
},
{
"name": "Python",
"bytes": "79871"
},
{
"name": "Scala",
"bytes": "765981"
},
{
"name": "Shell",
"bytes": "64170"
},
{
"name": "TypeScript",
"bytes": "146564"
},
{
"name": "XSLT",
"bytes": "510113"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "72a1a468b391dfdc46101103529c604b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "c74b7e2b707f79dbcc4f771562fad677b5548417",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Chlorophyta/Ulvophyceae/Ulvales/Ulvaceae/Ulva/Ulva lobata/ Syn. Phycoseris lobata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>equations: 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.10.1 / equations - 1.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
equations
<small>
1.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-16 14:17:11 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-16 14:17:11 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
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
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
authors: [ "Matthieu Sozeau <matthieu.sozeau@inria.fr>" "Cyprien Mangin <cyprien.mangin@m4x.org>" ]
dev-repo: "git+https://github.com/mattam82/Coq-Equations.git"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://mattam82.github.io/Coq-Equations"
bug-reports: "https://github.com/mattam82/Coq-Equations/issues"
license: "LGPL-2.1-only"
build: [
["coq_makefile" "-f" "_CoqProject" "-o" "Makefile"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Equations"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7"}
]
synopsis: "A function definition package for Coq"
description: """
Equations is a function definition plugin for Coq, that allows the
definition of functions by dependent pattern-matching and well-founded,
mutual or nested structural recursion and compiles them into core
terms. It automatically derives the clauses equations, the graph of the
function and its associated elimination principle."""
flags: light-uninstall
url {
src: "https://github.com/mattam82/Coq-Equations/archive/v1.0.tar.gz"
checksum: "md5=66ed25baaf876b63e2798228181ada46"
}
</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-equations.1.0 coq.8.10.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1).
The following dependencies couldn't be met:
- coq-equations -> 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-equations.1.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": "e824cca2a8498bf24a1c5d65541fd9c5",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 159,
"avg_line_length": 41.50581395348837,
"alnum_prop": 0.551617873651772,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "34538867c39345065788c402bc5eb19ec12c5b55",
"size": "7164",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.10.1/equations/1.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ObjectBuilder;
using DiExtension.AutoFactory;
using JohnLambe.Util.Reflection;
using JohnLambe.Util.Text;
using DiExtension;
using DiExtension.ConfigInject;
// Integration with Microsoft Unity.
namespace DiExtension.Unity
{
/// <summary>
/// </summary>
// Registers the BuilderStrategy.
public class DiUnityExtension : UnityContainerExtension
{
public DiUnityExtension(ExtendedDiContext diContext)
{
this._diContext = diContext;
}
protected override void Initialize()
{
var strategy = new DiBuilderStrategy(Context,_diContext);
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
// Context.Strategies.Add(strategy, UnityBuildStage.Initialization);
}
protected ExtendedDiContext _diContext;
}
public class DiBuilderStrategy : BuilderStrategyBase
{
public DiBuilderStrategy(ExtensionContext baseContext, ExtendedDiContext diContext)
: base(baseContext)
{
this._diContext = diContext;
}
public override object CustomResolve(IBuilderContext context)
{
var key = context.OriginalBuildKey;
if (key.Name != null && key.Name.StartsWith(_diContext.ConfigNamePrefix)) // named string
{
object value;
// var name = key.Name.RemovePrefix(_diContext.ConfigNamePrefix);
// if (_diContext.ProviderChain.GetValue(name, key.Type, out value))
if (_diContext.GetValue(key.Name, key.Type, out value))
return value;
}
return null;
}
protected ExtendedDiContext _diContext;
}
}
| {
"content_hash": "8e228ade7655c5690cfc904f2e5bc486",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 103,
"avg_line_length": 29.159420289855074,
"alnum_prop": 0.6366799204771372,
"repo_name": "JohnLambe/JLCSUtils",
"id": "4a08dce3d81fc539ab5378c1c1314c9f7e56d017",
"size": "2014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JLCSUtils/DiExtension/Unity/UnityExtension.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2651368"
}
],
"symlink_target": ""
} |
package org.pentaho.di.trans.steps.orabulkloader;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.injection.AfterInjection;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.ProvidesDatabaseConnectionInformation;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.injection.Injection;
import org.pentaho.di.core.injection.InjectionSupported;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.shared.SharedObjectInterface;
import org.pentaho.di.trans.DatabaseImpact;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
import org.pentaho.di.core.annotations.Step;
/**
* Created on 20-feb-2007
*
* @author Sven Boden
*/
@Step( id = "OraBulkLoader", name = "BaseStep.TypeLongDesc.OraBulkLoader",
description = "BaseStep.TypeTooltipDesc.OraBulkLoader",
categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Bulk",
image = "BLKO.svg",
documentationUrl = "http://wiki.pentaho.com/display/EAI/Oracle+Bulk+Loader",
i18nPackageName = "org.pentaho.di.trans.steps.orabulkloader.OraBulkLoaderMeta" )
@InjectionSupported( localizationPrefix = "OraBulkLoader.Injection.", groups = { "FIELDS", "DATABASE_FIELDS" } )
public class OraBulkLoaderMeta extends BaseStepMeta implements StepMetaInterface,
ProvidesDatabaseConnectionInformation {
private static Class<?> PKG = OraBulkLoaderMeta.class; // for i18n purposes, needed by Translator2!!
private static int DEFAULT_COMMIT_SIZE = 100000; // The bigger the better for Oracle
private static int DEFAULT_BIND_SIZE = 0;
private static int DEFAULT_READ_SIZE = 0;
private static int DEFAULT_MAX_ERRORS = 50;
/** database connection */
private DatabaseMeta databaseMeta;
private List<? extends SharedObjectInterface> databases;
/** what's the schema for the target? */
@Injection( name = "SCHEMA_NAME", group = "FIELDS" )
private String schemaName;
/** what's the table for the target? */
@Injection( name = "TABLE_NAME", group = "FIELDS" )
private String tableName;
/** Path to the sqlldr utility */
@Injection( name = "SQLLDR_PATH", group = "FIELDS" )
private String sqlldr;
/** Path to the control file */
@Injection( name = "CONTROL_FILE", group = "FIELDS" )
private String controlFile;
/** Path to the data file */
@Injection( name = "DATA_FILE", group = "FIELDS" )
private String dataFile;
/** Path to the log file */
@Injection( name = "LOG_FILE", group = "FIELDS" )
private String logFile;
/** Path to the bad file */
@Injection( name = "BAD_FILE", group = "FIELDS" )
private String badFile;
/** Path to the discard file */
@Injection( name = "DISCARD_FILE", group = "FIELDS" )
private String discardFile;
/** Field value to dateMask after lookup */
@Injection( name = "FIELD_TABLE", group = "DATABASE_FIELDS" )
private String[] fieldTable;
/** Field name in the stream */
@Injection( name = "FIELD_STREAM", group = "DATABASE_FIELDS" )
private String[] fieldStream;
/** boolean indicating if field needs to be updated */
@Injection( name = "FIELD_DATEMASK", group = "DATABASE_FIELDS" )
private String[] dateMask;
/** Commit size (ROWS) */
@Injection( name = "COMMIT_SIZE", group = "FIELDS" )
private String commitSize;
/** bindsize */
@Injection( name = "BIND_SIZE", group = "FIELDS" )
private String bindSize;
/** readsize */
@Injection( name = "READ_SIZE", group = "FIELDS" )
private String readSize;
/** maximum errors */
@Injection( name = "MAX_ERRORS", group = "FIELDS" )
private String maxErrors;
/** Load method */
@Injection( name = "LOAD_METHOD", group = "FIELDS" )
private String loadMethod;
/** Load action */
@Injection( name = "LOAD_ACTION", group = "FIELDS" )
private String loadAction;
/** Encoding to use */
@Injection( name = "ENCODING", group = "FIELDS" )
private String encoding;
/** Character set name used for Oracle */
@Injection( name = "ORACLE_CHARSET_NAME", group = "FIELDS" )
private String characterSetName;
/** Direct Path? */
@Injection( name = "DIRECT_PATH", group = "FIELDS" )
private boolean directPath;
/** Erase files after use */
@Injection( name = "ERASE_FILES", group = "FIELDS" )
private boolean eraseFiles;
/** Database name override */
@Injection( name = "DB_NAME_OVERRIDE", group = "FIELDS" )
private String dbNameOverride;
/** Fails when sqlldr returns a warning **/
@Injection( name = "FAIL_ON_WARNING", group = "FIELDS" )
private boolean failOnWarning;
/** Fails when sqlldr returns anything else than a warning or OK **/
@Injection( name = "FAIL_ON_ERROR", group = "FIELDS" )
private boolean failOnError;
/** allow Oracle to load data in parallel **/
@Injection( name = "PARALLEL", group = "FIELDS" )
private boolean parallel;
/** If not empty, use this record terminator instead of default one **/
@Injection( name = "RECORD_TERMINATOR", group = "FIELDS" )
private String altRecordTerm;
@Injection( name = "CONNECTION_NAME" )
public void setConnection( String connectionName ) {
databaseMeta = DatabaseMeta.findDatabase( databases, connectionName );
}
/*
* Do not translate following values!!! They are will end up in the job export.
*/
public static final String ACTION_APPEND = "APPEND";
public static final String ACTION_INSERT = "INSERT";
public static final String ACTION_REPLACE = "REPLACE";
public static final String ACTION_TRUNCATE = "TRUNCATE";
/*
* Do not translate following values!!! They are will end up in the job export.
*/
public static final String METHOD_AUTO_CONCURRENT = "AUTO_CONCURRENT";
public static final String METHOD_AUTO_END = "AUTO_END";
public static final String METHOD_MANUAL = "MANUAL";
/*
* Do not translate following values!!! They are will end up in the job export.
*/
public static final String DATE_MASK_DATE = "DATE";
public static final String DATE_MASK_DATETIME = "DATETIME";
public OraBulkLoaderMeta() {
super();
}
public int getCommitSizeAsInt( VariableSpace varSpace ) {
try {
return Integer.valueOf( varSpace.environmentSubstitute( getCommitSize() ) );
} catch ( NumberFormatException ex ) {
return DEFAULT_COMMIT_SIZE;
}
}
/**
* @return Returns the commitSize.
*/
public String getCommitSize() {
return commitSize;
}
/**
* @param commitSize
* The commitSize to set.
*/
public void setCommitSize( String commitSize ) {
this.commitSize = commitSize;
}
/**
* @return Returns the database.
*/
public DatabaseMeta getDatabaseMeta() {
return databaseMeta;
}
/**
* @param database
* The database to set.
*/
public void setDatabaseMeta( DatabaseMeta database ) {
this.databaseMeta = database;
}
/**
* @return Returns the tableName.
*/
public String getTableName() {
return tableName;
}
/**
* @param tableName
* The tableName to set.
*/
public void setTableName( String tableName ) {
this.tableName = tableName;
}
public String getSqlldr() {
return sqlldr;
}
public void setSqlldr( String sqlldr ) {
this.sqlldr = sqlldr;
}
/**
* @return Returns the fieldTable.
*/
public String[] getFieldTable() {
return fieldTable;
}
/**
* @param updateLookup
* The fieldTable to set.
*/
public void setFieldTable( String[] updateLookup ) {
this.fieldTable = updateLookup;
}
/**
* @return Returns the fieldStream.
*/
public String[] getFieldStream() {
return fieldStream;
}
/**
* @param updateStream
* The fieldStream to set.
*/
public void setFieldStream( String[] updateStream ) {
this.fieldStream = updateStream;
}
public String[] getDateMask() {
return dateMask;
}
public void setDateMask( String[] dateMask ) {
this.dateMask = dateMask;
}
public boolean isFailOnWarning() {
return failOnWarning;
}
public void setFailOnWarning( boolean failOnWarning ) {
this.failOnWarning = failOnWarning;
}
public boolean isFailOnError() {
return failOnError;
}
public void setFailOnError( boolean failOnError ) {
this.failOnError = failOnError;
}
public String getCharacterSetName() {
return characterSetName;
}
public void setCharacterSetName( String characterSetName ) {
this.characterSetName = characterSetName;
}
public String getAltRecordTerm() {
return altRecordTerm;
}
public void setAltRecordTerm( String altRecordTerm ) {
this.altRecordTerm = altRecordTerm;
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode, databases );
}
public void allocate( int nrvalues ) {
fieldTable = new String[nrvalues];
fieldStream = new String[nrvalues];
dateMask = new String[nrvalues];
}
public Object clone() {
OraBulkLoaderMeta retval = (OraBulkLoaderMeta) super.clone();
int nrvalues = fieldTable.length;
retval.allocate( nrvalues );
System.arraycopy( fieldTable, 0, retval.fieldTable, 0, nrvalues );
System.arraycopy( fieldStream, 0, retval.fieldStream, 0, nrvalues );
System.arraycopy( dateMask, 0, retval.dateMask, 0, nrvalues );
return retval;
}
private void readData( Node stepnode, List<? extends SharedObjectInterface> databases ) throws KettleXMLException {
try {
// String csize, bsize, rsize, serror;
// int nrvalues;
this.databases = databases;
String con = XMLHandler.getTagValue( stepnode, "connection" );
databaseMeta = DatabaseMeta.findDatabase( databases, con );
commitSize = XMLHandler.getTagValue( stepnode, "commit" );
if ( Utils.isEmpty( commitSize ) ) {
commitSize = Integer.toString( DEFAULT_COMMIT_SIZE );
}
bindSize = XMLHandler.getTagValue( stepnode, "bind_size" );
if ( Utils.isEmpty( bindSize ) ) {
bindSize = Integer.toString( DEFAULT_BIND_SIZE );
}
readSize = XMLHandler.getTagValue( stepnode, "read_size" );
if ( Utils.isEmpty( readSize ) ) {
readSize = Integer.toString( DEFAULT_READ_SIZE );
}
maxErrors = XMLHandler.getTagValue( stepnode, "errors" );
if ( Utils.isEmpty( maxErrors ) ) {
maxErrors = Integer.toString( DEFAULT_MAX_ERRORS );
}
schemaName = XMLHandler.getTagValue( stepnode, "schema" );
tableName = XMLHandler.getTagValue( stepnode, "table" );
loadMethod = XMLHandler.getTagValue( stepnode, "load_method" );
loadAction = XMLHandler.getTagValue( stepnode, "load_action" );
sqlldr = XMLHandler.getTagValue( stepnode, "sqlldr" );
controlFile = XMLHandler.getTagValue( stepnode, "control_file" );
dataFile = XMLHandler.getTagValue( stepnode, "data_file" );
logFile = XMLHandler.getTagValue( stepnode, "log_file" );
badFile = XMLHandler.getTagValue( stepnode, "bad_file" );
discardFile = XMLHandler.getTagValue( stepnode, "discard_file" );
directPath = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "direct_path" ) );
eraseFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "erase_files" ) );
encoding = XMLHandler.getTagValue( stepnode, "encoding" );
dbNameOverride = XMLHandler.getTagValue( stepnode, "dbname_override" );
characterSetName = XMLHandler.getTagValue( stepnode, "character_set" );
failOnWarning = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "fail_on_warning" ) );
failOnError = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "fail_on_error" ) );
parallel = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "parallel" ) );
altRecordTerm = XMLHandler.getTagValue( stepnode, "alt_rec_term" );
int nrvalues = XMLHandler.countNodes( stepnode, "mapping" );
allocate( nrvalues );
for ( int i = 0; i < nrvalues; i++ ) {
Node vnode = XMLHandler.getSubNodeByNr( stepnode, "mapping", i );
fieldTable[i] = XMLHandler.getTagValue( vnode, "stream_name" );
fieldStream[i] = XMLHandler.getTagValue( vnode, "field_name" );
if ( fieldStream[i] == null ) {
fieldStream[i] = fieldTable[i]; // default: the same name!
}
String locDateMask = XMLHandler.getTagValue( vnode, "date_mask" );
if ( locDateMask == null ) {
dateMask[i] = "";
} else {
if ( OraBulkLoaderMeta.DATE_MASK_DATE.equals( locDateMask )
|| OraBulkLoaderMeta.DATE_MASK_DATETIME.equals( locDateMask ) ) {
dateMask[i] = locDateMask;
} else {
dateMask[i] = "";
}
}
}
} catch ( Exception e ) {
throw new KettleXMLException( BaseMessages.getString(
PKG, "OraBulkLoaderMeta.Exception.UnableToReadStepInfoFromXML" ), e );
}
}
public void setDefault() {
fieldTable = null;
databaseMeta = null;
commitSize = Integer.toString( DEFAULT_COMMIT_SIZE );
bindSize = Integer.toString( DEFAULT_BIND_SIZE ); // Use platform default
readSize = Integer.toString( DEFAULT_READ_SIZE ); // Use platform default
maxErrors = Integer.toString( DEFAULT_MAX_ERRORS );
schemaName = "";
tableName = BaseMessages.getString( PKG, "OraBulkLoaderMeta.DefaultTableName" );
loadMethod = METHOD_AUTO_END;
loadAction = ACTION_APPEND;
sqlldr = "sqlldr";
controlFile = "control${Internal.Step.CopyNr}.cfg";
dataFile = "load${Internal.Step.CopyNr}.dat";
logFile = "";
badFile = "";
discardFile = "";
encoding = "";
dbNameOverride = "";
directPath = false;
eraseFiles = true;
characterSetName = "";
failOnWarning = false;
failOnError = false;
parallel = false;
altRecordTerm = "";
int nrvalues = 0;
allocate( nrvalues );
}
public String getXML() {
StringBuilder retval = new StringBuilder( 300 );
retval
.append( " " ).append(
XMLHandler.addTagValue( "connection", databaseMeta == null ? "" : databaseMeta.getName() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "commit", commitSize ) );
retval.append( " " ).append( XMLHandler.addTagValue( "bind_size", bindSize ) );
retval.append( " " ).append( XMLHandler.addTagValue( "read_size", readSize ) );
retval.append( " " ).append( XMLHandler.addTagValue( "errors", maxErrors ) );
retval.append( " " ).append( XMLHandler.addTagValue( "schema", schemaName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "table", tableName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "load_method", loadMethod ) );
retval.append( " " ).append( XMLHandler.addTagValue( "load_action", loadAction ) );
retval.append( " " ).append( XMLHandler.addTagValue( "sqlldr", sqlldr ) );
retval.append( " " ).append( XMLHandler.addTagValue( "control_file", controlFile ) );
retval.append( " " ).append( XMLHandler.addTagValue( "data_file", dataFile ) );
retval.append( " " ).append( XMLHandler.addTagValue( "log_file", logFile ) );
retval.append( " " ).append( XMLHandler.addTagValue( "bad_file", badFile ) );
retval.append( " " ).append( XMLHandler.addTagValue( "discard_file", discardFile ) );
retval.append( " " ).append( XMLHandler.addTagValue( "direct_path", directPath ) );
retval.append( " " ).append( XMLHandler.addTagValue( "erase_files", eraseFiles ) );
retval.append( " " ).append( XMLHandler.addTagValue( "encoding", encoding ) );
retval.append( " " ).append( XMLHandler.addTagValue( "dbname_override", dbNameOverride ) );
retval.append( " " ).append( XMLHandler.addTagValue( "character_set", characterSetName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "fail_on_warning", failOnWarning ) );
retval.append( " " ).append( XMLHandler.addTagValue( "fail_on_error", failOnError ) );
retval.append( " " ).append( XMLHandler.addTagValue( "parallel", parallel ) );
retval.append( " " ).append( XMLHandler.addTagValue( "alt_rec_term", altRecordTerm ) );
for ( int i = 0; i < fieldTable.length; i++ ) {
retval.append( " <mapping>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "stream_name", fieldTable[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "field_name", fieldStream[i] ) );
retval.append( " " ).append( XMLHandler.addTagValue( "date_mask", dateMask[i] ) );
retval.append( " </mapping>" ).append( Const.CR );
}
return retval.toString();
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
try {
this.databases = databases;
databaseMeta = rep.loadDatabaseMetaFromStepAttribute( id_step, "id_connection", databases );
commitSize = rep.getStepAttributeString( id_step, "commit" );
bindSize = rep.getStepAttributeString( id_step, "bind_size" );
readSize = rep.getStepAttributeString( id_step, "read_size" );
maxErrors = rep.getStepAttributeString( id_step, "errors" );
schemaName = rep.getStepAttributeString( id_step, "schema" );
tableName = rep.getStepAttributeString( id_step, "table" );
loadMethod = rep.getStepAttributeString( id_step, "load_method" );
loadAction = rep.getStepAttributeString( id_step, "load_action" );
sqlldr = rep.getStepAttributeString( id_step, "sqlldr" );
controlFile = rep.getStepAttributeString( id_step, "control_file" );
dataFile = rep.getStepAttributeString( id_step, "data_file" );
logFile = rep.getStepAttributeString( id_step, "log_file" );
badFile = rep.getStepAttributeString( id_step, "bad_file" );
discardFile = rep.getStepAttributeString( id_step, "discard_file" );
directPath = rep.getStepAttributeBoolean( id_step, "direct_path" );
eraseFiles = rep.getStepAttributeBoolean( id_step, "erase_files" );
encoding = rep.getStepAttributeString( id_step, "encoding" );
dbNameOverride = rep.getStepAttributeString( id_step, "dbname_override" );
characterSetName = rep.getStepAttributeString( id_step, "character_set" );
failOnWarning = rep.getStepAttributeBoolean( id_step, "fail_on_warning" );
failOnError = rep.getStepAttributeBoolean( id_step, "fail_on_error" );
parallel = rep.getStepAttributeBoolean( id_step, "parallel" );
altRecordTerm = rep.getStepAttributeString( id_step, "alt_rec_term" );
int nrvalues = rep.countNrStepAttributes( id_step, "stream_name" );
allocate( nrvalues );
for ( int i = 0; i < nrvalues; i++ ) {
fieldTable[i] = rep.getStepAttributeString( id_step, i, "stream_name" );
fieldStream[i] = rep.getStepAttributeString( id_step, i, "field_name" );
dateMask[i] = rep.getStepAttributeString( id_step, i, "date_mask" );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "OraBulkLoaderMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository" ), e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
try {
rep.saveDatabaseMetaStepAttribute( id_transformation, id_step, "id_connection", databaseMeta );
rep.saveStepAttribute( id_transformation, id_step, "commit", commitSize );
rep.saveStepAttribute( id_transformation, id_step, "bind_size", bindSize );
rep.saveStepAttribute( id_transformation, id_step, "read_size", readSize );
rep.saveStepAttribute( id_transformation, id_step, "errors", maxErrors );
rep.saveStepAttribute( id_transformation, id_step, "schema", schemaName );
rep.saveStepAttribute( id_transformation, id_step, "table", tableName );
rep.saveStepAttribute( id_transformation, id_step, "load_method", loadMethod );
rep.saveStepAttribute( id_transformation, id_step, "load_action", loadAction );
rep.saveStepAttribute( id_transformation, id_step, "sqlldr", sqlldr );
rep.saveStepAttribute( id_transformation, id_step, "control_file", controlFile );
rep.saveStepAttribute( id_transformation, id_step, "data_file", dataFile );
rep.saveStepAttribute( id_transformation, id_step, "log_file", logFile );
rep.saveStepAttribute( id_transformation, id_step, "bad_file", badFile );
rep.saveStepAttribute( id_transformation, id_step, "discard_file", discardFile );
rep.saveStepAttribute( id_transformation, id_step, "direct_path", directPath );
rep.saveStepAttribute( id_transformation, id_step, "erase_files", eraseFiles );
rep.saveStepAttribute( id_transformation, id_step, "encoding", encoding );
rep.saveStepAttribute( id_transformation, id_step, "dbname_override", dbNameOverride );
rep.saveStepAttribute( id_transformation, id_step, "character_set", characterSetName );
rep.saveStepAttribute( id_transformation, id_step, "fail_on_warning", failOnWarning );
rep.saveStepAttribute( id_transformation, id_step, "fail_on_error", failOnError );
rep.saveStepAttribute( id_transformation, id_step, "parallel", parallel );
rep.saveStepAttribute( id_transformation, id_step, "alt_rec_term", altRecordTerm );
for ( int i = 0; i < fieldTable.length; i++ ) {
rep.saveStepAttribute( id_transformation, id_step, i, "stream_name", fieldTable[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "field_name", fieldStream[i] );
rep.saveStepAttribute( id_transformation, id_step, i, "date_mask", dateMask[i] );
}
// Also, save the step-database relationship!
if ( databaseMeta != null ) {
rep.insertStepDatabase( id_transformation, id_step, databaseMeta.getObjectId() );
}
} catch ( Exception e ) {
throw new KettleException( BaseMessages.getString(
PKG, "OraBulkLoaderMeta.Exception.UnableToSaveStepInfoToRepository" )
+ id_step, e );
}
}
public void getFields( RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
// Default: nothing changes to rowMeta
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
CheckResult cr;
String error_message = "";
if ( databaseMeta != null ) {
Database db = new Database( loggingObject, databaseMeta );
db.shareVariablesWith( transMeta );
try {
db.connect();
if ( !Utils.isEmpty( tableName ) ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.TableNameOK" ), stepMeta );
remarks.add( cr );
boolean first = true;
boolean error_found = false;
error_message = "";
// Check fields in table
String schemaTable =
databaseMeta.getQuotedSchemaTableCombination(
transMeta.environmentSubstitute( schemaName ), transMeta.environmentSubstitute( tableName ) );
RowMetaInterface r = db.getTableFields( schemaTable );
if ( r != null ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.TableExists" ), stepMeta );
remarks.add( cr );
// How about the fields to insert/dateMask in the table?
first = true;
error_found = false;
error_message = "";
for ( int i = 0; i < fieldTable.length; i++ ) {
String field = fieldTable[i];
ValueMetaInterface v = r.searchValueMeta( field );
if ( v == null ) {
if ( first ) {
first = false;
error_message +=
BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.MissingFieldsToLoadInTargetTable" )
+ Const.CR;
}
error_found = true;
error_message += "\t\t" + field + Const.CR;
}
}
if ( error_found ) {
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.AllFieldsFoundInTargetTable" ), stepMeta );
}
remarks.add( cr );
} else {
error_message = BaseMessages.getString( PKG, "OraBulkLoaderMeta.CheckResult.CouldNotReadTableInfo" );
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
}
}
// Look up fields in the input stream <prev>
if ( prev != null && prev.size() > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.StepReceivingDatas", prev.size() + "" ), stepMeta );
remarks.add( cr );
boolean first = true;
error_message = "";
boolean error_found = false;
for ( int i = 0; i < fieldStream.length; i++ ) {
ValueMetaInterface v = prev.searchValueMeta( fieldStream[i] );
if ( v == null ) {
if ( first ) {
first = false;
error_message +=
BaseMessages.getString( PKG, "OraBulkLoaderMeta.CheckResult.MissingFieldsInInput" ) + Const.CR;
}
error_found = true;
error_message += "\t\t" + fieldStream[i] + Const.CR;
}
}
if ( error_found ) {
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.AllFieldsFoundInInput" ), stepMeta );
}
remarks.add( cr );
} else {
error_message =
BaseMessages.getString( PKG, "OraBulkLoaderMeta.CheckResult.MissingFieldsInInput3" ) + Const.CR;
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
}
} catch ( KettleException e ) {
error_message =
BaseMessages.getString( PKG, "OraBulkLoaderMeta.CheckResult.DatabaseErrorOccurred" ) + e.getMessage();
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} finally {
db.disconnect();
}
} else {
error_message = BaseMessages.getString( PKG, "OraBulkLoaderMeta.CheckResult.InvalidConnection" );
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
}
// See if we have input streams leading to this step!
if ( input.length > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.StepReceivingInfoFromOtherSteps" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "OraBulkLoaderMeta.CheckResult.NoInputError" ), stepMeta );
remarks.add( cr );
}
}
public SQLStatement getSQLStatements( TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev,
Repository repository, IMetaStore metaStore ) throws KettleStepException {
SQLStatement retval = new SQLStatement( stepMeta.getName(), databaseMeta, null ); // default: nothing to do!
if ( databaseMeta != null ) {
if ( prev != null && prev.size() > 0 ) {
// Copy the row
RowMetaInterface tableFields = new RowMeta();
// Now change the field names
for ( int i = 0; i < fieldTable.length; i++ ) {
ValueMetaInterface v = prev.searchValueMeta( fieldStream[i] );
if ( v != null ) {
ValueMetaInterface tableField = v.clone();
tableField.setName( fieldTable[i] );
tableFields.addValueMeta( tableField );
} else {
throw new KettleStepException( "Unable to find field [" + fieldStream[i] + "] in the input rows" );
}
}
if ( !Utils.isEmpty( tableName ) ) {
Database db = new Database( loggingObject, databaseMeta );
db.shareVariablesWith( transMeta );
try {
db.connect();
String schemaTable =
databaseMeta.getQuotedSchemaTableCombination(
transMeta.environmentSubstitute( schemaName ), transMeta.environmentSubstitute( tableName ) );
String sql = db.getDDL( schemaTable, tableFields, null, false, null, true );
if ( sql.length() == 0 ) {
retval.setSQL( null );
} else {
retval.setSQL( sql );
}
} catch ( KettleException e ) {
retval.setError( BaseMessages.getString( PKG, "OraBulkLoaderMeta.GetSQL.ErrorOccurred" )
+ e.getMessage() );
}
} else {
retval.setError( BaseMessages.getString( PKG, "OraBulkLoaderMeta.GetSQL.NoTableDefinedOnConnection" ) );
}
} else {
retval.setError( BaseMessages.getString( PKG, "OraBulkLoaderMeta.GetSQL.NotReceivingAnyFields" ) );
}
} else {
retval.setError( BaseMessages.getString( PKG, "OraBulkLoaderMeta.GetSQL.NoConnectionDefined" ) );
}
return retval;
}
public void analyseImpact(List<DatabaseImpact> impact, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, Repository repository,
IMetaStore metaStore ) throws KettleStepException {
if ( prev != null ) {
/* DEBUG CHECK THIS */
// Insert dateMask fields : read/write
for ( int i = 0; i < fieldTable.length; i++ ) {
ValueMetaInterface v = prev.searchValueMeta( fieldStream[i] );
DatabaseImpact ii =
new DatabaseImpact(
DatabaseImpact.TYPE_IMPACT_READ_WRITE, transMeta.getName(), stepMeta.getName(), databaseMeta
.getDatabaseName(), transMeta.environmentSubstitute( tableName ), fieldTable[i],
fieldStream[i], v != null ? v.getOrigin() : "?", "", "Type = " + v.toStringMeta() );
impact.add( ii );
}
}
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr,
TransMeta transMeta, Trans trans ) {
return new OraBulkLoader( stepMeta, stepDataInterface, cnr, transMeta, trans );
}
public StepDataInterface getStepData() {
return new OraBulkLoaderData();
}
public DatabaseMeta[] getUsedDatabaseConnections() {
if ( databaseMeta != null ) {
return new DatabaseMeta[] { databaseMeta };
} else {
return super.getUsedDatabaseConnections();
}
}
/**
* @return Do we want direct path loading.
*/
public boolean isDirectPath() {
return directPath;
}
/**
* @param directPath
* do we want direct path
*/
public void setDirectPath( boolean directPath ) {
this.directPath = directPath;
}
public RowMetaInterface getRequiredFields( VariableSpace space ) throws KettleException {
String realTableName = space.environmentSubstitute( tableName );
String realSchemaName = space.environmentSubstitute( schemaName );
if ( databaseMeta != null ) {
Database db = new Database( loggingObject, databaseMeta );
try {
db.connect();
if ( !Utils.isEmpty( realTableName ) ) {
String schemaTable = databaseMeta.getQuotedSchemaTableCombination( realSchemaName, realTableName );
// Check if this table exists...
if ( db.checkTableExists( schemaTable ) ) {
return db.getTableFields( schemaTable );
} else {
throw new KettleException( BaseMessages.getString( PKG, "OraBulkLoaderMeta.Exception.TableNotFound" ) );
}
} else {
throw new KettleException( BaseMessages.getString( PKG, "OraBulkLoaderMeta.Exception.TableNotSpecified" ) );
}
} catch ( Exception e ) {
throw new KettleException(
BaseMessages.getString( PKG, "OraBulkLoaderMeta.Exception.ErrorGettingFields" ), e );
} finally {
db.disconnect();
}
} else {
throw new KettleException( BaseMessages.getString( PKG, "OraBulkLoaderMeta.Exception.ConnectionNotDefined" ) );
}
}
/**
* @return the schemaName
*/
public String getSchemaName() {
return schemaName;
}
/**
* @param schemaName
* the schemaName to set
*/
public void setSchemaName( String schemaName ) {
this.schemaName = schemaName;
}
public String getBadFile() {
return badFile;
}
public void setBadFile( String badFile ) {
this.badFile = badFile;
}
public String getControlFile() {
return controlFile;
}
public void setControlFile( String controlFile ) {
this.controlFile = controlFile;
}
public String getDataFile() {
return dataFile;
}
public void setDataFile( String dataFile ) {
this.dataFile = dataFile;
}
public String getDiscardFile() {
return discardFile;
}
public void setDiscardFile( String discardFile ) {
this.discardFile = discardFile;
}
public String getLogFile() {
return logFile;
}
public void setLogFile( String logFile ) {
this.logFile = logFile;
}
public void setLoadAction( String action ) {
this.loadAction = action;
}
public String getLoadAction() {
return this.loadAction;
}
public void setLoadMethod( String method ) {
this.loadMethod = method;
}
public String getLoadMethod() {
return this.loadMethod;
}
public String getEncoding() {
return encoding;
}
public void setEncoding( String encoding ) {
this.encoding = encoding;
}
public String getDelimiter() {
return ",";
}
public String getEnclosure() {
return "\"";
}
public boolean isEraseFiles() {
return eraseFiles;
}
public void setEraseFiles( boolean eraseFiles ) {
this.eraseFiles = eraseFiles;
}
public int getBindSizeAsInt( VariableSpace varSpace ) {
try {
return Integer.valueOf( varSpace.environmentSubstitute( getBindSize() ) );
} catch ( NumberFormatException ex ) {
return DEFAULT_BIND_SIZE;
}
}
public String getBindSize() {
return bindSize;
}
public void setBindSize( String bindSize ) {
this.bindSize = bindSize;
}
public int getMaxErrorsAsInt( VariableSpace varSpace ) {
try {
return Integer.valueOf( varSpace.environmentSubstitute( getMaxErrors() ) );
} catch ( NumberFormatException ex ) {
return DEFAULT_MAX_ERRORS;
}
}
public String getMaxErrors() {
return maxErrors;
}
public void setMaxErrors( String maxErrors ) {
this.maxErrors = maxErrors;
}
public int getReadSizeAsInt( VariableSpace varSpace ) {
try {
return Integer.valueOf( varSpace.environmentSubstitute( getReadSize() ) );
} catch ( NumberFormatException ex ) {
return DEFAULT_READ_SIZE;
}
}
public String getReadSize() {
return readSize;
}
public void setReadSize( String readSize ) {
this.readSize = readSize;
}
public String getDbNameOverride() {
return dbNameOverride;
}
public void setDbNameOverride( String dbNameOverride ) {
this.dbNameOverride = dbNameOverride;
}
/**
* @return the parallel
*/
public boolean isParallel() {
return parallel;
}
/**
* @param parallel
* the parallel to set
*/
public void setParallel( boolean parallel ) {
this.parallel = parallel;
}
@Override
public String getMissingDatabaseConnectionInformationMessage() {
// TODO Auto-generated method stub
return null;
}
/**
* If we use injection we can have different arrays lengths.
* We need synchronize them for consistency behavior with UI
*/
@AfterInjection
public void afterInjectionSynchronization() {
if ( fieldTable == null || fieldTable.length == 0 ) {
return;
}
int nrFields = fieldTable.length;
if ( fieldStream.length < nrFields ) {
String[] newFieldStream = new String[ nrFields ];
System.arraycopy( fieldStream, 0, newFieldStream, 0, fieldStream.length );
fieldStream = newFieldStream;
}
for ( int i = 0; i < fieldStream.length; i++ ) {
if ( fieldStream[ i ] == null ) {
fieldStream[ i ] = StringUtils.EMPTY;
}
}
//PDI-16472
if ( dateMask.length < nrFields ) {
String[] newDateMask = new String[ nrFields ];
System.arraycopy( dateMask, 0, newDateMask, 0, dateMask.length );
dateMask = newDateMask;
}
}
}
| {
"content_hash": "a2b6dcc5a78ecc9d52e09b4ec1cf016e",
"timestamp": "",
"source": "github",
"line_count": 1077,
"max_line_length": 134,
"avg_line_length": 35.97493036211699,
"alnum_prop": 0.6527810040005162,
"repo_name": "rmansoor/pentaho-kettle",
"id": "fc45d02f31e80e155fb9a07688924d7a42ac748f",
"size": "39657",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "plugins/oracle-bulk-loader/impl/src/main/java/org/pentaho/di/trans/steps/orabulkloader/OraBulkLoaderMeta.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "45618"
},
{
"name": "CSS",
"bytes": "37792"
},
{
"name": "GAP",
"bytes": "4005"
},
{
"name": "HTML",
"bytes": "41671"
},
{
"name": "Java",
"bytes": "45347869"
},
{
"name": "JavaScript",
"bytes": "511961"
},
{
"name": "Shell",
"bytes": "48803"
}
],
"symlink_target": ""
} |
import AWS from 'aws-sdk';
import url from 'url';
import fs from 'fs-extra';
import debug from 'debug';
const log = debug('google-drive-sync:file-system');
export default class FileSystem {
constructor(opts) {
if (opts.s3) {
const s3 = url.parse(opts.s3, true);
const [accessKeyId, secretAccessKey] = s3.auth.split(':', 2);
this.bucket = s3.pathname.replace(/^\//, '');
if (s3.query.log && s3.query.log !== 'false') {
AWS.config.logger = { log };
}
const s3Opts = {
endpoint: `${s3.protocol}//${s3.hostname}`,
bucket: this.bucket,
httpOptions: {
proxy: s3.query['http.proxy'],
connectTimeout: s3.query['http.connectTimeout']
? +s3.query['http.connectTimeout']
: undefined,
timeout: s3.query['http.timeout']
? +s3.query['http.timeout']
: undefined,
},
apiVersion: s3.query.apiVersion,
signatureVersion: s3.query.signatureVersion,
};
log(s3Opts);
this.s3 = new AWS.S3({ ...s3Opts, accessKeyId, secretAccessKey });
}
}
read(filePath, encoding = 'utf8') {
if (this.s3) {
return this.s3
.getObject({ Bucket: this.bucket, Key: filePath })
.promise();
} else {
return fs.readFile(filePath, encoding);
}
}
write(filePath, data, { mimeType = null } = {}) {
if (this.s3) {
return this.s3
.upload(
{
Bucket: this.bucket,
Key: filePath,
Body: data,
ContentType: mimeType,
},
{ queueSize: 1 }
)
.promise();
} else {
return fs.outputFile(filePath, data);
}
}
}
| {
"content_hash": "3b0d00f26f98fdf01f21a707e056c8a6",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 78,
"avg_line_length": 30.492753623188406,
"alnum_prop": 0.436787072243346,
"repo_name": "jarib/google-drive-sync",
"id": "22e0d2f8f30fc1bb22c246abf32fdf23fd49bdde",
"size": "2104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/file-system.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "47367"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ky" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Plankton</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The Plankton developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Жаң даректи жасоо</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your Plankton addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>Ө&чүрүү</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Дарек</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(аты жок)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Plankton will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Транзакциялар</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show information about Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>Билдирүүнү &текшерүү...</translation>
</message>
<message>
<location line="-202"/>
<source>Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Капчык</translation>
</message>
<message>
<location line="+180"/>
<source>&About Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Жардам</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>Plankton client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to Plankton network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About Plankton card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Plankton card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Жаңыланган</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Plankton address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. Plankton can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Дарек</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(аты жок)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Дарек</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Plankton address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>Plankton-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Plankton after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Plankton on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Тармак</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Plankton client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Plankton network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Порт:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Терезе</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Plankton.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Plankton addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Жарайт</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Жокко чыгаруу</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>жарыяланбаган</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Plankton.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Plankton network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Капчык</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>синхрондоштурулган эмес</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Ачуу</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Plankton-Qt help message to get a list with possible Plankton command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Консоль</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Plankton - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Plankton Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Plankton debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Консолду тазалоо</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Plankton RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 FOOD</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Бардыгын тазалоо</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>123.456 FOOD</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Жөнөтүү</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a Plankton address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(аты жок)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Даректи алмашуу буферинен коюу</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Plankton address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Даректи алмашуу буферинен коюу</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Бардыгын тазалоо</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Plankton address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Plankton address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Plankton signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/тармакта эмес</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Билдирүү</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Дарек</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Дарек</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>Plankton version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or Planktond</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: Plankton.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: Planktond.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Plankton will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=Planktonrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Plankton Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. Plankton is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Plankton</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Plankton to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. Plankton is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Ката</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | {
"content_hash": "466cbcb41a3ce99c33c884b186944d7d",
"timestamp": "",
"source": "github",
"line_count": 3285,
"max_line_length": 395,
"avg_line_length": 32.70654490106545,
"alnum_prop": 0.583296879217431,
"repo_name": "plankton-food/Plankton",
"id": "3b6b2246d02bf1a05ee32a2cac4f057bd16813e5",
"size": "107797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_ky.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "3074320"
},
{
"name": "C++",
"bytes": "2480414"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "14785"
},
{
"name": "Objective-C++",
"bytes": "3537"
},
{
"name": "Python",
"bytes": "11646"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "TypeScript",
"bytes": "7751348"
}
],
"symlink_target": ""
} |
package tuffy.db;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.postgresql.PGConnection;
import tuffy.mln.Predicate;
import tuffy.util.Config;
import tuffy.util.ExceptionMan;
import tuffy.util.FileMan;
import tuffy.util.StringMan;
import tuffy.util.Timer;
import tuffy.util.UIMan;
/**
* Interface with the RDBMS. Currently only supports PostgreSQL (8.4 or later).
*/
public class RDB {
private int lastUpdateRowCount = -1;
private boolean savedAutoCommit = false;
public static final long constantIdBase = 1 << 29;
static ArrayList<RDB> allRDBs = new ArrayList<RDB>();
static int currentDBCounter = 0;
public Connection con = null;
private Statement currentlyRunningQuery = null;
public String db;
public String user;
public String password;
public String schema = null;
public static HashSet<RDB> historyInstances = new HashSet<RDB>();
/**
* Disable auto-commit so that JDBC won't fetch all query results at once.
* Call this before retrieving data from a huge table.
* After the big query is done, call {@link RDB#restoreAutoCommitState()} to
* restore the initial auto-commit state.
*
* @see RDB#restoreAutoCommitState()
* @see <a href='http://jdbc.postgresql.org/documentation/84/query.html#query-with-cursor'>
* PostgreSQL's JDBC doc</a>
*/
public void disableAutoCommitForNow(){
try {
savedAutoCommit = con.getAutoCommit();
con.setAutoCommit(false);
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Register a stored procedure to explain SQL queries.
* @param pname name of the stored procedure
*/
public void regExplainProc(String pname){
String sql = "create or replace function " + pname +
"(q text) returns setof text as $$\r\n" +
"declare r record;\r\n" +
"begin\r\n" +
" for r in execute 'explain ' || q loop\r\n" +
" return next r.\"QUERY PLAN\";\r\n" +
" end loop;\r\n" +
"end$$ language plpgsql";
update(sql);
}
public void estimateQuery(String sql, boolean analyze){
RDB db = this;
db.estimateCost(sql);
UIMan.verbose(2, "ESTIMATED cost = " + db.estimatedCost + " ; rows = " + db.estimatedRows);
if(analyze){
Timer.start("cqmat");
db.update(sql);
double rtime = Timer.elapsedMilliSeconds("cqmat");
UIMan.verbose(2, Timer.elapsed("cqmat"));
UIMan.verbose(2, "COST-RATIO = " + (db.estimatedCost/rtime) + " ; ROW-RATIO = " +
((double)db.estimatedRows/db.getLastUpdateRowCount()));
}
}
public double estimatedCost = 0;
public double estimatedRows = 0;
public String estimateCost(String sql){
String plan = explain(sql);
if(plan == null){
estimatedCost = Double.MAX_VALUE;
estimatedRows = Double.MAX_VALUE;
return null;
}
String rep = plan.split("\n")[0];
String[] parts = rep.split(" ");
for(String p : parts){
if(p.startsWith("(cost=")){
int i = p.indexOf("..") + 2;
estimatedCost = Double.parseDouble(p.substring(i));
}else if(p.startsWith("rows=")){
estimatedRows = Double.parseDouble(p.substring(5));
}
}
return rep;
}
/**
* Explain a SQL query with an execution plan.
* @param sql
*/
public String explain(String sql){
try {
//this.execute("EXPLAIN " + sql);
//this.regExplainProc("expl");
PreparedStatement ps = getPrepareStatement(
"SELECT * FROM expl(cast(? as text))");
ps.setString(1, sql);
//System.out.println(sql);
ResultSet rs = ps.executeQuery();
StringBuilder sb = new StringBuilder();
while(rs.next()){
sb.append(rs.getString(1) + "\n");
}
return sb.toString();
} catch (SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
// dirty
try {
this.con.close();
this.con = DriverManager.getConnection(db, user, password);
if(this.schema != null){
this.execute("SET SEARCH_PATH TO " + schema);
}
//return this.explain(sql);
return null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
}
public void createTempTableIntList(String rel, Collection<Integer> vals){
dropTable(rel);
String sql = "CREATE TABLE " + rel + "(id INT)";
update(sql);
try {
String loadingFile = Config.dir_working + "/createTempTableIntList";
BufferedWriter bw = new BufferedWriter(new FileWriter(
Config.dir_working + "/createTempTableIntList"));
for(int pid : vals){
bw.write(pid + "\n");
}
bw.close();
ArrayList<String> cols = new ArrayList<String>();
cols.add("id");
FileInputStream in = new FileInputStream(loadingFile);
PGConnection con = (PGConnection) this.getConnection();
sql = "COPY " + rel +
StringMan.commaListParen(cols) + " FROM STDIN CSV";
con.getCopyAPI().copyIn(sql, in);
in.close();
this.analyze(rel);
FileMan.removeFile(loadingFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Restore the auto-commit state saved by {@link RDB#disableAutoCommitForNow()}.
*
* @see RDB#disableAutoCommitForNow()
*/
public void restoreAutoCommitState(){
try {
con.setAutoCommit(savedAutoCommit);
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Return the number of affected tuples from last update.
*/
public int getLastUpdateRowCount() {
return lastUpdateRowCount;
}
/**
* Return the database connection.
*/
public Connection getConnection(){
return con;
}
/**
* Dump a MAP world produced by MAP inference.
*
* @param fout path of output file
*/
public void dumpTableToFile(Predicate p, String fout) {
HashMap<Long,String> cmap = this.loadIdSymbolMapFromTable();
try {
BufferedWriter bufferedWriter = null;
bufferedWriter = new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(fout),"UTF8"));
String sql = "SELECT * FROM " + p.getRelName() +
" WHERE truth OR itruth " +
" ORDER BY " + StringMan.commaList(p.getArgs());
ResultSet rs = this.query(sql);
while(rs.next()) {
String line = p.getName() + "(";
ArrayList<String> cs = new ArrayList<String>();
for(String a : p.getArgs()) {
long c = rs.getLong(a);
cs.add("\"" + StringMan.escapeJavaString(cmap.get(c)) + "\"");
}
line += StringMan.commaList(cs) + ")";
bufferedWriter.append(line + "\n");
}
rs.close();
bufferedWriter.close();
} catch (Exception e) {
ExceptionMan.handle(e);
}
}
/**
* Attempt to establish the connection as specified in the
* (deault) configuration.
*/
public static RDB getRDBbyConfig() {
//TODO: why need so large
//int nConnections = 1;
//TODO: change nCores to # connect
//if(allRDBs.size() < nConnections){
RDB tmp = new RDB(Config.db_url,
Config.db_username, Config.db_password);
tmp.db = Config.db_url;
tmp.user = Config.db_username;
tmp.password = Config.db_password;
historyInstances.add(tmp);
// allRDBs.add(tmp);
// currentDBCounter = allRDBs.size() - 1;
//}else{
// currentDBCounter = (currentDBCounter+1) % nConnections;
//}
//return allRDBs.get(currentDBCounter);
return tmp;
}
public static RDB getRDBbyConfig(String schema) {
RDB tmp = new RDB(Config.db_url,
Config.db_username, Config.db_password);
tmp.db = Config.db_url;
tmp.user = Config.db_username;
tmp.password = Config.db_password;
tmp.schema = schema;
tmp.execute("SET search_path = " + schema);
historyInstances.add(tmp);
return tmp;
}
/**
* Register the JDBC driver.
*/
private void registerDrivers(){
/*
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.err.println(e.getMessage());
System.err.println("Failed to load PostgreSQL JDBC driver.");
}
*/
}
private void dumpSQL(String sql){
UIMan.println("-----BEGIN:SQL-----");
UIMan.println(sql);
UIMan.println("-----END:SQL-----");
}
/**
* Execute an update SQL statement.
*
* @return the number of tuples affected
*/
public int update(String sql){
if(Config.exiting_mode) ExceptionMan.die("");
try {
Statement stmt = con.createStatement();
currentlyRunningQuery = stmt;
lastUpdateRowCount = stmt.executeUpdate(sql);
stmt.close();
currentlyRunningQuery = null;
} catch (SQLException e) {
UIMan.error(sql);
ExceptionMan.handle(e);
return 0;
}
return lastUpdateRowCount;
}
/**
* Execute a SQL statement (query/update).
*/
public void execute(String sql) {
//if(sql.contains("DELETE") || sql.contains("delete")) System.out.println(sql);
if(Config.exiting_mode) ExceptionMan.die("");
try {
Statement stmt = con.createStatement();
currentlyRunningQuery = stmt;
stmt.execute(sql);
stmt.close();
currentlyRunningQuery = null;
} catch (SQLException e) {
dumpSQL(sql);
e.printStackTrace();
ExceptionMan.handle(e);
}
}
public void executeWhatever(String sql) {
try {
Statement stmt = con.createStatement();
stmt.execute(sql);
stmt.close();
} catch (SQLException e) {
dumpSQL(sql);
}
}
private void executeRaw(String sql) throws SQLException{
Statement stmt = con.createStatement();
stmt.execute(sql);
stmt.close();
}
private void updateRaw(String sql) throws SQLException{
this.commit();
this.setAutoCommit(true);
Statement stmt = con.createStatement();
currentlyRunningQuery = stmt;
stmt.executeUpdate(sql);
stmt.close();
currentlyRunningQuery = null;
}
/**
* Execute a set of update SQL statements as a batch.
*
* @return true on success
*/
public boolean updateBatch(ArrayList<String> sqls) {
try {
Statement st = con.createStatement();
currentlyRunningQuery = st;
for(String s : sqls) {
st.addBatch(s);
}
st.executeBatch();
st.close();
currentlyRunningQuery = null;
return true;
} catch (SQLException e) {
ExceptionMan.handle(e);
}
return false;
}
/**
* Execute a SQL query.
*
* @param sql the SQL statement
* @return the result set. remembe to close it afterwards.
*/
public ResultSet query(String sql){
if(Config.exiting_mode) ExceptionMan.die("");
try {
Statement stmt = con.createStatement(ResultSet.HOLD_CURSORS_OVER_COMMIT, 1);
currentlyRunningQuery = stmt;
stmt.setFetchSize(100000);
ResultSet rs = stmt.executeQuery(sql);
currentlyRunningQuery = null;
return rs;
} catch (SQLException e) {
UIMan.error(sql);
ExceptionMan.handle(e);
return null;
}
}
/**
* Load the symbol table into a hash table mapping
* symbols to their IDs.
*
* @see Config#relConstants
*/
public ConcurrentHashMap<String, Integer> loadSymbolIdMapFromTable() {
ConcurrentHashMap<String, Integer> map =
new ConcurrentHashMap<String, Integer>();
String rel = Config.relConstants;
String sql = "SELECT * FROM " + rel;
ResultSet rs = query(sql);
try {
while(rs.next()) {
String word = rs.getString("string");
int id = rs.getInt("id");
map.put(word, id);
}
rs.close();
} catch (SQLException e) {
ExceptionMan.handle(e);
}
return map;
}
/**
* Load the symbol table into a hash table mapping
* symbol IDs to the original symbols.
*
* @see Config#relConstants
*/
public HashMap<Long,String> loadIdSymbolMapFromTable() {
HashMap<Long,String> map =
new HashMap<Long,String>();
String sql = "SELECT * FROM " + Config.relConstants;
ResultSet rs = query(sql);
try {
while(rs.next()) {
String word = rs.getString("string");
long id = rs.getLong("id");
map.put(id, word);
}
rs.close();
} catch (SQLException e) {
ExceptionMan.handle(e);
}
return map;
}
/**
* Store the symbol-ID mapping into a symbol table.
*
* @param mapConstantID the symbol-ID mapping
* @see Config#relConstants
*/
public void createConstantTable(Map<String, Integer> mapConstantID, String rel) {
dropTable(rel);
String sql = "CREATE TABLE " + rel +
"(id bigint, string TEXT)";
if (rel.equals(Config.relConstants)) {
sql = "CREATE TABLE " + rel +
"(id bigint PRIMARY KEY, string TEXT)";
}
//if(Config.using_greenplum){
// sql += " DISTRIBUTED BY (string)";
//}
update(sql);
BufferedWriter writer = null;
File loadingFile = new File(Config.getLoadingDir(), "loading_symbols_");
try {
writer = new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(loadingFile),"UTF8"));
} catch (Exception e) {
ExceptionMan.handle(e);
}
try {
for(Map.Entry<String, Integer> pair : mapConstantID.entrySet()) {
writer.append(pair.getValue().toString());
writer.append("\t");
writer.append(StringMan.escapeJavaString(pair.getKey()));
writer.append("\n");
}
writer.close();
FileInputStream in = new FileInputStream(loadingFile);
PGConnection con = (PGConnection)this.getConnection();
sql = "COPY " + rel + " FROM STDIN ";
con.getCopyAPI().copyIn(sql, in);
in.close();
//sql = "CREATE INDEX " + rel + "_constants_index_id ON " + rel + "(id)";
//this.execute(sql);
}catch(Exception e) {
ExceptionMan.handle(e);
}
}
public void insertConstantTable(Map<String, Integer> mapConstantID) {
String rel = Config.relConstants;
String sql;
BufferedWriter writer = null;
File loadingFile = new File(Config.getLoadingDir(), "loading_symbols_");
try {
writer = new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(loadingFile),"UTF8"));
} catch (Exception e) {
ExceptionMan.handle(e);
}
try {
for(Map.Entry<String, Integer> pair : mapConstantID.entrySet()) {
writer.append(pair.getValue() + "\t" +
StringMan.escapeJavaString(pair.getKey()) + "\n");
}
writer.close();
FileInputStream in = new FileInputStream(loadingFile);
PGConnection con = (PGConnection)this.getConnection();
sql = "COPY " + rel + " FROM STDIN ";
con.getCopyAPI().copyIn(sql, in);
in.close();
//sql = "CREATE INDEX constants_index_id ON " + rel + "(id)";
//this.execute(sql);
}catch(Exception e) {
ExceptionMan.handle(e);
}
}
/**
* Create a table to store a set of integers
* @param rel the name of the table
* @param set the set of integers
*/
public void createSetTable(String rel, HashSet<Integer> set){
dropTable(rel);
String sql = "CREATE TEMPORARY TABLE " + rel +
"(id INT)";
update(sql);
PreparedStatement ps = getPrepareStatement(
"INSERT INTO " + rel + " VALUES(?)");
try {
for(int pid : set){
ps.setInt(1, pid);
ps.addBatch();
}
ps.executeBatch();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Try to drop a table; remain silent if the specified
* table doesn't exist.
*/
public void dropTable(String rel){
// System.out.println("####### drop " + rel);
dropStuff("TABLE", rel);
}
/**
* Try to drop a schema; remain silent if the specified
* schema doesn't exist.
*/
public boolean dropSchema(String sch){
return dropStuff("SCHEMA", sch + "");
}
/**
* Try to drop a sequence; remain silent if the specified
* sequence doesn't exist.
*/
public void dropSequence(String seq){
dropStuff("SEQUENCE", seq);
}
public void dropView(String view){
dropStuff("VIEW", view);
}
private boolean dropStuff(String type, String obj){
String sql = "DROP " + type + " IF EXISTS " + obj + " CASCADE";
String sql2 = "DROP " + type + " IF EXISTS " + obj + "";
try {
updateRaw(sql);
return true;
} catch (SQLException e) {
// the target was not found; do nothing
try{
updateRaw(sql2);
return true;
}catch(Exception e2){
return false;
}
}
}
/**
* Return a prepared statement of the given SQL statement.
* A SQL statement with or without parameters can be pre-compiled
* and stored in a PreparedStatement object. This object can then
* be used to efficiently execute this statement multiple times.
*/
public PreparedStatement getPrepareStatement(String sql) {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ps.setFetchSize(100000);
} catch (SQLException e) {
ExceptionMan.handle(e);
}
return ps;
}
public boolean schemaExists(String name){
ResultSet rs = this.query("SELECT * FROM information_schema.schemata WHERE schema_name = '" + name.toLowerCase() + "'");
try {
if(rs.next()){
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean tableExists(String tableName) {
String sql = "SELECT * FROM " + tableName + " LIMIT 1";
try {
executeRaw(sql);
return true;
} catch (SQLException e){
return false;
}
}
public boolean tableExists(String schemaName, String tableName){
String sql = "SELECT * FROM " + schemaName + "." + tableName + " LIMIT 1";
try {
executeRaw(sql);
return true;
} catch (SQLException e){
return false;
}
}
/**
* Reset the database schema that serves as Tuffy's workspace.
*
* @see Config#db_schema
*/
public void resetSchema(String schema) {
UIMan.verbose(3, "### Checking existence of " + schema);
if (schemaExists(schema)) {
execute("SET search_path TO " + schema);
UIMan.verbose(3, "### Reusing schema " + schema);
this.schema = schema;
} else {
UIMan.verbose(3, "### Creating schema " + schema);
String sql = "CREATE SCHEMA " + schema + " AUTHORIZATION "
+ Config.db_username;
update(sql);
sql = "GRANT ALL ON SCHEMA " + schema + " TO " + Config.db_username;
update(sql);
execute("SET search_path TO " + schema);
execute("DROP TYPE IF EXISTS typeOfIntArray CASCADE");
execute("CREATE TYPE typeOfIntArray AS ( a INT[] );");
execute(SQLMan.sqlTypeConversions);
execute(SQLMan.sqlIntArrayFuncReg);
execute(SQLMan.sqlRandomAgg);
execute(SQLMan.sqlFuncMisc);
regExplainProc("expl");
this.schema = schema;
}
}
/**
* Copy the tuples of a table to another.
* Can be used to check out the content of a temporary table.
*
* @param src name of the source table
* @param dest name the destination table; will be dropped if already exists
*/
public void copyTable(String src, String dest) {
dropTable(dest);
String sql = "CREATE TABLE "+dest+" AS " +
"SELECT * FROM " + src;
try {
updateRaw(sql);
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Commit the previous actions.
* Useless when AutoCommit is on, which is so by default.
*/
public void commit() {
try {
con.commit();
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Specifies a JDBC connection.
*/
public RDB(String url, String user, String password){
UIMan.verbose(1000, "------------------- Open a new DB " + this);
registerDrivers();
try {
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(true);
//execute("SET work_mem = '100MB'");
//execute("SET checkpoint_segments = 30");
//execute("SET temp_buffers = '2000MB'");
//execute("SET maintenance_work_mem = '100MB'");
//execute("SET archive_mode = OFF");
//execute("SET wal_buffers = '50MB'");
//execute("SET shared_buffers = '500MB'");
execute("set client_encoding='utf8'");
/*
if(Config.forceNestedLoop) {
execute("SET enable_bitmapscan = 'off'");
execute("SET enable_hashagg = 'off'");
execute("SET enable_hashjoin = 'off'");
execute("SET enable_indexscan = 'off'");
execute("SET enable_mergejoin = 'off'");
execute("SET enable_sort = 'off'");
execute("SET enable_tidscan = 'off'");
}
if(Config.forceJoinOrder) {
execute("SET join_collapse_limit = '1'");
}
*/
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if(Config.exiting_mode) return;
Config.exiting_mode = true;
UIMan.setSilent(true);
UIMan.setSilentErr(true);
System.out.println("\n!!! Shutting down Tuffy !!!");
if (currentlyRunningQuery != null){
try {
System.out.print("Cacelling currently running DB query...");
currentlyRunningQuery.cancel();
currentlyRunningQuery = null;
System.out.println("Done.");
} catch (SQLException e) {
System.out.println("Failed.");
}
}
System.out.print("Removing temporary dir '" + Config.getWorkingDir() + "'...");
System.out.println(FileMan.removeDirectory(new File(Config.getWorkingDir()))?"OK" : "FAILED");
if(!Config.keep_db_data){
System.out.print("Removing database schema '" + Config.db_schema + "'...");
System.out.println(dropSchema(Config.db_schema)?"OK" : "FAILED");
}else{
System.out.println("Data remains in schema '" + Config.db_schema + "'.");
}
try {
if(con != null && !con.isClosed()) {
con.close();
}
} catch (SQLException e) {
}
}
});
} catch (SQLException e) {
System.err.println("Failed to connect to PostgreSQL!");
System.err.println(e.getMessage());
return;
}
}
/**
* Set auto-commit state of this connection.
*/
public void setAutoCommit(boolean v){
try {
con.setAutoCommit(v);
} catch (SQLException e) {
System.err.println("Failed to set AutoCommit to " + v);
System.err.println(e.getMessage());
}
}
/**
* Read the current value of a sequence.
*
* @param seq the name of the sequence
*/
public int getSequenceCurValue(String seq) {
String s = "SELECT CURRVAL('"+seq+"')";
ResultSet rs = query(s);
if(rs == null) return -1;
try {
if(rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
* Count the tuples in a table.
*/
public long countTuples(String table) {
if(Config.exiting_mode) ExceptionMan.die("");
String s = "SELECT COUNT(*) FROM " + table;
ResultSet rs = query(s);
if(rs == null) ExceptionMan.die("");
try {
if(rs.next()) {
long c = rs.getLong(1);
rs.close();
return c;
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
* Close this connection.
*/
public void close() {
try {
if (con != null) {
UIMan.verbose(1000, "------------------- Close a DB " + this);
con.close();
con = null;
}
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Analyze a specific table.
*
* @param rel name of the table
*
* @see <a hef='http://www.postgresql.org/docs/current/static/sql-analyze.html'>
* the PostgreSQL doc</a>
*/
public void analyze(String rel) {
String sql = "ANALYZE " + rel;
this.update(sql);
}
/**
* Vacuum a specific table.
*
* @param rel name of the table
*
* @see <a hef='http://www.postgresql.org/docs/current/static/sql-vacuum.html'>
* the PostgreSQL doc</a>
*/
public void vacuum(String rel) {
String sql = "VACUUM " + rel;
this.update(sql);
}
/**
* Drop an index if it exists.
*
* @param idx name of the index
*/
public void dropIndex(String idx){
String sql = "DROP INDEX IF EXISTS " + idx;
try {
updateRaw(sql);
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Reset the value of a sequence to 1.
*
* @param seq name of the sequence
*/
public void resetSequence(String seq) {
String sql = "SELECT setval('" + seq +
"', 1, false)";
execute(sql);
}
/**
* Call a stored procedure that doesn't have any parameters.
*
* @param proc name of the stored procedure
*/
public void callProcedure(String proc) {
CallableStatement stmt = null;
try {
stmt = con.prepareCall("{call "+proc+"()}");
stmt.execute();
stmt.close();
} catch (SQLException e) {
ExceptionMan.handle(e);
}
}
/**
* Call a function that returns a double.
*
* @param func name of the function
* @param args arguments in the form of a string
* @return value returned by the function; null on error
*/
public Double callFunctionDouble(String func, String args) {
CallableStatement stmt = null;
try {
if(args == null) args = "";
stmt = con.prepareCall("{? = call "+func+"(" +args + ")}");
stmt.registerOutParameter(1, java.sql.Types.DOUBLE);
stmt.execute();
double x = stmt.getDouble(1);
stmt.close();
return x;
} catch (SQLException e) {
ExceptionMan.handle(e);
}
return null;
}
}
| {
"content_hash": "d8c52a074669ce304114bcb38fe7c278",
"timestamp": "",
"source": "github",
"line_count": 1005,
"max_line_length": 122,
"avg_line_length": 27.00398009950249,
"alnum_prop": 0.591252441136372,
"repo_name": "gaapt/deepdive",
"id": "83dcc28bcc8a51ec13384d890528ae7b99a794c7",
"size": "27139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mln/src/tuffy/db/RDB.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "86493"
},
{
"name": "C++",
"bytes": "18655"
},
{
"name": "Diff",
"bytes": "24109"
},
{
"name": "GAP",
"bytes": "22850"
},
{
"name": "HTML",
"bytes": "19985"
},
{
"name": "Java",
"bytes": "652768"
},
{
"name": "Makefile",
"bytes": "951"
},
{
"name": "Perl",
"bytes": "24674"
},
{
"name": "Protocol Buffer",
"bytes": "1734"
},
{
"name": "Python",
"bytes": "148767"
},
{
"name": "Scala",
"bytes": "380272"
},
{
"name": "Shell",
"bytes": "46894"
},
{
"name": "XSLT",
"bytes": "2150"
}
],
"symlink_target": ""
} |
import { EventEmitter } from 'angular2/src/core/facade/async';
import { OnChanges, OnDestroy } from 'angular2/lifecycle_hooks';
import { SimpleChange } from 'angular2/src/core/change_detection';
import { ControlContainer } from './control_container';
import { NgControl } from './ng_control';
import { ControlValueAccessor } from './control_value_accessor';
import { Control } from '../model';
/**
* Creates and binds a control with a specified name to a DOM element.
*
* This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
* ### Example
*
* In this example, we create the login and password controls.
* We can work with each control separately: check its validity, get its value, listen to its
* changes.
*
* ```
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: `
* <form #f="form" (submit)='onLogIn(f.value)'>
* Login <input type='text' ng-control='login' #l="form">
* <div *ng-if="!l.valid">Login is invalid</div>
*
* Password <input type='password' ng-control='password'>
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* onLogIn(value): void {
* // value === {login: 'some login', password: 'some password'}
* }
* }
* ```
*
* We can also use ng-model to bind a domain model to the form.
*
* ```
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: `
* <form (submit)='onLogIn()'>
* Login <input type='text' ng-control='login' [(ng-model)]="credentials.login">
* Password <input type='password' ng-control='password'
* [(ng-model)]="credentials.password">
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* credentials: {login:string, password:string};
*
* onLogIn(): void {
* // this.credentials.login === "some login"
* // this.credentials.password === "some password"
* }
* }
* ```
*/
export declare class NgControlName extends NgControl implements OnChanges, OnDestroy {
update: EventEmitter;
model: any;
viewModel: any;
private _validator;
constructor(parent: ControlContainer, validators: any[], valueAccessors: ControlValueAccessor[]);
onChanges(changes: {
[key: string]: SimpleChange;
}): void;
onDestroy(): void;
viewToModelUpdate(newValue: any): void;
path: string[];
formDirective: any;
validator: Function;
control: Control;
}
| {
"content_hash": "78c01267bfb60cff65e959b1a045212c",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 101,
"avg_line_length": 34.217948717948715,
"alnum_prop": 0.5957287373548146,
"repo_name": "hilts-vaughan/webrtc-components",
"id": "042690031f120d85d3beb0a56652f2d34e207536",
"size": "2669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/node_modules/angular2/src/core/forms/directives/ng_control_name.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3203"
},
{
"name": "HTML",
"bytes": "6202"
},
{
"name": "JavaScript",
"bytes": "1918073"
},
{
"name": "TypeScript",
"bytes": "45654"
}
],
"symlink_target": ""
} |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for manipulating arrays.
*
*/
goog.provide('goog.array');
goog.provide('goog.array.ArrayLike');
goog.require('goog.asserts');
/**
* @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
* rely on Array.prototype functions, if available.
*
* The Array.prototype functions can be defined by external libraries like
* Prototype and setting this flag to false forces closure to use its own
* goog.array implementation.
*
* If your javascript can be loaded by a third party site and you are wary about
* relying on the prototype functions, specify
* "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
*
* Setting goog.TRUSTED_SITE to false will automatically set
* NATIVE_ARRAY_PROTOTYPES to false.
*/
goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
/**
* @typedef {Array|NodeList|Arguments|{length: number}}
*/
goog.array.ArrayLike;
/**
* Returns the last element in an array without removing it.
* @param {Array.<T>|goog.array.ArrayLike} array The array.
* @return {T} Last item in array.
* @template T
*/
goog.array.peek = function(array) {
return array[array.length - 1];
};
/**
* Reference to the original {@code Array.prototype}.
* @private
*/
goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
// NOTE(arv): Since most of the array functions are generic it allows you to
// pass an array-like object. Strings have a length and are considered array-
// like. However, the 'in' operator does not work on strings so we cannot just
// use the array path even if the browser supports indexing into strings. We
// therefore end up splitting the string.
/**
* Returns the index of the first element of an array with a specified value, or
* -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
*
* @param {Array.<T>|goog.array.ArrayLike} arr The array to be searched.
* @param {T} obj The object for which we are searching.
* @param {number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at index 0.
* @return {number} The index of the first matching array element.
* @template T
*/
goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.indexOf ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ?
0 : (opt_fromIndex < 0 ?
Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
if (goog.isString(arr)) {
// Array.prototype.indexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.indexOf(obj, fromIndex);
}
for (var i = fromIndex; i < arr.length; i++) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Returns the index of the last element of an array with a specified value, or
* -1 if the element is not present in the array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
*
* @param {!Array.<T>|!goog.array.ArrayLike} arr The array to be searched.
* @param {T} obj The object for which we are searching.
* @param {?number=} opt_fromIndex The index at which to start the search. If
* omitted the search starts at the end of the array.
* @return {number} The index of the last matching array element.
* @template T
*/
goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.lastIndexOf ?
function(arr, obj, opt_fromIndex) {
goog.asserts.assert(arr.length != null);
// Firefox treats undefined and null as 0 in the fromIndex argument which
// leads it to always return -1
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex);
} :
function(arr, obj, opt_fromIndex) {
var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
if (fromIndex < 0) {
fromIndex = Math.max(0, arr.length + fromIndex);
}
if (goog.isString(arr)) {
// Array.prototype.lastIndexOf uses === so only strings should be found.
if (!goog.isString(obj) || obj.length != 1) {
return -1;
}
return arr.lastIndexOf(obj, fromIndex);
}
for (var i = fromIndex; i >= 0; i--) {
if (i in arr && arr[i] === obj)
return i;
}
return -1;
};
/**
* Calls a function for each element in an array. Skips holes in the array.
* See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function takes 3 arguments (the element, the index and the
* array). The return value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @template T,S
*/
goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.forEach ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, starting from the last
* element rather than the first.
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this: S, T, number, ?): ?} f The function to call for every
* element. This function
* takes 3 arguments (the element, the index and the array). The return
* value is ignored.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @template T,S
*/
goog.array.forEachRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; --i) {
if (i in arr2) {
f.call(opt_obj, arr2[i], i, arr);
}
}
};
/**
* Calls a function for each element in an array, and if the function returns
* true adds the element to a new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?):boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and must
* return a Boolean. If the return value is true the element is added to the
* result array. If it is false the element is not included.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {!Array.<T>} a new array in which only elements that passed the test
* are present.
* @template T,S
*/
goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.filter ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = [];
var resLength = 0;
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
var val = arr2[i]; // in case f mutates arr2
if (f.call(opt_obj, val, i, arr)) {
res[resLength++] = val;
}
}
}
return res;
};
/**
* Calls a function for each element in an array and inserts the result into a
* new array.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-map}
*
* @param {Array.<VALUE>|goog.array.ArrayLike} arr Array or array like object
* over which to iterate.
* @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
* for every element. This function takes 3 arguments (the element,
* the index and the array) and should return something. The result will be
* inserted into a new array.
* @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
* @return {!Array.<RESULT>} a new array with the results from f.
* @template THIS, VALUE, RESULT
*/
goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.map ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var res = new Array(l);
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2) {
res[i] = f.call(opt_obj, arr2[i], i, arr);
}
}
return res;
};
/**
* Passes every element of an array into a function and accumulates the result.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
*
* For example:
* var a = [1, 2, 3, 4];
* goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
* returns 10
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Result of evaluating f repeatedly across the values of the array.
* @template T,S,R
*/
goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.reduce ?
function(arr, f, val, opt_obj) {
goog.asserts.assert(arr.length != null);
if (opt_obj) {
f = goog.bind(f, opt_obj);
}
return goog.array.ARRAY_PROTOTYPE_.reduce.call(arr, f, val);
} :
function(arr, f, val, opt_obj) {
var rval = val;
goog.array.forEach(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Passes every element of an array into a function and accumulates the result,
* starting from the last element and working towards the first.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
*
* For example:
* var a = ['a', 'b', 'c'];
* goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
* returns 'cba'
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, R, T, number, ?) : R} f The function to call for
* every element. This function
* takes 4 arguments (the function's previous result or the initial value,
* the value of the current array element, the current array index, and the
* array itself)
* function(previousValue, currentValue, index, array).
* @param {?} val The initial value to pass into the function on the first call.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {R} Object returned as a result of evaluating f repeatedly across the
* values of the array.
* @template T,S,R
*/
goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.reduceRight ?
function(arr, f, val, opt_obj) {
goog.asserts.assert(arr.length != null);
if (opt_obj) {
f = goog.bind(f, opt_obj);
}
return goog.array.ARRAY_PROTOTYPE_.reduceRight.call(arr, f, val);
} :
function(arr, f, val, opt_obj) {
var rval = val;
goog.array.forEachRight(arr, function(val, index) {
rval = f.call(opt_obj, rval, val, index, arr);
});
return rval;
};
/**
* Calls f for each element of an array. If any call returns true, some()
* returns true (without checking the remaining elements). If all calls
* return false, some() returns false.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-some}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} true if any element passes the test.
* @template T,S
*/
goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.some ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return true;
}
}
return false;
};
/**
* Call f for each element of an array. If all calls return true, every()
* returns true. If any call returns false, every() returns false and
* does not continue to check the remaining elements.
*
* See {@link http://tinyurl.com/developer-mozilla-org-array-every}
*
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within f.
* @return {boolean} false if any element fails the test.
* @template T,S
*/
goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
goog.array.ARRAY_PROTOTYPE_.every ?
function(arr, f, opt_obj) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
} :
function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
return false;
}
}
return true;
};
/**
* Counts the array elements that fulfill the predicate, i.e. for which the
* callback function returns true. Skips holes in the array.
*
* @param {!(Array.<T>|goog.array.ArrayLike)} arr Array or array like object
* over which to iterate.
* @param {function(this: S, T, number, ?): boolean} f The function to call for
* every element. Takes 3 arguments (the element, the index and the array).
* @param {S=} opt_obj The object to be used as the value of 'this' within f.
* @return {number} The number of the matching elements.
* @template T,S
*/
goog.array.count = function(arr, f, opt_obj) {
var count = 0;
goog.array.forEach(arr, function(element, index, arr) {
if (f.call(opt_obj, element, index, arr)) {
++count;
}
}, opt_obj);
return count;
};
/**
* Search an array for the first element that satisfies a given condition and
* return that element.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T} The first array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.find = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array for the first element that satisfies a given condition and
* return its index.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call for
* every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {number} The index of the first array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndex = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = 0; i < l; i++) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return that element.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {T} The last array element that passes the test, or null if no
* element is found.
* @template T,S
*/
goog.array.findRight = function(arr, f, opt_obj) {
var i = goog.array.findIndexRight(arr, f, opt_obj);
return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
};
/**
* Search an array (in reverse order) for the last element that satisfies a
* given condition and return its index.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {Object=} opt_obj An optional "this" context for the function.
* @return {number} The index of the last array element that passes the test,
* or -1 if no element is found.
* @template T,S
*/
goog.array.findIndexRight = function(arr, f, opt_obj) {
var l = arr.length; // must be fixed during loop... see docs
var arr2 = goog.isString(arr) ? arr.split('') : arr;
for (var i = l - 1; i >= 0; i--) {
if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
return i;
}
}
return -1;
};
/**
* Whether the array contains the given object.
* @param {goog.array.ArrayLike} arr The array to test for the presence of the
* element.
* @param {*} obj The object for which to test.
* @return {boolean} true if obj is present.
*/
goog.array.contains = function(arr, obj) {
return goog.array.indexOf(arr, obj) >= 0;
};
/**
* Whether the array is empty.
* @param {goog.array.ArrayLike} arr The array to test.
* @return {boolean} true if empty.
*/
goog.array.isEmpty = function(arr) {
return arr.length == 0;
};
/**
* Clears the array.
* @param {goog.array.ArrayLike} arr Array or array like object to clear.
*/
goog.array.clear = function(arr) {
// For non real arrays we don't have the magic length so we delete the
// indices.
if (!goog.isArray(arr)) {
for (var i = arr.length - 1; i >= 0; i--) {
delete arr[i];
}
}
arr.length = 0;
};
/**
* Pushes an item into an array, if it's not already in the array.
* @param {Array.<T>} arr Array into which to insert the item.
* @param {T} obj Value to add.
* @template T
*/
goog.array.insert = function(arr, obj) {
if (!goog.array.contains(arr, obj)) {
arr.push(obj);
}
};
/**
* Inserts an object at the given index of the array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {*} obj The object to insert.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertAt = function(arr, obj, opt_i) {
goog.array.splice(arr, opt_i, 0, obj);
};
/**
* Inserts at the given index of the array, all elements of another array.
* @param {goog.array.ArrayLike} arr The array to modify.
* @param {goog.array.ArrayLike} elementsToAdd The array of elements to add.
* @param {number=} opt_i The index at which to insert the object. If omitted,
* treated as 0. A negative index is counted from the end of the array.
*/
goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
};
/**
* Inserts an object into an array before a specified object.
* @param {Array.<T>} arr The array to modify.
* @param {T} obj The object to insert.
* @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
* is omitted or not found, obj is inserted at the end of the array.
* @template T
*/
goog.array.insertBefore = function(arr, obj, opt_obj2) {
var i;
if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
arr.push(obj);
} else {
goog.array.insertAt(arr, obj, i);
}
};
/**
* Removes the first occurrence of a particular value from an array.
* @param {Array.<T>|goog.array.ArrayLike} arr Array from which to remove
* value.
* @param {T} obj Object to remove.
* @return {boolean} True if an element was removed.
* @template T
*/
goog.array.remove = function(arr, obj) {
var i = goog.array.indexOf(arr, obj);
var rv;
if ((rv = i >= 0)) {
goog.array.removeAt(arr, i);
}
return rv;
};
/**
* Removes from an array the element at index i
* @param {goog.array.ArrayLike} arr Array or array like object from which to
* remove value.
* @param {number} i The index to remove.
* @return {boolean} True if an element was removed.
*/
goog.array.removeAt = function(arr, i) {
goog.asserts.assert(arr.length != null);
// use generic form of splice
// splice returns the removed items and if successful the length of that
// will be 1
return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
};
/**
* Removes the first value that satisfies the given condition.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array
* like object over which to iterate.
* @param {?function(this:S, T, number, ?) : boolean} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the array) and should
* return a boolean.
* @param {S=} opt_obj An optional "this" context for the function.
* @return {boolean} True if an element was removed.
* @template T,S
*/
goog.array.removeIf = function(arr, f, opt_obj) {
var i = goog.array.findIndex(arr, f, opt_obj);
if (i >= 0) {
goog.array.removeAt(arr, i);
return true;
}
return false;
};
/**
* Returns a new array that is the result of joining the arguments. If arrays
* are passed then their items are added, however, if non-arrays are passed they
* will be added to the return array as is.
*
* Note that ArrayLike objects will be added as is, rather than having their
* items added.
*
* goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
* goog.array.concat(0, [1, 2]) -> [0, 1, 2]
* goog.array.concat([1, 2], null) -> [1, 2, null]
*
* There is bug in all current versions of IE (6, 7 and 8) where arrays created
* in an iframe become corrupted soon (not immediately) after the iframe is
* destroyed. This is common if loading data via goog.net.IframeIo, for example.
* This corruption only affects the concat method which will start throwing
* Catastrophic Errors (#-2147418113).
*
* See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
*
* Internally goog.array should use this, so that all methods will continue to
* work on these broken array objects.
*
* @param {...*} var_args Items to concatenate. Arrays will have each item
* added, while primitives and objects will be added as is.
* @return {!Array} The new resultant array.
*/
goog.array.concat = function(var_args) {
return goog.array.ARRAY_PROTOTYPE_.concat.apply(
goog.array.ARRAY_PROTOTYPE_, arguments);
};
/**
* Converts an object to an array.
* @param {Array.<T>|goog.array.ArrayLike} object The object to convert to an
* array.
* @return {!Array.<T>} The object converted into an array. If object has a
* length property, every property indexed with a non-negative number
* less than length will be included in the result. If object does not
* have a length property, an empty array will be returned.
* @template T
*/
goog.array.toArray = function(object) {
var length = object.length;
// If length is not a number the following it false. This case is kept for
// backwards compatibility since there are callers that pass objects that are
// not array like.
if (length > 0) {
var rv = new Array(length);
for (var i = 0; i < length; i++) {
rv[i] = object[i];
}
return rv;
}
return [];
};
/**
* Does a shallow copy of an array.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array-like object to
* clone.
* @return {!Array.<T>} Clone of the input array.
* @template T
*/
goog.array.clone = goog.array.toArray;
/**
* Extends an array with another array, element, or "array like" object.
* This function operates 'in-place', it does not create a new Array.
*
* Example:
* var a = [];
* goog.array.extend(a, [0, 1]);
* a; // [0, 1]
* goog.array.extend(a, 2);
* a; // [0, 1, 2]
*
* @param {Array.<VALUE>} arr1 The array to modify.
* @param {...(Array.<VALUE>|VALUE)} var_args The elements or arrays of elements
* to add to arr1.
* @template VALUE
*/
goog.array.extend = function(arr1, var_args) {
for (var i = 1; i < arguments.length; i++) {
var arr2 = arguments[i];
// If we have an Array or an Arguments object we can just call push
// directly.
var isArrayLike;
if (goog.isArray(arr2) ||
// Detect Arguments. ES5 says that the [[Class]] of an Arguments object
// is "Arguments" but only V8 and JSC/Safari gets this right. We instead
// detect Arguments by checking for array like and presence of "callee".
(isArrayLike = goog.isArrayLike(arr2)) &&
// The getter for callee throws an exception in strict mode
// according to section 10.6 in ES5 so check for presence instead.
Object.prototype.hasOwnProperty.call(arr2, 'callee')) {
arr1.push.apply(arr1, arr2);
} else if (isArrayLike) {
// Otherwise loop over arr2 to prevent copying the object.
var len1 = arr1.length;
var len2 = arr2.length;
for (var j = 0; j < len2; j++) {
arr1[len1 + j] = arr2[j];
}
} else {
arr1.push(arr2);
}
}
};
/**
* Adds or removes elements from an array. This is a generic version of Array
* splice. This means that it might work on other objects similar to arrays,
* such as the arguments object.
*
* @param {Array.<T>|goog.array.ArrayLike} arr The array to modify.
* @param {number|undefined} index The index at which to start changing the
* array. If not defined, treated as 0.
* @param {number} howMany How many elements to remove (0 means no removal. A
* value below 0 is treated as zero and so is any other non number. Numbers
* are floored).
* @param {...T} var_args Optional, additional elements to insert into the
* array.
* @return {!Array.<T>} the removed elements.
* @template T
*/
goog.array.splice = function(arr, index, howMany, var_args) {
goog.asserts.assert(arr.length != null);
return goog.array.ARRAY_PROTOTYPE_.splice.apply(
arr, goog.array.slice(arguments, 1));
};
/**
* Returns a new array from a segment of an array. This is a generic version of
* Array slice. This means that it might work on other objects similar to
* arrays, such as the arguments object.
*
* @param {Array.<T>|goog.array.ArrayLike} arr The array from
* which to copy a segment.
* @param {number} start The index of the first element to copy.
* @param {number=} opt_end The index after the last element to copy.
* @return {!Array.<T>} A new array containing the specified segment of the
* original array.
* @template T
*/
goog.array.slice = function(arr, start, opt_end) {
goog.asserts.assert(arr.length != null);
// passing 1 arg to slice is not the same as passing 2 where the second is
// null or undefined (in that case the second argument is treated as 0).
// we could use slice on the arguments object and then use apply instead of
// testing the length
if (arguments.length <= 2) {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
} else {
return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
}
};
/**
* Removes all duplicates from an array (retaining only the first
* occurrence of each array element). This function modifies the
* array in place and doesn't change the order of the non-duplicate items.
*
* For objects, duplicates are identified as having the same unique ID as
* defined by {@link goog.getUid}.
*
* Alternatively you can specify a custom hash function that returns a unique
* value for each item in the array it should consider unique.
*
* Runtime: N,
* Worstcase space: 2N (no dupes)
*
* @param {Array.<T>|goog.array.ArrayLike} arr The array from which to remove
* duplicates.
* @param {Array=} opt_rv An optional array in which to return the results,
* instead of performing the removal inplace. If specified, the original
* array will remain unchanged.
* @param {function(T):string=} opt_hashFn An optional function to use to
* apply to every item in the array. This function should return a unique
* value for each item in the array it should consider unique.
* @template T
*/
goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
var returnArray = opt_rv || arr;
var defaultHashFn = function(item) {
// Prefix each type with a single character representing the type to
// prevent conflicting keys (e.g. true and 'true').
return goog.isObject(current) ? 'o' + goog.getUid(current) :
(typeof current).charAt(0) + current;
};
var hashFn = opt_hashFn || defaultHashFn;
var seen = {}, cursorInsert = 0, cursorRead = 0;
while (cursorRead < arr.length) {
var current = arr[cursorRead++];
var key = hashFn(current);
if (!Object.prototype.hasOwnProperty.call(seen, key)) {
seen[key] = true;
returnArray[cursorInsert++] = current;
}
}
returnArray.length = cursorInsert;
};
/**
* Searches the specified array for the specified target using the binary
* search algorithm. If no opt_compareFn is specified, elements are compared
* using <code>goog.array.defaultCompare</code>, which compares the elements
* using the built in < and > operators. This will produce the expected
* behavior for homogeneous arrays of String(s) and Number(s). The array
* specified <b>must</b> be sorted in ascending order (as defined by the
* comparison function). If the array is not sorted, results are undefined.
* If the array contains multiple instances of the specified target value, any
* of these instances may be found.
*
* Runtime: O(log n)
*
* @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
* @param {TARGET} target The sought value.
* @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
* @template TARGET, VALUE
*/
goog.array.binarySearch = function(arr, target, opt_compareFn) {
return goog.array.binarySearch_(arr,
opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
target);
};
/**
* Selects an index in the specified array using the binary search algorithm.
* The evaluator receives an element and determines whether the desired index
* is before, at, or after it. The evaluator must be consistent (formally,
* goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
* must be monotonically non-increasing).
*
* Runtime: O(log n)
*
* @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
* @param {function(this:THIS, VALUE, number, ?): number} evaluator
* Evaluator function that receives 3 arguments (the element, the index and
* the array). Should return a negative number, zero, or a positive number
* depending on whether the desired index is before, at, or after the
* element passed to it.
* @param {THIS=} opt_obj The object to be used as the value of 'this'
* within evaluator.
* @return {number} Index of the leftmost element matched by the evaluator, if
* such exists; otherwise (-(insertion point) - 1). The insertion point is
* the index of the first element for which the evaluator returns negative,
* or arr.length if no such element exists. The return value is non-negative
* iff a match is found.
* @template THIS, VALUE
*/
goog.array.binarySelect = function(arr, evaluator, opt_obj) {
return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
undefined /* opt_target */, opt_obj);
};
/**
* Implementation of a binary search algorithm which knows how to use both
* comparison functions and evaluators. If an evaluator is provided, will call
* the evaluator with the given optional data object, conforming to the
* interface defined in binarySelect. Otherwise, if a comparison function is
* provided, will call the comparison function against the given data object.
*
* This implementation purposefully does not use goog.bind or goog.partial for
* performance reasons.
*
* Runtime: O(log n)
*
* @param {Array.<VALUE>|goog.array.ArrayLike} arr The array to be searched.
* @param {function(TARGET, VALUE): number|
* function(this:THIS, VALUE, number, ?): number} compareFn Either an
* evaluator or a comparison function, as defined by binarySearch
* and binarySelect above.
* @param {boolean} isEvaluator Whether the function is an evaluator or a
* comparison function.
* @param {TARGET=} opt_target If the function is a comparison function, then
* this is the target to binary search for.
* @param {THIS=} opt_selfObj If the function is an evaluator, this is an
* optional this object for the evaluator.
* @return {number} Lowest index of the target value if found, otherwise
* (-(insertion point) - 1). The insertion point is where the value should
* be inserted into arr to preserve the sorted property. Return value >= 0
* iff target is found.
* @template THIS, VALUE, TARGET
* @private
*/
goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
opt_selfObj) {
var left = 0; // inclusive
var right = arr.length; // exclusive
var found;
while (left < right) {
var middle = (left + right) >> 1;
var compareResult;
if (isEvaluator) {
compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
} else {
compareResult = compareFn(opt_target, arr[middle]);
}
if (compareResult > 0) {
left = middle + 1;
} else {
right = middle;
// We are looking for the lowest index so we can't return immediately.
found = !compareResult;
}
}
// left is the index if found, or the insertion point otherwise.
// ~left is a shorthand for -left - 1.
return found ? left : ~left;
};
/**
* Sorts the specified array into ascending order. If no opt_compareFn is
* specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s), unlike the native sort,
* but will give unpredictable results for heterogenous lists of strings and
* numbers with different numbers of digits.
*
* This sort is not guaranteed to be stable.
*
* Runtime: Same as <code>Array.prototype.sort</code>
*
* @param {Array.<T>} arr The array to be sorted.
* @param {?function(T,T):number=} opt_compareFn Optional comparison
* function by which the
* array is to be ordered. Should take 2 arguments to compare, and return a
* negative number, zero, or a positive number depending on whether the
* first argument is less than, equal to, or greater than the second.
* @template T
*/
goog.array.sort = function(arr, opt_compareFn) {
// TODO(arv): Update type annotation since null is not accepted.
goog.asserts.assert(arr.length != null);
goog.array.ARRAY_PROTOTYPE_.sort.call(
arr, opt_compareFn || goog.array.defaultCompare);
};
/**
* Sorts the specified array into ascending order in a stable way. If no
* opt_compareFn is specified, elements are compared using
* <code>goog.array.defaultCompare</code>, which compares the elements using
* the built in < and > operators. This will produce the expected behavior
* for homogeneous arrays of String(s) and Number(s).
*
* Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
* O(n) overhead of copying the array twice.
*
* @param {Array.<T>} arr The array to be sorted.
* @param {?function(T, T): number=} opt_compareFn Optional comparison function
* by which the array is to be ordered. Should take 2 arguments to compare,
* and return a negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template T
*/
goog.array.stableSort = function(arr, opt_compareFn) {
for (var i = 0; i < arr.length; i++) {
arr[i] = {index: i, value: arr[i]};
}
var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
function stableCompareFn(obj1, obj2) {
return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
};
goog.array.sort(arr, stableCompareFn);
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].value;
}
};
/**
* Sorts an array of objects by the specified object key and compare
* function. If no compare function is provided, the key values are
* compared in ascending order using <code>goog.array.defaultCompare</code>.
* This won't work for keys that get renamed by the compiler. So use
* {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
* @param {Array.<Object>} arr An array of objects to sort.
* @param {string} key The object key to sort by.
* @param {Function=} opt_compareFn The function to use to compare key
* values.
*/
goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
var compare = opt_compareFn || goog.array.defaultCompare;
goog.array.sort(arr, function(a, b) {
return compare(a[key], b[key]);
});
};
/**
* Tells if the array is sorted.
* @param {!Array.<T>} arr The array.
* @param {?function(T,T):number=} opt_compareFn Function to compare the
* array elements.
* Should take 2 arguments to compare, and return a negative number, zero,
* or a positive number depending on whether the first argument is less
* than, equal to, or greater than the second.
* @param {boolean=} opt_strict If true no equal elements are allowed.
* @return {boolean} Whether the array is sorted.
* @template T
*/
goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
var compare = opt_compareFn || goog.array.defaultCompare;
for (var i = 1; i < arr.length; i++) {
var compareResult = compare(arr[i - 1], arr[i]);
if (compareResult > 0 || compareResult == 0 && opt_strict) {
return false;
}
}
return true;
};
/**
* Compares two arrays for equality. Two arrays are considered equal if they
* have the same length and their corresponding elements are equal according to
* the comparison function.
*
* @param {goog.array.ArrayLike} arr1 The first array to compare.
* @param {goog.array.ArrayLike} arr2 The second array to compare.
* @param {Function=} opt_equalsFn Optional comparison function.
* Should take 2 arguments to compare, and return true if the arguments
* are equal. Defaults to {@link goog.array.defaultCompareEquality} which
* compares the elements using the built-in '===' operator.
* @return {boolean} Whether the two arrays are equal.
*/
goog.array.equals = function(arr1, arr2, opt_equalsFn) {
if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
arr1.length != arr2.length) {
return false;
}
var l = arr1.length;
var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
for (var i = 0; i < l; i++) {
if (!equalsFn(arr1[i], arr2[i])) {
return false;
}
}
return true;
};
/**
* @deprecated Use {@link goog.array.equals}.
* @param {goog.array.ArrayLike} arr1 See {@link goog.array.equals}.
* @param {goog.array.ArrayLike} arr2 See {@link goog.array.equals}.
* @param {Function=} opt_equalsFn See {@link goog.array.equals}.
* @return {boolean} See {@link goog.array.equals}.
*/
goog.array.compare = function(arr1, arr2, opt_equalsFn) {
return goog.array.equals(arr1, arr2, opt_equalsFn);
};
/**
* 3-way array compare function.
* @param {!Array.<VALUE>|!goog.array.ArrayLike} arr1 The first array to
* compare.
* @param {!Array.<VALUE>|!goog.array.ArrayLike} arr2 The second array to
* compare.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is to be ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {number} Negative number, zero, or a positive number depending on
* whether the first argument is less than, equal to, or greater than the
* second.
* @template VALUE
*/
goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
var compare = opt_compareFn || goog.array.defaultCompare;
var l = Math.min(arr1.length, arr2.length);
for (var i = 0; i < l; i++) {
var result = compare(arr1[i], arr2[i]);
if (result != 0) {
return result;
}
}
return goog.array.defaultCompare(arr1.length, arr2.length);
};
/**
* Compares its two arguments for order, using the built in < and >
* operators.
* @param {VALUE} a The first object to be compared.
* @param {VALUE} b The second object to be compared.
* @return {number} A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
* @template VALUE
*/
goog.array.defaultCompare = function(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
};
/**
* Compares its two arguments for equality, using the built in === operator.
* @param {*} a The first object to compare.
* @param {*} b The second object to compare.
* @return {boolean} True if the two arguments are equal, false otherwise.
*/
goog.array.defaultCompareEquality = function(a, b) {
return a === b;
};
/**
* Inserts a value into a sorted array. The array is not modified if the
* value is already present.
* @param {Array.<VALUE>|goog.array.ArrayLike} array The array to modify.
* @param {VALUE} value The object to insert.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {boolean} True if an element was inserted.
* @template VALUE
*/
goog.array.binaryInsert = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
if (index < 0) {
goog.array.insertAt(array, value, -(index + 1));
return true;
}
return false;
};
/**
* Removes a value from a sorted array.
* @param {!Array.<VALUE>|!goog.array.ArrayLike} array The array to modify.
* @param {VALUE} value The object to remove.
* @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
* function by which the array is ordered. Should take 2 arguments to
* compare, and return a negative number, zero, or a positive number
* depending on whether the first argument is less than, equal to, or
* greater than the second.
* @return {boolean} True if an element was removed.
* @template VALUE
*/
goog.array.binaryRemove = function(array, value, opt_compareFn) {
var index = goog.array.binarySearch(array, value, opt_compareFn);
return (index >= 0) ? goog.array.removeAt(array, index) : false;
};
/**
* Splits an array into disjoint buckets according to a splitting function.
* @param {Array.<T>} array The array.
* @param {function(this:S, T,number,Array.<T>):?} sorter Function to call for
* every element. This takes 3 arguments (the element, the index and the
* array) and must return a valid object key (a string, number, etc), or
* undefined, if that object should not be placed in a bucket.
* @param {S=} opt_obj The object to be used as the value of 'this' within
* sorter.
* @return {!Object} An object, with keys being all of the unique return values
* of sorter, and values being arrays containing the items for
* which the splitter returned that key.
* @template T,S
*/
goog.array.bucket = function(array, sorter, opt_obj) {
var buckets = {};
for (var i = 0; i < array.length; i++) {
var value = array[i];
var key = sorter.call(opt_obj, value, i, array);
if (goog.isDef(key)) {
// Push the value to the right bucket, creating it if necessary.
var bucket = buckets[key] || (buckets[key] = []);
bucket.push(value);
}
}
return buckets;
};
/**
* Creates a new object built from the provided array and the key-generation
* function.
* @param {Array.<T>|goog.array.ArrayLike} arr Array or array like object over
* which to iterate whose elements will be the values in the new object.
* @param {?function(this:S, T, number, ?) : string} keyFunc The function to
* call for every element. This function takes 3 arguments (the element, the
* index and the array) and should return a string that will be used as the
* key for the element in the new object. If the function returns the same
* key for more than one element, the value for that key is
* implementation-defined.
* @param {S=} opt_obj The object to be used as the value of 'this'
* within keyFunc.
* @return {!Object.<T>} The new object.
* @template T,S
*/
goog.array.toObject = function(arr, keyFunc, opt_obj) {
var ret = {};
goog.array.forEach(arr, function(element, index) {
ret[keyFunc.call(opt_obj, element, index, arr)] = element;
});
return ret;
};
/**
* Creates a range of numbers in an arithmetic progression.
*
* Range takes 1, 2, or 3 arguments:
* <pre>
* range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
* range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
* range(-2, -5, -1) produces [-2, -3, -4]
* range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
* </pre>
*
* @param {number} startOrEnd The starting value of the range if an end argument
* is provided. Otherwise, the start value is 0, and this is the end value.
* @param {number=} opt_end The optional end value of the range.
* @param {number=} opt_step The step size between range values. Defaults to 1
* if opt_step is undefined or 0.
* @return {!Array.<number>} An array of numbers for the requested range. May be
* an empty array if adding the step would not converge toward the end
* value.
*/
goog.array.range = function(startOrEnd, opt_end, opt_step) {
var array = [];
var start = 0;
var end = startOrEnd;
var step = opt_step || 1;
if (opt_end !== undefined) {
start = startOrEnd;
end = opt_end;
}
if (step * (end - start) < 0) {
// Sign mismatch: start + step will never reach the end value.
return [];
}
if (step > 0) {
for (var i = start; i < end; i += step) {
array.push(i);
}
} else {
for (var i = start; i > end; i += step) {
array.push(i);
}
}
return array;
};
/**
* Returns an array consisting of the given value repeated N times.
*
* @param {VALUE} value The value to repeat.
* @param {number} n The repeat count.
* @return {!Array.<VALUE>} An array with the repeated value.
* @template VALUE
*/
goog.array.repeat = function(value, n) {
var array = [];
for (var i = 0; i < n; i++) {
array[i] = value;
}
return array;
};
/**
* Returns an array consisting of every argument with all arrays
* expanded in-place recursively.
*
* @param {...*} var_args The values to flatten.
* @return {!Array} An array containing the flattened values.
*/
goog.array.flatten = function(var_args) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (goog.isArray(element)) {
result.push.apply(result, goog.array.flatten.apply(null, element));
} else {
result.push(element);
}
}
return result;
};
/**
* Rotates an array in-place. After calling this method, the element at
* index i will be the element previously at index (i - n) %
* array.length, for all values of i between 0 and array.length - 1,
* inclusive.
*
* For example, suppose list comprises [t, a, n, k, s]. After invoking
* rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
*
* @param {!Array.<T>} array The array to rotate.
* @param {number} n The amount to rotate.
* @return {!Array.<T>} The array.
* @template T
*/
goog.array.rotate = function(array, n) {
goog.asserts.assert(array.length != null);
if (array.length) {
n %= array.length;
if (n > 0) {
goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
} else if (n < 0) {
goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
}
}
return array;
};
/**
* Moves one item of an array to a new position keeping the order of the rest
* of the items. Example use case: keeping a list of JavaScript objects
* synchronized with the corresponding list of DOM elements after one of the
* elements has been dragged to a new position.
* @param {!(Array|Arguments|{length:number})} arr The array to modify.
* @param {number} fromIndex Index of the item to move between 0 and
* {@code arr.length - 1}.
* @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
*/
goog.array.moveItem = function(arr, fromIndex, toIndex) {
goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
// Remove 1 item at fromIndex.
var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1);
// Insert the removed item at toIndex.
goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]);
// We don't use goog.array.insertAt and goog.array.removeAt, because they're
// significantly slower than splice.
};
/**
* Creates a new array for which the element at position i is an array of the
* ith element of the provided arrays. The returned array will only be as long
* as the shortest array provided; additional values are ignored. For example,
* the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
*
* This is similar to the zip() function in Python. See {@link
* http://docs.python.org/library/functions.html#zip}
*
* @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
* @return {!Array.<!Array>} A new array of arrays created from provided arrays.
*/
goog.array.zip = function(var_args) {
if (!arguments.length) {
return [];
}
var result = [];
for (var i = 0; true; i++) {
var value = [];
for (var j = 0; j < arguments.length; j++) {
var arr = arguments[j];
// If i is larger than the array length, this is the shortest array.
if (i >= arr.length) {
return result;
}
value.push(arr[i]);
}
result.push(value);
}
};
/**
* Shuffles the values in the specified array using the Fisher-Yates in-place
* shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
* and so resets the state of that random number generator. Similarly, may reset
* the state of the any other specified random number generator.
*
* Runtime: O(n)
*
* @param {!Array} arr The array to be shuffled.
* @param {function():number=} opt_randFn Optional random function to use for
* shuffling.
* Takes no arguments, and returns a random number on the interval [0, 1).
* Defaults to Math.random() using JavaScript's built-in Math library.
*/
goog.array.shuffle = function(arr, opt_randFn) {
var randFn = opt_randFn || Math.random;
for (var i = arr.length - 1; i > 0; i--) {
// Choose a random array index in [0, i] (inclusive with i).
var j = Math.floor(randFn() * (i + 1));
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
};
| {
"content_hash": "8a2a93c3e9cc3765ad01888e3bc52b46",
"timestamp": "",
"source": "github",
"line_count": 1545,
"max_line_length": 80,
"avg_line_length": 35.961812297734625,
"alnum_prop": 0.6597613433883479,
"repo_name": "bfgeek/thermo-js",
"id": "cf3897752ae010779204212f8067f554dd0e2c88",
"size": "55561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "closure-library/closure/goog/array/array.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "122251"
},
{
"name": "Emacs Lisp",
"bytes": "2410"
},
{
"name": "JavaScript",
"bytes": "14565981"
},
{
"name": "Python",
"bytes": "76518"
},
{
"name": "Shell",
"bytes": "8973"
}
],
"symlink_target": ""
} |
<html>
<head>
<script>document.write('<base href="' + document.location + '" />');</script>
<title>FCamara Teste</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="libs/core-js/client/shim.min.js"></script>
<script src="libs/zone.js/dist/zone.js"></script>
<script src="libs/reflect-metadata/Reflect.js"></script>
<script src="libs/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html> | {
"content_hash": "0866dc2d46e0af014685267635142c70",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 109,
"avg_line_length": 34.1875,
"alnum_prop": 0.659963436928702,
"repo_name": "AlanMarcell/FCamaraTeste",
"id": "8003e77ed8e1d246a80d70e646db8898b4d05103",
"size": "1094",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5470"
},
{
"name": "HTML",
"bytes": "9901"
},
{
"name": "JavaScript",
"bytes": "3994"
},
{
"name": "TypeScript",
"bytes": "48023"
}
],
"symlink_target": ""
} |
#include <ruby.h>
#include "driver.h"
/** Extension initializer, called when .so is loaded */
void Init_rdo_mysql(void) {
rb_require("rdo");
Init_rdo_mysql_driver();
}
| {
"content_hash": "c15f9e95cd91e30fadb851d543b4e3e7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 55,
"avg_line_length": 17.5,
"alnum_prop": 0.6628571428571428,
"repo_name": "d11wtq/rdo-mysql",
"id": "5046bf89c1c08a5b4612a0969bd90c6568ffc2e1",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ext/rdo_mysql/rdo_mysql.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "16356"
},
{
"name": "C++",
"bytes": "230"
},
{
"name": "Ruby",
"bytes": "32284"
}
],
"symlink_target": ""
} |
layout: post
title: "Clase en VisualBasic .NET"
date: 2009-01-05 20:45:00
categories: vb.net, oop
---
Este lenguaje es horrible.<br>
Como se puede concebir un lenguaje de programacion que no cierra las sentencias con punto y coma???
<br>
En fin
<pre>
Public Class Persona
'constructor por defecto
Sub New()
End Sub
'constructor con parametros
Sub New(ByVal nombre As String, ByVal apellidos As String, ByVal fecha As Date)
strNombre = nombre
strApellidos = apellidos
strFecha = fecha
End Sub
Private strNombre As String
Private strApellidos As String
Private strFecha As Date
'campo o ATRIBUTO Direcciones
Public Direcciones() As String = {"tu casa", "la de la ama", "la del abuelo", "la mia"}
Private msNotas() As String
'property por defecto
Default Property Notas(ByVal intIndice As Integer) As String
Get
Return Notas(intIndice)
End Get
Set(ByVal Value As String)
If msNotas Is Nothing Then
ReDim msNotas(0)
Else
ReDim Preserve msNotas(UBound(msNotas) + 1)
End If
msNotas(intIndice) = Value
End Set
End Property
'property nombre
Property nombre()
Get
Return strNombre
End Get
Set(ByVal Value)
strNombre = Value
End Set
End Property
'property apellidos
Property apellidos()
Get
Return strApellidos
End Get
Set(ByVal Value)
strApellidos = Value
End Set
End Property
'property fecha
Property fecha()
Get
Return strFecha
End Get
Set(ByVal Value)
strFecha = Value
End Set
End Property
' Edad lo saco de nacimiento y actual.
ReadOnly Property Edad() As Integer
Get
Dim actual, nac As Integer
actual = Format(Now(), "yyyy")
nac = Format(strFecha, "yyyy")
'otra forma elegante:
'DateDiff(DateInterval.Year, Now(), strFecha)
Return (actual - nac)
End Get
End Property
'nombre completo
Function NombreCompleto(ByVal Titulo As String)
If (Trim(Titulo) <> "") Then
Return Titulo & " " & strNombre & " " & strApellidos
Else
Return strNombre & " " & strApellidos
End If
End Function
'nombre completo sobrecargado
Function NombreCompleto()
Return strNombre & " " & strApellidos
End Function
'metodo mostrar notas
Sub mostrarNotas()
Dim elemento As String
Dim contador As Integer
contador = 0
'recorremos el array
For Each elemento In msNotas
contador += 1
Console.WriteLine(contador & ".- " & elemento & ".")
Next
End Sub
End Class
</pre>
| {
"content_hash": "8d57cecba1ee8dfa0e325fa8c0722658",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 99,
"avg_line_length": 23.055118110236222,
"alnum_prop": 0.5846994535519126,
"repo_name": "pxai/pxai.github.io",
"id": "d62f06153c1e62831a21274ab3baaa6eb88bf3e1",
"size": "2932",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2009-01-05-clase-en-visualbasic-net.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "282"
},
{
"name": "CSS",
"bytes": "279765"
},
{
"name": "HTML",
"bytes": "29635383"
},
{
"name": "Hack",
"bytes": "17972"
},
{
"name": "JavaScript",
"bytes": "2339966"
},
{
"name": "PHP",
"bytes": "1508"
},
{
"name": "Ruby",
"bytes": "3236"
},
{
"name": "Shell",
"bytes": "3588"
}
],
"symlink_target": ""
} |
"""Layout JSON App Config"""
# standard library
import json
import logging
import os
from collections import OrderedDict
from pathlib import Path
from typing import TYPE_CHECKING, Optional
# first-party
from tcex.app_config.models import LayoutJsonModel
from tcex.backports import cached_property
from tcex.pleb.singleton import Singleton
if TYPE_CHECKING: # pragma: no cover
# first-party
from tcex.app_config.models.install_json_model import OutputVariablesModel, ParamsModel
# get tcex logger
tcex_logger = logging.getLogger('tcex')
class LayoutJson(metaclass=Singleton):
"""Provide a model for the layout.json config file."""
def __init__(
self,
filename: Optional[str] = None,
path: Optional[str] = None,
logger: Optional[logging.Logger] = None,
):
"""Initialize class properties."""
filename = filename or 'layout.json'
path = path or os.getcwd()
self.log = logger or tcex_logger
# properties
self.fqfn = Path(os.path.join(path, filename))
@cached_property
def contents(self) -> dict:
"""Return layout.json file contents."""
contents = {}
if self.fqfn.is_file():
try:
with self.fqfn.open() as fh:
contents = json.load(fh, object_pairs_hook=OrderedDict)
except (OSError, ValueError): # pragma: no cover
self.log.error(
f'feature=layout-json, exception=failed-reading-file, filename={self.fqfn}'
)
else: # pragma: no cover
self.log.error(f'feature=layout-json, exception=file-not-found, filename={self.fqfn}')
return contents
def create(self, inputs: 'ParamsModel', outputs: 'OutputVariablesModel'):
"""Create new layout.json file based on inputs and outputs."""
def input_data(sequence: int, title: str) -> dict:
return {
'parameters': [],
'sequence': sequence,
'title': title,
}
lj = LayoutJsonModel(
**{
'inputs': [
input_data(1, 'Action'),
input_data(2, 'Connection'),
input_data(3, 'Configure'),
input_data(4, 'Advanced'),
],
'outputs': [{'display': '', 'name': o.name} for o in outputs],
}
)
for input_ in inputs:
if input_.name == 'tc_action':
lj.inputs[0].parameters.append({'name': 'tc_action'})
elif input_.hidden is True:
lj.inputs[2].parameters.append(
{'display': "'hidden' != 'hidden'", 'hidden': 'true', 'name': input_.name}
)
else:
lj.inputs[2].parameters.append({'display': '', 'name': input_.name})
# write layout file to disk
data = lj.json(
by_alias=True, exclude_defaults=True, exclude_none=True, indent=2, sort_keys=True
)
self.write(data)
@property
def has_layout(self):
"""Return True if App has layout.json file."""
return self.fqfn.is_file()
@cached_property
def model(self) -> 'LayoutJsonModel':
"""Return the Install JSON model."""
return LayoutJsonModel(**self.contents)
@property
def update(self):
"""Return InstallJsonUpdate instance."""
return LayoutJsonUpdate(lj=self)
def write(self, data: str):
"""Write updated file.
Args:
data: The JSON string to write data.
"""
with self.fqfn.open(mode='w') as fh:
fh.write(f'{data}\n')
class LayoutJsonUpdate:
"""Update layout.json file with current standards and schema."""
def __init__(self, lj: LayoutJson):
"""Initialize class properties."""
self.lj = lj
def multiple(self):
"""Update the layouts.json file."""
# APP-86 - sort output data by name
self.update_sort_outputs()
data = self.lj.model.json(
by_alias=True, exclude_defaults=True, exclude_none=True, indent=2, sort_keys=True
)
self.lj.write(data)
def update_sort_outputs(self):
"""Sort output field by name."""
# APP-86 - sort output data by name
self.lj.model.outputs = sorted(
self.lj.model.dict().get('outputs', []), key=lambda i: i['name']
)
| {
"content_hash": "8b29623e1a6f02d3e8698d8e827376d9",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 98,
"avg_line_length": 31.80141843971631,
"alnum_prop": 0.5626672613737734,
"repo_name": "ThreatConnect-Inc/tcex",
"id": "af7ad841bc3af9eb9df85b4439fb770e39554098",
"size": "4484",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tcex/app_config/layout_json.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2735042"
}
],
"symlink_target": ""
} |
FactoryBot.define do
factory :page, class: Refinery::Page do
sequence(:title, "a") { |n| "Test title #{n}" }
factory :page_with_page_part do
after(:create) do |page|
page.parts << FactoryBot.build(:page_part)
end
end
end
end
| {
"content_hash": "289217f381d265730a60f0dd6de38e02",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 51,
"avg_line_length": 23.818181818181817,
"alnum_prop": 0.6068702290076335,
"repo_name": "refinery/refinerycms",
"id": "bd533537db2cf5a79779e3d16068fbc39b8711cb",
"size": "262",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "pages/spec/factories/pages.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "580"
},
{
"name": "HTML",
"bytes": "116927"
},
{
"name": "JavaScript",
"bytes": "65936"
},
{
"name": "Ruby",
"bytes": "471388"
},
{
"name": "SCSS",
"bytes": "54782"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class MoveBackgroundObject : MonoBehaviour {
public float speed = 3.0f;
// Update is called once per frame
void Update () {
this.transform.Translate(Vector3.left * Time.deltaTime * speed);
}
}
| {
"content_hash": "8e90a5b31011ed81fb46372535716a86",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 72,
"avg_line_length": 22.083333333333332,
"alnum_prop": 0.7094339622641509,
"repo_name": "Saxit/Afgangsprojekt-2014",
"id": "1fe5f9ba132fcc2647b1682af60239296504ac87",
"size": "267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RunBastardTheGame/Assets/Scripts/Level/MoveBackgroundObject.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "42288"
}
],
"symlink_target": ""
} |
Git checkout allow you to modify your local filesystem by files knew to git.
The main usecase is to switch from one branch to another.
But this also allow you to get a signle file from Git.
```sh
# Checkout a branch, tag or commit
git checkout my-branch
git checkout my-tag
git checkout HEAD
git checkout d926579
# Checkout a single file
git checkout README.md
# Checkout an older version of a single file.
git checkout master~2 README.md
# IF branch and file have the same name the branch is the defautl behavior. to checkout the file :
git checkout -- my-branch
```
In case of conflicts you can use sevral strategy (reset, stash, ...) or simply ask git to precede to a merge on checkout.
See [git documentation](https://git-scm.com/docs/git-checkout#git-checkout---conflictltstylegt) for advanced merge options.
```sh
# In case of conflict, allow git to try an automated merge
git checkout -m my-branch
```
You can checkout a remote tracking branch in one line, using the same parameters (checkout an older commit, ...).
```sh
#git checkout -b <branch name> <name of remote>/<branch name>
git checkout -b my-feature origin/my-feature
```
| {
"content_hash": "b9eb051a3d1addff813c8ac43b187e52",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 123,
"avg_line_length": 34.72727272727273,
"alnum_prop": 0.7556719022687609,
"repo_name": "jetmartin/dev_tools",
"id": "fde1610ef59aebc8464302b869fe09b6b0c54071",
"size": "1158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/git/checkout.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "557"
}
],
"symlink_target": ""
} |
class Hash
def compact
delete_if { |k, v| v.blank? }
end
def cleanup
whitelist = %w(controller action id
input
layout
resource resource_id resource_action
selected
back_to)
delete_if { |k, v| !whitelist.include?(k) }
end
end
| {
"content_hash": "7ede21f743f4d1bf4284587b23e68f44",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 55,
"avg_line_length": 20.176470588235293,
"alnum_prop": 0.4839650145772595,
"repo_name": "heroku/typus",
"id": "9a953ceab9c69501f91e94fa0650227fb7b598d1",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/support/hash.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
from django.db import transaction
from django.shortcuts import render, redirect
import haikunator
from .models import Room
from django.shortcuts import render
# Create your views here.
def about(request):
return render(request, "chat/about.html")
def new_room(request):
"""
Randomly create new room, and redirect to it.
"""
new_room = None
while not new_room:
with transaction.atomic():
label = haikunator.haikunate()
if Room.objects.filter(label=label).exists():
continue
new_room = Room.objects.create(label=label)
return redirect(chat_room, label=label)
def chat_room(request, label):
"""
Room view - show the room, with latest messages.
The template for this view has the WebSocket business to send and stream
messages, so see the template for where the magic happens.
"""
room, created = Room.objects.get_or_create(label=label)
# We want to show the last 50 messages, ordered most-recent-last
messages = reversed(room.messages.order_by('-timestamp')[:50])
return render(request, "chat/room.html", {
'room': room,
'messages': messages
})
| {
"content_hash": "e0bf6cc79d1663cf3215194d76ffd5ef",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 76,
"avg_line_length": 27.204545454545453,
"alnum_prop": 0.6641604010025063,
"repo_name": "antoniocarlosortiz/django-channels-chat",
"id": "55ca0e15eb2fd00848642728ed0e00afb334c03a",
"size": "1197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chat/rooms/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11549"
},
{
"name": "HTML",
"bytes": "4042"
},
{
"name": "Python",
"bytes": "17182"
}
],
"symlink_target": ""
} |
package it.prisma.domain.dsl.accounting.workgroups;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({ "workgroupId", "memberUserAccountId",
"workgroupPrivilege", "approved", "approvedByUserAccountId" })
public class WorkgroupMembershipRepresentation implements java.io.Serializable {
@JsonProperty("workgroupId")
private Long workgroupId;
@JsonProperty("memberUserAccountId")
private Long memberUserAccountId;
@JsonProperty("workgroupPrivilege")
private WorkgroupPrivilegeRepresentation workgroupPrivilege;
@JsonProperty("approved")
private Boolean approved;
@JsonProperty("approvedByUserAccountId")
private Long approvedByUserAccountId;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return The workgroupId
*/
@JsonProperty("workgroupId")
public Long getWorkgroupId() {
return workgroupId;
}
/**
*
* @param workgroupId
* The workgroupId
*/
@JsonProperty("workgroupId")
public void setWorkgroupId(Long workgroupId) {
this.workgroupId = workgroupId;
}
/**
*
* @return The memberUserAccountId
*/
@JsonProperty("memberUserAccountId")
public Long getMemberUserAccountId() {
return memberUserAccountId;
}
/**
*
* @param memberUserAccountId
* The memberUserAccountId
*/
@JsonProperty("memberUserAccountId")
public void setMemberUserAccountId(Long memberUserAccountId) {
this.memberUserAccountId = memberUserAccountId;
}
/**
*
* @return The workgroupPrivilege
*/
@JsonProperty("workgroupPrivilege")
public WorkgroupPrivilegeRepresentation getWorkgroupPrivilege() {
return workgroupPrivilege;
}
/**
*
* @param workgroupPrivilege
* The workgroupPrivilege
*/
@JsonProperty("workgroupPrivilege")
public void setWorkgroupPrivilege(
WorkgroupPrivilegeRepresentation workgroupPrivilege) {
this.workgroupPrivilege = workgroupPrivilege;
}
/**
*
* @return The approved
*/
@JsonProperty("approved")
public Boolean getApproved() {
return approved;
}
/**
*
* @param approved
* The approved
*/
@JsonProperty("approved")
public void setApproved(Boolean approved) {
this.approved = approved;
}
/**
*
* @return The approvedByUserAccountId
*/
@JsonProperty("approvedByUserAccountId")
public Long getApprovedByUserAccountId() {
return approvedByUserAccountId;
}
/**
*
* @param approvedByUserAccountId
* The approvedByUserAccountId
*/
@JsonProperty("approvedByUserAccountId")
public void setApprovedByUserAccountId(Long approvedByUserAccountId) {
this.approvedByUserAccountId = approvedByUserAccountId;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(workgroupId)
.append(memberUserAccountId).append(workgroupPrivilege)
.append(approved).append(approvedByUserAccountId)
.append(additionalProperties).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof WorkgroupMembershipRepresentation) == false) {
return false;
}
WorkgroupMembershipRepresentation rhs = ((WorkgroupMembershipRepresentation) other);
return new EqualsBuilder().append(workgroupId, rhs.workgroupId)
.append(memberUserAccountId, rhs.memberUserAccountId)
.append(workgroupPrivilege, rhs.workgroupPrivilege)
.append(approved, rhs.approved)
.append(approvedByUserAccountId, rhs.approvedByUserAccountId)
.append(additionalProperties, rhs.additionalProperties)
.isEquals();
}
}
| {
"content_hash": "a69f2485292f1072838fd24a4d1dde47",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 86,
"avg_line_length": 25.794285714285714,
"alnum_prop": 0.7574213557820115,
"repo_name": "pon-prisma/PrismaDemo",
"id": "ce485b97eec0b28aba46f369e15ff03fb9cc4350",
"size": "4514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Domain/src/main/java/it/prisma/domain/dsl/accounting/workgroups/WorkgroupMembershipRepresentation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "46806"
},
{
"name": "HTML",
"bytes": "1087968"
},
{
"name": "Java",
"bytes": "3591269"
},
{
"name": "JavaScript",
"bytes": "401870"
}
],
"symlink_target": ""
} |
using namespace bandit;
using namespace arg3::game;
go_bandit([]() {
describe("a script", []() {
it("can return values", []() {
npc temp;
temp.set_name("bob");
script script("return obj:name();");
script.push("obj", &temp);
script.execute();
string val = script.get_string(1);
Assert::That(val, Equals("bob"));
});
});
});
| {
"content_hash": "3b42edf3ac6f1e4d0419e34a57d1e839",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 48,
"avg_line_length": 15.857142857142858,
"alnum_prop": 0.4617117117117117,
"repo_name": "ryjen/arg3game",
"id": "2b7f4179f9ba846dc4699ffeac062f4911787702",
"size": "509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/script.test.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "88328"
},
{
"name": "C++",
"bytes": "182776"
},
{
"name": "CMake",
"bytes": "2543"
},
{
"name": "HTML",
"bytes": "3432"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.pinpoint.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.pinpoint.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetExportJobRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetExportJobRequestProtocolMarshaller implements Marshaller<Request<GetExportJobRequest>, GetExportJobRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/v1/apps/{application-id}/jobs/export/{job-id}").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonPinpoint").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetExportJobRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetExportJobRequest> marshall(GetExportJobRequest getExportJobRequest) {
if (getExportJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetExportJobRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
getExportJobRequest);
protocolMarshaller.startMarshalling();
GetExportJobRequestMarshaller.getInstance().marshall(getExportJobRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "6ee40f7119b1cdde5b150b8b7d4d0974",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 149,
"avg_line_length": 39.80769230769231,
"alnum_prop": 0.7555555555555555,
"repo_name": "aws/aws-sdk-java",
"id": "f9d77fd134fc4b4013e30f8122441865250205b3",
"size": "2650",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/transform/GetExportJobRequestProtocolMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef READ_ONLY_H
#define READ_ONLY_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* read_only.h
*/
/*
* The helper merely intercepts SET requests and handles them early on
* making everything read-only (no SETs are actually permitted).
* Useful as a helper to handlers that are implementing MIBs with no
* SET support.
*/
netsnmp_mib_handler *netsnmp_get_read_only_handler(void);
void netsnmp_init_read_only_helper(void);
Netsnmp_Node_Handler netsnmp_read_only_helper;
#ifdef __cplusplus
}
#endif
#endif
| {
"content_hash": "93a8c102af534c79f633b170332c1228",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 70,
"avg_line_length": 18.620689655172413,
"alnum_prop": 0.7,
"repo_name": "Kri-7-q/SnmpScanner",
"id": "41635b0e22357c0a214375d0acf0e380514faa35",
"size": "540",
"binary": false,
"copies": "44",
"ref": "refs/heads/master",
"path": "net-snmp-api/include/net-snmp/agent/read_only.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "660401"
},
{
"name": "C++",
"bytes": "46653"
},
{
"name": "Objective-C",
"bytes": "4054"
},
{
"name": "QMake",
"bytes": "798"
}
],
"symlink_target": ""
} |
package org.literacyapp.dao;
import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.SqlUtils;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import java.util.Calendar;
import org.literacyapp.dao.converter.CalendarConverter;
import org.literacyapp.model.Device;
import org.literacyapp.model.Student;
import org.literacyapp.model.analytics.AuthenticationEvent;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "AUTHENTICATION_EVENT".
*/
public class AuthenticationEventDao extends AbstractDao<AuthenticationEvent, Long> {
public static final String TABLENAME = "AUTHENTICATION_EVENT";
/**
* Properties of entity AuthenticationEvent.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property DeviceId = new Property(1, long.class, "deviceId", false, "DEVICE_ID");
public final static Property Time = new Property(2, long.class, "time", false, "TIME");
public final static Property StudentId = new Property(3, long.class, "studentId", false, "STUDENT_ID");
public final static Property IsFallback = new Property(4, boolean.class, "isFallback", false, "IS_FALLBACK");
}
private DaoSession daoSession;
private final CalendarConverter timeConverter = new CalendarConverter();
public AuthenticationEventDao(DaoConfig config) {
super(config);
}
public AuthenticationEventDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
this.daoSession = daoSession;
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"AUTHENTICATION_EVENT\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"DEVICE_ID\" INTEGER NOT NULL ," + // 1: deviceId
"\"TIME\" INTEGER NOT NULL ," + // 2: time
"\"STUDENT_ID\" INTEGER NOT NULL ," + // 3: studentId
"\"IS_FALLBACK\" INTEGER NOT NULL );"); // 4: isFallback
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"AUTHENTICATION_EVENT\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, AuthenticationEvent entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindLong(2, entity.getDeviceId());
stmt.bindLong(3, timeConverter.convertToDatabaseValue(entity.getTime()));
stmt.bindLong(4, entity.getStudentId());
stmt.bindLong(5, entity.getIsFallback() ? 1L: 0L);
}
@Override
protected final void bindValues(SQLiteStatement stmt, AuthenticationEvent entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindLong(2, entity.getDeviceId());
stmt.bindLong(3, timeConverter.convertToDatabaseValue(entity.getTime()));
stmt.bindLong(4, entity.getStudentId());
stmt.bindLong(5, entity.getIsFallback() ? 1L: 0L);
}
@Override
protected final void attachEntity(AuthenticationEvent entity) {
super.attachEntity(entity);
entity.__setDaoSession(daoSession);
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public AuthenticationEvent readEntity(Cursor cursor, int offset) {
AuthenticationEvent entity = new AuthenticationEvent( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getLong(offset + 1), // deviceId
timeConverter.convertToEntityProperty(cursor.getLong(offset + 2)), // time
cursor.getLong(offset + 3), // studentId
cursor.getShort(offset + 4) != 0 // isFallback
);
return entity;
}
@Override
public void readEntity(Cursor cursor, AuthenticationEvent entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setDeviceId(cursor.getLong(offset + 1));
entity.setTime(timeConverter.convertToEntityProperty(cursor.getLong(offset + 2)));
entity.setStudentId(cursor.getLong(offset + 3));
entity.setIsFallback(cursor.getShort(offset + 4) != 0);
}
@Override
protected final Long updateKeyAfterInsert(AuthenticationEvent entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(AuthenticationEvent entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(AuthenticationEvent entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
private String selectDeep;
protected String getSelectDeep() {
if (selectDeep == null) {
StringBuilder builder = new StringBuilder("SELECT ");
SqlUtils.appendColumns(builder, "T", getAllColumns());
builder.append(',');
SqlUtils.appendColumns(builder, "T0", daoSession.getDeviceDao().getAllColumns());
builder.append(',');
SqlUtils.appendColumns(builder, "T1", daoSession.getStudentDao().getAllColumns());
builder.append(" FROM AUTHENTICATION_EVENT T");
builder.append(" LEFT JOIN DEVICE T0 ON T.\"DEVICE_ID\"=T0.\"_id\"");
builder.append(" LEFT JOIN STUDENT T1 ON T.\"STUDENT_ID\"=T1.\"_id\"");
builder.append(' ');
selectDeep = builder.toString();
}
return selectDeep;
}
protected AuthenticationEvent loadCurrentDeep(Cursor cursor, boolean lock) {
AuthenticationEvent entity = loadCurrent(cursor, 0, lock);
int offset = getAllColumns().length;
Device device = loadCurrentOther(daoSession.getDeviceDao(), cursor, offset);
if(device != null) {
entity.setDevice(device);
}
offset += daoSession.getDeviceDao().getAllColumns().length;
Student student = loadCurrentOther(daoSession.getStudentDao(), cursor, offset);
if(student != null) {
entity.setStudent(student);
}
return entity;
}
public AuthenticationEvent loadDeep(Long key) {
assertSinglePk();
if (key == null) {
return null;
}
StringBuilder builder = new StringBuilder(getSelectDeep());
builder.append("WHERE ");
SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
String sql = builder.toString();
String[] keyArray = new String[] { key.toString() };
Cursor cursor = db.rawQuery(sql, keyArray);
try {
boolean available = cursor.moveToFirst();
if (!available) {
return null;
} else if (!cursor.isLast()) {
throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
}
return loadCurrentDeep(cursor, true);
} finally {
cursor.close();
}
}
/** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
public List<AuthenticationEvent> loadAllDeepFromCursor(Cursor cursor) {
int count = cursor.getCount();
List<AuthenticationEvent> list = new ArrayList<AuthenticationEvent>(count);
if (cursor.moveToFirst()) {
if (identityScope != null) {
identityScope.lock();
identityScope.reserveRoom(count);
}
try {
do {
list.add(loadCurrentDeep(cursor, false));
} while (cursor.moveToNext());
} finally {
if (identityScope != null) {
identityScope.unlock();
}
}
}
return list;
}
protected List<AuthenticationEvent> loadDeepAllAndCloseCursor(Cursor cursor) {
try {
return loadAllDeepFromCursor(cursor);
} finally {
cursor.close();
}
}
/** A raw-style query where you can pass any WHERE clause and arguments. */
public List<AuthenticationEvent> queryDeep(String where, String... selectionArg) {
Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
return loadDeepAllAndCloseCursor(cursor);
}
}
| {
"content_hash": "102e18708dc2bcb64df3f4daacede025",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 117,
"avg_line_length": 36.40926640926641,
"alnum_prop": 0.6200424178154825,
"repo_name": "schaemik/literacyapp-android",
"id": "55555cc6615e06ca2120a94f149c5268eeb2924d",
"size": "9430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/org/literacyapp/dao/AuthenticationEventDao.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1459334"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of CCONJ in UD_Icelandic-PUD</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/is_pud/is_pud-pos-CCONJ.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_icelandic-pud-pos-tags-cconj">Treebank Statistics: UD_Icelandic-PUD: POS Tags: <code class="language-plaintext highlighter-rouge">CCONJ</code></h2>
<p>There are 8 <code class="language-plaintext highlighter-rouge">CCONJ</code> lemmas (0%), 8 <code class="language-plaintext highlighter-rouge">CCONJ</code> types (0%) and 692 <code class="language-plaintext highlighter-rouge">CCONJ</code> tokens (4%).
Out of 17 observed tags, the rank of <code class="language-plaintext highlighter-rouge">CCONJ</code> is: 11 in number of lemmas, 13 in number of types and 11 in number of tokens.</p>
<p>The 10 most frequent <code class="language-plaintext highlighter-rouge">CCONJ</code> lemmas: <em>og, en, eða, bæði, heldur, annaðhvort, enda, né</em></p>
<p>The 10 most frequent <code class="language-plaintext highlighter-rouge">CCONJ</code> types: <em>og, en, eða, bæði, heldur, annaðhvort, enda, né</em></p>
<p>The 10 most frequent ambiguous lemmas: <em>og</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 547, <tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 6, <tt><a href="is_pud-pos-ADV.html">ADV</a></tt> 1), <em>en</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 94, <tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 21), <em>eða</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 33, <tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 2), <em>bæði</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 7, <tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 1), <em>heldur</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 6, <tt><a href="is_pud-pos-VERB.html">VERB</a></tt> 1)</p>
<p>The 10 most frequent ambiguous types: <em>og</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 546, <tt><a href="is_pud-pos-ADV.html">ADV</a></tt> 1), <em>en</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 93, <tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 1), <em>bæði</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 7, <tt><a href="is_pud-pos-PRON.html">PRON</a></tt> 1), <em>heldur</em> (<tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 6, <tt><a href="is_pud-pos-VERB.html">VERB</a></tt> 2)</p>
<ul>
<li><em>og</em>
<ul>
<li><tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 546: <em>Það sem hún segir <b>og</b> það sem hún gerir , það — það er raunar ótrúlegt .</em></li>
<li><tt><a href="is_pud-pos-ADV.html">ADV</a></tt> 1: <em>Það var eins <b>og</b> hann sveiflaði boltanum fram og aftur á milli þriggja bolla á hvolfi .</em></li>
</ul>
</li>
<li><em>en</em>
<ul>
<li><tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 93: <em>Í dag er Khanzir ef til vill einmana svín , <b>en</b> hann er ekki alltaf einn .</em></li>
<li><tt><a href="is_pud-pos-SCONJ.html">SCONJ</a></tt> 1: <em>Þótt ljósmynd hafi verið birt í morgun segist lögreglan í B.C. enn hafa fleiri spurningar <b>en</b> svör um mann sem virðist vera heimilislaus og var ákærður fyrir að stinga og myrða unglingsstúlku í miðskólanum hennar í Abbotsford .</em></li>
</ul>
</li>
<li><em>bæði</em>
<ul>
<li><tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 7: <em>Meðal manna eru <b>bæði</b> karlar og konur ákafir söngvarar og tónlistarsköpun er að mestu samfélagsleg iðja .</em></li>
<li><tt><a href="is_pud-pos-PRON.html">PRON</a></tt> 1: <em>Eftir málamiðlunina gætti keisarinn og konungurinn Frans Jósef I vandlega að koma jafnt fram við <b>bæði</b> konungsdæmin sín .</em></li>
</ul>
</li>
<li><em>heldur</em>
<ul>
<li><tt><a href="is_pud-pos-CCONJ.html">CCONJ</a></tt> 6: <em>Þegar Millican dó gerðum við ráð fyrir að sjá ekki <b>heldur</b> hinn bilunargjarna og óstyrka Odi framar .</em></li>
<li><tt><a href="is_pud-pos-VERB.html">VERB</a></tt> 2: <em>„ Starf okkar <b>heldur</b> áfram í borgunum þar sem við höfum hafið starfsemi eða stöndum í framkvæmdum “ sagði Barratt .</em></li>
</ul>
</li>
</ul>
<h2 id="morphology">Morphology</h2>
<p>The form / lemma ratio of <code class="language-plaintext highlighter-rouge">CCONJ</code> is 1.000000 (the average of all parts of speech is 1.365967).</p>
<p>The 1st highest number of forms (1) was observed with the lemma “annaðhvort”: <em>annaðhvort</em>.</p>
<p>The 2nd highest number of forms (1) was observed with the lemma “bæði”: <em>bæði</em>.</p>
<p>The 3rd highest number of forms (1) was observed with the lemma “en”: <em>en</em>.</p>
<p><code class="language-plaintext highlighter-rouge">CCONJ</code> does not occur with any features.</p>
<h2 id="relations">Relations</h2>
<p><code class="language-plaintext highlighter-rouge">CCONJ</code> nodes are attached to their parents using 5 different relations: <tt><a href="is_pud-dep-cc.html">cc</a></tt> (637; 92% instances), <tt><a href="is_pud-dep-fixed.html">fixed</a></tt> (33; 5% instances), <tt><a href="is_pud-dep-mark.html">mark</a></tt> (19; 3% instances), <tt><a href="is_pud-dep-advmod.html">advmod</a></tt> (2; 0% instances), <tt><a href="is_pud-dep-case.html">case</a></tt> (1; 0% instances)</p>
<p>Parents of <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes belong to 9 different parts of speech: <tt><a href="is_pud-pos-VERB.html">VERB</a></tt> (251; 36% instances), <tt><a href="is_pud-pos-NOUN.html">NOUN</a></tt> (240; 35% instances), <tt><a href="is_pud-pos-PROPN.html">PROPN</a></tt> (86; 12% instances), <tt><a href="is_pud-pos-ADJ.html">ADJ</a></tt> (46; 7% instances), <tt><a href="is_pud-pos-ADV.html">ADV</a></tt> (40; 6% instances), <tt><a href="is_pud-pos-PRON.html">PRON</a></tt> (10; 1% instances), <tt><a href="is_pud-pos-ADP.html">ADP</a></tt> (9; 1% instances), <tt><a href="is_pud-pos-NUM.html">NUM</a></tt> (8; 1% instances), <tt><a href="is_pud-pos-AUX.html">AUX</a></tt> (2; 0% instances)</p>
<p>691 (100%) <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes are leaves.</p>
<p>0 (0%) <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes have one child.</p>
<p>1 (0%) <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes have two children.</p>
<p>The highest child degree of a <code class="language-plaintext highlighter-rouge">CCONJ</code> node is 2.</p>
<p>Children of <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes are attached using 1 different relations: <tt><a href="is_pud-dep-fixed.html">fixed</a></tt> (2; 100% instances)</p>
<p>Children of <code class="language-plaintext highlighter-rouge">CCONJ</code> nodes belong to 1 different parts of speech: <tt><a href="is_pud-pos-ADV.html">ADV</a></tt> (2; 100% instances)</p>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
| {
"content_hash": "19b852d2c02148f1f5ff7df6a90cab07",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 740,
"avg_line_length": 56.99103139013453,
"alnum_prop": 0.6332520261232197,
"repo_name": "UniversalDependencies/universaldependencies.github.io",
"id": "ff120ea3dd4ef555ee9bf3961f2e813c222f1775",
"size": "12831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "treebanks/is_pud/is_pud-pos-CCONJ.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64420"
},
{
"name": "HTML",
"bytes": "383191916"
},
{
"name": "JavaScript",
"bytes": "687350"
},
{
"name": "Perl",
"bytes": "7788"
},
{
"name": "Python",
"bytes": "21203"
},
{
"name": "Shell",
"bytes": "7253"
}
],
"symlink_target": ""
} |
package org.jnosql.artemis.graph.spi;
import org.jnosql.artemis.Database;
import org.jnosql.artemis.graph.BookRepository;
import org.jnosql.artemis.graph.GraphTemplate;
import org.jnosql.artemis.graph.cdi.CDIExtension;
import org.jnosql.artemis.graph.model.Book;
import org.jnosql.artemis.graph.model.Person;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
import static org.jnosql.artemis.DatabaseType.GRAPH;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(CDIExtension.class)
public class GraphConfigurationProducerExtensionTest {
@Inject
@Database(value = GRAPH, provider = "graphRepositoryMock")
private GraphTemplate managerMock;
@Inject
private GraphTemplate manager;
@Inject
@Database(value = GRAPH, provider = "graphRepositoryMock")
private BookRepository repositoryMock;
@Inject
@Database(value = GRAPH)
private BookRepository repository;
@Test
public void shouldInstance() {
assertNotNull(manager);
assertNotNull(managerMock);
}
@Test
public void shouldSave() {
Person personMock = managerMock.insert(Person.builder().withId(10L).build());
assertEquals(Long.valueOf(10L), personMock.getId());
}
@Test
public void shoudlInjectRepository() {
repositoryMock.save(Book.builder().withName("book").build());
assertNotNull(repository.findById("10"));
}
} | {
"content_hash": "f3de0089b7512d1c75b3aec7c7d0976d",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 85,
"avg_line_length": 27.24561403508772,
"alnum_prop": 0.7385705086928526,
"repo_name": "JNOSQL/artemis",
"id": "3f448fe63a8b784dc1b2e6593fe3f2f68a640f8e",
"size": "2134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "artemis-graph/src/test/java/org/jnosql/artemis/graph/spi/GraphConfigurationProducerExtensionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "689185"
}
],
"symlink_target": ""
} |
<?php
namespace App\Http\Controllers\Admin;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class MainController extends Controller
{
public function welcome()
{
return view('admin.main.welcome');
}
}
| {
"content_hash": "b184aa07d9f3e9a0ec4bb438f1d0b6fe",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 39,
"avg_line_length": 15.352941176470589,
"alnum_prop": 0.7586206896551724,
"repo_name": "cntnn11/cntnn11.com",
"id": "5c62279fbb2c857bcff80a5c53159e53ab4c5875",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Controllers/Admin/MainController.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "14689"
},
{
"name": "HTML",
"bytes": "202352"
},
{
"name": "JavaScript",
"bytes": "9350693"
},
{
"name": "PHP",
"bytes": "142637"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven</groupId>
<artifactId>maven</artifactId>
<version>4.0.0-alpha-3-SNAPSHOT</version>
</parent>
<artifactId>maven-xml-impl</artifactId>
<name>Maven XML Implementation</name>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-api-xml</artifactId>
<version>4.0.0-alpha-3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.eclipse.sisu</groupId>
<artifactId>org.eclipse.sisu.plexus</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>${plexusUtilsVersionEmbedded}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "5345f440bf057570d07a4a879f3099e8",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 204,
"avg_line_length": 36.68,
"alnum_prop": 0.727917121046892,
"repo_name": "apache/maven",
"id": "789126a1b09894c930c500d59d26e5c75fc3db67",
"size": "1834",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "maven-xml-impl/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8860"
},
{
"name": "HTML",
"bytes": "2379"
},
{
"name": "Java",
"bytes": "5615236"
},
{
"name": "Shell",
"bytes": "5741"
}
],
"symlink_target": ""
} |
package org.dashbuilder.common.client.widgets.slider.view;
import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.user.client.ui.Widget;
import org.dashbuilder.common.client.widgets.slider.presenter.Presenter;
import java.util.ArrayList;
/**
*
* @author kiouri
*
*/
public class SliderBarHorizontal extends SliderBar {
protected int barWidth, barHeight, dragTopPosition, scaleWidth;
protected int getBarHeight(){
barHeight = getH(drag.getElement());
for (int i = 0; i < orderedWidgets.size(); i++){
if (orderedWidgets.get(i) == scale){
barHeight = Math.max(barHeight, scaleSize);
} else {
barHeight = Math.max(barHeight, getH(orderedWidgets.get(i).getElement()));
}
}
barHeight = Math.max(barHeight, scaleSize);
return barHeight;
}
protected void ajustScaleSize(int widgetWidth){
scaleWidth = widgetWidth;
if (less != null) {
for (int i = 0; i < less.size(); i++) {
scaleWidth -= getW(less.get(i).getElement());
}
}
if (more != null) {
for (int i = 0; i < more.size(); i++) {
scaleWidth -= getW(more.get(i).getElement());
}
}
scale.setPixelSize(scaleWidth, scaleSize);
}
public int getAbsMaxLength() {
return scaleWidth - getW(drag.getElement());
}
public void drawScrollBar(int barWidth) {
absPanel.clear();
putWidgetsToAbsPanel();
initVariables(barWidth);
ajustScaleSize(barWidth);
this.setHeight(getBarHeight() + "px");
absPanel.setPixelSize(barWidth,getBarHeight());
placeWidgets(orderedWidgets);
absPanel.setWidgetPosition(drag, getScaleLeft(orderedWidgets), dragTopPosition);
}
protected void initVariables(int barWidth){
this.barWidth = barWidth;
startPosition = getScaleLeft(orderedWidgets);
dragTopPosition = (getBarHeight() - getH(drag.getElement()))/2;
}
protected int getScaleLeft(ArrayList<Widget> widgets){
int sPosition = 0;
for (int i = 0; i < widgets.size(); i++){
if (widgets.get(i) != scale){
sPosition += getW(widgets.get(i).getElement());
} else {
return sPosition;
}
}
return sPosition;
}
protected void placeWidgets(ArrayList<Widget> widgets){
int tmpPosition = 0;
int barHeight = getBarHeight();
for (int i = 0; i < widgets.size(); i++){
if (widgets.get(i) == scale){
absPanel.setWidgetPosition(widgets.get(i), tmpPosition, (barHeight - scaleSize)/2);
} else {
absPanel.setWidgetPosition(widgets.get(i), tmpPosition, (barHeight - getH(widgets.get(i).getElement()))/2);
}
tmpPosition += getW(widgets.get(i).getElement());
}
}
public void setDragPosition(int position){
position = startPosition + position;
absPanel.setWidgetPosition(drag, position, dragTopPosition );
}
public int getScaleTouchPosition(MouseEvent event) {
return event.getRelativeX(this.getElement()) - startPosition - getW(drag.getElement())/2;
}
public int getDragPosition() {
return absPanel.getWidgetLeft(drag) - startPosition;
}
/**
* Sets scale mark to scale
*/
public void putMark(Mark mark, int markPosition) {
int markY = (this.barHeight - mark.getMarkHeight()) / 2;
this.absPanel.add(mark, this.startPosition + markPosition + getW(drag.getElement())/2, markY);
}
public Presenter.Orientation getOrientation(){
return Presenter.Orientation.HORIZONTAL;
}
@Override
/**
* It is not possible to adjust height of horizontal sliderbar with help of this method.
* Height of horizontal sliderbar is automatically calculated on base of height of components which are included in widget
*/
public void setHeight(String height) {
super.setHeight(getBarHeight() + "px");
}
public void setWidth(int width) {
super.setWidth(width + "px");
if (isAttached()) {
presenter.setBarPixelSize(width);
presenter.processParams();
reDrawMarks();
setValue(getValue());
}
}
public void setScaleWidget(Widget scaleWidget, int scaleHeight){
super.setScaleWidget(scaleWidget, scaleHeight);
}
}
| {
"content_hash": "0c2adac1364d1f194249e367c0f827e1",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 126,
"avg_line_length": 28.792857142857144,
"alnum_prop": 0.684941701810965,
"repo_name": "cristianonicolai/dashbuilder",
"id": "6cef33a533b3b87bb2b2962559ac99da05959d09",
"size": "4031",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dashbuilder-client/dashbuilder-common-client/src/main/java/org/dashbuilder/common/client/widgets/slider/view/SliderBarHorizontal.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "117"
},
{
"name": "HTML",
"bytes": "21397"
},
{
"name": "Java",
"bytes": "2988090"
}
],
"symlink_target": ""
} |
package com.kwizzad.model.events;
import com.kwizzad.Util;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
public abstract class AEvent {
public final EEventType type;
public Date eventTimestamp;
public AEvent() {
this.type = EventLookup.get(getClass());
}
public void from(JSONObject o) throws JSONException {
if (o.isNull("eventTimestamp") == false)
eventTimestamp = Util.fromISO8601(o.getString("eventTimestamp"));
}
public void to(JSONObject o) throws JSONException {
if (eventTimestamp != null)
o.put("eventTimestamp", Util.toISO8601(eventTimestamp));
o.put("type", EventLookup.get(getClass()).key);
}
}
| {
"content_hash": "1001c1bfdf4aeaafaf31c85eb1680aeb",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 77,
"avg_line_length": 26.357142857142858,
"alnum_prop": 0.6720867208672087,
"repo_name": "kwizzad/kwizzad-android",
"id": "89a7a09ef4c3f48bdb736ece1fa103b9a519cb79",
"size": "738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/src/main/java/com/kwizzad/model/events/AEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "212442"
}
],
"symlink_target": ""
} |
/**!
* tippy.js v5.1.3
* (c) 2017-2019 atomiks
* MIT License
*/
var tippy = (function (Popper) {
'use strict';
Popper = Popper && Popper.hasOwnProperty('default') ? Popper['default'] : Popper;
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
var version = "5.1.3";
/**
* Triggers reflow
*/
function reflow(element) {
void element.offsetHeight;
}
/**
* Sets the innerHTML of an element
*/
function setInnerHTML(element, html) {
element[innerHTML()] = html;
}
/**
* Determines if the value is a reference element
*/
function isReferenceElement(value) {
return !!(value && value._tippy && value._tippy.reference === value);
}
/**
* Safe .hasOwnProperty check, for prototype-less objects
*/
function hasOwnProperty(obj, key) {
return {}.hasOwnProperty.call(obj, key);
}
/**
* Returns an array of elements based on the value
*/
function getArrayOfElements(value) {
if (isElement(value)) {
return [value];
}
if (isNodeList(value)) {
return arrayFrom(value);
}
if (Array.isArray(value)) {
return value;
}
return arrayFrom(document.querySelectorAll(value));
}
/**
* Returns a value at a given index depending on if it's an array or number
*/
function getValueAtIndexOrReturn(value, index, defaultValue) {
if (Array.isArray(value)) {
var v = value[index];
return v == null ? Array.isArray(defaultValue) ? defaultValue[index] : defaultValue : v;
}
return value;
}
/**
* Prevents errors from being thrown while accessing nested modifier objects
* in `popperOptions`
*/
function getModifier(obj, key) {
return obj && obj.modifiers && obj.modifiers[key];
}
/**
* Determines if the value is of type
*/
function isType(value, type) {
var str = {}.toString.call(value);
return str.indexOf('[object') === 0 && str.indexOf(type + "]") > -1;
}
/**
* Determines if the value is of type Element
*/
function isElement(value) {
return isType(value, 'Element');
}
/**
* Determines if the value is of type NodeList
*/
function isNodeList(value) {
return isType(value, 'NodeList');
}
/**
* Determines if the value is of type MouseEvent
*/
function isMouseEvent(value) {
return isType(value, 'MouseEvent');
}
/**
* Firefox extensions don't allow setting .innerHTML directly, this will trick
* it
*/
function innerHTML() {
return 'innerHTML';
}
/**
* Evaluates a function if one, or returns the value
*/
function invokeWithArgsOrReturn(value, args) {
return typeof value === 'function' ? value.apply(void 0, args) : value;
}
/**
* Sets a popperInstance modifier's property to a value
*/
function setModifierValue(modifiers, name, property, value) {
modifiers.filter(function (m) {
return m.name === name;
})[0][property] = value;
}
/**
* Returns a new `div` element
*/
function div() {
return document.createElement('div');
}
/**
* Applies a transition duration to a list of elements
*/
function setTransitionDuration(els, value) {
els.forEach(function (el) {
if (el) {
el.style.transitionDuration = value + "ms";
}
});
}
/**
* Sets the visibility state to elements so they can begin to transition
*/
function setVisibilityState(els, state) {
els.forEach(function (el) {
if (el) {
el.setAttribute('data-state', state);
}
});
}
/**
* Debounce utility. To avoid bloating bundle size, we're only passing 1
* argument here, a more generic function would pass all arguments. Only
* `onMouseMove` uses this which takes the event object for now.
*/
function debounce(fn, ms) {
// Avoid wrapping in `setTimeout` if ms is 0 anyway
if (ms === 0) {
return fn;
}
var timeout;
return function (arg) {
clearTimeout(timeout);
timeout = setTimeout(function () {
fn(arg);
}, ms);
};
}
/**
* Preserves the original function invocation when another function replaces it
*/
function preserveInvocation(originalFn, currentFn, args) {
if (originalFn && originalFn !== currentFn) {
originalFn.apply(void 0, args);
}
}
/**
* Deletes properties from an object (pure)
*/
function removeProperties(obj, keys) {
var clone = _extends({}, obj);
keys.forEach(function (key) {
delete clone[key];
});
return clone;
}
/**
* Ponyfill for Array.from - converts iterable values to an array
*/
function arrayFrom(value) {
return [].slice.call(value);
}
/**
* Works like Element.prototype.closest, but uses a callback instead
*/
function closestCallback(element, callback) {
while (element) {
if (callback(element)) {
return element;
}
element = element.parentElement;
}
return null;
}
/**
* Determines if an array or string includes a string
*/
function includes(a, b) {
return a.indexOf(b) > -1;
}
/**
* Creates an array from string of values separated by whitespace
*/
function splitBySpaces(value) {
return value.split(/\s+/).filter(Boolean);
}
/**
* Returns the `nextValue` if `nextValue` is not `undefined`, otherwise returns
* `currentValue`
*/
function useIfDefined(nextValue, currentValue) {
return nextValue !== undefined ? nextValue : currentValue;
}
/**
* Converts a value that's an array or single value to an array
*/
function normalizeToArray(value) {
return [].concat(value);
}
/**
* Returns the ownerDocument of the first available element, otherwise global
* document
*/
function getOwnerDocument(elementOrElements) {
var _normalizeToArray = normalizeToArray(elementOrElements),
element = _normalizeToArray[0];
return element ? element.ownerDocument || document : document;
}
/**
* Adds item to array if array does not contain it
*/
function pushIfUnique(arr, value) {
if (arr.indexOf(value) === -1) {
arr.push(value);
}
}
/**
* Adds `px` if value is a number, or returns it directly
*/
function appendPxIfNumber(value) {
return typeof value === 'number' ? value + "px" : value;
}
/**
* Filters out duplicate elements in an array
*/
function unique(arr) {
return arr.filter(function (item, index) {
return arr.indexOf(item) === index;
});
}
/**
* Returns number from number or CSS units string
*/
function getNumber(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
/**
* Gets number or CSS string units in pixels (e.g. `1rem` -> 16)
*/
function getUnitsInPx(doc, value) {
var isRem = typeof value === 'string' && includes(value, 'rem');
var html = doc.documentElement;
var rootFontSize = 16;
if (html && isRem) {
return parseFloat(getComputedStyle(html).fontSize || String(rootFontSize)) * getNumber(value);
}
return getNumber(value);
}
/**
* Adds the `distancePx` value to the placement of a Popper.Padding object
*/
function getComputedPadding(basePlacement, padding, distancePx) {
if (padding === void 0) {
padding = 5;
}
var freshPaddingObject = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
var keys = Object.keys(freshPaddingObject);
return keys.reduce(function (obj, key) {
obj[key] = typeof padding === 'number' ? padding : padding[key];
if (basePlacement === key) {
obj[key] = typeof padding === 'number' ? padding + distancePx : padding[basePlacement] + distancePx;
}
return obj;
}, freshPaddingObject);
}
function createMemoryLeakWarning(method) {
var txt = method === 'destroy' ? 'n already-' : ' ';
return "\n " + method + "() was called on a" + txt + "destroyed instance. This is a no-op but\n indicates a potential memory leak.\n ";
}
function clean(value) {
var spacesAndTabs = /[ \t]{2,}/g;
var lineStartWithSpaces = /^[ \t]*/gm;
return value.replace(spacesAndTabs, ' ').replace(lineStartWithSpaces, '').trim();
}
function getDevMessage(message) {
return clean("\n %ctippy.js\n\n %c" + clean(message) + "\n\n %c\uD83D\uDC77\u200D This is a development-only message. It will be removed in production.\n ");
}
function getFormattedMessage(message) {
return [getDevMessage(message), // title
'color: #00C584; font-size: 1.3em; font-weight: bold;', // message
'line-height: 1.5', // footer
'color: #a6a095;'];
}
/**
* Helpful wrapper around `console.warn()`.
* TODO: Should we use a cache so it only warns a single time and not spam the
* console? (Need to consider hot reloading and invalidation though). Chrome
* already batches warnings as well.
*/
function warnWhen(condition, message) {
if (condition) {
var _console;
(_console = console).warn.apply(_console, getFormattedMessage(message));
}
}
/**
* Helpful wrapper around `console.error()`
*/
function errorWhen(condition, message) {
if (condition) {
var _console2;
(_console2 = console).error.apply(_console2, getFormattedMessage(message));
}
}
/**
* Validates the `targets` value passed to `tippy()`
*/
function validateTargets(targets) {
var didPassFalsyValue = !targets;
var didPassPlainObject = Object.prototype.toString.call(targets) === '[object Object]' && !targets.addEventListener;
errorWhen(didPassFalsyValue, ['tippy() was passed', '`' + String(targets) + '`', 'as its targets (first) argument. Valid types are: String, Element, Element[],', 'or NodeList.'].join(' '));
errorWhen(didPassPlainObject, ['tippy() was passed a plain object which is no longer supported as an argument.', 'See: https://atomiks.github.io/tippyjs/misc/#custom-position'].join(' '));
}
var pluginProps = {
animateFill: false,
followCursor: false,
inlinePositioning: false,
sticky: false
};
var defaultProps = _extends({
allowHTML: true,
animation: 'fade',
appendTo: function appendTo() {
return document.body;
},
aria: 'describedby',
arrow: true,
boundary: 'scrollParent',
content: '',
delay: 0,
distance: 10,
duration: [300, 250],
flip: true,
flipBehavior: 'flip',
flipOnUpdate: false,
hideOnClick: true,
ignoreAttributes: false,
inertia: false,
interactive: false,
interactiveBorder: 2,
interactiveDebounce: 0,
lazy: true,
maxWidth: 350,
multiple: false,
offset: 0,
onAfterUpdate: function onAfterUpdate() {},
onBeforeUpdate: function onBeforeUpdate() {},
onCreate: function onCreate() {},
onDestroy: function onDestroy() {},
onHidden: function onHidden() {},
onHide: function onHide() {},
onMount: function onMount() {},
onShow: function onShow() {},
onShown: function onShown() {},
onTrigger: function onTrigger() {},
onUntrigger: function onUntrigger() {},
placement: 'top',
plugins: [],
popperOptions: {},
role: 'tooltip',
showOnCreate: false,
theme: '',
touch: true,
trigger: 'mouseenter focus',
triggerTarget: null,
updateDuration: 0,
zIndex: 9999
}, pluginProps);
var defaultKeys = Object.keys(defaultProps);
/**
* If the setProps() method encounters one of these, the popperInstance must be
* recreated
*/
var POPPER_INSTANCE_DEPENDENCIES = ['arrow', 'boundary', 'distance', 'flip', 'flipBehavior', 'flipOnUpdate', 'offset', 'placement', 'popperOptions'];
/**
* Mutates the defaultProps object by setting the props specified
*/
var setDefaultProps = function setDefaultProps(partialProps) {
{
validateProps(partialProps, []);
}
var keys = Object.keys(partialProps);
keys.forEach(function (key) {
defaultProps[key] = partialProps[key];
});
};
/**
* Returns an extended props object including plugin props
*/
function getExtendedPassedProps(passedProps) {
var plugins = passedProps.plugins || [];
var pluginProps = plugins.reduce(function (acc, plugin) {
var name = plugin.name,
defaultValue = plugin.defaultValue;
if (name) {
acc[name] = passedProps[name] !== undefined ? passedProps[name] : defaultValue;
}
return acc;
}, {});
return _extends({}, passedProps, {}, pluginProps);
}
/**
* Returns an object of optional props from data-tippy-* attributes
*/
function getDataAttributeProps(reference, plugins) {
var propKeys = plugins ? Object.keys(getExtendedPassedProps(_extends({}, defaultProps, {
plugins: plugins
}))) : defaultKeys;
var props = propKeys.reduce(function (acc, key) {
var valueAsString = (reference.getAttribute("data-tippy-" + key) || '').trim();
if (!valueAsString) {
return acc;
}
if (key === 'content') {
acc[key] = valueAsString;
} else {
try {
acc[key] = JSON.parse(valueAsString);
} catch (e) {
acc[key] = valueAsString;
}
}
return acc;
}, {});
return props;
}
/**
* Evaluates the props object by merging data attributes and disabling
* conflicting props where necessary
*/
function evaluateProps(reference, props) {
var out = _extends({}, props, {
content: invokeWithArgsOrReturn(props.content, [reference])
}, props.ignoreAttributes ? {} : getDataAttributeProps(reference, props.plugins));
if (out.interactive) {
out.aria = null;
}
return out;
}
/**
* Validates props with the valid `defaultProps` object
*/
function validateProps(partialProps, plugins) {
if (partialProps === void 0) {
partialProps = {};
}
if (plugins === void 0) {
plugins = [];
}
var keys = Object.keys(partialProps);
keys.forEach(function (prop) {
var value = partialProps[prop];
var didSpecifyPlacementInPopperOptions = prop === 'popperOptions' && value !== null && typeof value === 'object' && hasOwnProperty(value, 'placement');
var nonPluginProps = removeProperties(defaultProps, ['animateFill', 'followCursor', 'inlinePositioning', 'sticky']); // These props have custom warnings
var customWarningProps = ['a11y', 'arrowType', 'showOnInit', 'size', 'target', 'touchHold'];
var didPassUnknownProp = !hasOwnProperty(nonPluginProps, prop) && !includes(customWarningProps, prop); // Check if the prop exists in `plugins`
if (didPassUnknownProp) {
didPassUnknownProp = plugins.filter(function (plugin) {
return plugin.name === prop;
}).length === 0;
}
warnWhen(prop === 'target', ['The `target` prop was removed in v5 and replaced with the delegate() addon', 'in order to conserve bundle size.', 'See: https://atomiks.github.io/tippyjs/addons/#event-delegation'].join(' '));
warnWhen(prop === 'a11y', ['The `a11y` prop was removed in v5. Make sure the element you are giving a', 'tippy to is natively focusable, such as <button> or <input>, not <div>', 'or <span>.'].join(' '));
warnWhen(prop === 'showOnInit', 'The `showOnInit` prop was renamed to `showOnCreate` in v5.');
warnWhen(prop === 'arrowType', ['The `arrowType` prop was removed in v5 in favor of overloading the `arrow`', 'prop.', '\n\n', '"round" string was replaced with importing the string from the package.', '\n\n', "* import {roundArrow} from 'tippy.js'; (ESM version)\n", '* const {roundArrow} = tippy; (IIFE CDN version)', '\n\n', 'Before: {arrow: true, arrowType: "round"}\n', 'After: {arrow: roundArrow}`'].join(' '));
warnWhen(prop === 'touchHold', ['The `touchHold` prop was removed in v5 in favor of overloading the `touch`', 'prop.', '\n\n', 'Before: {touchHold: true}\n', 'After: {touch: "hold"}'].join(' '));
warnWhen(prop === 'size', ['The `size` prop was removed in v5. Instead, use a theme that specifies', 'CSS padding and font-size properties.'].join(' '));
warnWhen(prop === 'theme' && value === 'google', 'The included theme "google" was renamed to "material" in v5.');
warnWhen(didSpecifyPlacementInPopperOptions, ['Specifying placement in `popperOptions` is not supported. Use the base-level', '`placement` prop instead.', '\n\n', 'Before: {popperOptions: {placement: "bottom"}}\n', 'After: {placement: "bottom"}'].join(' '));
warnWhen(didPassUnknownProp, ["`" + prop + "`", "is not a valid prop. You may have spelled it incorrectly, or if it's a", 'plugin, forgot to pass it in an array as props.plugins.', '\n\n', 'In v5, the following props were turned into plugins:', '\n\n', '* animateFill\n', '* followCursor\n', '* sticky', '\n\n', 'All props: https://atomiks.github.io/tippyjs/all-props/\n', 'Plugins: https://atomiks.github.io/tippyjs/plugins/'].join(' '));
});
}
var PASSIVE = {
passive: true
};
var ROUND_ARROW = '<svg viewBox="0 0 18 7" xmlns="http://www.w3.org/2000/svg"><path d="M0 7s2.021-.015 5.253-4.218C6.584 1.051 7.797.007 9 0c1.203-.007 2.416 1.035 3.761 2.782C16.012 7.005 18 7 18 7H0z"/></svg>';
var IOS_CLASS = "tippy-iOS";
var POPPER_CLASS = "tippy-popper";
var TOOLTIP_CLASS = "tippy-tooltip";
var CONTENT_CLASS = "tippy-content";
var BACKDROP_CLASS = "tippy-backdrop";
var ARROW_CLASS = "tippy-arrow";
var SVG_ARROW_CLASS = "tippy-svg-arrow";
var POPPER_SELECTOR = "." + POPPER_CLASS;
var TOOLTIP_SELECTOR = "." + TOOLTIP_CLASS;
var CONTENT_SELECTOR = "." + CONTENT_CLASS;
var ARROW_SELECTOR = "." + ARROW_CLASS;
var SVG_ARROW_SELECTOR = "." + SVG_ARROW_CLASS;
var currentInput = {
isTouch: false
};
var lastMouseMoveTime = 0;
/**
* When a `touchstart` event is fired, it's assumed the user is using touch
* input. We'll bind a `mousemove` event listener to listen for mouse input in
* the future. This way, the `isTouch` property is fully dynamic and will handle
* hybrid devices that use a mix of touch + mouse input.
*/
function onDocumentTouchStart() {
if (currentInput.isTouch) {
return;
}
currentInput.isTouch = true;
if (window.performance) {
document.addEventListener('mousemove', onDocumentMouseMove);
}
}
/**
* When two `mousemove` event are fired consecutively within 20ms, it's assumed
* the user is using mouse input again. `mousemove` can fire on touch devices as
* well, but very rarely that quickly.
*/
function onDocumentMouseMove() {
var now = performance.now();
if (now - lastMouseMoveTime < 20) {
currentInput.isTouch = false;
document.removeEventListener('mousemove', onDocumentMouseMove);
}
lastMouseMoveTime = now;
}
/**
* When an element is in focus and has a tippy, leaving the tab/window and
* returning causes it to show again. For mouse users this is unexpected, but
* for keyboard use it makes sense.
* TODO: find a better technique to solve this problem
*/
function onWindowBlur() {
var activeElement = document.activeElement;
if (isReferenceElement(activeElement)) {
var instance = activeElement._tippy;
if (activeElement.blur && !instance.state.isVisible) {
activeElement.blur();
}
}
}
/**
* Adds the needed global event listeners
*/
function bindGlobalEventListeners() {
document.addEventListener('touchstart', onDocumentTouchStart, _extends({}, PASSIVE, {
capture: true
}));
window.addEventListener('blur', onWindowBlur);
}
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var ua = isBrowser ? navigator.userAgent : '';
var isIE = /MSIE |Trident\//.test(ua);
var isUCBrowser = /UCBrowser\//.test(ua);
var isIOS = isBrowser && /iPhone|iPad|iPod/.test(navigator.platform);
function updateIOSClass(isAdd) {
var shouldAdd = isAdd && isIOS && currentInput.isTouch;
document.body.classList[shouldAdd ? 'add' : 'remove'](IOS_CLASS);
}
/**
* Returns the popper's placement, ignoring shifting (top-start, etc)
*/
function getBasePlacement(placement) {
return placement.split('-')[0];
}
/**
* Adds `data-inertia` attribute
*/
function addInertia(tooltip) {
tooltip.setAttribute('data-inertia', '');
}
/**
* Removes `data-inertia` attribute
*/
function removeInertia(tooltip) {
tooltip.removeAttribute('data-inertia');
}
/**
* Adds interactive-related attributes
*/
function addInteractive(tooltip) {
tooltip.setAttribute('data-interactive', '');
}
/**
* Removes interactive-related attributes
*/
function removeInteractive(tooltip) {
tooltip.removeAttribute('data-interactive');
}
/**
* Sets the content of a tooltip
*/
function setContent(contentEl, props) {
if (isElement(props.content)) {
setInnerHTML(contentEl, '');
contentEl.appendChild(props.content);
} else if (typeof props.content !== 'function') {
var key = props.allowHTML ? 'innerHTML' : 'textContent';
contentEl[key] = props.content;
}
}
/**
* Returns the child elements of a popper element
*/
function getChildren(popper) {
return {
tooltip: popper.querySelector(TOOLTIP_SELECTOR),
content: popper.querySelector(CONTENT_SELECTOR),
arrow: popper.querySelector(ARROW_SELECTOR) || popper.querySelector(SVG_ARROW_SELECTOR)
};
}
/**
* Creates an arrow element and returns it
*/
function createArrowElement(arrow) {
var arrowElement = div();
if (arrow === true) {
arrowElement.className = ARROW_CLASS;
} else {
arrowElement.className = SVG_ARROW_CLASS;
if (isElement(arrow)) {
arrowElement.appendChild(arrow);
} else {
setInnerHTML(arrowElement, arrow);
}
}
return arrowElement;
}
/**
* Constructs the popper element and returns it
*/
function createPopperElement(id, props) {
var popper = div();
popper.className = POPPER_CLASS;
popper.style.position = 'absolute';
popper.style.top = '0';
popper.style.left = '0';
var tooltip = div();
tooltip.className = TOOLTIP_CLASS;
tooltip.id = "tippy-" + id;
tooltip.setAttribute('data-state', 'hidden');
tooltip.setAttribute('tabindex', '-1');
updateTheme(tooltip, 'add', props.theme);
var content = div();
content.className = CONTENT_CLASS;
content.setAttribute('data-state', 'hidden');
if (props.interactive) {
addInteractive(tooltip);
}
if (props.arrow) {
tooltip.setAttribute('data-arrow', '');
tooltip.appendChild(createArrowElement(props.arrow));
}
if (props.inertia) {
addInertia(tooltip);
}
setContent(content, props);
tooltip.appendChild(content);
popper.appendChild(tooltip);
updatePopperElement(popper, props, props);
return popper;
}
/**
* Updates the popper element based on the new props
*/
function updatePopperElement(popper, prevProps, nextProps) {
var _getChildren = getChildren(popper),
tooltip = _getChildren.tooltip,
content = _getChildren.content,
arrow = _getChildren.arrow;
popper.style.zIndex = '' + nextProps.zIndex;
tooltip.setAttribute('data-animation', nextProps.animation);
tooltip.style.maxWidth = appendPxIfNumber(nextProps.maxWidth);
if (nextProps.role) {
tooltip.setAttribute('role', nextProps.role);
} else {
tooltip.removeAttribute('role');
}
if (prevProps.content !== nextProps.content) {
setContent(content, nextProps);
} // arrow
if (!prevProps.arrow && nextProps.arrow) {
// false to true
tooltip.appendChild(createArrowElement(nextProps.arrow));
tooltip.setAttribute('data-arrow', '');
} else if (prevProps.arrow && !nextProps.arrow) {
// true to false
tooltip.removeChild(arrow);
tooltip.removeAttribute('data-arrow');
} else if (prevProps.arrow !== nextProps.arrow) {
// true to 'round' or vice-versa
tooltip.removeChild(arrow);
tooltip.appendChild(createArrowElement(nextProps.arrow));
} // interactive
if (!prevProps.interactive && nextProps.interactive) {
addInteractive(tooltip);
} else if (prevProps.interactive && !nextProps.interactive) {
removeInteractive(tooltip);
} // inertia
if (!prevProps.inertia && nextProps.inertia) {
addInertia(tooltip);
} else if (prevProps.inertia && !nextProps.inertia) {
removeInertia(tooltip);
} // theme
if (prevProps.theme !== nextProps.theme) {
updateTheme(tooltip, 'remove', prevProps.theme);
updateTheme(tooltip, 'add', nextProps.theme);
}
}
/**
* Add/remove transitionend listener from tooltip
*/
function updateTransitionEndListener(tooltip, action, listener) {
var eventName = isUCBrowser && document.body.style.webkitTransition !== undefined ? 'webkitTransitionEnd' : 'transitionend';
tooltip[action + 'EventListener'](eventName, listener);
}
/**
* Adds/removes theme from tooltip's classList
*/
function updateTheme(tooltip, action, theme) {
splitBySpaces(theme).forEach(function (name) {
tooltip.classList[action](name + "-theme");
});
}
/**
* Determines if the mouse cursor is outside of the popper's interactive border
* region
*/
function isCursorOutsideInteractiveBorder(popperTreeData, event) {
var clientX = event.clientX,
clientY = event.clientY;
return popperTreeData.every(function (_ref) {
var popperRect = _ref.popperRect,
tooltipRect = _ref.tooltipRect,
interactiveBorder = _ref.interactiveBorder;
// Get min/max bounds of both the popper and tooltip rects due to
// `distance` offset
var mergedRect = {
top: Math.min(popperRect.top, tooltipRect.top),
right: Math.max(popperRect.right, tooltipRect.right),
bottom: Math.max(popperRect.bottom, tooltipRect.bottom),
left: Math.min(popperRect.left, tooltipRect.left)
};
var exceedsTop = mergedRect.top - clientY > interactiveBorder;
var exceedsBottom = clientY - mergedRect.bottom > interactiveBorder;
var exceedsLeft = mergedRect.left - clientX > interactiveBorder;
var exceedsRight = clientX - mergedRect.right > interactiveBorder;
return exceedsTop || exceedsBottom || exceedsLeft || exceedsRight;
});
}
var idCounter = 1;
var mouseMoveListeners = [];
/**
* Used by `hideAll()`
*/
var mountedInstances = [];
/**
* Creates and returns a Tippy object. We're using a closure pattern instead of
* a class so that the exposed object API is clean without private members
* prefixed with `_`.
*/
function createTippy(reference, passedProps) {
var props = evaluateProps(reference, _extends({}, defaultProps, {}, getExtendedPassedProps(passedProps))); // If the reference shouldn't have multiple tippys, return null early
if (!props.multiple && reference._tippy) {
return null;
}
/* ======================= 🔒 Private members 🔒 ======================= */
var showTimeout;
var hideTimeout;
var scheduleHideAnimationFrame;
var isBeingDestroyed = false;
var isVisibleFromClick = false;
var didHideDueToDocumentMouseDown = false;
var popperUpdates = 0;
var lastTriggerEvent;
var currentMountCallback;
var currentTransitionEndListener;
var listeners = [];
var debouncedOnMouseMove = debounce(onMouseMove, props.interactiveDebounce);
var currentTarget; // Support iframe contexts
// Static check that assumes any of the `triggerTarget` or `reference`
// nodes will never change documents, even when they are updated
var doc = getOwnerDocument(props.triggerTarget || reference);
/* ======================= 🔑 Public members 🔑 ======================= */
var id = idCounter++;
var popper = createPopperElement(id, props);
var popperChildren = getChildren(popper);
var popperInstance = null;
var plugins = unique(props.plugins); // These two elements are static
var tooltip = popperChildren.tooltip,
content = popperChildren.content;
var transitionableElements = [tooltip, content];
var state = {
// The current real placement (`data-placement` attribute)
currentPlacement: null,
// Is the instance currently enabled?
isEnabled: true,
// Is the tippy currently showing and not transitioning out?
isVisible: false,
// Has the instance been destroyed?
isDestroyed: false,
// Is the tippy currently mounted to the DOM?
isMounted: false,
// Has the tippy finished transitioning in?
isShown: false
};
var instance = {
// properties
id: id,
reference: reference,
popper: popper,
popperChildren: popperChildren,
popperInstance: popperInstance,
props: props,
state: state,
plugins: plugins,
// methods
clearDelayTimeouts: clearDelayTimeouts,
setProps: setProps,
setContent: setContent,
show: show,
hide: hide,
enable: enable,
disable: disable,
destroy: destroy
};
/* ==================== Initial instance mutations =================== */
reference._tippy = instance;
popper._tippy = instance;
var pluginsHooks = plugins.map(function (plugin) {
return plugin.fn(instance);
});
addListenersToTriggerTarget();
handleAriaExpandedAttribute();
if (!props.lazy) {
createPopperInstance();
}
invokeHook('onCreate', [instance]);
if (props.showOnCreate) {
scheduleShow();
} // Prevent a tippy with a delay from hiding if the cursor left then returned
// before it started hiding
popper.addEventListener('mouseenter', function () {
if (instance.props.interactive && instance.state.isVisible) {
instance.clearDelayTimeouts();
}
});
popper.addEventListener('mouseleave', function () {
if (instance.props.interactive && includes(instance.props.trigger, 'mouseenter')) {
doc.addEventListener('mousemove', debouncedOnMouseMove);
}
});
return instance;
/* ======================= 🔒 Private methods 🔒 ======================= */
function getNormalizedTouchSettings() {
var touch = instance.props.touch;
return Array.isArray(touch) ? touch : [touch, 0];
}
function getIsCustomTouchBehavior() {
return getNormalizedTouchSettings()[0] === 'hold';
}
function getCurrentTarget() {
return currentTarget || reference;
}
function getDelay(isShow) {
// For touch or keyboard input, force `0` delay for UX reasons
// Also if the instance is mounted but not visible (transitioning out),
// ignore delay
if (instance.state.isMounted && !instance.state.isVisible || currentInput.isTouch || lastTriggerEvent && lastTriggerEvent.type === 'focus') {
return 0;
}
return getValueAtIndexOrReturn(instance.props.delay, isShow ? 0 : 1, defaultProps.delay);
}
function invokeHook(hook, args, shouldInvokePropsHook) {
if (shouldInvokePropsHook === void 0) {
shouldInvokePropsHook = true;
}
pluginsHooks.forEach(function (pluginHooks) {
if (hasOwnProperty(pluginHooks, hook)) {
// @ts-ignore
pluginHooks[hook].apply(pluginHooks, args);
}
});
if (shouldInvokePropsHook) {
var _instance$props;
// @ts-ignore
(_instance$props = instance.props)[hook].apply(_instance$props, args);
}
}
function handleAriaDescribedByAttribute() {
var aria = instance.props.aria;
if (!aria) {
return;
}
var attr = "aria-" + aria;
var id = tooltip.id;
var nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach(function (node) {
var currentValue = node.getAttribute(attr);
if (instance.state.isVisible) {
node.setAttribute(attr, currentValue ? currentValue + " " + id : id);
} else {
var nextValue = currentValue && currentValue.replace(id, '').trim();
if (nextValue) {
node.setAttribute(attr, nextValue);
} else {
node.removeAttribute(attr);
}
}
});
}
function handleAriaExpandedAttribute() {
var nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach(function (node) {
if (instance.props.interactive) {
node.setAttribute('aria-expanded', instance.state.isVisible && node === getCurrentTarget() ? 'true' : 'false');
} else {
node.removeAttribute('aria-expanded');
}
});
}
function cleanupInteractiveMouseListeners() {
doc.body.removeEventListener('mouseleave', scheduleHide);
doc.removeEventListener('mousemove', debouncedOnMouseMove);
mouseMoveListeners = mouseMoveListeners.filter(function (listener) {
return listener !== debouncedOnMouseMove;
});
}
function onDocumentMouseDown(event) {
// Clicked on interactive popper
if (instance.props.interactive && popper.contains(event.target)) {
return;
} // Clicked on the event listeners target
if (getCurrentTarget().contains(event.target)) {
if (currentInput.isTouch) {
return;
}
if (instance.state.isVisible && includes(instance.props.trigger, 'click')) {
return;
}
}
if (instance.props.hideOnClick === true) {
isVisibleFromClick = false;
instance.clearDelayTimeouts();
instance.hide(); // `mousedown` event is fired right before `focus` if pressing the
// currentTarget. This lets a tippy with `focus` trigger know that it
// should not show
didHideDueToDocumentMouseDown = true;
setTimeout(function () {
didHideDueToDocumentMouseDown = false;
}); // The listener gets added in `scheduleShow()`, but this may be hiding it
// before it shows, and hide()'s early bail-out behavior can prevent it
// from being cleaned up
if (!instance.state.isMounted) {
removeDocumentMouseDownListener();
}
}
}
function addDocumentMouseDownListener() {
doc.addEventListener('mousedown', onDocumentMouseDown, true);
}
function removeDocumentMouseDownListener() {
doc.removeEventListener('mousedown', onDocumentMouseDown, true);
}
function onTransitionedOut(duration, callback) {
onTransitionEnd(duration, function () {
if (!instance.state.isVisible && popper.parentNode && popper.parentNode.contains(popper)) {
callback();
}
});
}
function onTransitionedIn(duration, callback) {
onTransitionEnd(duration, callback);
}
function onTransitionEnd(duration, callback) {
function listener(event) {
if (event.target === tooltip && event.propertyName === 'visibility') {
updateTransitionEndListener(tooltip, 'remove', listener);
callback();
}
} // Make callback synchronous if duration is 0
// `transitionend` won't fire otherwise
if (duration === 0) {
return callback();
}
updateTransitionEndListener(tooltip, 'remove', currentTransitionEndListener);
updateTransitionEndListener(tooltip, 'add', listener);
currentTransitionEndListener = listener;
}
function on(eventType, handler, options) {
if (options === void 0) {
options = false;
}
var nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach(function (node) {
node.addEventListener(eventType, handler, options);
listeners.push({
node: node,
eventType: eventType,
handler: handler,
options: options
});
});
}
function addListenersToTriggerTarget() {
if (getIsCustomTouchBehavior()) {
on('touchstart', onTrigger, PASSIVE);
on('touchend', onMouseLeave, PASSIVE);
}
splitBySpaces(instance.props.trigger).forEach(function (eventType) {
if (eventType === 'manual') {
return;
}
on(eventType, onTrigger);
switch (eventType) {
case 'mouseenter':
on('mouseleave', onMouseLeave);
break;
case 'focus':
on(isIE ? 'focusout' : 'blur', onBlur);
break;
}
});
}
function removeListenersFromTriggerTarget() {
listeners.forEach(function (_ref) {
var node = _ref.node,
eventType = _ref.eventType,
handler = _ref.handler,
options = _ref.options;
node.removeEventListener(eventType, handler, options);
});
listeners = [];
}
function onTrigger(event) {
var shouldScheduleClickHide = false;
if (!instance.state.isEnabled || isEventListenerStopped(event) || didHideDueToDocumentMouseDown) {
return;
}
lastTriggerEvent = event;
currentTarget = event.currentTarget;
handleAriaExpandedAttribute();
if (!instance.state.isVisible && isMouseEvent(event)) {
// If scrolling, `mouseenter` events can be fired if the cursor lands
// over a new target, but `mousemove` events don't get fired. This
// causes interactive tooltips to get stuck open until the cursor is
// moved
mouseMoveListeners.forEach(function (listener) {
return listener(event);
});
} // Toggle show/hide when clicking click-triggered tooltips
if (event.type === 'click' && (!includes(instance.props.trigger, 'mouseenter') || isVisibleFromClick) && instance.props.hideOnClick !== false && instance.state.isVisible) {
shouldScheduleClickHide = true;
} else {
var _getNormalizedTouchSe = getNormalizedTouchSettings(),
value = _getNormalizedTouchSe[0],
duration = _getNormalizedTouchSe[1];
if (currentInput.isTouch && value === 'hold' && duration) {
// We can hijack the show timeout here, it will be cleared by
// `scheduleHide()` when necessary
showTimeout = setTimeout(function () {
scheduleShow(event);
}, duration);
} else {
scheduleShow(event);
}
}
if (event.type === 'click') {
isVisibleFromClick = !shouldScheduleClickHide;
}
if (shouldScheduleClickHide) {
scheduleHide(event);
}
}
function onMouseMove(event) {
var isCursorOverReferenceOrPopper = closestCallback(event.target, function (el) {
return el === reference || el === popper;
});
if (isCursorOverReferenceOrPopper) {
return;
}
var popperTreeData = arrayFrom(popper.querySelectorAll(POPPER_SELECTOR)).concat(popper).map(function (popper) {
var instance = popper._tippy;
var tooltip = instance.popperChildren.tooltip;
var interactiveBorder = instance.props.interactiveBorder;
return {
popperRect: popper.getBoundingClientRect(),
tooltipRect: tooltip.getBoundingClientRect(),
interactiveBorder: interactiveBorder
};
});
if (isCursorOutsideInteractiveBorder(popperTreeData, event)) {
cleanupInteractiveMouseListeners();
scheduleHide(event);
}
}
function onMouseLeave(event) {
if (isEventListenerStopped(event)) {
return;
}
if (instance.props.interactive) {
doc.body.addEventListener('mouseleave', scheduleHide);
doc.addEventListener('mousemove', debouncedOnMouseMove);
pushIfUnique(mouseMoveListeners, debouncedOnMouseMove);
return;
}
if (includes(instance.props.trigger, 'click') && isVisibleFromClick) {
return;
}
scheduleHide(event);
}
function onBlur(event) {
if (event.target !== getCurrentTarget()) {
return;
} // If focus was moved to within the popper
if (instance.props.interactive && event.relatedTarget && popper.contains(event.relatedTarget)) {
return;
}
scheduleHide(event);
}
function isEventListenerStopped(event) {
var supportsTouch = 'ontouchstart' in window;
var isTouchEvent = includes(event.type, 'touch');
var isCustomTouch = getIsCustomTouchBehavior();
return supportsTouch && currentInput.isTouch && isCustomTouch && !isTouchEvent || currentInput.isTouch && !isCustomTouch && isTouchEvent;
}
function createPopperInstance() {
var popperOptions = instance.props.popperOptions;
var arrow = instance.popperChildren.arrow;
var flipModifier = getModifier(popperOptions, 'flip');
var preventOverflowModifier = getModifier(popperOptions, 'preventOverflow');
var distancePx;
function applyMutations(data) {
var prevPlacement = instance.state.currentPlacement;
instance.state.currentPlacement = data.placement;
if (instance.props.flip && !instance.props.flipOnUpdate) {
if (data.flipped) {
instance.popperInstance.options.placement = data.placement;
}
setModifierValue(instance.popperInstance.modifiers, 'flip', 'enabled', false);
}
tooltip.setAttribute('data-placement', data.placement);
if (data.attributes['x-out-of-boundaries'] !== false) {
tooltip.setAttribute('data-out-of-boundaries', '');
} else {
tooltip.removeAttribute('data-out-of-boundaries');
}
var basePlacement = getBasePlacement(data.placement);
var isVerticalPlacement = includes(['top', 'bottom'], basePlacement);
var isSecondaryPlacement = includes(['bottom', 'right'], basePlacement); // Apply `distance` prop
tooltip.style.top = '0';
tooltip.style.left = '0';
tooltip.style[isVerticalPlacement ? 'top' : 'left'] = (isSecondaryPlacement ? 1 : -1) * distancePx + 'px'; // Careful not to cause an infinite loop here
// Fixes https://github.com/FezVrasta/popper.js/issues/784
if (prevPlacement && prevPlacement !== data.placement) {
instance.popperInstance.update();
}
}
var config = _extends({
eventsEnabled: false,
placement: instance.props.placement
}, popperOptions, {
modifiers: _extends({}, popperOptions && popperOptions.modifiers, {
// We can't use `padding` on the popper el because of these bugs when
// flipping from a vertical to horizontal placement or vice-versa,
// there is severe flickering.
// https://github.com/FezVrasta/popper.js/issues/720
// This workaround increases bundle size by 250B minzip unfortunately,
// due to need to custom compute the distance (since Popper rect does
// not get affected by the inner tooltip's distance offset)
tippyDistance: {
enabled: true,
order: 0,
fn: function fn(data) {
// `html` fontSize may change while `popperInstance` is alive
// e.g. on resize in media queries
distancePx = getUnitsInPx(doc, instance.props.distance);
var basePlacement = getBasePlacement(data.placement);
var computedPreventOverflowPadding = getComputedPadding(basePlacement, preventOverflowModifier && preventOverflowModifier.padding, distancePx);
var computedFlipPadding = getComputedPadding(basePlacement, flipModifier && flipModifier.padding, distancePx);
var instanceModifiers = instance.popperInstance.modifiers;
setModifierValue(instanceModifiers, 'preventOverflow', 'padding', computedPreventOverflowPadding);
setModifierValue(instanceModifiers, 'flip', 'padding', computedFlipPadding);
return data;
}
},
preventOverflow: _extends({
boundariesElement: instance.props.boundary
}, preventOverflowModifier),
flip: _extends({
enabled: instance.props.flip,
behavior: instance.props.flipBehavior
}, flipModifier),
arrow: _extends({
element: arrow,
enabled: !!arrow
}, getModifier(popperOptions, 'arrow')),
offset: _extends({
offset: instance.props.offset
}, getModifier(popperOptions, 'offset'))
}),
onCreate: function onCreate(data) {
applyMutations(data);
preserveInvocation(popperOptions && popperOptions.onCreate, config.onCreate, [data]);
runMountCallback();
},
onUpdate: function onUpdate(data) {
applyMutations(data);
preserveInvocation(popperOptions && popperOptions.onUpdate, config.onUpdate, [data]);
runMountCallback();
}
});
instance.popperInstance = new Popper(reference, popper, config);
}
function runMountCallback() {
// Only invoke currentMountCallback after 2 updates
// This fixes some bugs in Popper.js (TODO: aim for only 1 update)
if (popperUpdates === 0) {
popperUpdates++; // 1
instance.popperInstance.update();
} else if (currentMountCallback && popperUpdates === 1) {
popperUpdates++; // 2
reflow(popper);
currentMountCallback();
}
}
function mount() {
// The mounting callback (`currentMountCallback`) is only run due to a
// popperInstance update/create
popperUpdates = 0;
var appendTo = instance.props.appendTo;
var parentNode; // By default, we'll append the popper to the triggerTargets's parentNode so
// it's directly after the reference element so the elements inside the
// tippy can be tabbed to
// If there are clipping issues, the user can specify a different appendTo
// and ensure focus management is handled correctly manually
var node = getCurrentTarget();
if (instance.props.interactive && appendTo === defaultProps.appendTo || appendTo === 'parent') {
parentNode = node.parentNode;
} else {
parentNode = invokeWithArgsOrReturn(appendTo, [node]);
} // The popper element needs to exist on the DOM before its position can be
// updated as Popper.js needs to read its dimensions
if (!parentNode.contains(popper)) {
parentNode.appendChild(popper);
}
{
// Accessibility check
warnWhen(instance.props.interactive && appendTo === defaultProps.appendTo && node.nextElementSibling !== popper, ['Interactive tippy element may not be accessible via keyboard navigation', 'because it is not directly after the reference element in the DOM source', 'order.', '\n\n', 'Using a wrapper <div> or <span> tag around the reference element solves', 'this by creating a new parentNode context.', '\n\n', 'Specifying `appendTo: document.body` silences this warning, but it', 'assumes you are using a focus management solution to handle keyboard', 'navigation.', '\n\n', 'See: https://atomiks.github.io/tippyjs/accessibility/#interactivity'].join(' '));
}
setModifierValue(instance.popperInstance.modifiers, 'flip', 'enabled', instance.props.flip);
instance.popperInstance.enableEventListeners(); // Mounting callback invoked in `onUpdate`
instance.popperInstance.update();
}
function scheduleShow(event) {
instance.clearDelayTimeouts();
if (!instance.popperInstance) {
createPopperInstance();
}
if (event) {
invokeHook('onTrigger', [instance, event]);
}
addDocumentMouseDownListener();
var delay = getDelay(true);
if (delay) {
showTimeout = setTimeout(function () {
instance.show();
}, delay);
} else {
instance.show();
}
}
function scheduleHide(event) {
instance.clearDelayTimeouts();
invokeHook('onUntrigger', [instance, event]);
if (!instance.state.isVisible) {
removeDocumentMouseDownListener();
return;
}
var delay = getDelay(false);
if (delay) {
hideTimeout = setTimeout(function () {
if (instance.state.isVisible) {
instance.hide();
}
}, delay);
} else {
// Fixes a `transitionend` problem when it fires 1 frame too
// late sometimes, we don't want hide() to be called.
scheduleHideAnimationFrame = requestAnimationFrame(function () {
instance.hide();
});
}
}
/* ======================= 🔑 Public methods 🔑 ======================= */
function enable() {
instance.state.isEnabled = true;
}
function disable() {
// Disabling the instance should also hide it
// https://github.com/atomiks/tippy.js-react/issues/106
instance.hide();
instance.state.isEnabled = false;
}
function clearDelayTimeouts() {
clearTimeout(showTimeout);
clearTimeout(hideTimeout);
cancelAnimationFrame(scheduleHideAnimationFrame);
}
function setProps(partialProps) {
{
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('setProps'));
}
if (instance.state.isDestroyed) {
return;
}
{
validateProps(partialProps, plugins);
warnWhen(partialProps.plugins ? partialProps.plugins.length !== plugins.length || plugins.some(function (p, i) {
if (partialProps.plugins && partialProps.plugins[i]) {
return p !== partialProps.plugins[i];
} else {
return true;
}
}) : false, "Cannot update plugins");
}
invokeHook('onBeforeUpdate', [instance, partialProps]);
removeListenersFromTriggerTarget();
var prevProps = instance.props;
var nextProps = evaluateProps(reference, _extends({}, instance.props, {}, partialProps, {
ignoreAttributes: true
}));
nextProps.ignoreAttributes = useIfDefined(partialProps.ignoreAttributes, prevProps.ignoreAttributes);
instance.props = nextProps;
addListenersToTriggerTarget();
if (prevProps.interactiveDebounce !== nextProps.interactiveDebounce) {
cleanupInteractiveMouseListeners();
debouncedOnMouseMove = debounce(onMouseMove, nextProps.interactiveDebounce);
}
updatePopperElement(popper, prevProps, nextProps);
instance.popperChildren = getChildren(popper); // Ensure stale aria-expanded attributes are removed
if (prevProps.triggerTarget && !nextProps.triggerTarget) {
normalizeToArray(prevProps.triggerTarget).forEach(function (node) {
node.removeAttribute('aria-expanded');
});
} else if (nextProps.triggerTarget) {
reference.removeAttribute('aria-expanded');
}
handleAriaExpandedAttribute();
if (instance.popperInstance) {
if (POPPER_INSTANCE_DEPENDENCIES.some(function (prop) {
return hasOwnProperty(partialProps, prop) && partialProps[prop] !== prevProps[prop];
})) {
var currentReference = instance.popperInstance.reference;
instance.popperInstance.destroy();
createPopperInstance();
instance.popperInstance.reference = currentReference;
if (instance.state.isVisible) {
instance.popperInstance.enableEventListeners();
}
} else {
instance.popperInstance.update();
}
}
invokeHook('onAfterUpdate', [instance, partialProps]);
}
function setContent(content) {
instance.setProps({
content: content
});
}
function show(duration) {
if (duration === void 0) {
duration = getValueAtIndexOrReturn(instance.props.duration, 0, defaultProps.duration);
}
{
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('show'));
} // Early bail-out
var isAlreadyVisible = instance.state.isVisible;
var isDestroyed = instance.state.isDestroyed;
var isDisabled = !instance.state.isEnabled;
var isTouchAndTouchDisabled = currentInput.isTouch && !instance.props.touch;
if (isAlreadyVisible || isDestroyed || isDisabled || isTouchAndTouchDisabled) {
return;
} // Normalize `disabled` behavior across browsers.
// Firefox allows events on disabled elements, but Chrome doesn't.
// Using a wrapper element (i.e. <span>) is recommended.
if (getCurrentTarget().hasAttribute('disabled')) {
return;
}
if (!instance.popperInstance) {
createPopperInstance();
}
invokeHook('onShow', [instance], false);
if (instance.props.onShow(instance) === false) {
return;
}
addDocumentMouseDownListener();
popper.style.visibility = 'visible';
instance.state.isVisible = true; // Prevent a transition of the popper from its previous position and of the
// elements at a different placement
// Check if the tippy was fully unmounted before `show()` was called, to
// allow for smooth transition for `createSingleton()`
if (!instance.state.isMounted) {
setTransitionDuration(transitionableElements.concat(popper), 0);
}
currentMountCallback = function currentMountCallback() {
if (!instance.state.isVisible) {
return;
}
setTransitionDuration([popper], instance.props.updateDuration);
setTransitionDuration(transitionableElements, duration);
setVisibilityState(transitionableElements, 'visible');
handleAriaDescribedByAttribute();
handleAriaExpandedAttribute();
pushIfUnique(mountedInstances, instance);
updateIOSClass(true);
instance.state.isMounted = true;
invokeHook('onMount', [instance]);
onTransitionedIn(duration, function () {
instance.state.isShown = true;
invokeHook('onShown', [instance]);
});
};
mount();
}
function hide(duration) {
if (duration === void 0) {
duration = getValueAtIndexOrReturn(instance.props.duration, 1, defaultProps.duration);
}
{
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('hide'));
} // Early bail-out
var isAlreadyHidden = !instance.state.isVisible && !isBeingDestroyed;
var isDestroyed = instance.state.isDestroyed;
var isDisabled = !instance.state.isEnabled && !isBeingDestroyed;
if (isAlreadyHidden || isDestroyed || isDisabled) {
return;
}
invokeHook('onHide', [instance], false);
if (instance.props.onHide(instance) === false && !isBeingDestroyed) {
return;
}
removeDocumentMouseDownListener();
popper.style.visibility = 'hidden';
instance.state.isVisible = false;
instance.state.isShown = false;
setTransitionDuration(transitionableElements, duration);
setVisibilityState(transitionableElements, 'hidden');
handleAriaDescribedByAttribute();
handleAriaExpandedAttribute();
onTransitionedOut(duration, function () {
instance.popperInstance.disableEventListeners();
instance.popperInstance.options.placement = instance.props.placement;
popper.parentNode.removeChild(popper);
mountedInstances = mountedInstances.filter(function (i) {
return i !== instance;
});
if (mountedInstances.length === 0) {
updateIOSClass(false);
}
instance.state.isMounted = false;
invokeHook('onHidden', [instance]);
});
}
function destroy() {
{
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('destroy'));
}
if (instance.state.isDestroyed) {
return;
}
isBeingDestroyed = true;
instance.clearDelayTimeouts();
instance.hide(0);
removeListenersFromTriggerTarget();
delete reference._tippy;
if (instance.popperInstance) {
instance.popperInstance.destroy();
}
isBeingDestroyed = false;
instance.state.isDestroyed = true;
invokeHook('onDestroy', [instance]);
}
}
function tippy(targets, optionalProps,
/** @deprecated use Props.plugins */
plugins) {
if (optionalProps === void 0) {
optionalProps = {};
}
if (plugins === void 0) {
plugins = [];
}
plugins = defaultProps.plugins.concat(optionalProps.plugins || plugins);
{
validateTargets(targets);
validateProps(optionalProps, plugins);
}
bindGlobalEventListeners();
var passedProps = _extends({}, optionalProps, {
plugins: plugins
});
var elements = getArrayOfElements(targets);
{
var isSingleContentElement = isElement(passedProps.content);
var isMoreThanOneReferenceElement = elements.length > 1;
warnWhen(isSingleContentElement && isMoreThanOneReferenceElement, ['tippy() was passed an Element as the `content` prop, but more than one tippy', 'instance was created by this invocation. This means the content element will', 'only be appended to the last tippy instance.', '\n\n', 'Instead, pass the .innerHTML of the element, or use a function that returns a', 'cloned version of the element instead.', '\n\n', '1) content: element.innerHTML\n', '2) content: () => element.cloneNode(true)'].join(' '));
}
var instances = elements.reduce(function (acc, reference) {
var instance = reference && createTippy(reference, passedProps);
if (instance) {
acc.push(instance);
}
return acc;
}, []);
return isElement(targets) ? instances[0] : instances;
}
tippy.version = version;
tippy.defaultProps = defaultProps;
tippy.setDefaultProps = setDefaultProps;
tippy.currentInput = currentInput;
/**
* Hides all visible poppers on the document
*/
var hideAll = function hideAll(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
excludedReferenceOrInstance = _ref.exclude,
duration = _ref.duration;
mountedInstances.forEach(function (instance) {
var isExcluded = false;
if (excludedReferenceOrInstance) {
isExcluded = isReferenceElement(excludedReferenceOrInstance) ? instance.reference === excludedReferenceOrInstance : instance.popper === excludedReferenceOrInstance.popper;
}
if (!isExcluded) {
instance.hide(duration);
}
});
};
/**
* Re-uses a single tippy element for many different tippy instances.
* Replaces v4's `tippy.group()`.
*/
var createSingleton = function createSingleton(tippyInstances, optionalProps,
/** @deprecated use Props.plugins */
plugins) {
if (optionalProps === void 0) {
optionalProps = {};
}
if (plugins === void 0) {
plugins = [];
}
{
errorWhen(!Array.isArray(tippyInstances), ['The first argument passed to createSingleton() must be an array of tippy', 'instances. The passed value was', String(tippyInstances)].join(' '));
}
plugins = optionalProps.plugins || plugins;
tippyInstances.forEach(function (instance) {
instance.disable();
});
var userAria = _extends({}, defaultProps, {}, optionalProps).aria;
var currentAria;
var currentTarget;
var shouldSkipUpdate = false;
var references = tippyInstances.map(function (instance) {
return instance.reference;
});
var singleton = {
fn: function fn(instance) {
function handleAriaDescribedByAttribute(isShow) {
if (!currentAria) {
return;
}
var attr = "aria-" + currentAria;
if (isShow && !instance.props.interactive) {
currentTarget.setAttribute(attr, instance.popperChildren.tooltip.id);
} else {
currentTarget.removeAttribute(attr);
}
}
return {
onAfterUpdate: function onAfterUpdate(_, _ref) {
var aria = _ref.aria;
// Ensure `aria` for the singleton instance stays `null`, while
// changing the `userAria` value
if (aria !== undefined && aria !== userAria) {
if (!shouldSkipUpdate) {
userAria = aria;
} else {
shouldSkipUpdate = true;
instance.setProps({
aria: null
});
shouldSkipUpdate = false;
}
}
},
onDestroy: function onDestroy() {
tippyInstances.forEach(function (instance) {
instance.enable();
});
},
onMount: function onMount() {
handleAriaDescribedByAttribute(true);
},
onUntrigger: function onUntrigger() {
handleAriaDescribedByAttribute(false);
},
onTrigger: function onTrigger(_, event) {
var target = event.currentTarget;
var index = references.indexOf(target); // bail-out
if (target === currentTarget) {
return;
}
currentTarget = target;
currentAria = userAria;
if (instance.state.isVisible) {
handleAriaDescribedByAttribute(true);
}
instance.popperInstance.reference = target;
instance.setContent(tippyInstances[index].props.content);
}
};
}
};
return tippy(div(), _extends({}, optionalProps, {
plugins: [singleton].concat(plugins),
aria: null,
triggerTarget: references
}));
};
var BUBBLING_EVENTS_MAP = {
mouseover: 'mouseenter',
focusin: 'focus',
click: 'click'
};
/**
* Creates a delegate instance that controls the creation of tippy instances
* for child elements (`target` CSS selector).
*/
function delegate(targets, props,
/** @deprecated use Props.plugins */
plugins) {
if (plugins === void 0) {
plugins = [];
}
{
errorWhen(!(props && props.target), ['You must specity a `target` prop indicating a CSS selector string matching', 'the target elements that should receive a tippy.'].join(' '));
}
plugins = props.plugins || plugins;
var listeners = [];
var childTippyInstances = [];
var target = props.target;
var nativeProps = removeProperties(props, ['target']);
var parentProps = _extends({}, nativeProps, {
plugins: plugins,
trigger: 'manual'
});
var childProps = _extends({}, nativeProps, {
plugins: plugins,
showOnCreate: true
});
var returnValue = tippy(targets, parentProps);
var normalizedReturnValue = normalizeToArray(returnValue);
function onTrigger(event) {
if (!event.target) {
return;
}
var targetNode = event.target.closest(target);
if (!targetNode) {
return;
} // Get relevant trigger with fallbacks:
// 1. Check `data-tippy-trigger` attribute on target node
// 2. Fallback to `trigger` passed to `delegate()`
// 3. Fallback to `defaultProps.trigger`
var trigger = targetNode.getAttribute('data-tippy-trigger') || props.trigger || defaultProps.trigger; // Only create the instance if the bubbling event matches the trigger type
if (!includes(trigger, BUBBLING_EVENTS_MAP[event.type])) {
return;
}
var instance = tippy(targetNode, childProps);
if (instance) {
childTippyInstances = childTippyInstances.concat(instance);
}
}
function on(node, eventType, handler, options) {
if (options === void 0) {
options = false;
}
node.addEventListener(eventType, handler, options);
listeners.push({
node: node,
eventType: eventType,
handler: handler,
options: options
});
}
function addEventListeners(instance) {
var reference = instance.reference;
on(reference, 'mouseover', onTrigger);
on(reference, 'focusin', onTrigger);
on(reference, 'click', onTrigger);
}
function removeEventListeners() {
listeners.forEach(function (_ref) {
var node = _ref.node,
eventType = _ref.eventType,
handler = _ref.handler,
options = _ref.options;
node.removeEventListener(eventType, handler, options);
});
listeners = [];
}
function applyMutations(instance) {
var originalDestroy = instance.destroy;
instance.destroy = function (shouldDestroyChildInstances) {
if (shouldDestroyChildInstances === void 0) {
shouldDestroyChildInstances = true;
}
if (shouldDestroyChildInstances) {
childTippyInstances.forEach(function (instance) {
instance.destroy();
});
}
childTippyInstances = [];
removeEventListeners();
originalDestroy();
};
addEventListeners(instance);
}
normalizedReturnValue.forEach(applyMutations);
return returnValue;
}
var animateFill = {
name: 'animateFill',
defaultValue: false,
fn: function fn(instance) {
var _instance$popperChild = instance.popperChildren,
tooltip = _instance$popperChild.tooltip,
content = _instance$popperChild.content;
var backdrop = instance.props.animateFill && !isUCBrowser ? createBackdropElement() : null;
function addBackdropToPopperChildren() {
instance.popperChildren.backdrop = backdrop;
}
return {
onCreate: function onCreate() {
if (backdrop) {
addBackdropToPopperChildren();
tooltip.insertBefore(backdrop, tooltip.firstElementChild);
tooltip.setAttribute('data-animatefill', '');
tooltip.style.overflow = 'hidden';
instance.setProps({
animation: 'shift-away',
arrow: false
});
}
},
onMount: function onMount() {
if (backdrop) {
var transitionDuration = tooltip.style.transitionDuration;
var duration = Number(transitionDuration.replace('ms', '')); // The content should fade in after the backdrop has mostly filled the
// tooltip element. `clip-path` is the other alternative but is not
// well-supported and is buggy on some devices.
content.style.transitionDelay = Math.round(duration / 10) + "ms";
backdrop.style.transitionDuration = transitionDuration;
setVisibilityState([backdrop], 'visible'); // Warn if the stylesheets are not loaded
{
warnWhen(getComputedStyle(backdrop).position !== 'absolute', "The `tippy.js/dist/backdrop.css` stylesheet has not been\n imported!\n \n The `animateFill` plugin requires this stylesheet to work.");
warnWhen(getComputedStyle(tooltip).transform === 'none', "The `tippy.js/animations/shift-away.css` stylesheet has not\n been imported!\n \n The `animateFill` plugin requires this stylesheet to work.");
}
}
},
onShow: function onShow() {
if (backdrop) {
backdrop.style.transitionDuration = '0ms';
}
},
onHide: function onHide() {
if (backdrop) {
setVisibilityState([backdrop], 'hidden');
}
},
onAfterUpdate: function onAfterUpdate() {
// With this type of prop, it's highly unlikely it will be changed
// dynamically. We'll leave out the diff/update logic it to save bytes.
// `popperChildren` is assigned a new object onAfterUpdate
addBackdropToPopperChildren();
}
};
}
};
function createBackdropElement() {
var backdrop = div();
backdrop.className = BACKDROP_CLASS;
setVisibilityState([backdrop], 'hidden');
return backdrop;
}
var followCursor = {
name: 'followCursor',
defaultValue: false,
fn: function fn(instance) {
var reference = instance.reference,
popper = instance.popper;
var originalReference = null; // Support iframe contexts
// Static check that assumes any of the `triggerTarget` or `reference`
// nodes will never change documents, even when they are updated
var doc = getOwnerDocument(instance.props.triggerTarget || reference); // Internal state
var lastMouseMoveEvent;
var mouseCoords = null;
var isInternallySettingControlledProp = false; // These are controlled by this plugin, so we need to store the user's
// original prop value
var userProps = instance.props;
function setUserProps(props) {
var keys = Object.keys(props);
keys.forEach(function (prop) {
userProps[prop] = useIfDefined(props[prop], userProps[prop]);
});
}
function getIsManual() {
return instance.props.trigger.trim() === 'manual';
}
function getIsEnabled() {
// #597
var isValidMouseEvent = getIsManual() ? true : // Check if a keyboard "click"
mouseCoords !== null && !(mouseCoords.clientX === 0 && mouseCoords.clientY === 0);
return instance.props.followCursor && isValidMouseEvent;
}
function getIsInitialBehavior() {
return currentInput.isTouch || instance.props.followCursor === 'initial' && instance.state.isVisible;
}
function resetReference() {
if (instance.popperInstance && originalReference) {
instance.popperInstance.reference = originalReference;
}
}
function handlePlacement() {
// Due to `getVirtualOffsets()`, we need to reverse the placement if it's
// shifted (start -> end, and vice-versa)
// Early bail-out
if (!getIsEnabled() && instance.props.placement === userProps.placement) {
return;
}
var placement = userProps.placement;
var shift = placement.split('-')[1];
isInternallySettingControlledProp = true;
instance.setProps({
placement: getIsEnabled() && shift ? placement.replace(shift, shift === 'start' ? 'end' : 'start') : placement
});
isInternallySettingControlledProp = false;
}
function handlePopperListeners() {
if (!instance.popperInstance) {
return;
} // Popper's scroll listeners make sense for `true` only. TODO: work out
// how to only listen horizontal scroll for "horizontal" and vertical
// scroll for "vertical"
if (getIsEnabled() && (getIsInitialBehavior() || instance.props.followCursor !== true)) {
instance.popperInstance.disableEventListeners();
}
}
function handleMouseMoveListener() {
if (getIsEnabled()) {
addListener();
} else {
resetReference();
}
}
function triggerLastMouseMove() {
if (getIsEnabled()) {
onMouseMove(lastMouseMoveEvent);
}
}
function addListener() {
doc.addEventListener('mousemove', onMouseMove);
}
function removeListener() {
doc.removeEventListener('mousemove', onMouseMove);
}
function onMouseMove(event) {
var _lastMouseMoveEvent = lastMouseMoveEvent = event,
clientX = _lastMouseMoveEvent.clientX,
clientY = _lastMouseMoveEvent.clientY;
if (!instance.popperInstance || !instance.state.currentPlacement) {
return;
} // If the instance is interactive, avoid updating the position unless it's
// over the reference element
var isCursorOverReference = closestCallback(event.target, function (el) {
return el === reference;
});
var rect = reference.getBoundingClientRect();
var followCursor = instance.props.followCursor;
var isHorizontal = followCursor === 'horizontal';
var isVertical = followCursor === 'vertical';
var isVerticalPlacement = includes(['top', 'bottom'], getBasePlacement(instance.state.currentPlacement)); // The virtual reference needs some size to prevent itself from overflowing
var _getVirtualOffsets = getVirtualOffsets(popper, isVerticalPlacement),
size = _getVirtualOffsets.size,
x = _getVirtualOffsets.x,
y = _getVirtualOffsets.y;
if (isCursorOverReference || !instance.props.interactive) {
// Preserve custom position ReferenceObjects, which may not be the
// original targets reference passed as an argument
if (originalReference === null) {
originalReference = instance.popperInstance.reference;
}
instance.popperInstance.reference = {
referenceNode: reference,
// These `client` values don't get used by Popper.js if they are 0
clientWidth: 0,
clientHeight: 0,
getBoundingClientRect: function getBoundingClientRect() {
return {
width: isVerticalPlacement ? size : 0,
height: isVerticalPlacement ? 0 : size,
top: (isHorizontal ? rect.top : clientY) - y,
bottom: (isHorizontal ? rect.bottom : clientY) + y,
left: (isVertical ? rect.left : clientX) - x,
right: (isVertical ? rect.right : clientX) + x
};
}
};
instance.popperInstance.update();
}
if (getIsInitialBehavior()) {
removeListener();
}
}
return {
onAfterUpdate: function onAfterUpdate(_, partialProps) {
if (!isInternallySettingControlledProp) {
setUserProps(partialProps);
if (partialProps.placement) {
handlePlacement();
}
} // A new placement causes the popperInstance to be recreated
if (partialProps.placement) {
handlePopperListeners();
} // Wait for `.update()` to set `instance.state.currentPlacement` to
// the new placement
requestAnimationFrame(triggerLastMouseMove);
},
onMount: function onMount() {
triggerLastMouseMove();
handlePopperListeners();
},
onShow: function onShow() {
if (getIsManual()) {
// Since there's no trigger event to use, we have to use these as
// baseline coords
mouseCoords = {
clientX: 0,
clientY: 0
}; // Ensure `lastMouseMoveEvent` doesn't access any other properties
// of a MouseEvent here
lastMouseMoveEvent = mouseCoords;
handlePlacement();
handleMouseMoveListener();
}
},
onTrigger: function onTrigger(_, event) {
// Tapping on touch devices can trigger `mouseenter` then `focus`
if (mouseCoords) {
return;
}
if (isMouseEvent(event)) {
mouseCoords = {
clientX: event.clientX,
clientY: event.clientY
};
lastMouseMoveEvent = event;
}
handlePlacement();
handleMouseMoveListener();
},
onUntrigger: function onUntrigger() {
// If untriggered before showing (`onHidden` will never be invoked)
if (!instance.state.isVisible) {
removeListener();
mouseCoords = null;
}
},
onHidden: function onHidden() {
removeListener();
resetReference();
mouseCoords = null;
}
};
}
};
function getVirtualOffsets(popper, isVerticalPlacement) {
var size = isVerticalPlacement ? popper.offsetWidth : popper.offsetHeight;
return {
size: size,
x: isVerticalPlacement ? size : 0,
y: isVerticalPlacement ? 0 : size
};
}
// position. This will require the `followCursor` plugin's fixes for overflow
// due to using event.clientX/Y values. (normalizedPlacement, getVirtualOffsets)
var inlinePositioning = {
name: 'inlinePositioning',
defaultValue: false,
fn: function fn(instance) {
var reference = instance.reference;
function getIsEnabled() {
return !!instance.props.inlinePositioning;
}
return {
onHidden: function onHidden() {
if (getIsEnabled()) {
instance.popperInstance.reference = reference;
}
},
onShow: function onShow() {
if (!getIsEnabled()) {
return;
}
instance.popperInstance.reference = {
referenceNode: reference,
// These `client` values don't get used by Popper.js if they are 0
clientWidth: 0,
clientHeight: 0,
getBoundingClientRect: function getBoundingClientRect() {
return getInlineBoundingClientRect(instance.state.currentPlacement && getBasePlacement(instance.state.currentPlacement), reference.getBoundingClientRect(), arrayFrom(reference.getClientRects()));
}
};
}
};
}
};
function getInlineBoundingClientRect(currentBasePlacement, boundingRect, clientRects) {
// Not an inline element, or placement is not yet known
if (clientRects.length < 2 || currentBasePlacement === null) {
return boundingRect;
}
switch (currentBasePlacement) {
case 'top':
case 'bottom':
{
var firstRect = clientRects[0];
var lastRect = clientRects[clientRects.length - 1];
var isTop = currentBasePlacement === 'top';
var top = firstRect.top;
var bottom = lastRect.bottom;
var left = isTop ? firstRect.left : lastRect.left;
var right = isTop ? firstRect.right : lastRect.right;
var width = right - left;
var height = bottom - top;
return {
top: top,
bottom: bottom,
left: left,
right: right,
width: width,
height: height
};
}
case 'left':
case 'right':
{
var minLeft = Math.min.apply(Math, clientRects.map(function (rects) {
return rects.left;
}));
var maxRight = Math.max.apply(Math, clientRects.map(function (rects) {
return rects.right;
}));
var measureRects = clientRects.filter(function (rect) {
return currentBasePlacement === 'left' ? rect.left === minLeft : rect.right === maxRight;
});
var _top = measureRects[0].top;
var _bottom = measureRects[measureRects.length - 1].bottom;
var _left = minLeft;
var _right = maxRight;
var _width = _right - _left;
var _height = _bottom - _top;
return {
top: _top,
bottom: _bottom,
left: _left,
right: _right,
width: _width,
height: _height
};
}
default:
{
return boundingRect;
}
}
}
var sticky = {
name: 'sticky',
defaultValue: false,
fn: function fn(instance) {
var reference = instance.reference,
popper = instance.popper;
function getReference() {
return instance.popperInstance ? instance.popperInstance.reference : reference;
}
function shouldCheck(value) {
return instance.props.sticky === true || instance.props.sticky === value;
}
var prevRefRect = null;
var prevPopRect = null;
function updatePosition() {
var currentRefRect = shouldCheck('reference') ? getReference().getBoundingClientRect() : null;
var currentPopRect = shouldCheck('popper') ? popper.getBoundingClientRect() : null;
if (currentRefRect && areRectsDifferent(prevRefRect, currentRefRect) || currentPopRect && areRectsDifferent(prevPopRect, currentPopRect)) {
instance.popperInstance.update();
}
prevRefRect = currentRefRect;
prevPopRect = currentPopRect;
if (instance.state.isMounted) {
requestAnimationFrame(updatePosition);
}
}
return {
onMount: function onMount() {
if (instance.props.sticky) {
updatePosition();
}
}
};
}
};
function areRectsDifferent(rectA, rectB) {
if (rectA && rectB) {
return rectA.top !== rectB.top || rectA.right !== rectB.right || rectA.bottom !== rectB.bottom || rectA.left !== rectB.left;
}
return true;
}
tippy.setDefaultProps({
plugins: [animateFill, followCursor, inlinePositioning, sticky]
});
tippy.createSingleton = createSingleton;
tippy.delegate = delegate;
tippy.hideAll = hideAll;
tippy.roundArrow = ROUND_ARROW;
return tippy;
}(Popper));
//# sourceMappingURL=tippy.iife.js.map
| {
"content_hash": "3f7730afe3ac92049fce86004a08b990",
"timestamp": "",
"source": "github",
"line_count": 2569,
"max_line_length": 667,
"avg_line_length": 31.869209809264305,
"alnum_prop": 0.6197967559116669,
"repo_name": "cdnjs/cdnjs",
"id": "8a73b86696aef38869d340acc80ca361a41d592c",
"size": "81896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/tippy.js/5.1.3/tippy.iife.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
namespace orbit_vulkan_layer {
// This class provides a wrapper for calls directly into the Vulkan loader.
// It is used, such that we can fake the called Vulkan functions in the tests.
//
// Note: in most cases we use the function pointers returned by "GetDevice/InstanceProcAddr",
// which directly point to the implementation in the next layer or ICD. So most used Vulkan
// functions don't need to show up here.
// See `DispatchTable` and `VulkanLayerController`.
class VulkanWrapper {
public:
VkResult CallVkEnumerateInstanceExtensionProperties(const char* layer_name,
uint32_t* property_count,
VkExtensionProperties* properties) {
return vkEnumerateInstanceExtensionProperties(layer_name, property_count, properties);
}
};
} // namespace orbit_vulkan_layer
#endif // ORBIT_VULKAN_LAYER_VULKAN_WRAPPER_H_
| {
"content_hash": "faec69e5b70e73cb8151265c53a19bba",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 93,
"avg_line_length": 46.6,
"alnum_prop": 0.6845493562231759,
"repo_name": "google/orbit",
"id": "45d4ee632be0069ba37d461fd5aab6f75c1c243d",
"size": "1218",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/OrbitVulkanLayer/VulkanWrapper.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "220990"
},
{
"name": "C++",
"bytes": "7042919"
},
{
"name": "CMake",
"bytes": "185711"
},
{
"name": "Jupyter Notebook",
"bytes": "1930"
},
{
"name": "PowerShell",
"bytes": "6590"
},
{
"name": "Python",
"bytes": "241593"
},
{
"name": "Shell",
"bytes": "19524"
},
{
"name": "Starlark",
"bytes": "36414"
}
],
"symlink_target": ""
} |
Sample web service with Chicago Boss web framework
#### Quick Start
Prerequisites: Erlang and rebar
##### Build project
```bash
$ make
```
##### Start Server
```bash
$ ./init-dev.sh
````
Open
- [http://localhost:8001/primes/index/](http://localhost:8001/primes/index/)
- to view list of cached primes
- [http://localhost:8001/primes/index/37](http://localhost:8001/primes/index/37)
- to get response indicating whether 37 is prime
| {
"content_hash": "78939e6f6a43645c10176c99ae62c349",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 80,
"avg_line_length": 19.391304347826086,
"alnum_prop": 0.6883408071748879,
"repo_name": "ericdahl/cb-primes",
"id": "9c4611cdc155a4c8397c67d09aa35fd8da309c2b",
"size": "458",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Erlang",
"bytes": "13001"
},
{
"name": "Makefile",
"bytes": "1254"
},
{
"name": "Shell",
"bytes": "2299"
}
],
"symlink_target": ""
} |
// Type definitions for @node-red/registry 1.1
// Project: https://github.com/node-red/node-red/tree/master/packages/node_modules/%40node-red/registry, https://nodered.org/
// Definitions by: Alex Kaul <https://github.com/alexk111>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.1
import { EventEmitter } from 'events';
import { Request, Response, NextFunction, Express } from 'express';
import { Server as HttpsServer } from 'https';
import { LocalSettings } from '@node-red/runtime';
import * as util from '@node-red/util';
/**
* Omit Helper
* Typescript 3.5 includes this.
* TODO: Remove after March 2021, after
* the end of support for TS 3.4
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
declare const registry: registry.RegistryModule;
export = registry;
declare namespace registry {
interface RegistryModule {} // tslint:disable-line:no-empty-interface
interface NodeConstructor<TNode extends Node<TCred>, TNodeDef extends NodeDef, TCred> {
(this: TNode, nodeDef: TNodeDef): void;
}
interface NodeSetting<T> {
value: T;
exportable?: boolean;
}
type NodeSettings<TSets> = {
[K in keyof TSets]: NodeSetting<TSets[K]>;
};
interface NodeCredential {
type: 'text' | 'password';
}
type NodeCredentials<TCreds> = {
[K in keyof TCreds]: NodeCredential;
};
interface NodeAPINodes {
/**
* Registers a node constructor
* @param type - the string type name
* @param constructor - the constructor function for this node type
* @param opts - optional additional options for the node
*/
registerType<TNode extends Node<TCreds>, TNodeDef extends NodeDef, TSets, TCreds>(
type: string,
constructor: NodeConstructor<TNode, TNodeDef, TCreds>, // tslint:disable-line:no-unnecessary-generics
opts?: {
credentials?: NodeCredentials<TCreds>;
settings?: NodeSettings<TSets>; // tslint:disable-line:no-unnecessary-generics
},
): void;
/**
* Called from a Node's constructor function, invokes the super-class
* constructor and attaches any credentials to the node.
* @param node the node object being created
* @param def the instance definition for the node
*/
createNode(node: Node, def: NodeDef): void;
getNode(id: string): Node;
eachNode(cb: (node: NodeDef) => void): void;
/**
* Adds a set of credentials for the given node id.
* @param id the node id for the credentials
* @param creds an object of credential key/value pairs
* @returns a promise for backwards compatibility TODO: can this be removed?
*/
addCredentials(id: string, creds: object): Promise<void>;
/**
* Gets the credentials for the given node id.
* @param id the node id for the credentials
* @returns the credentials
*/
getCredentials(id: string): object;
/**
* Deletes the credentials for the given node id.
* @param id the node id for the credentials
*/
deleteCredentials(id: string): void;
}
interface NodeAPIComms {
publish(topic: string, data: any, retain: boolean): void;
}
interface NodeAPILibrary {
register(type: string): void;
}
type NodeApiLog = Omit<util.Log, 'init'>;
interface NodeAPISettings {
get(prop: string): any;
set(prop: string, value: any): Promise<void>;
delete(prop: string): Promise<void>;
available(): boolean;
registerNodeSettings(type: string, opts: object): void;
exportNodeSettings(safeSettings: object): object;
enableNodeSettings(types: string[]): void;
disableNodeSettings(types: string[]): void;
getUserSettings(username: string): void;
setUserSettings(username: string, settings: object): Promise<void>;
}
interface NodeAPISettingsWithData extends NodeAPISettings, LocalSettings {}
interface NodeAPIAuth {
/**
* Returns an Express middleware function that ensures the user making a request has the necessary permission.
*/
needsPermission(permission: string): (req: Request, res: Response, next: NextFunction) => void;
}
/**
* Runtime API provided to nodes by Node Registry
*/
interface NodeAPI<TSets extends NodeAPISettingsWithData = NodeAPISettingsWithData> {
nodes: NodeAPINodes;
log: NodeApiLog;
settings: TSets;
events: EventEmitter;
util: util.Util;
version(): Promise<string>;
require(id: string): any;
comms: NodeAPIComms;
library: NodeAPILibrary;
auth: NodeAPIAuth;
readonly httpNode: Express;
readonly httpAdmin: Express;
readonly server: HttpsServer;
_: util.I18nTFunction;
}
/**
* Function called by Node Registry to init node.
*/
interface NodeInitializer<TSets extends NodeAPISettingsWithData = NodeAPISettingsWithData> {
(RED: NodeAPI<TSets>): void | Promise<void>;
}
interface NodeMessage {
payload?: unknown;
_msgid?: string;
}
interface NodeMessageParts {
/** a unique identifier for the sequence */
id: string;
/** the message's position within the sequence */
index: number;
/** if known, the total number of messages in the sequence */
count?: number;
}
interface NodeMessageInFlow extends NodeMessage {
_msgid: string;
/**
* If there is a message sequence, then each message in a sequence has the ```parts``` property.
* More info: https://nodered.org/docs/user-guide/messages#understanding-msgparts
*/
parts?: NodeMessageParts;
}
interface Node<TCreds extends {} = {}> extends EventEmitter {
id: string;
type: string;
z: string;
name?: string;
credentials: TCreds;
/**
* Update the wiring configuration for this node.
* @param wires -the new wiring configuration
*/
updateWires(wires: Array<[]>): void;
/**
* Get the context object for this node.
* @returnsthe context object
*/
context(): NodeContext;
/**
* Called when the node is being stopped
* @param removed Whether the node has been removed, or just being stopped
* @returns Promises which resolves when the node has closed
*/
close(removed: boolean): Promise<void>;
/**
* Send a message to the nodes wired.
* @param msg A message or array of messages to send
*/
send(msg?: NodeMessage | NodeMessage[]): void;
/**
* Receive a message.
*
* This will emit the `input` event with the provided message.
* As of 1.0, this will return *before* any 'input' callback handler is invoked.
*/
receive(msg?: NodeMessage): void;
/**
* Log an INFO level message
*/
log(msg: any): void;
/**
* Log a WARN level message
*/
warn(msg: any): void;
/**
* Log an ERROR level message
*/
error(logMessage: any, msg?: NodeMessage): void;
/**
* Log an DEBUG level message
*/
debug(msg: any): void;
/**
* Log an TRACE level message
*/
trace(msg: any): void;
/**
* Log a metric event.
* If called with no args, returns whether metric collection is enabled
*/
metric(): boolean;
metric(eventname: string, msg: NodeMessage, metricValue: number): void;
/**
* Set the node's status object
*
* status: { fill:"red|green", shape:"dot|ring", text:"blah" }
* or
* status: "simple text status"
*/
status(status: string | NodeStatus): void;
/**
* Nodes register a listener on the input event to receive messages from the
* up-stream nodes in a flow.
* More info: https://nodered.org/docs/creating-nodes/node-js#receiving-messages
*/
on(
event: 'input',
listener: (
msg: NodeMessageInFlow,
send: (msg: NodeMessage | Array<NodeMessage | null>) => void,
done: (err?: Error) => void,
) => void,
): this;
/**
* Whenever a new flow is deployed, the existing nodes are deleted. If any of them
* need to tidy up state when this happens, such as disconnecting from a remote
* system, they should register a listener on the close event.
* More info: https://nodered.org/docs/creating-nodes/node-js#closing-the-node
*/
on(event: 'close', listener: () => void): this;
/**
* If the node needs to do any asynchronous work to complete the tidy up, the
* registered listener should accept an argument which is a function to be called
* when all the work is complete.
* More info: https://nodered.org/docs/creating-nodes/node-js#closing-the-node
*/
on(event: 'close', listener: (done: () => void) => void): this; // tslint:disable-line:unified-signatures
/**
* If the registered listener accepts two arguments, the first will be a boolean
* flag that indicates whether the node is being closed because it has been removed
* entirely, or that it is just being restarted.
* More info: https://nodered.org/docs/creating-nodes/node-js#closing-the-node
*/
on(event: 'close', listener: (removed: boolean, done: () => void) => void): this; // tslint:disable-line:unified-signatures
}
type NodeStatusFill = 'red' | 'green' | 'yellow' | 'blue' | 'grey';
type NodeStatusShape = 'ring' | 'dot';
interface NodeStatus {
fill?: NodeStatusFill;
shape?: NodeStatusShape;
text?: string;
}
/**
* Node Instance Definition Object
*/
interface NodeDef {
id: string;
type: string;
name: string;
z: string;
}
interface NodeContextData {
/**
* Get a value from context
* @param key
* @param storeName - store name when multiple context stores are used
*/
get(key: string, storeName?: string): unknown;
/**
* Get a value from context asynchronously
*/
get(key: string, cb: (err: Error, value: unknown) => void): void;
/**
* Get multiple values from context
* @param keys
* @param storeName - store name when multiple context stores are used
*/
get(keys: string[], storeName?: string): unknown[];
/**
* Get multiple values from context asynchronously
*/
get(keys: string[], cb: (err: Error, value: unknown[]) => void): void;
/**
* Get a value from context asynchronously, when multiple context stores are used
*/
get(key: string, storeName: string | undefined, cb: (err: Error, value: unknown) => void): void;
/**
* Get multiple values from context asynchronously, when multiple context stores are used
*/
get(keys: string[], storeName: string | undefined, cb: (err: Error, value: unknown[]) => void): void;
/**
* Set a value in context
* @param key
* @param value
* @param cb - callback for async calls
*/
set(key: string, value: unknown, cb?: (err: Error) => void): void;
/**
* Set multiple values in context
* @param keys
* @param values
* @param cb - callback for async calls
*/
set(keys: string[], values: unknown[], cb?: (err: Error) => void): void;
/**
* Set a value in context, when multiple context stores are used
* @param key
* @param value
* @param storeName
* @param cb - callback for async calls
*/
set(key: string, value: unknown, storeName: string | undefined, cb?: (err: Error) => void): void;
/**
* Set multiple values in context, when multiple context stores are used
* @param keys
* @param values
* @param storeName
* @param cb - callback for async calls
*/
set(keys: string[], values: unknown[], storeName: string | undefined, cb?: (err: Error) => void): void;
/**
* Returns a list of all node-scoped context property keys
* @param storeName - store name when multiple context stores are used
*/
keys(storeName?: string): string[];
/**
* Returns a list of all node-scoped context property keys asynchronously
*/
keys(cb: (err: Error, value: unknown[]) => void): void;
/**
* Returns a list of all node-scoped context property keys asynchronously, when multiple context stores are used
*/
keys(storeName: string | undefined, cb: (err: Error, value: unknown[]) => void): void;
}
interface NodeContext extends NodeContextData {
global: NodeContextData;
flow: NodeContextData;
}
}
| {
"content_hash": "0a9e03ac4389234d5e58221018400102",
"timestamp": "",
"source": "github",
"line_count": 381,
"max_line_length": 131,
"avg_line_length": 35.70866141732284,
"alnum_prop": 0.5861815509004042,
"repo_name": "mcliment/DefinitelyTyped",
"id": "ad149faec29d12d0c481e99aa673c6f9be6554ba",
"size": "13605",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "types/node-red__registry/index.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17214021"
}
],
"symlink_target": ""
} |
<?php
namespace Biblioteca\BibliotecaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Biblioteca\BibliotecaBundle\Entity\Resource;
use Biblioteca\BibliotecaBundle\Lib\Globals;
/**
* Documento
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Biblioteca\BibliotecaBundle\Entity\DocumentoRepository")
* @ORM\HasLifecycleCallbacks
*/
class Documento extends Resource
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="TDocumento", inversedBy="tipo")
* @ORM\JoinColumn(name="tipo_id", referencedColumnName="id")
*/
protected $tipo;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
public function getPath(){
if($this->recurso)
return 'uploads/Documentos/'.$this->getTipo().'/'.$this->getRecurso();
return null;
}
public function getUploadRootDir() {
return $this->getTmpUploadRootDir().$this->getTipo()."/";
}
public function getTmpUploadRootDir() {
return Globals::getUploadDir().'Documentos/';
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function uploadFile() {
parent::uploadFile();
}
/**
* @ORM\PostPersist()
*/
public function moveRecurso()
{
parent::moveRecurso();
}
/**
* @ORM\PreRemove()
*/
public function removeRecurso() {
parent::removeRecurso();
}
public function __toString() {
return $this->getRecurso();
}
/**
* Set tipo
*
* @param \Biblioteca\BibliotecaBundle\Entity\TDocumento $tipo
* @return Documento
*/
public function setTipo(\Biblioteca\BibliotecaBundle\Entity\TDocumento $tipo = null)
{
$this->tipo = $tipo;
return $this;
}
/**
* Get tipo
*
* @return \Biblioteca\BibliotecaBundle\Entity\TDocumento
*/
public function getTipo()
{
return $this->tipo;
}
} | {
"content_hash": "81050165b9d377684dcba223c94e4d79",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 90,
"avg_line_length": 20.69811320754717,
"alnum_prop": 0.5651777575205105,
"repo_name": "CondeMonteCristo/biblioteca",
"id": "09787df9cb706fd75a70f8a5ee3515ec41e85262",
"size": "2194",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Biblioteca/BibliotecaBundle/Entity/Documento.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "239"
},
{
"name": "CSS",
"bytes": "189250"
},
{
"name": "HTML",
"bytes": "1247235"
},
{
"name": "JavaScript",
"bytes": "3564764"
},
{
"name": "PHP",
"bytes": "318521"
},
{
"name": "Shell",
"bytes": "1345"
}
],
"symlink_target": ""
} |
package io.hentitydb.serialization;
/**
* A {@link Codec} implementation which stores longs as variable-length encoded bytes.
*/
public class VarLongCodec extends AbstractCodec<Long> {
@Override
public int expectedSize(Long value) {
return 9;
}
@Override
public void encode(Long value, WriteBuffer buffer) {
buffer.writeVarLong(value);
}
@Override
public Long decode(ReadBuffer buffer) {
return buffer.readVarLong();
}
}
| {
"content_hash": "8ce82eafe9bd3d1461eaf5bed59ed2cb",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 86,
"avg_line_length": 23.142857142857142,
"alnum_prop": 0.6728395061728395,
"repo_name": "rayokota/hentitydb",
"id": "4bd81c0c3dbd5d28261f68d9a4551c8822a1545d",
"size": "486",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/hentitydb/serialization/VarLongCodec.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "551279"
}
],
"symlink_target": ""
} |
"""
Urls for herald app
"""
from django.conf.urls import url
from .views import TestNotificationList, TestNotification
urlpatterns = [
url(r'^$', TestNotificationList.as_view(), name='herald_preview_list'),
url(r'^(?P<index>\d+)/(?P<type>[\w\-]+)/$', TestNotification.as_view(), name='herald_preview'),
]
| {
"content_hash": "893151bd8e94ba5896b8c210b14c683f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 99,
"avg_line_length": 26.333333333333332,
"alnum_prop": 0.6708860759493671,
"repo_name": "jproffitt/django-herald",
"id": "c10b831f68d6a43075b71182e4cfa3ebf4331da3",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "herald/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "841"
},
{
"name": "Python",
"bytes": "63319"
}
],
"symlink_target": ""
} |
"""Views for dashboard
All dashboard blueprint can be disabled if you set ``DASHBOARD = False`` in configuration
"""
import logging
from passlib.apps import custom_app_context
from sqlalchemy.orm.exc import NoResultFound
from flask_principal import identity_changed, Identity
from flask_login import login_required, login_user, logout_user
from flask import Blueprint, render_template, abort, request,\
current_app as app, flash, redirect, url_for
from extrapypi.extensions import csrf, db
from extrapypi.commons.packages import get_store
from extrapypi.models import Package, Release, User
from extrapypi.commons.permissions import admin_permission
from extrapypi.forms.user import UserForm, UserCreateForm, LoginForm
log = logging.getLogger("extrapypi")
blueprint = Blueprint('dashboard', __name__, url_prefix='/dashboard')
@blueprint.route('/', methods=['GET'])
@login_required
def index():
"""Dashboard index, listing packages from database
"""
packages = Package.query.all()
return render_template("dashboard/index.html", packages=packages)
@blueprint.route('/login', methods=['GET', 'POST'])
def login():
"""Login view
Will redirect to dashboard index if login is successful
"""
form = LoginForm(request.form)
if form.validate_on_submit():
username = form.username.data
pwd = form.password.data
user = User.query.filter_by(username=username).first()
if not user or not custom_app_context.verify(pwd, user.password_hash):
flash("Bad user / password", 'alert-danger')
return render_template("login.html", form=form)
login_user(user, remember=form.remember.data)
identity_changed.send(
app._get_current_object(),
identity=Identity(user.id)
)
dest = request.args.get('next')
try:
return redirect(url_for(dest))
except:
return redirect(url_for('dashboard.index'))
return render_template("login.html", form=form)
@blueprint.route('/logout', methods=['GET'])
@login_required
def logout():
"""Logout view
Will redirect to login view after logout current user
"""
logout_user()
return redirect(url_for('dashboard.login'))
@blueprint.route('/search/', methods=['POST'])
@login_required
@csrf.exempt
def search():
"""Search page
Will use SQL Like syntax to search packages
"""
name = request.form.get('search')
packages = Package.query.filter(Package.name.ilike('%{}%'.format(name)))
packages = packages.all()
return render_template("dashboard/index.html", packages=packages)
@blueprint.route('/<string:package>/', methods=['GET'])
@login_required
def package(package):
"""Package detail view
"""
try:
p = Package.query.filter_by(name=package).one()
except NoResultFound:
abort(404)
release = p.latest_release
store = get_store(app.config['STORAGE'], app.config['STORAGE_PARAMS'])
files = store.get_files(p, release) or []
releases = [r for r in p.sorted_releases if r != release]
return render_template("dashboard/package_detail.html",
release=release,
files=files,
releases=releases)
@blueprint.route('/<string:package>/<int:release_id>', methods=['GET'])
@login_required
def release(package, release_id):
"""Specific release view
"""
try:
package = Package.query.filter_by(name=package).one()
release = Release.query.filter(
Release.id == release_id,
Release.package_id == package.id
).one()
except NoResultFound:
abort(404)
store = get_store(app.config['STORAGE'], app.config['STORAGE_PARAMS'])
files = store.get_files(package, release) or []
releases = [r for r in package.sorted_releases if r != release]
return render_template("dashboard/package_detail.html",
release=release,
files=files,
releases=releases)
@blueprint.route('/packages/delete/<int:package_id>', methods=['GET'])
@login_required
@admin_permission.require()
def delete_package(package_id):
"""Delete a package, all its releases and all files and directory
associated with it
"""
package = Package.query.get_or_404(package_id)
store = get_store(app.config['STORAGE'], app.config['STORAGE_PARAMS'])
if store.delete_package(package) is True:
db.session.delete(package)
db.session.commit()
return redirect(url_for("dashboard.index"))
@blueprint.route('/users/', methods=['GET'])
@login_required
@admin_permission.require()
def users_list():
"""List user in dashboard
"""
users = User.query.all()
return render_template("dashboard/users.html", users=users)
@blueprint.route('/users/create', methods=['GET', 'POST'])
@login_required
@admin_permission.require()
def create_user():
"""Create a new user
"""
form = UserCreateForm(request.form)
form.role.choices = [(r, r) for r in User.ROLES]
if form.validate_on_submit():
u = User(
username=form.username.data,
email=form.email.data,
is_active=form.is_active.data,
role=form.role.data
)
u.password_hash = custom_app_context.hash(form.password.data)
db.session.add(u)
db.session.commit()
flash("User created")
return redirect(url_for('dashboard.users_list'))
return render_template("dashboard/user_create.html", form=form)
@blueprint.route('/users/<int:user_id>', methods=['GET', 'POST'])
@login_required
@admin_permission.require()
def user_detail(user_id):
"""View to update user from admin account
"""
user = User.query.get_or_404(user_id)
form = UserForm(request.form, obj=user)
form.role.choices = [(r, r) for r in User.ROLES]
if form.validate_on_submit():
flash("User updated")
form.populate_obj(user)
db.session.commit()
return redirect(url_for('dashboard.users_list'))
return render_template("dashboard/user_detail.html", form=form, user=user)
@blueprint.route('/users/delete/<int:user_id>', methods=['GET'])
@login_required
@admin_permission.require()
def delete_user(user_id):
"""Delete a user and redirect to dashboard
"""
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
flash("User deleted")
return redirect(url_for('dashboard.users_list'))
| {
"content_hash": "dd76c904fe84630a2b418f1a7ba7bbc7",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 89,
"avg_line_length": 30.516279069767442,
"alnum_prop": 0.6505105928974242,
"repo_name": "karec/extrapypi",
"id": "c88f6742e05f680b8855b131d2397886a646c594",
"size": "6561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "extrapypi/dashboard/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "11924"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "71722"
}
],
"symlink_target": ""
} |
/*******************************************************************************
*
* Module Name: dmnames - AML disassembler, names, namestrings, pathnames
* xRevision: 7 $
*
******************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2004, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD$");
#include "acpi.h"
#include "acparser.h"
#include "amlcode.h"
#include "acnamesp.h"
#include "acdisasm.h"
#ifdef ACPI_DISASSEMBLER
#define _COMPONENT ACPI_CA_DEBUGGER
ACPI_MODULE_NAME ("dmnames")
/*******************************************************************************
*
* FUNCTION: AcpiDmValidateName
*
* PARAMETERS: Name - 4 character ACPI name
*
* RETURN: None
*
* DESCRIPTION: Lookup the name
*
******************************************************************************/
void
AcpiDmValidateName (
char *Name,
ACPI_PARSE_OBJECT *Op)
{
#if 0
if ((!Name) ||
(!Op->Common.Parent))
{
return;
}
if (!Op->Common.Node)
{
AcpiOsPrintf (" /**** Name not found or not accessible from this scope ****/ ");
}
ACPI_PARSE_OBJECT *TargetOp;
if ((!Name) ||
(!Op->Common.Parent))
{
return;
}
TargetOp = AcpiPsFind (Op, Name, 0, 0);
if (!TargetOp)
{
/*
* Didn't find the name in the parse tree. This may be
* a problem, or it may simply be one of the predefined names
* (such as _OS_). Rather than worry about looking up all
* the predefined names, just display the name as given
*/
AcpiOsPrintf (" /**** Name not found or not accessible from this scope ****/ ");
}
#endif
}
/*******************************************************************************
*
* FUNCTION: AcpiDmDumpName
*
* PARAMETERS: Name - 4 character ACPI name
*
* RETURN: Final length of name
*
* DESCRIPTION: Dump an ACPI name, minus any trailing underscores.
*
******************************************************************************/
UINT32
AcpiDmDumpName (
char *Name)
{
UINT32 i;
UINT32 Length;
char *End = Name + ACPI_NAME_SIZE;
for (i = 0; i < ACPI_NAME_SIZE; i++)
{
if (Name[i] != '_')
{
End = &Name[i];
}
}
Length = (UINT32)(End - Name) + 1;
for (i = 0; i < Length; i++)
{
AcpiOsPrintf ("%c", Name[i]);
}
return (Length);
}
/*******************************************************************************
*
* FUNCTION: AcpiPsDisplayObjectPathname
*
* PARAMETERS: WalkState - Current walk state
* Op - Object whose pathname is to be obtained
*
* RETURN: Status
*
* DESCRIPTION: Diplay the pathname associated with a named object. Two
* versions. One searches the parse tree (for parser-only
* applications suchas AcpiDump), and the other searches the
* ACPI namespace (the parse tree is probably deleted)
*
******************************************************************************/
ACPI_STATUS
AcpiPsDisplayObjectPathname (
ACPI_WALK_STATE *WalkState,
ACPI_PARSE_OBJECT *Op)
{
ACPI_STATUS Status;
ACPI_NAMESPACE_NODE *Node;
ACPI_BUFFER Buffer;
UINT32 DebugLevel;
/* Save current debug level so we don't get extraneous debug output */
DebugLevel = AcpiDbgLevel;
AcpiDbgLevel = 0;
/* Just get the Node out of the Op object */
Node = Op->Common.Node;
if (!Node)
{
/* Node not defined in this scope, look it up */
Status = AcpiNsLookup (WalkState->ScopeInfo, Op->Common.Value.String, ACPI_TYPE_ANY,
ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT, WalkState, &(Node));
if (ACPI_FAILURE (Status))
{
/*
* We can't get the pathname since the object
* is not in the namespace. This can happen during single
* stepping where a dynamic named object is *about* to be created.
*/
AcpiOsPrintf (" [Path not found]");
goto Exit;
}
/* Save it for next time. */
Op->Common.Node = Node;
}
/* Convert NamedDesc/handle to a full pathname */
Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
Status = AcpiNsHandleToPathname (Node, &Buffer);
if (ACPI_FAILURE (Status))
{
AcpiOsPrintf ("****Could not get pathname****)");
goto Exit;
}
AcpiOsPrintf (" (Path %s)", (char *) Buffer.Pointer);
ACPI_MEM_FREE (Buffer.Pointer);
Exit:
/* Restore the debug level */
AcpiDbgLevel = DebugLevel;
return (Status);
}
/*******************************************************************************
*
* FUNCTION: AcpiDmNamestring
*
* PARAMETERS: Name - ACPI Name string to store
*
* RETURN: None
*
* DESCRIPTION: Decode an ACPI namestring. Handles prefix characters
*
******************************************************************************/
void
AcpiDmNamestring (
char *Name)
{
UINT32 SegCount;
if (!Name)
{
return;
}
/* Handle all Scope Prefix operators */
while (AcpiPsIsPrefixChar (ACPI_GET8 (Name)))
{
/* Append prefix character */
AcpiOsPrintf ("%1c", ACPI_GET8 (Name));
Name++;
}
switch (ACPI_GET8 (Name))
{
case 0:
SegCount = 0;
break;
case AML_DUAL_NAME_PREFIX:
SegCount = 2;
Name++;
break;
case AML_MULTI_NAME_PREFIX_OP:
SegCount = (UINT32) ACPI_GET8 (Name + 1);
Name += 2;
break;
default:
SegCount = 1;
break;
}
while (SegCount)
{
/* Append Name segment */
AcpiDmDumpName ((char *) Name);
SegCount--;
if (SegCount)
{
/* Not last name, append dot separator */
AcpiOsPrintf (".");
}
Name += ACPI_NAME_SIZE;
}
}
/*******************************************************************************
*
* FUNCTION: AcpiDmDisplayPath
*
* PARAMETERS: Op - Named Op whose path is to be constructed
*
* RETURN: None
*
* DESCRIPTION: Walk backwards from current scope and display the name
* of each previous level of scope up to the root scope
* (like "pwd" does with file systems)
*
******************************************************************************/
void
AcpiDmDisplayPath (
ACPI_PARSE_OBJECT *Op)
{
ACPI_PARSE_OBJECT *Prev;
ACPI_PARSE_OBJECT *Search;
UINT32 Name;
BOOLEAN DoDot = FALSE;
ACPI_PARSE_OBJECT *NamePath;
const ACPI_OPCODE_INFO *OpInfo;
/* We are only interested in named objects */
OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode);
if (!(OpInfo->Flags & AML_NSNODE))
{
return;
}
if (OpInfo->Flags & AML_CREATE)
{
/* Field creation - check for a fully qualified namepath */
if (Op->Common.AmlOpcode == AML_CREATE_FIELD_OP)
{
NamePath = AcpiPsGetArg (Op, 3);
}
else
{
NamePath = AcpiPsGetArg (Op, 2);
}
if ((NamePath) &&
(NamePath->Common.Value.String) &&
(NamePath->Common.Value.String[0] == '\\'))
{
AcpiDmNamestring (NamePath->Common.Value.String);
return;
}
}
Prev = NULL; /* Start with Root Node */
while (Prev != Op)
{
/* Search upwards in the tree to find scope with "prev" as its parent */
Search = Op;
for (; ;)
{
if (Search->Common.Parent == Prev)
{
break;
}
/* Go up one level */
Search = Search->Common.Parent;
}
if (Prev)
{
OpInfo = AcpiPsGetOpcodeInfo (Search->Common.AmlOpcode);
if (!(OpInfo->Flags & AML_FIELD))
{
/* Below root scope, append scope name */
if (DoDot)
{
/* Append dot */
AcpiOsPrintf (".");
}
if (OpInfo->Flags & AML_CREATE)
{
if (Op->Common.AmlOpcode == AML_CREATE_FIELD_OP)
{
NamePath = AcpiPsGetArg (Op, 3);
}
else
{
NamePath = AcpiPsGetArg (Op, 2);
}
if ((NamePath) &&
(NamePath->Common.Value.String))
{
AcpiDmDumpName (NamePath->Common.Value.String);
}
}
else
{
Name = AcpiPsGetName (Search);
AcpiDmDumpName ((char *) &Name);
}
DoDot = TRUE;
}
}
Prev = Search;
}
}
#endif
| {
"content_hash": "6c91e82421b7ac20191806e77cf0f72c",
"timestamp": "",
"source": "github",
"line_count": 502,
"max_line_length": 92,
"avg_line_length": 30.948207171314742,
"alnum_prop": 0.56629763130793,
"repo_name": "MarginC/kame",
"id": "e0850ad851d742dfb5cb14aeae45908d1085c6c7",
"size": "15536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "netbsd/sys/dev/acpi/acpica/Subsystem/dmnames.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Wed Mar 02 16:45:54 EST 2011 -->
<TITLE>
gov.nih.nci.cabig.caaers.scheduler.runtime.job
</TITLE>
<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.scheduler.runtime.job package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../../../gov/nih/nci/cabig/caaers/scheduler/runtime/job/package-summary.html" target="classFrame">gov.nih.nci.cabig.caaers.scheduler.runtime.job</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="ReminderEmailJob.html" title="class in gov.nih.nci.cabig.caaers.scheduler.runtime.job" target="classFrame">ReminderEmailJob</A>
<BR>
<A HREF="ReminderEmailJobTest.html" title="class in gov.nih.nci.cabig.caaers.scheduler.runtime.job" target="classFrame">ReminderEmailJobTest</A>
<BR>
<A HREF="ReportStatusResetJob.html" title="class in gov.nih.nci.cabig.caaers.scheduler.runtime.job" target="classFrame">ReportStatusResetJob</A>
<BR>
<A HREF="ReportStatusResetJobTest.html" title="class in gov.nih.nci.cabig.caaers.scheduler.runtime.job" target="classFrame">ReportStatusResetJobTest</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| {
"content_hash": "c6d2a2dc03ff08c0b8f302c27983ebf0",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 179,
"avg_line_length": 40.89473684210526,
"alnum_prop": 0.6956241956241956,
"repo_name": "CBIIT/caaers",
"id": "96bce337f186fd86a7f7d3b8af445246ebbd75fc",
"size": "1554",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "caAERS/software/docs/gov/nih/nci/cabig/caaers/scheduler/runtime/job/package-frame.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "127"
},
{
"name": "AspectJ",
"bytes": "2052"
},
{
"name": "Batchfile",
"bytes": "778"
},
{
"name": "CSS",
"bytes": "150327"
},
{
"name": "Cucumber",
"bytes": "666"
},
{
"name": "Groovy",
"bytes": "19198183"
},
{
"name": "HTML",
"bytes": "78184618"
},
{
"name": "Java",
"bytes": "14455656"
},
{
"name": "JavaScript",
"bytes": "439130"
},
{
"name": "PLSQL",
"bytes": "75583"
},
{
"name": "PLpgSQL",
"bytes": "34461"
},
{
"name": "Ruby",
"bytes": "29724"
},
{
"name": "Shell",
"bytes": "14770"
},
{
"name": "XSLT",
"bytes": "1262163"
}
],
"symlink_target": ""
} |
require 'uri'
require 'active_support/core_ext/object/blank'
module Swarker
module Readers
class ServiceReader
attr_reader :services
SERVICE_EXT = '.service.yml'.freeze
DEFAULT_PORT = 80
DEFINITIONS_DIR = 'definitions'.freeze
PATHS_DIR = 'api'.freeze
def initialize(dir, subtree = nil)
@dir = dir
@subtree = subtree
@services = read_services
end
private
attr_reader :dir, :subtree
def read_services
hosts.collect do |host|
Swarker::Service.new(host, original_schema, definitions, paths)
end.presence || [local_service]
end
def local_service
Swarker::Service.new(nil, original_schema, definitions, paths)
end
def definitions
@definitions ||= DefinitionsReader.new(definitions_dir).definitions
end
def definitions_dir
File.join(dir, DEFINITIONS_DIR)
end
def paths
@paths ||= PathsMerger.new(PathsReader.new(paths_dir).paths).paths
end
def paths_dir
File.join(dir, subtree || PATHS_DIR)
end
def hosts
original_schema[:domains].values.collect do |domain|
uri = URI(domain)
uri.port == DEFAULT_PORT ? uri.host : "#{uri.host}:#{uri.port}"
end
end
def original_schema
@original_schema ||= HashWithIndifferentAccess.new(YAML.load_file(service_file))
end
def service_file
# Assumes that it can be only one service file in service directory
Dir["#{dir}/*#{SERVICE_EXT}"].first
end
end
end
end
| {
"content_hash": "e5e68c9a04aa74190d896eb387554e80",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 88,
"avg_line_length": 24.102941176470587,
"alnum_prop": 0.600366076876144,
"repo_name": "sponomarev/swarker",
"id": "dd4ecf8559a06e03a6ea9028b6786add78fbe05e",
"size": "1639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/swarker/readers/service_reader.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "25858"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
<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>
<groupId>clinic.programmming</groupId>
<artifactId>maven-quick-start</artifactId>
<version>1.2</version>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "03141eaed3ce2d0e5a0ff09d09eb3ccc",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 55,
"avg_line_length": 27.025641025641026,
"alnum_prop": 0.6290322580645161,
"repo_name": "draikone/maven-quick-start",
"id": "e0c5778d8b3d3bc0fad2e11c43eae2e138c6b056",
"size": "1054",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1955"
}
],
"symlink_target": ""
} |
package be
import (
"crypto/tls"
"errors"
"net"
"sync"
"time"
)
// StoppableListener taken from https://github.com/hydrogen18/stoppableListener
type StoppableListener struct {
net.Listener //inner, TLS listener
tcpListener *net.TCPListener // TCPlistener
stop chan int //Channel used only to indicate listener should shutdown
waitGroup sync.WaitGroup
}
func NewStoppableListener(connect string, certPath string, keyPath string) (*StoppableListener, error) {
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
logger.Println("Error loading cert", err)
return nil, err
}
config := &tls.Config{Certificates: []tls.Certificate{cert}}
netListener, err := net.Listen("tcp", connect)
if err != nil {
return nil, err
}
tcpListener, ok := netListener.(*net.TCPListener)
if !ok {
return nil, errors.New("Cannot wrap listener")
}
tlsListener := tls.NewListener(tcpListener, config)
stoppableListener := &StoppableListener{}
stoppableListener.Listener = tlsListener
stoppableListener.tcpListener = tcpListener
stoppableListener.stop = make(chan int)
return stoppableListener, nil
}
var ErrStopped = errors.New("Listener stopped")
func (sl *StoppableListener) Accept() (net.Conn, error) {
for {
//Wait up to one second for a new connection
sl.tcpListener.SetDeadline(time.Now().Add(time.Second))
newConn, err := sl.Listener.Accept()
//Check for the channel being closed
select {
case <-sl.stop:
return nil, ErrStopped
default:
//If the channel is still open, continue as normal
}
if err != nil {
netErr, ok := err.(net.Error)
//If this is a timeout, then continue to wait for
//new connections
if ok && netErr.Timeout() && netErr.Temporary() {
continue
}
}
return newConn, err
}
}
func (sl *StoppableListener) Stop() {
close(sl.stop)
}
| {
"content_hash": "a91284da236c35e9f1727c09fd3e5a21",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 104,
"avg_line_length": 25.27027027027027,
"alnum_prop": 0.6994652406417112,
"repo_name": "Spaciblo/spaciblo-core",
"id": "faf0fd148d518fd3f41ce97457f716e5458d3215",
"size": "1870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "go/src/spaciblo.org/be/http.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11952"
},
{
"name": "GLSL",
"bytes": "4483"
},
{
"name": "Go",
"bytes": "275083"
},
{
"name": "HTML",
"bytes": "12901"
},
{
"name": "JavaScript",
"bytes": "1486467"
},
{
"name": "Makefile",
"bytes": "4699"
},
{
"name": "Shell",
"bytes": "442"
}
],
"symlink_target": ""
} |
/**
* Interaction for the pages module
*/
/* global pageID, CKEDITOR, extrasById, extrasData, ss, templates, initDefaults, selectedId */
jsBackend.pages = {
// init, something like a constructor
init: function () {
// load the tree
jsBackend.pages.tree.init()
// are we adding or editing?
if (typeof templates !== 'undefined') {
// load stuff for the page
jsBackend.pages.extras.init()
jsBackend.pages.template.init()
}
// button to save to draft
$('#saveAsDraft').on('click', function (e) {
$('form#edit').append('<input type="hidden" name="status" value="draft" />')
$('form#edit').submit()
})
// show / hide the remove from search index checkbox on change
$('#authRequired').on('change', function (e) {
if ($(this).is(':checked')) {
$('[data-role="remove-from-search-index"]').removeClass('hidden')
} else {
$('[data-role="remove-from-search-index"]').addClass('hidden')
}
}).trigger('change')
// do meta
if ($('#title').length > 0) $('#title').doMeta()
if ($('[data-role="move-page-toggle"]').length > 0) jsBackend.pages.move.init()
}
}
jsBackend.pages.move = {
init: function () {
jsBackend.pages.move.allowGodUsersToEnableTheMovePageSetting()
jsBackend.pages.move.handleChangingPageTree()
jsBackend.pages.move.handleChangingReferencePage()
},
handleChangingReferencePage: function () {
$('[data-role="move-page-pages-select"]').on('change', function () {
var $this = $(this)
var $selectedOption = $this.find(':selected')
var $typeSelect = $('[data-role="move-page-type-changer"]')
var $typeSelectOptions = $typeSelect.find('option')
var selectedValue = $typeSelect.find('option:selected').val()
$typeSelectOptions.removeClass('disabled').prop('disabled', false).prop('selected', false)
if ($selectedOption.data('allowInside') !== 1 && $this.val() !== '0') {
$typeSelect.find('[value=inside]').addClass('disabled').prop('disabled', true)
}
if ($selectedOption.data('allowBefore') !== 1) {
$typeSelect.find('[value=before]').addClass('disabled').prop('disabled', true)
}
if ($selectedOption.data('allowAfter') !== 1) {
$typeSelect.find('[value=after]').addClass('disabled').prop('disabled', true)
}
if ($typeSelect.find('option[value="' + selectedValue + '"]').is(':disabled')) {
selectedValue = $typeSelectOptions.not(':disabled').first().val()
}
$typeSelect.val(selectedValue)
$typeSelect.trigger('change')
}).trigger('change')
},
handleChangingPageTree: function () {
$('[data-role="move-page-tree-changer"]').on('change', function () {
var $this = $(this)
var $pagesSelect = $('[data-role="move-page-pages-select"]')
var selectedValue = $pagesSelect.find('option:selected').val()
$pagesSelect.find('optgroup option').prop('selected', false).prop('disabled', true)
// only show the pages of the selected tree
$pagesSelect.find('optgroup').hide().children().hide()
var $visiblePages = $pagesSelect.find('[data-tree-name="' + $this.val() + '"]')
if ($visiblePages.length > 0) {
$visiblePages.show().prop('disabled', false)
$pagesSelect.find('optgroup[label="' + $visiblePages.first().attr('data-tree-label') + '"]').show()
}
if ($pagesSelect.find('option[value="' + selectedValue + '"]').is(':disabled')) {
selectedValue = 0
}
$pagesSelect.val(selectedValue)
$pagesSelect.trigger('change')
}).trigger('change')
},
allowGodUsersToEnableTheMovePageSetting: function () {
var $toggle = $('[data-role="allow-move-toggle"]')
if ($toggle.length === 0) {
return
}
$toggle.on('change', function () {
var $movePageToggle = $('[data-role="move-page-toggle"]')
if ($(this).is(':checked')) {
$movePageToggle.removeClass('disabled').prop('disabled', false)
return
}
$movePageToggle.addClass('disabled').prop('disabled', true).prop('checked', false).trigger('change')
}).trigger('change')
}
}
/**
* All methods related to the controls (buttons, ...)
*/
jsBackend.pages.extras = {
uploaders: [],
counter: 0,
// init, something like a constructor
init: function () {
// get user templates
jsBackend.pages.template.userTemplates = jsData.pages.userTemplates
// bind events
$('#extraType').on('change', jsBackend.pages.extras.populateExtraModules)
$('#extraModule').on('change', jsBackend.pages.extras.populateExtraIds)
// bind buttons
$(document).on('click', 'button.addBlock', jsBackend.pages.extras.showAddDialog)
$(document).on('click', 'button.deleteBlock', jsBackend.pages.extras.showDeleteDialog)
$(document).on('click', '.showEditor', jsBackend.pages.extras.editContent)
$(document).on('click', '.editUserTemplate', jsBackend.pages.extras.editUserTemplate)
$(document).on('click', '.toggleVisibility', jsBackend.pages.extras.toggleVisibility)
$('.modal').on('scroll', jsBackend.pages.extras.modalScrolledHandler)
// make the default position sortable
jsBackend.pages.extras.sortable($('#templateVisualFallback div.linkedBlocks'))
$('#authRequired').on('change', jsBackend.pages.extras.showGroups)
},
// handle stuff when scroll inside a modal
modalScrolledHandler: function (event) {
jsBackend.pages.extras.counter++
// skip 9 out of 10 scrolls
if (jsBackend.pages.extras.counter % 10 !== 0) {
return false
}
// update the positions on each uploader
$.each(jsBackend.pages.extras.uploaders, function (index, uploader) {
uploader.updatePosition()
})
},
// store the extra for real
addBlock: function (selectedExtraId, selectedPosition, selectedExtraType, selectedExtraData) {
selectedExtraType = selectedExtraType || 'rich_text'
// clone prototype block
var block = $('.contentBlock:first').clone()
// fetch amount of blocks already on page, it'll be the index of the newly added block
var index = $('.contentBlock').length
// update index occurences in the hidden data
var blockHtml = $('textarea[id^=blockHtml]', block)
var blockExtraId = $('input[id^=blockExtraId]', block)
var blockExtraType = $('input[id^=blockExtraType]', block)
var blockExtraData = $('input[id^=blockExtraData]', block)
var blockPosition = $('input[id^=blockPosition]', block)
var blockVisibility = $('input[id^=blockVisible]', block)
// update id & name to new index
blockHtml.prop('id', blockHtml.prop('id').replace('0', index)).prop('name', blockHtml.prop('name').replace('0', index))
blockExtraId.prop('id', blockExtraId.prop('id').replace('0', index)).prop('name', blockExtraId.prop('name').replace('0', index))
blockExtraType.prop('id', blockExtraType.prop('id').replace('0', index)).prop('name', blockExtraType.prop('name').replace('0', index))
blockExtraData.prop('id', blockExtraData.prop('id').replace('0', index)).prop('name', blockExtraData.prop('name').replace('0', index))
blockPosition.prop('id', blockPosition.prop('id').replace('0', index)).prop('name', blockPosition.prop('name').replace('0', index))
blockVisibility.prop('id', blockVisibility.prop('id').replace('0', index)).prop('name', blockVisibility.prop('name').replace('0', index))
// save position
blockPosition.val(selectedPosition)
// save extra id
blockExtraId.val(selectedExtraId)
// save extra type
blockExtraType.val(selectedExtraType)
// save extra data
blockExtraData.val(JSON.stringify(selectedExtraData))
// add block to dom
block.appendTo($('#editContent'))
// get block visibility
var visible = blockVisibility.attr('checked')
// add visual representation of block to template visualisation
var addedVisual = jsBackend.pages.extras.addBlockVisual(selectedPosition, index, selectedExtraId, visible, selectedExtraType, selectedExtraData)
// block/widget = don't show editor
if (selectedExtraType !== 'usertemplate' && typeof extrasById !== 'undefined' && typeof extrasById[selectedExtraId] !== 'undefined') {
$('.blockContentHTML', block).hide()
} else {
// editor or user template
$('.blockContentHTML', block).show()
}
return addedVisual ? index : false
},
// add block visual on template
addBlockVisual: function (position, index, extraId, visible, extraType, extraData) {
// check if the extra is valid
if (extraType !== 'usertemplate' && extraId !== 0 && typeof extrasById[extraId] === 'undefined') return false
// block
var editLink, title, description
if (extraType !== 'usertemplate' && extraId !== 0) {
// link to edit this block/widget
editLink = ''
if (extrasById[extraId].type === 'block' && extrasById[extraId].data.url) editLink = extrasById[extraId].data.url
if (typeof extrasById[extraId].data.edit_url !== 'undefined' && extrasById[extraId].data.edit_url) editLink = extrasById[extraId].data.edit_url
// title, description & visibility
title = extrasById[extraId].path
description = extrasById[extraId].path
} else if (extraType === 'usertemplate') {
// user template
if (typeof extraData === 'string' && extraData !== '') {
extraData = JSON.parse(extraData)
}
editLink = ''
title = utils.string.ucfirst(jsBackend.locale.lbl('UserTemplate'))
if (extraData.title) {
title += ' > ' + extraData.title
title += ' (' + extraData.description + ')'
}
description = utils.string.stripTags($('#blockHtml' + index).val()).substr(0, 200)
} else {
// editor
// link to edit this content, title, description & visibility
editLink = ''
title = utils.string.ucfirst(jsBackend.locale.lbl('Editor'))
description = utils.string.stripTags($('#blockHtml' + index).val()).substr(0, 200)
}
var linkClass = ''
if (extraType === 'usertemplate') {
linkClass = 'editUserTemplate '
} else if (extraId === 0) {
linkClass = 'showEditor '
}
var showEditLink = (extraType === 'usertemplate' || (extraId !== 0 && editLink))
// create html to be appended in template-view
var blockHTML = '<div class="templatePositionCurrentType' + (visible ? ' ' : ' templateDisabled') + '" data-block-id="' + index + '">' +
'<span class="templateTitle" id="templateTitle' + index + '">' + title + '</span>'
if (title !== description) {
blockHTML += '<span class="templateDescription">' + description + '</span>'
}
blockHTML += '<div class="btn-group buttonHolder">' +
'<button class="btn btn-default btn-icon-only btn-xs toggleVisibility"><span class="fa fa-' + (visible ? 'eye' : 'eye-slash') + '" aria-hidden="true"></span><span class="sr-only">' + (visible ? jsBackend.locale.lbl('Hide') : jsBackend.locale.lbl('Show')) + '</span></span></button>' +
'<a href="' + (editLink || '#') + '" class="' + linkClass + 'btn btn-primary btn-icon-only btn-xs' + '"' + (showEditLink ? ' target="_blank" rel="noopener noreferrer"' : '') + (showEditLink ? '' : ' onclick="return false;"') + ((showEditLink) || extraId === 0 ? '' : 'style="display: none;" ') + '><span class="fa fa-pencil" aria-hidden="true"></span><span class="sr-only">' + jsBackend.locale.lbl('EditContent') + '</span></a>' +
'<button class="deleteBlock btn btn-danger btn-icon-only btn-xs"><span class="fa fa-trash-o" aria-hidden="true"></span><span class="sr-only">' + jsBackend.locale.lbl('DeleteBlock') + '</span></button>' +
'</div>' +
'</div>'
// set block description in template-view
$('#templatePosition-' + position + ' .linkedBlocks').append(blockHTML)
// mark as updated
jsBackend.pages.extras.updatedBlock($('.templatePositionCurrentType[data-block-id=' + index + ']'))
return true
},
// delete a linked block
deleteBlock: function (index) {
// remove block from template overview
$('.templatePositionCurrentType[data-block-id=' + index + ']').remove()
// remove block
$('[name=block_extra_id_' + index + ']').parent('.contentBlock').remove()
// after removing all from fallback; hide fallback
jsBackend.pages.extras.hideFallback()
// reset indexes (sequence)
jsBackend.pages.extras.resetIndexes()
},
// edit content
editContent: function (e) {
// prevent default event action
e.preventDefault()
// fetch block index
var index = $(this).closest('*[data-block-id]').data('block-id')
// fetch block position
var $templatePosition = $(this).closest('.templatePosition')
// save unaltered content
var previousContent = $('#blockHtml' + index).val()
// placeholder for block node that will be moved by the jQuery dialog
$('#blockHtml' + index).parent().parent().parent().after('<div id="blockPlaceholder"></div>')
// show dialog
$('#blockHtmlSubmit').unbind('click').on('click', function (e) {
e.preventDefault()
// grab the content
var content = $('#html').val()
// save content
jsBackend.pages.extras.setContent(index, content)
// edit content = template is no longer original
jsBackend.pages.template.original = false
// close dialog
$('#blockHtml').modal('hide')
// set focus on position add block button after the modal is closed
$('#blockHtml').on('hidden.bs.modal', function (e) {
$templatePosition.find('.addBlock').focus()
})
})
$('#blockHtmlCancel').unbind('click').on('click', function (e) {
e.preventDefault()
// reset content
jsBackend.pages.extras.setContent(index, previousContent)
// close the dialog
$('#blockHtml').modal('hide')
// set focus on position add block button after the modal is closed
$('#blockHtml').on('hidden.bs.modal', function (e) {
$templatePosition.find('.addBlock').focus()
})
})
$('#blockHtml').unbind('show.bs.modal').on('show.bs.modal', function (e) {
if (jsData.Core.preferred_editor !== 'ck-editor') {
$('#html').val(previousContent);
return;
}
// set content in editor
CKEDITOR.instances['html'].setData(previousContent)
}).modal('show')
},
// hide fallback
hideFallback: function () {
// after removing all from fallback; hide fallback
if ($('#templateVisualFallback .templatePositionCurrentType').length === 0) $('#templateVisualFallback').hide()
},
// populate the dropdown with the modules
populateExtraModules: function () {
// get selected value
var selectedType = $('#extraType').val()
// hide
$('#extraModuleHolder').hide()
$('#extraExtraIdHolder').hide()
$('#userTemplateHolder').hide()
$('#extraModule').html('<option value="0">-</option>')
$('#extraExtraId').html('<option value="0">-</option>')
// only widgets and block need the module dropdown
if (selectedType === 'widget' || selectedType === 'block') {
// loop modules
for (var i in extrasData) {
// add option if needed
if (typeof extrasData[i]['items'][selectedType] !== 'undefined') $('#extraModule').append('<option value="' + extrasData[i].value + '">' + extrasData[i].name + '</option>')
}
// show
$('#extraModuleHolder').show()
}
var userTemplates = jsBackend.pages.template.userTemplates
// show the defined user templates
if (selectedType === 'usertemplate') {
var $userTemplate = $('#userTemplate')
$userTemplate.find('option').not('[value=-1]').remove()
for (var j in userTemplates) {
// add option if needed
$userTemplate.append('<option value="' + j + '">' + userTemplates[j].title + '</option>')
}
$('#userTemplateHolder').show()
}
},
// populates the dropdown with the extra's
populateExtraIds: function () {
// get selected value
var selectedType = $('#extraType').val()
var selectedModule = $('#extraModule').val()
// hide and clear previous items
$('#extraExtraIdHolder').hide()
$('#extraExtraId').html('')
// any items?
if (typeof extrasData[selectedModule] !== 'undefined' && typeof extrasData[selectedModule]['items'][selectedType] !== 'undefined') {
if (extrasData[selectedModule]['items'][selectedType].length === 1 && selectedType === 'block') {
$('#extraExtraId').append('<option selected="selected" value="' + extrasData[selectedModule]['items'][selectedType][0].id + '">' + extrasData[selectedModule]['items'][selectedType][0].label + '</option>')
} else {
// loop items
for (var i in extrasData[selectedModule]['items'][selectedType]) {
// add option
$('#extraExtraId').append('<option value="' + extrasData[selectedModule]['items'][selectedType][i].id + '">' + extrasData[selectedModule]['items'][selectedType][i].label + '</option>')
}
// show
$('#extraExtraIdHolder').show()
}
}
},
// reset all indexes to keep all items in proper order
resetIndexes: function () {
// mark content to be reset
$('.contentBlock').addClass('reset')
// reorder indexes of existing blocks:
// is doesn't really matter if a certain block at a certain position has a certain index; the important part
// is that they're all sequential without gaps and that the sequence of blocks inside a position is correct
$('.templatePositionCurrentType').each(function (i) {
// fetch block id
var oldIndex = $(this).attr('data-block-id')
var newIndex = i + 1
// update index of entry in template-view
$(this).attr('data-block-id', newIndex)
// update index occurences in the hidden data
var blockHtml = $('.reset [name=block_html_' + oldIndex + ']')
var blockExtraId = $('.reset [name=block_extra_id_' + oldIndex + ']')
var blockExtraType = $('.reset [name=block_extra_type_' + oldIndex + ']')
var blockExtraData = $('.reset [name=block_extra_data_' + oldIndex + ']')
var blockPosition = $('.reset [name=block_position_' + oldIndex + ']')
var blockVisible = $('.reset [name=block_visible_' + oldIndex + ']')
blockHtml.prop('id', blockHtml.prop('id').replace(oldIndex, newIndex)).prop('name', blockHtml.prop('name').replace(oldIndex, newIndex))
blockExtraId.prop('id', blockExtraId.prop('id').replace(oldIndex, newIndex)).prop('name', blockExtraId.prop('name').replace(oldIndex, newIndex))
blockExtraType.prop('id', blockExtraType.prop('id').replace(oldIndex, newIndex)).prop('name', blockExtraType.prop('name').replace(oldIndex, newIndex))
blockExtraData.prop('id', blockExtraData.prop('id').replace(oldIndex, newIndex)).prop('name', blockExtraData.prop('name').replace(oldIndex, newIndex))
blockPosition.prop('id', blockPosition.prop('id').replace(oldIndex, newIndex)).prop('name', blockPosition.prop('name').replace(oldIndex, newIndex))
blockVisible.prop('id', blockVisible.prop('id').replace(oldIndex, newIndex)).prop('name', blockVisible.prop('name').replace(oldIndex, newIndex))
// no longer mark as needing to be reset
blockExtraId.parent('.contentBlock').removeClass('reset')
// while we're at it, make sure the position is also correct
blockPosition.val($(this).closest('*[data-position]').attr('data-position'))
})
// mark all as having been reset
$('.contentBlock').removeClass('reset')
},
// save/reset the content
setContent: function (index, content) {
// the content to set
if (content !== null) $('#blockHtml' + index).val(content)
// add short description to visual representation of block, except for usertemplates
var description = utils.string.stripTags($('#blockHtml' + index).val()).substr(0, 200)
$('.templatePositionCurrentType[data-block-id=' + index + '] .templateDescription').html(description)
// mark as updated
jsBackend.pages.extras.updatedBlock($('.templatePositionCurrentType[data-block-id=' + index + ']'))
},
// add a block
showAddDialog: function (e) {
// prevent the default action
e.preventDefault()
// save the position wherefor we will change the extra
var position = $(this).closest('*[data-position]').data('position')
// init var
var hasModules = false
// check if there already blocks linked
$('input[id^=blockExtraId]').each(function () {
// get id
var id = $(this).val()
// check if a block is already linked
if (id !== '' && typeof extrasById[id] !== 'undefined' && extrasById[id].type === 'block') hasModules = true
})
// hide warnings
$('#extraWarningAlreadyBlock').hide()
$('#extraWarningHomeNoBlock').hide()
// init var
var enabled = true
// blocks linked?
if (hasModules) {
// disable module selection
enabled = false
// show warning
$('#extraWarningAlreadyBlock').show()
}
// home can't have any modules linked!
if (typeof pageID !== 'undefined' && pageID === 1) {
// disable module selection
enabled = false
// show warning
$('#extraWarningHomeNoBlock').show()
}
// enable/disable blocks
$('#extraType option[value=block]').attr('disabled', !enabled)
// set type
$('#extraType').val($('#extraType').val())
$('#extraExtraId').val(0)
// populate the modules
jsBackend.pages.extras.populateExtraModules()
// initialize the modal for choosing an extra
if ($('#addBlock').length > 0) {
$('#addBlockSubmit').unbind('click').on('click', function (e) {
e.preventDefault()
// fetch the selected extra type
var selectedExtraType = $('#extraType').val()
// fetch the selected extra id
var selectedExtraId = parseInt($('#extraExtraId').val())
// is user template?
var isUserTemplate = (selectedExtraType === 'usertemplate')
// fetch the selected extra data
var selectedExtraData = $('#extraData').val()
// fetch user template id
if (isUserTemplate) {
selectedExtraId = $('#userTemplate').val()
selectedExtraData = jsData.pages.userTemplates[selectedExtraId]
}
// add the extra
var index = jsBackend.pages.extras.addBlock(selectedExtraId, position, selectedExtraType, selectedExtraData)
// add a block = template is no longer original
jsBackend.pages.template.original = false
// close dialog
$('#addBlock').off('hidden.bs.modal').on('hidden.bs.modal', function () {
// if the added block was a user template, show the template popup immediately
if (isUserTemplate && index) {
$('.templatePositionCurrentType[data-block-id=' + index + '] .editUserTemplate').click()
}
}).modal('hide')
// set focus on position add block button after the modal is closed
$('#addBlock').on('hidden.bs.modal', function (e) {
$('[data-position="' + position + '"]').find('.addBlock').focus()
})
// if the added block was an editor, show the editor immediately
if (!isUserTemplate && index && !(typeof extrasById !== 'undefined' && typeof extrasById[selectedExtraId] !== 'undefined')) {
$('.templatePositionCurrentType[data-block-id=' + index + '] .showEditor').click()
}
})
$('#addBlock').modal('show')
}
},
editUserTemplate: function (e) {
// prevent default event action
e.preventDefault()
// fetch block index
var index = $(this).parent().parent().attr('data-block-id')
// fetch block position
var $templatePosition = $(this).closest('.templatePosition')
// fetch user template id
var userTemplateId = $('#blockExtraId' + index).val()
// fetch the current content
var previousContent = $('#blockHtml' + index).val()
var templateUrl
// Set the title of the modal to the title of the user template
$('[data-fork-cms-role=user-template-title]').text(jsBackend.pages.template.userTemplates[userTemplateId].title)
// if there already was content, use this.
if (previousContent !== '') {
$('#userTemplateHiddenPlaceholder').html(previousContent)
jsBackend.pages.extras.buildUserTemplateForm(
$('#userTemplateHiddenPlaceholder'),
$('#userTemplatePlaceholder')
)
} else {
// if there was no content yet, take the default content
templateUrl = String(jsBackend.pages.template.userTemplates[userTemplateId].file)
$.ajax({
url: templateUrl,
dataType: 'html',
success: function (data) {
$('#userTemplateHiddenPlaceholder').html(data)
jsBackend.pages.extras.buildUserTemplateForm(
$('#userTemplateHiddenPlaceholder'),
$('#userTemplatePlaceholder')
)
}
})
}
var $modal = $('#addUserTemplate')
$modal.find('.js-submit-user-template').off('click').on('click', function (e) {
jsBackend.pages.extras.saveUserTemplateForm(
$('#userTemplateHiddenPlaceholder'),
$('#userTemplatePlaceholder')
)
// grab content
var content = $('#userTemplateHiddenPlaceholder').html()
// save content
jsBackend.pages.extras.setContent(index, content)
// edit content = template is no longer original
jsBackend.pages.template.original = false
$('#addUserTemplate').modal('hide')
// set focus on position add block button after the modal is closed
$('#addUserTemplate').on('hidden.bs.modal', function (e) {
$templatePosition.find('.addBlock').focus()
})
})
$modal.off('hidden.bs.modal').on('hidden.bs.modal', function () {
// the ajax file uploader inserts an input field in the body, remove it
$('body > div > input[name="file"]').parent().remove()
$('#userTemplatePlaceholder').html('')
})
$modal.modal('show')
},
/**
* Builds a form containing all fields that should be replaced in the
* hidden placeholder
*/
buildUserTemplateForm: function ($hiddenPlaceholder, $placeholder) {
$placeholder.html('')
$hiddenPlaceholder.find('*').each(function (key) {
jsBackend.pages.extras.addCustomFieldInPlaceholderFor($(this), key, $placeholder)
})
},
/**
* Creates the html for a normal link
*/
getLinkFieldHtml: function (text, url, label, key) {
var html = '<div class="panel panel-default" id="user-template-link-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body">'
html += '<div class="form-group">'
html += '<label>' + label + '</label>'
html += '<input data-ft-label="' + label + '" type="text" class="form-control" value="' + text + '"/>'
html += '</div>'
html += '<div class="form-group last">'
html += '<label>URL</label>'
html += '<input data-ft-url="' + label + '" type="url" class="form-control" value="' + url + '"/>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for a link without content
*/
getLinkWithoutContentFieldHtml: function (url, label, key) {
var html = '<div class="panel panel-default" id="user-template-link-without-content-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body">'
html += '<div class="form-group last">'
html += '<input data-ft-url="' + label + '" type="url" class="form-control" value="' + url + '"/>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for a text field
*/
getTextFieldHtml: function (text, label, key) {
var html = '<div class="panel panel-default" id="user-template-text-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body">'
html += '<div class="form-group last">'
html += '<input data-ft-label="' + label + '" type="text" class="form-control" value="' + text.trim() + '" />'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for a text area
*/
getTextAreaFieldHtml: function (text, label, key) {
var html = '<div class="panel panel-default panel-editor" id="user-template-textarea-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body">'
html += '<div class="form-group last">'
html += '<textarea class="form-control" data-ft-label="' + label + '" cols="83" rows="15">' + text.trim() + '</textarea>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for an editor
*/
getEditorFieldHtml: function (text, label, key) {
var html = '<div class="panel panel-default panel-editor" id="user-template-editor-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body">'
html += '<div class="form-group last">'
html += '<textarea id="user-template-cke-' + key + '" data-ft-label="' + label + '" cols="83" rows="15" class="inputEditor form-control">' + text.trim() + '</textarea>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for an image field
*/
getImageFieldHtml: function (src, alt, label, isVisible, optionalHide, key) {
var html = '<div class="panel panel-default" id="user-template-image-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body clearfix">'
html += '<div class="form-group thumbnail">'
html += '<img class="img-responsive"' + (isVisible ? '' : ' style="display: none;"') + ' src="' + src + '" />'
html += '<div class="caption" id="ajax-upload-' + key + '">'
html += '<label>' + label + '</label>'
// this will be replaced by the ajax uploader
html += '<input data-ft-label="' + label + '" type="file" accept="image/*" />'
html += '</div>'
html += '</div>'
html += '<div class="form-group">'
html += '<label for="alt' + key + '">Alt attribute</label>'
html += '<input class="form-control" type="text" id="alt' + key + '" value="' + alt + '" />'
html += '</div>'
html += '<div class="checkbox"' + (optionalHide ? '' : ' style="display: none;"') + '>'
html += '<label><input type="checkbox"' + (isVisible ? 'checked' : '') + '/> ' + jsBackend.locale.lbl('ShowImage') + '</label>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Creates the html for an image background field
*/
getImageBackgroundFieldHtml: function (src, label, key) {
var html = '<div class="panel panel-default" id="user-template-image-background-' + key + '">'
html += '<div class="panel-heading">'
html += '<h2 class="panel-title">' + label + '</h2>'
html += '</div>'
html += '<div class="panel-body clearfix">'
html += '<div class="form-group thumbnail">'
html += '<img class="img-responsive"' + ' src="' + src + '" />'
html += '<div class="caption" id="ajax-upload-' + key + '">'
html += '<label>' + label + '</label>'
// this will be replaced by the ajax uploader
html += '<input data-ft-label="' + label + '" type="file" accept="image/*" />'
html += '</div>'
html += '</div>'
html += '</div>'
html += '</div>'
return html
},
/**
* Checks if an element is some kind of special field that should have form
* fields and builds the html for it
*/
addCustomFieldInPlaceholderFor: function ($element, key, $placeholder) {
// replace links
if (($element).is('[data-ft-type="link"]')) {
$placeholder.append(jsBackend.pages.extras.getLinkFieldHtml($element.text(), $element.attr('href'), $element.data('ft-label'), key))
return
}
// replace links without content
if ($element.is('[data-ft-type="link-without-content"]')) {
$placeholder.append(jsBackend.pages.extras.getLinkWithoutContentFieldHtml($element.attr('href'), $element.data('ft-label'), key))
return
}
// replace text
if ($element.is('[data-ft-type="text"]')) {
$placeholder.append(jsBackend.pages.extras.getTextFieldHtml($element.text(), $element.data('ft-label'), key))
return
}
if ($element.is('[data-ft-type="textarea"]')) {
$placeholder.append(jsBackend.pages.extras.getTextAreaFieldHtml($element.text(), $element.data('ft-label'), key))
return
}
// replace image
if ($element.is('[data-ft-type="image"]')) {
$placeholder.append(
jsBackend.pages.extras.getImageFieldHtml(
$element.attr('src'),
$element.attr('alt'),
$element.data('ft-label'),
$element.attr('style') !== 'display: none;',
$element.data('ft-block-optional'),
key
)
)
// attach an ajax uploader to the field
jsBackend.pages.extras.uploaders.push(new ss.SimpleUpload({
button: 'ajax-upload-' + key,
url: '/backend/ajax?fork[module]=Pages&fork[action]=UploadFile&type=UserTemplate',
name: 'file',
accept: 'image/*',
responseType: 'json',
onComplete: function (filename, response) {
if (!response) {
window.alert(filename + 'upload failed')
return false
}
// cache the old image variable, we'll want to remove it to keep our filesystem clean
var oldImage = $('#user-template-image-' + key + ' img').attr('src')
$('#user-template-image-' + key + ' img').attr(
'src',
'/src/Frontend/Files/Pages/UserTemplate/' + response.data
)
// send a request to remove the old image if the old image doesn't have the same name
if (oldImage !== response.data) {
$.ajax({
data: {
fork: {module: 'Pages', action: 'RemoveUploadedFile'},
file: oldImage,
type: 'UserTemplate'
}
})
}
}
}))
// handle the "show image" checkbox
$('#user-template-image-' + key + ' input[type=checkbox]').on('click', function (e) {
$('#user-template-image-' + key + ' img').toggle($(this).is(':checked'))
})
return
}
// replace image background
if ($element.is('[data-ft-type="image-background"]')) {
$placeholder.append(
jsBackend.pages.extras.getImageBackgroundFieldHtml(
$element.attr('data-src'),
$element.data('ft-label'),
key
)
)
// attach an ajax uploader to the field
jsBackend.pages.extras.uploaders.push(new ss.SimpleUpload({
button: 'ajax-upload-' + key,
url: '/backend/ajax?fork[module]=Pages&fork[action]=UploadFile&type=UserTemplate',
name: 'file',
accept: 'image/*',
responseType: 'json',
onComplete: function (filename, response) {
if (!response) {
window.alert(filename + 'upload failed')
return false
}
// cache the old image variable, we'll want to remove it to keep our filesystem clean
var oldImage = $('#user-template-image-background-' + key + ' img').attr('src')
$('#user-template-image-background-' + key + ' img').attr(
'src',
'/src/Frontend/Files/Pages/UserTemplate/' + response.data
)
// send a request to remove the old image if the old image doesn't have the same name
if (oldImage !== response.data) {
$.ajax({
data: {
fork: {module: 'Pages', action: 'RemoveUploadedFile'},
file: oldImage,
type: 'UserTemplate'
}
})
}
}
}))
return
}
// replace editor
if ($element.is('[data-ft-type="editor"]')) {
$placeholder.append(jsBackend.pages.extras.getEditorFieldHtml($element.html(), $element.data('ft-label'), key))
if (jsData.Core.preferred_editor === 'ck-editor') {
jsBackend.ckeditor.load()
}
}
},
/**
* Takes all the data out of the user template form and injects it again in
* the original template html
*/
saveUserTemplateForm: function ($hiddenPlaceholder, $placeholder) {
$hiddenPlaceholder.find('*').each(function (key) {
jsBackend.pages.extras.saveCustomField($(this), key, $placeholder)
})
},
saveCustomField: function ($element, key, $placeholder) {
var $labelField
var $urlField
var $img
var $textarea
if ($element.is('[data-ft-type="link"]')) {
$labelField = $placeholder.find('#user-template-link-' + key + ' input[data-ft-label]')
$urlField = $placeholder.find('#user-template-link-' + key + ' input[data-ft-url]')
$element.attr('href', $urlField.val())
$element.text($labelField.val())
return
}
if ($element.is('[data-ft-type="link-without-content"]')) {
$urlField = $placeholder.find('#user-template-link-without-content-' + key + ' input[data-ft-url]')
$element.attr('href', $urlField.val())
return
}
if ($element.is('[data-ft-type="text"]')) {
$labelField = $placeholder.find('#user-template-text-' + key + ' input[data-ft-label]')
$element.text($labelField.val())
return
}
if ($element.is('[data-ft-type="textarea"]')) {
$textarea = $placeholder.find('#user-template-textarea-' + key + ' textarea[data-ft-label]')
$element.text($textarea.val())
return
}
if ($element.is('[data-ft-type="image"]')) {
$img = $placeholder.find('#user-template-image-' + key + ' img')
var alt = $placeholder.find('#alt' + key).val()
var $visible = $placeholder.find('#user-template-image-' + key + ' input[type=checkbox]')
$element.attr('src', $img.attr('src'))
$element.attr('alt', alt)
if ($visible.is(':checked')) {
$element.attr('style', 'display: block;')
} else {
$element.attr('style', 'display: none;')
}
return
}
if ($element.is('[data-ft-type="image-background"]')) {
$img = $placeholder.find('#user-template-image-background-' + key + ' img')
$element.attr('data-src', $img.attr('src'))
$element.css('background-image\'' + $img.attr('src') + '\')')
return
}
if ($element.is('[data-ft-type="editor"]')) {
$textarea = $placeholder.find('#user-template-editor-' + key + ' textarea[data-ft-label]')
$element.html($textarea.val())
if (jsData.Core.preferred_editor === 'ck-editor') {
// destroy the editor
var editor = CKEDITOR.instances['user-template-cke-' + key]
if (editor) {
editor.destroy(true)
}
}
}
},
// delete a block
showDeleteDialog: function (e) {
// prevent the default action
e.preventDefault()
// save element to variable
var element = $(this)
// save add block button from the position of the element
var $templateAddBlock = element.closest('.templatePosition').find('.addBlock')
// initialize the modal for deleting a block
if ($('#confirmDeleteBlock').length > 0) {
$('#confirmDeleteBlockSubmit').unbind('click').on('click', function (e) {
// delete this block
jsBackend.pages.extras.deleteBlock(element.parent().parent('.templatePositionCurrentType').attr('data-block-id'))
// delete a block = template is no longer original
jsBackend.pages.template.original = false
// close dialog
$('#confirmDeleteBlock').modal('hide')
// set focus to add block button after modal is closed
$('#confirmDeleteBlock').on('hidden.bs.modal', function (e) {
$templateAddBlock.focus()
})
})
$('#confirmDeleteBlock').modal('show')
}
},
// show the groups for authentication
showGroups: function (e) {
// save element to variable
$('.js-authentication-groups').toggle()
},
// re-order blocks
sortable: function (element) {
// make blocks sortable
element.sortable({
items: '.templatePositionCurrentType',
tolerance: 'pointer',
placeholder: 'dragAndDropPlaceholder',
forcePlaceholderSize: true,
connectWith: 'div.linkedBlocks',
opacity: 0.7,
delay: 300,
stop: function (e, ui) {
// reorder indexes of existing blocks:
jsBackend.pages.extras.resetIndexes()
// mark as updated
jsBackend.pages.extras.updatedBlock(ui.item)
// after removing all from fallback; hide fallback
jsBackend.pages.extras.hideFallback()
// reorder blocks = template is no longer original
jsBackend.pages.template.original = false
},
start: function (e, ui) {
// check if we're moving from template
if ($(this).parents('#templateVisualLarge').length > 0) {
// disable dropping to fallback
$('div.linkedBlocks').sortable('option', 'connectWith', '#templateVisualLarge div.linkedBlocks')
} else {
// enable dropping on fallback
$('div.linkedBlocks').sortable('option', 'connectWith', 'div.linkedBlocks')
}
// refresh sortable to reflect altered dropping
$('div.linkedBlocks').sortable('refresh')
}
})
},
// toggle block visibility
toggleVisibility: function (e) {
// prevent default event action
e.preventDefault()
// toggle visibility = template is no longer original
jsBackend.pages.template.original = false
// get index of block
var index = $(this).closest('*[data-block-id]').attr('data-block-id')
// get visibility checbox
var checkbox = $('#blockVisible' + index)
// get current visibility state
var visible = checkbox.is(':checked')
// invert visibility
visible = !visible
// change visibility state
checkbox.attr('checked', visible)
// remove current visibility indicators
$(this).find('.fa').removeClass('fa-eye fa-eye-slash')
$(this).closest('*[data-block-id]').removeClass('templateDisabled')
// toggle visibility indicators
if (visible) {
$(this).find('.fa').addClass('fa-eye')
$(this).find('.sr-only').html(jsBackend.locale.lbl('Hide'))
} else {
$(this).find('.fa').addClass('fa-eye-slash')
$(this).find('.sr-only').html(jsBackend.locale.lbl('Show'))
$(this).closest('*[data-block-id]').addClass('templateDisabled')
}
},
// display an effect on updated items
updatedBlock: function (element) {
element.effect('highlight', {color: '#D9E5F3'})
}
}
/**
* All methods related to the templates
*/
jsBackend.pages.template = {
// indicates whether or not the page content is original or has been altered already
original: true,
userTemplates: {},
// init, something like a constructor
init: function () {
// bind events
jsBackend.pages.template.changeTemplateBindSubmit()
// assign the global variable so we can use & modify it later on
jsBackend.pages.template.initDefaults = initDefaults
// load to initialize when adding a page
jsBackend.pages.template.changeTemplate()
},
// method to change a template
changeTemplate: function () {
// get checked
var selected = $('#templateList input:radio:checked').val()
// get current & old template
var old = templates[$('#templateId').val()]
var current = templates[selected]
var i = 0
// show or hide the image tab
if ('image' in current.data && current.data.image) {
$('.js-page-image-tab').show()
} else {
$('.js-page-image-tab').hide()
}
// hide default (base) block
$('#block-0').hide()
// reset HTML for the visual representation of the template
$('#templateVisual').html(current.html)
$('#templateVisualLarge').html(current.htmlLarge)
$('#templateVisualFallback .linkedBlocks').children().remove()
$('#templateId').val(selected)
$('#templateLabel, #tabTemplateLabel').html(current.label)
// make new positions sortable
jsBackend.pages.extras.sortable($('#templateVisualLarge div.linkedBlocks'))
// hide fallback by default
$('#templateVisualFallback').hide()
// remove previous fallback blocks
$('input[id^=blockPosition][value=fallback][id!=blockPosition0]').parent().remove()
// check if we have already committed changes (if not, we can just ignore existing blocks and remove all of them)
if (current !== old && jsBackend.pages.template.original) $('input[id^=blockPosition][id!=blockPosition0]').parent().remove()
// loop existing blocks
$('#editContent .contentBlock').each(function (i) {
// fetch variables
var index = parseInt($('input[id^=blockExtraId]', this).prop('id').replace('blockExtraId', ''))
var extraId = parseInt($('input[id^=blockExtraId]', this).val())
var position = $('input[id^=blockPosition]', this).val()
var html = $('textarea[id^=blockHtml]', this).val()
// skip default (base) block (= continue)
if (index === 0) return true
// blocks were present already = template was not original
jsBackend.pages.template.original = false
// check if this block is a default of the old template, in which case it'll go to the fallback position
if (current !== old && typeof old.data.default_extras !== 'undefined' && $.inArray(extraId, old.data.default_extras[position]) >= 0 && html === '') $('input[id=blockPosition' + index + ']', this).val('fallback')
})
// init var
var newDefaults = []
// check if this default block has been changed
if (current !== old || (typeof jsBackend.pages.template.initDefaults !== 'undefined' && jsBackend.pages.template.initDefaults)) {
// this is a variable indicating that the add-action may initially set default blocks
if (typeof jsBackend.pages.template.initDefaults !== 'undefined') jsBackend.pages.template.initDefaults = false
// loop positions in new template
for (var position in current.data.default_extras) {
// loop default extra's on positions
for (var block in current.data.default_extras[position]) {
// grab extraId
var extraId = current.data.default_extras[position][block]
// find existing block sent to default
var existingBlock = $('input[id^=blockPosition][value=fallback]:not(#blockPosition0)').parent().find('input[id^=blockExtraId][value=' + extraId + ']').parent()
// if this block did net yet exist, add it
if (existingBlock.length === 0) {
newDefaults.push([extraId, position])
} else {
// if this block already existed, reset it to correct (new) position
$('input[id^=blockPosition]', existingBlock).val(position)
}
}
}
}
// loop existing blocks
$('#editContent .contentBlock').each(function (i) {
// fetch variables
var index = parseInt($('input[id^=blockExtraId]', this).prop('id').replace('blockExtraId', ''))
var extraId = parseInt($('input[id^=blockExtraId]', this).val())
var extraType = $('input[id^=blockExtraType]', this).val()
var extraData = $('input[id^=blockExtraData]', this).val()
var position = $('input[id^=blockPosition]', this).val()
var visible = $('input[id^=blockVisible]', this).attr('checked')
// skip default (base) block (= continue)
if (index === 0) return true
// check if this position exists
if ($.inArray(position, current.data.names) < 0) {
// blocks in positions that do no longer exist should go to fallback
position = 'fallback'
// save position as fallback
$('input[id=blockPosition' + index + ']', this).val(position)
// show fallback
$('#templateVisualFallback').show()
}
// add visual representation of block to template visualisation
var added = jsBackend.pages.extras.addBlockVisual(position, index, extraId, visible, extraType, extraData)
// if the visual could be not added, remove the content entirely
if (!added) $(this).remove()
})
// reset block indexes
jsBackend.pages.extras.resetIndexes()
// add new defaults at last
for (i in newDefaults) {
jsBackend.pages.extras.addBlock(newDefaults[i][0], newDefaults[i][1])
}
},
// bind template change submit click event
changeTemplateBindSubmit: function (e) {
// prevent the default action
$('#changeTemplateSubmit').unbind('click').on('click', function (e) {
e.preventDefault()
if ($('#templateList input:radio:checked').val() !== $('#templateId').val()) {
// change the template for real
jsBackend.pages.template.changeTemplate()
}
// close modal
$('#changeTemplate').modal('hide')
})
}
}
/**
* All methods related to the tree
*/
jsBackend.pages.tree = {
// init, something like a constructor
init: function () {
if ($('#tree div').length === 0) return false
// add "treeHidden"-class on leafs that are hidden, only for browsers that don't support opacity
if (!jQuery.support.opacity) $('#tree ul li[rel="hidden"]').addClass('treeHidden')
var openedIds = []
if (typeof pageID !== 'undefined') {
// get parents
var parents = $('#page-' + pageID).parents('li')
// init var
openedIds = ['page-' + pageID]
// add parents
for (var i = 0; i < parents.length; i++) {
openedIds.push($(parents[i]).prop('id'))
}
}
// add home if needed
if (!utils.array.inArray('page-1', openedIds)) openedIds.push('page-1')
var options = {
ui: {theme_name: 'fork'},
opened: openedIds,
rules: {
multiple: false,
multitree: 'all',
drag_copy: false
},
lang: {loading: utils.string.ucfirst(jsBackend.locale.lbl('Loading'))},
callback: {
beforemove: jsBackend.pages.tree.beforeMove,
onselect: jsBackend.pages.tree.onSelect,
onmove: jsBackend.pages.tree.onMove
},
plugins: {
cookie: {prefix: 'jstree_', types: {selected: false}, options: {path: '/', secure: location.protocol === 'https:'}}
}
}
// create tree
$('#tree div').tree(options)
// layout fix for the tree
$('.tree li.open').each(function () {
// if the so-called open-element doesn't have any childs we should replace the open-class.
if ($(this).find('ul').length === 0) $(this).removeClass('open').addClass('leaf')
})
// set the item selected
if (typeof selectedId !== 'undefined') $('#' + selectedId).addClass('selected')
jsBackend.pages.tree.toggleJsTreeCollapse()
},
// before an item will be moved we have to do some checks
beforeMove: function (node, refNode, type, tree) {
// get pageID that has to be moved
var parentPageID
var currentPageID = $(node).prop('id').replace('page-', '')
if (typeof refNode === 'undefined') {
parentPageID = 0
} else {
parentPageID = $(refNode).prop('id').replace('page-', '')
}
// home is a special item
if (parentPageID === '1') {
if (type === 'before') return false
if (type === 'after') return false
}
// init var
var result = false
// make the call
$.ajax({
async: false, // important that this isn't asynchronous
data: {
fork: {action: 'GetInfo'},
id: currentPageID
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (jsBackend.debug) window.alert(textStatus)
result = false
},
success: function (json, textStatus) {
if (json.code !== 200) {
if (jsBackend.debug) window.alert(textStatus)
result = false
} else {
if (json.data.allow_move) result = true
}
}
})
// return
return result
},
// when an item is selected
onSelect: function (node, tree) {
// get current and new URL
var currentPageURL = window.location.pathname + window.location.search
var newPageURL = $(node).find('a').prop('href')
// only redirect if destination isn't the current one.
if (typeof newPageURL !== 'undefined' && newPageURL !== currentPageURL) window.location = newPageURL
},
// when an item is moved
onMove: function (node, refNode, type, tree, rollback) {
// get the tree
tree = tree.container.data('tree')
// get pageID that has to be moved
var currentPageID = $(node).prop('id').replace('page-', '')
// get pageID wheron the page has been dropped
var droppedOnPageID
if (typeof refNode === 'undefined') {
droppedOnPageID = 0
} else {
droppedOnPageID = $(refNode).prop('id').replace('page-', '')
}
// make the call
$.ajax({
data: {
fork: {action: 'Move'},
id: currentPageID,
dropped_on: droppedOnPageID,
type: type,
tree: tree
},
success: function (json, textStatus) {
if (json.code !== 200) {
if (jsBackend.debug) window.alert(textStatus)
// show message
jsBackend.messages.add('danger', jsBackend.locale.err('CantBeMoved'))
// rollback
$.tree.rollback(rollback)
} else {
// show message
jsBackend.messages.add('success', jsBackend.locale.msg('PageIsMoved').replace('%1$s', json.data.title))
}
}
})
},
toggleJsTreeCollapse: function () {
$('[data-role="toggle-js-tree-collapse"]').on('click', function () {
var $this = $(this)
$this.toggleClass('tree-collapsed')
var collapsed = $this.hasClass('tree-collapsed')
var $buttonText = $('[data-role="toggle-js-tree-collapse-text"]')
if (collapsed) {
$buttonText.html(jsBackend.locale.lbl('OpenTreeNavigation'))
$.each($('#tree div'), function (index, element) {
$.tree.reference($(element).attr('id')).close_all()
})
return
}
$buttonText.html(jsBackend.locale.lbl('CloseTreeNavigation'))
$.each($('#tree div'), function (index, element) {
$.tree.reference($(element).attr('id')).open_all()
})
})
}
}
$(jsBackend.pages.init)
| {
"content_hash": "6de1ed25aca1eb10ecbc53ed657e254a",
"timestamp": "",
"source": "github",
"line_count": 1580,
"max_line_length": 436,
"avg_line_length": 34.868354430379746,
"alnum_prop": 0.6089268859362521,
"repo_name": "carakas/forkcms",
"id": "5d85dbe7a218e898d9e3dab88b7a0516af2f3462",
"size": "55092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Backend/Modules/Pages/Js/Pages.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "200953"
},
{
"name": "Dockerfile",
"bytes": "2522"
},
{
"name": "HTML",
"bytes": "839240"
},
{
"name": "JavaScript",
"bytes": "746759"
},
{
"name": "PHP",
"bytes": "3237493"
},
{
"name": "Ruby",
"bytes": "4302"
},
{
"name": "Shell",
"bytes": "797"
},
{
"name": "Smarty",
"bytes": "5840"
},
{
"name": "TSQL",
"bytes": "17699"
}
],
"symlink_target": ""
} |
package com.opengamma.strata.math.impl.integration;
import static org.testng.AssertJUnit.assertEquals;
import java.util.function.Function;
import org.testng.annotations.Test;
/**
* Test.
*/
@Test
public class RungeKuttaIntegrator1DTest {
private static final double ROOT_2PI = Math.sqrt(2.0 * java.lang.Math.PI);
private static final Function<Double, Double> CUBE = new Function<Double, Double>() {
@Override
public Double apply(final Double x) {
return x * x * x;
}
};
private static final Function<Double, Double> TRIANGLE = new Function<Double, Double>() {
@Override
public Double apply(final Double x) {
if (x > 1.0 || x < 0.0)
return x - Math.floor(x);
return x;
}
};
private static final Function<Double, Double> MIX_NORM = new Function<Double, Double>() {
private final double[] W = new double[] {0.2, 0.2, 0.2, 0.2, 0.2 };
private final double[] MU = new double[] {0.0, -0.4, 0.5, 0.0, 0.01234583 };
private final double[] SIGMA = new double[] {3.0, 0.1, 5.0, 0.001, 0.0001 };
@SuppressWarnings("synthetic-access")
@Override
public Double apply(final Double x) {
final int n = W.length;
double res = 0.0;
double expo;
for (int i = 0; i < n; i++) {
expo = (x - MU[i]) * (x - MU[i]) / SIGMA[i] / SIGMA[i];
res += W[i] * Math.exp(-0.5 * expo) / ROOT_2PI / SIGMA[i];
}
return res;
}
};
private static final Function<Double, Double> SIN_INV_X = new Function<Double, Double>() {
@Override
public Double apply(final Double x) {
final double eps = 1e-127;
if (Math.abs(x) < eps)
return 0.0;
return Math.sin(1.0 / x);
}
};
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNegativeAbsTol() {
new RungeKuttaIntegrator1D(-1.0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNegativeRelTol() {
new RungeKuttaIntegrator1D(1e-7, -1.0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testLessTahnOneStep() {
new RungeKuttaIntegrator1D(0);
}
@Test
public void test() {
final double eps = 1e-9;
final int minSteps = 10;
final Integrator1D<Double, Double> integrator = new RungeKuttaIntegrator1D(eps, eps, minSteps);
double lower = 0;
double upper = 2.0;
assertEquals(4.0, integrator.integrate(CUBE, lower, upper), eps);
lower = 0.0;
upper = 1.5;
assertEquals(0.625, integrator.integrate(TRIANGLE, lower, upper), eps);
lower = -30;
upper = 30;
assertEquals(1.0, integrator.integrate(MIX_NORM, lower, upper), eps);
}
@Test
public void testCutoff() {
final double eps = 1e-9;
final int minSteps = 10;
final Integrator1D<Double, Double> integrator = new RungeKuttaIntegrator1D(eps, eps, minSteps);
final double lower = -1.0;
final double upper = 1.0;
assertEquals(0.0, integrator.integrate(SIN_INV_X, lower, upper), eps);
}
}
| {
"content_hash": "bc512a9ba942bb52cd0f31f3bfc0d288",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 99,
"avg_line_length": 25.871794871794872,
"alnum_prop": 0.6366038982490915,
"repo_name": "ChinaQuants/Strata",
"id": "c938ea91792498c8c0cbc6d4ebee518bb624d67e",
"size": "3165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/math/src/test/java/com/opengamma/strata/math/impl/integration/RungeKuttaIntegrator1DTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "23559288"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.