code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2018 Google LLC
#
# 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
#
# https://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.
#
#
# This example gets all account budget proposals. To add an account budget
# proposal, run AddAccountBudgetProposal.rb.
require 'optparse'
require 'google/ads/google_ads'
def get_account_budget_proposals(customer_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
ga_service = client.service.google_ads
search_query = <<~QUERY
SELECT
account_budget_proposal.id,
account_budget_proposal.account_budget,
account_budget_proposal.billing_setup,
account_budget_proposal.status,
account_budget_proposal.proposed_name,
account_budget_proposal.proposed_notes,
account_budget_proposal.proposed_purchase_order_number,
account_budget_proposal.proposal_type,
account_budget_proposal.approval_date_time,
account_budget_proposal.creation_date_time
FROM account_budget_proposal
QUERY
response = ga_service.search(
customer_id: customer_id,
query: search_query,
page_size: PAGE_SIZE,
)
response.each do |row|
account_budget_proposal = row.account_budget_proposal
puts sprintf('Account budget proposal with ID %s, status %s, '\
'account_budget %s, billing_setup %s, proposed_name %s, '\
'proposed_notes %s, proposed_po_number %s, proposal_type %s, '\
'approval_date_time %s, creation_date_time %s',
account_budget_proposal.id,
account_budget_proposal.account_budget,
account_budget_proposal.billing_setup,
account_budget_proposal.status,
account_budget_proposal.proposed_name,
account_budget_proposal.proposed_notes,
account_budget_proposal.proposed_purchase_order_number,
account_budget_proposal.proposal_type,
account_budget_proposal.approval_date_time,
account_budget_proposal.creation_date_time
)
end
end
if __FILE__ == $0
PAGE_SIZE = 1000
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
options[:ad_group_id] = nil
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
get_account_budget_proposals(options.fetch(:customer_id).tr("-", ""))
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
| googleads/google-ads-ruby | examples/billing/get_account_budget_proposals.rb | Ruby | apache-2.0 | 4,070 |
fuzzy-computing-machine
=======================
코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노〉〈《 / ☆○◇□△。▽♤♥ /》\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7。C0M 】→ゑ\\코리아카지노ベジ
| rgfbdsa/fuzzy-computing-machine | README.md | Markdown | apache-2.0 | 2,048 |
# Avena fatua var. sativa VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Avena/Avena sativa/ Syn. Avena fatua sativa/README.md | Markdown | apache-2.0 | 180 |
// Copyright 2017 The Oppia 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 Factory for creating new frontend instances of Interaction
* domain objects.
*/
oppia.factory('InteractionObjectFactory', [
'AnswerGroupObjectFactory', 'HintObjectFactory', 'OutcomeObjectFactory',
'SolutionObjectFactory',
function(
AnswerGroupObjectFactory, HintObjectFactory, OutcomeObjectFactory,
SolutionObjectFactory) {
var Interaction = function(
answerGroups, confirmedUnclassifiedAnswers, customizationArgs,
defaultOutcome, hints, id, solution) {
this.answerGroups = answerGroups;
this.confirmedUnclassifiedAnswers = confirmedUnclassifiedAnswers;
this.customizationArgs = customizationArgs;
this.defaultOutcome = defaultOutcome;
this.hints = hints;
this.id = id;
this.solution = solution;
};
Interaction.prototype.toBackendDict = function() {
return {
answer_groups: this.answerGroups.map(function(answerGroup) {
return answerGroup.toBackendDict();
}),
confirmed_unclassified_answers: this.confirmedUnclassifiedAnswers,
customization_args: this.customizationArgs,
default_outcome:
this.defaultOutcome ? this.defaultOutcome.toBackendDict() : null,
hints: this.hints.map(function(hint) {
return hint.toBackendDict();
}),
id: this.id,
solution: this.solution ? this.solution.toBackendDict() : null
};
};
Interaction.createFromBackendDict = function(interactionDict) {
var defaultOutcome;
if (interactionDict.default_outcome) {
defaultOutcome = OutcomeObjectFactory.createFromBackendDict(
interactionDict.default_outcome);
} else {
defaultOutcome = null;
}
return new Interaction(
generateAnswerGroupsFromBackend(interactionDict.answer_groups),
interactionDict.confirmed_unclassified_answers,
interactionDict.customization_args,
defaultOutcome,
generateHintsFromBackend(interactionDict.hints),
interactionDict.id,
interactionDict.solution ? (
generateSolutionFromBackend(interactionDict.solution)) : null);
};
var generateAnswerGroupsFromBackend = function(answerGroupBackendDicts) {
return answerGroupBackendDicts.map(function(
answerGroupBackendDict) {
return AnswerGroupObjectFactory.createFromBackendDict(
answerGroupBackendDict);
});
};
var generateHintsFromBackend = function(hintBackendDicts) {
return hintBackendDicts.map(function(hintBackendDict) {
return HintObjectFactory.createFromBackendDict(hintBackendDict);
});
};
var generateSolutionFromBackend = function(solutionBackendDict) {
return SolutionObjectFactory.createFromBackendDict(solutionBackendDict);
};
return Interaction;
}
]);
| AllanYangZhou/oppia | core/templates/dev/head/domain/exploration/InteractionObjectFactory.js | JavaScript | apache-2.0 | 3,481 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
package org.elasticsearch.client.documentation;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.MachineLearningGetResultsIT;
import org.elasticsearch.client.MachineLearningIT;
import org.elasticsearch.client.MlTestStateCleaner;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.PageParams;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.ml.CloseJobRequest;
import org.elasticsearch.client.ml.CloseJobResponse;
import org.elasticsearch.client.ml.DeleteCalendarEventRequest;
import org.elasticsearch.client.ml.DeleteCalendarJobRequest;
import org.elasticsearch.client.ml.DeleteCalendarRequest;
import org.elasticsearch.client.ml.DeleteDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.DeleteDatafeedRequest;
import org.elasticsearch.client.ml.DeleteExpiredDataRequest;
import org.elasticsearch.client.ml.DeleteExpiredDataResponse;
import org.elasticsearch.client.ml.DeleteFilterRequest;
import org.elasticsearch.client.ml.DeleteForecastRequest;
import org.elasticsearch.client.ml.DeleteJobRequest;
import org.elasticsearch.client.ml.DeleteJobResponse;
import org.elasticsearch.client.ml.DeleteModelSnapshotRequest;
import org.elasticsearch.client.ml.DeleteTrainedModelRequest;
import org.elasticsearch.client.ml.EstimateModelMemoryRequest;
import org.elasticsearch.client.ml.EstimateModelMemoryResponse;
import org.elasticsearch.client.ml.EvaluateDataFrameRequest;
import org.elasticsearch.client.ml.EvaluateDataFrameResponse;
import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsResponse;
import org.elasticsearch.client.ml.FindFileStructureRequest;
import org.elasticsearch.client.ml.FindFileStructureResponse;
import org.elasticsearch.client.ml.FlushJobRequest;
import org.elasticsearch.client.ml.FlushJobResponse;
import org.elasticsearch.client.ml.ForecastJobRequest;
import org.elasticsearch.client.ml.ForecastJobResponse;
import org.elasticsearch.client.ml.GetBucketsRequest;
import org.elasticsearch.client.ml.GetBucketsResponse;
import org.elasticsearch.client.ml.GetCalendarEventsRequest;
import org.elasticsearch.client.ml.GetCalendarEventsResponse;
import org.elasticsearch.client.ml.GetCalendarsRequest;
import org.elasticsearch.client.ml.GetCalendarsResponse;
import org.elasticsearch.client.ml.GetCategoriesRequest;
import org.elasticsearch.client.ml.GetCategoriesResponse;
import org.elasticsearch.client.ml.GetDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.GetDataFrameAnalyticsResponse;
import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsRequest;
import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsResponse;
import org.elasticsearch.client.ml.GetDatafeedRequest;
import org.elasticsearch.client.ml.GetDatafeedResponse;
import org.elasticsearch.client.ml.GetDatafeedStatsRequest;
import org.elasticsearch.client.ml.GetDatafeedStatsResponse;
import org.elasticsearch.client.ml.GetFiltersRequest;
import org.elasticsearch.client.ml.GetFiltersResponse;
import org.elasticsearch.client.ml.GetInfluencersRequest;
import org.elasticsearch.client.ml.GetInfluencersResponse;
import org.elasticsearch.client.ml.GetJobRequest;
import org.elasticsearch.client.ml.GetJobResponse;
import org.elasticsearch.client.ml.GetJobStatsRequest;
import org.elasticsearch.client.ml.GetJobStatsResponse;
import org.elasticsearch.client.ml.GetModelSnapshotsRequest;
import org.elasticsearch.client.ml.GetModelSnapshotsResponse;
import org.elasticsearch.client.ml.GetOverallBucketsRequest;
import org.elasticsearch.client.ml.GetOverallBucketsResponse;
import org.elasticsearch.client.ml.GetRecordsRequest;
import org.elasticsearch.client.ml.GetRecordsResponse;
import org.elasticsearch.client.ml.GetTrainedModelsRequest;
import org.elasticsearch.client.ml.GetTrainedModelsResponse;
import org.elasticsearch.client.ml.GetTrainedModelsStatsRequest;
import org.elasticsearch.client.ml.GetTrainedModelsStatsResponse;
import org.elasticsearch.client.ml.MlInfoRequest;
import org.elasticsearch.client.ml.MlInfoResponse;
import org.elasticsearch.client.ml.OpenJobRequest;
import org.elasticsearch.client.ml.OpenJobResponse;
import org.elasticsearch.client.ml.PostCalendarEventRequest;
import org.elasticsearch.client.ml.PostCalendarEventResponse;
import org.elasticsearch.client.ml.PostDataRequest;
import org.elasticsearch.client.ml.PostDataResponse;
import org.elasticsearch.client.ml.PreviewDatafeedRequest;
import org.elasticsearch.client.ml.PreviewDatafeedResponse;
import org.elasticsearch.client.ml.PutCalendarJobRequest;
import org.elasticsearch.client.ml.PutCalendarRequest;
import org.elasticsearch.client.ml.PutCalendarResponse;
import org.elasticsearch.client.ml.PutDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.PutDataFrameAnalyticsResponse;
import org.elasticsearch.client.ml.PutDatafeedRequest;
import org.elasticsearch.client.ml.PutDatafeedResponse;
import org.elasticsearch.client.ml.PutFilterRequest;
import org.elasticsearch.client.ml.PutFilterResponse;
import org.elasticsearch.client.ml.PutJobRequest;
import org.elasticsearch.client.ml.PutJobResponse;
import org.elasticsearch.client.ml.PutTrainedModelRequest;
import org.elasticsearch.client.ml.PutTrainedModelResponse;
import org.elasticsearch.client.ml.RevertModelSnapshotRequest;
import org.elasticsearch.client.ml.RevertModelSnapshotResponse;
import org.elasticsearch.client.ml.SetUpgradeModeRequest;
import org.elasticsearch.client.ml.StartDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.StartDataFrameAnalyticsResponse;
import org.elasticsearch.client.ml.StartDatafeedRequest;
import org.elasticsearch.client.ml.StartDatafeedResponse;
import org.elasticsearch.client.ml.StopDataFrameAnalyticsRequest;
import org.elasticsearch.client.ml.StopDataFrameAnalyticsResponse;
import org.elasticsearch.client.ml.StopDatafeedRequest;
import org.elasticsearch.client.ml.StopDatafeedResponse;
import org.elasticsearch.client.ml.UpdateDatafeedRequest;
import org.elasticsearch.client.ml.UpdateFilterRequest;
import org.elasticsearch.client.ml.UpdateJobRequest;
import org.elasticsearch.client.ml.UpdateModelSnapshotRequest;
import org.elasticsearch.client.ml.UpdateModelSnapshotResponse;
import org.elasticsearch.client.ml.calendars.Calendar;
import org.elasticsearch.client.ml.calendars.ScheduledEvent;
import org.elasticsearch.client.ml.calendars.ScheduledEventTests;
import org.elasticsearch.client.ml.datafeed.ChunkingConfig;
import org.elasticsearch.client.ml.datafeed.DatafeedConfig;
import org.elasticsearch.client.ml.datafeed.DatafeedStats;
import org.elasticsearch.client.ml.datafeed.DatafeedUpdate;
import org.elasticsearch.client.ml.datafeed.DelayedDataCheckConfig;
import org.elasticsearch.client.ml.dataframe.Classification;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalysis;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsDest;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsSource;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsState;
import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsStats;
import org.elasticsearch.client.ml.dataframe.OutlierDetection;
import org.elasticsearch.client.ml.dataframe.QueryConfig;
import org.elasticsearch.client.ml.dataframe.Regression;
import org.elasticsearch.client.ml.dataframe.evaluation.Evaluation;
import org.elasticsearch.client.ml.dataframe.evaluation.EvaluationMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.classification.AccuracyMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric.ActualClass;
import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric.PredictedClass;
import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredErrorMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.regression.RSquaredMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.AucRocMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.BinarySoftClassification;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.ConfusionMatrixMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.ConfusionMatrixMetric.ConfusionMatrix;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.PrecisionMetric;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.RecallMetric;
import org.elasticsearch.client.ml.dataframe.explain.FieldSelection;
import org.elasticsearch.client.ml.dataframe.explain.MemoryEstimation;
import org.elasticsearch.client.ml.filestructurefinder.FileStructure;
import org.elasticsearch.client.ml.inference.InferenceToXContentCompressor;
import org.elasticsearch.client.ml.inference.MlInferenceNamedXContentProvider;
import org.elasticsearch.client.ml.inference.TrainedModelConfig;
import org.elasticsearch.client.ml.inference.TrainedModelDefinition;
import org.elasticsearch.client.ml.inference.TrainedModelDefinitionTests;
import org.elasticsearch.client.ml.inference.TrainedModelInput;
import org.elasticsearch.client.ml.inference.TrainedModelStats;
import org.elasticsearch.client.ml.inference.trainedmodel.RegressionConfig;
import org.elasticsearch.client.ml.inference.trainedmodel.TargetType;
import org.elasticsearch.client.ml.job.config.AnalysisConfig;
import org.elasticsearch.client.ml.job.config.AnalysisLimits;
import org.elasticsearch.client.ml.job.config.DataDescription;
import org.elasticsearch.client.ml.job.config.DetectionRule;
import org.elasticsearch.client.ml.job.config.Detector;
import org.elasticsearch.client.ml.job.config.Job;
import org.elasticsearch.client.ml.job.config.JobUpdate;
import org.elasticsearch.client.ml.job.config.MlFilter;
import org.elasticsearch.client.ml.job.config.ModelPlotConfig;
import org.elasticsearch.client.ml.job.config.Operator;
import org.elasticsearch.client.ml.job.config.RuleCondition;
import org.elasticsearch.client.ml.job.process.DataCounts;
import org.elasticsearch.client.ml.job.process.ModelSnapshot;
import org.elasticsearch.client.ml.job.results.AnomalyRecord;
import org.elasticsearch.client.ml.job.results.Bucket;
import org.elasticsearch.client.ml.job.results.CategoryDefinition;
import org.elasticsearch.client.ml.job.results.Influencer;
import org.elasticsearch.client.ml.job.results.OverallBucket;
import org.elasticsearch.client.ml.job.stats.JobStats;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.tasks.TaskId;
import org.junit.After;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.Is.is;
public class MlClientDocumentationIT extends ESRestHighLevelClientTestCase {
@After
public void cleanUp() throws IOException {
new MlTestStateCleaner(logger, highLevelClient().machineLearning()).clearMlMetadata();
}
public void testCreateJob() throws Exception {
RestHighLevelClient client = highLevelClient();
// tag::put-job-detector
Detector.Builder detectorBuilder = new Detector.Builder()
.setFunction("sum") // <1>
.setFieldName("total") // <2>
.setDetectorDescription("Sum of total"); // <3>
// end::put-job-detector
// tag::put-job-analysis-config
List<Detector> detectors = Collections.singletonList(detectorBuilder.build()); // <1>
AnalysisConfig.Builder analysisConfigBuilder = new AnalysisConfig.Builder(detectors) // <2>
.setBucketSpan(TimeValue.timeValueMinutes(10)); // <3>
// end::put-job-analysis-config
// tag::put-job-data-description
DataDescription.Builder dataDescriptionBuilder = new DataDescription.Builder()
.setTimeField("timestamp"); // <1>
// end::put-job-data-description
{
String id = "job_1";
// tag::put-job-config
Job.Builder jobBuilder = new Job.Builder(id) // <1>
.setAnalysisConfig(analysisConfigBuilder) // <2>
.setDataDescription(dataDescriptionBuilder) // <3>
.setDescription("Total sum of requests"); // <4>
// end::put-job-config
// tag::put-job-request
PutJobRequest request = new PutJobRequest(jobBuilder.build()); // <1>
// end::put-job-request
// tag::put-job-execute
PutJobResponse response = client.machineLearning().putJob(request, RequestOptions.DEFAULT);
// end::put-job-execute
// tag::put-job-response
Date createTime = response.getResponse().getCreateTime(); // <1>
// end::put-job-response
assertThat(createTime.getTime(), greaterThan(0L));
}
{
String id = "job_2";
Job.Builder jobBuilder = new Job.Builder(id)
.setAnalysisConfig(analysisConfigBuilder)
.setDataDescription(dataDescriptionBuilder)
.setDescription("Total sum of requests");
PutJobRequest request = new PutJobRequest(jobBuilder.build());
// tag::put-job-execute-listener
ActionListener<PutJobResponse> listener = new ActionListener<PutJobResponse>() {
@Override
public void onResponse(PutJobResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-job-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-job-execute-async
client.machineLearning().putJobAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetJob() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("get-machine-learning-job1");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("get-machine-learning-job2");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
{
// tag::get-job-request
GetJobRequest request = new GetJobRequest("get-machine-learning-job1", "get-machine-learning-job*"); // <1>
request.setAllowNoJobs(true); // <2>
// end::get-job-request
// tag::get-job-execute
GetJobResponse response = client.machineLearning().getJob(request, RequestOptions.DEFAULT);
// end::get-job-execute
// tag::get-job-response
long numberOfJobs = response.count(); // <1>
List<Job> jobs = response.jobs(); // <2>
// end::get-job-response
assertEquals(2, response.count());
assertThat(response.jobs(), hasSize(2));
assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()),
containsInAnyOrder(job.getId(), secondJob.getId()));
}
{
GetJobRequest request = new GetJobRequest("get-machine-learning-job1", "get-machine-learning-job*");
// tag::get-job-execute-listener
ActionListener<GetJobResponse> listener = new ActionListener<GetJobResponse>() {
@Override
public void onResponse(GetJobResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-job-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-job-execute-async
client.machineLearning().getJobAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteJob() throws Exception {
RestHighLevelClient client = highLevelClient();
String jobId = "my-first-machine-learning-job";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("my-second-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
{
//tag::delete-job-request
DeleteJobRequest deleteJobRequest = new DeleteJobRequest("my-first-machine-learning-job"); // <1>
//end::delete-job-request
//tag::delete-job-request-force
deleteJobRequest.setForce(false); // <1>
//end::delete-job-request-force
//tag::delete-job-request-wait-for-completion
deleteJobRequest.setWaitForCompletion(true); // <1>
//end::delete-job-request-wait-for-completion
//tag::delete-job-execute
DeleteJobResponse deleteJobResponse = client.machineLearning().deleteJob(deleteJobRequest, RequestOptions.DEFAULT);
//end::delete-job-execute
//tag::delete-job-response
Boolean isAcknowledged = deleteJobResponse.getAcknowledged(); // <1>
TaskId task = deleteJobResponse.getTask(); // <2>
//end::delete-job-response
assertTrue(isAcknowledged);
assertNull(task);
}
{
//tag::delete-job-execute-listener
ActionListener<DeleteJobResponse> listener = new ActionListener<DeleteJobResponse>() {
@Override
public void onResponse(DeleteJobResponse deleteJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-job-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
DeleteJobRequest deleteJobRequest = new DeleteJobRequest("my-second-machine-learning-job");
// tag::delete-job-execute-async
client.machineLearning().deleteJobAsync(deleteJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::delete-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testOpenJob() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("opening-my-first-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("opening-my-second-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
{
// tag::open-job-request
OpenJobRequest openJobRequest = new OpenJobRequest("opening-my-first-machine-learning-job"); // <1>
openJobRequest.setTimeout(TimeValue.timeValueMinutes(10)); // <2>
// end::open-job-request
// tag::open-job-execute
OpenJobResponse openJobResponse = client.machineLearning().openJob(openJobRequest, RequestOptions.DEFAULT);
// end::open-job-execute
// tag::open-job-response
boolean isOpened = openJobResponse.isOpened(); // <1>
String node = openJobResponse.getNode(); // <2>
// end::open-job-response
assertThat(node, notNullValue());
}
{
// tag::open-job-execute-listener
ActionListener<OpenJobResponse> listener = new ActionListener<OpenJobResponse>() {
@Override
public void onResponse(OpenJobResponse openJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::open-job-execute-listener
OpenJobRequest openJobRequest = new OpenJobRequest("opening-my-second-machine-learning-job");
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::open-job-execute-async
client.machineLearning().openJobAsync(openJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::open-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testCloseJob() throws Exception {
RestHighLevelClient client = highLevelClient();
{
Job job = MachineLearningIT.buildJob("closing-my-first-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
// tag::close-job-request
CloseJobRequest closeJobRequest = new CloseJobRequest("closing-my-first-machine-learning-job", "otherjobs*"); // <1>
closeJobRequest.setForce(false); // <2>
closeJobRequest.setAllowNoJobs(true); // <3>
closeJobRequest.setTimeout(TimeValue.timeValueMinutes(10)); // <4>
// end::close-job-request
// tag::close-job-execute
CloseJobResponse closeJobResponse = client.machineLearning().closeJob(closeJobRequest, RequestOptions.DEFAULT);
// end::close-job-execute
// tag::close-job-response
boolean isClosed = closeJobResponse.isClosed(); // <1>
// end::close-job-response
}
{
Job job = MachineLearningIT.buildJob("closing-my-second-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
// tag::close-job-execute-listener
ActionListener<CloseJobResponse> listener = new ActionListener<CloseJobResponse>() {
@Override
public void onResponse(CloseJobResponse closeJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::close-job-execute-listener
CloseJobRequest closeJobRequest = new CloseJobRequest("closing-my-second-machine-learning-job");
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::close-job-execute-async
client.machineLearning().closeJobAsync(closeJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::close-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testUpdateJob() throws Exception {
RestHighLevelClient client = highLevelClient();
String jobId = "test-update-job";
Job tempJob = MachineLearningIT.buildJob(jobId);
Job job = new Job.Builder(tempJob)
.setAnalysisConfig(new AnalysisConfig.Builder(tempJob.getAnalysisConfig())
.setCategorizationFieldName("categorization-field")
.setDetector(0,
new Detector.Builder().setFieldName("total")
.setFunction("sum")
.setPartitionFieldName("mlcategory")
.setDetectorDescription(randomAlphaOfLength(10))
.build()))
.build();
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
{
List<DetectionRule> detectionRules = Arrays.asList(
new DetectionRule.Builder(Arrays.asList(RuleCondition.createTime(Operator.GT, 100L))).build());
Map<String, Object> customSettings = new HashMap<>();
customSettings.put("custom-setting-1", "custom-value");
// tag::update-job-detector-options
JobUpdate.DetectorUpdate detectorUpdate = new JobUpdate.DetectorUpdate(0, // <1>
"detector description", // <2>
detectionRules); // <3>
// end::update-job-detector-options
// tag::update-job-options
JobUpdate update = new JobUpdate.Builder(jobId) // <1>
.setDescription("My description") // <2>
.setAnalysisLimits(new AnalysisLimits(1000L, null)) // <3>
.setBackgroundPersistInterval(TimeValue.timeValueHours(3)) // <4>
.setCategorizationFilters(Arrays.asList("categorization-filter")) // <5>
.setDetectorUpdates(Arrays.asList(detectorUpdate)) // <6>
.setGroups(Arrays.asList("job-group-1")) // <7>
.setResultsRetentionDays(10L) // <8>
.setModelPlotConfig(new ModelPlotConfig(true, null, true)) // <9>
.setModelSnapshotRetentionDays(7L) // <10>
.setCustomSettings(customSettings) // <11>
.setRenormalizationWindowDays(3L) // <12>
.build();
// end::update-job-options
// tag::update-job-request
UpdateJobRequest updateJobRequest = new UpdateJobRequest(update); // <1>
// end::update-job-request
// tag::update-job-execute
PutJobResponse updateJobResponse = client.machineLearning().updateJob(updateJobRequest, RequestOptions.DEFAULT);
// end::update-job-execute
// tag::update-job-response
Job updatedJob = updateJobResponse.getResponse(); // <1>
// end::update-job-response
assertEquals(update.getDescription(), updatedJob.getDescription());
}
{
// tag::update-job-execute-listener
ActionListener<PutJobResponse> listener = new ActionListener<PutJobResponse>() {
@Override
public void onResponse(PutJobResponse updateJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::update-job-execute-listener
UpdateJobRequest updateJobRequest = new UpdateJobRequest(new JobUpdate.Builder(jobId).build());
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::update-job-execute-async
client.machineLearning().updateJobAsync(updateJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::update-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// We need to create a job for the datafeed request to be valid
String jobId = "put-datafeed-job-1";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String id = "datafeed-1";
// tag::put-datafeed-config
DatafeedConfig.Builder datafeedBuilder = new DatafeedConfig.Builder(id, jobId) // <1>
.setIndices("index_1", "index_2"); // <2>
// end::put-datafeed-config
AggregatorFactories.Builder aggs = AggregatorFactories.builder();
// tag::put-datafeed-config-set-aggregations
datafeedBuilder.setAggregations(aggs); // <1>
// end::put-datafeed-config-set-aggregations
// Clearing aggregation to avoid complex validation rules
datafeedBuilder.setAggregations((String) null);
// tag::put-datafeed-config-set-chunking-config
datafeedBuilder.setChunkingConfig(ChunkingConfig.newAuto()); // <1>
// end::put-datafeed-config-set-chunking-config
// tag::put-datafeed-config-set-frequency
datafeedBuilder.setFrequency(TimeValue.timeValueSeconds(30)); // <1>
// end::put-datafeed-config-set-frequency
// tag::put-datafeed-config-set-query
datafeedBuilder.setQuery(QueryBuilders.matchAllQuery()); // <1>
// end::put-datafeed-config-set-query
// tag::put-datafeed-config-set-query-delay
datafeedBuilder.setQueryDelay(TimeValue.timeValueMinutes(1)); // <1>
// end::put-datafeed-config-set-query-delay
// tag::put-datafeed-config-set-delayed-data-check-config
datafeedBuilder.setDelayedDataCheckConfig(DelayedDataCheckConfig
.enabledDelayedDataCheckConfig(TimeValue.timeValueHours(1))); // <1>
// end::put-datafeed-config-set-delayed-data-check-config
// no need to accidentally trip internal validations due to job bucket size
datafeedBuilder.setDelayedDataCheckConfig(null);
List<SearchSourceBuilder.ScriptField> scriptFields = Collections.emptyList();
// tag::put-datafeed-config-set-script-fields
datafeedBuilder.setScriptFields(scriptFields); // <1>
// end::put-datafeed-config-set-script-fields
// tag::put-datafeed-config-set-scroll-size
datafeedBuilder.setScrollSize(1000); // <1>
// end::put-datafeed-config-set-scroll-size
// tag::put-datafeed-request
PutDatafeedRequest request = new PutDatafeedRequest(datafeedBuilder.build()); // <1>
// end::put-datafeed-request
// tag::put-datafeed-execute
PutDatafeedResponse response = client.machineLearning().putDatafeed(request, RequestOptions.DEFAULT);
// end::put-datafeed-execute
// tag::put-datafeed-response
DatafeedConfig datafeed = response.getResponse(); // <1>
// end::put-datafeed-response
assertThat(datafeed.getId(), equalTo("datafeed-1"));
}
{
// We need to create a job for the datafeed request to be valid
String jobId = "put-datafeed-job-2";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String id = "datafeed-2";
DatafeedConfig datafeed = new DatafeedConfig.Builder(id, jobId).setIndices("index_1", "index_2").build();
PutDatafeedRequest request = new PutDatafeedRequest(datafeed);
// tag::put-datafeed-execute-listener
ActionListener<PutDatafeedResponse> listener = new ActionListener<PutDatafeedResponse>() {
@Override
public void onResponse(PutDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-datafeed-execute-async
client.machineLearning().putDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testUpdateDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("update-datafeed-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String datafeedId = job.getId() + "-feed";
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()).setIndices("foo").build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
{
AggregatorFactories.Builder aggs = AggregatorFactories.builder();
List<SearchSourceBuilder.ScriptField> scriptFields = Collections.emptyList();
// tag::update-datafeed-config
DatafeedUpdate.Builder datafeedUpdateBuilder = new DatafeedUpdate.Builder(datafeedId) // <1>
.setAggregations(aggs) // <2>
.setIndices("index_1", "index_2") // <3>
.setChunkingConfig(ChunkingConfig.newAuto()) // <4>
.setFrequency(TimeValue.timeValueSeconds(30)) // <5>
.setQuery(QueryBuilders.matchAllQuery()) // <6>
.setQueryDelay(TimeValue.timeValueMinutes(1)) // <7>
.setScriptFields(scriptFields) // <8>
.setScrollSize(1000); // <9>
// end::update-datafeed-config
// Clearing aggregation to avoid complex validation rules
datafeedUpdateBuilder.setAggregations((String) null);
// tag::update-datafeed-request
UpdateDatafeedRequest request = new UpdateDatafeedRequest(datafeedUpdateBuilder.build()); // <1>
// end::update-datafeed-request
// tag::update-datafeed-execute
PutDatafeedResponse response = client.machineLearning().updateDatafeed(request, RequestOptions.DEFAULT);
// end::update-datafeed-execute
// tag::update-datafeed-response
DatafeedConfig updatedDatafeed = response.getResponse(); // <1>
// end::update-datafeed-response
assertThat(updatedDatafeed.getId(), equalTo(datafeedId));
}
{
DatafeedUpdate datafeedUpdate = new DatafeedUpdate.Builder(datafeedId).setIndices("index_1", "index_2").build();
UpdateDatafeedRequest request = new UpdateDatafeedRequest(datafeedUpdate);
// tag::update-datafeed-execute-listener
ActionListener<PutDatafeedResponse> listener = new ActionListener<PutDatafeedResponse>() {
@Override
public void onResponse(PutDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::update-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::update-datafeed-execute-async
client.machineLearning().updateDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::update-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("get-datafeed-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String datafeedId = job.getId() + "-feed";
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()).setIndices("foo").build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
{
// tag::get-datafeed-request
GetDatafeedRequest request = new GetDatafeedRequest(datafeedId); // <1>
request.setAllowNoDatafeeds(true); // <2>
// end::get-datafeed-request
// tag::get-datafeed-execute
GetDatafeedResponse response = client.machineLearning().getDatafeed(request, RequestOptions.DEFAULT);
// end::get-datafeed-execute
// tag::get-datafeed-response
long numberOfDatafeeds = response.count(); // <1>
List<DatafeedConfig> datafeeds = response.datafeeds(); // <2>
// end::get-datafeed-response
assertEquals(1, numberOfDatafeeds);
assertEquals(1, datafeeds.size());
}
{
GetDatafeedRequest request = new GetDatafeedRequest(datafeedId);
// tag::get-datafeed-execute-listener
ActionListener<GetDatafeedResponse> listener = new ActionListener<GetDatafeedResponse>() {
@Override
public void onResponse(GetDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-datafeed-execute-async
client.machineLearning().getDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
String jobId = "test-delete-datafeed-job";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String datafeedId = "test-delete-datafeed";
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId).setIndices("foo").build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
{
// tag::delete-datafeed-request
DeleteDatafeedRequest deleteDatafeedRequest = new DeleteDatafeedRequest(datafeedId);
deleteDatafeedRequest.setForce(false); // <1>
// end::delete-datafeed-request
// tag::delete-datafeed-execute
AcknowledgedResponse deleteDatafeedResponse = client.machineLearning().deleteDatafeed(
deleteDatafeedRequest, RequestOptions.DEFAULT);
// end::delete-datafeed-execute
// tag::delete-datafeed-response
boolean isAcknowledged = deleteDatafeedResponse.isAcknowledged(); // <1>
// end::delete-datafeed-response
}
// Recreate datafeed to allow second deletion
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
{
// tag::delete-datafeed-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
DeleteDatafeedRequest deleteDatafeedRequest = new DeleteDatafeedRequest(datafeedId);
// tag::delete-datafeed-execute-async
client.machineLearning().deleteDatafeedAsync(deleteDatafeedRequest, RequestOptions.DEFAULT, listener); // <1>
// end::delete-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPreviewDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("preview-datafeed-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String datafeedId = job.getId() + "-feed";
String indexName = "preview_data_2";
createIndex(indexName);
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId())
.setIndices(indexName)
.build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
{
// tag::preview-datafeed-request
PreviewDatafeedRequest request = new PreviewDatafeedRequest(datafeedId); // <1>
// end::preview-datafeed-request
// tag::preview-datafeed-execute
PreviewDatafeedResponse response = client.machineLearning().previewDatafeed(request, RequestOptions.DEFAULT);
// end::preview-datafeed-execute
// tag::preview-datafeed-response
BytesReference rawPreview = response.getPreview(); // <1>
List<Map<String, Object>> semiParsedPreview = response.getDataList(); // <2>
// end::preview-datafeed-response
assertTrue(semiParsedPreview.isEmpty());
}
{
PreviewDatafeedRequest request = new PreviewDatafeedRequest(datafeedId);
// tag::preview-datafeed-execute-listener
ActionListener<PreviewDatafeedResponse> listener = new ActionListener<PreviewDatafeedResponse>() {
@Override
public void onResponse(PreviewDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::preview-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::preview-datafeed-execute-async
client.machineLearning().previewDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::preview-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testStartDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("start-datafeed-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
String datafeedId = job.getId() + "-feed";
String indexName = "start_data_2";
createIndex(indexName);
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId())
.setIndices(indexName)
.build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
{
// tag::start-datafeed-request
StartDatafeedRequest request = new StartDatafeedRequest(datafeedId); // <1>
// end::start-datafeed-request
// tag::start-datafeed-request-options
request.setEnd("2018-08-21T00:00:00Z"); // <1>
request.setStart("2018-08-20T00:00:00Z"); // <2>
request.setTimeout(TimeValue.timeValueMinutes(10)); // <3>
// end::start-datafeed-request-options
// tag::start-datafeed-execute
StartDatafeedResponse response = client.machineLearning().startDatafeed(request, RequestOptions.DEFAULT);
// end::start-datafeed-execute
// tag::start-datafeed-response
boolean started = response.isStarted(); // <1>
String node = response.getNode(); // <2>
// end::start-datafeed-response
assertTrue(started);
assertThat(node, notNullValue());
}
{
StartDatafeedRequest request = new StartDatafeedRequest(datafeedId);
// tag::start-datafeed-execute-listener
ActionListener<StartDatafeedResponse> listener = new ActionListener<StartDatafeedResponse>() {
@Override
public void onResponse(StartDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::start-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::start-datafeed-execute-async
client.machineLearning().startDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::start-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testStopDatafeed() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::stop-datafeed-request
StopDatafeedRequest request = new StopDatafeedRequest("datafeed_id1", "datafeed_id*"); // <1>
// end::stop-datafeed-request
request = StopDatafeedRequest.stopAllDatafeedsRequest();
// tag::stop-datafeed-request-options
request.setAllowNoDatafeeds(true); // <1>
request.setForce(true); // <2>
request.setTimeout(TimeValue.timeValueMinutes(10)); // <3>
// end::stop-datafeed-request-options
// tag::stop-datafeed-execute
StopDatafeedResponse response = client.machineLearning().stopDatafeed(request, RequestOptions.DEFAULT);
// end::stop-datafeed-execute
// tag::stop-datafeed-response
boolean stopped = response.isStopped(); // <1>
// end::stop-datafeed-response
assertTrue(stopped);
}
{
StopDatafeedRequest request = StopDatafeedRequest.stopAllDatafeedsRequest();
// tag::stop-datafeed-execute-listener
ActionListener<StopDatafeedResponse> listener = new ActionListener<StopDatafeedResponse>() {
@Override
public void onResponse(StopDatafeedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::stop-datafeed-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::stop-datafeed-execute-async
client.machineLearning().stopDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::stop-datafeed-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetDatafeedStats() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("get-machine-learning-datafeed-stats1");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("get-machine-learning-datafeed-stats2");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
String datafeedId1 = job.getId() + "-feed";
String indexName = "datafeed_stats_data_2";
createIndex(indexName);
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId1, job.getId())
.setIndices(indexName)
.build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT);
String datafeedId2 = secondJob.getId() + "-feed";
DatafeedConfig secondDatafeed = DatafeedConfig.builder(datafeedId2, secondJob.getId())
.setIndices(indexName)
.build();
client.machineLearning().putDatafeed(new PutDatafeedRequest(secondDatafeed), RequestOptions.DEFAULT);
{
//tag::get-datafeed-stats-request
GetDatafeedStatsRequest request =
new GetDatafeedStatsRequest("get-machine-learning-datafeed-stats1-feed", "get-machine-learning-datafeed*"); // <1>
request.setAllowNoDatafeeds(true); // <2>
//end::get-datafeed-stats-request
//tag::get-datafeed-stats-execute
GetDatafeedStatsResponse response = client.machineLearning().getDatafeedStats(request, RequestOptions.DEFAULT);
//end::get-datafeed-stats-execute
//tag::get-datafeed-stats-response
long numberOfDatafeedStats = response.count(); // <1>
List<DatafeedStats> datafeedStats = response.datafeedStats(); // <2>
//end::get-datafeed-stats-response
assertEquals(2, response.count());
assertThat(response.datafeedStats(), hasSize(2));
assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()),
containsInAnyOrder(datafeed.getId(), secondDatafeed.getId()));
}
{
GetDatafeedStatsRequest request = new GetDatafeedStatsRequest("*");
// tag::get-datafeed-stats-execute-listener
ActionListener<GetDatafeedStatsResponse> listener = new ActionListener<GetDatafeedStatsResponse>() {
@Override
public void onResponse(GetDatafeedStatsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-datafeed-stats-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-datafeed-stats-execute-async
client.machineLearning().getDatafeedStatsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-datafeed-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetBuckets() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-get-buckets";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a bucket
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-get-buckets\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," +
"\"bucket_span\": 600,\"is_interim\": false, \"anomaly_score\": 80.0}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::get-buckets-request
GetBucketsRequest request = new GetBucketsRequest(jobId); // <1>
// end::get-buckets-request
// tag::get-buckets-timestamp
request.setTimestamp("2018-08-17T00:00:00Z"); // <1>
// end::get-buckets-timestamp
// Set timestamp to null as it is incompatible with other args
request.setTimestamp(null);
// tag::get-buckets-anomaly-score
request.setAnomalyScore(75.0); // <1>
// end::get-buckets-anomaly-score
// tag::get-buckets-desc
request.setDescending(true); // <1>
// end::get-buckets-desc
// tag::get-buckets-end
request.setEnd("2018-08-21T00:00:00Z"); // <1>
// end::get-buckets-end
// tag::get-buckets-exclude-interim
request.setExcludeInterim(true); // <1>
// end::get-buckets-exclude-interim
// tag::get-buckets-expand
request.setExpand(true); // <1>
// end::get-buckets-expand
// tag::get-buckets-page
request.setPageParams(new PageParams(100, 200)); // <1>
// end::get-buckets-page
// Set page params back to null so the response contains the bucket we indexed
request.setPageParams(null);
// tag::get-buckets-sort
request.setSort("anomaly_score"); // <1>
// end::get-buckets-sort
// tag::get-buckets-start
request.setStart("2018-08-01T00:00:00Z"); // <1>
// end::get-buckets-start
// tag::get-buckets-execute
GetBucketsResponse response = client.machineLearning().getBuckets(request, RequestOptions.DEFAULT);
// end::get-buckets-execute
// tag::get-buckets-response
long count = response.count(); // <1>
List<Bucket> buckets = response.buckets(); // <2>
// end::get-buckets-response
assertEquals(1, buckets.size());
}
{
GetBucketsRequest request = new GetBucketsRequest(jobId);
// tag::get-buckets-execute-listener
ActionListener<GetBucketsResponse> listener =
new ActionListener<GetBucketsResponse>() {
@Override
public void onResponse(GetBucketsResponse getBucketsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-buckets-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-buckets-execute-async
client.machineLearning().getBucketsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-buckets-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testFlushJob() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("flushing-my-first-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("flushing-my-second-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(secondJob.getId()), RequestOptions.DEFAULT);
{
// tag::flush-job-request
FlushJobRequest flushJobRequest = new FlushJobRequest("flushing-my-first-machine-learning-job"); // <1>
// end::flush-job-request
// tag::flush-job-request-options
flushJobRequest.setCalcInterim(true); // <1>
flushJobRequest.setAdvanceTime("2018-08-31T16:35:07+00:00"); // <2>
flushJobRequest.setStart("2018-08-31T16:35:17+00:00"); // <3>
flushJobRequest.setEnd("2018-08-31T16:35:27+00:00"); // <4>
flushJobRequest.setSkipTime("2018-08-31T16:35:00+00:00"); // <5>
// end::flush-job-request-options
// tag::flush-job-execute
FlushJobResponse flushJobResponse = client.machineLearning().flushJob(flushJobRequest, RequestOptions.DEFAULT);
// end::flush-job-execute
// tag::flush-job-response
boolean isFlushed = flushJobResponse.isFlushed(); // <1>
Date lastFinalizedBucketEnd = flushJobResponse.getLastFinalizedBucketEnd(); // <2>
// end::flush-job-response
}
{
// tag::flush-job-execute-listener
ActionListener<FlushJobResponse> listener = new ActionListener<FlushJobResponse>() {
@Override
public void onResponse(FlushJobResponse FlushJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::flush-job-execute-listener
FlushJobRequest flushJobRequest = new FlushJobRequest("flushing-my-second-machine-learning-job");
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::flush-job-execute-async
client.machineLearning().flushJobAsync(flushJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::flush-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteForecast() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("deleting-forecast-for-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder();
for(int i = 0; i < 30; i++) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("total", randomInt(1000));
hashMap.put("timestamp", (i+1)*1000);
builder.addDoc(hashMap);
}
PostDataRequest postDataRequest = new PostDataRequest(job.getId(), builder);
client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT);
client.machineLearning().flushJob(new FlushJobRequest(job.getId()), RequestOptions.DEFAULT);
ForecastJobResponse forecastJobResponse = client.machineLearning().
forecastJob(new ForecastJobRequest(job.getId()), RequestOptions.DEFAULT);
String forecastId = forecastJobResponse.getForecastId();
GetRequest request = new GetRequest(".ml-anomalies-" + job.getId());
request.id(job.getId() + "_model_forecast_request_stats_" + forecastId);
assertBusy(() -> {
GetResponse getResponse = highLevelClient().get(request, RequestOptions.DEFAULT);
assertTrue(getResponse.isExists());
assertTrue(getResponse.getSourceAsString().contains("finished"));
}, 30, TimeUnit.SECONDS);
{
// tag::delete-forecast-request
DeleteForecastRequest deleteForecastRequest = new DeleteForecastRequest("deleting-forecast-for-job"); // <1>
// end::delete-forecast-request
// tag::delete-forecast-request-options
deleteForecastRequest.setForecastIds(forecastId); // <1>
deleteForecastRequest.timeout("30s"); // <2>
deleteForecastRequest.setAllowNoForecasts(true); // <3>
// end::delete-forecast-request-options
// tag::delete-forecast-execute
AcknowledgedResponse deleteForecastResponse = client.machineLearning().deleteForecast(deleteForecastRequest,
RequestOptions.DEFAULT);
// end::delete-forecast-execute
// tag::delete-forecast-response
boolean isAcknowledged = deleteForecastResponse.isAcknowledged(); // <1>
// end::delete-forecast-response
}
{
// tag::delete-forecast-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse DeleteForecastResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-forecast-execute-listener
DeleteForecastRequest deleteForecastRequest = DeleteForecastRequest.deleteAllForecasts(job.getId());
deleteForecastRequest.setAllowNoForecasts(true);
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-forecast-execute-async
client.machineLearning().deleteForecastAsync(deleteForecastRequest, RequestOptions.DEFAULT, listener); // <1>
// end::delete-forecast-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetJobStats() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("get-machine-learning-job-stats1");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
Job secondJob = MachineLearningIT.buildJob("get-machine-learning-job-stats2");
client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT);
{
// tag::get-job-stats-request
GetJobStatsRequest request = new GetJobStatsRequest("get-machine-learning-job-stats1", "get-machine-learning-job-*"); // <1>
request.setAllowNoJobs(true); // <2>
// end::get-job-stats-request
// tag::get-job-stats-execute
GetJobStatsResponse response = client.machineLearning().getJobStats(request, RequestOptions.DEFAULT);
// end::get-job-stats-execute
// tag::get-job-stats-response
long numberOfJobStats = response.count(); // <1>
List<JobStats> jobStats = response.jobStats(); // <2>
// end::get-job-stats-response
assertEquals(2, response.count());
assertThat(response.jobStats(), hasSize(2));
assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()),
containsInAnyOrder(job.getId(), secondJob.getId()));
}
{
GetJobStatsRequest request = new GetJobStatsRequest("get-machine-learning-job-stats1", "get-machine-learning-job-*");
// tag::get-job-stats-execute-listener
ActionListener<GetJobStatsResponse> listener = new ActionListener<GetJobStatsResponse>() {
@Override
public void onResponse(GetJobStatsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-job-stats-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-job-stats-execute-async
client.machineLearning().getJobStatsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-job-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testForecastJob() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("forecasting-my-first-machine-learning-job");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder();
for(int i = 0; i < 30; i++) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("total", randomInt(1000));
hashMap.put("timestamp", (i+1)*1000);
builder.addDoc(hashMap);
}
PostDataRequest postDataRequest = new PostDataRequest(job.getId(), builder);
client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT);
client.machineLearning().flushJob(new FlushJobRequest(job.getId()), RequestOptions.DEFAULT);
{
// tag::forecast-job-request
ForecastJobRequest forecastJobRequest = new ForecastJobRequest("forecasting-my-first-machine-learning-job"); // <1>
// end::forecast-job-request
// tag::forecast-job-request-options
forecastJobRequest.setExpiresIn(TimeValue.timeValueHours(48)); // <1>
forecastJobRequest.setDuration(TimeValue.timeValueHours(24)); // <2>
forecastJobRequest.setMaxModelMemory(new ByteSizeValue(30, ByteSizeUnit.MB)); // <3>
// end::forecast-job-request-options
// tag::forecast-job-execute
ForecastJobResponse forecastJobResponse = client.machineLearning().forecastJob(forecastJobRequest, RequestOptions.DEFAULT);
// end::forecast-job-execute
// tag::forecast-job-response
boolean isAcknowledged = forecastJobResponse.isAcknowledged(); // <1>
String forecastId = forecastJobResponse.getForecastId(); // <2>
// end::forecast-job-response
assertTrue(isAcknowledged);
assertNotNull(forecastId);
}
{
// tag::forecast-job-execute-listener
ActionListener<ForecastJobResponse> listener = new ActionListener<ForecastJobResponse>() {
@Override
public void onResponse(ForecastJobResponse forecastJobResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::forecast-job-execute-listener
ForecastJobRequest forecastJobRequest = new ForecastJobRequest("forecasting-my-first-machine-learning-job");
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::forecast-job-execute-async
client.machineLearning().forecastJobAsync(forecastJobRequest, RequestOptions.DEFAULT, listener); // <1>
// end::forecast-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetOverallBuckets() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId1 = "test-get-overall-buckets-1";
String jobId2 = "test-get-overall-buckets-2";
Job job1 = MachineLearningGetResultsIT.buildJob(jobId1);
Job job2 = MachineLearningGetResultsIT.buildJob(jobId2);
client.machineLearning().putJob(new PutJobRequest(job1), RequestOptions.DEFAULT);
client.machineLearning().putJob(new PutJobRequest(job2), RequestOptions.DEFAULT);
// Let us index some buckets
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
{
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.source("{\"job_id\":\"test-get-overall-buckets-1\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," +
"\"bucket_span\": 600,\"is_interim\": false, \"anomaly_score\": 60.0}", XContentType.JSON);
bulkRequest.add(indexRequest);
}
{
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.source("{\"job_id\":\"test-get-overall-buckets-2\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," +
"\"bucket_span\": 3600,\"is_interim\": false, \"anomaly_score\": 100.0}", XContentType.JSON);
bulkRequest.add(indexRequest);
}
client.bulk(bulkRequest, RequestOptions.DEFAULT);
{
// tag::get-overall-buckets-request
GetOverallBucketsRequest request = new GetOverallBucketsRequest(jobId1, jobId2); // <1>
// end::get-overall-buckets-request
// tag::get-overall-buckets-bucket-span
request.setBucketSpan(TimeValue.timeValueHours(24)); // <1>
// end::get-overall-buckets-bucket-span
// tag::get-overall-buckets-end
request.setEnd("2018-08-21T00:00:00Z"); // <1>
// end::get-overall-buckets-end
// tag::get-overall-buckets-exclude-interim
request.setExcludeInterim(true); // <1>
// end::get-overall-buckets-exclude-interim
// tag::get-overall-buckets-overall-score
request.setOverallScore(75.0); // <1>
// end::get-overall-buckets-overall-score
// tag::get-overall-buckets-start
request.setStart("2018-08-01T00:00:00Z"); // <1>
// end::get-overall-buckets-start
// tag::get-overall-buckets-top-n
request.setTopN(2); // <1>
// end::get-overall-buckets-top-n
// tag::get-overall-buckets-execute
GetOverallBucketsResponse response = client.machineLearning().getOverallBuckets(request, RequestOptions.DEFAULT);
// end::get-overall-buckets-execute
// tag::get-overall-buckets-response
long count = response.count(); // <1>
List<OverallBucket> overallBuckets = response.overallBuckets(); // <2>
// end::get-overall-buckets-response
assertEquals(1, overallBuckets.size());
assertThat(overallBuckets.get(0).getOverallScore(), is(closeTo(80.0, 0.001)));
}
{
GetOverallBucketsRequest request = new GetOverallBucketsRequest(jobId1, jobId2);
// tag::get-overall-buckets-execute-listener
ActionListener<GetOverallBucketsResponse> listener =
new ActionListener<GetOverallBucketsResponse>() {
@Override
public void onResponse(GetOverallBucketsResponse getOverallBucketsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-overall-buckets-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-overall-buckets-execute-async
client.machineLearning().getOverallBucketsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-overall-buckets-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetRecords() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-get-records";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a record
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-get-records\", \"result_type\":\"record\", \"timestamp\": 1533081600000," +
"\"bucket_span\": 600,\"is_interim\": false, \"record_score\": 80.0}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::get-records-request
GetRecordsRequest request = new GetRecordsRequest(jobId); // <1>
// end::get-records-request
// tag::get-records-desc
request.setDescending(true); // <1>
// end::get-records-desc
// tag::get-records-end
request.setEnd("2018-08-21T00:00:00Z"); // <1>
// end::get-records-end
// tag::get-records-exclude-interim
request.setExcludeInterim(true); // <1>
// end::get-records-exclude-interim
// tag::get-records-page
request.setPageParams(new PageParams(100, 200)); // <1>
// end::get-records-page
// Set page params back to null so the response contains the record we indexed
request.setPageParams(null);
// tag::get-records-record-score
request.setRecordScore(75.0); // <1>
// end::get-records-record-score
// tag::get-records-sort
request.setSort("probability"); // <1>
// end::get-records-sort
// tag::get-records-start
request.setStart("2018-08-01T00:00:00Z"); // <1>
// end::get-records-start
// tag::get-records-execute
GetRecordsResponse response = client.machineLearning().getRecords(request, RequestOptions.DEFAULT);
// end::get-records-execute
// tag::get-records-response
long count = response.count(); // <1>
List<AnomalyRecord> records = response.records(); // <2>
// end::get-records-response
assertEquals(1, records.size());
}
{
GetRecordsRequest request = new GetRecordsRequest(jobId);
// tag::get-records-execute-listener
ActionListener<GetRecordsResponse> listener =
new ActionListener<GetRecordsResponse>() {
@Override
public void onResponse(GetRecordsResponse getRecordsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-records-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-records-execute-async
client.machineLearning().getRecordsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-records-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPostData() throws Exception {
RestHighLevelClient client = highLevelClient();
Job job = MachineLearningIT.buildJob("test-post-data");
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT);
{
// tag::post-data-request
PostDataRequest.JsonBuilder jsonBuilder = new PostDataRequest.JsonBuilder(); // <1>
Map<String, Object> mapData = new HashMap<>();
mapData.put("total", 109);
jsonBuilder.addDoc(mapData); // <2>
jsonBuilder.addDoc("{\"total\":1000}"); // <3>
PostDataRequest postDataRequest = new PostDataRequest("test-post-data", jsonBuilder); // <4>
// end::post-data-request
// tag::post-data-request-options
postDataRequest.setResetStart("2018-08-31T16:35:07+00:00"); // <1>
postDataRequest.setResetEnd("2018-08-31T16:35:17+00:00"); // <2>
// end::post-data-request-options
postDataRequest.setResetEnd(null);
postDataRequest.setResetStart(null);
// tag::post-data-execute
PostDataResponse postDataResponse = client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT);
// end::post-data-execute
// tag::post-data-response
DataCounts dataCounts = postDataResponse.getDataCounts(); // <1>
// end::post-data-response
assertEquals(2, dataCounts.getInputRecordCount());
}
{
// tag::post-data-execute-listener
ActionListener<PostDataResponse> listener = new ActionListener<PostDataResponse>() {
@Override
public void onResponse(PostDataResponse postDataResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::post-data-execute-listener
PostDataRequest.JsonBuilder jsonBuilder = new PostDataRequest.JsonBuilder();
Map<String, Object> mapData = new HashMap<>();
mapData.put("total", 109);
jsonBuilder.addDoc(mapData);
PostDataRequest postDataRequest = new PostDataRequest("test-post-data", jsonBuilder); // <1>
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::post-data-execute-async
client.machineLearning().postDataAsync(postDataRequest, RequestOptions.DEFAULT, listener); // <1>
// end::post-data-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testFindFileStructure() throws Exception {
RestHighLevelClient client = highLevelClient();
Path anInterestingFile = createTempFile();
String contents = "{\"logger\":\"controller\",\"timestamp\":1478261151445,\"level\":\"INFO\"," +
"\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 1\",\"class\":\"ml\"," +
"\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n" +
"{\"logger\":\"controller\",\"timestamp\":1478261151445," +
"\"level\":\"INFO\",\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 2\",\"class\":\"ml\"," +
"\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n";
Files.write(anInterestingFile, Collections.singleton(contents), StandardCharsets.UTF_8);
{
// tag::find-file-structure-request
FindFileStructureRequest findFileStructureRequest = new FindFileStructureRequest(); // <1>
findFileStructureRequest.setSample(Files.readAllBytes(anInterestingFile)); // <2>
// end::find-file-structure-request
// tag::find-file-structure-request-options
findFileStructureRequest.setLinesToSample(500); // <1>
findFileStructureRequest.setExplain(true); // <2>
// end::find-file-structure-request-options
// tag::find-file-structure-execute
FindFileStructureResponse findFileStructureResponse =
client.machineLearning().findFileStructure(findFileStructureRequest, RequestOptions.DEFAULT);
// end::find-file-structure-execute
// tag::find-file-structure-response
FileStructure structure = findFileStructureResponse.getFileStructure(); // <1>
// end::find-file-structure-response
assertEquals(2, structure.getNumLinesAnalyzed());
}
{
// tag::find-file-structure-execute-listener
ActionListener<FindFileStructureResponse> listener = new ActionListener<FindFileStructureResponse>() {
@Override
public void onResponse(FindFileStructureResponse findFileStructureResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::find-file-structure-execute-listener
FindFileStructureRequest findFileStructureRequest = new FindFileStructureRequest();
findFileStructureRequest.setSample(Files.readAllBytes(anInterestingFile));
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::find-file-structure-execute-async
client.machineLearning().findFileStructureAsync(findFileStructureRequest, RequestOptions.DEFAULT, listener); // <1>
// end::find-file-structure-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetInfluencers() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-get-influencers";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a record
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-get-influencers\", \"result_type\":\"influencer\", \"timestamp\": 1533081600000," +
"\"bucket_span\": 600,\"is_interim\": false, \"influencer_score\": 80.0, \"influencer_field_name\": \"my_influencer\"," +
"\"influencer_field_value\":\"foo\"}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::get-influencers-request
GetInfluencersRequest request = new GetInfluencersRequest(jobId); // <1>
// end::get-influencers-request
// tag::get-influencers-desc
request.setDescending(true); // <1>
// end::get-influencers-desc
// tag::get-influencers-end
request.setEnd("2018-08-21T00:00:00Z"); // <1>
// end::get-influencers-end
// tag::get-influencers-exclude-interim
request.setExcludeInterim(true); // <1>
// end::get-influencers-exclude-interim
// tag::get-influencers-influencer-score
request.setInfluencerScore(75.0); // <1>
// end::get-influencers-influencer-score
// tag::get-influencers-page
request.setPageParams(new PageParams(100, 200)); // <1>
// end::get-influencers-page
// Set page params back to null so the response contains the influencer we indexed
request.setPageParams(null);
// tag::get-influencers-sort
request.setSort("probability"); // <1>
// end::get-influencers-sort
// tag::get-influencers-start
request.setStart("2018-08-01T00:00:00Z"); // <1>
// end::get-influencers-start
// tag::get-influencers-execute
GetInfluencersResponse response = client.machineLearning().getInfluencers(request, RequestOptions.DEFAULT);
// end::get-influencers-execute
// tag::get-influencers-response
long count = response.count(); // <1>
List<Influencer> influencers = response.influencers(); // <2>
// end::get-influencers-response
assertEquals(1, influencers.size());
}
{
GetInfluencersRequest request = new GetInfluencersRequest(jobId);
// tag::get-influencers-execute-listener
ActionListener<GetInfluencersResponse> listener =
new ActionListener<GetInfluencersResponse>() {
@Override
public void onResponse(GetInfluencersResponse getInfluencersResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-influencers-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-influencers-execute-async
client.machineLearning().getInfluencersAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-influencers-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetCategories() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-get-categories";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a category
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\": \"test-get-categories\", \"category_id\": 1, \"terms\": \"AAL\"," +
" \"regex\": \".*?AAL.*\", \"max_matching_length\": 3, \"examples\": [\"AAL\"]}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::get-categories-request
GetCategoriesRequest request = new GetCategoriesRequest(jobId); // <1>
// end::get-categories-request
// tag::get-categories-category-id
request.setCategoryId(1L); // <1>
// end::get-categories-category-id
// tag::get-categories-page
request.setPageParams(new PageParams(100, 200)); // <1>
// end::get-categories-page
// Set page params back to null so the response contains the category we indexed
request.setPageParams(null);
// tag::get-categories-execute
GetCategoriesResponse response = client.machineLearning().getCategories(request, RequestOptions.DEFAULT);
// end::get-categories-execute
// tag::get-categories-response
long count = response.count(); // <1>
List<CategoryDefinition> categories = response.categories(); // <2>
// end::get-categories-response
assertEquals(1, categories.size());
}
{
GetCategoriesRequest request = new GetCategoriesRequest(jobId);
// tag::get-categories-execute-listener
ActionListener<GetCategoriesResponse> listener =
new ActionListener<GetCategoriesResponse>() {
@Override
public void onResponse(GetCategoriesResponse getcategoriesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-categories-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-categories-execute-async
client.machineLearning().getCategoriesAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-categories-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteExpiredData() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-delete-expired-data";
MachineLearningIT.buildJob(jobId);
{
// tag::delete-expired-data-request
DeleteExpiredDataRequest request = new DeleteExpiredDataRequest( // <1>
null, // <2>
1000.0f, // <3>
TimeValue.timeValueHours(12) // <4>
);
// end::delete-expired-data-request
// tag::delete-expired-data-execute
DeleteExpiredDataResponse response = client.machineLearning().deleteExpiredData(request, RequestOptions.DEFAULT);
// end::delete-expired-data-execute
// tag::delete-expired-data-response
boolean deleted = response.getDeleted(); // <1>
// end::delete-expired-data-response
assertTrue(deleted);
}
{
// tag::delete-expired-data-execute-listener
ActionListener<DeleteExpiredDataResponse> listener = new ActionListener<DeleteExpiredDataResponse>() {
@Override
public void onResponse(DeleteExpiredDataResponse deleteExpiredDataResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-expired-data-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
DeleteExpiredDataRequest deleteExpiredDataRequest = new DeleteExpiredDataRequest();
// tag::delete-expired-data-execute-async
client.machineLearning().deleteExpiredDataAsync(deleteExpiredDataRequest, RequestOptions.DEFAULT, listener); // <1>
// end::delete-expired-data-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteModelSnapshot() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-delete-model-snapshot";
String snapshotId = "1541587919";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a snapshot
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " +
"\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " +
"\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" +
"\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " +
"\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," +
"\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " +
"\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," +
"\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON);
{
client.index(indexRequest, RequestOptions.DEFAULT);
// tag::delete-model-snapshot-request
DeleteModelSnapshotRequest request = new DeleteModelSnapshotRequest(jobId, snapshotId); // <1>
// end::delete-model-snapshot-request
// tag::delete-model-snapshot-execute
AcknowledgedResponse response = client.machineLearning().deleteModelSnapshot(request, RequestOptions.DEFAULT);
// end::delete-model-snapshot-execute
// tag::delete-model-snapshot-response
boolean isAcknowledged = response.isAcknowledged(); // <1>
// end::delete-model-snapshot-response
assertTrue(isAcknowledged);
}
{
client.index(indexRequest, RequestOptions.DEFAULT);
// tag::delete-model-snapshot-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-model-snapshot-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
DeleteModelSnapshotRequest deleteModelSnapshotRequest = new DeleteModelSnapshotRequest(jobId, "1541587919");
// tag::delete-model-snapshot-execute-async
client.machineLearning().deleteModelSnapshotAsync(deleteModelSnapshotRequest, RequestOptions.DEFAULT, listener); // <1>
// end::delete-model-snapshot-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetModelSnapshots() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-get-model-snapshots";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a snapshot
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared");
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-get-model-snapshots\", \"timestamp\":1541587919000, " +
"\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " +
"\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" +
"\"job_id\":\"test-get-model-snapshots\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " +
"\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," +
"\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " +
"\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," +
"\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::get-model-snapshots-request
GetModelSnapshotsRequest request = new GetModelSnapshotsRequest(jobId); // <1>
// end::get-model-snapshots-request
// tag::get-model-snapshots-snapshot-id
request.setSnapshotId("1541587919"); // <1>
// end::get-model-snapshots-snapshot-id
// Set snapshot id to null as it is incompatible with other args
request.setSnapshotId(null);
// tag::get-model-snapshots-desc
request.setDesc(true); // <1>
// end::get-model-snapshots-desc
// tag::get-model-snapshots-end
request.setEnd("2018-11-07T21:00:00Z"); // <1>
// end::get-model-snapshots-end
// tag::get-model-snapshots-page
request.setPageParams(new PageParams(100, 200)); // <1>
// end::get-model-snapshots-page
// Set page params back to null so the response contains the snapshot we indexed
request.setPageParams(null);
// tag::get-model-snapshots-sort
request.setSort("latest_result_time_stamp"); // <1>
// end::get-model-snapshots-sort
// tag::get-model-snapshots-start
request.setStart("2018-11-07T00:00:00Z"); // <1>
// end::get-model-snapshots-start
// tag::get-model-snapshots-execute
GetModelSnapshotsResponse response = client.machineLearning().getModelSnapshots(request, RequestOptions.DEFAULT);
// end::get-model-snapshots-execute
// tag::get-model-snapshots-response
long count = response.count(); // <1>
List<ModelSnapshot> modelSnapshots = response.snapshots(); // <2>
// end::get-model-snapshots-response
assertEquals(1, modelSnapshots.size());
}
{
GetModelSnapshotsRequest request = new GetModelSnapshotsRequest(jobId);
// tag::get-model-snapshots-execute-listener
ActionListener<GetModelSnapshotsResponse> listener =
new ActionListener<GetModelSnapshotsResponse>() {
@Override
public void onResponse(GetModelSnapshotsResponse getModelSnapshotsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-model-snapshots-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-model-snapshots-execute-async
client.machineLearning().getModelSnapshotsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-model-snapshots-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testRevertModelSnapshot() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-revert-model-snapshot";
String snapshotId = "1541587919";
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a snapshot
String documentId = jobId + "_model_snapshot_" + snapshotId;
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId);
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-revert-model-snapshot\", \"timestamp\":1541587919000, " +
"\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " +
"\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" +
"\"job_id\":\"test-revert-model-snapshot\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " +
"\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," +
"\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " +
"\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," +
"\"latest_result_time_stamp\":1519930800000, \"retain\":false, " +
"\"quantiles\":{\"job_id\":\"test-revert-model-snapshot\", \"timestamp\":1541587919000, " +
"\"quantile_state\":\"state\"}}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::revert-model-snapshot-request
RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId); // <1>
// end::revert-model-snapshot-request
// tag::revert-model-snapshot-delete-intervening-results
request.setDeleteInterveningResults(true); // <1>
// end::revert-model-snapshot-delete-intervening-results
// tag::revert-model-snapshot-execute
RevertModelSnapshotResponse response = client.machineLearning().revertModelSnapshot(request, RequestOptions.DEFAULT);
// end::revert-model-snapshot-execute
// tag::revert-model-snapshot-response
ModelSnapshot modelSnapshot = response.getModel(); // <1>
// end::revert-model-snapshot-response
assertEquals(snapshotId, modelSnapshot.getSnapshotId());
assertEquals("State persisted due to job close at 2018-11-07T10:51:59+0000", modelSnapshot.getDescription());
assertEquals(51722, modelSnapshot.getModelSizeStats().getModelBytes());
}
{
RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId);
// tag::revert-model-snapshot-execute-listener
ActionListener<RevertModelSnapshotResponse> listener =
new ActionListener<RevertModelSnapshotResponse>() {
@Override
public void onResponse(RevertModelSnapshotResponse revertModelSnapshotResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::revert-model-snapshot-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::revert-model-snapshot-execute-async
client.machineLearning().revertModelSnapshotAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::revert-model-snapshot-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testUpdateModelSnapshot() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String jobId = "test-update-model-snapshot";
String snapshotId = "1541587919";
String documentId = jobId + "_model_snapshot_" + snapshotId;
Job job = MachineLearningIT.buildJob(jobId);
client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT);
// Let us index a snapshot
IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId);
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
indexRequest.source("{\"job_id\":\"test-update-model-snapshot\", \"timestamp\":1541587919000, " +
"\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " +
"\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" +
"\"job_id\":\"test-update-model-snapshot\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " +
"\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," +
"\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " +
"\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," +
"\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON);
client.index(indexRequest, RequestOptions.DEFAULT);
{
// tag::update-model-snapshot-request
UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId); // <1>
// end::update-model-snapshot-request
// tag::update-model-snapshot-description
request.setDescription("My Snapshot"); // <1>
// end::update-model-snapshot-description
// tag::update-model-snapshot-retain
request.setRetain(true); // <1>
// end::update-model-snapshot-retain
// tag::update-model-snapshot-execute
UpdateModelSnapshotResponse response = client.machineLearning().updateModelSnapshot(request, RequestOptions.DEFAULT);
// end::update-model-snapshot-execute
// tag::update-model-snapshot-response
boolean acknowledged = response.getAcknowledged(); // <1>
ModelSnapshot modelSnapshot = response.getModel(); // <2>
// end::update-model-snapshot-response
assertTrue(acknowledged);
assertEquals("My Snapshot", modelSnapshot.getDescription()); }
{
UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId);
// tag::update-model-snapshot-execute-listener
ActionListener<UpdateModelSnapshotResponse> listener =
new ActionListener<UpdateModelSnapshotResponse>() {
@Override
public void onResponse(UpdateModelSnapshotResponse updateModelSnapshotResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::update-model-snapshot-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::update-model-snapshot-execute-async
client.machineLearning().updateModelSnapshotAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::update-model-snapshot-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutCalendar() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
// tag::put-calendar-request
Calendar calendar = new Calendar("public_holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest request = new PutCalendarRequest(calendar); // <1>
// end::put-calendar-request
// tag::put-calendar-execute
PutCalendarResponse response = client.machineLearning().putCalendar(request, RequestOptions.DEFAULT);
// end::put-calendar-execute
// tag::put-calendar-response
Calendar newCalendar = response.getCalendar(); // <1>
// end::put-calendar-response
assertThat(newCalendar.getId(), equalTo("public_holidays"));
// tag::put-calendar-execute-listener
ActionListener<PutCalendarResponse> listener = new ActionListener<PutCalendarResponse>() {
@Override
public void onResponse(PutCalendarResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-calendar-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-calendar-execute-async
client.machineLearning().putCalendarAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-calendar-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testPutCalendarJob() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
{
// tag::put-calendar-job-request
PutCalendarJobRequest request = new PutCalendarJobRequest("holidays", // <1>
"job_2", "job_group_1"); // <2>
// end::put-calendar-job-request
// tag::put-calendar-job-execute
PutCalendarResponse response = client.machineLearning().putCalendarJob(request, RequestOptions.DEFAULT);
// end::put-calendar-job-execute
// tag::put-calendar-job-response
Calendar updatedCalendar = response.getCalendar(); // <1>
// end::put-calendar-job-response
assertThat(updatedCalendar.getJobIds(), containsInAnyOrder("job_1", "job_2", "job_group_1"));
}
{
PutCalendarJobRequest request = new PutCalendarJobRequest("holidays", "job_4");
// tag::put-calendar-job-execute-listener
ActionListener<PutCalendarResponse> listener =
new ActionListener<PutCalendarResponse>() {
@Override
public void onResponse(PutCalendarResponse putCalendarsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-calendar-job-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-calendar-job-execute-async
client.machineLearning().putCalendarJobAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-calendar-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteCalendarJob() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays",
Arrays.asList("job_1", "job_group_1", "job_2"),
"A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
{
// tag::delete-calendar-job-request
DeleteCalendarJobRequest request = new DeleteCalendarJobRequest("holidays", // <1>
"job_1", "job_group_1"); // <2>
// end::delete-calendar-job-request
// tag::delete-calendar-job-execute
PutCalendarResponse response = client.machineLearning().deleteCalendarJob(request, RequestOptions.DEFAULT);
// end::delete-calendar-job-execute
// tag::delete-calendar-job-response
Calendar updatedCalendar = response.getCalendar(); // <1>
// end::delete-calendar-job-response
assertThat(updatedCalendar.getJobIds(), containsInAnyOrder("job_2"));
}
{
DeleteCalendarJobRequest request = new DeleteCalendarJobRequest("holidays", "job_2");
// tag::delete-calendar-job-execute-listener
ActionListener<PutCalendarResponse> listener =
new ActionListener<PutCalendarResponse>() {
@Override
public void onResponse(PutCalendarResponse deleteCalendarsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-calendar-job-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-calendar-job-execute-async
client.machineLearning().deleteCalendarJobAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-calendar-job-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetCalendar() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
{
// tag::get-calendars-request
GetCalendarsRequest request = new GetCalendarsRequest(); // <1>
// end::get-calendars-request
// tag::get-calendars-id
request.setCalendarId("holidays"); // <1>
// end::get-calendars-id
// tag::get-calendars-page
request.setPageParams(new PageParams(10, 20)); // <1>
// end::get-calendars-page
// reset page params
request.setPageParams(null);
// tag::get-calendars-execute
GetCalendarsResponse response = client.machineLearning().getCalendars(request, RequestOptions.DEFAULT);
// end::get-calendars-execute
// tag::get-calendars-response
long count = response.count(); // <1>
List<Calendar> calendars = response.calendars(); // <2>
// end::get-calendars-response
assertEquals(1, calendars.size());
}
{
GetCalendarsRequest request = new GetCalendarsRequest("holidays");
// tag::get-calendars-execute-listener
ActionListener<GetCalendarsResponse> listener =
new ActionListener<GetCalendarsResponse>() {
@Override
public void onResponse(GetCalendarsResponse getCalendarsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-calendars-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-calendars-execute-async
client.machineLearning().getCalendarsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-calendars-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteCalendar() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest putCalendarRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putCalendarRequest, RequestOptions.DEFAULT);
// tag::delete-calendar-request
DeleteCalendarRequest request = new DeleteCalendarRequest("holidays"); // <1>
// end::delete-calendar-request
// tag::delete-calendar-execute
AcknowledgedResponse response = client.machineLearning().deleteCalendar(request, RequestOptions.DEFAULT);
// end::delete-calendar-execute
// tag::delete-calendar-response
boolean isAcknowledged = response.isAcknowledged(); // <1>
// end::delete-calendar-response
assertTrue(isAcknowledged);
// tag::delete-calendar-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-calendar-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-calendar-execute-async
client.machineLearning().deleteCalendarAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-calendar-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testGetCalendarEvent() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance(calendar.getId(), null));
client.machineLearning().postCalendarEvent(new PostCalendarEventRequest("holidays", events), RequestOptions.DEFAULT);
{
// tag::get-calendar-events-request
GetCalendarEventsRequest request = new GetCalendarEventsRequest("holidays"); // <1>
// end::get-calendar-events-request
// tag::get-calendar-events-page
request.setPageParams(new PageParams(10, 20)); // <1>
// end::get-calendar-events-page
// tag::get-calendar-events-start
request.setStart("2018-08-01T00:00:00Z"); // <1>
// end::get-calendar-events-start
// tag::get-calendar-events-end
request.setEnd("2018-08-02T00:00:00Z"); // <1>
// end::get-calendar-events-end
// tag::get-calendar-events-jobid
request.setJobId("job_1"); // <1>
// end::get-calendar-events-jobid
// reset params
request.setPageParams(null);
request.setJobId(null);
request.setStart(null);
request.setEnd(null);
// tag::get-calendar-events-execute
GetCalendarEventsResponse response = client.machineLearning().getCalendarEvents(request, RequestOptions.DEFAULT);
// end::get-calendar-events-execute
// tag::get-calendar-events-response
long count = response.count(); // <1>
List<ScheduledEvent> scheduledEvents = response.events(); // <2>
// end::get-calendar-events-response
assertEquals(1, scheduledEvents.size());
}
{
GetCalendarEventsRequest request = new GetCalendarEventsRequest("holidays");
// tag::get-calendar-events-execute-listener
ActionListener<GetCalendarEventsResponse> listener =
new ActionListener<GetCalendarEventsResponse>() {
@Override
public void onResponse(GetCalendarEventsResponse getCalendarsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-calendar-events-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-calendar-events-execute-async
client.machineLearning().getCalendarEventsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-calendar-events-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPostCalendarEvent() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
{
List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance(calendar.getId(), null));
// tag::post-calendar-event-request
PostCalendarEventRequest request = new PostCalendarEventRequest("holidays", // <1>
events); // <2>
// end::post-calendar-event-request
// tag::post-calendar-event-execute
PostCalendarEventResponse response = client.machineLearning().postCalendarEvent(request, RequestOptions.DEFAULT);
// end::post-calendar-event-execute
// tag::post-calendar-event-response
List<ScheduledEvent> scheduledEvents = response.getScheduledEvents(); // <1>
// end::post-calendar-event-response
assertEquals(1, scheduledEvents.size());
}
{
List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance());
PostCalendarEventRequest request = new PostCalendarEventRequest("holidays", events); // <1>
// tag::post-calendar-event-execute-listener
ActionListener<PostCalendarEventResponse> listener =
new ActionListener<PostCalendarEventResponse>() {
@Override
public void onResponse(PostCalendarEventResponse postCalendarsResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::post-calendar-event-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::post-calendar-event-execute-async
client.machineLearning().postCalendarEventAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::post-calendar-event-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteCalendarEvent() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
Calendar calendar = new Calendar("holidays",
Arrays.asList("job_1", "job_group_1", "job_2"),
"A calendar for public holidays");
PutCalendarRequest putRequest = new PutCalendarRequest(calendar);
client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT);
List<ScheduledEvent> events = Arrays.asList(ScheduledEventTests.testInstance(calendar.getId(), null),
ScheduledEventTests.testInstance(calendar.getId(), null));
client.machineLearning().postCalendarEvent(new PostCalendarEventRequest("holidays", events), RequestOptions.DEFAULT);
GetCalendarEventsResponse getCalendarEventsResponse =
client.machineLearning().getCalendarEvents(new GetCalendarEventsRequest("holidays"), RequestOptions.DEFAULT);
{
// tag::delete-calendar-event-request
DeleteCalendarEventRequest request = new DeleteCalendarEventRequest("holidays", // <1>
"EventId"); // <2>
// end::delete-calendar-event-request
request = new DeleteCalendarEventRequest("holidays", getCalendarEventsResponse.events().get(0).getEventId());
// tag::delete-calendar-event-execute
AcknowledgedResponse response = client.machineLearning().deleteCalendarEvent(request, RequestOptions.DEFAULT);
// end::delete-calendar-event-execute
// tag::delete-calendar-event-response
boolean acknowledged = response.isAcknowledged(); // <1>
// end::delete-calendar-event-response
assertThat(acknowledged, is(true));
}
{
DeleteCalendarEventRequest request = new DeleteCalendarEventRequest("holidays",
getCalendarEventsResponse.events().get(1).getEventId());
// tag::delete-calendar-event-execute-listener
ActionListener<AcknowledgedResponse> listener =
new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse deleteCalendarEventResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-calendar-event-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-calendar-event-execute-async
client.machineLearning().deleteCalendarEventAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-calendar-event-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetDataFrameAnalytics() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
RestHighLevelClient client = highLevelClient();
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
// tag::get-data-frame-analytics-request
GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("my-analytics-config"); // <1>
// end::get-data-frame-analytics-request
// tag::get-data-frame-analytics-execute
GetDataFrameAnalyticsResponse response = client.machineLearning().getDataFrameAnalytics(request, RequestOptions.DEFAULT);
// end::get-data-frame-analytics-execute
// tag::get-data-frame-analytics-response
List<DataFrameAnalyticsConfig> configs = response.getAnalytics();
// end::get-data-frame-analytics-response
assertThat(configs, hasSize(1));
}
{
GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("my-analytics-config");
// tag::get-data-frame-analytics-execute-listener
ActionListener<GetDataFrameAnalyticsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(GetDataFrameAnalyticsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-data-frame-analytics-execute-async
client.machineLearning().getDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetDataFrameAnalyticsStats() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
RestHighLevelClient client = highLevelClient();
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
// tag::get-data-frame-analytics-stats-request
GetDataFrameAnalyticsStatsRequest request = new GetDataFrameAnalyticsStatsRequest("my-analytics-config"); // <1>
// end::get-data-frame-analytics-stats-request
// tag::get-data-frame-analytics-stats-execute
GetDataFrameAnalyticsStatsResponse response =
client.machineLearning().getDataFrameAnalyticsStats(request, RequestOptions.DEFAULT);
// end::get-data-frame-analytics-stats-execute
// tag::get-data-frame-analytics-stats-response
List<DataFrameAnalyticsStats> stats = response.getAnalyticsStats();
// end::get-data-frame-analytics-stats-response
assertThat(stats, hasSize(1));
}
{
GetDataFrameAnalyticsStatsRequest request = new GetDataFrameAnalyticsStatsRequest("my-analytics-config");
// tag::get-data-frame-analytics-stats-execute-listener
ActionListener<GetDataFrameAnalyticsStatsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(GetDataFrameAnalyticsStatsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-data-frame-analytics-stats-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-data-frame-analytics-stats-execute-async
client.machineLearning().getDataFrameAnalyticsStatsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-data-frame-analytics-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutDataFrameAnalytics() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
RestHighLevelClient client = highLevelClient();
{
// tag::put-data-frame-analytics-query-config
QueryConfig queryConfig = new QueryConfig(new MatchAllQueryBuilder());
// end::put-data-frame-analytics-query-config
// tag::put-data-frame-analytics-source-config
DataFrameAnalyticsSource sourceConfig = DataFrameAnalyticsSource.builder() // <1>
.setIndex("put-test-source-index") // <2>
.setQueryConfig(queryConfig) // <3>
.setSourceFiltering(new FetchSourceContext(true,
new String[] { "included_field_1", "included_field_2" },
new String[] { "excluded_field" })) // <4>
.build();
// end::put-data-frame-analytics-source-config
// tag::put-data-frame-analytics-dest-config
DataFrameAnalyticsDest destConfig = DataFrameAnalyticsDest.builder() // <1>
.setIndex("put-test-dest-index") // <2>
.build();
// end::put-data-frame-analytics-dest-config
// tag::put-data-frame-analytics-outlier-detection-default
DataFrameAnalysis outlierDetection = OutlierDetection.createDefault(); // <1>
// end::put-data-frame-analytics-outlier-detection-default
// tag::put-data-frame-analytics-outlier-detection-customized
DataFrameAnalysis outlierDetectionCustomized = OutlierDetection.builder() // <1>
.setMethod(OutlierDetection.Method.DISTANCE_KNN) // <2>
.setNNeighbors(5) // <3>
.setFeatureInfluenceThreshold(0.1) // <4>
.setComputeFeatureInfluence(true) // <5>
.setOutlierFraction(0.05) // <6>
.setStandardizationEnabled(true) // <7>
.build();
// end::put-data-frame-analytics-outlier-detection-customized
// tag::put-data-frame-analytics-classification
DataFrameAnalysis classification = Classification.builder("my_dependent_variable") // <1>
.setLambda(1.0) // <2>
.setGamma(5.5) // <3>
.setEta(5.5) // <4>
.setMaxTrees(50) // <5>
.setFeatureBagFraction(0.4) // <6>
.setNumTopFeatureImportanceValues(3) // <7>
.setPredictionFieldName("my_prediction_field_name") // <8>
.setTrainingPercent(50.0) // <9>
.setRandomizeSeed(1234L) // <10>
.setClassAssignmentObjective(Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY) // <11>
.setNumTopClasses(1) // <12>
.build();
// end::put-data-frame-analytics-classification
// tag::put-data-frame-analytics-regression
DataFrameAnalysis regression = org.elasticsearch.client.ml.dataframe.Regression.builder("my_dependent_variable") // <1>
.setLambda(1.0) // <2>
.setGamma(5.5) // <3>
.setEta(5.5) // <4>
.setMaxTrees(50) // <5>
.setFeatureBagFraction(0.4) // <6>
.setNumTopFeatureImportanceValues(3) // <7>
.setPredictionFieldName("my_prediction_field_name") // <8>
.setTrainingPercent(50.0) // <9>
.setRandomizeSeed(1234L) // <10>
.setLossFunction(Regression.LossFunction.MSE) // <11>
.setLossFunctionParameter(1.0) // <12>
.build();
// end::put-data-frame-analytics-regression
// tag::put-data-frame-analytics-analyzed-fields
FetchSourceContext analyzedFields =
new FetchSourceContext(
true,
new String[] { "included_field_1", "included_field_2" },
new String[] { "excluded_field" });
// end::put-data-frame-analytics-analyzed-fields
// tag::put-data-frame-analytics-config
DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder()
.setId("my-analytics-config") // <1>
.setSource(sourceConfig) // <2>
.setDest(destConfig) // <3>
.setAnalysis(outlierDetection) // <4>
.setAnalyzedFields(analyzedFields) // <5>
.setModelMemoryLimit(new ByteSizeValue(5, ByteSizeUnit.MB)) // <6>
.setDescription("this is an example description") // <7>
.build();
// end::put-data-frame-analytics-config
// tag::put-data-frame-analytics-request
PutDataFrameAnalyticsRequest request = new PutDataFrameAnalyticsRequest(config); // <1>
// end::put-data-frame-analytics-request
// tag::put-data-frame-analytics-execute
PutDataFrameAnalyticsResponse response = client.machineLearning().putDataFrameAnalytics(request, RequestOptions.DEFAULT);
// end::put-data-frame-analytics-execute
// tag::put-data-frame-analytics-response
DataFrameAnalyticsConfig createdConfig = response.getConfig();
// end::put-data-frame-analytics-response
assertThat(createdConfig.getId(), equalTo("my-analytics-config"));
}
{
PutDataFrameAnalyticsRequest request = new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG);
// tag::put-data-frame-analytics-execute-listener
ActionListener<PutDataFrameAnalyticsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(PutDataFrameAnalyticsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-data-frame-analytics-execute-async
client.machineLearning().putDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteDataFrameAnalytics() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
RestHighLevelClient client = highLevelClient();
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
// tag::delete-data-frame-analytics-request
DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("my-analytics-config"); // <1>
// end::delete-data-frame-analytics-request
//tag::delete-data-frame-analytics-request-options
request.setForce(false); // <1>
request.setTimeout(TimeValue.timeValueMinutes(1)); // <2>
//end::delete-data-frame-analytics-request-options
// tag::delete-data-frame-analytics-execute
AcknowledgedResponse response = client.machineLearning().deleteDataFrameAnalytics(request, RequestOptions.DEFAULT);
// end::delete-data-frame-analytics-execute
// tag::delete-data-frame-analytics-response
boolean acknowledged = response.isAcknowledged();
// end::delete-data-frame-analytics-response
assertThat(acknowledged, is(true));
}
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("my-analytics-config");
// tag::delete-data-frame-analytics-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-data-frame-analytics-execute-async
client.machineLearning().deleteDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testStartDataFrameAnalytics() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
highLevelClient().index(
new IndexRequest(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]).source(XContentType.JSON, "total", 10000)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT);
RestHighLevelClient client = highLevelClient();
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
// tag::start-data-frame-analytics-request
StartDataFrameAnalyticsRequest request = new StartDataFrameAnalyticsRequest("my-analytics-config"); // <1>
// end::start-data-frame-analytics-request
// tag::start-data-frame-analytics-execute
StartDataFrameAnalyticsResponse response = client.machineLearning().startDataFrameAnalytics(request, RequestOptions.DEFAULT);
// end::start-data-frame-analytics-execute
// tag::start-data-frame-analytics-response
boolean acknowledged = response.isAcknowledged();
String node = response.getNode(); // <1>
// end::start-data-frame-analytics-response
assertThat(acknowledged, is(true));
assertThat(node, notNullValue());
}
assertBusy(
() -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)),
30, TimeUnit.SECONDS);
{
StartDataFrameAnalyticsRequest request = new StartDataFrameAnalyticsRequest("my-analytics-config");
// tag::start-data-frame-analytics-execute-listener
ActionListener<StartDataFrameAnalyticsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(StartDataFrameAnalyticsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::start-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::start-data-frame-analytics-execute-async
client.machineLearning().startDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::start-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
assertBusy(
() -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)),
30, TimeUnit.SECONDS);
}
public void testStopDataFrameAnalytics() throws Exception {
createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]);
highLevelClient().index(
new IndexRequest(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]).source(XContentType.JSON, "total", 10000)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT);
RestHighLevelClient client = highLevelClient();
client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT);
{
// tag::stop-data-frame-analytics-request
StopDataFrameAnalyticsRequest request = new StopDataFrameAnalyticsRequest("my-analytics-config"); // <1>
request.setForce(false); // <2>
// end::stop-data-frame-analytics-request
// tag::stop-data-frame-analytics-execute
StopDataFrameAnalyticsResponse response = client.machineLearning().stopDataFrameAnalytics(request, RequestOptions.DEFAULT);
// end::stop-data-frame-analytics-execute
// tag::stop-data-frame-analytics-response
boolean acknowledged = response.isStopped();
// end::stop-data-frame-analytics-response
assertThat(acknowledged, is(true));
}
assertBusy(
() -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)),
30, TimeUnit.SECONDS);
{
StopDataFrameAnalyticsRequest request = new StopDataFrameAnalyticsRequest("my-analytics-config");
// tag::stop-data-frame-analytics-execute-listener
ActionListener<StopDataFrameAnalyticsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(StopDataFrameAnalyticsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::stop-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::stop-data-frame-analytics-execute-async
client.machineLearning().stopDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::stop-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
assertBusy(
() -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)),
30, TimeUnit.SECONDS);
}
public void testEvaluateDataFrame() throws Exception {
String indexName = "evaluate-test-index";
CreateIndexRequest createIndexRequest =
new CreateIndexRequest(indexName)
.mapping(XContentFactory.jsonBuilder().startObject()
.startObject("properties")
.startObject("label")
.field("type", "keyword")
.endObject()
.startObject("p")
.field("type", "double")
.endObject()
.endObject()
.endObject());
BulkRequest bulkRequest =
new BulkRequest(indexName)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.1)) // #0
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.2)) // #1
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.3)) // #2
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.4)) // #3
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.7)) // #4
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.2)) // #5
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.3)) // #6
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.4)) // #7
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.8)) // #8
.add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.9)); // #9
RestHighLevelClient client = highLevelClient();
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
client.bulk(bulkRequest, RequestOptions.DEFAULT);
{
// tag::evaluate-data-frame-evaluation-softclassification
Evaluation evaluation =
new BinarySoftClassification( // <1>
"label", // <2>
"p", // <3>
// Evaluation metrics // <4>
PrecisionMetric.at(0.4, 0.5, 0.6), // <5>
RecallMetric.at(0.5, 0.7), // <6>
ConfusionMatrixMetric.at(0.5), // <7>
AucRocMetric.withCurve()); // <8>
// end::evaluate-data-frame-evaluation-softclassification
// tag::evaluate-data-frame-request
EvaluateDataFrameRequest request =
new EvaluateDataFrameRequest( // <1>
indexName, // <2>
new QueryConfig(QueryBuilders.termQuery("dataset", "blue")), // <3>
evaluation); // <4>
// end::evaluate-data-frame-request
// tag::evaluate-data-frame-execute
EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT);
// end::evaluate-data-frame-execute
// tag::evaluate-data-frame-response
List<EvaluationMetric.Result> metrics = response.getMetrics(); // <1>
// end::evaluate-data-frame-response
// tag::evaluate-data-frame-results-softclassification
PrecisionMetric.Result precisionResult = response.getMetricByName(PrecisionMetric.NAME); // <1>
double precision = precisionResult.getScoreByThreshold("0.4"); // <2>
ConfusionMatrixMetric.Result confusionMatrixResult = response.getMetricByName(ConfusionMatrixMetric.NAME); // <3>
ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); // <4>
// end::evaluate-data-frame-results-softclassification
assertThat(
metrics.stream().map(EvaluationMetric.Result::getMetricName).collect(Collectors.toList()),
containsInAnyOrder(PrecisionMetric.NAME, RecallMetric.NAME, ConfusionMatrixMetric.NAME, AucRocMetric.NAME));
assertThat(precision, closeTo(0.6, 1e-9));
assertThat(confusionMatrix.getTruePositives(), equalTo(2L)); // docs #8 and #9
assertThat(confusionMatrix.getFalsePositives(), equalTo(1L)); // doc #4
assertThat(confusionMatrix.getTrueNegatives(), equalTo(4L)); // docs #0, #1, #2 and #3
assertThat(confusionMatrix.getFalseNegatives(), equalTo(3L)); // docs #5, #6 and #7
}
{
EvaluateDataFrameRequest request = new EvaluateDataFrameRequest(
indexName,
new QueryConfig(QueryBuilders.termQuery("dataset", "blue")),
new BinarySoftClassification(
"label",
"p",
PrecisionMetric.at(0.4, 0.5, 0.6),
RecallMetric.at(0.5, 0.7),
ConfusionMatrixMetric.at(0.5),
AucRocMetric.withCurve()));
// tag::evaluate-data-frame-execute-listener
ActionListener<EvaluateDataFrameResponse> listener = new ActionListener<>() {
@Override
public void onResponse(EvaluateDataFrameResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::evaluate-data-frame-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::evaluate-data-frame-execute-async
client.machineLearning().evaluateDataFrameAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::evaluate-data-frame-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testEvaluateDataFrame_Classification() throws Exception {
String indexName = "evaluate-classification-test-index";
CreateIndexRequest createIndexRequest =
new CreateIndexRequest(indexName)
.mapping(XContentFactory.jsonBuilder().startObject()
.startObject("properties")
.startObject("actual_class")
.field("type", "keyword")
.endObject()
.startObject("predicted_class")
.field("type", "keyword")
.endObject()
.endObject()
.endObject());
BulkRequest bulkRequest =
new BulkRequest(indexName)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #0
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #1
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #2
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "dog")) // #3
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "fox")) // #4
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "cat")) // #5
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #6
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #7
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #8
.add(new IndexRequest().source(XContentType.JSON, "actual_class", "ant", "predicted_class", "cat")); // #9
RestHighLevelClient client = highLevelClient();
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
client.bulk(bulkRequest, RequestOptions.DEFAULT);
{
// tag::evaluate-data-frame-evaluation-classification
Evaluation evaluation =
new org.elasticsearch.client.ml.dataframe.evaluation.classification.Classification( // <1>
"actual_class", // <2>
"predicted_class", // <3>
// Evaluation metrics // <4>
new AccuracyMetric(), // <5>
new org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric(), // <6>
new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric(), // <7>
new MulticlassConfusionMatrixMetric(3)); // <8>
// end::evaluate-data-frame-evaluation-classification
EvaluateDataFrameRequest request = new EvaluateDataFrameRequest(indexName, null, evaluation);
EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT);
// tag::evaluate-data-frame-results-classification
AccuracyMetric.Result accuracyResult = response.getMetricByName(AccuracyMetric.NAME); // <1>
double accuracy = accuracyResult.getOverallAccuracy(); // <2>
org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.Result precisionResult =
response.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME); // <3>
double precision = precisionResult.getAvgPrecision(); // <4>
org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.Result recallResult =
response.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME); // <5>
double recall = recallResult.getAvgRecall(); // <6>
MulticlassConfusionMatrixMetric.Result multiclassConfusionMatrix =
response.getMetricByName(MulticlassConfusionMatrixMetric.NAME); // <7>
List<ActualClass> confusionMatrix = multiclassConfusionMatrix.getConfusionMatrix(); // <8>
long otherClassesCount = multiclassConfusionMatrix.getOtherActualClassCount(); // <9>
// end::evaluate-data-frame-results-classification
assertThat(accuracyResult.getMetricName(), equalTo(AccuracyMetric.NAME));
assertThat(accuracy, equalTo(0.6));
assertThat(
precisionResult.getMetricName(),
equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME));
assertThat(precision, equalTo(0.675));
assertThat(
recallResult.getMetricName(),
equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME));
assertThat(recall, equalTo(0.45));
assertThat(multiclassConfusionMatrix.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME));
assertThat(
confusionMatrix,
equalTo(
List.of(
new ActualClass(
"ant",
1L,
List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 1L), new PredictedClass("dog", 0L)),
0L),
new ActualClass(
"cat",
5L,
List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 3L), new PredictedClass("dog", 1L)),
1L),
new ActualClass(
"dog",
4L,
List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 1L), new PredictedClass("dog", 3L)),
0L))));
assertThat(otherClassesCount, equalTo(0L));
}
}
public void testEvaluateDataFrame_Regression() throws Exception {
String indexName = "evaluate-classification-test-index";
CreateIndexRequest createIndexRequest =
new CreateIndexRequest(indexName)
.mapping(XContentFactory.jsonBuilder().startObject()
.startObject("properties")
.startObject("actual_value")
.field("type", "double")
.endObject()
.startObject("predicted_value")
.field("type", "double")
.endObject()
.endObject()
.endObject());
BulkRequest bulkRequest =
new BulkRequest(indexName)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.0, "predicted_value", 1.0)) // #0
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.0, "predicted_value", 0.9)) // #1
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.0, "predicted_value", 2.0)) // #2
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.5, "predicted_value", 1.4)) // #3
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.2, "predicted_value", 1.3)) // #4
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.7, "predicted_value", 2.0)) // #5
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.1, "predicted_value", 2.1)) // #6
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.5, "predicted_value", 2.7)) // #7
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 0.8, "predicted_value", 1.0)) // #8
.add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.5, "predicted_value", 2.4)); // #9
RestHighLevelClient client = highLevelClient();
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
client.bulk(bulkRequest, RequestOptions.DEFAULT);
{
// tag::evaluate-data-frame-evaluation-regression
Evaluation evaluation =
new org.elasticsearch.client.ml.dataframe.evaluation.regression.Regression( // <1>
"actual_value", // <2>
"predicted_value", // <3>
// Evaluation metrics // <4>
new MeanSquaredErrorMetric(), // <5>
new RSquaredMetric()); // <6>
// end::evaluate-data-frame-evaluation-regression
EvaluateDataFrameRequest request = new EvaluateDataFrameRequest(indexName, null, evaluation);
EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT);
// tag::evaluate-data-frame-results-regression
MeanSquaredErrorMetric.Result meanSquaredErrorResult = response.getMetricByName(MeanSquaredErrorMetric.NAME); // <1>
double meanSquaredError = meanSquaredErrorResult.getError(); // <2>
RSquaredMetric.Result rSquaredResult = response.getMetricByName(RSquaredMetric.NAME); // <3>
double rSquared = rSquaredResult.getValue(); // <4>
// end::evaluate-data-frame-results-regression
assertThat(meanSquaredError, closeTo(0.021, 1e-3));
assertThat(rSquared, closeTo(0.941, 1e-3));
}
}
public void testExplainDataFrameAnalytics() throws Exception {
createIndex("explain-df-test-source-index");
BulkRequest bulkRequest =
new BulkRequest("explain-df-test-source-index")
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
for (int i = 0; i < 10; ++i) {
bulkRequest.add(new IndexRequest().source(XContentType.JSON, "timestamp", 123456789L, "total", 10L));
}
RestHighLevelClient client = highLevelClient();
client.bulk(bulkRequest, RequestOptions.DEFAULT);
{
// tag::explain-data-frame-analytics-id-request
ExplainDataFrameAnalyticsRequest request = new ExplainDataFrameAnalyticsRequest("existing_job_id"); // <1>
// end::explain-data-frame-analytics-id-request
// tag::explain-data-frame-analytics-config-request
DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder()
.setSource(DataFrameAnalyticsSource.builder().setIndex("explain-df-test-source-index").build())
.setAnalysis(OutlierDetection.createDefault())
.build();
request = new ExplainDataFrameAnalyticsRequest(config); // <1>
// end::explain-data-frame-analytics-config-request
// tag::explain-data-frame-analytics-execute
ExplainDataFrameAnalyticsResponse response = client.machineLearning().explainDataFrameAnalytics(request,
RequestOptions.DEFAULT);
// end::explain-data-frame-analytics-execute
// tag::explain-data-frame-analytics-response
List<FieldSelection> fieldSelection = response.getFieldSelection(); // <1>
MemoryEstimation memoryEstimation = response.getMemoryEstimation(); // <2>
// end::explain-data-frame-analytics-response
assertThat(fieldSelection.size(), equalTo(2));
assertThat(fieldSelection.stream().map(FieldSelection::getName).collect(Collectors.toList()), contains("timestamp", "total"));
ByteSizeValue expectedMemoryWithoutDisk = memoryEstimation.getExpectedMemoryWithoutDisk(); // <1>
ByteSizeValue expectedMemoryWithDisk = memoryEstimation.getExpectedMemoryWithDisk(); // <2>
// We are pretty liberal here as this test does not aim at verifying concrete numbers but rather end-to-end user workflow.
ByteSizeValue lowerBound = new ByteSizeValue(1, ByteSizeUnit.KB);
ByteSizeValue upperBound = new ByteSizeValue(1, ByteSizeUnit.GB);
assertThat(expectedMemoryWithoutDisk, allOf(greaterThan(lowerBound), lessThan(upperBound)));
assertThat(expectedMemoryWithDisk, allOf(greaterThan(lowerBound), lessThan(upperBound)));
}
{
DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder()
.setSource(DataFrameAnalyticsSource.builder().setIndex("explain-df-test-source-index").build())
.setAnalysis(OutlierDetection.createDefault())
.build();
ExplainDataFrameAnalyticsRequest request = new ExplainDataFrameAnalyticsRequest(config);
// tag::explain-data-frame-analytics-execute-listener
ActionListener<ExplainDataFrameAnalyticsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(ExplainDataFrameAnalyticsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::explain-data-frame-analytics-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::explain-data-frame-analytics-execute-async
client.machineLearning().explainDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::explain-data-frame-analytics-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetTrainedModels() throws Exception {
putTrainedModel("my-trained-model");
RestHighLevelClient client = highLevelClient();
{
// tag::get-trained-models-request
GetTrainedModelsRequest request = new GetTrainedModelsRequest("my-trained-model") // <1>
.setPageParams(new PageParams(0, 1)) // <2>
.setIncludeDefinition(false) // <3>
.setDecompressDefinition(false) // <4>
.setAllowNoMatch(true) // <5>
.setTags("regression") // <6>
.setForExport(false); // <7>
// end::get-trained-models-request
request.setTags((List<String>)null);
// tag::get-trained-models-execute
GetTrainedModelsResponse response = client.machineLearning().getTrainedModels(request, RequestOptions.DEFAULT);
// end::get-trained-models-execute
// tag::get-trained-models-response
List<TrainedModelConfig> models = response.getTrainedModels();
// end::get-trained-models-response
assertThat(models, hasSize(1));
}
{
GetTrainedModelsRequest request = new GetTrainedModelsRequest("my-trained-model");
// tag::get-trained-models-execute-listener
ActionListener<GetTrainedModelsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(GetTrainedModelsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-trained-models-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-trained-models-execute-async
client.machineLearning().getTrainedModelsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-trained-models-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutTrainedModel() throws Exception {
TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build();
// tag::put-trained-model-config
TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder()
.setDefinition(definition) // <1>
.setCompressedDefinition(InferenceToXContentCompressor.deflate(definition)) // <2>
.setModelId("my-new-trained-model") // <3>
.setInput(new TrainedModelInput("col1", "col2", "col3", "col4")) // <4>
.setDescription("test model") // <5>
.setMetadata(new HashMap<>()) // <6>
.setTags("my_regression_models") // <7>
.setInferenceConfig(new RegressionConfig("value", 0)) // <8>
.build();
// end::put-trained-model-config
trainedModelConfig = TrainedModelConfig.builder()
.setDefinition(definition)
.setInferenceConfig(new RegressionConfig(null, null))
.setModelId("my-new-trained-model")
.setInput(new TrainedModelInput("col1", "col2", "col3", "col4"))
.setDescription("test model")
.setMetadata(new HashMap<>())
.setTags("my_regression_models")
.build();
RestHighLevelClient client = highLevelClient();
{
// tag::put-trained-model-request
PutTrainedModelRequest request = new PutTrainedModelRequest(trainedModelConfig); // <1>
// end::put-trained-model-request
// tag::put-trained-model-execute
PutTrainedModelResponse response = client.machineLearning().putTrainedModel(request, RequestOptions.DEFAULT);
// end::put-trained-model-execute
// tag::put-trained-model-response
TrainedModelConfig model = response.getResponse();
// end::put-trained-model-response
assertThat(model.getModelId(), equalTo(trainedModelConfig.getModelId()));
highLevelClient().machineLearning()
.deleteTrainedModel(new DeleteTrainedModelRequest("my-new-trained-model"), RequestOptions.DEFAULT);
}
{
PutTrainedModelRequest request = new PutTrainedModelRequest(trainedModelConfig);
// tag::put-trained-model-execute-listener
ActionListener<PutTrainedModelResponse> listener = new ActionListener<>() {
@Override
public void onResponse(PutTrainedModelResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-trained-model-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-trained-model-execute-async
client.machineLearning().putTrainedModelAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-trained-model-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
highLevelClient().machineLearning()
.deleteTrainedModel(new DeleteTrainedModelRequest("my-new-trained-model"), RequestOptions.DEFAULT);
}
}
public void testGetTrainedModelsStats() throws Exception {
putTrainedModel("my-trained-model");
RestHighLevelClient client = highLevelClient();
{
// tag::get-trained-models-stats-request
GetTrainedModelsStatsRequest request =
new GetTrainedModelsStatsRequest("my-trained-model") // <1>
.setPageParams(new PageParams(0, 1)) // <2>
.setAllowNoMatch(true); // <3>
// end::get-trained-models-stats-request
// tag::get-trained-models-stats-execute
GetTrainedModelsStatsResponse response =
client.machineLearning().getTrainedModelsStats(request, RequestOptions.DEFAULT);
// end::get-trained-models-stats-execute
// tag::get-trained-models-stats-response
List<TrainedModelStats> models = response.getTrainedModelStats();
// end::get-trained-models-stats-response
assertThat(models, hasSize(1));
}
{
GetTrainedModelsStatsRequest request = new GetTrainedModelsStatsRequest("my-trained-model");
// tag::get-trained-models-stats-execute-listener
ActionListener<GetTrainedModelsStatsResponse> listener = new ActionListener<>() {
@Override
public void onResponse(GetTrainedModelsStatsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-trained-models-stats-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-trained-models-stats-execute-async
client.machineLearning()
.getTrainedModelsStatsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-trained-models-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteTrainedModel() throws Exception {
RestHighLevelClient client = highLevelClient();
{
putTrainedModel("my-trained-model");
// tag::delete-trained-model-request
DeleteTrainedModelRequest request = new DeleteTrainedModelRequest("my-trained-model"); // <1>
// end::delete-trained-model-request
// tag::delete-trained-model-execute
AcknowledgedResponse response = client.machineLearning().deleteTrainedModel(request, RequestOptions.DEFAULT);
// end::delete-trained-model-execute
// tag::delete-trained-model-response
boolean deleted = response.isAcknowledged();
// end::delete-trained-model-response
assertThat(deleted, is(true));
}
{
putTrainedModel("my-trained-model");
DeleteTrainedModelRequest request = new DeleteTrainedModelRequest("my-trained-model");
// tag::delete-trained-model-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-trained-model-execute-listener
// Replace the empty listener by a blocking listener in test
CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-trained-model-execute-async
client.machineLearning().deleteTrainedModelAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-trained-model-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testCreateFilter() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::put-filter-config
MlFilter.Builder filterBuilder = MlFilter.builder("my_safe_domains") // <1>
.setDescription("A list of safe domains") // <2>
.setItems("*.google.com", "wikipedia.org"); // <3>
// end::put-filter-config
// tag::put-filter-request
PutFilterRequest request = new PutFilterRequest(filterBuilder.build()); // <1>
// end::put-filter-request
// tag::put-filter-execute
PutFilterResponse response = client.machineLearning().putFilter(request, RequestOptions.DEFAULT);
// end::put-filter-execute
// tag::put-filter-response
MlFilter createdFilter = response.getResponse(); // <1>
// end::put-filter-response
assertThat(createdFilter.getId(), equalTo("my_safe_domains"));
}
{
MlFilter.Builder filterBuilder = MlFilter.builder("safe_domains_async")
.setDescription("A list of safe domains")
.setItems("*.google.com", "wikipedia.org");
PutFilterRequest request = new PutFilterRequest(filterBuilder.build());
// tag::put-filter-execute-listener
ActionListener<PutFilterResponse> listener = new ActionListener<PutFilterResponse>() {
@Override
public void onResponse(PutFilterResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-filter-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-filter-execute-async
client.machineLearning().putFilterAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-filter-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetFilters() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String filterId = "get-filter-doc-test";
MlFilter.Builder filterBuilder = MlFilter.builder(filterId).setDescription("test").setItems("*.google.com", "wikipedia.org");
client.machineLearning().putFilter(new PutFilterRequest(filterBuilder.build()), RequestOptions.DEFAULT);
{
// tag::get-filters-request
GetFiltersRequest request = new GetFiltersRequest(); // <1>
// end::get-filters-request
// tag::get-filters-filter-id
request.setFilterId("get-filter-doc-test"); // <1>
// end::get-filters-filter-id
// tag::get-filters-page-params
request.setFrom(100); // <1>
request.setSize(200); // <2>
// end::get-filters-page-params
request.setFrom(null);
request.setSize(null);
// tag::get-filters-execute
GetFiltersResponse response = client.machineLearning().getFilter(request, RequestOptions.DEFAULT);
// end::get-filters-execute
// tag::get-filters-response
long count = response.count(); // <1>
List<MlFilter> filters = response.filters(); // <2>
// end::get-filters-response
assertEquals(1, filters.size());
}
{
GetFiltersRequest request = new GetFiltersRequest();
request.setFilterId(filterId);
// tag::get-filters-execute-listener
ActionListener<GetFiltersResponse> listener = new ActionListener<GetFiltersResponse>() {
@Override
public void onResponse(GetFiltersResponse getfiltersResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-filters-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-filters-execute-async
client.machineLearning().getFilterAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-filters-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testUpdateFilter() throws IOException, InterruptedException {
RestHighLevelClient client = highLevelClient();
String filterId = "update-filter-doc-test";
MlFilter.Builder filterBuilder = MlFilter.builder(filterId).setDescription("test").setItems("*.google.com", "wikipedia.org");
client.machineLearning().putFilter(new PutFilterRequest(filterBuilder.build()), RequestOptions.DEFAULT);
{
// tag::update-filter-request
UpdateFilterRequest request = new UpdateFilterRequest(filterId); // <1>
// end::update-filter-request
// tag::update-filter-description
request.setDescription("my new description"); // <1>
// end::update-filter-description
// tag::update-filter-add-items
request.setAddItems(Arrays.asList("*.bing.com", "*.elastic.co")); // <1>
// end::update-filter-add-items
// tag::update-filter-remove-items
request.setRemoveItems(Arrays.asList("*.google.com")); // <1>
// end::update-filter-remove-items
// tag::update-filter-execute
PutFilterResponse response = client.machineLearning().updateFilter(request, RequestOptions.DEFAULT);
// end::update-filter-execute
// tag::update-filter-response
MlFilter updatedFilter = response.getResponse(); // <1>
// end::update-filter-response
assertEquals(request.getDescription(), updatedFilter.getDescription());
}
{
UpdateFilterRequest request = new UpdateFilterRequest(filterId);
// tag::update-filter-execute-listener
ActionListener<PutFilterResponse> listener = new ActionListener<PutFilterResponse>() {
@Override
public void onResponse(PutFilterResponse putFilterResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::update-filter-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::update-filter-execute-async
client.machineLearning().updateFilterAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::update-filter-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteFilter() throws Exception {
RestHighLevelClient client = highLevelClient();
String filterId = createFilter(client);
{
// tag::delete-filter-request
DeleteFilterRequest request = new DeleteFilterRequest(filterId); // <1>
// end::delete-filter-request
// tag::delete-filter-execute
AcknowledgedResponse response = client.machineLearning().deleteFilter(request, RequestOptions.DEFAULT);
// end::delete-filter-execute
// tag::delete-filter-response
boolean isAcknowledged = response.isAcknowledged(); // <1>
// end::delete-filter-response
assertTrue(isAcknowledged);
}
filterId = createFilter(client);
{
DeleteFilterRequest request = new DeleteFilterRequest(filterId);
// tag::delete-filter-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-filter-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-filter-execute-async
client.machineLearning().deleteFilterAsync(request, RequestOptions.DEFAULT, listener); //<1>
// end::delete-filter-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetMlInfo() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::get-ml-info-request
MlInfoRequest request = new MlInfoRequest(); // <1>
// end::get-ml-info-request
// tag::get-ml-info-execute
MlInfoResponse response = client.machineLearning()
.getMlInfo(request, RequestOptions.DEFAULT);
// end::get-ml-info-execute
// tag::get-ml-info-response
final Map<String, Object> info = response.getInfo();// <1>
// end::get-ml-info-response
assertTrue(info.containsKey("defaults"));
assertTrue(info.containsKey("limits"));
}
{
MlInfoRequest request = new MlInfoRequest();
// tag::get-ml-info-execute-listener
ActionListener<MlInfoResponse> listener = new ActionListener<MlInfoResponse>() {
@Override
public void onResponse(MlInfoResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-ml-info-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-ml-info-execute-async
client.machineLearning()
.getMlInfoAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-ml-info-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testSetUpgradeMode() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::set-upgrade-mode-request
SetUpgradeModeRequest request = new SetUpgradeModeRequest(true); // <1>
request.setTimeout(TimeValue.timeValueMinutes(10)); // <2>
// end::set-upgrade-mode-request
// Set to false so that the cluster setting does not have to be unset at the end of the test.
request.setEnabled(false);
// tag::set-upgrade-mode-execute
AcknowledgedResponse acknowledgedResponse = client.machineLearning().setUpgradeMode(request, RequestOptions.DEFAULT);
// end::set-upgrade-mode-execute
// tag::set-upgrade-mode-response
boolean acknowledged = acknowledgedResponse.isAcknowledged(); // <1>
// end::set-upgrade-mode-response
assertThat(acknowledged, is(true));
}
{
SetUpgradeModeRequest request = new SetUpgradeModeRequest(false);
// tag::set-upgrade-mode-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::set-upgrade-mode-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::set-upgrade-mode-execute-async
client.machineLearning()
.setUpgradeModeAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::set-upgrade-mode-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testEstimateModelMemory() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::estimate-model-memory-request
Detector.Builder detectorBuilder = new Detector.Builder()
.setFunction("count")
.setPartitionFieldName("status");
AnalysisConfig.Builder analysisConfigBuilder =
new AnalysisConfig.Builder(Collections.singletonList(detectorBuilder.build()))
.setBucketSpan(TimeValue.timeValueMinutes(10))
.setInfluencers(Collections.singletonList("src_ip"));
EstimateModelMemoryRequest request = new EstimateModelMemoryRequest(analysisConfigBuilder.build()); // <1>
request.setOverallCardinality(Collections.singletonMap("status", 50L)); // <2>
request.setMaxBucketCardinality(Collections.singletonMap("src_ip", 30L)); // <3>
// end::estimate-model-memory-request
// tag::estimate-model-memory-execute
EstimateModelMemoryResponse estimateModelMemoryResponse =
client.machineLearning().estimateModelMemory(request, RequestOptions.DEFAULT);
// end::estimate-model-memory-execute
// tag::estimate-model-memory-response
ByteSizeValue modelMemoryEstimate = estimateModelMemoryResponse.getModelMemoryEstimate(); // <1>
long estimateInBytes = modelMemoryEstimate.getBytes();
// end::estimate-model-memory-response
assertThat(estimateInBytes, greaterThan(10000000L));
}
{
AnalysisConfig analysisConfig =
AnalysisConfig.builder(Collections.singletonList(Detector.builder().setFunction("count").build())).build();
EstimateModelMemoryRequest request = new EstimateModelMemoryRequest(analysisConfig);
// tag::estimate-model-memory-execute-listener
ActionListener<EstimateModelMemoryResponse> listener = new ActionListener<EstimateModelMemoryResponse>() {
@Override
public void onResponse(EstimateModelMemoryResponse estimateModelMemoryResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::estimate-model-memory-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::estimate-model-memory-execute-async
client.machineLearning()
.estimateModelMemoryAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::estimate-model-memory-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
private String createFilter(RestHighLevelClient client) throws IOException {
MlFilter.Builder filterBuilder = MlFilter.builder("my_safe_domains")
.setDescription("A list of safe domains")
.setItems("*.google.com", "wikipedia.org");
PutFilterRequest putFilterRequest = new PutFilterRequest(filterBuilder.build());
PutFilterResponse putFilterResponse = client.machineLearning().putFilter(putFilterRequest, RequestOptions.DEFAULT);
MlFilter createdFilter = putFilterResponse.getResponse();
assertThat(createdFilter.getId(), equalTo("my_safe_domains"));
return createdFilter.getId();
}
private void createIndex(String indexName) throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.mapping(XContentFactory.jsonBuilder().startObject()
.startObject("properties")
.startObject("timestamp")
.field("type", "date")
.endObject()
.startObject("total")
.field("type", "long")
.endObject()
.endObject()
.endObject());
highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
}
private DataFrameAnalyticsState getAnalyticsState(String configId) throws IOException {
GetDataFrameAnalyticsStatsResponse statsResponse =
highLevelClient().machineLearning().getDataFrameAnalyticsStats(
new GetDataFrameAnalyticsStatsRequest(configId), RequestOptions.DEFAULT);
assertThat(statsResponse.getAnalyticsStats(), hasSize(1));
DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0);
return stats.getState();
}
private void putTrainedModel(String modelId) throws IOException {
TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build();
TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder()
.setDefinition(definition)
.setModelId(modelId)
.setInferenceConfig(new RegressionConfig("value", 0))
.setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4")))
.setDescription("test model")
.build();
highLevelClient().machineLearning().putTrainedModel(new PutTrainedModelRequest(trainedModelConfig), RequestOptions.DEFAULT);
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return new NamedXContentRegistry(new MlInferenceNamedXContentProvider().getNamedXContentParsers());
}
private static final DataFrameAnalyticsConfig DF_ANALYTICS_CONFIG =
DataFrameAnalyticsConfig.builder()
.setId("my-analytics-config")
.setSource(DataFrameAnalyticsSource.builder()
.setIndex("put-test-source-index")
.build())
.setDest(DataFrameAnalyticsDest.builder()
.setIndex("put-test-dest-index")
.build())
.setAnalysis(OutlierDetection.createDefault())
.build();
}
| uschindler/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/MlClientDocumentationIT.java | Java | apache-2.0 | 199,205 |
package org.tmarciniak.mtp.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* @author tomasz.marciniak
*
* Immutable class representing trade message
*/
@Entity
@Table
public final class TradeMessage implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trade_message_id_seq")
@SequenceGenerator(name = "trade_message_id_seq", sequenceName = "trade_message_id_seq", allocationSize = 1)
private long id;
private String userId;
private String currencyFrom;
private String currencyTo;
private BigDecimal amountBuy;
private BigDecimal amountSell;
private BigDecimal rate;
private Date timePlaced;
private String originatingCountry;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCurrencyFrom() {
return currencyFrom;
}
public void setCurrencyFrom(String currencyFrom) {
this.currencyFrom = currencyFrom;
}
public String getCurrencyTo() {
return currencyTo;
}
public void setCurrencyTo(String currencyTo) {
this.currencyTo = currencyTo;
}
public BigDecimal getAmountBuy() {
return amountBuy;
}
public void setAmountBuy(BigDecimal amountBuy) {
this.amountBuy = amountBuy;
}
public BigDecimal getAmountSell() {
return amountSell;
}
public void setAmountSell(BigDecimal amountSell) {
this.amountSell = amountSell;
}
public BigDecimal getRate() {
return rate;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((amountBuy == null) ? 0 : amountBuy.hashCode());
result = prime * result
+ ((amountSell == null) ? 0 : amountSell.hashCode());
result = prime * result
+ ((currencyFrom == null) ? 0 : currencyFrom.hashCode());
result = prime * result
+ ((currencyTo == null) ? 0 : currencyTo.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime
* result
+ ((originatingCountry == null) ? 0 : originatingCountry
.hashCode());
result = prime * result + ((rate == null) ? 0 : rate.hashCode());
result = prime * result
+ ((timePlaced == null) ? 0 : timePlaced.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TradeMessage other = (TradeMessage) obj;
if (amountBuy == null) {
if (other.amountBuy != null)
return false;
} else if (!amountBuy.equals(other.amountBuy))
return false;
if (amountSell == null) {
if (other.amountSell != null)
return false;
} else if (!amountSell.equals(other.amountSell))
return false;
if (currencyFrom == null) {
if (other.currencyFrom != null)
return false;
} else if (!currencyFrom.equals(other.currencyFrom))
return false;
if (currencyTo == null) {
if (other.currencyTo != null)
return false;
} else if (!currencyTo.equals(other.currencyTo))
return false;
if (id != other.id)
return false;
if (originatingCountry == null) {
if (other.originatingCountry != null)
return false;
} else if (!originatingCountry.equals(other.originatingCountry))
return false;
if (rate == null) {
if (other.rate != null)
return false;
} else if (!rate.equals(other.rate))
return false;
if (timePlaced == null) {
if (other.timePlaced != null)
return false;
} else if (!timePlaced.equals(other.timePlaced))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public Date getTimePlaced() {
return new Date(timePlaced.getTime());
}
public void setTimePlaced(Date timePlaced) {
this.timePlaced = timePlaced;
}
public String getOriginatingCountry() {
return originatingCountry;
}
public void setOriginatingCountry(String originatingCountry) {
this.originatingCountry = originatingCountry;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
| tmarciniak/cfmtp | mtp-core/src/main/java/org/tmarciniak/mtp/model/TradeMessage.java | Java | apache-2.0 | 4,895 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.polly;
import javax.annotation.Generated;
import com.amazonaws.services.polly.model.*;
/**
* Abstract implementation of {@code AmazonPollyAsync}. Convenient method forms pass through to the corresponding
* overload that takes a request object and an {@code AsyncHandler}, which throws an
* {@code UnsupportedOperationException}.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAmazonPollyAsync extends AbstractAmazonPolly implements AmazonPollyAsync {
protected AbstractAmazonPollyAsync() {
}
@Override
public java.util.concurrent.Future<DeleteLexiconResult> deleteLexiconAsync(DeleteLexiconRequest request) {
return deleteLexiconAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteLexiconResult> deleteLexiconAsync(DeleteLexiconRequest request,
com.amazonaws.handlers.AsyncHandler<DeleteLexiconRequest, DeleteLexiconResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<DescribeVoicesResult> describeVoicesAsync(DescribeVoicesRequest request) {
return describeVoicesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeVoicesResult> describeVoicesAsync(DescribeVoicesRequest request,
com.amazonaws.handlers.AsyncHandler<DescribeVoicesRequest, DescribeVoicesResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<GetLexiconResult> getLexiconAsync(GetLexiconRequest request) {
return getLexiconAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetLexiconResult> getLexiconAsync(GetLexiconRequest request,
com.amazonaws.handlers.AsyncHandler<GetLexiconRequest, GetLexiconResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<ListLexiconsResult> listLexiconsAsync(ListLexiconsRequest request) {
return listLexiconsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListLexiconsResult> listLexiconsAsync(ListLexiconsRequest request,
com.amazonaws.handlers.AsyncHandler<ListLexiconsRequest, ListLexiconsResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<PutLexiconResult> putLexiconAsync(PutLexiconRequest request) {
return putLexiconAsync(request, null);
}
@Override
public java.util.concurrent.Future<PutLexiconResult> putLexiconAsync(PutLexiconRequest request,
com.amazonaws.handlers.AsyncHandler<PutLexiconRequest, PutLexiconResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
@Override
public java.util.concurrent.Future<SynthesizeSpeechResult> synthesizeSpeechAsync(SynthesizeSpeechRequest request) {
return synthesizeSpeechAsync(request, null);
}
@Override
public java.util.concurrent.Future<SynthesizeSpeechResult> synthesizeSpeechAsync(SynthesizeSpeechRequest request,
com.amazonaws.handlers.AsyncHandler<SynthesizeSpeechRequest, SynthesizeSpeechResult> asyncHandler) {
throw new java.lang.UnsupportedOperationException();
}
}
| dagnir/aws-sdk-java | aws-java-sdk-polly/src/main/java/com/amazonaws/services/polly/AbstractAmazonPollyAsync.java | Java | apache-2.0 | 4,021 |
<!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 (version 1.7.0_21) on Sat May 11 22:08:47 BST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError (Apache Jena ARQ)</title>
<meta name="date" content="2013-05-11">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError (Apache Jena ARQ)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../../../../com/hp/hpl/jena/sparql/lang/sparql_10/TokenMgrError.html" title="class in com.hp.hpl.jena.sparql.lang.sparql_10">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/lang/sparql_10/class-use/TokenMgrError.html" target="_top">Frames</a></li>
<li><a href="TokenMgrError.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">
<h2 title="Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError" class="title">Uses of Class<br>com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError</h2>
</div>
<div class="classUseContainer">No usage of com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../../../../com/hp/hpl/jena/sparql/lang/sparql_10/TokenMgrError.html" title="class in com.hp.hpl.jena.sparql.lang.sparql_10">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/lang/sparql_10/class-use/TokenMgrError.html" target="_top">Frames</a></li>
<li><a href="TokenMgrError.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>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
| chinhnc/floodlight | lib/apache-jena-2.10.1/javadoc-arq/com/hp/hpl/jena/sparql/lang/sparql_10/class-use/TokenMgrError.html | HTML | apache-2.0 | 4,613 |
package dk.itu.pervasive.mobile.data;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import dk.itu.pervasive.mobile.R;
import java.io.FileOutputStream;
/**
* @author Tony Beltramelli www.tonybeltramelli.com
*/
public class DataManager
{
public static final String PREF_KEY_SAVE = "save";
public static final String PREF_KEY_USERNAME = "username";
public static final String PREF_KEY_SURFACE_ADDRESS = "surfaceAddress";
public static final String PREF_KEY_STICKER_ID = "stickerID";
private static DataManager _instance = null;
private Activity _context;
private String _username = "";
private String _surfaceAddress = "";
private String _stickerID = "";
private DataManager()
{
}
public static DataManager getInstance()
{
if (_instance == null)
{
_instance = new DataManager();
}
return _instance;
}
public void saveData()
{
_username = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_USERNAME, _context.getResources().getString(R.string.preference_user_name_default));
_surfaceAddress = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_SURFACE_ADDRESS, _context.getResources().getString(R.string.preference_surface_address_default));
_stickerID = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_STICKER_ID, _context.getResources().getString(R.string.preference_sticker_id_default));
Log.wtf("save data", _username + ", " + _surfaceAddress + ", " + _stickerID);
}
public String getPathFromUri(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = _context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void saveImage(String imageName, byte[] bytes)
{
FileOutputStream fos;
try
{
fos = _context.openFileOutput(imageName, Context.MODE_PRIVATE);
fos.write(bytes);
fos.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void displayMessage(final String message)
{
_context.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(_context, message, Toast.LENGTH_SHORT).show();
}
});
}
public String getUsername()
{
return _username;
}
public String getSurfaceAddress()
{
return _surfaceAddress;
}
public String getStickerID()
{
return _stickerID;
}
public void setContext(Activity context)
{
_context = context;
saveData();
}
public Context getContext(){
return _context;
}
}
| tonybeltramelli/Ubiquitous-Media-Sharing-Surface | dk.itu.pervasive.mobile.android/src/dk/itu/pervasive/mobile/data/DataManager.java | Java | apache-2.0 | 2,863 |
/*
* Copyright (c) 2005-2011 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.accounts.struts.actionforms;
import static org.mifos.framework.util.helpers.DateUtils.dateFallsBeforeDate;
import static org.mifos.framework.util.helpers.DateUtils.getDateAsSentFromBrowser;
import java.sql.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.joda.time.LocalDate;
import org.mifos.accounts.servicefacade.AccountTypeDto;
import org.mifos.accounts.util.helpers.AccountConstants;
import org.mifos.application.admin.servicefacade.InvalidDateException;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.config.AccountingRules;
import org.mifos.framework.business.util.helpers.MethodNameConstants;
import org.mifos.framework.struts.actionforms.BaseActionForm;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.DoubleConversionResult;
import org.mifos.framework.util.helpers.SessionUtils;
import org.mifos.security.login.util.helpers.LoginConstants;
import org.mifos.security.util.ActivityMapper;
import org.mifos.security.util.UserContext;
public class AccountApplyPaymentActionForm extends BaseActionForm {
private String input;
private String transactionDateDD;
private String transactionDateMM;
private String transactionDateYY;
private String amount;
private Short currencyId;
private String receiptId;
private String receiptDateDD;
private String receiptDateMM;
private String receiptDateYY;
/*
* Among other things, this field holds the PaymentTypes value for disbursements.
*/
private String paymentTypeId;
private String waiverInterest;
private String globalAccountNum;
private String accountId;
private String prdOfferingName;
private boolean amountCannotBeZero = true;
private java.util.Date lastPaymentDate;
private String accountForTransfer;
private Short transferPaymentTypeId;
public boolean amountCannotBeZero() {
return this.amountCannotBeZero;
}
public void setAmountCannotBeZero(boolean amountCannotBeZero) {
this.amountCannotBeZero = amountCannotBeZero;
}
public String getPrdOfferingName() {
return prdOfferingName;
}
public void setPrdOfferingName(String prdOfferingName) {
this.prdOfferingName = prdOfferingName;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getInput() {
return input;
}
@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
String methodCalled = request.getParameter(MethodNameConstants.METHOD);
ActionErrors errors = new ActionErrors();
if (methodCalled != null && methodCalled.equals("preview")) {
validateTransfer(errors);
validateTransactionDate(errors);
validatePaymentType(errors);
validateReceiptDate(errors);
String accountType = (String) request.getSession().getAttribute(Constants.ACCOUNT_TYPE);
validateAccountType(errors, accountType);
validateAmount(errors);
validateModeOfPaymentSecurity(request, errors);
}
if (!errors.isEmpty()) {
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute("methodCalled", methodCalled);
}
return errors;
}
private void validateModeOfPaymentSecurity(HttpServletRequest request, ActionErrors errors){
UserContext userContext = (UserContext) SessionUtils.getAttribute(Constants.USER_CONTEXT_KEY, request.getSession());
if(getPaymentTypeId().equals("4") && !ActivityMapper.getInstance().isModeOfPaymentSecurity(userContext)){
errors.add(AccountConstants.LOAN_TRANSFER_PERMISSION, new ActionMessage(AccountConstants.LOAN_TRANSFER_PERMISSION,
getLocalizedMessage("accounts.mode_of_payment_permission")));
}
}
private void validateTransfer(ActionErrors errors) {
if (paymentTypeId.equals(String.valueOf(transferPaymentTypeId))
&& StringUtils.isBlank(accountForTransfer)) {
errors.add(AccountConstants.NO_ACCOUNT_FOR_TRANSFER, new ActionMessage(AccountConstants.NO_ACCOUNT_FOR_TRANSFER));
}
}
private void validateAccountType(ActionErrors errors, String accountType) {
if (accountType != null && accountType.equals(AccountTypeDto.LOAN_ACCOUNT.name())) {
if (getAmount() == null || getAmount().equals("")) {
errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY,
getLocalizedMessage("accounts.amt")));
}
}
}
private void validatePaymentType(ActionErrors errors) {
if (StringUtils.isEmpty(getPaymentTypeId())) {
errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY,
getLocalizedMessage("accounts.mode_of_payment")));
}
}
private void validateReceiptDate(ActionErrors errors) {
if (getReceiptDate() != null && !getReceiptDate().equals("")) {
ActionErrors validationErrors = validateDate(getReceiptDate(), getLocalizedMessage("accounts.receiptdate"));
if (null != validationErrors && !validationErrors.isEmpty()) {
errors.add(validationErrors);
}
}
}
private void validateTransactionDate(ActionErrors errors) {
String fieldName = "accounts.date_of_trxn";
ActionErrors validationErrors = validateDate(getTransactionDate(), getLocalizedMessage(fieldName));
if (null != validationErrors && !validationErrors.isEmpty()) {
errors.add(validationErrors);
}
if (null != getTransactionDate()){
validationErrors = validatePaymentDate(getTransactionDate(), getLocalizedMessage(fieldName));
if (validationErrors != null && !validationErrors.isEmpty()) {
errors.add(validationErrors);
}
}
}
//exposed for testing
public ActionErrors validatePaymentDate(String transactionDate, String fieldName) {
ActionErrors errors = null;
try {
if (lastPaymentDate != null && dateFallsBeforeDate(getDateAsSentFromBrowser(transactionDate), lastPaymentDate)) {
errors = new ActionErrors();
errors.add(AccountConstants.ERROR_PAYMENT_DATE_BEFORE_LAST_PAYMENT,
new ActionMessage(AccountConstants.ERROR_PAYMENT_DATE_BEFORE_LAST_PAYMENT,
fieldName));
}
} catch (InvalidDateException ide) {
errors = new ActionErrors(); //dont add a message, since it was already added in validateDate()
}
return errors;
}
protected ActionErrors validateDate(String date, String fieldName) {
ActionErrors errors = null;
java.sql.Date sqlDate = null;
if (date != null && !date.equals("")) {
try {
sqlDate = getDateAsSentFromBrowser(date);
if (DateUtils.whichDirection(sqlDate) > 0) {
errors = new ActionErrors();
errors.add(AccountConstants.ERROR_FUTUREDATE, new ActionMessage(AccountConstants.ERROR_FUTUREDATE,
fieldName));
}
} catch (InvalidDateException ide) {
errors = new ActionErrors();
errors.add(AccountConstants.ERROR_INVALIDDATE, new ActionMessage(AccountConstants.ERROR_INVALIDDATE,
fieldName));
}
} else {
errors = new ActionErrors();
errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY,
fieldName));
}
return errors;
}
protected Locale getUserLocale(HttpServletRequest request) {
Locale locale = null;
HttpSession session = request.getSession();
if (session != null) {
UserContext userContext = (UserContext) session.getAttribute(LoginConstants.USERCONTEXT);
if (null != userContext) {
locale = userContext.getCurrentLocale();
}
}
return locale;
}
protected void validateAmount(ActionErrors errors) {
MifosCurrency currency = null;
if (getCurrencyId() != null && AccountingRules.isMultiCurrencyEnabled()) {
currency = AccountingRules.getCurrencyByCurrencyId(getCurrencyId());
}
DoubleConversionResult conversionResult = validateAmount(getAmount(), currency , AccountConstants.ACCOUNT_AMOUNT, errors, "");
if (amountCannotBeZero() && conversionResult.getErrors().size() == 0 && !(conversionResult.getDoubleValue() > 0.0)) {
addError(errors, AccountConstants.ACCOUNT_AMOUNT, AccountConstants.ERRORS_MUST_BE_GREATER_THAN_ZERO,
getLocalizedMessage(AccountConstants.ACCOUNT_AMOUNT));
}
}
public void setInput(String input) {
this.input = input;
}
public String getPaymentTypeId() {
return paymentTypeId;
}
public void setPaymentTypeId(String paymentTypeId) {
this.paymentTypeId = paymentTypeId;
}
public String getReceiptDate() {
return compileDateString(receiptDateDD, receiptDateMM, receiptDateYY);
}
public void setReceiptDate(String receiptDate) throws InvalidDateException {
if (StringUtils.isBlank(receiptDate)) {
receiptDateDD = null;
receiptDateMM = null;
receiptDateYY = null;
} else {
Calendar cal = new GregorianCalendar();
java.sql.Date date = getDateAsSentFromBrowser(receiptDate);
cal.setTime(date);
receiptDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
receiptDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1);
receiptDateYY = Integer.toString(cal.get(Calendar.YEAR));
}
}
public String getReceiptId() {
return receiptId;
}
public void setReceiptId(String receiptId) {
this.receiptId = receiptId;
}
public String getTransactionDate() {
return compileDateString(transactionDateDD, transactionDateMM, transactionDateYY);
}
public void setTransactionDate(String receiptDate) throws InvalidDateException {
if (StringUtils.isBlank(receiptDate)) {
transactionDateDD = null;
transactionDateMM = null;
transactionDateYY = null;
} else {
Calendar cal = new GregorianCalendar();
java.sql.Date date = getDateAsSentFromBrowser(receiptDate);
cal.setTime(date);
transactionDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
transactionDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1);
transactionDateYY = Integer.toString(cal.get(Calendar.YEAR));
}
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getGlobalAccountNum() {
return globalAccountNum;
}
public void setGlobalAccountNum(String globalAccountNum) {
this.globalAccountNum = globalAccountNum;
}
protected void clear() throws InvalidDateException {
this.amount = null;
this.paymentTypeId = null;
setReceiptDate(null);
this.receiptId = null;
}
public String getReceiptDateDD() {
return receiptDateDD;
}
public void setReceiptDateDD(String receiptDateDD) {
this.receiptDateDD = receiptDateDD;
}
public String getReceiptDateMM() {
return receiptDateMM;
}
public void setReceiptDateMM(String receiptDateMM) {
this.receiptDateMM = receiptDateMM;
}
public String getReceiptDateYY() {
return receiptDateYY;
}
public void setReceiptDateYY(String receiptDateYY) {
this.receiptDateYY = receiptDateYY;
}
public String getTransactionDateDD() {
return transactionDateDD;
}
public void setTransactionDateDD(String transactionDateDD) {
this.transactionDateDD = transactionDateDD;
}
public String getTransactionDateMM() {
return transactionDateMM;
}
public void setTransactionDateMM(String transactionDateMM) {
this.transactionDateMM = transactionDateMM;
}
public String getTransactionDateYY() {
return transactionDateYY;
}
public void setTransactionDateYY(String transactionDateYY) {
this.transactionDateYY = transactionDateYY;
}
public Short getCurrencyId() {
return this.currencyId;
}
public void setCurrencyId(Short currencyId) {
this.currencyId = currencyId;
}
public String getWaiverInterest() {
return waiverInterest;
}
public void setWaiverInterest(String waiverInterest) {
this.waiverInterest = waiverInterest;
}
public LocalDate getReceiptDateAsLocalDate() throws InvalidDateException {
Date receiptDateStr = getDateAsSentFromBrowser(getReceiptDate());
return (receiptDateStr != null) ? new LocalDate(receiptDateStr.getTime()) : null;
}
public LocalDate getTrxnDateAsLocalDate() throws InvalidDateException {
return new LocalDate(getTrxnDate().getTime());
}
public Date getTrxnDate() throws InvalidDateException {
return getDateAsSentFromBrowser(getTransactionDate());
}
public void setLastPaymentDate(java.util.Date lastPaymentDate) {
this.lastPaymentDate = lastPaymentDate;
}
public String getAccountForTransfer() {
return accountForTransfer;
}
public void setAccountForTransfer(String accountForTransfer) {
this.accountForTransfer = accountForTransfer;
}
public Short getTransferPaymentTypeId() {
return transferPaymentTypeId;
}
public void setTransferPaymentTypeId(Short transferPaymentTypeId) {
this.transferPaymentTypeId = transferPaymentTypeId;
}
}
| jpodeszwik/mifos | application/src/main/java/org/mifos/accounts/struts/actionforms/AccountApplyPaymentActionForm.java | Java | apache-2.0 | 15,538 |
package org.apache.activemq.nob.filestore.uuiddir;
import org.apache.activemq.nob.filestore.BrokerFilenameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.UUID;
/**
* Decoder of filenames in a UUID-based filesystem store of broker configuration files. This store only supports
* broker IDs in the form of UUIDs.
*
* Created by art on 2/19/15.
*/
public class UUIDDirectoryStoreFilenameDecoder implements BrokerFilenameDecoder {
public static final String XBEAN_FILE_PATH_SUFFIX = "-xbean.xml";
private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(UUIDDirectoryStoreFilenameDecoder.class);
private Logger LOG = DEFAULT_LOGGER;
/**
* Decode the pathname as a UUID if it is a regular file (i.e. not a directory) and return the UUID.
*
* @param brokerPath path to the candidate broker.
* @return
*/
@Override
public String extractIdFromFilename(File brokerPath) {
String result = null;
if ( ! brokerPath.isDirectory() ) {
try {
UUID uuid = UUID.fromString(brokerPath.getName());
if (uuid != null) {
result = uuid.toString();
}
} catch ( IllegalArgumentException illegalArgExc ) {
LOG.debug("invalid UUID {}", brokerPath.getName());
}
}
return result;
}
/**
* Locate the path to the xbean configuration file for the broker at the given path. This method validates the
* broker path as it must to determine the broker ID.
*
* @param brokerPath path to the broker.
* @return path to the xbean configuration file, even if it does not exist.
*/
@Override
public File getBrokerXbeanFile(File brokerPath) {
File result = null;
String brokerId = this.extractIdFromFilename(brokerPath);
if ( brokerId != null ) {
result = new File(brokerPath.getPath() + XBEAN_FILE_PATH_SUFFIX);
}
return result;
}
}
| hzbarcea/activemq-nob | activemq-nob-filestore/src/main/java/org/apache/activemq/nob/filestore/uuiddir/UUIDDirectoryStoreFilenameDecoder.java | Java | apache-2.0 | 2,083 |
package antw.logger;
import java.util.Date;
import org.apache.tools.ant.BuildEvent;
import antw.common.util.Constants;
import antw.common.util.StringUtil;
import antw.common.util.TimeUtil;
import antw.logger.model.Project;
import antw.logger.model.Target;
public class TreeLogger extends LoggerAdapter {
protected Project _lastProject = new Project("");
protected int _spaceCount = 2;
protected Date _start;
protected final LoggerContext _context;
private boolean _junitTaskWasRunning;
public TreeLogger(LoggerContext context) {
_context = context;
}
@Override
public void targetStarted(BuildEvent event) {
Target target = _context.getTarget(event);
if (!target.getProject().equals(_lastProject)) {
switchToSubProject(_lastProject, target.getProject());
switchFromSubProject(_lastProject, target.getProject());
printProject(target.getProject());
}
_lastProject = target.getProject();
space(_spaceCount + 2);
out("%-40s %-40s%n",
new Object[] {
"|--- " + target.getName(),
"[" + target.getCounter() + " times; "
+ TimeUtil.formatTimeDuration(System.currentTimeMillis() - _start.getTime()) + "]" });
}
private void printProject(Project project) {
space(_spaceCount + 2);
out("|");
space(_spaceCount + 1);
out(project.getName());
}
private void switchFromSubProject(Project lastProject, Project project) {
if (lastProject.isSubProject()) {
if (!project.isSubProject()) {
space(_spaceCount + 1);
_spaceCount -= 2;
out("/");
}
}
}
private void switchToSubProject(Project lastProject, Project currentProject) {
if (!lastProject.isSubProject()) {
if (currentProject.isSubProject()) {
_spaceCount += 2;
space(_spaceCount + 1);
out("\\");
}
}
}
@Override
public void buildStarted(BuildEvent event) {
newLine();
_start = new Date();
}
@Override
public void buildFinished(BuildEvent event) {
if (event.getException() != null) {
newLine(3);
err(event.getException(), false);
newLine(3);
out("BUILD FAILED :(");
out("Total Time: " + _context.getProjects().getDurationAsString());
} else {
newLine(3);
out("BUILD SUCCESSFUL :)");
out("Total Time: " + _context.getProjects().getDurationAsString());
}
newLine(2);
}
@Override
public void messageLogged(BuildEvent event) {
if (event.getTask() != null) {
if ("junit".equals(event.getTask().getTaskType())) {
if (!_junitTaskWasRunning) {
switchToTestSuite();
}
if (event.getPriority() <= org.apache.tools.ant.Project.MSG_INFO) {
String message = event.getMessage();
if (message.contains(Constants.TEST_SUITE_LABEL)) {
printTestSuite(message);
} else if (message.contains(Constants.TEST_CASE_LABEL)) {
printTestCase(message);
}
}
_junitTaskWasRunning = true;
} else {
if (_junitTaskWasRunning) {
switchFromTestSuite();
}
_junitTaskWasRunning = false;
}
}
}
private void switchFromTestSuite() {
space(_spaceCount + 1);
_spaceCount -= 2;
out("/");
}
private void printTestCase(String message) {
space(_spaceCount + 2);
out("|--- " + StringUtil.remove(Constants.TEST_CASE_LABEL, message));
}
private void switchToTestSuite() {
_spaceCount += 2;
space(_spaceCount + 1);
out("\\");
}
private void printTestSuite(String testStuite) {
space(_spaceCount + 2);
out("|");
space(_spaceCount + 1);
out(StringUtil.remove(Constants.TEST_SUITE_LABEL, testStuite));
}
}
| mbauhardt/antw | modules/logger/src/main/java/antw/logger/TreeLogger.java | Java | apache-2.0 | 4,319 |
<<<<<<< HEAD
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
/**
* ThinkPHP惯例配置文件
* 该文件请不要修改,如果要覆盖惯例配置的值,可在应用配置文件中设定和惯例不符的配置项
* 配置名称大小写任意,系统会统一转换成小写
* 所有配置参数都可以在生效前动态改变
*/
defined('THINK_PATH') or exit();
return array(
/* 应用设定 */
'APP_USE_NAMESPACE' => true, // 应用类库是否使用命名空间
'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名部署
'APP_SUB_DOMAIN_RULES' => array(), // 子域名部署规则
'APP_DOMAIN_SUFFIX' => '', // 域名后缀 如果是com.cn net.cn 之类的后缀必须设置
'ACTION_SUFFIX' => '', // 操作方法后缀
'MULTI_MODULE' => true, // 是否允许多模块 如果为false 则必须设置 DEFAULT_MODULE
'MODULE_DENY_LIST' => array('Common','Runtime'),
'CONTROLLER_LEVEL' => 1,
'APP_AUTOLOAD_LAYER' => 'Controller,Model', // 自动加载的应用类库层 关闭APP_USE_NAMESPACE后有效
'APP_AUTOLOAD_PATH' => '', // 自动加载的路径 关闭APP_USE_NAMESPACE后有效
/* Cookie设置 */
'COOKIE_EXPIRE' => 0, // Cookie有效期
'COOKIE_DOMAIN' => '', // Cookie有效域名
'COOKIE_PATH' => '/', // Cookie路径
'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突
'COOKIE_SECURE' => false, // Cookie安全传输
'COOKIE_HTTPONLY' => '', // Cookie httponly设置
/* 默认设定 */
'DEFAULT_M_LAYER' => 'Model', // 默认的模型层名称
'DEFAULT_C_LAYER' => 'Controller', // 默认的控制器层名称
'DEFAULT_V_LAYER' => 'View', // 默认的视图层名称
'DEFAULT_LANG' => 'zh-cn', // 默认语言
'DEFAULT_THEME' => '', // 默认模板主题名称
'DEFAULT_MODULE' => 'Home', // 默认模块
'DEFAULT_CONTROLLER' => 'Index', // 默认控制器名称
'DEFAULT_ACTION' => 'index', // 默认操作名称
'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码
'DEFAULT_TIMEZONE' => 'PRC', // 默认时区
'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', // 默认JSONP格式返回的处理方法
'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法 用于I函数...
/* 数据库设置 */
'DB_TYPE' => '', // 数据库类型
'DB_HOST' => '', // 服务器地址
'DB_NAME' => '', // 数据库名
'DB_USER' => '', // 用户名
'DB_PWD' => '', // 密码
'DB_PORT' => '', // 端口
'DB_PREFIX' => '', // 数据库表前缀
'DB_PARAMS' => array(), // 数据库连接参数
'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效
'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量
'DB_SLAVE_NO' => '', // 指定从服务器序号
/* 数据缓存设置 */
'DATA_CACHE_TIME' => 0, // 数据缓存有效期 0表示永久缓存
'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存
'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存
'DATA_CACHE_PREFIX' => '', // 缓存前缀
'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator
'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效)
'DATA_CACHE_KEY' => '', // 缓存文件KEY (仅对File方式缓存有效)
'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录)
'DATA_PATH_LEVEL' => 1, // 子目录缓存级别
/* 错误设置 */
'ERROR_MESSAGE' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效
'ERROR_PAGE' => '', // 错误定向页面
'SHOW_ERROR_MSG' => false, // 显示错误信息
'TRACE_MAX_RECORD' => 100, // 每个级别的错误信息 最大记录数
/* 日志设置 */
'LOG_RECORD' => false, // 默认不记录日志
'LOG_TYPE' => 'File', // 日志记录类型 默认为文件方式
'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR',// 允许记录的日志级别
'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制
'LOG_EXCEPTION_RECORD' => false, // 是否记录异常信息日志
/* SESSION设置 */
'SESSION_AUTO_START' => true, // 是否自动开启Session
'SESSION_OPTIONS' => array(), // session 配置数组 支持type name id path expire domain 等参数
'SESSION_TYPE' => '', // session hander类型 默认无需设置 除非扩展了session hander驱动
'SESSION_PREFIX' => '', // session 前缀
//'VAR_SESSION_ID' => 'session_id', //sessionID的提交变量
/* 模板引擎设置 */
'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型
'TMPL_ACTION_ERROR' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件
'TMPL_ACTION_SUCCESS' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件
'TMPL_EXCEPTION_FILE' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件
'TMPL_DETECT_THEME' => false, // 自动侦测模板主题
'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀
'TMPL_FILE_DEPR' => '/', //模板文件CONTROLLER_NAME与ACTION_NAME之间的分割符
// 布局设置
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效
'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀
'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数
'TMPL_DENY_PHP' => false, // 默认模板引擎是否禁用PHP原生代码
'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记
'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记
'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象
'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行
'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_CACHE_PREFIX' => '', // 模板缓存前缀标识,可以动态改变
'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识
'LAYOUT_ON' => false, // 是否启用布局
'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout
// Think模板引擎标签库相关设定
'TAGLIB_BEGIN' => '<', // 标签库标签开始标记
'TAGLIB_END' => '>', // 标签库标签结束标记
'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
/* URL设置 */
'URL_CASE_INSENSITIVE' => true, // 默认false 表示URL区分大小写 true则表示不区分大小写
'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式:
// 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式
'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号
'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', // 用于兼容判断PATH_INFO 参数的SERVER替代变量列表
'URL_REQUEST_URI' => 'REQUEST_URI', // 获取当前页面地址的系统变量 默认为REQUEST_URI
'URL_HTML_SUFFIX' => 'html', // URL伪静态后缀设置
'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', // URL禁止访问的后缀设置
'URL_PARAMS_BIND' => true, // URL变量绑定到Action方法参数
'URL_PARAMS_BIND_TYPE' => 0, // URL变量绑定的类型 0 按变量名绑定 1 按变量顺序绑定
'URL_PARAMS_FILTER' => false, // URL变量绑定过滤
'URL_PARAMS_FILTER_TYPE'=> '', // URL变量绑定过滤方法 如果为空 调用DEFAULT_FILTER
'URL_ROUTER_ON' => false, // 是否开启URL路由
'URL_ROUTE_RULES' => array(), // 默认路由规则 针对模块
'URL_MAP_RULES' => array(), // URL映射定义规则
/* 系统变量名称设置 */
'VAR_MODULE' => 'm', // 默认模块获取变量
'VAR_ADDON' => 'addon', // 默认的插件控制器命名空间变量
'VAR_CONTROLLER' => 'c', // 默认控制器获取变量
'VAR_ACTION' => 'a', // 默认操作获取变量
'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量
'VAR_JSONP_HANDLER' => 'callback',
'VAR_PATHINFO' => 's', // 兼容模式PATHINFO获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_DEPR
'VAR_TEMPLATE' => 't', // 默认模板切换变量
'VAR_AUTO_STRING' => false, // 输入变量是否自动强制转换为字符串 如果开启则数组变量需要手动传入变量修饰符获取变量
'HTTP_CACHE_CONTROL' => 'private', // 网页缓存控制
'CHECK_APP_DIR' => true, // 是否检查应用目录是否创建
'FILE_UPLOAD_TYPE' => 'Local', // 文件上传方式
'DATA_CRYPT_TYPE' => 'Think', // 数据加密方式
);
=======
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
/**
* ThinkPHP惯例配置文件
* 该文件请不要修改,如果要覆盖惯例配置的值,可在应用配置文件中设定和惯例不符的配置项
* 配置名称大小写任意,系统会统一转换成小写
* 所有配置参数都可以在生效前动态改变
*/
defined('THINK_PATH') or exit();
return array(
/* 应用设定 */
'APP_USE_NAMESPACE' => true, // 应用类库是否使用命名空间
'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名部署
'APP_SUB_DOMAIN_RULES' => array(), // 子域名部署规则
'APP_DOMAIN_SUFFIX' => '', // 域名后缀 如果是com.cn net.cn 之类的后缀必须设置
'ACTION_SUFFIX' => '', // 操作方法后缀
'MULTI_MODULE' => true, // 是否允许多模块 如果为false 则必须设置 DEFAULT_MODULE
'MODULE_DENY_LIST' => array('Common','Runtime'),
'CONTROLLER_LEVEL' => 1,
'APP_AUTOLOAD_LAYER' => 'Controller,Model', // 自动加载的应用类库层 关闭APP_USE_NAMESPACE后有效
'APP_AUTOLOAD_PATH' => '', // 自动加载的路径 关闭APP_USE_NAMESPACE后有效
/* Cookie设置 */
'COOKIE_EXPIRE' => 0, // Cookie有效期
'COOKIE_DOMAIN' => '', // Cookie有效域名
'COOKIE_PATH' => '/', // Cookie路径
'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突
'COOKIE_SECURE' => false, // Cookie安全传输
'COOKIE_HTTPONLY' => '', // Cookie httponly设置
/* 默认设定 */
'DEFAULT_M_LAYER' => 'Model', // 默认的模型层名称
'DEFAULT_C_LAYER' => 'Controller', // 默认的控制器层名称
'DEFAULT_V_LAYER' => 'View', // 默认的视图层名称
'DEFAULT_LANG' => 'zh-cn', // 默认语言
'DEFAULT_THEME' => '', // 默认模板主题名称
'DEFAULT_MODULE' => 'Home', // 默认模块
'DEFAULT_CONTROLLER' => 'Index', // 默认控制器名称
'DEFAULT_ACTION' => 'index', // 默认操作名称
'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码
'DEFAULT_TIMEZONE' => 'PRC', // 默认时区
'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', // 默认JSONP格式返回的处理方法
'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法 用于I函数...
/* 数据库设置 */
'DB_TYPE' => '', // 数据库类型
'DB_HOST' => '', // 服务器地址
'DB_NAME' => '', // 数据库名
'DB_USER' => '', // 用户名
'DB_PWD' => '', // 密码
'DB_PORT' => '', // 端口
'DB_PREFIX' => '', // 数据库表前缀
'DB_PARAMS' => array(), // 数据库连接参数
'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效
'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量
'DB_SLAVE_NO' => '', // 指定从服务器序号
/* 数据缓存设置 */
'DATA_CACHE_TIME' => 0, // 数据缓存有效期 0表示永久缓存
'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存
'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存
'DATA_CACHE_PREFIX' => '', // 缓存前缀
'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator
'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效)
'DATA_CACHE_KEY' => '', // 缓存文件KEY (仅对File方式缓存有效)
'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录)
'DATA_PATH_LEVEL' => 1, // 子目录缓存级别
/* 错误设置 */
'ERROR_MESSAGE' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效
'ERROR_PAGE' => '', // 错误定向页面
'SHOW_ERROR_MSG' => false, // 显示错误信息
'TRACE_MAX_RECORD' => 100, // 每个级别的错误信息 最大记录数
/* 日志设置 */
'LOG_RECORD' => false, // 默认不记录日志
'LOG_TYPE' => 'File', // 日志记录类型 默认为文件方式
'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR',// 允许记录的日志级别
'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制
'LOG_EXCEPTION_RECORD' => false, // 是否记录异常信息日志
/* SESSION设置 */
'SESSION_AUTO_START' => true, // 是否自动开启Session
'SESSION_OPTIONS' => array(), // session 配置数组 支持type name id path expire domain 等参数
'SESSION_TYPE' => '', // session hander类型 默认无需设置 除非扩展了session hander驱动
'SESSION_PREFIX' => '', // session 前缀
//'VAR_SESSION_ID' => 'session_id', //sessionID的提交变量
/* 模板引擎设置 */
'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型
'TMPL_ACTION_ERROR' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件
'TMPL_ACTION_SUCCESS' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件
'TMPL_EXCEPTION_FILE' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件
'TMPL_DETECT_THEME' => false, // 自动侦测模板主题
'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀
'TMPL_FILE_DEPR' => '/', //模板文件CONTROLLER_NAME与ACTION_NAME之间的分割符
// 布局设置
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效
'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀
'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数
'TMPL_DENY_PHP' => false, // 默认模板引擎是否禁用PHP原生代码
'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记
'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记
'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象
'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行
'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_CACHE_PREFIX' => '', // 模板缓存前缀标识,可以动态改变
'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识
'LAYOUT_ON' => false, // 是否启用布局
'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout
// Think模板引擎标签库相关设定
'TAGLIB_BEGIN' => '<', // 标签库标签开始标记
'TAGLIB_END' => '>', // 标签库标签结束标记
'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
/* URL设置 */
'URL_CASE_INSENSITIVE' => true, // 默认false 表示URL区分大小写 true则表示不区分大小写
'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式:
// 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式
'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号
'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', // 用于兼容判断PATH_INFO 参数的SERVER替代变量列表
'URL_REQUEST_URI' => 'REQUEST_URI', // 获取当前页面地址的系统变量 默认为REQUEST_URI
'URL_HTML_SUFFIX' => 'html', // URL伪静态后缀设置
'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', // URL禁止访问的后缀设置
'URL_PARAMS_BIND' => true, // URL变量绑定到Action方法参数
'URL_PARAMS_BIND_TYPE' => 0, // URL变量绑定的类型 0 按变量名绑定 1 按变量顺序绑定
'URL_PARAMS_FILTER' => false, // URL变量绑定过滤
'URL_PARAMS_FILTER_TYPE'=> '', // URL变量绑定过滤方法 如果为空 调用DEFAULT_FILTER
'URL_ROUTER_ON' => false, // 是否开启URL路由
'URL_ROUTE_RULES' => array(), // 默认路由规则 针对模块
'URL_MAP_RULES' => array(), // URL映射定义规则
/* 系统变量名称设置 */
'VAR_MODULE' => 'm', // 默认模块获取变量
'VAR_ADDON' => 'addon', // 默认的插件控制器命名空间变量
'VAR_CONTROLLER' => 'c', // 默认控制器获取变量
'VAR_ACTION' => 'a', // 默认操作获取变量
'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量
'VAR_JSONP_HANDLER' => 'callback',
'VAR_PATHINFO' => 's', // 兼容模式PATHINFO获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_DEPR
'VAR_TEMPLATE' => 't', // 默认模板切换变量
'VAR_AUTO_STRING' => false, // 输入变量是否自动强制转换为字符串 如果开启则数组变量需要手动传入变量修饰符获取变量
'HTTP_CACHE_CONTROL' => 'private', // 网页缓存控制
'CHECK_APP_DIR' => true, // 是否检查应用目录是否创建
'FILE_UPLOAD_TYPE' => 'Local', // 文件上传方式
'DATA_CRYPT_TYPE' => 'Think', // 数据加密方式
);
>>>>>>> 98b56c4fd74d8c0bc5ebc0c352b176e8d8f7d926
| zhoujiangyou/happychou | Inc/Conf/convention.php | PHP | apache-2.0 | 22,628 |
"use strict";
import {Vector2, Vector3, Matrix4, Vector4} from 'vectormath';
/*
NOTE: this was originally a WebGL UI library I wrote.
it's gone through several transitions since then, and
is now a canvas2d UI library (bleh). the code is quite
horrible.
*/
#include "src/utils/utildefine.js"
//we keep track of any canvases with non-GC managed data,
//(gl objects, TriListAlloc, TA_Alloc, etc) to avoid reference leaks
//g_app_state.reset calls .destroy() on all canvases inside this list.
//(then resets it back to {}).
window.active_canvases = {};
window._canvas_draw_id = 1;
//disable use of theoretically faster typed array allocator,
//for now.
//#ifdef NOCACHE
#define F32ALLOC(verts) new Float32Array(verts);
#define F32FREE(verts) verts = undefined;
/*#else
-#define F32ALLOC(verts123) f32_alloc.from_array(verts123);
-#define F32FREE(verts123) if (verts123 != undefined) { f32_alloc.free(verts123); verts123 = undefined;}
#endif
*/
//
//
//stupid statics
var _trilist_n0 = new Vector3(); var _trilist_n1 = new Vector3()
var _trilist_n2 = new Vector3(); var _trilist_n3 = new Vector3()
var _trilist_v1 = new Vector3(); var _trilist_v2 = new Vector3()
var _trilist_v3 = new Vector3(); var _trilist_v4 = new Vector3()
var _trilist_c1 = new Vector4(); var _trilist_c2 = new Vector4()
var _trilist_c3 = new Vector4(); var _trilist_c4 = new Vector4()
var _trilist_v5 = new Vector3(); var _trilist_v6 = new Vector3();
var _trilist_v7 = new Vector3(); var _trilist_v8 = new Vector3();
var _trilist_v9 = new Vector3();
#define TRILIST_CACHE_SIZE 8192
/*I hate garbage collected languages. Bleh! This class
is necessary to avoid object allocations within draw frames.
evil!*/
export class TriListAlloc {
constructor() {
this.freelist = [];
this.freecount = 0;
this.usedcount = 0;
this.peakcount = 0;
}
alloc(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) : TriList {
this.peakcount = Math.max(this.peakcount, this.usedcount+1);
#ifdef NOCACHE
return new TriList(canvas, transmat, use_small_icons);
#endif
if (this.freecount == 0) {
//ensure a saturated cache
if (this.usedcount == 0) {
for (var i=0; i<TRILIST_CACHE_SIZE; i++) {
var tl = new TriList(canvas, transmat, use_small_icons);
tl.cache_destroy();
this.freelist.push(tl);
this.freecount++;
}
}
this.usedcount++;
return new TriList(canvas, transmat, use_small_icons);
} else {
//console.log("using cached trilist", this.freecount, this.freelist.length);
var ret = this.freelist.pop();
ret.cache_init(canvas, transmat, use_small_icons);
this.freecount--;
this.usedcount++;
return ret;
}
}
free(TriList trilist) {
this.usedcount--;
#ifdef NOCACHE
trilist.cache_destroy();
return;
#endif
//abandon trilist to the GC
if (this.freecount >= TRILIST_CACHE_SIZE)
return;
trilist.cache_destroy();
this.freelist.push(trilist);
this.freecount++;
}
}
var _talloc = new TriListAlloc();
/*
TriList is being refactored to make it more usable.
vertex buffers will be reused, and transformation
matrices will be passed in at draw time, not applied
at vertex generation time.
*/
export class TriListRef {
constructor(gl, TriList trilist, Matrix4 mat, UICanvas canvas) {
this.trilist = trilist;
this.mat = mat;
this.workmat = new Matrix4();
this.gl = gl;
this.canvas = canvas;
}
destroy() {
}
on_draw(WebGLRenderingContext gl) {
this.workmat.load(this.mat);
this.workmat.multiply(this.canvas.global_matrix);
this.trilist.global_matrix = this.workmat;
this.trilist.on_draw(gl);
}
}
export class TriListCache {
constructor(limit=100) {
this.cache = {};
this.length = 0;
this.limit = limit;
}
get(String key) : TriList {
return this.cache[key];
}
has(String key) : Boolean {
return key in this.cache;
}
set(String key, TriList trilist) {
if (!(key in this.cache)) {
this.length++;
}
this.cache[key] = trilist;
}
remove(String key) {
if (key in this.cache) {
this.cache[key].destroy();
this.length--;
delete this.cache[key];
}
}
destroy() {
for (var k in this.cache) {
var tl = this.cache[k];
tl.destroy();
}
this.cache = {};
this.length = 0;
}
on_gl_lost() {
this.length = 0;
this.cache = {};
}
}
export class TriList {
cache_destroy() {
this._free_typed();
this.verts.length = 0;
this.texcos.length = 0;
this.colors.length = 0;
this.tottri = 0;
//this.canvas = undefined;
//this.iconsheet = undefined;
//this.viewport = undefined;
this._dead = true;
}
_free_typed() {
//f32free sets vertbuf/colorbuf/texbuf to undefined
F32FREE(this.vertbuf);
F32FREE(this.colorbuf);
F32FREE(this.texbuf);
}
cache_init(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) {
this._dead = false;
this.transmat = transmat;
this.global_matrix = canvas.global_matrix;
this.use_tex = 1;
this.tex = 0 : WebGLTexture;
this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet;
this.small_icons = use_small_icons;
this.verts.length = 0;
this.colors.length = 0;
this.texcos.length = 0;
this.recalc = 1
this.tottri = 0;
this.canvas = canvas
this.spos = undefined : Array<float>;
this.ssize = undefined : Array<float>;
this.gl_spos = undefined : Array<float>;
this.gl_ssize = undefined : Array<float>;
this.viewport = canvas != undefined ? canvas.viewport : undefined;
}
constructor(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) {
this._id = _canvas_draw_id++;
this.transmat = transmat;
this.global_matrix = canvas.global_matrix;
this.verts = [];
this.colors = [];
this.texcos = [];
this._dead = false;
this.vertbuf = undefined;
this.colorbuf = undefined;
this.texbuf = undefined;
this.use_tex = 1;
this.tex = 0 : WebGLTexture;
this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet;
this.small_icons = use_small_icons;
this.recalc = 1
this.tottri = 0;
this.canvas = canvas
this.spos = undefined : Array<float>;
this.ssize = undefined : Array<float>;
this.gl_spos = undefined : Array<float>;
this.gl_ssize = undefined : Array<float>;
this.viewport = canvas != undefined ? canvas.viewport : undefined;
}
add_tri(Array<float> v1, Array<float> v2, Array<float> v3,
Array<float> c1, Array<float> c2, Array<float> c3,
Array<float> t1, Array<float> t2, Array<float> t3)
{
var vs = this.verts;
this.tottri++;
static v12 = new Vector3();
static v22 = new Vector3();
static v32 = new Vector3();
v12.loadxy(v1); v22.loadxy(v2); v32.loadxy(v3);
v1 = v12; v2 = v22; v3 = v32;
this.transform(v1); this.transform(v2); this.transform(v3);
vs.push(v1[0]); vs.push(v1[1]); vs.push(v1[2]);
vs.push(v2[0]); vs.push(v2[1]); vs.push(v2[2]);
vs.push(v3[0]); vs.push(v3[1]); vs.push(v3[2]);
var cs = this.colors
if (c2 == undefined) {
c2 = c1;
c3 = c1;
}
cs.push(c1[0]); cs.push(c1[1]); cs.push(c1[2]); cs.push(c1[3]);
cs.push(c2[0]); cs.push(c2[1]); cs.push(c2[2]); cs.push(c2[3]);
cs.push(c3[0]); cs.push(c3[1]); cs.push(c3[2]); cs.push(c3[3]);
if (this.use_tex) {
if (t1 == undefined) {
static negone = [-1, -1];
t1 = t2 = t3 = negone;
}
var ts = this.texcos
ts.push(t1[0]); ts.push(t1[1]); ts.push(t2[0]); ts.push(t2[1]);
ts.push(t3[0]); ts.push(t3[1])
}
}
add_quad(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4,
Array<float> c1,Array<float> c2,Array<float> c3,
Array<float> c4,Array<float> t1,Array<float> t2,
Array<float> t3,Array<float> t4)
{
this.add_tri(v1, v2, v3, c1, c2, c3, t1, t2, t3);
this.add_tri(v1, v3, v4, c1, c3, c4, t1, t3, t4);
}
icon_quad(int icon, Vector3 pos, Array<Array<float>> cs)
{
static tcos = new Array(0);
//var clr = [1, 1, 1, 1];
//var cs = [clr, clr, clr, clr];
var cw = this.iconsheet.cellsize[0], ch = this.iconsheet.cellsize[1];
var v1 = new Vector3([pos[0], pos[1], 0.0]);
var v2 = new Vector3([pos[0], pos[1]+ch, 0.0]);
var v3 = new Vector3([pos[0]+cw, pos[1]+ch, 0.0]);
var v4 = new Vector3([pos[0]+cw, pos[1], 0.0]);
tcos.length = 0;
this.iconsheet.gen_tile(icon, tcos);
var t1 = new Vector3([tcos[0], tcos[1], 0]);
var t2 = new Vector3([tcos[2], tcos[3], 0]);
var t3 = new Vector3([tcos[4], tcos[5], 0]);
var t4 = new Vector3([tcos[6], tcos[7], 0]);
var t5 = new Vector3([tcos[8], tcos[9], 0]);
var t6 = new Vector3([tcos[10], tcos[11], 0]);
this.add_tri(v1, v2, v3, cs[0], cs[1], cs[2], t1, t2, t3);
this.add_tri(v1, v3, v4, cs[0], cs[2], cs[3], t4, t5, t6);
}
transform(v) {
static transvec = new Vector3();
transvec[0] = v[0];
transvec[1] = v[1];
transvec[2] = 0.0;
transvec.multVecMatrix(this.transmat);
v[0] = (transvec[0]/this.viewport[1][0])*2.0 - 1.0;
v[1] = (transvec[1]/this.viewport[1][1])*2.0 - 1.0;
}
line(v1, v2, c1, c2=undefined, width=undefined) { //c2 and width are optional
if (c2 == undefined) {
c2 = c1;
}
if (v1.length == 2) v1.push(0);
if (v2.length == 2) v2.push(0);
this.line_strip(CACHEARR2(CACHEARR2(v1, v2), CACHEARR2(c1, c2)), undefined, width);
//this.line_strip(objcache.getarr(objcache.getarr(v1, v2), objcache.getarr(c1, c2)), undefined, width);
}
line_strip(lines, colors, texcos=undefined, width=2.0, half=false) {
static black = new Vector4([0.0, 0.0, 0.0, 1.0]);
static v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3();
static v3 = new Vector3(), v4 = new Vector3(), n0 = new Vector3();
static n1 = new Vector3(), n2 = new Vector3(), c3 = new Vector3();
static c4 = new Vector3();
for (var i =0; i<lines.length; i++) {
var lc1 = colors[i][0], lc2 = colors[i][1];
//if (lines[i][0].length == 2) lines[i][0].push(0);
//if (lines[i][1].length == 2) lines[i][1].push(0);
if (lc1 == undefined) lc1 = black;
if (lc2 == undefined) lc2 = black;
var z = 0.0;
v1.loadxy(lines[i][0])
v2.loadxy(lines[i][1])
n0.zero(); n1.zero(); n2.zero();
v1.loadxy(lines[i][1]);
v1.sub(lines[i][0]);
v1.normalize();
n1[0] = v1[1];
n1[1] = -v1[0];
n1[2] = z;
n1.normalize()
if (i > 0) {
v0.loadxy(lines[i-1][1]);
v0.sub(lines[i-1][0])
v0.normalize();
n0[0] = v0[1];
n0[1] = -v0[0];
n0[2] = z;
n0.normalize()
} else {
n0.load(n1);
}
v1.loadxy(lines[i][1]);
v1.sub(lines[i][0])
if (i < lines.length-1) {
v3.loadxy(lines[i+1][1]);
v3.sub(lines[i+1][0]);
v3.normalize();
n2[0] = v3[1];
n2[1] = -v3[0];
n2[2] = z;
n2.normalize()
} else {
n2.load(n1);
}
/*
n0.normalize();
n1.normalize();
n2.normalize();
n0.mulScalar(0.5);
n1.mulScalar(0.5);
n2.mulScalar(0.5);
*/
n2.add(n1).normalize();
n1.add(n0).normalize();
n1.mulScalar(width*0.5);
n2.mulScalar(width*0.5);
v0.loadxy(lines[i][0]);
v1.loadxy(lines[i][1]);
v2.loadxy(lines[i][1]);
v2.add(n1);
v3.loadxy(lines[i][0]);
v3.add(n2);
var c1 = _trilist_c1.load(lc1); var c2 = _trilist_c2.load(lc2);
var c3 = _trilist_c3.load(lc2); var c4 = _trilist_c4.load(lc1);
if (width >= 1.5) {
c3[3] = 0.0;
c4[3] = 0.0;
}
n1.mulScalar(2.0);
n2.mulScalar(2.0);
if (this.use_tex && texcos) {
if (!half)
this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4, texcos[i][0],
texcos[i][1], texcos[i][0], texcos[i][1]);
this.add_quad(v1, v0, v3.sub(n1), v2.sub(n2), c2, c1, c3, c4, texcos[i][0],
texcos[i][1], texcos[i][0], texcos[i][1]);
} else {
if (!half)
this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4);
this.add_quad(v1, v0, v3.sub(n2), v2.sub(n1), c2, c1, c3, c4);
}
}
}
destroy(Boolean only_gl=false) {
var gl = g_app_state.gl;
if (this.vbuf) {
gl.deleteBuffer(this.vbuf);
gl.deleteBuffer(this.cbuf);
}
if (this.tbuf) {
gl.deleteBuffer(this.tbuf);
}
this.vbuf = this.cbuf = this.tbuf = undefined;
this.recalc = 1;
this._free_typed();
if (!only_gl) {
this._dead = true;
_talloc.free(this);
}
}
gen_buffers(gl) {
if (this.verts.length == 0)
return;
this.destroy(true);
this._free_typed();
this._dead = false;
this.vertbuf = F32ALLOC(this.verts); //new Float32Array(this.verts)
this.colorbuf = F32ALLOC(this.colors); //new Float32Array(this.colors)
if (this.use_tex)
this.texbuf = F32ALLOC(this.texcos); //new Float32Array(this.texcos);
gl.enableVertexAttribArray(0);
gl.enableVertexAttribArray(1);
if (this.use_tex)
gl.enableVertexAttribArray(2);
else
gl.disableVertexAttribArray(2);
var vbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbuf);
gl.bufferData(gl.ARRAY_BUFFER, this.vertbuf, gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vbuf);
var cbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cbuf);
gl.bufferData(gl.ARRAY_BUFFER, this.colorbuf, gl.STATIC_DRAW);
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, cbuf);
if (this.use_tex) {
var tbuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, tbuf);
gl.bufferData(gl.ARRAY_BUFFER, this.texbuf, gl.STATIC_DRAW);
gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, tbuf);
this.tbuf = tbuf
}
this.vbuf = vbuf;
this.cbuf = cbuf;
gl.disableVertexAttribArray(1);
gl.disableVertexAttribArray(2);
this.recalc = 0;
}
on_draw(gl) {
if (!this.iconsheet.ready)
return;
//if (this._dead)
// return;
if (this.verts.length == 0)
return;
if (this.recalc || (this.tdrawbuf != undefined && this.tdrawbuf.is_dead)) {
this.gen_buffers(gl);
}
if (this.ssize != undefined) {
gl.enable(gl.SCISSOR_TEST);
// g_app_state.raster.push_scissor(this.spos, this.ssize);
}
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl_blend_func(gl);
//gl.blendEquation(gl.BLEND_EQUATION);
//gl.blendEquationSeparate(gl.BLEND_EQUATION, gl.BLEND_EQUATION);
gl.enableVertexAttribArray(0);
gl.enableVertexAttribArray(1);
gl.disableVertexAttribArray(3);
gl.disableVertexAttribArray(4);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf);
gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf);
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf);
if (this.use_tex) {
gl.enableVertexAttribArray(2);
gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf);
gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf);
} else {
gl.disableVertexAttribArray(2);
}
gl.activeTexture(gl.TEXTURE4);
gl.bindTexture(gl.TEXTURE_2D, this.iconsheet.tex);
gl.useProgram(gl.basic2d.program);
this.global_matrix.setUniform(gl, gl.basic2d.uniformloc(gl, "mat"));
gl.uniform1i(gl.basic2d.uniformloc(gl, "iconsampler"), 4);
//console.log(this.verts);
//console.log(this.tottri*3, this.verts.length/3, this.colors.length/4, this.verts[0], this.verts[1], this.verts[2])
gl.drawArrays(gl.TRIANGLES, 0,this.tottri*3);
gl.disableVertexAttribArray(1);
gl.disableVertexAttribArray(2);
gl.enable(gl.DEPTH_TEST);
if (this.ssize != undefined) {
//g_app_state.raster.pop_scissor();
}
}
}
/*
var MAX_TRILIST_CACHE = 512;
var _trilist_frame_counter = 0;
var _trilist_template = {obj : new TriList(undefined, undefined), cachesize : MAX_TRILIST_CACHE};
function _reset_trilist_frame_counter() {
_trilist_frame_counter = 0;
}
function _new_trilist(UICanvas canvas) {
if (_trilist_frame_counter = 0 >= MAX_TRILIST_CACHE) {
return new TriList(canvas);
} else {
var list = objcache.fetch(_trilist_template)
TriList.call(list, canvas);
}
}
function _save_trilist(TriList trilist) {
if (objcache.is_cache_obj(trilist)) {
objcache.cache_remove(trilist);
}
}
*/
export class TextDraw {
constructor(pos, text, color, spos, ssize, viewport, size, scale, global_matrix, rot=0) {
this._id = _canvas_draw_id++;
this.rot = rot;
this.global_matrix = global_matrix;
this.text = text;
this.pos = [pos[0], pos[1], pos[2]];
this.color = color;
this.tdrawbuf = undefined : TextDrawBuffer;
this.spos = spos;
this.ssize = ssize;
this.asp = viewport[1][1] / viewport[1][0];
this.viewport = viewport;
this.scale = [scale[0], scale[1], 0];
this.size = size;
this.raster = g_app_state.raster;
var mat = new Matrix4();
mat.translate(this.pos[0], this.pos[1], 0.0);
//denormalize to avoid squashed rotations
mat.scale(1, 1.0/this.asp, 1);
mat.rotate(0, 0, rot);
mat.scale(this.scale);
//norrmalize again
mat.scale(1, this.asp, 1);
this.mat = mat;
}
destroy() {
/*don't destroy the gl buffers here, since I'm
now caching them*/
/*
if (this.tdrawbuf != undefined)
this.tdrawbuf.destroy();
this.tdrawbuf = undefined;
*/
}
toString() : String {
return "TD" + this._id;
}
gen_buffers(gl) {
this.tdrawbuf = this.raster.get_font(this.size).gen_text_buffers(gl, this.text, this.color, this.viewport);
return this.tdrawbuf;
}
on_draw(gl) {
static identitymat = new Matrix4();
gl.disableVertexAttribArray(4);
if (this.tdrawbuf == undefined)
this.gen_buffers(gl);
var spos, ssize;
if (this.ssize != undefined) {
spos = CACHEARR3(this.spos[0], this.spos[1], 0);
ssize = CACHEARR3(this.ssize[0], this.ssize[1], 0);
// g_app_state.raster.push_scissor(spos, ssize);
}
static mat = new Matrix4();
mat.load(this.global_matrix);
mat.multiply(this.mat);
this.tdrawbuf.on_draw(gl, mat);
if (this.ssize != undefined) {
//g_app_state.raster.pop_scissor();
}
}
}
var _ls_static_colors = {reallength: 0, length: 0};
window._box_process_clr = function _box_process_clr(default_cs, clr) {
var cs = default_cs;
static arr4 = [0, 0, 0, 0];
if (clr != undefined) {
if (typeof clr == "number") {
var cs2 = arr4;
for (var i=0; i<4; i++) {
cs2[i] = CACHEARR4(cs[i][0], cs[i][1], cs[i][2], cs[i][3]);
for (var j=0; j<4; j++) {
cs2[i] *= clr;
}
}
cs = cs2;
} else if (typeof clr[0] == "number") {
var cs = arr4;
cs[0] = clr; cs[1] = clr; cs[2] = clr; cs[3] = clr;
} else {
cs = clr;
}
}
return cs;
}
//XXX XXX!
export class UICanvas_ {
constructor(viewport) {
static _id = 1;
this._id = _id++;
this.global_matrix = new Matrix4();
this.iconsheet = g_app_state.raster.iconsheet;
this.iconsheet16 = g_app_state.raster.iconsheet16;
this.viewport = viewport;
this.raster = g_app_state.raster;
this.trilist = _talloc.alloc(this, this.transmat);
this.textcache = {};
this.textcachelen = 0;
this.max_textcache = 64;
this.boxcache = new TriListCache();
this.trans_stack = []
this.transmat = new Matrix4()
this.drawlists = [this.trilist]
this.textlist = [];
this.stack = []
this.cache = new hashtable();
this.oldcache = new hashtable();
this.uncached = new Array();
this.uncached.push(this.trilist);
this.scissor_stack = new Array();
this.flag = 0;
}
ensure_trilist() {
if (this.drawlists.length == 0 || !(this.drawlists[this.drawlists.length-1] instanceof TriList)) {
this.new_trilist();
}
}
set_viewport(viewport) {
var bad = false;
for (var i=0; i<3; i++) {
if (viewport[1][i] != this.viewport[1][i])
bad = true;
}
this.viewport = viewport;
if (bad) {
this.on_resize(viewport[1], viewport[1]);
}
}
on_gl_lost(WebGLRenderingContext new_gl) {
this.boxcache.on_gl_lost();
if (this.gl === new_gl) {
console.trace();
console.log("Warning: uicanvas.on_gl_lost() called multiple times");
return;
}
this.gl = new_gl;
this.drawlists = new Array();
this.iconsheet = g_app_state.raster.iconsheet;
this.iconsheet16 = g_app_state.raster.iconsheet16;
this.textcache = {};
this.textcachelen = 0;
this.stack = []
this.raster = g_app_state.raster;
this.cache = new hashtable();
this.oldcache = new hashtable();
this.boxcache = UICanvas.boxcache;
this.new_trilist();
//now that gl data is destroyed,
//call .reset to maintain data structure integrity
this.reset();
}
push_scissor(pos, size) {
var oldpos = pos;
pos = new Vector3([pos[0], pos[1], 0]);
size = new Vector3([size[0], size[1], 0]);
pos.multVecMatrix(this.transmat);
size.multVecMatrix(this.transmat);
var vx=this.viewport[0][0], vy=this.viewport[0][1]
pos[0] += vx; pos[1] += vy;
var dx = pos[0]-oldpos[0]-vx, dy = pos[1]-oldpos[1]-vy;
size[0] -= dx; size[1] -= dy;
for (var i=0; i<3; i++) {
pos[i] = Math.floor(pos[i]);
size[i] = Math.ceil(size[i]);
}
this.scissor_stack.push([pos, size]);
this.new_trilist();
}
pop_scissor() {
this.scissor_stack.pop();
this.new_trilist();
}
new_trilist(Boolean use_small_icons=false) {
//flag canvas for memory leak detection, see active_canvases's definition
active_canvases[this._id] = this;
this.trilist = _talloc.alloc(this, this.transmat, use_small_icons); //new TriList(this, use_small_icons);
if (this.scissor_stack.length > 0) {
this.trilist.spos = this.scissor_stack[this.scissor_stack.length-1][0];
this.trilist.ssize = this.scissor_stack[this.scissor_stack.length-1][1];
}
this.drawlists.push(this.trilist);
return this.trilist;
}
translate(Array<float> off) {
this.transmat.translate(off[0], off[1], 0.0);
}
push_transform(mat=undefined) {
this.trans_stack.push(new Matrix4(this.transmat));
if (mat != undefined)
this.transmat.multiply(mat);
}
pop_transform() {
this.transmat.load(this.trans_stack.pop());
}
frame_begin(Object item) {
return;//XXX
if (DEBUG.ui_canvas) {
console.log("canvas start, stack length: ", this.stack.length);
}
this.new_trilist();
this.stack.push(this.drawlists.length-1);
}
frame_end(Object item) {
return;//XXX
var arr = new Array()
var start = this.stack[this.stack.length-1];
this.stack.pop();
if (DEBUG.ui_canvas)
console.log(start);
for (var i=start; i<this.drawlists.length; i++) {
arr.push(this.drawlists[i]);
}
this.cache.set(item, arr);
this.new_trilist();
if (DEBUG.ui_canvas) {
console.log("canvas end, stack length: ", this.stack.length);
}
return arr;
}
begin(Object item) {
//okay, individual leaf element caching may not have been a good
//idea. . .
//-XXX
return;
if (DEBUG.ui_canvas) {
console.log("canvas start, stack length: ", this.stack.length);
}
this.new_trilist();
this.stack.push(this.drawlists.length-1);
}
end(Object item) {
//-XXX;
return;
var arr = new Array()
var start = this.stack.pop(this.stack.length-1);
if (DEBUG.ui_canvas)
console.log(start);
for (var i=start; i<this.drawlists.length; i++) {
arr.push(this.drawlists[i]);
}
this.stack.pop();
this.cache.set(item, arr);
this.new_trilist();
if (DEBUG.ui_canvas) {
console.log("canvas end, stack length: ", this.stack.length);
}
return arr;
}
use_cache(Object item) {
if (this.oldcache.has(item)) {
var arr = this.oldcache.get(item);
for (var i=0; i<arr.length; i++) {
this.drawlists.push(arr[i]);
if (arr[i] instanceof TextDraw)
this.textlist.push(arr[i]);
}
this.oldcache.remove(item);
this.cache.set(item, arr);
this.new_trilist();
}
}
has_cache(Object item) {
return this.oldcache.has(item);
}
remove_cache(Object item) {
if (this.oldcache.has(item))
this.oldcache.remove(item);
}
textsize(text, size=default_ui_font_size) {
var box = this.raster.get_font(size).calcsize(text);
return [box[0], box[1]];
}
line(v1, v2, c1, c2=c1, width=2.0) {
this.ensure_trilist();
this.line_strip([[v1, v2]], [[c1, c2]], undefined, width);
}
line_strip(lines, colors, texcos, width, half) {//colors,texcos,width are optional
this.ensure_trilist();
if (colors == undefined) {
colors = uicolors["DefaultLine"];
}
if (typeof(colors[0]) == "number") {
var clr = colors;
colors =_ls_static_colors;
for (var i=0; i<lines.length; i++) {
if (colors[i] == undefined) {
colors[i] = [clr, clr];
} else {
colors[i][0] = clr;
colors[i][1] = clr;
}
}
colors.reallength = Math.max(colors.reallength, i);
colors.length = i;
}
this.trilist.line_strip(lines, colors, texcos, width, half);
}
line_loop(points, colors, texcos, width, half) { //colors,texcos,width are optional
var lines = []
this.ensure_trilist();
if (colors == undefined) {
colors = uicolors["DefaultLine"];
}
var lcolors;
if (typeof colors[0] != "number")
lcolors = []
else
lcolors = []
for (var i=0; i<points.length; i++) {
var i2 = (i+1)%points.length;
lines.push([points[i], points[i2]]);
if (typeof(colors[0]) != "number") {
lcolors.push([colors[i], colors[i2]]);
} else {
lcolors.push([colors, colors]);
}
}
this.line_strip(lines, lcolors, undefined, width, half);
}
quad(v1, v2, v3, v4, c1, c2, c3, c4) {
this.ensure_trilist();
if (v1.length == 2)
v1.push(0);
if (v2.length == 2)
v2.push(0);
if (v3.length == 2)
v3.push(0);
if (v4.length == 2)
v4.push(0);
this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4);
}
quad_aa(v1, v2, v3, v4, c1, c2, c3, c4) {
this.ensure_trilist();
if (v1.length == 2)
v1.push(0);
if (v2.length == 2)
v2.push(0);
if (v3.length == 2)
v3.push(0);
if (v4.length == 2)
v4.push(0);
if (c2 == undefined) {
c2 = c3 = c4 = c1;
}
this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4);
var lines = [[v1, v4], [v4, v3], [v3, v2], [v2, v1]];
var colors = [[c1, c4], [c4, c3], [c3, c2], [c2, c1]];
this.trilist.line_strip(lines, colors, undefined, undefined, true)
}
tri(v1, v2, v3, c1, c2, c3) {
this.ensure_trilist();
if (v1.length == 2)
v1.push(0);
if (v2.length == 2)
v2.push(0);
if (v3.length == 2)
v3.push(0);
this.trilist.add_tri(v1, v2, v3, c1, c2, c3);
}
on_draw(gl) {
//Set the viewport and projection matrix for the scene
gl.viewport(this.viewport[0][0], this.viewport[0][1], this.viewport[1][0], this.viewport[1][1]);
var len = this.drawlists.length;
for (var i=0; i<len; i++) {
if (DEBUG.canvas_sep_text && this.drawlists[i] instanceof TextDraw)
continue;
this.drawlists[i].on_draw(gl);
}
if (DEBUG.canvas_sep_text) {
var len = this.textlist.length;
for (var i=0; i<len; i++) {
this.textlist[i].on_draw(gl);
}
}
}
arc_points(pos, start, arc, r, steps) {//steps is optional
if (steps == undefined) {
steps = Math.floor(6*arc/Math.PI);
}
var f, df;
var f = start;
var df = arc / steps;
var points = [];
for (var i=0; i<steps+1; i++) {
var x = pos[0] + Math.sin(f)*r;
var y = pos[1] + Math.cos(f)*r;
points.push([x, y, 0]);
f += df;
}
return points;
}
arc(pos, start, arc, r, clr, half) {
if (clr == undefined) {
clr = [0.9, 0.8, 0.7, 0.6];
}
var steps = 18/(2.0 - arc/(Math.PI*2));
var f, df;
var f = start;
var df = arc / steps;
var points = [];
for (var i=0; i<steps+1; i++) {
var x = pos[0] + Math.sin(f)*r;
var y = pos[1] + Math.cos(f)*r;
points.push([x, y, 0]);
f += df;
}
var lines = [];
var colors = [];
for (var i=0; i<points.length-1; i++) {
lines.push([points[i], points[i+1]])
colors.push([clr, clr])
}
colors[0][0] = [1.0, 1.0, 0.0, 1.0]
colors[0][1] = [1.0, 1.0, 0.0, 1.0]
this.trilist.line_strip(lines, colors, undefined, undefined, half);
}
destroy() {
this.reset();
//get rid of any cache data, too
for (var k in this.cache) {
var arr = this.cache.get(k);
for (var i=0; i<arr.length; i++) {
arr[i].destroy();
arr[i] = undefined;
}
}
this.boxcache.destroy();
this.cache = new hashtable();
if (this._id in active_canvases) {
delete active_canvases[this._id];
}
}
reset() {
/*
for (var i=0; i<this.uncached.length; i++) {
this.uncached[i].destroy();
this.uncached[i] = undefined;
}*/
var dmap = {};
for (var k in this.cache) {
var item = this.cache.get(k);
for (var i=0; i<item.length; i++) {
dmap[item[i]._id] = item[i];
}
}
var dl = this.drawlists;
for (var i=0; i<dl.length; i++) {
if (!(dl[i]._id in dmap)) {
dl[i].destroy();
}
}
if (DEBUG.canvas_sep_text) {
var tl = this.textlist;
for (var i=0; i<tl.length; i++) {
tl[i].destroy();
}
this.textlist.length = 0;
}
this.uncached.length = 0;
this.scissor_stack.length = 0;
/*destroy old cache that was used in last draw cycle, then swap it with
the new cache that was *built* last cycle.*/
for (var k in this.oldcache) {
var arr = this.oldcache.get(k)
for (var i=0; i<arr.length; i++) {
arr[i].destroy();
arr[i] = undefined;
}
}
this.oldcache = this.cache;
this.cache = new hashtable();
this.drawlists.length = 0;
if (this.trans_stack.length > 0) {
this.trans_stack[0].makeIdentity();
this.trans_stack.length = 1;
} else {
this.trans_stack.length = 0;
this.trans_stack.push(new Matrix4());
}
this.transmat = this.trans_stack[0];
this.stack.length = 0;
this.new_trilist();
}
invbox(pos, size, clr, r) {
var cs = uicolors["InvBox"]
cs = _box_process_clr(cs, clr);
this.box(pos, size, cs, r);
}
simple_box(pos, size, clr=undefined, r=2.0) { //clr is optional
var cs = uicolors["SimpleBox"]
cs = _box_process_clr(cs, clr);
this.box(pos, size, cs, r);
}
hlightbox(pos, size, clr_mul, r) { //clr_mul is optional
var cs = uicolors["HLightBox"]
/*if (clr != undefined) {
cs = [clr, clr, clr, clr]
}*/
if (clr_mul != undefined) {
cs = [new Vector4(cs[0]), new Vector4(cs[1]), new Vector4(cs[2]), new Vector4(cs[3])]
for (var i=0; i<4; i++) {
for (var j=0; j<4; j++) {
cs[i][j] *= clr_mul;
}
}
}
this.box(pos, size, cs, r);
}
box_outline(pos, size, clr, rfac) {
this.box(pos, size, clr, rfac, true);
}
shadow_box(pos, size, steps=6, margin=[6, 6], clr=uicolors["ShadowBox"]) {
static neg1 = [-2, -2];
//arg, can't remember the correct formula to use here
//x**steps = 0.1
//x = 0.1**(1.0/steps)
var fac = (1.0/steps)*0.4;
var clr = [clr[0], clr[1], clr[2], clr[3]*fac]
pos = new Vector2(pos);
size = new Vector2(size);
expand_rect2d(pos, size, margin);
for (var i=0; i<steps; i++) {
this.box(pos, size, clr);
expand_rect2d(pos, size, neg1);
}
}
box(pos, size, clr, rfac, outline_only) {
if (IsMobile || rfac == 0.0)
return this.box2(pos, size, clr, rfac, outline_only);
else //XXX
return this.box1(pos, size, clr, rfac, outline_only);
}
/* I think this word is Dutch. it comes from photography,
it means to dim the screen around a rectangle of
interest. need to look up the english word.
and no, I'm not Dutch.
*/
passpart(pos, size, clr=[0,0,0,0.5]) {
this.ensure_trilist();
var p = this.viewport[0];
var s = this.viewport[1];
this.box2([p[0], p[1]], [pos[0], s[1]], clr);
this.box2([p[0]+pos[0]+size[0], p[1]], [s[0]-pos[0]-size[0], s[1]], clr);
this.box2([pos[0]+p[0], pos[1]+p[1]+size[1]], [size[0], s[1]-size[1]-p[1]], clr);
this.box2([pos[0]+p[0], p[1]], [size[0], pos[1]], clr)
}
icon(int icon, Array<float> pos, float alpha=1.0, Boolean small=false,
Array<float> clr=undefined)
{
static white = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]];
var cs = _box_process_clr(white, clr);
for (var i=0; i<4; i++) {
cs[i][3] = alpha;
}
this.ensure_trilist();
if (this.trilist.small_icons != small) {
this.new_trilist(small);
}
this.trilist.icon_quad(icon, pos, cs);
}
box2(Array<float> pos, Array<float> size, Array<float> clr=undefined, float rfac=undefined, Boolean outline_only=false) {
this.ensure_trilist();
var cs = uicolors["Box"];
cs = _box_process_clr(cs, clr);
var x = pos[0], y=pos[1];
var w=size[0], h=size[1];
if (outline_only) {
this.line([pos[0], pos[1]], [pos[0], pos[1]+size[1]], clr, clr, 1.0);
this.line([pos[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]+size[1]], clr, clr, 1.0);
this.line([pos[0]+size[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]], clr, clr, 1.0);
this.line([pos[0]+size[0], pos[1]], [pos[0], pos[1]], clr, clr, 1.0);
} else {
this.trilist.add_quad(CACHEARR3(x, y, 0), CACHEARR3(x+w, y, 0), CACHEARR3(x+w, y+h, 0), CACHEARR3(x, y+h, 0), cs[0], cs[1], cs[2], cs[3]);
}
}
gen_box_trilist(Array<float> size, Array<float> clr=undefined, float rfac=1, Boolean outline_only=false) {
var w=size[0], h=size[1];
var start = 0, ang = Math.PI/2, r = 4;
var cs = _box_process_clr(uicolors["Box"], clr);
var trilist = new TriList(this, new Matrix4(), false);
r /= rfac;
var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r);
var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r);
var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r);
var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r);
var plen = p1.length;
p4.reverse(); p3.reverse();
p2.reverse(); p1.reverse();
var points = [];
for (var i=0; i<p1.length; i++) {
points.push(p1[i]);
}
for (var i=0; i<p2.length; i++) {
points.push(p2[i]);
p1.push(p2[i]);
}
for (var i=0; i<p3.length; i++) {
points.push(p3[i]);
}
p2 = p3;
for (var i=0; i<p4.length; i++) {
p2.push(p4[i]);
points.push(p4[i]);
}
p2.reverse();
var plen = p1.length;
function color(i) {
if (i < plen) return cs[0];
else if (i < plen*2) return cs[1];
else if (i < plen*3) return cs[2];
else if (i <= plen*4+1) return cs[3];
}
static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3();
#define LOAD_CLR(a, b) a[0] = b[0]; a[1] = b[1]; a[2] = b[2];
if (!outline_only) {
for (var i=0; i<p1.length-1; i++) {
var i1 = i;
var i2 = i+plen*2;
var i3 = i + 1+plen*2;
var i4 = i+1;
LOAD_CLR(v1, p1[i]);
LOAD_CLR(v2, p2[i]);
LOAD_CLR(v3, p2[i+1]);
LOAD_CLR(v4, p1[i+1]);
trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4));
}
}
var lines = [];
var colors = [];
static pairs = [];
for (var i=0; i<points.length; i++) {
LOAD_CLR(v1, points[(i+1)%points.length]);
LOAD_CLR(v2, points[i]);
if (pairs.length <= i) {
pairs.push([[0, 0], [0, 0]]);
}
pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0);
pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0);
lines.push(pairs[i][0]);
pairs[i][1][0] = color((i+1)%points.length);
pairs[i][1][1] = color(i);
colors.push(pairs[i][1]);
}
#undef LOAD_CLR
trilist.line_strip(lines, colors, undefined, outline_only ? 1.4 : 1.5, !outline_only);
return trilist;
}
box1(Array<float> pos, Array<float> size, Array<float> clr=[0, 0, 0, 1],
float rfac=1, Boolean outline_only=false)
{
var sclr = clr==undefined ? "u" : clr.toString();
var hash = size.toString()+sclr+rfac.toString()+(outline_only ? "|1" : "|0");
var cache = this.boxcache;
if (!cache.has(hash)) {
cache.set(hash, this.gen_box_trilist(size, clr, rfac, outline_only));
}
static co = new Vector3();
co.loadxy(pos);
co[2] = 0.0;
co.multVecMatrix(this.transmat);
var viewport = g_app_state.raster.viewport;
var sx = viewport[1][0];
var sy = viewport[1][1];
co[0] = (Math.floor(co[0])/sx)*2.0;// - 1.0;
co[1] = (Math.floor(co[1])/sy)*2.0;// - 1.0;
var mat = new Matrix4();
mat.translate(co[0], co[1], 0.0);
var ret = new TriListRef(this.gl, cache.get(hash), mat, this);
this.drawlists.push(ret);
return ret;
}
box1_old(Array<float> pos, Array<float> size, Array<float> clr=undefined,
float rfac=undefined, Boolean outline_only=false)
{
var c1, c2, c3, c4;
var cs = uicolors["Box"];
static cache = {};
if (outline_only == undefined)
outline_only = false;
cs = _box_process_clr(cs, clr);
var x = Math.floor(pos[0]), y=Math.floor(pos[1]);
var w=size[0], h=size[1];
var start = 0;
var ang = Math.PI/2;
var r = 4 //Math.sqrt(size[0]*size[1])
if (rfac == undefined)
rfac = 1;
var hash = size[0].toString() + " " + size[1] + " " + rfac;
if (!(hash in cache)) {
r /= rfac;
var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r);
var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r);
var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r);
var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r);
var plen = p1.length;
p4.reverse();
p3.reverse();
p2.reverse();
p1.reverse();
var points = []
for (var i=0; i<p1.length; i++) {
points.push(p1[i]);
}
for (var i=0; i<p2.length; i++) {
points.push(p2[i]);
p1.push(p2[i]);
}
for (var i=0; i<p3.length; i++) {
points.push(p3[i]);
}
p2 = p3;
for (var i=0; i<p4.length; i++) {
p2.push(p4[i]);
points.push(p4[i]);
}
p2.reverse();
cache[hash] = [p1, p2, points];
}
var cp = cache[hash];
var p1 = cp[0];
var p2 = cp[1];
var points = cp[2];
var plen = p1.length;
function color(i) {
if (i < plen) return cs[0];
else if (i < plen*2) return cs[1];
else if (i < plen*3) return cs[2];
else if (i <= plen*4+1) return cs[3];
}
static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3();
#define LOAD_CLR(a, b) a[0] = b[0]+x; a[1] = b[1]+y; a[2] = b[2];
if (!outline_only) {
for (var i=0; i<p1.length-1; i++) {
var i1 = i;
var i2 = i+plen*2;
var i3 = i + 1+plen*2;
var i4 = i+1;
LOAD_CLR(v1, p1[i]);
LOAD_CLR(v2, p2[i]);
LOAD_CLR(v3, p2[i+1]);
LOAD_CLR(v4, p1[i+1]);
this.trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4));
}
}
var lines = []
var colors = []
static pairs = [];
for (var i=0; i<points.length; i++) {
LOAD_CLR(v1, points[(i+1)%points.length]);
LOAD_CLR(v2, points[i]);
if (pairs.length <= i) {
pairs.push([[0, 0], [0, 0]]);
}
pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0);
pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0);
lines.push(pairs[i][0]);
pairs[i][1][0] = color((i+1)%points.length);
pairs[i][1][1] = color(i);
colors.push(pairs[i][1]);
}
#undef LOAD_CLR
this.trilist.line_strip(lines, colors, undefined, 4, true);
//this.box2(pos, size, clr, rfac, outline_only);
return this.trilist
}
on_resize(newsize, oldsize) {
this.boxcache.destroy();
//all cache entries with old size are now bad
for (var k in this.textcache) {
if (!this.textcache.hasOwnProperty(k)) continue;
this.textcache[k].destroy();
}
this.textcache = {};
this.textcachelen = 0;
//clear entire cache
this.destroy();
this.reset();
}
text(Array<float> pos, String text, Array<float> color, float size,
float scale, float rot, Array<float> scissor_pos, Array<float> scissor_size)
{
static loc = new Vector3();
if (rot == undefined)
rot = 0.0;
if (size == undefined)
size = default_ui_font_size;
if (scale == undefined) {
scale = CACHEARR3(1.0, 1.0, 1.0);
} else if (typeof(scale) == "number") {
scale = CACHEARR3(scale, scale, scale);
}
if (color == undefined) {
color = uicolors["DefaultText"]
}
if (scissor_pos == undefined) {
if (this.scissor_stack.length > 0) {
scissor_pos = this.scissor_stack[this.scissor_stack.length-1][0];
scissor_size = this.scissor_stack[this.scissor_stack.length-1][1];
}
} else {
scissor_pos = new Vector3([scissor_pos[0], scissor_pos[1], 0]);
scissor_size = new Vector3([scissor_size[0], scissor_size[1], 0]);
scissor_pos.multVecMatrix(this.transmat);
}
loc[0] = 0; loc[1] = 0; loc[2] = 0;
loc.multVecMatrix(this.transmat);
loc[0] += pos[0]
loc[1] += pos[1]
//yes, raster is supposed to be a nasty global
var port = g_app_state.raster.viewport
var sx = port[1][0]
var sy = port[1][1]
loc[0] = (Math.floor(loc[0])/sx)*2.0; //*2.0-1.0;
loc[1] = (Math.floor(loc[1])/sy)*2.0; //*2.0-1.0;
var textdraw = new TextDraw(loc, text, color, scissor_pos,
scissor_size, this.viewport, size, scale,
this.global_matrix, rot);
var hash = text.toString() + ">>" + size + "|" + color + "|" + JSON.stringify(this.viewport);
//XXX
// /*
if (!(hash in this.textcache)) {
if (this.textcachelen > this.max_textcache) {
var keys = Object.getOwnPropertyNames(this.textcache)
for (i=0; i<keys.length; i++) {
var k = keys[i];
this.textcache[k].destroy();
var users = this.textcache[k].users;
//possible evil!
for (var j=0; j<users.length; j++) {
users[j].recalc = true;
users[j].tdrawbuf = undefined;
}
delete this.textcache[k];
this.textcachelen--;
//amortize cache destruction calls
if (this.textcachelen < this.max_textcache/3)
break;
}
}
this.textcache[hash] = textdraw.gen_buffers(g_app_state.gl);
this.textcachelen++;
} else {
textdraw.tdrawbuf = this.textcache[hash];
}
this.textcache[hash].users.push(textdraw);
//-XXX
if (DEBUG.canvas_sep_text) {
this.textlist.push(textdraw);
this.drawlists.push(textdraw);
if (this.stack.length == 0) {
this.uncached.push(textdraw);
}
return loc;
} else {
if (this.drawlists[this.drawlists.length-1] == this.trilist) {
this.drawlists.push(textdraw);
this.new_trilist();
if (this.stack.length == 0) {
this.uncached.push(textdraw);
this.uncached.push(this.trilist);
}
} else {
this.drawlists.push(textdraw);
if (this.stack.length == 0) {
this.uncached.push(textdraw);
}
}
// */
return loc;
}
}
}
| joeedh/webblender | src/editors/interface/UICanvas.js | JavaScript | apache-2.0 | 46,545 |
/* Copyright 2014 Jonathan Holland.
*
* 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.
*/
namespace Wave
{
public interface IOutboundMessageFilter
{
bool OnMessagePublished(string routeKey, object message);
}
}
| WaveServiceBus/WaveServiceBus | src/Wave.Core/Interfaces/IOutboundMessageFilter.cs | C# | apache-2.0 | 735 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace CJia.Health.Presenters.Web
{
public class MyPicturePresenter:CJia.Health.Tools.PresenterPage<Models.Web.MyPictureModel,Views.Web.IMyPictureView>
{
public MyPicturePresenter(Views.Web.IMyPictureView view)
: base(view)
{
view.OnLoadPicture += view_OnLoadPicture;
view.OnProjectChanged += view_OnProjectChanged;
}
void view_OnProjectChanged(object sender, Views.Web.MyPictureArgs e)
{
DataTable data = Model.GetMyPictureByProID(e.HealthID, e.ProjectID);
View.ExeBindPictureByProjectID(data);
}
void view_OnLoadPicture(object sender, Views.Web.MyPictureArgs e)
{
DataTable project = Model.GetMyPictureProject(e.HealthID);
DataTable picture = Model.GetMyPicture(e.HealthID);
View.ExeBindPicture(picture);
View.ExeBindProject(project);
}
}
}
| leborety/CJia | CJia.HealthFileProject/CJia.Health/Presenters/Web/MyPicturePresenter.cs | C# | apache-2.0 | 1,049 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>PowerShell - Rename-Index - Rivet</title>
<link href="silk.css" type="text/css" rel="stylesheet" />
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<ul id="SiteNav">
<li><a href="index.html">Get-Rivet</a></li>
<!--<li><a href="about_Carbon_Installation.html">-Install</a></li>-->
<li><a href="documentation.html">-Documentation</a></li>
<!--<li><a href="about_Carbon_Support.html">-Support</a></li>-->
<li><a href="releasenotes.html">-ReleaseNotes</a></li>
<li><a href="http://pshdo.com">-Blog</a></li>
</ul>
<h1>Rename-Index</h1>
<div class="Synopsis">
<p>Renames an index.</p>
</div>
<h2>Syntax</h2>
<pre class="Syntax"><code>Rename-Index [-TableName] <String> [-Name] <String> [-NewName] <String> [-SchemaName <String>] [<CommonParameters>]</code></pre>
<h2>Description</h2>
<div class="Description">
<p>SQL Server ships with a stored procedure which is used to rename certain objects. This operation wraps that stored procedure.</p>
<p>Use <code>Rename-Column</code> to rename a column. Use <code>Rename-DataType</code> to rename a data type. Use <code>Rename-Object</code> to rename an object.</p>
</div>
<h2>Related Commands</h2>
<ul class="RelatedCommands">
<li><a href="http://technet.microsoft.com/en-us/library/ms188351.aspx">http://technet.microsoft.com/en-us/library/ms188351.aspx</a></li>
<li><a href="Rename-Column.html">Rename-Column</a></li>
<li><a href="Rename-DataType.html">Rename-DataType</a></li>
<li><a href="Rename-Object.html">Rename-Object</a></li>
</ul>
<h2> Parameters </h2>
<table id="Parameters">
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
<th>Required?</th>
<th>Pipeline Input</th>
<th>Default Value</th>
</tr>
<tr valign='top'>
<td>TableName</td>
<td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td>
<td class="ParamDescription"><p>The name of the table of the index to rename.</p></td>
<td>true</td>
<td>false</td>
<td></td>
</tr>
<tr valign='top'>
<td>Name</td>
<td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td>
<td class="ParamDescription"><p>The current name of the index.</p></td>
<td>true</td>
<td>false</td>
<td></td>
</tr>
<tr valign='top'>
<td>NewName</td>
<td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td>
<td class="ParamDescription"><p>The new name of the index.</p></td>
<td>true</td>
<td>false</td>
<td></td>
</tr>
<tr valign='top'>
<td>SchemaName</td>
<td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td>
<td class="ParamDescription"><p>The schema of the table. Default is <code>dbo</code>.</p></td>
<td>false</td>
<td>false</td>
<td>dbo</td>
</tr>
</table>
<h2>EXAMPLE 1</h2>
<pre><code>Rename-Index -TableName 'FooBar' -Name 'IX_Fizz' -NewName 'Buzz'</code></pre>
<p>Changes the name of the <code>Fizz</code> index on the <code>FooBar</code> table to <code>Buzz</code>.</p>
<h2>EXAMPLE 2</h2>
<pre><code>Rename-Index -SchemaName 'fizz' -TableName 'FooBar' -Name 'IX_Buzz' -NewName 'Fizz'</code></pre>
<p>Demonstrates how to rename an index on a table that is in a schema other than <code>dbo</code>.</p>
<h2>EXAMPLE 3</h2>
<pre><code>Rename-Index 'FooBar' 'IX_Fizz' 'Buzz'</code></pre>
<p>Demonstrates how to use the short form to rename the <code>Fizz</code> index on the <code>FooBar</code> table to <code>Buzz</code>: table name is first, then existing index name, then new index name.</p>
<div class="Footer">
Copyright 2013 - 2016 <a href="http://pshdo.com">Aaron Jensen</a>.
</div>
</body>
</html>
| RivetDB/Rivet | Website/Rename-Index.html | HTML | apache-2.0 | 3,921 |
$.FAQ = function(){
$self = this;
this.url = "/faq"
this.send = function(inputs){
var params = new FormData();
// var csrf = $("#csrf").val();
// params.append("csrf_ID", csrf);
$.each(inputs, function(key, val){
params.append(key,val);
});
$.ajax({
url : $self.url,
type: 'POST',
async: true,
processData: false,
data: params,
success: function(response){
response = JSON.parse(response);
$self.fillQAs(response.qadata);
$self.createPagination(response.metadata)
},
});
};
this.fillQAs = function(data){
var qaBox = $("#faq-container .faq-item").clone();
$("#faq-container .faq-item").remove();
$.each(data, function(obj){
var $div = qaBox.clone();
$div.find(".faq-item-question h2").html(obj.question);
$div.find(".faq-item-answer p").html(obj.answer);
});
};
this.createPagination = function(metadata){
};
this.load = function(data){
var limit = (data.limit > 0) ? data.limit : 5;
var offset = (data.page_num - 1)*limit;
var inputs = {
action : 'loadFaq',
limit : limit,
offset : offset
};
$self.send(inputs);
};
this.init = function(){
var inputs = {
limit : 5,
page_num : 1
};
$self.load(inputs);
};
};
| ajaykiet2/htdocs | assets/js/website/faq.js | JavaScript | apache-2.0 | 1,284 |
# Lasiosphaeriopsis cephalodiorum (Rostr.) Alstrup SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
in Alstrup, Christensen, Hansen & Svane, Fródskaparrit, Annales Societatis Scientiarium Færoensis 40: 92 (1994)
#### Original name
Sphaeria cephalodiorum Rostr.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Coronophorales/Lasiosphaeriopsis/Lasiosphaeriopsis cephalodiorum/README.md | Markdown | apache-2.0 | 315 |
# Doritis pulcherrima f. pulcherrima FORM
#### Status
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Phalaenopsis/Phalaenopsis pulcherrima/Doritis pulcherrima pulcherrima/README.md | Markdown | apache-2.0 | 173 |
# Splanchnonema quinqueseptatum (M.E. Barr) Aptroot, 1998 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Nova Hedwigia 66(1-2): 154 (1998)
#### Original name
Massarina quinqueseptata M.E. Barr, 1992
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Metacapnodiaceae/Metacapnodium/Metacapnodium quinqueseptatum/ Syn. Splanchnonema quinqueseptatum/README.md | Markdown | apache-2.0 | 277 |
/**
* Copyright 2011-2017 Asakusa Framework Team.
*
* 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.
*/
package com.asakusafw.testdriver.rule;
import java.math.BigDecimal;
import java.text.MessageFormat;
/**
* Accepts iff actual decimal is in [ expected + lower-bound, expected + upper-bound ].
* @since 0.2.0
*/
public class DecimalRange implements ValuePredicate<BigDecimal> {
private final BigDecimal lowerBound;
private final BigDecimal upperBound;
/**
* Creates a new instance.
* @param lowerBound lower bound offset from expected value
* @param upperBound upper bound offset from expected value
*/
public DecimalRange(BigDecimal lowerBound, BigDecimal upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
@Override
public boolean accepts(BigDecimal expected, BigDecimal actual) {
if (expected == null || actual == null) {
throw new IllegalArgumentException();
}
return expected.add(lowerBound).compareTo(actual) <= 0
&& actual.compareTo(expected.add(upperBound)) <= 0;
}
@Override
public String describeExpected(BigDecimal expected, BigDecimal actual) {
if (expected == null) {
return "(error)"; //$NON-NLS-1$
}
return MessageFormat.format(
"{0} ~ {1}", //$NON-NLS-1$
Util.format(expected.add(lowerBound)),
Util.format(expected.add(upperBound)));
}
}
| cocoatomo/asakusafw | testing-project/asakusa-test-moderator/src/main/java/com/asakusafw/testdriver/rule/DecimalRange.java | Java | apache-2.0 | 2,011 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.sasl.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
;
import org.wildfly.common.Assert;
import org.wildfly.security.auth.callback.ServerCredentialCallback;
import org.wildfly.security.credential.Credential;
/**
* A {@link SaslServerFactory} which sets the server's credential.
*
* @author <a href="mailto:[email protected]">Farah Juma</a>
*/
public final class CredentialSaslServerFactory extends AbstractDelegatingSaslServerFactory {
private final Credential credential;
/**
* Construct a new instance.
*
* @param delegate the delegate SASL server factory
* @param credential the server credential to use
*/
public CredentialSaslServerFactory(final SaslServerFactory delegate, final Credential credential) {
super(delegate);
Assert.checkNotNullParam("credential", credential);
this.credential = credential;
}
public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler cbh) throws SaslException {
return delegate.createSaslServer(mechanism, protocol, serverName, props, callbacks -> {
ArrayList<Callback> list = new ArrayList<>(Arrays.asList(callbacks));
final Iterator<Callback> iterator = list.iterator();
while (iterator.hasNext()) {
Callback callback = iterator.next();
if (callback instanceof ServerCredentialCallback) {
final ServerCredentialCallback credentialCallback = (ServerCredentialCallback) callback;
if (credentialCallback.isCredentialSupported(credential)) {
credentialCallback.setCredential(credential);
iterator.remove();
}
}
}
if (!list.isEmpty()) {
cbh.handle(list.toArray(new Callback[list.size()]));
}
});
}
}
| sguilhen/wildfly-elytron | src/main/java/org/wildfly/security/sasl/util/CredentialSaslServerFactory.java | Java | apache-2.0 | 2,996 |
<!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 (version 1.7.0_79) on Sat Jan 09 21:52:40 PST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.core.ObjectCodec (Jackson-core 2.7.0 API)</title>
<meta name="date" content="2016-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.core.ObjectCodec (Jackson-core 2.7.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/core/class-use/ObjectCodec.html" target="_top">Frames</a></li>
<li><a href="ObjectCodec.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">
<h2 title="Uses of Class com.fasterxml.jackson.core.ObjectCodec" class="title">Uses of Class<br>com.fasterxml.jackson.core.ObjectCodec</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core">com.fasterxml.jackson.core</a></td>
<td class="colLast">
<div class="block">Main public API classes of the core streaming JSON
processor: most importantly <a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core"><code>JsonFactory</code></a>
used for constructing
JSON parser (<a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core"><code>JsonParser</code></a>)
and generator
(<a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core"><code>JsonGenerator</code></a>)
instances.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core.base">com.fasterxml.jackson.core.base</a></td>
<td class="colLast">
<div class="block">Base classes used by concrete Parser and Generator implementations;
contain functionality that is not specific to JSON or input
abstraction (byte vs char).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core.json">com.fasterxml.jackson.core.json</a></td>
<td class="colLast">
<div class="block">JSON-specific parser and generator implementation classes that
Jackson defines and uses.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.core.util">com.fasterxml.jackson.core.util</a></td>
<td class="colLast">
<div class="block">Utility classes used by Jackson Core functionality.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.core">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#_objectCodec">_objectCodec</a></strong></code>
<div class="block">Object that implements conversion functionality between
Java objects and JSON content.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#_codec()">_codec</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#getCodec()">getCodec</a></strong>()</code>
<div class="block">Accessor for <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> associated with this
parser, if any.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonGenerator.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#getCodec()">getCodec</a></strong>()</code>
<div class="block">Method for accessing the object used for writing Java
object as JSON content
(using method <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#writeObject(java.lang.Object)"><code>JsonGenerator.writeObject(java.lang.Object)</code></a>).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> c)</code>
<div class="block">Setter that allows defining <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> associated with this
parser, if any.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td>
<td class="colLast"><span class="strong">JsonGenerator.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> oc)</code>
<div class="block">Method that can be called to set or reset the object to
use for writing Java objects as JsonContent
(using method <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#writeObject(java.lang.Object)"><code>JsonGenerator.writeObject(java.lang.Object)</code></a>).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core">JsonFactory</a></code></td>
<td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> oc)</code>
<div class="block">Method for associating a <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> (typically
a <code>com.fasterxml.jackson.databind.ObjectMapper</code>)
with this factory (and more importantly, parsers and generators
it constructs).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core">JsonParser</a></code></td>
<td class="colLast"><span class="strong">TreeNode.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/TreeNode.html#traverse(com.fasterxml.jackson.core.ObjectCodec)">traverse</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec)</code>
<div class="block">Same as <a href="../../../../../com/fasterxml/jackson/core/TreeNode.html#traverse()"><code>TreeNode.traverse()</code></a>, but additionally passes <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a>
to use if <a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#readValueAs(java.lang.Class)"><code>JsonParser.readValueAs(Class)</code></a> is used (otherwise caller must call
<a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)"><code>JsonParser.setCodec(com.fasterxml.jackson.core.ObjectCodec)</code></a> on response explicitly).</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#JsonFactory(com.fasterxml.jackson.core.JsonFactory,%20com.fasterxml.jackson.core.ObjectCodec)">JsonFactory</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core">JsonFactory</a> src,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec)</code>
<div class="block">Constructor used when copy()ing a factory instance.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#JsonFactory(com.fasterxml.jackson.core.ObjectCodec)">JsonFactory</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> oc)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.core.base">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#_objectCodec">_objectCodec</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td>
<td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> oc)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#GeneratorBase(int,%20com.fasterxml.jackson.core.ObjectCodec)">GeneratorBase</a></strong>(int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec)</code> </td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#GeneratorBase(int,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.json.JsonWriteContext)">GeneratorBase</a></strong>(int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="../../../../../com/fasterxml/jackson/core/json/JsonWriteContext.html" title="class in com.fasterxml.jackson.core.json">JsonWriteContext</a> ctxt)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.core.json">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#_objectCodec">_objectCodec</a></strong></code>
<div class="block">Codec used for data binding when (if) requested; typically full
<code>ObjectMapper</code>, but that abstract is not part of core
package.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#_objectCodec">_objectCodec</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core">JsonParser</a></code></td>
<td class="colLast"><span class="strong">ByteSourceJsonBootstrapper.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ByteSourceJsonBootstrapper.html#constructParser(int,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer,%20int)">constructParser</a></strong>(int parserFeatures,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="../../../../../com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">ByteQuadsCanonicalizer</a> rootByteSymbols,
<a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a> rootCharSymbols,
int factoryFeatures)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> c)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> c)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/JsonGeneratorImpl.html#JsonGeneratorImpl(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec)">JsonGeneratorImpl</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec)</code> </td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#ReaderBasedJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.Reader,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer)">ReaderBasedJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</a> r,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a> st)</code>
<div class="block">Method called when input comes as a <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io"><code>Reader</code></a>, and buffer allocation
can be done using default mechanism.</div>
</td>
</tr>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#ReaderBasedJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.Reader,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer,%20char[],%20int,%20int,%20boolean)">ReaderBasedJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</a> r,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a> st,
char[] inputBuffer,
int start,
int end,
boolean bufferRecyclable)</code>
<div class="block">Method called when caller wants to provide input buffer directly,
and it may or may not be recyclable use standard recycle context.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8JsonGenerator.html#UTF8JsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.OutputStream)">UTF8JsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</a> out)</code> </td>
</tr>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8JsonGenerator.html#UTF8JsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.OutputStream,%20byte[],%20int,%20boolean)">UTF8JsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</a> out,
byte[] outputBuffer,
int outputOffset,
boolean bufferRecyclable)</code> </td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#UTF8StreamJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.InputStream,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer,%20byte[],%20int,%20int,%20boolean)">UTF8StreamJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html?is-external=true" title="class or interface in java.io">InputStream</a> in,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="../../../../../com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">ByteQuadsCanonicalizer</a> sym,
byte[] inputBuffer,
int start,
int end,
boolean bufferRecyclable)</code> </td>
</tr>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/WriterBasedJsonGenerator.html#WriterBasedJsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.Writer)">WriterBasedJsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a> ctxt,
int features,
<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> codec,
<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Writer.html?is-external=true" title="class or interface in java.io">Writer</a> w)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.core.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonParserDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonParserDelegate.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td>
<td class="colLast"><span class="strong">JsonGeneratorDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonGeneratorDelegate.html#getCodec()">getCodec</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JsonParserDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonParserDelegate.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> c)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td>
<td class="colLast"><span class="strong">JsonGeneratorDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonGeneratorDelegate.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> oc)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/fasterxml/jackson/core/class-use/ObjectCodec.html" target="_top">Frames</a></li>
<li><a href="ObjectCodec.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 © 2008-2016 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p>
</body>
</html>
| FasterXML/jackson-core | docs/javadoc/2.7/com/fasterxml/jackson/core/class-use/ObjectCodec.html | HTML | apache-2.0 | 39,223 |
package com.board;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class BoardDAO {
private Connection conn;
public BoardDAO(Connection conn){
this.conn = conn;
}
//1. num의 최대값
public int getMaxNum(){
int maxNum = 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
sql = "select nvl(max(num),0) from board";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
maxNum = rs.getInt(1);
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return maxNum;
}
// 입력(created.jsp -> created_ok.jsp)
public int insertData(BoardForm dto){
int result = 0;
/*
PreparedStatement pstmt = null;
StringBuffer sql = new StringBuffer();
*/
PreparedStatement pstmt = null;
String sql;
try {
/*
sql.append("insert into board");
sql.append("(num, name, pwd, email, subject, content,");
*/
sql = "insert into board" +
"(num, name, pwd, email, subject, content," +
"ipAddr, hitCount, created) " +
"values(?, ?, ?, ?, ?, ?, ?, 0, sysdate)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, dto.getNum());
pstmt.setString(2, dto.getName());
pstmt.setString(3, dto.getPwd());
pstmt.setString(4, dto.getEmail());
pstmt.setString(5, dto.getSubject());
pstmt.setString(6, dto.getContent());
pstmt.setString(7, dto.getIpAddr());
result = pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
System.out.println("# insertData");
System.out.println(e.toString());
}
return result;
}
// 전체데이터 가지고 올거야
public List<BoardForm> getList(int start, int end){
List<BoardForm> lists = new ArrayList<BoardForm>();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
sql = "select * from (";
sql += "select rownum rnum,data.* " +
" from (select num,name,subject,hitCount," +
" to_char(created, 'YYYY-MM-DD') created" +
" from board order by num desc) data )" +
" where rnum >= ? and rnum <= ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, start);
pstmt.setInt(2, end);
rs = pstmt.executeQuery();
while(rs.next()){
BoardForm dto = new BoardForm();
dto.setNum(rs.getInt(2));
dto.setName(rs.getString(3));
dto.setSubject(rs.getString(4));
dto.setHitCount(rs.getInt(5));
dto.setCreated(rs.getString(6));
lists.add(dto);
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return lists;
}
//전체 데이터수 구하기
public int getDataCount(){
int result= 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
sql = "select nvl(count(*),0) from board";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
result = rs.getInt(1);
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
//조회수증가
public int updateHitCount(int num){
int result = 0;
PreparedStatement pstmt = null;
String sql;
try {
sql = "update board set hitCount=hitCount+1 where num=?" ;
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
result = pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
// 한명의 데이터 출력
public BoardForm getReadData(int num){
BoardForm dto = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
// 제목, 작성자, 줄수, 등록일, 조회수, 내용, ip주소
sql = "select num, name, pwd, email, subject, content, ipaddr, created, hitCount " +
"from board where num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()){
dto = new BoardForm();
dto.setNum(rs.getInt("num"));
dto.setName(rs.getString("name"));
dto.setPwd(rs.getString("pwd"));
dto.setEmail(rs.getString("email"));
dto.setSubject(rs.getString("subject"));
dto.setContent(rs.getString("content"));
dto.setIpAddr(rs.getString("ipAddr"));
dto.setHitCount(rs.getInt("hitCount"));
dto.setCreated(rs.getString("created"));
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return dto;
}
// 삭제
public int deleteData(int num){
int result = 0;
PreparedStatement pstmt = null;
String sql;
try {
sql = "delete board where num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
result = pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
// 수정
public int updateData(BoardForm dto){
int result = 0;
PreparedStatement pstmt = null;
String sql;
try {
sql = "update board set name=?, pwd=?, subject=?, content=?, email=? where num=? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getName());
pstmt.setString(2, dto.getPwd());
pstmt.setString(3, dto.getSubject());
pstmt.setString(4, dto.getContent());
pstmt.setString(5, dto.getEmail());
pstmt.setInt(6, dto.getNum());
result = pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
//검색된 데이터수 구하기
public int getDataCount(String searchKey, String searchValue){
int result= 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
searchValue = "%" + searchValue + "%";
sql = "select nvl(count(*),0) from board where "+searchKey + " like ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchValue);
rs = pstmt.executeQuery();
if(rs.next()){
result = rs.getInt(1);
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
// 검색데이터 가지고 올거야
public List<BoardForm> getList(int start, int end, String searchKey, String searchValue){
List<BoardForm> lists = new ArrayList<BoardForm>();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
searchValue = "%" + searchValue + "%";
sql = "select * from (";
sql += "select rownum rnum,data.* " +
" from (select num,name,subject,hitCount," +
" to_char(created, 'YYYY-MM-DD') created" +
" from board where "+searchKey + " like ? order by num desc) data )" +
" where rnum >= ? and rnum <= ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchValue);
pstmt.setInt(2, start);
pstmt.setInt(3, end);
rs = pstmt.executeQuery();
while(rs.next()){
BoardForm dto = new BoardForm();
dto.setNum(rs.getInt(2));
dto.setName(rs.getString(3));
dto.setSubject(rs.getString(4));
dto.setHitCount(rs.getInt(5));
dto.setCreated(rs.getString(6));
lists.add(dto);
}
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return lists;
}
}
/////////////////
| xerato/vk-study | src/com/board/BoardDAO.java | Java | apache-2.0 | 7,784 |
<html>
<head>
</head>
<body>
testf
</body>
</html>
| matthellwinkel/matthellwinkel.github.io | index.html | HTML | apache-2.0 | 51 |
/*
* Copyright 2016 the original author or authors.
*
* 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.
*/
package com.github.antennaesdk.common.messages;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* <code>ServerRestMessage</code> carries a REST api call to the mobile-broker.
* Broker executes this call, and returns the result via <code>ClientMessage</code>.
*
* @see ClientMessage
*/
public class ServerRestMessage {
// from where the message originates.
// it can be from a user or from a server (bot)
private ClientAddress from;
// rest resource path such as "/api/books"
// another example would be "/api/books?id=383763"
// another example would be "/api/books/383763"
private String path;
// represents the "protocol//host:port" such as "https://toys.company.com:8443"
// or port can be optional such as "https://toys.company.com"
private String host;
// represents REST method such as "GET", "POST", "PUT", "DELETE" etc
// TODO: use an enum instead of string
private String method;
// actual message ( this the payload if its POST/PUT call )
// this is optional
private String payLoad;
// the headers for a REST message
private Map<String, String> headers = new HashMap<>();
// The name/value pairs of multipart entities. Implies a multipart request.
private Map<String, String> multipartEntities;
// unique identified to track the request on the client side.
private String requestId;
// TODO: use TypeAdapterFactory instead of passing the type.
private String classType = ServerRestMessage.class.getName();
// getters and setters
public ServerRestMessage(){
requestId = UUID.randomUUID().toString();
}
public ServerRestMessage( String requestId ){
this.requestId = requestId;
}
public ClientAddress getFrom() {
return from;
}
public void setFrom(ClientAddress from) {
this.from = from;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPayLoad() {
return payLoad;
}
public void setPayLoad(String payLoad) {
this.payLoad = payLoad;
}
public Map<String, String> getHeaders() { return headers; }
public void setHeaders(Map<String, String> headers) { this.headers = headers; }
public void setMultipartEntities(Map<String, String> multipartEntities) { this.multipartEntities = multipartEntities; }
public Map<String, String> getMultipartEntities() { return multipartEntities; }
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
// utility methods
public String toJson(){
Gson gson = new Gson();
String json = gson.toJson(this);
return json;
}
public String toJsonPretty(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(this);
return json;
}
public static ServerRestMessage fromJson(String json ){
Gson gson = new Gson();
ServerRestMessage result = gson.fromJson( json, ServerRestMessage.class);
return result;
}
}
| AntennaeSDK/MMS | client-api/src/main/java/com/github/antennaesdk/common/messages/ServerRestMessage.java | Java | apache-2.0 | 4,171 |
<!--
$Id: package.html 35201 2011-07-22 14:58:48Z juergens $
@version $Rev: 35201 $
@ConQAT.Rating GREEN Hash: 92C5B8CDC35E818F72E381EA1A7E7CBE
-->
<body>
Processors and nodes for analyzing ConQAT itself.
</body>
| vimaier/conqat | org.conqat.engine.self/src/org/conqat/engine/self/package.html | HTML | apache-2.0 | 224 |
package io.quarkus.it.spring.data.jpa;
import java.io.Serializable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface IntermediateRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
default public void doNothing() {
}
default public T findMandatoryById(ID id) {
return findById(id).orElseThrow(() -> new IllegalStateException("not found: " + id));
}
}
| quarkusio/quarkus | integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/IntermediateRepository.java | Java | apache-2.0 | 508 |
/*
* Copyright 2016 The Error Prone Authors.
*
* 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.
*/
package com.google.errorprone.bugpatterns.threadsafety;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.ImmutableTypeParameter;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Purpose;
import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeKind;
/** Analyzes types for deep immutability. */
public class ImmutableAnalysis {
private final BugChecker bugChecker;
private final VisitorState state;
private final WellKnownMutability wellKnownMutability;
private final ThreadSafety threadSafety;
ImmutableAnalysis(
BugChecker bugChecker,
VisitorState state,
WellKnownMutability wellKnownMutability,
ImmutableSet<String> immutableAnnotations) {
this.bugChecker = bugChecker;
this.state = state;
this.wellKnownMutability = wellKnownMutability;
this.threadSafety =
ThreadSafety.builder()
.setPurpose(Purpose.FOR_IMMUTABLE_CHECKER)
.knownTypes(wellKnownMutability)
.markerAnnotations(immutableAnnotations)
.typeParameterAnnotation(ImmutableTypeParameter.class)
.build(state);
}
public ImmutableAnalysis(
BugChecker bugChecker, VisitorState state, WellKnownMutability wellKnownMutability) {
this(bugChecker, state, wellKnownMutability, ImmutableSet.of(Immutable.class.getName()));
}
Violation isThreadSafeType(
boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) {
return threadSafety.isThreadSafeType(
allowContainerTypeParameters, containerTypeParameters, type);
}
boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol sym) {
return threadSafety.hasThreadSafeTypeParameterAnnotation(sym);
}
Violation checkInstantiation(
Collection<TypeVariableSymbol> classTypeParameters, Collection<Type> typeArguments) {
return threadSafety.checkInstantiation(classTypeParameters, typeArguments);
}
public Violation checkInvocation(Type methodType, Symbol symbol) {
return threadSafety.checkInvocation(methodType, symbol);
}
/** Accepts {@link Violation violations} that are found during the analysis. */
@FunctionalInterface
public interface ViolationReporter {
Description.Builder describe(Tree tree, Violation info);
@CheckReturnValue
default Description report(Tree tree, Violation info, Optional<SuggestedFix> suggestedFix) {
Description.Builder description = describe(tree, info);
suggestedFix.ifPresent(description::addFix);
return description.build();
}
}
/**
* Check that an {@code @Immutable}-annotated class:
*
* <ul>
* <li>does not declare or inherit any mutable fields,
* <li>any immutable supertypes are instantiated with immutable type arguments as required by
* their containerOf spec, and
* <li>any enclosing instances are immutable.
* </ul>
*
* requiring supertypes to be annotated immutable would be too restrictive.
*/
public Violation checkForImmutability(
Optional<ClassTree> tree,
ImmutableSet<String> immutableTyParams,
ClassType type,
ViolationReporter reporter) {
Violation info = areFieldsImmutable(tree, immutableTyParams, type, reporter);
if (info.isPresent()) {
return info;
}
for (Type interfaceType : state.getTypes().interfaces(type)) {
AnnotationInfo interfaceAnnotation = getImmutableAnnotation(interfaceType.tsym, state);
if (interfaceAnnotation == null) {
continue;
}
info =
threadSafety.checkSuperInstantiation(
immutableTyParams, interfaceAnnotation, interfaceType);
if (info.isPresent()) {
return info.plus(
String.format(
"'%s' extends '%s'",
threadSafety.getPrettyName(type.tsym),
threadSafety.getPrettyName(interfaceType.tsym)));
}
}
if (!type.asElement().isEnum()) {
// don't check enum super types here to avoid double-reporting errors
info = checkSuper(immutableTyParams, type);
if (info.isPresent()) {
return info;
}
}
Type mutableEnclosing = threadSafety.mutableEnclosingInstance(tree, type);
if (mutableEnclosing != null) {
return info.plus(
String.format(
"'%s' has mutable enclosing instance '%s'",
threadSafety.getPrettyName(type.tsym), mutableEnclosing));
}
return Violation.absent();
}
private Violation checkSuper(ImmutableSet<String> immutableTyParams, ClassType type) {
ClassType superType = (ClassType) state.getTypes().supertype(type);
if (superType.getKind() == TypeKind.NONE
|| state.getTypes().isSameType(state.getSymtab().objectType, superType)) {
return Violation.absent();
}
if (WellKnownMutability.isAnnotation(state, type)) {
// TODO(b/25630189): add enforcement
return Violation.absent();
}
AnnotationInfo superannotation = getImmutableAnnotation(superType.tsym, state);
String message =
String.format(
"'%s' extends '%s'",
threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(superType.tsym));
if (superannotation != null) {
// If the superclass does happen to be immutable, we don't need to recursively
// inspect it. We just have to check that it's instantiated correctly:
Violation info =
threadSafety.checkSuperInstantiation(immutableTyParams, superannotation, superType);
if (!info.isPresent()) {
return Violation.absent();
}
return info.plus(message);
}
// Recursive case: check if the supertype is 'effectively' immutable.
Violation info =
checkForImmutability(
Optional.<ClassTree>empty(),
immutableTyParams,
superType,
new ViolationReporter() {
@Override
public Description.Builder describe(Tree tree, Violation info) {
return bugChecker
.buildDescription(tree)
.setMessage(info.plus(info.message()).message());
}
});
if (!info.isPresent()) {
return Violation.absent();
}
return info.plus(message);
}
/**
* Check a single class' fields for immutability.
*
* @param immutableTyParams the in-scope immutable type parameters
* @param classType the type to check the fields of
*/
Violation areFieldsImmutable(
Optional<ClassTree> tree,
ImmutableSet<String> immutableTyParams,
ClassType classType,
ViolationReporter reporter) {
ClassSymbol classSym = (ClassSymbol) classType.tsym;
if (classSym.members() == null) {
return Violation.absent();
}
Predicate<Symbol> instanceFieldFilter =
symbol -> symbol.getKind() == ElementKind.FIELD && !symbol.isStatic();
Map<Symbol, Tree> declarations = new HashMap<>();
if (tree.isPresent()) {
for (Tree member : tree.get().getMembers()) {
Symbol sym = ASTHelpers.getSymbol(member);
if (sym != null) {
declarations.put(sym, member);
}
}
}
// javac gives us members in reverse declaration order
// handling them in declaration order leads to marginally better diagnostics
List<Symbol> members =
ImmutableList.copyOf(ASTHelpers.scope(classSym.members()).getSymbols(instanceFieldFilter))
.reverse();
for (Symbol member : members) {
Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member));
Violation info =
isFieldImmutable(
memberTree, immutableTyParams, classSym, classType, (VarSymbol) member, reporter);
if (info.isPresent()) {
return info;
}
}
return Violation.absent();
}
/** Check a single field for immutability. */
private Violation isFieldImmutable(
Optional<Tree> tree,
ImmutableSet<String> immutableTyParams,
ClassSymbol classSym,
ClassType classType,
VarSymbol var,
ViolationReporter reporter) {
if (bugChecker.isSuppressed(var)) {
return Violation.absent();
}
if (!var.getModifiers().contains(Modifier.FINAL)
&& !ASTHelpers.hasAnnotation(var, LazyInit.class, state)) {
Violation info =
Violation.of(
String.format(
"'%s' has non-final field '%s'",
threadSafety.getPrettyName(classSym), var.getSimpleName()));
if (tree.isPresent()) {
// If we have a tree to attach diagnostics to, report the error immediately instead of
// accumulating the path to the error from the top-level class being checked
state.reportMatch(
reporter.report(
tree.get(), info, SuggestedFixes.addModifiers(tree.get(), state, Modifier.FINAL)));
return Violation.absent();
}
return info;
}
Type varType = state.getTypes().memberType(classType, var);
Violation info =
threadSafety.isThreadSafeType(
/* allowContainerTypeParameters= */ true, immutableTyParams, varType);
if (info.isPresent()) {
info =
info.plus(
String.format(
"'%s' has field '%s' of type '%s'",
threadSafety.getPrettyName(classSym), var.getSimpleName(), varType));
if (tree.isPresent()) {
// If we have a tree to attach diagnostics to, report the error immediately instead of
// accumulating the path to the error from the top-level class being checked
state.reportMatch(reporter.report(tree.get(), info, Optional.empty()));
return Violation.absent();
}
return info;
}
return Violation.absent();
}
/**
* Gets the {@link Symbol}'s {@code @Immutable} annotation info, either from an annotation on the
* symbol or from the list of well-known immutable types.
*/
AnnotationInfo getImmutableAnnotation(Symbol sym, VisitorState state) {
String nameStr = sym.flatName().toString();
AnnotationInfo known = wellKnownMutability.getKnownImmutableClasses().get(nameStr);
if (known != null) {
return known;
}
return threadSafety.getInheritedAnnotation(sym, state);
}
/**
* Gets the {@link Tree}'s {@code @Immutable} annotation info, either from an annotation on the
* symbol or from the list of well-known immutable types.
*/
AnnotationInfo getImmutableAnnotation(Tree tree, VisitorState state) {
Symbol sym = ASTHelpers.getSymbol(tree);
return sym == null ? null : threadSafety.getMarkerOrAcceptedAnnotation(sym, state);
}
}
| cushon/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnalysis.java | Java | apache-2.0 | 12,491 |
package com.planet_ink.coffee_mud.Abilities.Songs;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
public class Play_Organs extends Play_Instrument
{
@Override public String ID() { return "Play_Organs"; }
private final static String localizedName = CMLib.lang()._("Organs");
@Override public String name() { return localizedName; }
@Override protected int requiredInstrumentType(){return MusicalInstrument.TYPE_ORGANS;}
@Override public String mimicSpell(){return "Prayer_ProtectHealth";}
@Override protected int canAffectCode(){return 0;}
private static Ability theSpell=null;
@Override
protected Ability getSpell()
{
if(theSpell!=null) return theSpell;
if(mimicSpell().length()==0) return null;
theSpell=CMClass.getAbility(mimicSpell());
return theSpell;
}
}
| vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Abilities/Songs/Play_Organs.java | Java | apache-2.0 | 2,094 |
/**
* 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.
*/
package org.apache.bookkeeper.mledger;
public class ManagedLedgerFactoryConfig {
private static final long MB = 1024 * 1024;
private long maxCacheSize = 128 * MB;
private double cacheEvictionWatermark = 0.90;
public long getMaxCacheSize() {
return maxCacheSize;
}
/**
*
* @param maxCacheSize
* @return
*/
public ManagedLedgerFactoryConfig setMaxCacheSize(long maxCacheSize) {
this.maxCacheSize = maxCacheSize;
return this;
}
public double getCacheEvictionWatermark() {
return cacheEvictionWatermark;
}
/**
* The cache eviction watermark is the percentage of the cache size to reach when removing entries from the cache.
*
* @param cacheEvictionWatermark
* @return
*/
public ManagedLedgerFactoryConfig setCacheEvictionWatermark(double cacheEvictionWatermark) {
this.cacheEvictionWatermark = cacheEvictionWatermark;
return this;
}
}
| yush1ga/pulsar | managed-ledger/src/main/java/org/apache/bookkeeper/mledger/ManagedLedgerFactoryConfig.java | Java | apache-2.0 | 1,792 |
<!DOCTYPE html >
<html>
<head>
<title>Tables - ScalaTest 3.0.1 - org.scalatest.prop.Tables</title>
<meta name="description" content="Tables - ScalaTest 3.0.1 - org.scalatest.prop.Tables" />
<meta name="keywords" content="Tables ScalaTest 3.0.1 org.scalatest.prop.Tables" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../index.html';
var hash = 'org.scalatest.prop.Tables$';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="value">
<!-- Top of doc.scalatest.org [javascript] -->
<script type="text/javascript">
var rnd = window.rnd || Math.floor(Math.random()*10e6);
var pid204546 = window.pid204546 || rnd;
var plc204546 = window.plc204546 || 0;
var abkw = window.abkw || '';
var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER';
document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>');
</script>
<div id="definition">
<a href="Tables.html" title="See companion trait"><img alt="Object/Trait" src="../../../lib/object_to_trait_big.png" /></a>
<p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.prop">prop</a></p>
<h1><a href="Tables.html" title="See companion trait">Tables</a></h1><h3><span class="morelinks"><div>
Related Docs:
<a href="Tables.html" title="See companion trait">trait Tables</a>
| <a href="package.html" class="extype" name="org.scalatest.prop">package prop</a>
</div></span></h3><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">Tables</span><span class="result"> extends <a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object that facilitates the importing of <code>Tables</code> members as
an alternative to mixing it in. One use case is to import <code>Tables</code> members so you can use
them in the Scala interpreter:</p><p><pre>
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import org.scalatest.prop.Tables._
import org.scalatest.prop.Tables._
scala> val examples =
| Table(
| ("a", "b"),
| ( 1, 2),
| ( 3, 4)
| )
examples: org.scalatest.prop.TableFor2[Int,Int] = TableFor2((1,2), (3,4))
</pre>
</p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.1/scalatest//scala/gentables/Tables.scala" target="_blank">Tables.scala</a></dd></dl><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="org.scalatest.prop.Tables"><span>Tables</span></li><li class="in" name="org.scalatest.prop.Tables"><span>Tables</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@!=(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@##():Int" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@==(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="org.scalatest.prop.Tables.Table" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Table"></a>
<a id="Table:Table"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<a href="Tables$Table$.html"><span class="name">Table</span></a>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables@Table" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<p class="shortcomment cmt">Object containing one <code>apply</code> factory method for each <code>TableFor<n></code> class.</code></code></p><div class="fullcomment"><div class="comment cmt"><p>Object containing one <code>apply</code> factory method for each <code>TableFor<n></code> class.</p><p>For example, you could create a table of 5 rows and 2 colums like this:</p><p><pre class="stHighlighted">
<span class="stReserved">import</span> org.scalatest.prop.Tables._
<span class="stReserved">val</span> examples =
<span class="stType">Table</span>(
(<span class="stQuotedString">"a"</span>, <span class="stQuotedString">"b"</span>),
( <span class="stLiteral">1</span>, <span class="stLiteral">2</span>),
( <span class="stLiteral">2</span>, <span class="stLiteral">4</span>),
( <span class="stLiteral">4</span>, <span class="stLiteral">8</span>),
( <span class="stLiteral">8</span>, <span class="stLiteral">16</span>),
( <span class="stLiteral">16</span>, <span class="stLiteral">32</span>)
)
</pre></p><p>Because you supplied 2 members in each tuple, the type you'll get back will be a <code>TableFor2</code>. If
you wanted a table with just one column you could write this:</p><p><pre class="stHighlighted">
<span class="stReserved">val</span> moreExamples =
<span class="stType">Table</span>(
<span class="stQuotedString">"powerOfTwo"</span>,
<span class="stLiteral">1</span>,
<span class="stLiteral">2</span>,
<span class="stLiteral">4</span>,
<span class="stLiteral">8</span>,
<span class="stLiteral">16</span>
)
</pre></p><p>Or if you wanted a table with 10 columns and 10 rows, you could do this:</p><p><pre class="stHighlighted">
<span class="stReserved">val</span> multiplicationTable =
<span class="stType">Table</span>(
(<span class="stQuotedString">"a"</span>, <span class="stQuotedString">"b"</span>, <span class="stQuotedString">"c"</span>, <span class="stQuotedString">"d"</span>, <span class="stQuotedString">"e"</span>, <span class="stQuotedString">"f"</span>, <span class="stQuotedString">"g"</span>, <span class="stQuotedString">"h"</span>, <span class="stQuotedString">"i"</span>, <span class="stQuotedString">"j"</span>),
( <span class="stLiteral">1</span>, <span class="stLiteral">2</span>, <span class="stLiteral">3</span>, <span class="stLiteral">4</span>, <span class="stLiteral">5</span>, <span class="stLiteral">6</span>, <span class="stLiteral">7</span>, <span class="stLiteral">8</span>, <span class="stLiteral">9</span>, <span class="stLiteral">10</span>),
( <span class="stLiteral">2</span>, <span class="stLiteral">4</span>, <span class="stLiteral">6</span>, <span class="stLiteral">8</span>, <span class="stLiteral">10</span>, <span class="stLiteral">12</span>, <span class="stLiteral">14</span>, <span class="stLiteral">16</span>, <span class="stLiteral">18</span>, <span class="stLiteral">20</span>),
( <span class="stLiteral">3</span>, <span class="stLiteral">6</span>, <span class="stLiteral">9</span>, <span class="stLiteral">12</span>, <span class="stLiteral">15</span>, <span class="stLiteral">18</span>, <span class="stLiteral">21</span>, <span class="stLiteral">24</span>, <span class="stLiteral">27</span>, <span class="stLiteral">30</span>),
( <span class="stLiteral">4</span>, <span class="stLiteral">8</span>, <span class="stLiteral">12</span>, <span class="stLiteral">16</span>, <span class="stLiteral">20</span>, <span class="stLiteral">24</span>, <span class="stLiteral">28</span>, <span class="stLiteral">32</span>, <span class="stLiteral">36</span>, <span class="stLiteral">40</span>),
( <span class="stLiteral">5</span>, <span class="stLiteral">10</span>, <span class="stLiteral">15</span>, <span class="stLiteral">20</span>, <span class="stLiteral">25</span>, <span class="stLiteral">30</span>, <span class="stLiteral">35</span>, <span class="stLiteral">40</span>, <span class="stLiteral">45</span>, <span class="stLiteral">50</span>),
( <span class="stLiteral">6</span>, <span class="stLiteral">12</span>, <span class="stLiteral">18</span>, <span class="stLiteral">24</span>, <span class="stLiteral">30</span>, <span class="stLiteral">36</span>, <span class="stLiteral">42</span>, <span class="stLiteral">48</span>, <span class="stLiteral">54</span>, <span class="stLiteral">60</span>),
( <span class="stLiteral">7</span>, <span class="stLiteral">14</span>, <span class="stLiteral">21</span>, <span class="stLiteral">28</span>, <span class="stLiteral">35</span>, <span class="stLiteral">42</span>, <span class="stLiteral">49</span>, <span class="stLiteral">56</span>, <span class="stLiteral">63</span>, <span class="stLiteral">70</span>),
( <span class="stLiteral">8</span>, <span class="stLiteral">16</span>, <span class="stLiteral">24</span>, <span class="stLiteral">32</span>, <span class="stLiteral">40</span>, <span class="stLiteral">48</span>, <span class="stLiteral">56</span>, <span class="stLiteral">64</span>, <span class="stLiteral">72</span>, <span class="stLiteral">80</span>),
( <span class="stLiteral">9</span>, <span class="stLiteral">18</span>, <span class="stLiteral">27</span>, <span class="stLiteral">36</span>, <span class="stLiteral">45</span>, <span class="stLiteral">54</span>, <span class="stLiteral">63</span>, <span class="stLiteral">72</span>, <span class="stLiteral">81</span>, <span class="stLiteral">90</span>),
( <span class="stLiteral">10</span>, <span class="stLiteral">20</span>, <span class="stLiteral">30</span>, <span class="stLiteral">40</span>, <span class="stLiteral">50</span>, <span class="stLiteral">60</span>, <span class="stLiteral">70</span>, <span class="stLiteral">80</span>, <span class="stLiteral">90</span>, <span class="stLiteral">100</span>)
)
</pre></p><p>The type of <code>multiplicationTable</code> would be <code>TableFor10</code>. You can pass the resulting
tables to a <code>forAll</code> method (defined in trait <code>PropertyChecks</code>), to perform a property
check with the data in the table. Or, because tables are sequences of tuples, you can treat them as a <code>Seq</code>.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@asInstanceOf[T0]:T0" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@clone():Object" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@equals(x$1:Any):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@finalize():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@getClass():Class[_]" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@hashCode():Int" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@isInstanceOf[T0]:Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@notify():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@notifyAll():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@synchronized[T0](x$1:=>T0):T0" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@toString():String" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@wait():Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4><span class="permalink">
<a href="../../../index.html#org.scalatest.prop.Tables$@wait(x$1:Long):Unit" title="Permalink" target="_top">
<img src="../../../lib/permalink.png" alt="Permalink" />
</a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="org.scalatest.prop.Tables">
<h3>Inherited from <a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
| scalatest/scalatest-website | public/scaladoc/3.0.1/org/scalatest/prop/Tables$.html | HTML | apache-2.0 | 33,719 |
// Copyright 2016 Pikkpoiss
//
// 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.
package gamejam
type SceneID int
type Scene interface {
AddComponent(c Component)
Load(r Resources) (err error)
Unload(r Resources) (err error)
Render()
Update(mgr SceneManager)
SetSceneID(id SceneID)
SceneID() SceneID
}
type BaseScene struct {
components map[ComponentID]Component
id SceneID
}
func NewBaseScene() *BaseScene {
return &BaseScene{
components: map[ComponentID]Component{},
}
}
func (s *BaseScene) AddComponent(c Component) {
c.SetScene(s)
s.components[c.GetID()] = c
}
func (s *BaseScene) Load(r Resources) (err error) {
return
}
func (s *BaseScene) Render() {
}
func (s *BaseScene) SetSceneID(id SceneID) {
s.id = id
}
func (s *BaseScene) SceneID() SceneID {
return s.id
}
func (s *BaseScene) Unload(r Resources) (err error) {
var (
id ComponentID
c Component
)
for id, c = range s.components {
s.components[id] = nil
c.Delete()
}
//s.DeleteObservers()
return
}
func (s *BaseScene) Update(mgr SceneManager) {
}
| pikkpoiss/gamejam | v1/gamejam/scene.go | GO | apache-2.0 | 1,558 |
<!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 (version 1.7.0_55) on Sun Oct 26 05:56:34 EDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase (Solr 4.10.2 API)</title>
<meta name="date" content="2014-10-26">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase (Solr 4.10.2 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/FacetComponent.FacetBase.html" target="_top">Frames</a></li>
<li><a href="FacetComponent.FacetBase.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">
<h2 title="Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase" class="title">Uses of Class<br>org.apache.solr.handler.component.FacetComponent.FacetBase</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.solr.handler.component">org.apache.solr.handler.component</a></td>
<td class="colLast">
<div class="block">
<a href="../../../../../../org/apache/solr/handler/component/SearchComponent.html" title="class in org.apache.solr.handler.component"><code>SearchComponent</code></a> implementations for
use in <a href="../../../../../../org/apache/solr/handler/component/SearchHandler.html" title="class in org.apache.solr.handler.component"><code>SearchHandler</code></a></div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.handler.component">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a> in <a href="../../../../../../org/apache/solr/handler/component/package-summary.html">org.apache.solr.handler.component</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a> in <a href="../../../../../../org/apache/solr/handler/component/package-summary.html">org.apache.solr.handler.component</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.DistribFieldFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.DistribFieldFacet</a></strong></code>
<div class="block"><b>This API is experimental and subject to change</b></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FieldFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.FieldFacet</a></strong></code>
<div class="block"><b>This API is experimental and subject to change</b></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.QueryFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.QueryFacet</a></strong></code>
<div class="block"><b>This API is experimental and subject to change</b></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/PivotFacet.html" title="class in org.apache.solr.handler.component">PivotFacet</a></strong></code>
<div class="block">Models a single instance of a "pivot" specified by a <a href="../../../../../../../solr-solrj/org/apache/solr/common/params/FacetParams.html?is-external=true#FACET_PIVOT" title="class or interface in org.apache.solr.common.params"><code>FacetParams.FACET_PIVOT</code></a>
param, which may contain multiple nested fields.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/FacetComponent.FacetBase.html" target="_top">Frames</a></li>
<li><a href="FacetComponent.FacetBase.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>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| eissac/solr4sentiment | docs/solr-core/org/apache/solr/handler/component/class-use/FacetComponent.FacetBase.html | HTML | apache-2.0 | 8,992 |
package com.mygame;
import java.util.Vector;
import loon.geom.RectBox;
public class StepSwitch extends Switch
{
StepSwitch(int x, int y, Vector<Thing> blocks)
{
this.x = x;
this.y = y;
this.blocks = blocks;
orgblocks = new Vector<Thing>();
for(int i = 0; i < blocks.size(); i++)
orgblocks.add((Thing)blocks.get(i));
height = 50;
width = 50;
active = false;
col = new RectBox(x, y, width, height);
}
public void update(Player player, Vector<Thing> things)
{
boolean b = false;
for(int i = 0; i < things.size(); i++)
if(col.intersects((int)((Thing)things.get(i)).x, (int)((Thing)things.get(i)).y, ((Thing)things.get(i)).width, ((Thing)things.get(i)).height) && !b)
{
b = true;
active = true;
blocks.clear();
}
if(col.intersects((int)player.x, (int)player.y, player.width, player.height))
{
b = true;
active = true;
blocks.clear();
}
if(!b)
{
active = false;
if(blocks.isEmpty())
{
for(int i = 0; i < orgblocks.size(); i++)
blocks.add((Thing)orgblocks.get(i));
}
}
}
}
| cping/LGame | Java/Examples/arpggame(0.5)/src/com/mygame/StepSwitch.java | Java | apache-2.0 | 1,359 |
/*
* DateAxisBuilder.java
*
* Created on March 17, 2007, 10:17 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.thecoderscorner.groovychart.axis;
import java.beans.IntrospectionException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.thecoderscorner.groovychart.chart.Buildable;
import com.thecoderscorner.groovychart.chart.ChartBuilder;
import com.thecoderscorner.groovychart.chart.BeanBuilder;
import org.jfree.chart.axis.NumberAxis;
/**
*
* @author jclarke
*/
public class NumberAxisBuilder extends BeanBuilder implements Buildable{
private static final Logger logger = Logger.getLogger(NumberAxisBuilder.class.getPackage().getName());
private NumberAxis axis = new NumberAxis();
private boolean domain;
/**
* Creates a new instance of DateAxisBuilder
*/
public NumberAxisBuilder() {
try {
setBeanClass(NumberAxis.class);
} catch (IntrospectionException ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
public void setChartBuilder(ChartBuilder chartBuilder) {
}
public void processNode(Object name, Map map, Object value) throws Exception {
String method = name.toString();
if(value != null) {
this.axis = (NumberAxis)value;
}else {
if(logger.isLoggable(Level.FINEST))
logger.finest("processNode: method = " + method);
if(method.equalsIgnoreCase("NumberAxis")) {
this.setProperties(this.axis, map);
}
}
}
private Object parent;
public Object getParent() {
return parent;
}
public void setParent(Object parent) {
this.parent = parent;
}
public void nodeCompleted(Object parent) {
if(parent != null && parent instanceof AxisSettable) {
logger.finest("Setting axis on parent");
((AxisSettable)parent).setAxis(this.axis);
}
}
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public NumberAxis getAxis() {
return axis;
}
}
| davetcc/groovychart | src/main/java/com/thecoderscorner/groovychart/axis/NumberAxisBuilder.java | Java | apache-2.0 | 2,310 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.servicecatalog.model.transform;
import java.util.Map;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.servicecatalog.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateServiceActionRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateServiceActionRequestMarshaller {
private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Id").build();
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Name").build();
private static final MarshallingInfo<Map> DEFINITION_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Definition").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
private static final MarshallingInfo<String> ACCEPTLANGUAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AcceptLanguage").build();
private static final UpdateServiceActionRequestMarshaller instance = new UpdateServiceActionRequestMarshaller();
public static UpdateServiceActionRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateServiceActionRequest updateServiceActionRequest, ProtocolMarshaller protocolMarshaller) {
if (updateServiceActionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateServiceActionRequest.getId(), ID_BINDING);
protocolMarshaller.marshall(updateServiceActionRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(updateServiceActionRequest.getDefinition(), DEFINITION_BINDING);
protocolMarshaller.marshall(updateServiceActionRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(updateServiceActionRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/transform/UpdateServiceActionRequestMarshaller.java | Java | apache-2.0 | 3,346 |
#!/bin/bash
rm -rf php-5.3.29
if [ ! -f php-5.3.29.tar.gz ];then
wget http://zy-res.oss-cn-hangzhou.aliyuncs.com/php/php-5.3.29.tar.gz
fi
tar zxvf php-5.3.29.tar.gz
cd php-5.3.29
./configure --prefix=/alidata/server/php \
--with-config-file-path=/alidata/server/php/etc \
--with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--enable-fpm \
--enable-fastcgi \
--enable-static \
--enable-maintainer-zts \
--enable-zend-multibyte \
--enable-inline-optimization \
--enable-sockets \
--enable-wddx \
--enable-zip \
--enable-calendar \
--enable-bcmath \
--enable-soap \
--with-zlib \
--with-iconv \
--with-gd \
--with-xmlrpc \
--enable-mbstring \
--without-sqlite \
--with-curl \
--enable-ftp \
--with-mcrypt \
--with-freetype-dir=/usr/local/freetype.2.1.10 \
--with-jpeg-dir=/usr/local/jpeg.6 \
--with-png-dir=/usr/local/libpng.1.2.50 \
--disable-ipv6 \
--disable-debug \
--with-openssl \
--disable-maintainer-zts \
--disable-safe-mode \
--disable-fileinfo
CPU_NUM=$(cat /proc/cpuinfo | grep processor | wc -l)
if [ $CPU_NUM -gt 1 ];then
make ZEND_EXTRA_LIBS='-liconv' -j$CPU_NUM
else
make ZEND_EXTRA_LIBS='-liconv'
fi
make install
cd ..
cp ./php-5.3.29/php.ini-production /alidata/server/php/etc/php.ini
#adjust php.ini
sed -i 's#; extension_dir = \"\.\/\"#extension_dir = "/alidata/server/php/lib/php/extensions/no-debug-non-zts-20090626/"#' /alidata/server/php/etc/php.ini
sed -i 's/post_max_size = 8M/post_max_size = 64M/g' /alidata/server/php/etc/php.ini
sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 64M/g' /alidata/server/php/etc/php.ini
sed -i 's/;date.timezone =/date.timezone = PRC/g' /alidata/server/php/etc/php.ini
sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=1/g' /alidata/server/php/etc/php.ini
sed -i 's/max_execution_time = 30/max_execution_time = 300/g' /alidata/server/php/etc/php.ini
#adjust php-fpm
cp /alidata/server/php/etc/php-fpm.conf.default /alidata/server/php/etc/php-fpm.conf
sed -i 's,user = nobody,user=www,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,group = nobody,group=www,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,^pm.min_spare_servers = 1,pm.min_spare_servers = 5,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,^pm.max_spare_servers = 3,pm.max_spare_servers = 35,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,^pm.max_children = 5,pm.max_children = 100,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,^pm.start_servers = 2,pm.start_servers = 20,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,;pid = run/php-fpm.pid,pid = run/php-fpm.pid,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,;error_log = log/php-fpm.log,error_log = /alidata/log/php/php-fpm.log,g' /alidata/server/php/etc/php-fpm.conf
sed -i 's,;slowlog = log/$pool.log.slow,slowlog = /alidata/log/php/\$pool.log.slow,g' /alidata/server/php/etc/php-fpm.conf
#self start
install -v -m755 ./php-5.3.29/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
/etc/init.d/php-fpm start
sleep 5 | HollenMok/pandoraf_v1.0 | docs/linuxServer/linux_setup_1.4.3/sh-1.4.3/php/install_nginx_php-5.3.29.sh | Shell | apache-2.0 | 2,961 |
codeigniter
===========
| manuelblanch/codeigniter | README.md | Markdown | apache-2.0 | 24 |
#!/usr/bin/env bash
echo "STABLE_K8S_CLUSTER MyCluster"
echo 'COMPLEX_JSON { nested: { secret: "top" } }'
| bazelbuild/rules_jsonnet | tools/stamping/workspace_status.sh | Shell | apache-2.0 | 107 |
<pre style="word-wrap: break-word; white-space: pre-wrap;">
This corpus were recorded in silence in-door environment using cellphone. It has 10 speakers. Each speaker has about 350 utterances. All utterances were carefully transcribed and checked by human. Transcription accuracy is guaranteed. If there is any problems, we agree to correct them for you.
Please cite the data as “ST-AEDS-20180100_1, Free ST American English Corpus”.
The data set is a subset of a much bigger data set (about 1000hours) which was recorded in the same environment as this open source data. Please visit our website <a target="_Blank" href="https://www.surfing.ai/">www.surfing.ai</a> or contact us at [email protected] for details.
</pre>
| danpovey/openslr | resources/45/about.html | HTML | apache-2.0 | 741 |
$(document).ready(function(){
$('#datepickerDay1').hide();
$('#datepickerDay2').hide();
$('#datepickerMnd1').hide();
$('#datepickerMnd2').hide();
$('#datepickerYear1').hide();
$('#datepickerYear2').hide();
$('select').change(function(){
var index = $('select').val();
if(index == 0){ //day
$('#datepickerDay1').show();
$('#datepickerDay2').show();
$('#datepickerMnd1').hide();
$('#datepickerMnd2').hide();
$('#datepickerYear1').hide();
$('#datepickerYear2').hide();
localStorage.setItem('type','0');
}
else if(index == 1){ //month
$('#datepickerMnd1').show();
$('#datepickerMnd2').show();
$('#datepickerDay1').hide();
$('#datepickerDay2').hide();
$('#datepickerYear1').hide();
$('#datepickerYear2').hide();
localStorage.setItem('type','1');
}
else if(index == 2){ //year
$('#datepickerYear1').show();
$('#datepickerYear2').show();
$('#datepickerDay1').hide();
$('#datepickerDay2').hide();
$('#datepickerMnd1').hide();
$('#datepickerMnd2').hide();
localStorage.setItem('type','2');
}
});
$('#datepickerDay1').datepicker({
format: "yyyy-mm-dd",
weekStart: 1,
language: "no",
todayHighlight: true
});
$('#datepickerDay1').on('changeDate', function(ev){
$(this).datepicker('hide');
day1();
if ($('input[name=date2]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#datepickerDay2').datepicker({
format: "yyyy-mm-dd",
weekStart: 1,
language: "no",
todayHighlight: true
});
$('#datepickerDay2').on('changeDate', function(ev){
$(this).datepicker('hide');
day2();
if ($('input[name=date]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#datepickerYear1').datepicker({
format: "yyyy",
weekStart: 1,
startView: 1,
minViewMode: 2,
language: "no",
todayHighlight: true
});
$('#datepickerYear1').on('changeDate', function(ev){
$(this).datepicker('hide');
year1();
if ($('input[name=date6]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#datepickerYear2').datepicker({
format: "yyyy",
weekStart: 1,
startView: 1,
minViewMode: 2,
language: "no",
todayHighlight: true
});
$('#datepickerYear2').on('changeDate', function(ev){
$(this).datepicker('hide');
year2();
if ($('input[name=date5]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#datepickerMnd1').datepicker({
format: "yyyy-mm",
weekStart: 1,
startView: 0,
minViewMode: 1,
language: "no",
todayHighlight: true
});
$('#datepickerMnd1').on('changeDate', function(ev){
$(this).datepicker('hide');
mnd1();
if ($('input[name=date4]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#datepickerMnd2').datepicker({
format: "yyyy-mm",
weekStart: 1,
startView: 0,
minViewMode: 1,
language: "no",
todayHighlight: true
});
$('#datepickerMnd2').on('changeDate', function(ev){
$(this).datepicker('hide');
mnd2();
if ($('input[name=date3]').val() != "") {
showChart1();
showChart2();
showChart3();
showChart4();
showChart5();
showChart6();
}
});
$('#backBtn').on('click', function(ev){
window.location.replace("../pages/stats.php");
});
function day1(){
var day = $('input[name=date]').val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("firstDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true);
xmlhttp.send();
}
function day2(){
var day = $('input[name=date2]').val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("lastDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true);
xmlhttp.send();
}
function mnd1(){
var day = $('input[name=date3]').val() + '-01';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("firstDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true);
xmlhttp.send();
}
function mnd2(){
var day = $('input[name=date4]').val() + '-01';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("lastDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true);
xmlhttp.send();
}
function year1(){
var day = $('input[name=date5]').val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("firstDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true);
xmlhttp.send();
}
function year2(){
var day = $('input[name=date6]').val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("lastDate").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true);
xmlhttp.send();
}
function showChart1(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk1').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 1,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 1,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#followersFirstDate").text(res1);
$("#followersLastDate").text(res2);
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 2,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 2,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#followersFirstDate").text(res1);
$("#followersLastDate").text(res2);
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 3,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 3,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#followersFirstDate").text(res1);
$("#followersLastDate").text(res2);
},
});
},
});
}
}
function showChart2(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk2').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 4,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 4,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#donationsFirstDate").text(res1);
$("#donationsLastDate").text(res2);
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 5,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 5,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#donationsFirstDate").text(res1);
$("#donationsLastDate").text(res2);
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 6,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 6,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#donationsFirstDate").text(res1);
$("#donationsLastDate").text(res2);
},
});
},
});
}
}
function showChart3(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk3').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 7,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 7,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#moneyDonatedFirstDate").text(res1 + ",-");
$("#moneyDonatedLastDate").text(res2 + ",-");
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 8,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 8,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#moneyDonatedFirstDate").text(res1 + ",-");
$("#moneyDonatedLastDate").text(res2 + ",-");
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 9,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 9,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#moneyDonatedFirstDate").text(res1 + ",-");
$("#moneyDonatedLastDate").text(res2 + ",-");
},
});
},
});
}
}
function showChart4(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk4').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 10,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 10,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#averageDonationFirstDate").text(res1 + ",-");
$("#averageDonationLastDate").text(res2 + ",-");
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 11,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 11,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#averageDonationFirstDate").text(res1 + ",-");
$("#averageDonationLastDate").text(res2 + ",-");
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 12,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 12,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#averageDonationFirstDate").text(res1 + ",-");
$("#averageDonationLastDate").text(res2 + ",-");
},
});
},
});
}
}
function showChart5(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk5').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 13,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 13,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#newsFirstDate").text(res1);
$("#newsLastDate").text(res2);
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 14,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 14,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#newsFirstDate").text(res1);
$("#newsLastDate").text(res2);
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 15,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 15,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#newsFirstDate").text(res1);
$("#newsLastDate").text(res2);
},
});
},
});
}
}
function showChart6(){
var data = [
{
value: 1,
color:"#1AA24C",
highlight: "#1AD24C",
label: "Valg 2"
},
{
value: 1,
color: "#000000",
highlight: "#333333",
label: "Valg 1"
}
]
var ctx = $('#statistikk6').get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(data,{
animation:true,
showTooltips: true,
percentageInnerCutout : 0,
segmentShowStroke : true
});
var res1;
var res2;
var x = localStorage.getItem('type');
if(x == 0){ //day
var date1 = $('input[name=date]').val();
var date2 = $('input[name=date2]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 16,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 16,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#prosjectsFirstDate").text(res1);
$("#prosjectsLastDate").text(res2);
},
});
},
});
}else if(x == 1){ //month
var date1 = $('input[name=date3]').val() + '-01';
var date2 = $('input[name=date4]').val() + '-01';
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 17,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 17,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#prosjectsFirstDate").text(res1);
$("#prosjectsLastDate").text(res2);
},
});
},
});
}else if(x == 2){ //year
var date1 = $('input[name=date5]').val();
var date2 = $('input[name=date6]').val();
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 18,
success: function(data) {
res1 = parseInt(data);
$.ajax({
url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 18,
success: function(data) {
res2 = parseInt(data);
myDoughnut.segments[0].value = res2;
myDoughnut.segments[1].value = res1;
myDoughnut.update();
$("#prosjectsFirstDate").text(res1);
$("#prosjectsLastDate").text(res2);
},
});
},
});
}
}
}); | lavhmrps/SharityCRM | js/comparison.js | JavaScript | apache-2.0 | 25,646 |
/* The all pages that do not require authentication */
function UnAuthenticatedHandler() {
"use strict";
this.displayAboutPage = function(req, res, next) {
return res.render("about");
};
this.displayContactPage = function(req, res, next) {
return res.render("contact");
};
this.displayHomePage = function(req, res, next) {
return res.render("home");
};
this.displayChatPage = function(req, res, next) {
return res.render("chat");
};
}
module.exports = UnAuthenticatedHandler;
| bertonjulian/NodeGoat | app/routes/unauthenticated.js | JavaScript | apache-2.0 | 549 |
# Pleurothallis tipuloides Luer SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Pleurothallis/Pleurothallis tipuloides/README.md | Markdown | apache-2.0 | 187 |
/*
* Copyright (C) 2016 the original author or authors.
*
* This file is part of jGrades Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jgrades.lic.api.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class LicenceValidationResult {
private boolean valid;
private String errorMessage;
public LicenceValidationResult() {
valid = true;
errorMessage = null;
}
}
| jgrades/jgrades | jg-backend/implementation/base/jg-lic/interface/src/main/java/org/jgrades/lic/api/model/LicenceValidationResult.java | Java | apache-2.0 | 636 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.mediaconvert.model;
import javax.annotation.Generated;
/**
* Use Deinterlacer (DeinterlaceMode) to choose how the service will do deinterlacing. Default is Deinterlace. -
* Deinterlace converts interlaced to progressive. - Inverse telecine converts Hard Telecine 29.97i to progressive
* 23.976p. - Adaptive auto-detects and converts to progressive.
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum DeinterlacerMode {
DEINTERLACE("DEINTERLACE"),
INVERSE_TELECINE("INVERSE_TELECINE"),
ADAPTIVE("ADAPTIVE");
private String value;
private DeinterlacerMode(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return DeinterlacerMode corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static DeinterlacerMode fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (DeinterlacerMode enumEntry : DeinterlacerMode.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/DeinterlacerMode.java | Java | apache-2.0 | 2,135 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cats.Models
{
public class RationDetail
{
public int RationDetailID { get; set; }
public int RationID { get; set; }
public int CommodityID { get; set; }
public decimal Amount { get; set; }
public Nullable<int> UnitID { get; set; }
public virtual Commodity Commodity { get; set; }
public virtual Ration Ration { get; set; }
public virtual Unit Unit { get; set; }
}
}
| ndrmc/cats | Models/Cats.Models/RationDetail.cs | C# | apache-2.0 | 552 |
if [ -z "$1" ]
then
echo "Usage: startup_node.sh <id_for_node>"
exit
fi
num_gpus=$2
if [ -z "$2" ]
then
num_gpus=1
echo "num_gpus not specified. Defaulting to 1"
fi
gcloud compute --project "visualdb-1046" disks create "hackinstance-$1" --size "20" --zone "us-east1-d" --source-snapshot "hacksnapshot" --type "pd-standard"
gcloud beta compute --project "visualdb-1046" instances create "hackinstance-$1" --zone "us-east1-d" --machine-type "n1-standard-4" --network "default" --metadata "ssh-keys=ubuntu:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDXJ3JrrWKc0TAM5KBXYmuTVAG06DyA8F1hHbqUULCNp767bDNN1dTF9zTo+ZDWdCuHm49XWrpRK552G8U0A55HvBEjOj4eEUSuAibd0uDAYMZr3dJNTzXNU/KfgnbJYGbRboBk3fu47D4bhKPmjX5ZDsSN++BuUYpf1bH829invPBzlGeBb/QRe3Jk9DMK/swIqFc4j6PWeOItj4/1flXFFruR/bT0p2/MIxTTAMAWlhHRYqhtia1YYMbfdv38eqZMH1GY+n7GQJTuKBDvz0qPxCus86xaE4vCawD+iQJFuD8XxppsHbc1+oCAmi5AtbUeHXjXirN95itMBi7S2evd ubuntu,node_id=$1" --maintenance-policy "TERMINATE" --service-account "[email protected]" --scopes "https://www.googleapis.com/auth/cloud-platform" --accelerator type=nvidia-tesla-k80,count=$num_gpus --tags "http-server","https-server" --disk "name=hackinstance-$1,device-name=hackinstance-$1,mode=rw,boot=yes,auto-delete=yes"
| scanner-research/scanner | scripts/startup_node.sh | Shell | apache-2.0 | 1,265 |
<!--- Provide a general summary of your changes in the Title above -->
## Description
<!--- Describe your changes in detail -->
## Related Issue
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested?
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
## Screenshots (if appropriate):
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
## Checklist:
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] I have signed the [Adobe Open Source CLA](https://opensource.adobe.com/cla.html).
- [ ] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
| Adobe-Marketing-Cloud/aem-eclipse-developer-tools | .github/PULL_REQUEST_TEMPLATE.md | Markdown | apache-2.0 | 1,724 |
<!DOCTYPE html>
<meta charset="utf-8">
<!--This page is adapted from Mike Bostock and Scott Murray's d3.js examples-->
<style>
.link {
stroke: #ccc;
}
.node text {
pointer-events: none;
font: 10px sans-serif;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960;
var height = 600;
var colors = d3.scale.category10();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(.25)
.distance(50)
.charge(-300)
.size([width, height]);
svg.append("text").attr("id", "tooltip");
d3.json("graph.json", function(error, json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("x", -8)
.attr("y", -8)
.attr("r", function(d){
return 1 + Math.sqrt(Math.pow(1.6, d.degree)/Math.PI) ;
}
)
.style("fill", function(d, i){
return colors(i);
}
)
.on("mouseover", function(d){
var xPosition = d3.event.clientX;
var yPosition = d3.event.clientY;
d3.select("#tooltip").remove();
svg.append("text")
.attr("id", "tooltip")
.attr("x", xPosition)
.attr("y", yPosition)
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("font-weight", "bold")
.attr("fill", "black")
.text(d.name + "(@" + d.scr_name + "), followed by " +
d.degree + " users");
}
)
.on("mouseout", function(){
d3.select("#tooltip")
.transition()
.delay(1500)
.text("");
}
)
;
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
});
</script>
</body>
</html>
| joyanujoy/twitter-graph | example/index.html | HTML | apache-2.0 | 2,438 |
<div id="print_area" style="width:200px; font-size:12px;">
<?php
include('dbcon_s.php');
$date=date('Y-m-d', $time_now);
if($_POST['h_status']=='off')
{
$query=mysql_query("select count(*) as num_order, sum(person) as total_person, sum(order_total) as total_order, sum(discount) as total_discount, sum(ser_charge) as total_s_charge, sum(vat_total) as total_vat, sum(cash) as total_cash, date from order_list where status='false' AND date='$date' AND terminal='".$_POST['terminal']."'");
}
else
{
$query=mysql_query("select count(*) as num_order, sum(person) as total_person, sum(order_total) as total_order, sum(discount) as total_discount, sum(ser_charge) as total_s_charge, sum(vat_total) as total_vat, sum(cash) as total_cash, date from order_list where status='false' AND date='$date' AND terminal='".$_POST['terminal']."'");
}
$row=mysql_fetch_array($query);
?>
<h2 style="text-align:center; font-family:Forte; margin:0px; padding:0px;">La Bamba</h2>
<p style="text-align:center; margin:0px; font-size:12px;">
House # 54, Road # 20,<br />
Sector # 03, Rabindra Sarani<br />
Uttara, Dhaka-1230<br />
Phone : 01759783896-7<br />
Vat Reg No: 5111110711
</p>
<p style="text-align:center; margin:0px; font-size:12px;">
Day Report (<?php echo $_POST['terminal']; ?>)
</p>
Report Date : <?php echo $row['date']; ?><br />
Print Date : <?php echo $date; ?><br />
<table cellspacing="0" style="width:100%; font-size:12px;">
<tr>
<th style="text-align:left">Number of order:</th>
<th style="text-align:left;"><?php echo $row['num_order']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Person:</th>
<th style="text-align:left;"><?php echo $row['total_person']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Order:</th>
<th style="text-align:left;"><?php echo $row['total_order']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Discount:</th>
<th style="text-align:left;"><?php echo $row['total_discount']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Service Charge:</th>
<th style="text-align:left;"><?php echo $row['total_s_charge']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Vat:</th>
<th style="text-align:left;"><?php echo $row['total_vat']; ?></th>
</tr>
<tr>
<th style="text-align:left">Total Cash:</th>
<th style="text-align:left;"><?php echo $row['total_cash']; ?></th>
</tr>
</table>
<br />
<div style="border-bottom:1px dotted #000;"></div>
<br />
Day report (<?php echo $_POST['terminal']; ?>) printed by : <?php echo $_POST['user']; ?>
</div>
| DR-PHP666/RMS | print_day_report.php | PHP | apache-2.0 | 3,222 |
/*
* Copyright (c) 2015 Ngewi Fet <[email protected]>
*
* 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.
*/
package org.gnucash.android.ui.common;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.LayoutRes;
import android.support.annotation.StringRes;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.uservoice.uservoicesdk.UserVoice;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.account.AccountsActivity;
import org.gnucash.android.ui.passcode.PasscodeLockActivity;
import org.gnucash.android.ui.report.ReportsActivity;
import org.gnucash.android.ui.settings.PreferenceActivity;
import org.gnucash.android.ui.transaction.ScheduledActionsActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Base activity implementing the navigation drawer, to be extended by all activities requiring one.
* <p>
* Each activity inheriting from this class has an indeterminate progress bar at the top,
* (above the action bar) which can be used to display busy operations. See {@link #getProgressBar()}
* </p>
*
* <p>Sub-classes should simply provide their layout using {@link #getContentView()} and then annotate
* any variables they wish to use with {@link ButterKnife#bind(Activity)} annotations. The view
* binding will be done in this base abstract class.<br>
* The activity layout of the subclass is expected to contain {@code DrawerLayout} and
* a {@code NavigationView}.<br>
* Sub-class should also consider using the {@code toolbar.xml} or {@code toolbar_with_spinner.xml}
* for the action bar in their XML layout. Otherwise provide another which contains widgets for the
* toolbar and progress indicator with the IDs {@code R.id.toolbar} and {@code R.id.progress_indicator} respectively.
* </p>
* @author Ngewi Fet <[email protected]>
*/
public abstract class BaseDrawerActivity extends PasscodeLockActivity implements
PopupMenu.OnMenuItemClickListener {
public static final int ID_MANAGE_BOOKS = 0xB00C;
@BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view) NavigationView mNavigationView;
@BindView(R.id.toolbar) Toolbar mToolbar;
@BindView(R.id.toolbar_progress) ProgressBar mToolbarProgress;
protected TextView mBookNameTextView;
protected ActionBarDrawerToggle mDrawerToggle;
public static final int REQUEST_OPEN_DOCUMENT = 0x20;
private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
onDrawerMenuItemClicked(menuItem.getItemId());
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
//if a parameter was passed to open an account within a specific book, then switch
String bookUID = getIntent().getStringExtra(UxArgument.BOOK_UID);
if (bookUID != null && !bookUID.equals(BooksDbAdapter.getInstance().getActiveBookUID())){
GnuCashApplication.activateBook(bookUID);
}
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getTitleRes());
}
mToolbarProgress.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
View headerView = mNavigationView.getHeaderView(0);
headerView.findViewById(R.id.drawer_title).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickAppTitle(v);
}
});
mBookNameTextView = (TextView) headerView.findViewById(R.id.book_name);
mBookNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickBook(v);
}
});
updateActiveBookName();
setUpNavigationDrawer();
}
@Override
protected void onResume() {
super.onResume();
updateActiveBookName();
}
/**
* Return the layout to inflate for this activity
* @return Layout resource identifier
*/
public abstract @LayoutRes int getContentView();
/**
* Return the title for this activity.
* This will be displayed in the action bar
* @return String resource identifier
*/
public abstract @StringRes int getTitleRes();
/**
* Returns the progress bar for the activity.
* <p>This progress bar is displayed above the toolbar and should be used to show busy status
* for long operations.<br/>
* The progress bar visibility is set to {@link View#GONE} by default. Make visible to use </p>
* @return Indeterminate progress bar.
*/
public ProgressBar getProgressBar(){
return mToolbarProgress;
}
/**
* Sets up the navigation drawer for this activity.
*/
private void setUpNavigationDrawer() {
mNavigationView.setNavigationItemSelectedListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
if (!mDrawerLayout.isDrawerOpen(mNavigationView))
mDrawerLayout.openDrawer(mNavigationView);
else
mDrawerLayout.closeDrawer(mNavigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Update the display name of the currently active book
*/
protected void updateActiveBookName(){
mBookNameTextView.setText(BooksDbAdapter.getInstance().getActiveBookDisplayName());
}
/**
* Handler for the navigation drawer items
* */
protected void onDrawerMenuItemClicked(int itemId) {
switch (itemId){
case R.id.nav_item_open: { //Open... files
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
//use the storage access framework
Intent openDocument = new Intent(Intent.ACTION_OPEN_DOCUMENT);
openDocument.addCategory(Intent.CATEGORY_OPENABLE);
openDocument.setType("*/*");
startActivityForResult(openDocument, REQUEST_OPEN_DOCUMENT);
} else {
AccountsActivity.startXmlFileChooser(this);
}
}
break;
case R.id.nav_item_favorites: { //favorite accounts
Intent intent = new Intent(this, AccountsActivity.class);
intent.putExtra(AccountsActivity.EXTRA_TAB_INDEX,
AccountsActivity.INDEX_FAVORITE_ACCOUNTS_FRAGMENT);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
case R.id.nav_item_reports: {
Intent intent = new Intent(this, ReportsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
/*
//todo: Re-enable this when Budget UI is complete
case R.id.nav_item_budgets:
startActivity(new Intent(this, BudgetsActivity.class));
break;
*/
case R.id.nav_item_scheduled_actions: { //show scheduled transactions
Intent intent = new Intent(this, ScheduledActionsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
break;
case R.id.nav_item_export:
AccountsActivity.openExportFragment(this);
break;
case R.id.nav_item_settings: //Settings activity
startActivity(new Intent(this, PreferenceActivity.class));
break;
case R.id.nav_item_help:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean(UxArgument.SKIP_PASSCODE_SCREEN, true).apply();
UserVoice.launchUserVoice(this);
break;
}
mDrawerLayout.closeDrawer(mNavigationView);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
switch (requestCode) {
case AccountsActivity.REQUEST_PICK_ACCOUNTS_FILE:
AccountsActivity.importXmlFileFromIntent(this, data, null);
break;
case BaseDrawerActivity.REQUEST_OPEN_DOCUMENT: //this uses the Storage Access Framework
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
AccountsActivity.importXmlFileFromIntent(this, data, null);
getContentResolver().takePersistableUriPermission(data.getData(), takeFlags);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
long id = item.getItemId();
if (id == ID_MANAGE_BOOKS){
Intent intent = new Intent(this, PreferenceActivity.class);
intent.setAction(PreferenceActivity.ACTION_MANAGE_BOOKS);
startActivity(intent);
mDrawerLayout.closeDrawer(mNavigationView);
return true;
}
BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance();
String bookUID = booksDbAdapter.getUID(id);
if (!bookUID.equals(booksDbAdapter.getActiveBookUID())){
GnuCashApplication.loadBook(bookUID);
finish();
}
AccountsActivity.start(GnuCashApplication.getAppContext());
return true;
}
public void onClickAppTitle(View view){
mDrawerLayout.closeDrawer(mNavigationView);
AccountsActivity.start(this);
}
public void onClickBook(View view){
PopupMenu popup = new PopupMenu(this, view);
popup.setOnMenuItemClickListener(this);
Menu menu = popup.getMenu();
int maxRecent = 0;
Cursor cursor = BooksDbAdapter.getInstance().fetchAllRecords(null, null,
DatabaseSchema.BookEntry.COLUMN_MODIFIED_AT + " DESC");
while (cursor.moveToNext() && maxRecent++ < 5) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME));
menu.add(0, (int)id, maxRecent, name);
}
menu.add(0, ID_MANAGE_BOOKS, maxRecent, R.string.menu_manage_books);
popup.show();
}
}
| lxbzmy/gnucash-android | app/src/main/java/org/gnucash/android/ui/common/BaseDrawerActivity.java | Java | apache-2.0 | 13,912 |
/* 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.
*/
#include <string.h>
#define CFISH_USE_SHORT_NAMES
#define TESTCFISH_USE_SHORT_NAMES
#include "Clownfish/Test/Util/TestStringHelper.h"
#include "Clownfish/String.h"
#include "Clownfish/Err.h"
#include "Clownfish/Test.h"
#include "Clownfish/TestHarness/TestBatchRunner.h"
#include "Clownfish/Util/StringHelper.h"
#include "Clownfish/Class.h"
/* This alternative implementation of utf8_valid() is (presumably) slower, but
* it implements the standard in a more linear, easy-to-grok way.
*/
#define TRAIL_OK(n) (n >= 0x80 && n <= 0xBF)
TestStringHelper*
TestStrHelp_new() {
return (TestStringHelper*)Class_Make_Obj(TESTSTRINGHELPER);
}
static bool
S_utf8_valid_alt(const char *maybe_utf8, size_t size) {
const uint8_t *string = (const uint8_t*)maybe_utf8;
const uint8_t *const end = string + size;
while (string < end) {
int count = StrHelp_UTF8_COUNT[*string];
bool valid = false;
if (count == 1) {
if (string[0] <= 0x7F) {
valid = true;
}
}
else if (count == 2) {
if (string[0] >= 0xC2 && string[0] <= 0xDF) {
if (TRAIL_OK(string[1])) {
valid = true;
}
}
}
else if (count == 3) {
if (string[0] == 0xE0) {
if (string[1] >= 0xA0 && string[1] <= 0xBF
&& TRAIL_OK(string[2])
) {
valid = true;
}
}
else if (string[0] >= 0xE1 && string[0] <= 0xEC) {
if (TRAIL_OK(string[1])
&& TRAIL_OK(string[2])
) {
valid = true;
}
}
else if (string[0] == 0xED) {
if (string[1] >= 0x80 && string[1] <= 0x9F
&& TRAIL_OK(string[2])
) {
valid = true;
}
}
else if (string[0] >= 0xEE && string[0] <= 0xEF) {
if (TRAIL_OK(string[1])
&& TRAIL_OK(string[2])
) {
valid = true;
}
}
}
else if (count == 4) {
if (string[0] == 0xF0) {
if (string[1] >= 0x90 && string[1] <= 0xBF
&& TRAIL_OK(string[2])
&& TRAIL_OK(string[3])
) {
valid = true;
}
}
else if (string[0] >= 0xF1 && string[0] <= 0xF3) {
if (TRAIL_OK(string[1])
&& TRAIL_OK(string[2])
&& TRAIL_OK(string[3])
) {
valid = true;
}
}
else if (string[0] == 0xF4) {
if (string[1] >= 0x80 && string[1] <= 0x8F
&& TRAIL_OK(string[2])
&& TRAIL_OK(string[3])
) {
valid = true;
}
}
}
if (!valid) {
return false;
}
string += count;
}
if (string != end) {
return false;
}
return true;
}
static void
test_overlap(TestBatchRunner *runner) {
size_t result;
result = StrHelp_overlap("", "", 0, 0);
TEST_INT_EQ(runner, result, 0, "two empty strings");
result = StrHelp_overlap("", "foo", 0, 3);
TEST_INT_EQ(runner, result, 0, "first string is empty");
result = StrHelp_overlap("foo", "", 3, 0);
TEST_INT_EQ(runner, result, 0, "second string is empty");
result = StrHelp_overlap("foo", "foo", 3, 3);
TEST_INT_EQ(runner, result, 3, "equal strings");
result = StrHelp_overlap("foo bar", "foo", 7, 3);
TEST_INT_EQ(runner, result, 3, "first string is longer");
result = StrHelp_overlap("foo", "foo bar", 3, 7);
TEST_INT_EQ(runner, result, 3, "second string is longer");
}
static void
test_to_base36(TestBatchRunner *runner) {
char buffer[StrHelp_MAX_BASE36_BYTES];
StrHelp_to_base36(UINT64_MAX, buffer);
TEST_STR_EQ(runner, "3w5e11264sgsf", buffer, "base36 UINT64_MAX");
StrHelp_to_base36(1, buffer);
TEST_STR_EQ(runner, "1", buffer, "base36 1");
TEST_INT_EQ(runner, buffer[1], 0, "base36 NULL termination");
}
static void
test_utf8_round_trip(TestBatchRunner *runner) {
int32_t code_point;
for (code_point = 0; code_point <= 0x10FFFF; code_point++) {
char buffer[4];
uint32_t size = StrHelp_encode_utf8_char(code_point, buffer);
char *start = buffer;
char *end = start + size;
// Verify length returned by encode_utf8_char().
if (size != StrHelp_UTF8_COUNT[(unsigned char)buffer[0]]) {
break;
}
// Verify that utf8_valid() agrees with alternate implementation.
if (!!StrHelp_utf8_valid(start, size)
!= !!S_utf8_valid_alt(start, size)
) {
break;
}
// Verify back_utf8_char().
if (StrHelp_back_utf8_char(end, start) != start) {
break;
}
// Verify round trip of encode/decode.
if (StrHelp_decode_utf8_char(buffer) != code_point) {
break;
}
}
if (code_point == 0x110000) {
PASS(runner, "Successfully round tripped 0 - 0x10FFFF");
}
else {
FAIL(runner, "Failed round trip at 0x%.1X", (unsigned)code_point);
}
}
static void
S_test_validity(TestBatchRunner *runner, const char *content, size_t size,
bool expected, const char *description) {
bool sane = StrHelp_utf8_valid(content, size);
bool double_check = S_utf8_valid_alt(content, size);
if (sane != double_check) {
FAIL(runner, "Disagreement: %s", description);
}
else {
TEST_TRUE(runner, sane == expected, "%s", description);
}
}
static void
test_utf8_valid(TestBatchRunner *runner) {
// Musical symbol G clef:
// Code point: U+1D11E
// UTF-16: 0xD834 0xDD1E
// UTF-8 0xF0 0x9D 0x84 0x9E
S_test_validity(runner, "\xF0\x9D\x84\x9E", 4, true,
"Musical symbol G clef");
S_test_validity(runner, "\xED\xA0\xB4\xED\xB4\x9E", 6, false,
"G clef as UTF-8 encoded UTF-16 surrogates");
S_test_validity(runner, ".\xED\xA0\xB4.", 5, false,
"Isolated high surrogate");
S_test_validity(runner, ".\xED\xB4\x9E.", 5, false,
"Isolated low surrogate");
// Shortest form.
S_test_validity(runner, ".\xC1\x9C.", 4, false,
"Non-shortest form ASCII backslash");
S_test_validity(runner, ".\xC0\xAF.", 4, false,
"Non-shortest form ASCII slash");
S_test_validity(runner, ".\xC0\x80.", 4, false,
"Non-shortest form ASCII NUL character");
// Range.
S_test_validity(runner, "\xF8\x88\x80\x80\x80", 5, false, "5-byte UTF-8");
// Bad continuations.
S_test_validity(runner, "\xE2\x98\xBA\xE2\x98\xBA", 6, true,
"SmileySmiley");
S_test_validity(runner, "\xE2\xBA\xE2\x98\xBA", 5, false,
"missing first continuation byte");
S_test_validity(runner, "\xE2\x98\xE2\x98\xBA", 5, false,
"missing second continuation byte");
S_test_validity(runner, "\xE2\xE2\x98\xBA", 4, false,
"missing both continuation bytes");
S_test_validity(runner, "\xBA\xE2\x98\xBA\xE2\xBA", 5, false,
"missing first continuation byte (end)");
S_test_validity(runner, "\xE2\x98\xBA\xE2\x98", 5, false,
"missing second continuation byte (end)");
S_test_validity(runner, "\xE2\x98\xBA\xE2", 4, false,
"missing both continuation bytes (end)");
S_test_validity(runner, "\xBA\xE2\x98\xBA", 4, false,
"isolated continuation byte 0xBA");
S_test_validity(runner, "\x98\xE2\x98\xBA", 4, false,
"isolated continuation byte 0x98");
S_test_validity(runner, "\xE2\x98\xBA\xBA", 4, false,
"isolated continuation byte 0xBA (end)");
S_test_validity(runner, "\xE2\x98\xBA\x98", 4, false,
"isolated continuation byte 0x98 (end)");
}
static void
test_is_whitespace(TestBatchRunner *runner) {
TEST_TRUE(runner, StrHelp_is_whitespace(' '), "space is whitespace");
TEST_TRUE(runner, StrHelp_is_whitespace('\n'), "newline is whitespace");
TEST_TRUE(runner, StrHelp_is_whitespace('\t'), "tab is whitespace");
TEST_TRUE(runner, StrHelp_is_whitespace('\v'),
"vertical tab is whitespace");
TEST_FALSE(runner, StrHelp_is_whitespace('a'), "'a' isn't whitespace");
TEST_FALSE(runner, StrHelp_is_whitespace(0), "NULL isn't whitespace");
TEST_FALSE(runner, StrHelp_is_whitespace(0x263A),
"Smiley isn't whitespace");
}
static void
test_back_utf8_char(TestBatchRunner *runner) {
char buffer[4];
char *buf = buffer + 1;
uint32_t len = StrHelp_encode_utf8_char(0x263A, buffer);
char *end = buffer + len;
TEST_TRUE(runner, StrHelp_back_utf8_char(end, buffer) == buffer,
"back_utf8_char");
TEST_TRUE(runner, StrHelp_back_utf8_char(end, buf) == NULL,
"back_utf8_char returns NULL rather than back up beyond start");
TEST_TRUE(runner, StrHelp_back_utf8_char(buffer, buffer) == NULL,
"back_utf8_char returns NULL when end == start");
}
void
TestStrHelp_Run_IMP(TestStringHelper *self, TestBatchRunner *runner) {
TestBatchRunner_Plan(runner, (TestBatch*)self, 39);
test_overlap(runner);
test_to_base36(runner);
test_utf8_round_trip(runner);
test_utf8_valid(runner);
test_is_whitespace(runner);
test_back_utf8_char(runner);
}
| rectang/lucy-clownfish | runtime/core/Clownfish/Test/Util/TestStringHelper.c | C | apache-2.0 | 10,638 |
# Gardenia squamifera R.D.Good SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Euclinia/Euclinia squamifera/ Syn. Gardenia squamifera/README.md | Markdown | apache-2.0 | 185 |
# Agassizia cheiranthifolia Spach SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Onagraceae/Agassizia/Agassizia cheiranthifolia/README.md | Markdown | apache-2.0 | 181 |
# Quercus cryptoneuron H.Lév. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Castanopsis/Castanopsis cryptoneuron/ Syn. Quercus cryptoneuron/README.md | Markdown | apache-2.0 | 185 |
# Pirigara globosa Span. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Lecythidaceae/Planchonia/Planchonia timorensis/ Syn. Pirigara globosa/README.md | Markdown | apache-2.0 | 179 |
function $childNode(o) {
return window.frames[o]
}
function animationHover(o, e) {
o = $(o), o.hover(function () {
o.addClass("animated " + e)
}, function () {
window.setTimeout(function () {
o.removeClass("animated " + e)
}, 2e3)
})
}
function WinMove() {
var o = "[class*=col]", e = ".ibox-title", i = "[class*=col]";
$(o).sortable({
handle: e,
connectWith: i,
tolerance: "pointer",
forcePlaceholderSize: !0,
opacity: .8
}).disableSelection()
}
var $parentNode = window.parent.document;
if ($(".tooltip-demo").tooltip({
selector: "[data-toggle=tooltip]",
container: "body"
}), $(".modal").appendTo("body"), $("[data-toggle=popover]").popover(), $(".collapse-link").click(function () {
var o = $(this).closest("div.ibox"), e = $(this).find("i"), i = o.find("div.ibox-content");
i.slideToggle(200), e.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down"), o.toggleClass("").toggleClass("border-bottom"), setTimeout(function () {
o.resize(), o.find("[id^=map-]").resize()
}, 50)
}), $(".close-link").click(function () {
var o = $(this).closest("div.ibox");
o.remove()
}), top == this) {
} | pantisocracy/live-report | src/main/resources/static/resource/js/content.min.js | JavaScript | apache-2.0 | 1,277 |
# Crepidium kerintjiense (J.J.Sm.) Szlach. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Microstylis kerintjiensis J.J.Sm.
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Crepidium/Crepidium kerintjiense/README.md | Markdown | apache-2.0 | 227 |
# Stylochaeton zenkeri Engl. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Stylochaeton/Stylochaeton zenkeri/README.md | Markdown | apache-2.0 | 184 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link href="../../../../../src/css/29tree.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tree" id="c1">
<div class="root open">
<div class="tag">
<div class="text">XLib</div>
</div>
<div class="childs">
<div class="folder normal open">
<div class="tag">
<div class="text">base</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
<div class="folder normal close">
<div class="tag">
<div class="text">ui</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
<div class="folder last close">
<div class="tag">
<div class="text">grid</div>
</div>
<div class="childs">
<div class="txt normal close">
<div class="tag">
<div class="text">basis</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">extend</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">core</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">out</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">dom</div>
</div>
<div class="childs"></div>
</div>
<div class="txt normal close">
<div class="tag">
<div class="text">css</div>
</div>
<div class="childs"></div>
</div>
<div class="txt last close">
<div class="tag">
<div class="text">createdom</div>
</div>
<div class="childs"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| ldjking/sharegrid | web/examples/xlib/5tree/50old/51tree/tree_design_0.8.html | HTML | apache-2.0 | 4,959 |
# Copyright 2020 Google LLC
#
# 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
#
# https://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.
from __future__ import absolute_import
import collections
import io
import json
import time
try:
import fastavro
except ImportError: # pragma: NO COVER
fastavro = None
import google.api_core.exceptions
import google.rpc.error_details_pb2
try:
import pandas
except ImportError: # pragma: NO COVER
pandas = None
try:
import pyarrow
except ImportError: # pragma: NO COVER
pyarrow = None
try:
import pyarrow
except ImportError: # pragma: NO COVER
pyarrow = None
_STREAM_RESUMPTION_EXCEPTIONS = (
google.api_core.exceptions.ServiceUnavailable,
# Caused by transport-level error. No status code was received.
# https://github.com/googleapis/python-bigquery-storage/issues/262
google.api_core.exceptions.Unknown,
)
# The Google API endpoint can unexpectedly close long-running HTTP/2 streams.
# Unfortunately, this condition is surfaced to the caller as an internal error
# by gRPC. We don't want to resume on all internal errors, so instead we look
# for error message that we know are caused by problems that are safe to
# reconnect.
_STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES = (
# See: https://github.com/googleapis/google-cloud-python/pull/9994
"RST_STREAM",
)
_FASTAVRO_REQUIRED = (
"fastavro is required to parse ReadRowResponse messages with Avro bytes."
)
_PANDAS_REQUIRED = "pandas is required to create a DataFrame"
_PYARROW_REQUIRED = (
"pyarrow is required to parse ReadRowResponse messages with Arrow bytes."
)
class ReadRowsStream(object):
"""A stream of results from a read rows request.
This stream is an iterable of
:class:`~google.cloud.bigquery_storage_v1.types.ReadRowsResponse`.
Iterate over it to fetch all row messages.
If the fastavro library is installed, use the
:func:`~google.cloud.bigquery_storage_v1.reader.ReadRowsStream.rows()`
method to parse all messages into a stream of row dictionaries.
If the pandas and fastavro libraries are installed, use the
:func:`~google.cloud.bigquery_storage_v1.reader.ReadRowsStream.to_dataframe()`
method to parse all messages into a :class:`pandas.DataFrame`.
This object should not be created directly, but is returned by
other methods in this library.
"""
def __init__(
self, client, name, offset, read_rows_kwargs, retry_delay_callback=None
):
"""Construct a ReadRowsStream.
Args:
client ( \
~google.cloud.bigquery_storage_v1.services. \
big_query_read.BigQueryReadClient \
):
A GAPIC client used to reconnect to a ReadRows stream. This
must be the GAPIC client to avoid a circular dependency on
this class.
name (str):
Required. Stream ID from which rows are being read.
offset (int):
Required. Position in the stream to start
reading from. The offset requested must be less than the last
row read from ReadRows. Requesting a larger offset is
undefined.
read_rows_kwargs (dict):
Keyword arguments to use when reconnecting to a ReadRows
stream.
retry_delay_callback (Optional[Callable[[float], None]]):
If the client receives a retryable error that asks the client to
delay its next attempt and retry_delay_callback is not None,
ReadRowsStream will call retry_delay_callback with the delay
duration (in seconds) before it starts sleeping until the next
attempt.
Returns:
Iterable[ \
~google.cloud.bigquery_storage.types.ReadRowsResponse \
]:
A sequence of row messages.
"""
# Make a copy of the read position so that we can update it without
# mutating the original input.
self._client = client
self._name = name
self._offset = offset
self._read_rows_kwargs = read_rows_kwargs
self._retry_delay_callback = retry_delay_callback
self._wrapped = None
def __iter__(self):
"""An iterable of messages.
Returns:
Iterable[ \
~google.cloud.bigquery_storage_v1.types.ReadRowsResponse \
]:
A sequence of row messages.
"""
# Infinite loop to reconnect on reconnectable errors while processing
# the row stream.
if self._wrapped is None:
self._reconnect()
while True:
try:
for message in self._wrapped:
rowcount = message.row_count
self._offset += rowcount
yield message
return # Made it through the whole stream.
except google.api_core.exceptions.InternalServerError as exc:
resumable_error = any(
resumable_message in exc.message
for resumable_message in _STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES
)
if not resumable_error:
raise
except _STREAM_RESUMPTION_EXCEPTIONS:
# Transient error, so reconnect to the stream.
pass
except Exception as exc:
if not self._resource_exhausted_exception_is_retryable(exc):
raise
self._reconnect()
def _reconnect(self):
"""Reconnect to the ReadRows stream using the most recent offset."""
while True:
try:
self._wrapped = self._client.read_rows(
read_stream=self._name,
offset=self._offset,
**self._read_rows_kwargs
)
break
except Exception as exc:
if not self._resource_exhausted_exception_is_retryable(exc):
raise
def _resource_exhausted_exception_is_retryable(self, exc):
if isinstance(exc, google.api_core.exceptions.ResourceExhausted):
# ResourceExhausted errors are only retried if a valid
# RetryInfo is provided with the error.
#
# TODO: Remove hasattr logic when we require google-api-core >= 2.2.0.
# ResourceExhausted added details/_details in google-api-core 2.2.0.
details = None
if hasattr(exc, "details"):
details = exc.details
elif hasattr(exc, "_details"):
details = exc._details
if details is not None:
for detail in details:
if isinstance(detail, google.rpc.error_details_pb2.RetryInfo):
retry_delay = detail.retry_delay
if retry_delay is not None:
delay = max(
0,
float(retry_delay.seconds)
+ (float(retry_delay.nanos) / 1e9),
)
if self._retry_delay_callback:
self._retry_delay_callback(delay)
time.sleep(delay)
return True
return False
def rows(self, read_session=None):
"""Iterate over all rows in the stream.
This method requires the fastavro library in order to parse row
messages in avro format. For arrow format messages, the pyarrow
library is required.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings in the fastavro library.
Args:
read_session ( \
Optional[~google.cloud.bigquery_storage_v1.types.ReadSession] \
):
DEPRECATED.
This argument was used to specify the schema of the rows in the
stream, but now the first message in a read stream contains
this information.
Returns:
Iterable[Mapping]:
A sequence of rows, represented as dictionaries.
"""
return ReadRowsIterable(self, read_session=read_session)
def to_arrow(self, read_session=None):
"""Create a :class:`pyarrow.Table` of all rows in the stream.
This method requires the pyarrow library and a stream using the Arrow
format.
Args:
read_session ( \
~google.cloud.bigquery_storage_v1.types.ReadSession \
):
DEPRECATED.
This argument was used to specify the schema of the rows in the
stream, but now the first message in a read stream contains
this information.
Returns:
pyarrow.Table:
A table of all rows in the stream.
"""
return self.rows(read_session=read_session).to_arrow()
def to_dataframe(self, read_session=None, dtypes=None):
"""Create a :class:`pandas.DataFrame` of all rows in the stream.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row messages.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings.
Args:
read_session ( \
~google.cloud.bigquery_storage_v1.types.ReadSession \
):
DEPRECATED.
This argument was used to specify the schema of the rows in the
stream, but now the first message in a read stream contains
this information.
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
Returns:
pandas.DataFrame:
A data frame of all rows in the stream.
"""
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
return self.rows(read_session=read_session).to_dataframe(dtypes=dtypes)
class ReadRowsIterable(object):
"""An iterable of rows from a read session.
Args:
reader (google.cloud.bigquery_storage_v1.reader.ReadRowsStream):
A read rows stream.
read_session ( \
Optional[~google.cloud.bigquery_storage_v1.types.ReadSession] \
):
DEPRECATED.
This argument was used to specify the schema of the rows in the
stream, but now the first message in a read stream contains
this information.
"""
# This class is modelled after the google.cloud.bigquery.table.RowIterator
# and aims to be API compatible where possible.
def __init__(self, reader, read_session=None):
self._reader = reader
if read_session is not None:
self._stream_parser = _StreamParser.from_read_session(read_session)
else:
self._stream_parser = None
@property
def pages(self):
"""A generator of all pages in the stream.
Returns:
types.GeneratorType[google.cloud.bigquery_storage_v1.ReadRowsPage]:
A generator of pages.
"""
# Each page is an iterator of rows. But also has num_items, remaining,
# and to_dataframe.
for message in self._reader:
# Only the first message contains the schema, which is needed to
# decode the messages.
if not self._stream_parser:
self._stream_parser = _StreamParser.from_read_rows_response(message)
yield ReadRowsPage(self._stream_parser, message)
def __iter__(self):
"""Iterator for each row in all pages."""
for page in self.pages:
for row in page:
yield row
def to_arrow(self):
"""Create a :class:`pyarrow.Table` of all rows in the stream.
This method requires the pyarrow library and a stream using the Arrow
format.
Returns:
pyarrow.Table:
A table of all rows in the stream.
"""
record_batches = []
for page in self.pages:
record_batches.append(page.to_arrow())
if record_batches:
return pyarrow.Table.from_batches(record_batches)
# No data, return an empty Table.
self._stream_parser._parse_arrow_schema()
return pyarrow.Table.from_batches([], schema=self._stream_parser._schema)
def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of all rows in the stream.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row messages.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings in the fastavro library.
Args:
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
Returns:
pandas.DataFrame:
A data frame of all rows in the stream.
"""
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
if dtypes is None:
dtypes = {}
# If it's an Arrow stream, calling to_arrow, then converting to a
# pandas dataframe is about 2x faster. This is because pandas.concat is
# rarely no-copy, whereas pyarrow.Table.from_batches + to_pandas is
# usually no-copy.
try:
record_batch = self.to_arrow()
except NotImplementedError:
pass
else:
df = record_batch.to_pandas()
for column in dtypes:
df[column] = pandas.Series(df[column], dtype=dtypes[column])
return df
frames = [page.to_dataframe(dtypes=dtypes) for page in self.pages]
if frames:
return pandas.concat(frames)
# No data, construct an empty dataframe with columns matching the schema.
# The result should be consistent with what an empty ARROW stream would produce.
self._stream_parser._parse_avro_schema()
schema = self._stream_parser._avro_schema_json
column_dtypes = self._dtypes_from_avro(schema["fields"])
column_dtypes.update(dtypes)
df = pandas.DataFrame(columns=column_dtypes.keys())
for column in df:
df[column] = pandas.Series([], dtype=column_dtypes[column])
return df
def _dtypes_from_avro(self, avro_fields):
"""Determine Pandas dtypes for columns in Avro schema.
Args:
avro_fields (Iterable[Mapping[str, Any]]):
Avro fields' metadata.
Returns:
colelctions.OrderedDict[str, str]:
Column names with their corresponding Pandas dtypes.
"""
result = collections.OrderedDict()
type_map = {"long": "int64", "double": "float64", "boolean": "bool"}
for field_info in avro_fields:
# If a type is an union of multiple types, pick the first type
# that is not "null".
if isinstance(field_info["type"], list):
type_info = next(item for item in field_info["type"] if item != "null")
if isinstance(type_info, str):
field_dtype = type_map.get(type_info, "object")
else:
logical_type = type_info.get("logicalType")
if logical_type == "timestamp-micros":
field_dtype = "datetime64[ns, UTC]"
else:
field_dtype = "object"
result[field_info["name"]] = field_dtype
return result
class ReadRowsPage(object):
"""An iterator of rows from a read session message.
Args:
stream_parser (google.cloud.bigquery_storage_v1.reader._StreamParser):
A helper for parsing messages into rows.
message (google.cloud.bigquery_storage_v1.types.ReadRowsResponse):
A message of data from a read rows stream.
"""
# This class is modeled after google.api_core.page_iterator.Page and aims
# to provide API compatibility where possible.
def __init__(self, stream_parser, message):
self._stream_parser = stream_parser
self._message = message
self._iter_rows = None
self._num_items = self._message.row_count
self._remaining = self._message.row_count
def _parse_rows(self):
"""Parse rows from the message only once."""
if self._iter_rows is not None:
return
rows = self._stream_parser.to_rows(self._message)
self._iter_rows = iter(rows)
@property
def num_items(self):
"""int: Total items in the page."""
return self._num_items
@property
def remaining(self):
"""int: Remaining items in the page."""
return self._remaining
def __iter__(self):
"""A ``ReadRowsPage`` is an iterator."""
return self
def next(self):
"""Get the next row in the page."""
self._parse_rows()
if self._remaining > 0:
self._remaining -= 1
return next(self._iter_rows)
# Alias needed for Python 2/3 support.
__next__ = next
def to_arrow(self):
"""Create an :class:`pyarrow.RecordBatch` of rows in the page.
Returns:
pyarrow.RecordBatch:
Rows from the message, as an Arrow record batch.
"""
return self._stream_parser.to_arrow(self._message)
def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of rows in the page.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row messages.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings in the fastavro library.
Args:
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
Returns:
pandas.DataFrame:
A data frame of all rows in the stream.
"""
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
return self._stream_parser.to_dataframe(self._message, dtypes=dtypes)
class _StreamParser(object):
def to_arrow(self, message):
raise NotImplementedError("Not implemented.")
def to_dataframe(self, message, dtypes=None):
raise NotImplementedError("Not implemented.")
def to_rows(self, message):
raise NotImplementedError("Not implemented.")
def _parse_avro_schema(self):
raise NotImplementedError("Not implemented.")
def _parse_arrow_schema(self):
raise NotImplementedError("Not implemented.")
@staticmethod
def from_read_session(read_session):
schema_type = read_session._pb.WhichOneof("schema")
if schema_type == "avro_schema":
return _AvroStreamParser(read_session)
elif schema_type == "arrow_schema":
return _ArrowStreamParser(read_session)
else:
raise TypeError(
"Unsupported schema type in read_session: {0}".format(schema_type)
)
@staticmethod
def from_read_rows_response(message):
schema_type = message._pb.WhichOneof("schema")
if schema_type == "avro_schema":
return _AvroStreamParser(message)
elif schema_type == "arrow_schema":
return _ArrowStreamParser(message)
else:
raise TypeError(
"Unsupported schema type in message: {0}".format(schema_type)
)
class _AvroStreamParser(_StreamParser):
"""Helper to parse Avro messages into useful representations."""
def __init__(self, message):
"""Construct an _AvroStreamParser.
Args:
message (Union[
google.cloud.bigquery_storage_v1.types.ReadSession, \
google.cloud.bigquery_storage_v1.types.ReadRowsResponse, \
]):
Either the first message of data from a read rows stream or a
read session. Both types contain a oneof "schema" field, which
can be used to determine how to deserialize rows.
"""
if fastavro is None:
raise ImportError(_FASTAVRO_REQUIRED)
self._first_message = message
self._avro_schema_json = None
self._fastavro_schema = None
self._column_names = None
def to_arrow(self, message):
"""Create an :class:`pyarrow.RecordBatch` of rows in the page.
Args:
message (google.cloud.bigquery_storage_v1.types.ReadRowsResponse):
Protocol buffer from the read rows stream, to convert into an
Arrow record batch.
Returns:
pyarrow.RecordBatch:
Rows from the message, as an Arrow record batch.
"""
raise NotImplementedError("to_arrow not implemented for Avro streams.")
def to_dataframe(self, message, dtypes=None):
"""Create a :class:`pandas.DataFrame` of rows in the page.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row messages.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings in the fastavro library.
Args:
message ( \
~google.cloud.bigquery_storage_v1.types.ReadRowsResponse \
):
A message containing Avro bytes to parse into a pandas DataFrame.
dtypes ( \
Map[str, Union[str, pandas.Series.dtype]] \
):
Optional. A dictionary of column names pandas ``dtype``s. The
provided ``dtype`` is used when constructing the series for
the column specified. Otherwise, the default pandas behavior
is used.
Returns:
pandas.DataFrame:
A data frame of all rows in the stream.
"""
self._parse_avro_schema()
if dtypes is None:
dtypes = {}
columns = collections.defaultdict(list)
for row in self.to_rows(message):
for column in row:
columns[column].append(row[column])
for column in dtypes:
columns[column] = pandas.Series(columns[column], dtype=dtypes[column])
return pandas.DataFrame(columns, columns=self._column_names)
def _parse_avro_schema(self):
"""Extract and parse Avro schema from a read session."""
if self._avro_schema_json:
return
self._avro_schema_json = json.loads(self._first_message.avro_schema.schema)
self._column_names = tuple(
(field["name"] for field in self._avro_schema_json["fields"])
)
self._first_message = None
def _parse_fastavro(self):
"""Convert parsed Avro schema to fastavro format."""
self._parse_avro_schema()
self._fastavro_schema = fastavro.parse_schema(self._avro_schema_json)
def to_rows(self, message):
"""Parse all rows in a stream message.
Args:
message ( \
~google.cloud.bigquery_storage_v1.types.ReadRowsResponse \
):
A message containing Avro bytes to parse into rows.
Returns:
Iterable[Mapping]:
A sequence of rows, represented as dictionaries.
"""
self._parse_fastavro()
messageio = io.BytesIO(message.avro_rows.serialized_binary_rows)
while True:
# Loop in a while loop because schemaless_reader can only read
# a single record.
try:
# TODO: Parse DATETIME into datetime.datetime (no timezone),
# instead of as a string.
yield fastavro.schemaless_reader(messageio, self._fastavro_schema)
except StopIteration:
break # Finished with message
class _ArrowStreamParser(_StreamParser):
def __init__(self, message):
"""Construct an _ArrowStreamParser.
Args:
message (Union[
google.cloud.bigquery_storage_v1.types.ReadSession, \
google.cloud.bigquery_storage_v1.types.ReadRowsResponse, \
]):
Either the first message of data from a read rows stream or a
read session. Both types contain a oneof "schema" field, which
can be used to determine how to deserialize rows.
"""
if pyarrow is None:
raise ImportError(_PYARROW_REQUIRED)
self._first_message = message
self._schema = None
def to_arrow(self, message):
return self._parse_arrow_message(message)
def to_rows(self, message):
record_batch = self._parse_arrow_message(message)
# Iterate through each column simultaneously, and make a dict from the
# row values
for row in zip(*record_batch.columns):
yield dict(zip(self._column_names, row))
def to_dataframe(self, message, dtypes=None):
record_batch = self._parse_arrow_message(message)
if dtypes is None:
dtypes = {}
df = record_batch.to_pandas()
for column in dtypes:
df[column] = pandas.Series(df[column], dtype=dtypes[column])
return df
def _parse_arrow_message(self, message):
self._parse_arrow_schema()
return pyarrow.ipc.read_record_batch(
pyarrow.py_buffer(message.arrow_record_batch.serialized_record_batch),
self._schema,
)
def _parse_arrow_schema(self):
if self._schema:
return
self._schema = pyarrow.ipc.read_schema(
pyarrow.py_buffer(self._first_message.arrow_schema.serialized_schema)
)
self._column_names = [field.name for field in self._schema]
self._first_message = None
| googleapis/python-bigquery-storage | google/cloud/bigquery_storage_v1/reader.py | Python | apache-2.0 | 27,503 |
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<span class='rank0 0.0'>?Y0V</span>
</br>
<span class='rank4 4.488678160318237'>BOTANIC</span>
<span class='rank0 0.0'>A</span>
</br>
<span class='rank0 0.0'>S¨'Ç</span>
</br>
<span class='rank8 8.229688880941637'>Wmm</span>
</br>
<span class='rank6 6.033766030327724'>THE</span>
<span class='rank5 5.23758013687111'>NEW</span>
<span class='rank5 5.092407184714711'>YORK</span>
<span class='rank4 4.3452095742978045'>BOTANICAL</span>
<span class='rank5 4.836230413135688'>GARDEN</span>
</br>
<span class='rank2 2.3388802077460475'>Plants</span>
<span class='rank17 16.624349504197816'>oolleoteo</span>
<span class='rank5 5.3627373972535715'>in</span>
<span class='rank5 4.551609905707915'>the</span>
<span class='rank-5 -5.170260790072973'>Republio</span>
<span class='rank6 6.129628052059067'>of</span>
<span class='rank21 21.233121605410794'>Hayti</span>
<span class='rank7 7.495719705861437'>by</span>
<span class='rank0 -0.2451656111325633'>George</span>
<span class='rank10 10.021448350169694'>V.</span>
<span class='rank-1 -0.5281890597046726'>Nash,</span>
<span class='rank4 3.522999256660679'>1903</span>
</br>
<span class='rank4 4.079395259471763'>PORT</span>
<span class='rank15 15.0908332066196'>MARGOT</span>
<span class='rank7 6.555712447369967'>TO</span>
<span class='rank22 22.325897378282733'>CORREIL,</span>
<span class='rank7 6.807446127280642'>AUG.</span>
</br>
<span class='rank6 5.910214491268059'>New</span>
<span class='rank5 5.027215308896533'>York</span>
<span class='rank3 2.5421264334187086'>Botanical</span>
<span class='rank3 3.451197890939337'>Garden</span>
</br>
<span class='rank0 0.0'>6</span>
<span class='rank0 0.0'>7</span>
<span class='rank0 0.0'>8</span>
<span class='rank0 0.0'>9</span>
<span class='rank6 5.886281793427337'>10</span>
<span class='rank0 0.0'>T</span>
<span class='rank0 0.0'>ã</span>
<span class='rank0 0.0'>v</span>
</br>
<span class='rank0 0.0'>?f</span>
<span class='rank5 5.380675333968457'>The</span>
<span class='rank6 5.910214491268059'>New</span>
<span class='rank5 5.027215308896533'>York</span>
<span class='rank4 4.050174224831018'>copyright</span>
<span class='rank2 1.7822710117187128'>reserved</span>
<span class='rank0 -0.3482453244774675'>botanical</span>
<span class='rank3 3.451197890939337'>Garden</span>
</br>
<span class='rank18 17.536343746729663'>1622564</span>
</br>
</br></br>
<strong>Legend - </strong>
Level of confidence that token is an accurately-transcribed word</br>
<span class='rank-13'> </span> extremely low
<span class='rank-7'> </span> very low
<span class='rank-1'> </span> low
<span class='rank0'> </span> undetermined
<span class='rank1'> </span> medium
<span class='rank6'> </span> high
<span class='rank16'> </span> very high</br>
</body>
</html>
| idigbio-citsci-hackathon/carrotFacetNgram | carrot2-webapp-3.8.1/herballsilvertrigram/1622564.txt.html | HTML | apache-2.0 | 2,953 |
/*
Copyright 2019 Google Inc.
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 { Map, Set } from 'immutable';
import React from 'react';
import { Link } from 'react-router-dom';
import { OpenInNew, PersonAdd } from '@material-ui/icons/';
import { IArticleModel, ICategoryModel, IUserModel, ModelId } from '../../../models';
import { Avatar, MagicTimestamp, PseudoAvatar } from '../../components';
import { COMMON_STYLES, IMAGE_BASE } from '../../stylesx';
import { css, stylesheet } from '../../utilx';
interface IModeratorsWidgetProps {
users: Map<string, IUserModel>;
moderatorIds: Array<ModelId>;
superModeratorIds: Array<ModelId>;
openSetModerators(): void;
}
export const MODERATOR_WIDGET_STYLES = stylesheet({
widget: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
},
});
export function ModeratorsWidget(props: IModeratorsWidgetProps) {
const { users, moderatorIds, superModeratorIds } = props;
let s = Set(moderatorIds);
if (superModeratorIds) {
s = s.merge(superModeratorIds);
}
const moderators = s.toArray().map((uid: string) => users.get(uid));
if (moderators.length === 0) {
return (
<div onClick={props.openSetModerators} {...css(MODERATOR_WIDGET_STYLES.widget)}>
<PseudoAvatar size={IMAGE_BASE}>
<PersonAdd/>
</PseudoAvatar>
</div>
);
}
if (moderators.length === 1) {
const u = moderators[0];
return (
<div onClick={props.openSetModerators} {...css(MODERATOR_WIDGET_STYLES.widget)}>
<Avatar target={u} size={IMAGE_BASE}/>
</div>
);
}
const ret = [];
let limit = moderators.length;
let extra = false;
if (limit > 4) {
limit = 3;
extra = true;
} else if (limit === 4) {
limit = 4;
}
for (let i = 0; i < limit; i++) {
ret.push(<Avatar target={moderators[i]} size={IMAGE_BASE / 2}/>);
}
if (extra) {
ret.push(<PseudoAvatar size={IMAGE_BASE / 2}>+{moderators.length - 3}</PseudoAvatar>);
}
return (
<div onClick={props.openSetModerators} {...css(MODERATOR_WIDGET_STYLES.widget)}>
{ret}
</div>
);
}
export const TITLE_CELL_STYLES = stylesheet({
superText: {
fontSize: '10px',
fontWeight: '600',
color: 'rgba(0,0,0,0.54)',
},
categoryLabel: {
textTransform: 'uppercase',
marginRight: '12px',
},
mainText: {
display: 'flex',
},
mainTextText: {
lineHeight: '20px',
},
mainTextLink: {
padding: '0 10px',
color: 'rgba(0,0,0,0.54)',
},
});
interface ITitleCellProps {
category?: ICategoryModel;
article: IArticleModel;
link: string;
}
export function TitleCell(props: ITitleCellProps) {
const {
category,
article,
link,
} = props;
const supertext = [];
if (category) {
supertext.push(<span key="label" {...css(TITLE_CELL_STYLES.categoryLabel)}>{category.label}</span>);
}
if (article.sourceCreatedAt) {
supertext.push((
<span key="timestamp">
<MagicTimestamp timestamp={article.sourceCreatedAt} inFuture={false}/>
</span>
));
}
return (
<>
{supertext.length > 0 && <div {...css(TITLE_CELL_STYLES.superText)}>{supertext}</div>}
<div {...css(TITLE_CELL_STYLES.mainText)}>
<div>
<Link to={link} {...css(COMMON_STYLES.cellLink, TITLE_CELL_STYLES.mainTextText)}>
{article.title}
</Link>
</div>
{article.url && (
<div {...css(TITLE_CELL_STYLES.mainTextLink)}>
<a key="link" href={article.url} target="_blank" {...css(COMMON_STYLES.cellLink)}>
<OpenInNew fontSize="small" />
</a>
</div>
)}
</div>
</>
);
}
| conversationai/conversationai-moderator | packages/frontend-web/src/app/scenes/Tables/components.tsx | TypeScript | apache-2.0 | 4,167 |
from capstone import *
from .architecture import Architecture
from avatar2.installer.config import GDB_X86, OPENOCD
class X86(Architecture):
get_gdb_executable = Architecture.resolve(GDB_X86)
get_oocd_executable = Architecture.resolve(OPENOCD)
qemu_name = 'i386'
gdb_name = 'i386'
registers = {'eax': 0,
'ecx': 1,
'edx': 2,
'ebx': 3,
'esp': 4,
'ebp': 5,
'esi': 6,
'edi': 7,
'eip': 8,
'pc': 8,
'eflags': 9,
'cs': 10,
'ss': 11,
'ds': 12,
'es': 13,
'fs': 14,
'gs': 15, }
special_registers = {
#SSE
'xmm0': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm0.v4_int32',
},
'xmm1': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm1.v4_int32',
},
'xmm2': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm2.v4_int32',
},
'xmm3': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm3.v4_int32',
},
'xmm4': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm4.v4_int32',
},
'xmm5': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm5.v4_int32',
},
'xmm6': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm6.v4_int32',
},
'xmm7': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm7.v4_int32',
},
'xmm8': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm8.v4_int32',
},
'xmm9': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm9.v4_int32',
},
'xmm10': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm10.v4_int32',
},
'xmm11': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm11.v4_int32',
},
'xmm12': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm12.v4_int32',
},
'xmm13': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm13.v4_int32',
},
'xmm14': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm14.v4_int32',
},
'xmm15': {'format': '{{{:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$xmm15.v4_int32',
},
#AVX
'ymm0': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm0.v8_int32',
},
'ymm1': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm1.v8_int32',
},
'ymm2': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm2.v8_int32',
},
'ymm3': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm3.v8_int32',
},
'ymm4': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm4.v8_int32',
},
'ymm5': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm5.v8_int32',
},
'ymm6': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm6.v8_int32',
},
'ymm7': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm7.v8_int32',
},
'ymm8': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm8.v8_int32',
},
'ymm9': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm9.v8_int32',
},
'ymm10': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm10.v8_int32',
},
'ymm11': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm11.v8_int32',
},
'ymm12': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm12.v8_int32',
},
'ymm13': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm13.v8_int32',
},
'ymm14': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm14.v8_int32',
},
'ymm15': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}',
'gdb_expression': '$ymm15.v8_int32',
},
}
sr_name = 'eflags'
unemulated_instructions = []
capstone_arch = CS_ARCH_X86
capstone_mode = CS_MODE_32
word_size = 32
class X86_64(X86):
qemu_name = 'x86_64'
gdb_name = 'i386:x86-64'
registers = {'rax': 0,
'rbx': 1,
'rcx': 2,
'rdx': 3,
'rsi': 4,
'rdi': 5,
'rbp': 6,
'rsp': 7,
'r8': 8,
'r9': 9,
'r10': 10,
'r11': 11,
'r12': 12,
'r13': 13,
'r14': 14,
'r15': 15,
'rip': 16,
'pc': 16,
'eflags': 17,
'cs': 18,
'ss': 19,
'ds': 20,
'es': 21,
'fs': 22,
'gs': 23,
}
capstone_mode = CS_MODE_64
unemulated_instructions = []
capstone_mode = CS_MODE_64
word_size = 64
| avatartwo/avatar2 | avatar2/archs/x86.py | Python | apache-2.0 | 6,401 |
# Elasticsearch 安装记录
## Elasticsearch 介绍
Elasticsearch是一个基于Java的实时分布式搜索和分析引擎,能够对数据进行实时处理、分析。<br>
本次安装的操作系统环境为**Ubuntu 16.04 64bit**,将按照[《Elasticsearch权威指南》](https://github.com/looly/elasticsearch-definitive-guide-cn)中的流程进行。
## Java环境
在终端输入
```sh
sudo apt-get install default-jre
```
安装最新版本的Java运行环境。安装结束后可输入
```sh
java -version
```
检查是否安装成功。如果安装成功,会返回Java的版本号,如1.8.0_131。<br><br>
*注:需要注意的是,如果Ubuntu的更新源选择不恰当,极有可能安装失败。aliyun的源实测可用,建议在安装前换源。*
## 运行Elasticsearch
### 方式一:通过下载安装包
从官方网站 https://www.elastic.co/downloads/elasticsearch 下载最新版本的Elasticsearch。<br><br>
拷贝tar包至工作目录后,输入
```sh
tar -xvf elasticsearch-$VERSION.tar.gz
```
解压文件,其中将$VERSION替换为当前版本号。<br><br>
输入
```sh
./elasticsearch-$VERSION/bin/elasticsearch
```
运行Elasticsearch。<br><br>
*注:如果需要在后台运行,添加命令行参数-d即可。*<br><br>
稍等片刻,运行成功会显示
```sh
[0] indices into cluster_state
```
### 方式二:通过Debian Package
部分操作与后续安装Kibana相同,执行一次即可。<br><br>
默认安装目录为 /usr/share/elasticsearch/。<br><br>
Import the Elasticsearch PGP Key
```sh
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
```
Installing from the APT repository
```sh
sudo apt-get install apt-transport-https
echo "deb https://artifacts.elastic.co/packages/5.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-5.x.list
```
Install the Elasticsearch Debian package
```sh
sudo apt-get update && sudo apt-get install elasticsearch
```
需要注意的是,此时不能以root权限直接运行可执行文件,而应通过服务启动:
```sh
service elasticsearch start
```
### 验证安装
此时另开启一个终端,输入
```sh
curl 'http://localhost:9200'
```
检验Elasticsearch是否运行,若正在运行则会返回(文本可能由于版本差异不同)
```json
{
"name" : "RcmBSMl",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "M6u8eyc8QF6cIAWOh0RkMQ",
"version" : {
"number" : "5.5.0",
"build_bash" : "260387d",
"build_date" : "2017-06-30T23:16:05.735Z",
"build_snapshot" : false,
"lucene_version" : "6.6.0"
},
"tagline" : "You Know, for Search"
}
```
## 运行Demo
Elasticsearch数据库可使用HTML的GET、PUT等方法访问和修改。
### PUT添加数据
```sh
curl -T $JSON_FILE "http://localhost:9200/$INDEX/$TYPE/$ID"
```
其中$JSON_FILE是json数据文件,$INDEX是索引名,$TYPE是类型名,$ID是记录编号。<br><br>
另外,若相同编号的记录已存在,PUT操作则会更新之。
### GET访问数据
```sh
curl -XGET "http://localhost:9200/$INDEX/$TYPE/$ID"
```
### GET无条件查询数据
```sh
curl -XGET "http://localhost:9200/$INDEX/$TYPE/_search"
```
该操作会列出同索引同类型的所有记录。
### GET条件查询数据
```sh
curl -XGET "http://localhost:9200/$INDEX/$TYPE/_search?q=$COND:$VALUE"
```
其中$COND是条件名,$VALUE是条件值,该操作会列出同索引同类型符合条件的记录。
### DELETE删除数据
```sh
curl -XDELETE "http://localhost:9200/$INDEX/$TYPE/$ID"
```
<br>
更多方法详见 [官方文档](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) 。
| WanQiyang/elasticsearch-setuplog | SetupLog.md | Markdown | apache-2.0 | 3,702 |
# Copyright (c) 2015 Intel Research and Development Ireland 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 instantiation_validation_benchmark as base
from experimental_framework import common
NUM_OF_NEIGHBORS = 'num_of_neighbours'
AMOUNT_OF_RAM = 'amount_of_ram'
NUMBER_OF_CORES = 'number_of_cores'
NETWORK_NAME = 'network'
SUBNET_NAME = 'subnet'
class InstantiationValidationNoisyNeighborsBenchmark(
base.InstantiationValidationBenchmark):
def __init__(self, name, params):
base.InstantiationValidationBenchmark.__init__(self, name, params)
if common.RELEASE == 'liberty':
temp_name = 'stress_workload_liberty.yaml'
else:
temp_name = 'stress_workload.yaml'
self.template_file = common.get_template_dir() + \
temp_name
self.stack_name = 'neighbour'
self.neighbor_stack_names = list()
def get_features(self):
features = super(InstantiationValidationNoisyNeighborsBenchmark,
self).get_features()
features['description'] = 'Instantiation Validation Benchmark ' \
'with noisy neghbors'
features['parameters'].append(NUM_OF_NEIGHBORS)
features['parameters'].append(AMOUNT_OF_RAM)
features['parameters'].append(NUMBER_OF_CORES)
features['parameters'].append(NETWORK_NAME)
features['parameters'].append(SUBNET_NAME)
features['allowed_values'][NUM_OF_NEIGHBORS] = \
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
features['allowed_values'][NUMBER_OF_CORES] = \
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
features['allowed_values'][AMOUNT_OF_RAM] = \
['256M', '1G', '2G', '3G', '4G', '5G', '6G', '7G', '8G', '9G',
'10G']
features['default_values'][NUM_OF_NEIGHBORS] = '1'
features['default_values'][NUMBER_OF_CORES] = '1'
features['default_values'][AMOUNT_OF_RAM] = '256M'
features['default_values'][NETWORK_NAME] = ''
features['default_values'][SUBNET_NAME] = ''
return features
def init(self):
super(InstantiationValidationNoisyNeighborsBenchmark, self).init()
common.replace_in_file(self.lua_file, 'local out_file = ""',
'local out_file = "' +
self.results_file + '"')
heat_param = dict()
heat_param['network'] = self.params[NETWORK_NAME]
heat_param['subnet'] = self.params[SUBNET_NAME]
heat_param['cores'] = self.params['number_of_cores']
heat_param['memory'] = self.params['amount_of_ram']
for i in range(0, int(self.params['num_of_neighbours'])):
stack_name = self.stack_name + str(i)
common.DEPLOYMENT_UNIT.deploy_heat_template(self.template_file,
stack_name,
heat_param)
self.neighbor_stack_names.append(stack_name)
def finalize(self):
common.replace_in_file(self.lua_file, 'local out_file = "' +
self.results_file + '"',
'local out_file = ""')
# destroy neighbor stacks
for stack_name in self.neighbor_stack_names:
common.DEPLOYMENT_UNIT.destroy_heat_template(stack_name)
self.neighbor_stack_names = list()
| dtudares/hello-world | yardstick/yardstick/vTC/apexlake/experimental_framework/benchmarks/instantiation_validation_noisy_neighbors_benchmark.py | Python | apache-2.0 | 3,974 |
package de.nl.moo.data.loader.systems;
import de.nl.moo.data.beans.systems.SystemsApplyerBean;
import de.nl.moo.data.beans.systems.SystemsBean;
import de.nl.moo.data.beans.systems.SystemsSystemBean;
import de.nl.moo.data.dao.GameBeanDAO;
import de.nl.moo.data.loader.AbstractBeanLoader;
import org.springframework.beans.factory.annotation.Autowired;
import javax.inject.Provider;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class SystemsBeanLoader extends AbstractBeanLoader<SystemsBean> {
@Autowired
private SystemsBean systemsBean = null;
@Autowired
private Provider<SystemsSystemBeanLoader> systemLoaderProvider = null;
@Autowired
private Provider<SystemsApplyerBeanLoader> applyerLoaderProvider = null;
public SystemsBeanLoader() {
super();
}
@Override
protected SystemsBean load(GameBeanDAO dao) {
List<SystemsApplyerBean> applyers = this.loadApplyers(dao);
this.systemsBean.setApplyers(applyers);
List<SystemsSystemBean> systems = this.loadSystems(dao);
this.systemsBean.setSystems(systems);
return this.systemsBean;
}
// ##############################################
private List<SystemsApplyerBean> loadApplyers(GameBeanDAO dao) {
Path file = dao.getFile();
Path parent = file.getParent();
List<String> paths = dao.getList("applyers");
List<SystemsApplyerBean> applyers = new ArrayList<>();
paths.stream()
.map(parent::resolve)
.map(this::loadApplyer)
.forEach(applyers::add);
return applyers;
}
private SystemsApplyerBean loadApplyer(Path path) {
SystemsApplyerBeanLoader beanLoader = this.applyerLoaderProvider.get();
SystemsApplyerBean applyerBean = beanLoader.load(path);
return applyerBean;
}
// ##############################################
private List<SystemsSystemBean> loadSystems(GameBeanDAO dao) {
Path file = dao.getFile();
Path parent = file.getParent();
List<String> paths = dao.getList("systems");
List<SystemsSystemBean> systems = new ArrayList<>();
paths.stream()
.map(parent::resolve)
.map(this::loadSystem)
.forEach(systems::add);
return systems;
}
private SystemsSystemBean loadSystem(Path path) {
SystemsSystemBeanLoader beanLoader = this.systemLoaderProvider.get();
SystemsSystemBean systemBean = beanLoader.load(path);
return systemBean;
}
}
| dayaftereh/master-of-orion | src/main/java/de/nl/moo/data/loader/systems/SystemsBeanLoader.java | Java | apache-2.0 | 2,608 |
package com.github.setial.intellijjavadocs.configuration.impl;
import com.github.setial.intellijjavadocs.configuration.JavaDocConfiguration;
import com.github.setial.intellijjavadocs.exception.SetupTemplateException;
import com.github.setial.intellijjavadocs.model.settings.JavaDocSettings;
import com.github.setial.intellijjavadocs.model.settings.Level;
import com.github.setial.intellijjavadocs.model.settings.Mode;
import com.github.setial.intellijjavadocs.model.settings.Visibility;
import com.github.setial.intellijjavadocs.template.DocTemplateManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Messages;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
import static com.github.setial.intellijjavadocs.configuration.JavaDocConfiguration.COMPONENT_CONFIG_PATH;
/**
* The type Java doc configuration impl.
*
* @author Sergey Timofiychuk
*/
@State(
name = JavaDocConfiguration.COMPONENT_NAME,
storages = {
@Storage(value = COMPONENT_CONFIG_PATH)
}
)
public class JavaDocConfigurationImpl implements JavaDocConfiguration, PersistentStateComponent<Element> {
public static final String JAVADOCS_PLUGIN_TITLE_MSG = "Javadocs plugin";
private static final Logger LOGGER = Logger.getInstance(JavaDocConfigurationImpl.class);
private JavaDocSettings settings;
private DocTemplateManager templateManager;
private boolean loadedStoredConfig = false;
/**
* Instantiates a new Java doc configuration object.
*/
public JavaDocConfigurationImpl() {
templateManager = ServiceManager.getService(DocTemplateManager.class);
initSettings();
}
@Override
public JavaDocSettings getConfiguration() {
return settings;
}
@Nullable
@Override
public Element getState() {
Element root = new Element("JAVA_DOC_SETTINGS_PLUGIN");
if (settings != null) {
settings.addToDom(root);
loadedStoredConfig = true;
}
return root;
}
@Override
public void loadState(@NotNull Element javaDocSettings) {
settings = new JavaDocSettings(javaDocSettings);
setupTemplates();
loadedStoredConfig = true;
}
private void initSettings() {
if (!loadedStoredConfig) {
// setup default values
settings = new JavaDocSettings();
Set<Level> levels = new HashSet<>();
levels.add(Level.TYPE);
levels.add(Level.METHOD);
levels.add(Level.FIELD);
Set<Visibility> visibilities = new HashSet<>();
visibilities.add(Visibility.PUBLIC);
visibilities.add(Visibility.PROTECTED);
visibilities.add(Visibility.DEFAULT);
settings.getGeneralSettings().setOverriddenMethods(false);
settings.getGeneralSettings().setSplittedClassName(true);
settings.getGeneralSettings().setMode(Mode.UPDATE);
settings.getGeneralSettings().setLevels(levels);
settings.getGeneralSettings().setVisibilities(visibilities);
settings.getTemplateSettings().setClassTemplates(templateManager.getClassTemplates());
settings.getTemplateSettings().setConstructorTemplates(templateManager.getConstructorTemplates());
settings.getTemplateSettings().setMethodTemplates(templateManager.getMethodTemplates());
settings.getTemplateSettings().setFieldTemplates(templateManager.getFieldTemplates());
}
}
@Override
public void setupTemplates() {
try {
templateManager.setClassTemplates(settings.getTemplateSettings().getClassTemplates());
templateManager.setConstructorTemplates(settings.getTemplateSettings().getConstructorTemplates());
templateManager.setMethodTemplates(settings.getTemplateSettings().getMethodTemplates());
templateManager.setFieldTemplates(settings.getTemplateSettings().getFieldTemplates());
} catch (SetupTemplateException e) {
LOGGER.error(e);
Messages.showErrorDialog("Javadocs plugin is not available, cause: " + e.getMessage(), JAVADOCS_PLUGIN_TITLE_MSG);
}
}
}
| setial/intellij-javadocs | src/main/java/com/github/setial/intellijjavadocs/configuration/impl/JavaDocConfigurationImpl.java | Java | apache-2.0 | 4,548 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keyword" content="">
<link rel="shortcut icon" href="/node-mongodb-native/3.1/img/favicon.png">
<title>APM</title>
<link rel="stylesheet" href="/node-mongodb-native/3.1/lib/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/lib/font-awesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/css/mongodb-docs.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/css/overrides.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/lib/highlight/styles/idea.css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/lib/bootstrap-toggle/bootstrap-toggle.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.1/css/java.css" type="text/css" />
</head>
<body>
<section id="container" class="">
<header id="header-db" class="row" role="navigation">
<div class="header-content">
<div class="toggle-nav pull-left">
<i class="fa fa-bars"></i>
<div class="icon-reorder tooltips" data-original-title="Toggle Navigation" data-placement="bottom"></div>
</div>
<div class="logo pull-left">
<a href="https://www.mongodb.com/">
<img src="http://mongodb.github.io/node-mongodb-native/img/logo-mongodb-header.png", alt="MongoDB.com" />
</a>
</div>
<div>
<div class="nav-items pull-right">
<a href="https://university.mongodb.com" data-toggle="tooltip" data-placement="bottom" title="Free Online Classes">MongoDB University</a>
<a href="http://www.mongodb.org/downloads" data-toggle="tooltip" data-placement="bottom" title="Download MongoDB">Downloads</a>
<a href="http://www.mongodb.org/get-involved" data-toggle="tooltip" data-placement="bottom" title="Get involved with MongoDB">Community</a>
<a href="http://docs.mongodb.org" data-toggle="tooltip" data-placement="bottom" title="The MongoDB Documentation">Docs</a>
<a href="http://blog.mongodb.org" data-toggle="tooltip" data-placement="bottom" title="The MongoDB Blog">Blog</a>
<div id="search">
<form method="get" action="//www.google.com/search" target="_blank">
<input type="text" name="searchQuery" size="20" value="" autocomplete="off" placeholder="Search docs">
<input type="hidden" name="site" value="/node-mongodb-native/3.1">
<input type="hidden" name="q" value="">
<label for="searchQuery"><i class="fa fa-search fa-1"></i></label>
</form>
</div>
</div>
</div>
</div>
</header>
<aside id="sidebar" class="sidebar">
<div class="ssidebar nav-collapse">
<div class="ssidebarwrapper">
<h3>
<a class="index-link" href="/node-mongodb-native/3.1/../">MongoDB Node.js Driver</a>
<a class="version pull-right" href="/node-mongodb-native/3.1">3.1</a>
</h3>
<ul class="sidebar-menu">
<li class="toctree-l1">
<a href="/node-mongodb-native/3.1/installation-guide/installation-guide/">
<i class='fa fa-puzzle-piece'></i>
Installation Guide
</a>
</li>
<li class="toctree-l1">
<a href="/node-mongodb-native/3.1/quick-start/quick-start/">
<i class='fa fa-road'></i>
Quick Start
</a>
</li>
<li class="toctree-l1 ">
<a href="/node-mongodb-native/3.1/tutorials/main/" class="">
<i class='fa fa-thumb-tack'></i>
<span>Tutorials</span>
<span class="menu-arrow fa fa-angle-right"></span>
</a>
<ul >
<li class="toctree-l2 ">
<a href="/node-mongodb-native/3.1/tutorials/connect/" class="">
<i class='fa'></i>
<span>Connect to MongoDB</span>
</a>
<ul >
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/tutorials/connect/authenticating/">
<i class='fa'></i>
Authentication
</a>
</li>
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/tutorials/connect/ssl/">
<i class='fa'></i>
SSL Settings
</a>
</li>
</ul>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/collations/">
<i class='fa'></i>
Collations
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/collections/">
<i class='fa'></i>
Collections
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/create-indexes/">
<i class='fa'></i>
Create Indexes
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/crud/">
<i class='fa'></i>
CRUD Operations
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/projections/">
<i class='fa'></i>
Projections
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/aggregation/">
<i class='fa'></i>
Aggregation
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/text-search/">
<i class='fa'></i>
Text Search
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/geospatial-search/">
<i class='fa'></i>
Geospatial Search
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/tutorials/commands/">
<i class='fa'></i>
Database Commands
</a>
</li>
<li class="toctree-l2 ">
<a href="/node-mongodb-native/3.1/tutorials/gridfs/" class="">
<i class='fa'></i>
<span>GridFS</span>
</a>
<ul >
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/tutorials/gridfs/streaming/">
<i class='fa'></i>
GridFS API
</a>
</li>
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/tutorials/gridfs/gridstore/">
<i class='fa'></i>
Legacy GridStore
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1 current">
<a href="/node-mongodb-native/3.1/reference/main/" class="">
<i class='fa fa-book'></i>
<span>Reference</span>
<span class="menu-arrow fa fa-angle-down"></span>
</a>
<ul class="current">
<li class="toctree-l2 ">
<a href="/node-mongodb-native/3.1/reference/connecting/" class="">
<i class='fa'></i>
<span>Connection Options</span>
</a>
<ul >
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/connecting/connection-settings/">
<i class='fa'></i>
Connection Settings
</a>
</li>
</ul>
</li>
<li class="toctree-l2 ">
<a href="/node-mongodb-native/3.1/reference/ecmascriptnext/" class="">
<i class='fa'></i>
<span>ECMAScript Next</span>
</a>
<ul >
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/ecmascriptnext/connecting/">
<i class='fa'></i>
Connecting
</a>
</li>
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/ecmascriptnext/crud/">
<i class='fa'></i>
CRUD Operations
</a>
</li>
</ul>
</li>
<li class="toctree-l2 current">
<a href="/node-mongodb-native/3.1/reference/management/" class="">
<i class='fa'></i>
<span>Management</span>
</a>
<ul class="current">
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/management/logging/">
<i class='fa'></i>
Logging
</a>
</li>
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/management/apm/">
<i class='fa'></i>
APM
</a>
</li>
<li class="toctree-l3">
<a href="/node-mongodb-native/3.1/reference/management/sdam-monitoring/">
<i class='fa'></i>
Topology Monitoring
</a>
</li>
</ul>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/reference/pool/">
<i class='fa'></i>
Pool Design
</a>
</li>
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/reference/faq/">
<i class='fa'></i>
Frequently Asked Questions
</a>
</li>
</ul>
</li>
<li class="toctree-l1 ">
<a href="/node-mongodb-native/3.1/upgrade-migration/main/" class="">
<i class='fa fa-cog'></i>
<span>Upgrade Guide</span>
<span class="menu-arrow fa fa-angle-right"></span>
</a>
<ul >
<li class="toctree-l2">
<a href="/node-mongodb-native/3.1/upgrade-migration/upgrading/">
<i class='fa fa-wrench'></i>
Upgrading to 2.x
</a>
</li>
</ul>
</li>
<li class="toctree-l1">
<a href="/node-mongodb-native/3.1/api">
<i class='fa fa-file-text-o'></i>
API Documentation
</a>
</li>
<li class="toctree-l1">
<a href="https://github.com/mongodb/node-mongodb-native">
<i class='fa fa-github'></i>
Source Code
</a>
</li>
<li class="toctree-l1">
<a href="/node-mongodb-native/3.1/issues-help/">
<i class='fa fa-life-ring'></i>
Issues & Help
</a>
</li>
<li class="toctree-l1">
<a href="https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge">
<img src='https://badges.gitter.im/Join Chat.svg'/>
</a>
</li>
</ul>
</div>
</div>
</aside>
<div class="option-popup closed hidden" id="optionsVersionsPopup">
<div class="option-header">
<i class="fa fa-gear"></i>
<span>OPTIONS</span>
<i class="fa fa-angle-up pull-right"></i>
</div>
<div class="option-body">
<ul>
<li>
<label>Version</label>
<div class="btn-group btn-group-xs pull-right">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select Version <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" id="optionsVersionsMenu">
</ul>
</div>
</li>
</ul>
</div>
</div>
<section id="main-content" class="content">
<section class="main-column pull-left">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="alert alert-info" role="alert">
Note: You are currently viewing version 3.1 of the Node.js driver documentation.
<a href="https://docs.mongodb.com/drivers/node">Click here</a> for the latest version.
</div>
<a class="edit-link" href="https://github.com/mongodb/node-mongodb-native/blob/3.1/docs/reference/content/reference/management/apm.md" target="_blank" title="Edit reference/management/apm.md on GitHub"><i class="fa fa-pencil-square-o"></i></a>
<div class="bc">
<ul>
<li><a href="/node-mongodb-native/3.1/reference/main/">Reference</a> <i class="fa fa-angle-right"></i></li>
<li><a href="/node-mongodb-native/3.1/reference/management/">Management</a> <i class="fa fa-angle-right"></i></li>
<li>APM</li>
</ul>
</div>
<h1 id="apm">APM</h1>
<p>Application Performance Monitoring support is a driver
feature that allows monitoring services to hook into the
driver in a forward compatible and stable way. The API is
not applied to the driver unless explicitly initialized to
avoid any performance penalties.</p>
<h2 id="api">API</h2>
<p>The following code example hooks into all the available features
of the APM API.</p>
<pre><code class="language-js">const listener = require('mongodb').instrument({
operationIdGenerator: {
operationId: 1,
next: function() {
return this.operationId++;
}
},
timestampGenerator: {
current: function() {
return new Date().getTime();
},
duration: function(start, end) {
return end - start;
}
}
}, function(err, instrumentations) {
// Instrument the driver
});
listener.on('started', function(event) {
// command start event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});
listener.on('succeeded', function(event) {
// command success event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});
listener.on('failed', function(event) {
// command failure event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});
</code></pre>
<p>There are two main aspects to the APM API. The first one is the command monitoring specification and the second one is the instrumentation method.</p>
<h2 id="command-monitoring">Command Monitoring</h2>
<p>Command monitoring is based on the cross-driver specification for MongoDB found in the Command monitoring <a href="https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst">specification</a>.</p>
<p>The Command monitoring specification is a low-level monitoring specification that sends a notification when a new command is executed against MongoDB and if it fails or succeeds. In most cases this is straightforward and you will receive a single start and either a success or failure event.</p>
<p>In this example, the user executes the <code>isMaster</code> command against the server and receives the following messages (full objects are abbreviated for simplicity’s sake). When the <code>isMaster</code> command starts execution we receive the following event (this result is from <code>JSON.stringify</code>; in the real event the connectionId is the actual connection object the command was executed against).</p>
<pre><code class="language-js">{
"command": {
"ismaster": true
},
"databaseName": "system",
"commandName": "ismaster",
"requestId": 7,
"operationId": 1,
"connectionId": {
"id": 8,
"host": "localhost",
"port": 27017
}
}
</code></pre>
<p><code>requestId</code> is the id used for the wire protocol message sent to MongoDB and allows you to correlate the commands executed on MongoDB with the commands from the driver.</p>
<p><code>operationId</code> is an id that is used to group commands into a single logical command execution. Use cases are queries and batch writes where a single logical operation might be executed as multiple commands to the server. For a query this might mean it gets executed as a <code>find</code> command and <em>n</em> number of <code>getMore</code> commands as well as a <code>killCursors</code> command. For bulk writes the logical grouping might contain <code>n</code> individual write operations. The goal of <code>operationId</code> is to allow APM providers to correlate the breakdown of a cursor or bulk operation with the method called by the user.</p>
<p>A typical example:</p>
<pre><code class="language-js">db.collection('data').find().batchSize(2).toArray(function(err, docs) {
});
</code></pre>
<p>That might be translated to <code>1</code> find, <code>n</code> getMores and <code>0|1</code> killCursors.</p>
<p>After the command executed successfully it sends the following result:</p>
<pre><code class="language-js">{
"duration": 0,
"commandName": "ismaster",
"requestId": 7,
"operationId": 1,
"connectionId": {
"id": 8,
"host": "localhost",
"port": 27017
},
"reply": {
"ismaster": true,
"maxBsonObjectSize": 16777216,
"maxMessageSizeBytes": 48000000,
"maxWriteBatchSize": 1000,
"localTime": "2015-08-04T10:26:01.445Z",
"maxWireVersion": 3,
"minWireVersion": 0,
"ok": 1
}
}
</code></pre>
<p>Notice that the <code>requestId</code> and <code>operationId</code> match up to the start message, allowing the user of the API to correlate the two events.</p>
<p>The next example shows a complete <code>find</code> operation that results in multiple <code>getMore</code> responses.</p>
<pre><code class="language-js">{
"command": {
"find": "apm_test_2",
"filter": {
"a": 1
},
"sort": {
"a": 1
},
"projection": {
"_id": 1,
"a": 1
},
"limit": 100,
"skip": 1,
"hint": {
"_id": 1
},
"batchSize": 2,
"comment": "some comment",
"maxTimeMS": 5000,
"noCursorTimeout": true
},
"databaseName": "integration_tests",
"commandName": "find",
"requestId": 44,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
}
}
{
"duration": 1,
"commandName": "find",
"requestId": 44,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
},
"reply": [
{
"_id": "55c096386e3b2283b70c294d",
"a": 1
},
{
"_id": "55c096386e3b2283b70c294e",
"a": 1
}
]
}
{
"command": {
"getMore": "104961726686",
"collection": "apm_test_2",
"batchSize": 2,
"maxTimeMS": 5000
},
"databaseName": "integration_tests",
"commandName": "getMore",
"requestId": 44,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
}
}
{
"duration": 1,
"commandName": "getMore",
"requestId": 44,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
},
"reply": [
{
"_id": "55c096386e3b2283b70c294f",
"a": 1
},
{
"_id": "55c096386e3b2283b70c2950",
"a": 1
}
]
}
{
"command": {
"getMore": "104961726686",
"collection": "apm_test_2",
"batchSize": 2,
"maxTimeMS": 5000
},
"databaseName": "integration_tests",
"commandName": "getMore",
"requestId": 45,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
}
}
{
"duration": 0,
"commandName": "getMore",
"requestId": 45,
"operationId": 39,
"connectionId": {
"id": 19,
"host": "localhost",
"port": 27017
},
"reply": [
{
"_id": "55c096386e3b2283b70c2951",
"a": 1
}
]
}
</code></pre>
<p><strong>Note:</strong> all the documents share the same <code>operationId</code>, allowing the
APM API user to correctly map the low level commands to the logical
command executed by the user (in this case <code>toArray</code> on a cursor).</p>
<h3 id="operationidgenerator">operationIdGenerator</h3>
<p>The <code>operationIdGenerator</code> option allows the API user to pass in a
custom <code>operationId</code> generator object. You can use this object to
synchronize internal request IDs in the APM client with the low-level
command monitoring API. This synchronization makes it possible to
associate the logical method called by the user’s code with the
low-level commands issued to MongoDB. This allows for a richer
APM experience and performance breakdown. Below is a simple
<code>operationIdGenerator</code> example.</p>
<pre><code class="language-js">const generator = {
operationId: 1,
next: function() {
return this.operationId++;
}
};
</code></pre>
<h3 id="timestampgenerator">timestampGenerator</h3>
<p>The <code>timestampGenerator</code> option lets the API user to override the method
used to timestamp the command monitoring events with a custom timestamp
type. The generator contains two methods. <code>current</code> returns the current
timestamp<code>and</code>duration<code>calculates the total operation duration
between the</code>start<code>and</code>end` time. Below is a simple generator example.</p>
<pre><code class="language-js">const generator = {
current: function() {
return new Date().getTime();
},
duration: function(start, end) {
return end - start;
}
}
</code></pre>
<h2 id="instrumentation">Instrumentation</h2>
<p>The <code>instrumentation</code> callback returns the instrumentation points in
the driver and associated metadata. In the following example, the
result shown is the result from performing <code>JSON.stringify</code>.</p>
<pre><code class="language-js">{
"name": "Gridstore",
"stream": true,
"instrumentations": [
{
"methods": [
"open",
"getc",
"puts",
"write",
"writeFile",
"close",
"unlink",
"readlines",
"rewind",
"read",
"tell",
"seek"
],
"options": {
"callback": true,
"promise": true
}
},
{
"methods": [
"eof"
],
"options": {
"callback": false,
"promise": false,
"returns": [
null
]
}
},
{
"methods": [
"stream"
],
"options": {
"callback": false,
"promise": false,
"returns": [
null
]
}
},
{
"methods": [
"destroy"
],
"options": {
"callback": false,
"promise": false
}
},
{
"methods": [
"chunkCollection",
"collection"
],
"options": {
"callback": true,
"promise": false,
"returns": [
null
]
}
},
{
"methods": [
"exist",
"list",
"read",
"readlines",
"unlink"
],
"options": {
"callback": true,
"promise": true,
"static": true
}
}
]
}
</code></pre>
<ul>
<li><code>name</code> the name of the class exposed for instrumentation.</li>
<li><code>stream</code> tells the user if the object can operate as a Node.js stream.</li>
<li><code>instrumentations</code> an array which contains all the methods available
for instrumentation. The methods are grouped
by method characteristics. All methods that support a callback as well
as a promise will be grouped in a single instrumentation. This
simplifies the code to perform the actual instrumentation.</li>
</ul>
<pre><code class="language-js">{
"methods": [
"open",
"getc",
"puts",
"write",
"writeFile",
"close",
"unlink",
"readlines",
"rewind",
"read",
"tell",
"seek"
],
"options": {
"callback": true,
"promise": true
}
}
</code></pre>
<p>The <code>methods</code> array contains all the methods that have the options
<code>callback=true</code> and <code>promise=true</code> for the GridStore prototype.
The available options are:</p>
<table>
<thead>
<tr>
<th>Options</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>callback</td>
<td align="left">The method supports a callback</td>
</tr>
<tr>
<td>promise</td>
<td align="left">The method can return a promise</td>
</tr>
<tr>
<td>static</td>
<td align="left">The method is a static method (not on the prototype)</td>
</tr>
<tr>
<td>returns</td>
<td align="left">The method can return one of the types in the array</td>
</tr>
</tbody>
</table>
<p>Below is a very basic instrumentation example.</p>
<pre><code class="language-js">const listener = require('../..').instrument(function(err, instrumentations) {
instrumentations.forEach(function(obj) {
const object = obj.obj;
// Iterate over all the methods that are just callback with no return
obj.instrumentations.forEach(function(instr) {
const options = instr.options;
if(options.callback
&& !options.returns && !options.static) {
// Method name
instr.methods.forEach(function(method) {
function applyMethod(_method) {
const func = object.prototype[_method];
overrides.push({
obj: object.prototype, method: _method, func: func
});
object.prototype[_method] = function() {
if(!methodsCalled[_method]) methodsCalled[_method] = 0;
methodsCalled[_method] = methodsCalled[_method] + 1;
const args = Array.prototype.slice.call(arguments, 0);
func.apply(this, args);
}
}
applyMethod(method);
});
}
});
});
});
</code></pre>
<p>This instrumentation only overrides methods that have callbacks and
ignores promises, so it’s not a complete solution, but shows how an
API user can structure code to tap into the exposed surface of the
driver.</p>
<div id="btnv">
<div class="pull-left">
<a class="navigation prev" href="/node-mongodb-native/3.1/reference/management/logging/">
<i class="fa fa-long-arrow-left"> </i> Logging
</a>
</div>
<div class="pull-right">
<a class="navigation next" href="/node-mongodb-native/3.1/reference/management/sdam-monitoring/">
Topology Monitoring <i class="fa fa-long-arrow-right"> </i>
</a>
</div>
</div>
</div>
<div class="right-column">
<div class="wrapper">
<div class="toc">
<span class="toc-header">On this page</span>
<nav id="TableOfContents">
<ul>
<li><a href="#apm">APM</a>
<ul>
<li><a href="#api">API</a></li>
<li><a href="#command-monitoring">Command Monitoring</a>
<ul>
<li><a href="#operationidgenerator">operationIdGenerator</a></li>
<li><a href="#timestampgenerator">timestampGenerator</a></li>
</ul></li>
<li><a href="#instrumentation">Instrumentation</a></li>
</ul></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
</section>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: "/node-mongodb-native/3.1",
VERSION: "3.1",
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="/node-mongodb-native/3.1/js/jquery.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/lib/bootstrap.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/js/navbar.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/lib/highlight/highlight.pack.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/js/scripts.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/lib/bootstrap-toggle/bootstrap-toggle.min.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/js/java.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.1/js/toggle-switch.js"></script>
<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-29229787-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| mongodb/node-mongodb-native | docs/3.1/reference/management/apm/index.html | HTML | apache-2.0 | 35,529 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins.newui;
import com.intellij.ide.IdeBundle;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author Alexander Lobas
*/
public class TagComponent extends LinkComponent {
private static final Color BACKGROUND = JBColor.namedColor("Plugins.tagBackground", new JBColor(0xEAEAEC, 0x4D4D4D));
private static final Color EAP_BACKGROUND = JBColor.namedColor("Plugins.eapTagBackground", new JBColor(0xF2D2CF, 0xF2D2CF));
private static final Color PAID_BACKGROUND = JBColor.namedColor("Plugins.paidTagBackground", new JBColor(0xD8EDF8, 0x3E505C));
private static final Color TRIAL_BACKGROUND = JBColor.namedColor("Plugins.trialTagBackground", new JBColor(0xDBE8DD, 0x345574E));
private static final Color FOREGROUND = JBColor.namedColor("Plugins.tagForeground", new JBColor(0x787878, 0x999999));
private Color myColor;
public TagComponent() {
setForeground(FOREGROUND);
setPaintUnderline(false);
setOpaque(false);
setBorder(JBUI.Borders.empty(1, 8));
}
public TagComponent(@NotNull @Nls String name) {
this();
setText(name);
}
@Override
public void setText(@NotNull @Nls String name) {
String tooltip = null;
myColor = BACKGROUND;
if (Tags.EAP.name().equals(name)) {
myColor = EAP_BACKGROUND;
tooltip = IdeBundle.message("tooltip.eap.plugin.version");
}
else if (Tags.Trial.name().equals(name) || Tags.Purchased.name().equals(name)) {
myColor = TRIAL_BACKGROUND;
}
else if (Tags.Paid.name().equals(name) || Tags.Freemium.name().equals(name)) {
myColor = PAID_BACKGROUND;
tooltip = IdeBundle.message("tooltip.paid.plugin");
}
super.setText(name);
setToolTipText(tooltip);
}
@Override
protected void paintComponent(Graphics g) {
//noinspection UseJBColor
g.setColor(myUnderline ? new Color(myColor.getRed(), myColor.getGreen(), myColor.getBlue(), 178) : myColor);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
@Override
protected boolean isInClickableArea(Point pt) {
return true;
}
} | JetBrains/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/newui/TagComponent.java | Java | apache-2.0 | 2,357 |
package esilegacy
/*
Gateway timeout model */
type GatewayTimeout struct {
/*
Gateway timeout message */
Error_ string `json:"error,omitempty"`
/*
number of seconds the request was given */
Timeout int32 `json:"timeout,omitempty"`
}
| antihax/mock-esi | legacy/go/model_gateway_timeout.go | GO | apache-2.0 | 242 |
/*
* Copyright 2013-2019 the original author or authors.
*
* 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
*
* https://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.
*/
package org.springframework.cloud.consul.discovery;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
public class ConsulCatalogWatchTests {
@Test
public void isRunningReportsCorrectly() {
ConsulDiscoveryProperties properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties()));
ConsulCatalogWatch watch = new ConsulCatalogWatch(properties, null) {
@Override
public void catalogServicesWatch() {
// do nothing
}
};
assertThat(watch.isRunning()).isFalse();
watch.start();
assertThat(watch.isRunning()).isTrue();
watch.stop();
assertThat(watch.isRunning()).isFalse();
}
}
| spring-cloud/spring-cloud-consul | spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchTests.java | Java | apache-2.0 | 1,452 |
// Copyright 2012 Google Inc. 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.
package com.google.collide.client.editor;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.document.anchor.AnchorType;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
import com.google.collide.shared.util.SortedList;
import com.google.collide.shared.util.SortedList.OneWayIntComparator;
/**
* This class takes care of mapping between the different coordinates used by
* the editor. The two supported systems are:
* <ul>
* <li>Offset (x,y) - in pixels, relative to the top left of line 0 in the
* current document.
* <li>Line (line, column) - the real line number and column, taking into
* account spacer objects in between lines. Lines and columns are 0-indexed.
* </ul>
*/
class CoordinateMap implements Document.LineListener {
interface DocumentSizeProvider {
float getEditorCharacterWidth();
int getEditorLineHeight();
void handleSpacerHeightChanged(Spacer spacer, int oldHeight);
}
private static class OffsetCache {
private static final SortedList.Comparator<OffsetCache> COMPARATOR =
new SortedList.Comparator<OffsetCache>() {
@Override
public int compare(OffsetCache a, OffsetCache b) {
return a.offset - b.offset;
}
};
private static final SortedList.OneWayIntComparator<OffsetCache> Y_OFFSET_ONE_WAY_COMPARATOR =
new SortedList.OneWayIntComparator<OffsetCache>() {
@Override
public int compareTo(OffsetCache s) {
return value - s.offset;
}
};
private static final SortedList.OneWayIntComparator<OffsetCache> LINE_NUMBER_ONE_WAY_COMPARATOR
= new SortedList.OneWayIntComparator<OffsetCache>() {
@Override
public int compareTo(OffsetCache s) {
return value - s.lineNumber;
}
};
private final int offset;
private final int height;
private final int lineNumber;
private OffsetCache(int offset, int lineNumber, int height) {
this.offset = offset;
this.height = height;
this.lineNumber = lineNumber;
}
}
private static final OffsetCache BEGINNING_EMPTY_OFFSET_CACHE = new OffsetCache(0, 0, 0);
private static final AnchorType SPACER_ANCHOR_TYPE = AnchorType.create(CoordinateMap.class,
"spacerAnchorType");
private static final Spacer.Comparator SPACER_COMPARATOR = new Spacer.Comparator();
private static final Spacer.OneWaySpacerComparator SPACER_ONE_WAY_COMPARATOR =
new Spacer.OneWaySpacerComparator();
/** Used by {@link #getPrecedingOffsetCache(int, int)} */
private static final int IGNORE = Integer.MIN_VALUE;
private Document document;
private DocumentSizeProvider documentSizeProvider;
/** List of offset cache items, sorted by the offset */
private SortedList<OffsetCache> offsetCache;
/**
* True if there is at least one spacer in the editor, false otherwise (false
* means a simple height / line height calculation can be used)
*/
private boolean requiresMapping;
/** Sorted by line number */
private SortedList<Spacer> spacers;
/** Summation of all spacers' heights */
private int totalSpacerHeight;
/** Remover for listener */
private Remover documentLineListenerRemover;
CoordinateMap(DocumentSizeProvider documentSizeProvider) {
this.documentSizeProvider = documentSizeProvider;
requiresMapping = false;
}
int convertYToLineNumber(int y) {
if (y < 0) {
return 0;
}
int lineHeight = documentSizeProvider.getEditorLineHeight();
if (!requiresMapping) {
return y / lineHeight;
}
OffsetCache precedingOffsetCache = getPrecedingOffsetCache(y, IGNORE);
int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height;
int lineNumberRelativeToOffsetCacheLine = (y - precedingOffsetCacheBottom) / lineHeight;
if (y < precedingOffsetCacheBottom) {
// y is inside the spacer
return precedingOffsetCache.lineNumber;
} else {
return precedingOffsetCache.lineNumber + lineNumberRelativeToOffsetCacheLine;
}
}
/**
* Returns the top of the given line.
*/
int convertLineNumberToY(int lineNumber) {
int lineHeight = documentSizeProvider.getEditorLineHeight();
if (!requiresMapping) {
return lineNumber * lineHeight;
}
OffsetCache precedingOffsetCache = getPrecedingOffsetCache(IGNORE, lineNumber);
int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height;
int offsetRelativeToOffsetCacheBottom =
(lineNumber - precedingOffsetCache.lineNumber) * lineHeight;
return precedingOffsetCacheBottom + offsetRelativeToOffsetCacheBottom;
}
/**
* Returns the first {@link OffsetCache} that is positioned less than or equal
* to {@code y} or {@code lineNumber}. This methods fills the
* {@link #offsetCache} if necessary ensuring the returned {@link OffsetCache}
* is up-to-date.
*
* @param y the y, or {@link #IGNORE} if looking up by {@code lineNumber}
* @param lineNumber the line number, or {@link #IGNORE} if looking up by
* {@code y}
*/
private OffsetCache getPrecedingOffsetCache(int y, int lineNumber) {
assert (y != IGNORE && lineNumber == IGNORE) || (lineNumber != IGNORE && y == IGNORE);
final int lineHeight = documentSizeProvider.getEditorLineHeight();
OffsetCache previousOffsetCache;
if (y != IGNORE) {
previousOffsetCache =
getCachedPrecedingOffsetCacheImpl(OffsetCache.Y_OFFSET_ONE_WAY_COMPARATOR, y);
} else {
previousOffsetCache =
getCachedPrecedingOffsetCacheImpl(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR, lineNumber);
}
if (previousOffsetCache == null) {
if (spacers.size() > 0 && spacers.get(0).getLineNumber() == 0) {
previousOffsetCache = createOffsetCache(0, 0, spacers.get(0).getHeight());
} else {
previousOffsetCache = BEGINNING_EMPTY_OFFSET_CACHE;
}
}
/*
* Optimization so the common case that the target has previously been
* computed requires no more computation
*/
int offsetCacheSize = offsetCache.size();
if (offsetCacheSize > 0
&& isTargetEarlierThanOffsetCache(y, lineNumber, offsetCache.get(offsetCacheSize - 1))) {
return previousOffsetCache;
}
// This will return this offset cache's matching spacer
int spacerPos = getPrecedingSpacerIndex(previousOffsetCache.lineNumber);
/*
* We want the spacer following this offset cache's spacer, or the first
* spacer if none were found
*/
spacerPos++;
for (int n = spacers.size(); spacerPos < n; spacerPos++) {
Spacer curSpacer = spacers.get(spacerPos);
int previousOffsetCacheBottom = previousOffsetCache.offset + previousOffsetCache.height;
int simpleLinesHeight =
(curSpacer.getLineNumber() - previousOffsetCache.lineNumber) * lineHeight;
if (simpleLinesHeight == 0) {
Log.warn(Spacer.class, "More than one spacer on line " + previousOffsetCache.lineNumber);
}
// Create an offset cache for this spacer
OffsetCache curOffsetCache =
createOffsetCache(previousOffsetCacheBottom + simpleLinesHeight,
curSpacer.getLineNumber(), curSpacer.getHeight());
if (isTargetEarlierThanOffsetCache(y, lineNumber, curOffsetCache)) {
return previousOffsetCache;
}
previousOffsetCache = curOffsetCache;
}
return previousOffsetCache;
}
/**
* Returns the {@link OffsetCache} instance in list that has the greatest
* value less than or equal to the given {@code value}. Returns null if there
* isn't one.
*
* This should only be used by {@link #getPrecedingOffsetCache(int, int)}.
*/
private OffsetCache getCachedPrecedingOffsetCacheImpl(
OneWayIntComparator<OffsetCache> comparator, int value) {
comparator.setValue(value);
int index = offsetCache.findInsertionIndex(comparator, false);
return index >= 0 ? offsetCache.get(index) : null;
}
private boolean isTargetEarlierThanOffsetCache(int y, int lineNumber, OffsetCache offsetCache) {
return ((y != IGNORE && y < offsetCache.offset) ||
(lineNumber != IGNORE && lineNumber < offsetCache.lineNumber));
}
private OffsetCache createOffsetCache(int offset, int lineNumber, int height) {
OffsetCache createdOffsetCache = new OffsetCache(offset, lineNumber, height);
offsetCache.add(createdOffsetCache);
return createdOffsetCache;
}
private int getPrecedingSpacerIndex(int lineNumber) {
SPACER_ONE_WAY_COMPARATOR.setValue(lineNumber);
return spacers.findInsertionIndex(SPACER_ONE_WAY_COMPARATOR, false);
}
/**
* Adds a spacer above the given lineInfo line with height heightPx and
* returns the created Spacer object.
*
* @param lineInfo the line before which the spacer will be inserted
* @param height the height in pixels of the spacer
*/
Spacer createSpacer(LineInfo lineInfo, int height, Buffer buffer, String cssClass) {
int lineNumber = lineInfo.number();
// create an anchor on the current line
Anchor anchor =
document.getAnchorManager().createAnchor(SPACER_ANCHOR_TYPE, lineInfo.line(), lineNumber,
AnchorManager.IGNORE_COLUMN);
anchor.setRemovalStrategy(RemovalStrategy.SHIFT);
// account for the height of the line the spacer is on
Spacer spacer = new Spacer(anchor, height, this, buffer, cssClass);
spacers.add(spacer);
totalSpacerHeight += height;
invalidateLineNumberAndFollowing(lineNumber);
requiresMapping = true;
return spacer;
}
boolean removeSpacer(Spacer spacer) {
int lineNumber = spacer.getLineNumber();
if (spacers.remove(spacer)) {
document.getAnchorManager().removeAnchor(spacer.getAnchor());
totalSpacerHeight -= spacer.getHeight();
invalidateLineNumberAndFollowing(lineNumber - 1);
updateRequiresMapping();
return true;
}
return false;
}
void handleDocumentChange(Document document) {
if (documentLineListenerRemover != null) {
documentLineListenerRemover.remove();
}
this.document = document;
spacers = new SortedList<Spacer>(SPACER_COMPARATOR);
offsetCache =
new SortedList<OffsetCache>(OffsetCache.COMPARATOR);
documentLineListenerRemover = document.getLineListenerRegistrar().add(this);
requiresMapping = false; // starts with no items in list
totalSpacerHeight = 0;
}
@Override
public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) {
invalidateLineNumberAndFollowing(lineNumber);
}
@Override
public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) {
invalidateLineNumberAndFollowing(lineNumber);
}
/**
* Call this after any line changes (adding/deleting lines, changing line
* heights). Only invalidate (delete) cache items >= lineNumber, don't
* recalculate.
*/
void invalidateLineNumberAndFollowing(int lineNumber) {
OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR.setValue(lineNumber);
int insertionIndex = offsetCache.findInsertionIndex(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR);
offsetCache.removeThisAndFollowing(insertionIndex);
}
private void updateRequiresMapping() {
// check to change active status
requiresMapping = spacers.size() > 0;
}
int getTotalSpacerHeight() {
return totalSpacerHeight;
}
void handleSpacerHeightChanged(Spacer spacer, int oldHeight) {
totalSpacerHeight -= oldHeight;
totalSpacerHeight += spacer.getHeight();
invalidateLineNumberAndFollowing(spacer.getLineNumber());
documentSizeProvider.handleSpacerHeightChanged(spacer, oldHeight);
}
}
| WeTheInternet/collide | client/src/main/java/com/google/collide/client/editor/CoordinateMap.java | Java | apache-2.0 | 12,795 |
package com.unitvectory.shak.jarvis.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.unitvectory.shak.jarvis.util.ResourceHelper;
/**
* Tests the SmartThingsPublish class
*
* @author Jared Hatfield
*
*/
public class SmartThingsPublishTest {
/**
* Test the parser being given a null value
*/
@Test
public void testNullStringParse() {
JsonPublishRequest myRequest = null;
SmartThingsPublish smart = new SmartThingsPublish(myRequest);
assertNotNull(smart);
assertNull(smart.getPublish());
assertNull(smart.getAuth());
assertNull(smart.getDate());
assertNull(smart.getDescription());
assertNull(smart.getDescriptionText());
assertNull(smart.getDeviceId());
assertNull(smart.getHubId());
assertNull(smart.getId());
assertNull(smart.getLocationId());
assertNull(smart.getName());
assertNull(smart.getSource());
assertNull(smart.getUnit());
assertNull(smart.getValue());
}
/**
* Test the parser when things go perfectly.
*/
@Test
public void testValidParse() {
// Load the test JSON
String json = ResourceHelper.load("/messagebody.json");
assertNotNull(json);
assertTrue(json.length() > 0);
// Create the object
JsonPublishRequest request = new JsonPublishRequest(json);
assertNotNull(request);
assertTrue(request.isValid());
assertNotNull(request.getData());
// Create the SmartThingsPublish
SmartThingsPublish smart = new SmartThingsPublish(request);
assertNotNull(smart);
assertEquals("foobar", smart.getAuth());
assertEquals("2013-12-30T16:03:08.224Z", smart.getDate());
assertEquals(
"raw:08EF170A59FF, dni:08EF, battery:17, batteryDivisor:0A, rssi:59, lqi:FF",
smart.getDescription());
assertEquals("Sensor was -39 dBm", smart.getDescriptionText());
assertEquals("2fffffff-fffff-ffff-ffff-fffffffffff",
smart.getDeviceId());
assertEquals("3fffffff-fffff-ffff-ffff-fffffffffff", smart.getHubId());
assertEquals("1fffffff-fffff-ffff-ffff-fffffffffff", smart.getId());
assertEquals("4fffffff-fffff-ffff-ffff-fffffffffff",
smart.getLocationId());
assertEquals("rssi", smart.getName());
assertEquals("DEVICE", smart.getSource());
assertEquals("dBm", smart.getUnit());
assertEquals("-39", smart.getValue());
}
}
| JaredHatfield/shak-jarvis | src/test/java/com/unitvectory/shak/jarvis/model/SmartThingsPublishTest.java | Java | apache-2.0 | 2,402 |
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2015 wcm.io
* %%
* 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.
* #L%
*/
package io.wcm.devops.conga.plugins.sling.validator;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.wcm.devops.conga.generator.spi.ValidationException;
import io.wcm.devops.conga.generator.spi.ValidatorPlugin;
import io.wcm.devops.conga.generator.spi.context.FileContext;
import io.wcm.devops.conga.generator.util.PluginManagerImpl;
public class ProvisioningValidatorTest {
private ValidatorPlugin underTest;
@BeforeEach
public void setUp() {
underTest = new PluginManagerImpl().get(ProvisioningValidator.NAME, ValidatorPlugin.class);
}
@Test
public void testValid() throws Exception {
File file = new File(getClass().getResource("/validProvisioning.txt").toURI());
FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8);
assertTrue(underTest.accepts(fileContext, null));
underTest.apply(fileContext, null);
}
@Test
public void testInvalid() throws Exception {
File file = new File(getClass().getResource("/invalidProvisioning.txt").toURI());
FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8);
assertTrue(underTest.accepts(fileContext, null));
assertThrows(ValidationException.class, () -> {
underTest.apply(fileContext, null);
});
}
@Test
public void testInvalidFileExtension() throws Exception {
File file = new File(getClass().getResource("/noProvisioning.txt").toURI());
FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8);
assertFalse(underTest.accepts(fileContext, null));
}
}
| wcm-io-devops/wcm-io-devops-conga-sling-plugin | conga-sling-plugin/src/test/java/io/wcm/devops/conga/plugins/sling/validator/ProvisioningValidatorTest.java | Java | apache-2.0 | 2,492 |
project-meet
============
| kanme818/meet | README.md | Markdown | apache-2.0 | 26 |
package org.targettest.org.apache.lucene.store;
/**
* 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.
*/
import java.io.IOException;
import java.io.Closeable;
import java.util.Map;
import java.util.HashMap;
/** Abstract base class for input from a file in a {@link Directory}. A
* random-access input stream. Used for all Lucene index input operations.
* @see Directory
*/
public abstract class IndexInput implements Cloneable,Closeable {
private boolean preUTF8Strings; // true if we are reading old (modified UTF8) string format
/** Reads and returns a single byte.
* @see IndexOutput#writeByte(byte)
*/
public abstract byte readByte() throws IOException;
/** Reads a specified number of bytes into an array at the specified offset.
* @param b the array to read bytes into
* @param offset the offset in the array to start storing bytes
* @param len the number of bytes to read
* @see IndexOutput#writeBytes(byte[],int)
*/
public abstract void readBytes(byte[] b, int offset, int len)
throws IOException;
/** Reads a specified number of bytes into an array at the
* specified offset with control over whether the read
* should be buffered (callers who have their own buffer
* should pass in "false" for useBuffer). Currently only
* {@link BufferedIndexInput} respects this parameter.
* @param b the array to read bytes into
* @param offset the offset in the array to start storing bytes
* @param len the number of bytes to read
* @param useBuffer set to false if the caller will handle
* buffering.
* @see IndexOutput#writeBytes(byte[],int)
*/
public void readBytes(byte[] b, int offset, int len, boolean useBuffer)
throws IOException
{
// Default to ignoring useBuffer entirely
readBytes(b, offset, len);
}
/** Reads four bytes and returns an int.
* @see IndexOutput#writeInt(int)
*/
public int readInt() throws IOException {
return ((readByte() & 0xFF) << 24) | ((readByte() & 0xFF) << 16)
| ((readByte() & 0xFF) << 8) | (readByte() & 0xFF);
}
/** Reads an int stored in variable-length format. Reads between one and
* five bytes. Smaller values take fewer bytes. Negative numbers are not
* supported.
* @see IndexOutput#writeVInt(int)
*/
public int readVInt() throws IOException {
byte b = readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = readByte();
i |= (b & 0x7F) << shift;
}
return i;
}
/** Reads eight bytes and returns a long.
* @see IndexOutput#writeLong(long)
*/
public long readLong() throws IOException {
return (((long)readInt()) << 32) | (readInt() & 0xFFFFFFFFL);
}
/** Reads a long stored in variable-length format. Reads between one and
* nine bytes. Smaller values take fewer bytes. Negative numbers are not
* supported. */
public long readVLong() throws IOException {
byte b = readByte();
long i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = readByte();
i |= (b & 0x7FL) << shift;
}
return i;
}
/** Call this if readString should read characters stored
* in the old modified UTF8 format (length in java chars
* and java's modified UTF8 encoding). This is used for
* indices written pre-2.4 See LUCENE-510 for details. */
public void setModifiedUTF8StringsMode() {
preUTF8Strings = true;
}
/** Reads a string.
* @see IndexOutput#writeString(String)
*/
public String readString() throws IOException {
if (preUTF8Strings)
return readModifiedUTF8String();
int length = readVInt();
final byte[] bytes = new byte[length];
readBytes(bytes, 0, length);
return new String(bytes, 0, length, "UTF-8");
}
private String readModifiedUTF8String() throws IOException {
int length = readVInt();
final char[] chars = new char[length];
readChars(chars, 0, length);
return new String(chars, 0, length);
}
/** Reads Lucene's old "modified UTF-8" encoded
* characters into an array.
* @param buffer the array to read characters into
* @param start the offset in the array to start storing characters
* @param length the number of characters to read
* @see IndexOutput#writeChars(String,int,int)
* @deprecated -- please use readString or readBytes
* instead, and construct the string
* from those utf8 bytes
*/
public void readChars(char[] buffer, int start, int length)
throws IOException {
final int end = start + length;
for (int i = start; i < end; i++) {
byte b = readByte();
if ((b & 0x80) == 0)
buffer[i] = (char)(b & 0x7F);
else if ((b & 0xE0) != 0xE0) {
buffer[i] = (char)(((b & 0x1F) << 6)
| (readByte() & 0x3F));
} else
buffer[i] = (char)(((b & 0x0F) << 12)
| ((readByte() & 0x3F) << 6)
| (readByte() & 0x3F));
}
}
/**
* Expert
*
* Similar to {@link #readChars(char[], int, int)} but does not do any conversion operations on the bytes it is reading in. It still
* has to invoke {@link #readByte()} just as {@link #readChars(char[], int, int)} does, but it does not need a buffer to store anything
* and it does not have to do any of the bitwise operations, since we don't actually care what is in the byte except to determine
* how many more bytes to read
* @param length The number of chars to read
* @deprecated this method operates on old "modified utf8" encoded
* strings
*/
public void skipChars(int length) throws IOException{
for (int i = 0; i < length; i++) {
byte b = readByte();
if ((b & 0x80) == 0){
//do nothing, we only need one byte
}
else if ((b & 0xE0) != 0xE0) {
readByte();//read an additional byte
} else{
//read two additional bytes.
readByte();
readByte();
}
}
}
/** Closes the stream to further operations. */
public abstract void close() throws IOException;
/** Returns the current position in this file, where the next read will
* occur.
* @see #seek(long)
*/
public abstract long getFilePointer();
/** Sets current position in this file, where the next read will occur.
* @see #getFilePointer()
*/
public abstract void seek(long pos) throws IOException;
/** The number of bytes in the file. */
public abstract long length();
/** Returns a clone of this stream.
*
* <p>Clones of a stream access the same data, and are positioned at the same
* point as the stream they were cloned from.
*
* <p>Expert: Subclasses must ensure that clones may be positioned at
* different points in the input from each other and from the stream they
* were cloned from.
*/
@Override
public Object clone() {
IndexInput clone = null;
try {
clone = (IndexInput)super.clone();
} catch (CloneNotSupportedException e) {}
return clone;
}
public Map<String,String> readStringStringMap() throws IOException {
final Map<String,String> map = new HashMap<String,String>();
final int count = readInt();
for(int i=0;i<count;i++) {
final String key = readString();
final String val = readString();
map.put(key, val);
}
return map;
}
}
| chrishumphreys/provocateur | provocateur-thirdparty/src/main/java/org/targettest/org/apache/lucene/store/IndexInput.java | Java | apache-2.0 | 8,089 |
# ExportHistoryResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**count** | **Long** | | [optional]
**data** | [**ExportDataArray**](ExportDataArray.md) | | [optional]
**offset** | **Long** | | [optional]
**total** | **Long** | | [optional]
| artikcloud/artikcloud-java | docs/ExportHistoryResponse.md | Markdown | apache-2.0 | 323 |
<!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.6.0_31) on Mon Oct 01 00:28:16 PDT 2012 -->
<TITLE>
org.apache.hadoop.metrics.file (Hadoop 1.0.3.16 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-01">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../org/apache/hadoop/metrics/file/package-summary.html" target="classFrame">org.apache.hadoop.metrics.file</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="FileContext.html" title="class in org.apache.hadoop.metrics.file" target="classFrame">FileContext</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| davidl1/hortonworks-extension | docs/api/org/apache/hadoop/metrics/file/package-frame.html | HTML | apache-2.0 | 940 |
## Copyright 2022 Google LLC
##
## 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
##
## https://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.
"""Sends a text mesage to the user with a suggestion action to dial a phone number.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action
This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""
import uuid
from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials
# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_service_account_key,
scopes=['https://www.googleapis.com/auth/businessmessages'])
client = bm_client.BusinessmessagesV1(credentials=credentials)
representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT
else:
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN
# Create a text message with a dial action and fallback text
message = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BusinessMessagesRepresentative(
representativeType=representative_type
),
text='Contact support for help with this issue.',
fallback='Give us a call at +12223334444.',
suggestions=[
BusinessMessagesSuggestion(
action=BusinessMessagesSuggestedAction(
text='Call support',
postbackData='call-support',
dialAction=BusinessMessagesDialAction(
phoneNumber='+12223334444'))
),
])
# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
businessMessagesMessage=message,
parent='conversations/' + conversation_id)
# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
client=client).Create(request=create_request)
| google-business-communications/bm-snippets-python | send-message-suggested-action-dial.py | Python | apache-2.0 | 3,227 |
<?php
/**
* Skeleton subclass for representing a row from the 'data2010' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.fbapp
*/
class Data2010 extends BaseData2010
{
}
| royrusso/fishbase | classes/fbapp/Data2010.php | PHP | apache-2.0 | 370 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.08.19 at 01:05:06 PM PDT
//
package com.google.api.ads.adwords.lib.jaxb.v201509;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SortOrder.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SortOrder">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ASCENDING"/>
* <enumeration value="DESCENDING"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SortOrder")
@XmlEnum
public enum SortOrder {
ASCENDING,
DESCENDING;
public String value() {
return name();
}
public static SortOrder fromValue(String v) {
return valueOf(v);
}
}
| gawkermedia/googleads-java-lib | modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/jaxb/v201509/SortOrder.java | Java | apache-2.0 | 1,139 |
---
layout: post
title: Some sites to place holder your site
date: 2016-10-10
categories: front-end skills
tags: front-end skills
---
* content
{:toc}
| mushroommie/try-for-github-pages | _posts/2016-10-10-Some sites to placeholder your site.md | Markdown | apache-2.0 | 154 |
package ru.job4j;
import org.junit.Test;
import java.util.*;
/**
* Класс для тестирования.
* @author agavrikov
* @since 13.07.2017
* @version 1
*/
public class TestTimeCollectionTest {
/**
* Тестирование метода добавления.
*/
@Test
public void add() {
TestTimeCollection methods = new TestTimeCollection();
List<String> linkedList = new LinkedList<String>();
long timeStart = new Date().getTime();
long timeEnd = methods.add(linkedList, 1000000);
System.out.println(timeEnd - timeStart);
List<String> arrayList = new ArrayList<String>();
timeStart = new Date().getTime();
timeEnd = methods.add(arrayList, 1000000);
System.out.println(timeEnd - timeStart);
Set<String> treeSet = new TreeSet<String>();
timeStart = new Date().getTime();
timeEnd = methods.add(treeSet, 1000000);
System.out.println(timeEnd - timeStart);
}
/**
* Тестирование метода удаления.
*/
@Test
public void delete() {
TestTimeCollection methods = new TestTimeCollection();
List<String> linkedList = new LinkedList<String>();
methods.add(linkedList, 100000);
long timeStart = new Date().getTime();
long timeEnd = methods.delete(linkedList, 10000);
System.out.println(timeEnd - timeStart);
List<String> arrayList = new ArrayList<String>();
methods.add(arrayList, 100000);
timeStart = new Date().getTime();
timeEnd = methods.delete(arrayList, 10000);
System.out.println(timeEnd - timeStart);
Set<String> treeSet = new TreeSet<String>();
methods.add(treeSet, 100000);
timeStart = new Date().getTime();
timeEnd = methods.delete(treeSet, 10000);
System.out.println(timeEnd - timeStart);
}
} | AntonGavr92/agavrikov | chapter_003/src/test/java/ru/job4j/TestTimeCollectionTest.java | Java | apache-2.0 | 1,926 |
package tinymonkeys.vue;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
* Classe du panneau de la carte.
*
* @version 1.0
* @author Camille Constant
*
*/
public class VueCarte extends JPanel {
/**
* UID auto-généré.
*/
private static final long serialVersionUID = 4884966649331011259L;
/**
* Rapport entre la taille de la carte et la taille de l'écran.
*/
private static final double RAPPORT_ECRAN = 0.75;
/**
* Constante permettant de placer un objet à la moitié de l'écran.
*/
private static final int DIVISEUR_MILIEU = 2;
/**
* Constante permettant de placer un objet au quart de l'écran.
*/
private static final int DIVISEUR_QUART = 4;
/**
* Constante indiquant la couleur des cases représentant la mer.
*/
private static final Color OCEAN = new Color(0, 120, 220);
/**
* Taille de la case en nombre de pixels.
*/
private int tailleCase;
/**
* La coordonnee en abscisse du coin supérieur gauche de la grille.
*/
private int xGrille;
/**
* La coordonnee en ordonnée du coin supérieur gauche de la grille.
*/
private int yGrille;
/**
* Largeur de l'ecran en nombre de pixels.
*/
private final int largeurEcran;
/**
* Hauteur de l'ecran en nombre de pixels.
*/
private final int hauteurEcran;
/**
* Largeur de la grille en nombre de cases.
*/
private int largeurGrille;
/**
* Hauteur de la grille en nombre de cases.
*/
private int hauteurGrille;
/**
* La carte.
*/
private int[][] carte;
/**
* Constructeur de la vue de la carte.
*
* @param largeurEcran largeur de l'ecran en nombre de pixels.
* @param hauteurEcran hauteur de l'ecran en nombre de pixels.
* @param carte la carte a dessiner
*/
public VueCarte(int largeurEcran, int hauteurEcran, int[][] carte) {
super();
this.largeurEcran = largeurEcran;
this.hauteurEcran = hauteurEcran;
this.largeurGrille = carte.length;
this.hauteurGrille = carte[0].length;
this.copieCarte(carte);
this.placementGrille();
this.setBounds(this.xGrille, this.yGrille, this.largeurGrille
* this.tailleCase + 1, this.hauteurGrille * this.tailleCase + 1);
this.setOpaque(false);
}
/**
* Dessine la carte de l'ile avec la grille.
*
* @param g le graphique dans lequel dessiner.
*/
public final void paintComponent(Graphics g) {
super.paintComponent(g);
this.dessineIle(g);
this.dessineGrille(g);
}
/**
* Place la carte au centre de l'écran.
*/
private void placementGrille() {
final int diviseurLargeur;
final int diviseurHauteur;
final int largeurCase = (int) ((this.largeurEcran * RAPPORT_ECRAN) / this.largeurGrille);
final int hauteurCase = (int) ((this.hauteurEcran * RAPPORT_ECRAN) / this.hauteurGrille);
if (largeurCase < hauteurCase) {
this.tailleCase = largeurCase;
diviseurLargeur = DIVISEUR_QUART;
diviseurHauteur = DIVISEUR_MILIEU;
} else {
this.tailleCase = hauteurCase;
diviseurLargeur = DIVISEUR_MILIEU;
diviseurHauteur = DIVISEUR_QUART;
}
this.xGrille = (int) ((this.largeurEcran - (this.tailleCase * this.largeurGrille)) / diviseurLargeur);
this.yGrille = (int) ((this.hauteurEcran - (this.tailleCase * this.hauteurGrille)) / diviseurHauteur);
}
/**
* Dessine la grille.
*
* @param g le graphique dans lequel dessiner.
*/
public void dessineGrille(Graphics g) {
// La grille apparait en noir.
g.setColor(Color.BLACK);
// colonnes
for (int i = 0; i <= (this.tailleCase * this.largeurGrille); i += this.tailleCase) {
g.drawLine(i, 0, i, this.tailleCase * this.hauteurGrille);
}
// lignes
for (int j = 0; j <= this.tailleCase * this.hauteurGrille; j += this.tailleCase) {
g.drawLine(0, j, this.tailleCase * this.largeurGrille, j);
}
}
/**
* Dessine l'ile.
*
* @param g le graphique dans lequel dessiner.
*/
public final void dessineIle(Graphics g) {
int i = -1;
while (++i < this.largeurGrille) {
int j = -1;
while (++j < this.hauteurGrille) {
// Si la case est de type mer.
if (this.carte[i][j] == 0) {
g.setColor(OCEAN);
g.fillRect(i * this.tailleCase, j * this.tailleCase,
this.tailleCase, this.tailleCase);
}
// Coloration inutile pour les cases terre.
}
}
}
/**
* Modifie la carte de l'ile.
*
* @param carte la nouvelle carte.
*/
public final void setVueCarte(int[][] carte) {
this.largeurGrille = carte.length;
this.hauteurGrille = carte[0].length;
this.copieCarte(carte);
this.placementGrille();
this.setBounds(this.xGrille, this.yGrille, this.largeurGrille
* this.tailleCase + 1, this.hauteurGrille * this.tailleCase + 1);
this.setOpaque(false);
}
/**
* Accesseur en lecture de la taille d'une case.
*
* @return la taille d'une case.
*/
public final int getTailleCase() {
return this.tailleCase;
}
/**
* Accesseur en lecture de l'abscisse de la grille.
*
* @return l'abscisse de la grille.
*/
public final int getXGrille() {
return this.xGrille;
}
/**
* Accesseur en lecture de l'ordonnee de la grille.
*
* @return l'ordonnee de la grille.
*/
public final int getYGrille() {
return this.yGrille;
}
/**
* Recopie de la carte dans l'attribut carte.
*
* @param carte la carte a copier.
*/
private void copieCarte(int[][] carte) {
this.carte = new int[carte.length][carte[0].length];
int i = -1;
while (++i < carte.length) {
int j = -1;
while(++j < carte[0].length) {
this.carte[i][j] = carte[i][j];
}
}
}
}
| afraisse/TinyMonkey | src/tinymonkeys/vue/VueCarte.java | Java | apache-2.0 | 5,524 |
package org.sagebionetworks.auth.services;
import org.sagebionetworks.repo.manager.AuthenticationManager;
import org.sagebionetworks.repo.manager.MessageManager;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.authentication.PersonalAccessTokenManager;
import org.sagebionetworks.repo.manager.oauth.AliasAndType;
import org.sagebionetworks.repo.manager.oauth.OAuthManager;
import org.sagebionetworks.repo.manager.oauth.OpenIDConnectManager;
import org.sagebionetworks.repo.model.AuthorizationUtils;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.auth.AccessToken;
import org.sagebionetworks.repo.model.auth.AccessTokenGenerationRequest;
import org.sagebionetworks.repo.model.auth.AccessTokenGenerationResponse;
import org.sagebionetworks.repo.model.auth.AccessTokenRecord;
import org.sagebionetworks.repo.model.auth.AccessTokenRecordList;
import org.sagebionetworks.repo.model.auth.AuthenticatedOn;
import org.sagebionetworks.repo.model.auth.ChangePasswordInterface;
import org.sagebionetworks.repo.model.auth.LoginRequest;
import org.sagebionetworks.repo.model.auth.LoginResponse;
import org.sagebionetworks.repo.model.auth.NewUser;
import org.sagebionetworks.repo.model.auth.PasswordResetSignedToken;
import org.sagebionetworks.repo.model.oauth.OAuthAccountCreationRequest;
import org.sagebionetworks.repo.model.oauth.OAuthProvider;
import org.sagebionetworks.repo.model.oauth.OAuthUrlRequest;
import org.sagebionetworks.repo.model.oauth.OAuthUrlResponse;
import org.sagebionetworks.repo.model.oauth.OAuthValidationRequest;
import org.sagebionetworks.repo.model.oauth.ProvidedUserInfo;
import org.sagebionetworks.repo.model.principal.AliasType;
import org.sagebionetworks.repo.model.principal.PrincipalAlias;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
@Autowired
private UserManager userManager;
@Autowired
private AuthenticationManager authManager;
@Autowired
private OAuthManager oauthManager;
@Autowired
private OpenIDConnectManager oidcManager;
@Autowired
private MessageManager messageManager;
@Autowired
private PersonalAccessTokenManager personalAccessTokenManager;
@WriteTransaction
@Override
public void changePassword(ChangePasswordInterface request) throws NotFoundException {
final long userId = authManager.changePassword(request);
messageManager.sendPasswordChangeConfirmationEmail(userId);
}
@Override
@WriteTransaction
public void signTermsOfUse(AccessToken accessToken) throws NotFoundException {
ValidateArgument.required(accessToken, "Access token");
ValidateArgument.required(accessToken.getAccessToken(), "Access token contents");
Long principalId = Long.parseLong(oidcManager.validateAccessToken(accessToken.getAccessToken()));
// Save the state of acceptance
authManager.setTermsOfUseAcceptance(principalId, true);
}
@Override
public String getSecretKey(Long principalId) throws NotFoundException {
return authManager.getSecretKey(principalId);
}
@Override
@WriteTransaction
public void deleteSecretKey(Long principalId) throws NotFoundException {
authManager.changeSecretKey(principalId);
}
@Override
public boolean hasUserAcceptedTermsOfUse(Long userId) throws NotFoundException {
return authManager.hasUserAcceptedTermsOfUse(userId);
}
@Override
public void sendPasswordResetEmail(String passwordResetUrlPrefix, String usernameOrEmail) {
try {
PrincipalAlias principalAlias = userManager.lookupUserByUsernameOrEmail(usernameOrEmail);
PasswordResetSignedToken passwordRestToken = authManager.createPasswordResetToken(principalAlias.getPrincipalId());
messageManager.sendNewPasswordResetEmail(passwordResetUrlPrefix, passwordRestToken, principalAlias);
} catch (NotFoundException e) {
// should not indicate that a email/user could not be found
}
}
@Override
public OAuthUrlResponse getOAuthAuthenticationUrl(OAuthUrlRequest request) {
String url = oauthManager.getAuthorizationUrl(request.getProvider(), request.getRedirectUrl(), request.getState());
OAuthUrlResponse response = new OAuthUrlResponse();
response.setAuthorizationUrl(url);
return response;
}
@Override
public LoginResponse validateOAuthAuthenticationCodeAndLogin(
OAuthValidationRequest request, String tokenIssuer) throws NotFoundException {
// Use the authentication code to lookup the user's information.
ProvidedUserInfo providedInfo = oauthManager.validateUserWithProvider(
request.getProvider(), request.getAuthenticationCode(), request.getRedirectUrl());
if(providedInfo.getUsersVerifiedEmail() == null){
throw new IllegalArgumentException("OAuthProvider: "+request.getProvider().name()+" did not provide a user email");
}
// This is the ID of the user within the provider's system.
PrincipalAlias emailAlias = userManager.lookupUserByUsernameOrEmail(providedInfo.getUsersVerifiedEmail());
// Return the user's access token
return authManager.loginWithNoPasswordCheck(emailAlias.getPrincipalId(), tokenIssuer);
}
@WriteTransaction
public LoginResponse createAccountViaOauth(OAuthAccountCreationRequest request, String tokenIssuer) {
// Use the authentication code to lookup the user's information.
ProvidedUserInfo providedInfo = oauthManager.validateUserWithProvider(
request.getProvider(), request.getAuthenticationCode(), request.getRedirectUrl());
if(providedInfo.getUsersVerifiedEmail() == null){
throw new IllegalArgumentException("OAuthProvider: "+request.getProvider().name()+" did not provide a user email");
}
// create account with the returned user info.
NewUser newUser = new NewUser();
newUser.setEmail(providedInfo.getUsersVerifiedEmail());
newUser.setFirstName(providedInfo.getFirstName());
newUser.setLastName(providedInfo.getLastName());
newUser.setUserName(request.getUserName());
long newPrincipalId = userManager.createUser(newUser);
return authManager.loginWithNoPasswordCheck(newPrincipalId, tokenIssuer);
}
@Override
public PrincipalAlias bindExternalID(Long userId, OAuthValidationRequest validationRequest) {
if (AuthorizationUtils.isUserAnonymous(userId)) throw new UnauthorizedException("User ID is required.");
AliasAndType providersUserId = oauthManager.retrieveProvidersId(
validationRequest.getProvider(),
validationRequest.getAuthenticationCode(),
validationRequest.getRedirectUrl());
// now bind the ID to the user account
return userManager.bindAlias(providersUserId.getAlias(), providersUserId.getType(), userId);
}
@Override
public void unbindExternalID(Long userId, OAuthProvider provider, String aliasName) {
if (AuthorizationUtils.isUserAnonymous(userId)) throw new UnauthorizedException("User ID is required.");
AliasType aliasType = oauthManager.getAliasTypeForProvider(provider);
userManager.unbindAlias(aliasName, aliasType, userId);
}
@Override
public LoginResponse login(LoginRequest request, String tokenIssuer) {
return authManager.login(request, tokenIssuer);
}
@Override
public AuthenticatedOn getAuthenticatedOn(long userId) {
UserInfo userInfo = userManager.getUserInfo(userId);
return authManager.getAuthenticatedOn(userInfo);
}
@Override
public PrincipalAlias lookupUserForAuthentication(String alias) {
return userManager.lookupUserByUsernameOrEmail(alias);
}
@Override
public AccessTokenGenerationResponse createPersonalAccessToken(Long userId, String accessToken, AccessTokenGenerationRequest request, String oauthEndpoint) {
UserInfo userInfo = userManager.getUserInfo(userId);
return personalAccessTokenManager.issueToken(userInfo, accessToken, request, oauthEndpoint);
}
@Override
public AccessTokenRecordList getPersonalAccessTokenRecords(Long userId, String nextPageToken) {
UserInfo userInfo = userManager.getUserInfo(userId);
return personalAccessTokenManager.getTokenRecords(userInfo, nextPageToken);
}
@Override
public AccessTokenRecord getPersonalAccessTokenRecord(Long userId, Long tokenId) {
UserInfo userInfo = userManager.getUserInfo(userId);
return personalAccessTokenManager.getTokenRecord(userInfo, tokenId.toString());
}
@Override
public void revokePersonalAccessToken(Long userId, Long tokenId) {
UserInfo userInfo = userManager.getUserInfo(userId);
personalAccessTokenManager.revokeToken(userInfo, tokenId.toString());
}
}
| Sage-Bionetworks/Synapse-Repository-Services | services/repository/src/main/java/org/sagebionetworks/auth/services/AuthenticationServiceImpl.java | Java | apache-2.0 | 8,736 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTypeBuysTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('type_buys', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('type_buys');
}
}
| sonico999/deliveryguy | app/database/migrations/2014_11_05_213148_create_type_buys_table.php | PHP | apache-2.0 | 548 |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 BigML
#
# 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.
from world import world
from bigml.api import HTTP_OK
def i_get_the_project(step, resource):
resource = world.api.get_project(resource)
world.status = resource['code']
assert world.status == HTTP_OK
world.project = resource['object']
| ShaguptaS/python | bigml/tests/read_project_steps.py | Python | apache-2.0 | 869 |
# AUTOGENERATED FILE
FROM balenalib/nanopi-neo-air-alpine:edge-run
ENV GO_VERSION 1.16
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-armv7hf.tar.gz" \
&& echo "e5ec1504696d3484c0161fe3a0bbd37179c50cd4856b5d492a282a767e45a5ad go$GO_VERSION.linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@golang" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux edge \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/golang/nanopi-neo-air/alpine/edge/1.16/run/Dockerfile | Dockerfile | apache-2.0 | 2,467 |
# automate/server/user/views.py
#################
#### imports ####
#################
#from flask import render_template, Blueprint, url_for, \
# redirect, flash, request
#from flask_login import login_user, logout_user, login_required
#from automate.server import bcrypt, db
#from automate.server import db
#from automate.server.models import User
#from automate.server.user.forms import LoginForm, RegisterForm
################
#### config ####
################
#user_blueprint = Blueprint('user', __name__,)
################
#### routes ####
################
#@user_blueprint.route('/register', methods=['GET', 'POST'])
#def register():
# form = RegisterForm(request.form)
# if form.validate_on_submit():
# user = User(
# email=form.email.data,
# password=form.password.data
# )
# db.session.add(user)
# db.session.commit()
#
# login_user(user)
#
# flash('Thank you for registering.', 'success')
# return redirect(url_for("user.members"))
#
# return render_template('user/register.html', form=form)
#
#
#@user_blueprint.route('/login', methods=['GET', 'POST'])
#def login():
# form = LoginForm(request.form)
# if form.validate_on_submit():
# user = User.query.filter_by(email=form.email.data).first()
# if user:
# #if user and bcrypt.check_password_hash(
# # user.password, request.form['password']):
# # login_user(user)
# flash('You are logged in. Welcome!', 'success')
# return redirect(url_for('user.members'))
# else:
# flash('Invalid email and/or password.', 'danger')
# return render_template('user/login.html', form=form)
# return render_template('user/login.html', title='Please Login', form=form)
#
#
#@user_blueprint.route('/logout')
#@login_required
#def logout():
# logout_user()
# flash('You were logged out. Bye!', 'success')
# return redirect(url_for('main.home'))
#
#
#@user_blueprint.route('/members')
#@login_required
#def members():
# return render_template('user/members.html')
# | JeromeErasmus/browserstack_automate | automate/server/user/views.py | Python | apache-2.0 | 2,112 |
<?php
/**
* PHP Version 5.
*
* @category Amazon
*
* @copyright Copyright 2009 Amazon Technologies, Inc.
*
* @see http://aws.amazon.com
*
* @license http://aws.amazon.com/apache2.0 Apache License, Version 2.0
*
* @version 2009-01-01
*/
/*******************************************************************************
* Marketplace Web Service PHP5 Library
* Generated: Thu May 07 13:07:36 PDT 2009
*
*/
/**
* @see MarketplaceWebService_Model
*/
require_once 'MarketplaceWebService/Model.php';
/**
* MarketplaceWebService_Model_ErrorResponse.
*
* Properties:
* <ul>
*
* <li>Error: MarketplaceWebService_Model_Error</li>
* <li>RequestId: string</li>
*
* </ul>
*/
class MarketplaceWebService_Model_ErrorResponse extends MarketplaceWebService_Model
{
/**
* Construct new MarketplaceWebService_Model_ErrorResponse.
*
* @param mixed $data DOMElement or Associative Array to construct from.
*
* Valid properties:
* <ul>
*
* <li>Error: MarketplaceWebService_Model_Error</li>
* <li>RequestId: string</li>
*
* </ul>
*/
public function __construct($data = null)
{
$this->fields = array(
'Error' => array('FieldValue' => array(), 'FieldType' => 'MarketplaceWebService_Model_Error'),
'RequestId' => array('FieldValue' => null, 'FieldType' => 'string'),
);
parent::__construct($data);
}
/**
* Construct MarketplaceWebService_Model_ErrorResponse from XML string.
*
* @param string $xml XML string to construct from
*
* @return MarketplaceWebService_Model_ErrorResponse
*/
public static function fromXML($xml)
{
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('a', 'http://mws.amazonaws.com/doc/2009-01-01/');
$response = $xpath->query('//a:ErrorResponse');
if ($response->length == 1) {
return new self(($response->item(0)));
} else {
throw new Exception('Unable to construct MarketplaceWebService_Model_ErrorResponse from provided XML.
Make sure that ErrorResponse is a root element');
}
}
/**
* Gets the value of the Error.
*
* @return array of Error Error
*/
public function getError()
{
return $this->fields['Error']['FieldValue'];
}
/**
* Sets the value of the Error.
*
* @param mixed Error or an array of Error Error
*
* @return $this instance
*/
public function setError($error)
{
if (!$this->_isNumericArray($error)) {
$error = array($error);
}
$this->fields['Error']['FieldValue'] = $error;
return $this;
}
/**
* Sets single or multiple values of Error list via variable number of arguments.
* For example, to set the list with two elements, simply pass two values as arguments to this function
* <code>withError($error1, $error2)</code>.
*
* @param Error $errorArgs one or more Error
*
* @return MarketplaceWebService_Model_ErrorResponse instance
*/
public function withError($errorArgs)
{
foreach (func_get_args() as $error) {
$this->fields['Error']['FieldValue'][] = $error;
}
return $this;
}
/**
* Checks if Error list is non-empty.
*
* @return bool true if Error list is non-empty
*/
public function isSetError()
{
return count($this->fields['Error']['FieldValue']) > 0;
}
/**
* Gets the value of the RequestId property.
*
* @return string RequestId
*/
public function getRequestId()
{
return $this->fields['RequestId']['FieldValue'];
}
/**
* Sets the value of the RequestId property.
*
* @param string RequestId
*
* @return $this instance
*/
public function setRequestId($value)
{
$this->fields['RequestId']['FieldValue'] = $value;
return $this;
}
/**
* Sets the value of the RequestId and returns this instance.
*
* @param string $value RequestId
*
* @return MarketplaceWebService_Model_ErrorResponse instance
*/
public function withRequestId($value)
{
$this->setRequestId($value);
return $this;
}
/**
* Checks if RequestId is set.
*
* @return bool true if RequestId is set
*/
public function isSetRequestId()
{
return !is_null($this->fields['RequestId']['FieldValue']);
}
/**
* XML Representation for this object.
*
* @return string XML for this object
*/
public function toXML()
{
$xml = '';
$xml .= '<ErrorResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">';
$xml .= $this->_toXMLFragment();
$xml .= '</ErrorResponse>';
return $xml;
}
private $_responseHeaderMetadata = null;
public function getResponseHeaderMetadata()
{
return $this->_responseHeaderMetadata;
}
public function setResponseHeaderMetadata($responseHeaderMetadata)
{
return $this->_responseHeaderMetadata = $responseHeaderMetadata;
}
}
| coopTilleuls/amazon-mws | src/MarketplaceWebService/Model/ErrorResponse.php | PHP | apache-2.0 | 5,341 |
# Salix farinosa Hartig SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Salix/Salix farinosa/README.md | Markdown | apache-2.0 | 171 |
# Taraxacum humbertii Maire SPECIES
#### Status
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Taraxacum/Taraxacum humbertii/README.md | Markdown | apache-2.0 | 162 |
# Diplodia cyparissa Cooke & Harkn. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Grevillea 9(no. 51): 83 (1881)
#### Original name
Diplodia cyparissa Cooke & Harkn.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Diplodia/Diplodia cyparissa/README.md | Markdown | apache-2.0 | 221 |
# Bulbophyllum scyphochilus Schltr. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Bulbophyllum/Bulbophyllum scyphochilus/README.md | Markdown | apache-2.0 | 191 |
# Coscinodiscopsis jonesiana (Greville) E.A. Sar & I. Sunesen in Sar, Suneson & Hinz, 2008 SPECIES
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Bacillariophyta/Bacillariophyceae/Coscinodiscopsis/Coscinodiscopsis jonesiana/README.md | Markdown | apache-2.0 | 239 |
# Cinnamomum citriodorum Thwaites SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Cinnamomum/Cinnamomum citriodorum/README.md | Markdown | apache-2.0 | 181 |
# Tecoma avellanedae Speg. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Bignoniaceae/Tecoma/Tecoma avellanedae/README.md | Markdown | apache-2.0 | 174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.